text
stringlengths 180
608k
|
---|
[Question]
[
I don't like numbers, but I do like the Fibonacci sequence. I'm sure we could work something out.
Please read one integer *n* from STDIN and output the *n*th Fibonacci number in base 26 (`abcdefghijklmnopqrstuvwxyz` instead of `0123456789`) to STDOUT.
The first Fibonacci number is 0. The second one is 1. The *n*th fibonacci number is the sum of the *n*-2nd and *n*-1st Fibonacci numbers.
First 32 fib-abc numbers:
```
fib(0) = a
fib(1) = b
fib(2) = b
fib(3) = c
fib(4) = d
fib(5) = f
fib(6) = i
fib(7) = n
fib(8) = v
fib(9) = bi
fib(10) = cd
fib(11) = dl
fib(12) = fo
fib(13) = iz
fib(14) = on
fib(15) = xm
fib(16) = blz
fib(17) = cjl
fib(18) = dvk
fib(19) = gev
fib(20) = kaf
fib(21) = qfa
fib(22) = baff
fib(23) = bqkf
fib(24) = cqpk
fib(25) = egzp
fib(26) = gxoz
fib(27) = leoo
fib(28) = scdn
fib(29) = bdgsb
fib(30) = bvivo
fib(31) = cypnp
```
This is code golf, so shortest code in bytes wins!
[Answer]
# CJam, 18 bytes
```
UXri{_@+}*;26b'af+
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=UXri%7B_%40%2B%7D*%3B26b'af%2B&input=31).
### How it works
```
UX e# Push 0 and 1.
ri{ e# Read an integer and execute the loop that many times.
_ e# Push a copy the topmost integer.
@ e# Rotate the bottom-most integer on top of the stack.
+ e# Pop the two topmost integers and push their sum.
}* e#
; e# Discard the topmost integer from the stack.
26b e# Convert the remaining integer to base 26.
'af+ e# Add the character 'a' to each base-26 digit.
```
[Answer]
# [TeaScript](https://esolangs.org/wiki/TeaScript), 34 bytes ~~37~~ ~~51~~ ~~54~~
TeaScript is JavaScript for golfing. It also brings ES2015 features to the average browser.
```
F(x)b(26)l(#C(lc()+(l<'a'?49:10)))
```
[Try it online](http://vihanserver.tk/p/TeaScript/?code=F(x).b(26).l(%23C(l.c()%2B(l%3C'a'%3F49%3A10)))&input=27&v=1)
### Explanation
```
// x is the input
F(x) // Fibonacci from input
.b(26) // To Base-26 string but with 0-9, a-p
// instead of a-z, to fix this...
.l(# // Loops through each char
C( // Charcode from...
l.c()+ // Charcode from char
(l<'a'? // If number
49 // Add 49 to char code
:10 // Else add 10
)
)
)
```
\*This answer is non-competing
[Answer]
# Mathematica, ~~67~~ 61 bytes
```
Print[""<>Alphabet[][[Fibonacci@Input[]~IntegerDigits~26+1]]]
```
Calculates `f(1000000)` in about 51 milliseconds.
[Answer]
# [Simplex v.0.6](http://conorobrien-foxx.github.io/Simplex/#commands), 35 bytes
Sometimes I sigh and think, "Is this even worth submitting? It doesn't win, so why bother?" In response, I think, "Heck. It was fun. Besides, this is really fancied-up brainf\*\*\* anyhow. Not too shabby."
```
5_*Ij1~SRpRi@T[Uj&ERp]pSR5_Vj26@pWo
5_ ~~ sqrt(5)
* ~~ copy to next byte, move right
I ~~ increment [sqrt(5),sqrt(5)+1]
j1 ~~ insert a new cell and set it to one
~~ [sqrt(5),1,sqrt(5)+1]
~ ~~ switch the previous with the current byte
~~ [1,sqrt(5),sqrt(5)+1]
S ~~ perform subtraction [1-sqrt(5),0,sqrt(5)+1]
Rp ~~ remove next cell [1-sqrt(5),sqrt(5)+1]
Ri@ ~~ take numeric input (n) into register
T[ ] ~~ applies the following to every cell
U ~~ halves the current cell
j& ~~ dumps and restores the value to the register
ERp ~~ raises cell to the nth power, remove cell made
p ~~ remove last cell
S ~~ subtract the two values
R5_ ~~ goes right and sets sqrt(5)
V ~~ divides the prev. two cells
j ~~ inserts new cell
26@ ~~ puts 26 into the register
p ~~ removes cell
Wo ~~ converts the current to base 26 and outputs as number
```
[Answer]
# Pyth, 17 bytes
```
s@LGjhu,eGsGQU2lG
```
[Try it](https://pyth.herokuapp.com/?code=s%40LGjhu%2CeGsGQU2lG&input=31&debug=0) online.
[Answer]
## [Minkolang 0.9](https://github.com/elendiastarman/Minkolang), 40 bytes
```
10n[0c+r]$x'26'r(d0c%1G0c:d$)xrx("a"+O).
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=10n%5B0c%2Br%5D%24x%2726%27r%28d0c%251G0c%3Ad%24%29xrx%28%22a%22%2BO%29.&input=20)
### Explanation
```
10n[0c+r] Calculates f(n) where n is taken from input
$x'26'r Dumps the addend I don't need and pushes a 26
(d0c%1G0c:d$) Base-encodes f(n) in base 26
xrx Dumps the 0, reverses, dumps the 26
("a"+O). Outputs the letters
```
[Answer]
# Python 2.7, 82 bytes
```
a=0
b=1
s=''
exec"a,b=b,a+b;"*input()
while a:s=chr(a%26+97)+s;a/=26
print s or'a'
```
[Answer]
# [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 111 bytes
```
> Input
> fₙ
>> ≺1
>> 2ᶠ1
>> 4ⁿ3
> 26
>> 5⊥6
> 97
>> 8+R
>> Each 9 7
>> 'R
>> Each 11 10
>> Output 12
```
[Try it on repl.it!](https://repl.it/@razetime/Whispers-online-runner#fibabc.wisp)
Needs to be run as `python3 whispers\ v3.py fibabc.wisp < input.txt 2> /dev/null` with input given on the first line of `input.txt`.
I think the first and last lines can be removed [as per the consensus here](https://codegolf.meta.stackexchange.com/questions/20737/can-whispers-programs-ignore-a-final-output-line), but I'm not sure.
8 bytes shorter than hardcoding the alphabet: [Try it on repl.it!](https://repl.it/@razetime/Whispers-online-runner#fibabc2.wisp)
[Answer]
# Haskell, 114 chars.
It is unexpectedly long. Any help welcome. Previously found a bug for fib(0)
```
f=scanl(+)0$1:f
k 0=[]
k x=k(x`div`26)++[toEnum$97+x`mod`26]
l 0=0
l x=k x
main=interact$l.(f!!).read.head.lines
```
`f` is infinite list of fibonacci. `toEnum` is same with `chr`, except that former doesn't need to import Data.Char.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ÆḞṃØaṙ1¤
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//w4bhuJ7huYPDmGHhuZkxwqT/4bi2w4figqxZ//8zMg "Jelly – Try It Online")
## How it works
```
ÆḞṃØaṙ1¤ - Main link. Takes an integer N on the left
ÆḞ - Take the Nth Fibonacci number
¤ - Group the previous links into a nilad:
Øa - "abc...xyz"
ṙ1 - Rotate once; "bcd...yza"
ṃ - Base decompress; Convert to base 26 then index into the string
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 94 bytes
```
x=>(f=n=>n>1?f(n-1)+f(n-2):1)(x)[S="toString"](26).replace(/./g,l=>(parseInt(l,26)+10)[S](36))
```
[Try it online!](https://tio.run/##XdA/C8IwEIfh3Y/hdIfV9i5a/0Dq7OwoHWppS6XEUIP47Wuc5NcpvBzHPeRRvatXPfY@rN@Hqe3vdvrYglrrbOEKObfk1sKr36N8EqYP3652GZ7XMPauW5akOW/Gxg9V3VC6SbtkiPu@Gl/NxQUakjhfSRa3SjI58@TjXqB4iTLmxb8ESqEM1BZqB5VD7aEOUEe8PsOgRpAj6BEECYoESYImQZSgSlGlsz9ClaJKUaWoUlQpqhRViiqDKhNV0xc "JavaScript (V8) – Try It Online")
Uses recursion to find factorial, and some `toString`, `replace`, and `parseInt` magic to convert to letters.
[Answer]
# [Zsh](https://www.zsh.org/), 68 bytes
```
<<<A;{for ((a=1;b+=a;a+=b))<<<$[[##26]a]<<<$[[##26]b]}|tr 0-9A-P A-Z
```
[Try it online!](https://tio.run/##qyrO@K/x38bGxtG6Oi2/SEFDI9HW0DpJ2zbROlHbNklTEyilEh2trGxkFpsYi8RJiq2tKSlSMNC1dNQNUHDUjfqvWZORmpiioKtiqFack5paoKBn9P@/sQEA "Zsh – Try It Online")
Pure fibonacci code stolen from [here](https://codegolf.stackexchange.com/a/190972).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
If a list of characters is fine as output, the `J` can be removed.
```
ÅfAÅвJ
```
[Try it online!](https://tio.run/##yy9OTMpM/W9seGySn1JaZpLG4f2aCrYKSvZ@/w@3pjkebr2wyeu/zn8A "05AB1E – Try It Online")
```
Åf # get the nth Fibonacci number
A # push the lowercase alphabet
Åв # convert the Fibonacci number to this custom base
J # join the list of digits into a string
```
[Answer]
# Ruby, 67 bytes
```
a,b=0,1
gets.to_i.times{a,b=b,a+b}
puts a.to_s(26).tr"0-9a-p","a-z"
```
[Answer]
# Matlab, 133 bytes
```
n=input('');if n<2,y=n;else
f=0;g=1;for k=2:n
h=f+g;f=g;g=h;end
y=fix(mod(g./26.^(fix(log(g)/log(26)):-1:0),26));end
disp(char(y+97))
```
[Answer]
# Ruby, 125 bytes
Not gonna win any time soon, but it was fun & my first code golf :')
```
def f(n);n<3?(n>0?1:0):f(n-1)+f(n-2);end
def a(s);s.bytes.map{|n|n<58?n+49:n+10}.pack("C*");end
puts a(f(gets.to_i).to_s(26))
```
First line is a function to compute fibonacci, second converts from Ruby's built-in base 26 encoding (0-9 then a-p) into a-z encoding, third gets a line from STDIN and runs it through both.
] |
[Question]
[
A secondary number is a positive integer whose prime factors (without multiplicity) are all less than or equal to its square root. `4` is a secondary number, because its only prime factor is `2`, which equals its square root. However, `15` is not a secondary number, because it has `5` as a prime factor, which is larger than its square root (`~ 3.9`). Because all prime numbers have themselves as prime factors, no prime number is a secondary number. The first few secondary numbers are as follows:
```
1, 4, 8, 9, 12, 16, 18, 24, 25, 27, 30, 32, 36, 40, 45, 48, 49, 50, 54, 56
```
A tertiary number is defined similarly, except all the prime factors must be less than or equal to its cube root. The first few tertiary numbers are as follows:
```
1, 8, 16, 27, 32, 36, 48, 54, 64, 72, 81, 96, 108, 125, 128, 135, 144, 150, 160, 162
```
In general, an *n-ary number* is one whose prime factors are all less than or equal to its n-th root. Thus, a positive integer \$x\$ is an `n`-ary number *iff* each of its prime factors \$p\$ satisfies \$p^n ≤ x\$. Thus, primary numbers are all positive integers (all prime factors less than or equal to themselves), quartenary numbers have all their prime factors less than or equal to their fourth root, and so on.
## The Challenge
Given integers `k` and `n` as inputs, output the `k`th `n`-ary number. `k` may either be zero- or one-indexed (your choice), and `n` will always be positive.
## Examples
These are the first 20 elements in each sequence up to 10-ary numbers:
```
Primary: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
Secondary: 1, 4, 8, 9, 12, 16, 18, 24, 25, 27, 30, 32, 36, 40, 45, 48, 49, 50, 54, 56
Tertiary: 1, 8, 16, 27, 32, 36, 48, 54, 64, 72, 81, 96, 108, 125, 128, 135, 144, 150, 160, 162
Quarternary: 1, 16, 32, 64, 81, 96, 108, 128, 144, 162, 192, 216, 243, 256, 288, 324, 384, 432, 486, 512
5-ary: 1, 32, 64, 128, 243, 256, 288, 324, 384, 432, 486, 512, 576, 648, 729, 768, 864, 972, 1024, 1152
6-ary: 1, 64, 128, 256, 512, 729, 768, 864, 972, 1024, 1152, 1296, 1458, 1536, 1728, 1944, 2048, 2187, 2304, 2592
7-ary: 1, 128, 256, 512, 1024, 2048, 2187, 2304, 2592, 2916, 3072, 3456, 3888, 4096, 4374, 4608, 5184, 5832, 6144, 6561
8-ary: 1, 256, 512, 1024, 2048, 4096, 6561, 6912, 7776, 8192, 8748, 9216, 10368, 11664, 12288, 13122, 13824, 15552, 16384, 17496
9-ary: 1, 512, 1024, 2048, 4096, 8192, 16384, 19683, 20736, 23328, 24576, 26244, 27648, 31104, 32768, 34992, 36864, 39366, 41472, 46656
10-ary: 1, 1024, 2048, 4096, 8192, 16384, 32768, 59049, 62208, 65536, 69984, 73728, 78732, 82944, 93312, 98304, 104976, 110592, 118098, 124416
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Æf*³<‘Ạ
1Ç#Ṫ
```
Takes **n** and **k** (one-indexed) as command-line arguments.
[Try it online!](https://tio.run/nexus/jelly#ARwA4///w4ZmKsKzPOKAmOG6oAoxw4cj4bmq////Nf84 "Jelly – TIO Nexus")
### How it works
```
1Ç#Ṫ Main link. Left argument: n. Right argument: k
1 Set the return value to 1.
Ç# Execute the helper link above for r = 1, 2, 3, ... until k of them return
a truthy value. Yield the list of all k matches.
Ṫ Tail; extract the last match.
Æf*³<‘Ạ Helper link. Argument: r
Æf Compute all prime factors of r.
*³ Elevate them to the n-th power.
<‘ Compare all powers with r + 1.
Ạ All; return 1 if all comparisons were true, 0 if one or more were not.
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 21 bytes
```
:[1]cyt
,1|,.$ph:?^<=
```
[Try it online!](http://brachylog.tryitonline.net/#code=OlsxXWN5dAosMXwsLiRwaDo_Xjw9&input=WzU6MjBd&args=Wg)
This answer is one-indexed.
### Explanation
```
Input: [N:K]
:[1]cy Retrieve the first K valid outputs of the predicate below with N as input
t Output is the last one
,1 Output = 1
| Or
,.$ph Take the biggest prime factor of the Output
:?^<= Its Nth power is less than the Output
```
[Answer]
## JavaScript (ES7), ~~95~~ 90 bytes
Reasonably fast but sadly limited by the maximum number of recursions.
```
f=(k,n,i=1)=>(F=(i,d)=>i-1?d>1?i%d?F(i,d-1):F(i/d,x):1:--k)(i,x=++i**(1/n)|0)?f(k,n,i):i-1
```
### How it works
Rather than factoring an integer **i** and verifying that all its prime factors are less than or equal to **x = floor(i1/n)**, we try to validate the latter assumption directly. That's the purpose of the inner function **F()**:
```
F = (i, d) => // given an integer i and a divisor d:
i - 1 ? // if the initial integer is not yet fully factored
d > 1 ? // if d is still a valid candidate
i % d ? // if d is not a divisor of i
F(i, d - 1) // try again with d-1
: // else
F(i / d, x) // try to factor i/d
: // else
1 // failed: yield 1
: // else
--k // success: decrement k
```
We check if any integer **d** in **[2 ... i1/n]** divides **i**. If not, the assumption is not valid and we return **1**. If yes, we recursively repeat the process on **i = i / d** until it fails or the initial integer is fully factored (**i == 1**), in which case we decrement **k**. In turn, the outer function **f()** is called recursively until **k == 0**.
*Note:* Due to floating point rounding errors such as `125**(1/3) == 4.9999…`, the actual computed value for **x** is **floor((i+1)1/n)**.
### Demo
(Here with a 97-byte ES6 version for a better compatibility.)
```
f=(k,n,i=1)=>(F=(i,d)=>i-1?d>1?i%d?F(i,d-1):F(i/d,x):1:--k)(i,x=Math.pow(++i,1/n)|0)?f(k,n,i):i-1
console.log(f(17, 3)); // 144
console.log(f(13, 4)); // 243
console.log(f(4, 10)); // 4096
```
[Answer]
## JavaScript (ES7), ~~93~~ 79 bytes
```
f=(k,n,g=(i,j=2)=>i<2?--k?g(++m):m:j**n>m?g(++m):i%j?g(i,j+1):g(i/j,j))=>g(m=1)
```
I couldn't understand Arnauld's answer so I wrote my own and conveniently it came in at two bytes shorter. Edit: Saved 14 bytes with help from @ETHproductions. Ungolfed:
```
function ary(k, n) {
for (var c = 1;; c++) {
var m = c;
for (var i = 2; m > 1 && i ** n <= c; i++)
while (m % i == 0) m /= i;
if (m == 1 && --k == 0) return c;
}
}
```
[Answer]
# Haskell, 86 bytes
```
m#n=(0:1:filter(\k->last[n|n<-[2..k],all((>0).rem n)[2..n-1],k`rem`n<1]^n<=k)[2..])!!m
```
Explanation:
(`%%%%` denotes the code from the line above)
```
[n|n<-[2..k],all((>0).rem n)[2..n-1],k`rem`n<1] -- generates all prime factors of k
last%%%%^n<=k -- checks whether k is n-ary
(0:1:filter(\k->%%%%)[2..])!!m -- generates all n-ary nubmers and picks the m-th
m#n=%%%% -- assignment to the function #
```
[Answer]
# Pyth, 13 bytes
```
e.f.AgL@ZQPZE
```
[Try it online.](https://pyth.herokuapp.com/?code=e.f.AgL%40ZQPZE&input=7%0A20&debug=0)
Works really just like the Jelly solution.
```
e.f.AgL@ZQPZE
Implicit: read n into Q.
E Read k.
.f Find the first k integers >= 1 for which
.A all
P prime factors of
Z the number
gL are at most
Q the n'th
@ root of
Z the number.
e Take the last one.
```
[Answer]
# Perl 6, 88 bytes
```
->\k,\n{sub f(\n,\d){n-1??n%%d??f n/d,d!!f n,d+1!!d};(1,|grep {$_>=f($_,2)**n},2..*)[k]}
```
My accidental insight is that you don't need to look at every factor of `n`, just the largest one, which is what the internal function `f` computes. Unfortunately, it blows the stack with larger inputs.
Robustness can be improved by adding a primality test, using the built-in `is-prime` method on Ints, at a cost of several more characters.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
!fS≤ȯ^⁰→pN
```
[Try it online!](https://tio.run/##yygtzv7/XzEt@FHnkhPr4x41bnjUNqnA7////yb/DQ0B "Husk – Try It Online")
### Explanation
Took me a while to figure out using `→` on the empty list returns `1` instead of `-Inf` for `▲` which leaves `1` in the list (otherwise that would cost 2 bytes to prepend it again):
```
!fS≤(^⁰→p)N -- input n as ⁰ and k implicit, for example: 4 3
!f N -- filter the natural numbers by the following predicate (example on 16):
S≤( ) -- is the following less than the element (16) itself?
p -- ..prime factors (in increasing order): [2]
→ -- ..last element/maximum: 2
^⁰ -- ..to the power of n: 16
-- 16 ≤ 16: yes
-- [1,16,32,64,81..
! -- get the k'th element: 32
```
[Answer]
# R, 93 bytes
```
f=function(k,n){x='if'(k,f(k-1,n)+1,1);while(!all(numbers::primeFactors(x)<=x^(1/n)))x=x+1;x}
```
Zero-indexed.
It is a recursive function that just keeps going until it finds the next number in line. Uses to `numbers` package to find the prime factors.
[Answer]
# MATL, 21 bytes
```
x~`@YflG^@>~A+t2G<}x@
```
This solution uses one-based indexing and the inputs are `n` and `k`, respectively.
[**Try it Online!**](http://matl.tryitonline.net/#code=eH5gQFlmbEdeQD5-QSt0Mkc8fXhA&input=MgoyMA)
**Explanation**
```
x % Implicitly grab the first input and delete it
~ % Implicitly grab the second input and make it FALSE (0) (this is the counter)
` % Beginning of the do-while loop
@Yf % Compute the prime factors of the current loop index
1G^ % Raise them to the power of the first input
@> % Determine if each value in the array is greater than the current index
~A % Yield a 0 if any of them were and a 1 if they weren't
+ % Add this to the counter (increments only for positive cases)
t2G< % Determine if we have reached a length specified by the second input
} % After we exit the loop (finally), ...
x@ % Delete the counter and push the current loop index to the stack
% Implicitly display the result
```
[Answer]
# [Brachylog v2](https://github.com/JCumin/Brachylog), 16 bytes
```
{∧.ḋ,1⌉;?^≤}ᶠ⁽t
```
[Try it online!](https://tio.run/##ATAAz/9icmFjaHlsb2cy//974oinLuG4iywx4oyJOz9e4omkfeG2oOKBvXT//1s5LDNd/1o "Brachylog – Try It Online")
*Credit to [Dennis's Jelly solution](https://codegolf.stackexchange.com/a/102890/16766) for getting me thinking in the right direction.*
### Explanation
Here's a slightly ungolfed version that's easier to parse:
```
↰₁ᶠ⁽t
∧.ḋ,1⌉;?^≤
```
Helper predicate (line 2): input is the exponent *n*, output is unconstrained:
```
∧ Break implicit unification
.ḋ Get the prime factors of the output
,1 Append 1 (necessary because 1 has no prime factors and you can't take
the max of an empty list)
⌉ Max (largest prime factor, or 1 if the output is 1)
;? Pair that factor with the input (n)
^ Take factor to the power of n
≤ Verify that the result is less than or equal to the output
```
Main predicate (line 1): input is a list containing the index *k* (1-based) and the exponent *n*; output is unconstrained:
```
ᶠ⁽ Find the first k outputs of
↰₁ calling the helper predicate with n as input
t Get the last (i.e. kth) one
```
[Answer]
# APL(NARS), 53 chars, 106 bytes
```
r←a f w;c
c←0⋄r←1
→3×⍳∼∧/(πr)≤a√r⋄→0×⍳w≤c+←1
r+←1⋄→2
```
test:
```
1 f¨1..20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
2 f¨1..20
1 4 8 9 12 16 18 24 25 27 30 32 36 40 45 48 49 50 54 56
3 f¨1..20
1 8 16 27 32 36 48 54 64 72 81 96 108 125 128 135 144 150 160 162
4 f¨1..20
1 16 32 64 81 96 108 128 144 162 192 216 243 256 288 324 384 432 486 512
10 f¨1..20
1 1024 2048 4096 8192 16384 32768 59049 62208 65536 69984 73728 78732 82944 93312 98304 104976 110592 118098 124416
```
[Answer]
# [Python 2](https://docs.python.org/2/), 114 bytes
```
f=lambda K,n,i=1:K and f(K-all(j**n<=i for j in range(1,i+1)if i%j==0and all(j%k for k in range(2,j))),n,i+1)or~-i
```
[Try it online!](https://tio.run/##Tc1BDoIwEIXhNZxiNiQdLIlt4obYE/QIxkUNVqeUgTRs3Hj1Ct3I/nv/Wz7re2adszfRTY/BgZUsyajeguMBvLCdi1GEtuWrIfBzggDEkBy/nkJJOikkD9QEY877ouhmLHL8Sy0DIu7tbTCnb0d5F3xsXbCvqyURr8Dytl1LxtKxR6UV3usq/wA "Python 2 – Try It Online")
1-indexed function.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
Takes `n` as the first input and `k` (1-indexed) as the second.
```
@_k e§Vq}aXÄ}g
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QF9rIGWnVnF9YVjEfWc=&input=OAo0)
] |
[Question]
[
Create a program or function to unjumble a 9x9x9 cube of digits by rotating individual 3x3 cubes within it.
This is similar to (but, I suspect, a bit harder than) my [Flippin' Squares](https://codegolf.stackexchange.com/questions/18545/flippin-squares) question.
## Input
Input will be a 9x9x9 cube. I'm not going to be as strict over the input as I was last time, 3d arrays are allowed, arrays of strings are allowed, arrays of arrays of characters are allowed, etc.
I will be strict on **what** you can input into your program though - only the digits that make up the cube. No additional information like dimensions or anything else can be given as input.
Here is an example cube:
```
123456789 234567891 345678912
234567891 345678912 456789123
345678912 456789123 567891234
456789123 567891234 678912345
567891234 678912345 789123456
678912345 789123456 891234567
789123456 891234567 912345678
891234567 912345678 123456789
912345678 123456789 234567891
456789123 567891234 678912345
567891234 678912345 789123456
678912345 789123456 891234567
789123456 891234567 912345678
891234567 912345678 123456789
912345678 123456789 234567891
123456789 234567891 345678912
234567891 345678912 456789123
345678912 456789123 567891234
789123456 891234567 912345678
891234567 912345678 123456789
912345678 123456789 234567891
123456789 234567891 345678912
234567891 345678912 456789123
345678912 456789123 567891234
456789123 567891234 678912345
567891234 678912345 789123456
678912345 789123456 891234567
```
The 9x9 square in the top left is the cross-section of the bottom layer of the cube. The square in the top-middle is the next layer up, then the top-right, the middle-left and so on through to the bottom-right, which is the top layer.
This cube is the target state. As you can see the digits increase in the positive x, y and z directions, looping back to `1` when they pass `9`.
## Sub-cubes
You solve this puzzle by manipulating 3x3 sub-cubes within the main cube.
Each sub-cube is identified by the `X Y Z` position of its centre within the main cube. Because each sub-cube must be a 3x3 cube, `X`, `Y` and `Z` can only be between 1 and 7 (inclusive). Point `0 0 0` is at the back-bottom-left and the values increase to the right, upwards and toward the front.
Example sub-cubes from the target state (all other values set to `0` to highlight the cube in question):
```
1 1 1:
123000000 234000000 345000000
234000000 345000000 456000000
345000000 456000000 567000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
7 1 1:
000000789 000000891 000000912
000000891 000000912 000000123
000000912 000000123 000000234
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
1 7 1:
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
789000000 891000000 912000000
891000000 912000000 123000000
912000000 123000000 234000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
1 1 7:
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
789000000 891000000 912000000
891000000 912000000 123000000
912000000 123000000 234000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
000000000 000000000 000000000
```
## Manipulation
Each move you make will be a rotation of one of the sub-cubes. You will be able to rotate a cube around any one of its axes; 1, 2 or 3 quarter turns.
Rotation will be specified by first naming the axis you wish to rotate around, then the number of quarter turns you wish to rotate.
Example rotations (using unique values for each item here to make the rotations more obvious):
```
ABC JKL STU
DEF MNO VWX
GHI PQR YZ*
X1
STU VWX YZ*
JKL MNO PQR
ABC DEF GHI
```
X rotations rotate towards the back (or anti-clockwise as viewed from the left-hand side).
```
ABC JKL STU
DEF MNO VWX
GHI PQR YZ*
Y1
CFI LOR UX*
BEH KNQ TWZ
ADG JMP SVY
```
Y rotations rotate anti-clockwise as viewed from above.
```
ABC JKL STU
DEF MNO VWX
GHI PQR YZ*
Z1
SJA TKB ULC
VMD WNE XOF
YPG ZQH *RI
```
Z rotations rotate anti-clockwise as viewed from the front.
## Output
Your output should be a list of moves required to take the given input back to the target state.
Each move should name the sub-cube and how it should be rotated:
```
111X1
Block at X=1, Y=1, Z=1, rotated 1 quarter turn around the X axis.
426Y3
Block at X=4, Y=2, Z=6, rotated 3 quarter turns around the Y axis.
789Z2
Block at X=7, Y=8, Z=9, rotated 2 quarter turn around the Z axis.
```
So an example output might be something like:
```
111X1
789Z2
426Y3
```
This is my preferred output - a list of newline separated moves where each line describes one move - and this is the kind of output my verification program will expect. That said, I'll be somewhat flexible on the output, so a long string of moves (for example) is okay (it'll just take me a little longer to verify).
I think this is probably enough of a challenge as it is, but let's make it [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") just to spice it up a bit more.
## Utilities
This is a program that will generate a random scrambling of the cube. It outputs the scrambled cube, the sequence of moves that generated it and those moves reversed as a possible solution.
Alternatively, it has a function that will take a scrambled function and a sequence of moves as input and then verify that it returns the target cube.
The program, along with a couple of files containing a test input solution for verification, the target cube and a cube I used to test the rotate functions, can be found at: <https://github.com/gazrogers/CodegolfCubularRandomiser>
```
import random
target = [[['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9', '1'], ['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['4', '5', '6', '7', '8', '9', '1', '2', '3'], ['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['6', '7', '8', '9', '1', '2', '3', '4', '5'], ['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['8', '9', '1', '2', '3', '4', '5', '6', '7'], ['9', '1', '2', '3', '4', '5', '6', '7', '8']], [['2', '3', '4', '5', '6', '7', '8', '9', '1'], ['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['4', '5', '6', '7', '8', '9', '1', '2', '3'], ['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['6', '7', '8', '9', '1', '2', '3', '4', '5'], ['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['8', '9', '1', '2', '3', '4', '5', '6', '7'], ['9', '1', '2', '3', '4', '5', '6', '7', '8'], ['1', '2', '3', '4', '5', '6', '7', '8', '9']], [['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['4', '5', '6', '7', '8', '9', '1', '2', '3'], ['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['6', '7', '8', '9', '1', '2', '3', '4', '5'], ['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['8', '9', '1', '2', '3', '4', '5', '6', '7'], ['9', '1', '2', '3', '4', '5', '6', '7', '8'], ['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9', '1']], [['4', '5', '6', '7', '8', '9', '1', '2', '3'], ['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['6', '7', '8', '9', '1', '2', '3', '4', '5'], ['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['8', '9', '1', '2', '3', '4', '5', '6', '7'], ['9', '1', '2', '3', '4', '5', '6', '7', '8'], ['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9', '1'], ['3', '4', '5', '6', '7', '8', '9', '1', '2']], [['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['6', '7', '8', '9', '1', '2', '3', '4', '5'], ['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['8', '9', '1', '2', '3', '4', '5', '6', '7'], ['9', '1', '2', '3', '4', '5', '6', '7', '8'], ['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9', '1'], ['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['4', '5', '6', '7', '8', '9', '1', '2', '3']], [['6', '7', '8', '9', '1', '2', '3', '4', '5'], ['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['8', '9', '1', '2', '3', '4', '5', '6', '7'], ['9', '1', '2', '3', '4', '5', '6', '7', '8'], ['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9', '1'], ['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['4', '5', '6', '7', '8', '9', '1', '2', '3'], ['5', '6', '7', '8', '9', '1', '2', '3', '4']], [['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['8', '9', '1', '2', '3', '4', '5', '6', '7'], ['9', '1', '2', '3', '4', '5', '6', '7', '8'], ['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9', '1'], ['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['4', '5', '6', '7', '8', '9', '1', '2', '3'], ['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['6', '7', '8', '9', '1', '2', '3', '4', '5']], [['8', '9', '1', '2', '3', '4', '5', '6', '7'], ['9', '1', '2', '3', '4', '5', '6', '7', '8'], ['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9', '1'], ['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['4', '5', '6', '7', '8', '9', '1', '2', '3'], ['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['6', '7', '8', '9', '1', '2', '3', '4', '5'], ['7', '8', '9', '1', '2', '3', '4', '5', '6']], [['9', '1', '2', '3', '4', '5', '6', '7', '8'], ['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9', '1'], ['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['4', '5', '6', '7', '8', '9', '1', '2', '3'], ['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['6', '7', '8', '9', '1', '2', '3', '4', '5'], ['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['8', '9', '1', '2', '3', '4', '5', '6', '7']]]
# Because of how we read the data in,
# the first index into the 3D array is the y-index (bottom layer first, top layer last),
# then the z-index (back first, front last),
# then the x-index (left first, right last)
def getinput(filename):
f = open(filename)
string = f.read().split('\n\n')
cube = '\n\n'.join(string[:-1])
solution = string[-1]
lists = [list(z) for y in [x.split('\n') for x in cube.split('\n\n')] for z in y]
return [[lists[i:i + 9] for i in xrange(0, len(lists), 9)], solution]
def output(data):
return '\n'.join([''.join(row) for layer in data for row in layer+[[]]])
def getsubcube(cube, x, y, z):
x = clamp(x, 1, 7)
y = clamp(y, 1, 7)
z = clamp(z, 1, 7)
return [[[char for char in row[x-1:x+2]] for row in layer[z-1:z+2]] for layer in cube[y-1:y+2]]
def replacesubcube(cube, subcube, x, y, z):
newcube = cube
for ypos in range(y-1, y+2):
for zpos in range(z-1, z+2):
for xpos in range(x-1, x+2):
newcube[ypos][zpos][xpos] = subcube[ypos-y+1][zpos-z+1][xpos-x+1]
return newcube
def clamp(n, minn, maxn):
return max(min(n, maxn), minn)
def rotateX(cube, n):
newcube = cube
for _ in range(n):
newcube = [
[newcube[2][0], newcube[1][0], newcube[0][0]],
[newcube[2][1], newcube[1][1], newcube[0][1]],
[newcube[2][2], newcube[1][2], newcube[0][2]]
]
return newcube
# algorithm shamelessly stolen from http://stackoverflow.com/a/496056/618347
def rotateY(cube, n):
newcube = cube
for _ in range(n):
newcube = [zip(*x)[::-1] for x in newcube]
return newcube
# Easier to define in terms of rotateX and rotateY
def rotateZ(cube, n):
newcube = cube
for _ in range(n):
newcube = rotateY(rotateX(rotateY(newcube, 1), 3), 3)
return newcube
def randomisecube(cube):
newcube = cube
generator = ""
solution = ""
funclist = [[rotateX, "X"], [rotateY, "Y"], [rotateZ, "Z"]]
for _ in range(random.randint(10, 100)):
x = random.randint(1, 7)
y = random.randint(1, 7)
z = random.randint(1, 7)
rotateFunc = random.choice(funclist)
numRots = random.randint(1,3)
subcube = getsubcube(newcube, x, y, z)
subcube = rotateFunc[0](subcube, numRots)
newcube = replacesubcube(newcube, subcube, x, y, z)
generator = generator + str(x) + str(y) + str(z) + rotateFunc[1] + str(numRots) + '\n'
solution = str(x) + str(y) + str(z) + rotateFunc[1] + str(4-numRots) +'\n' + solution
return [generator, solution, newcube]
def verifysoltuion(cube, solution):
newcube = cube
funclist = {"X": rotateX, "Y": rotateY, "Z": rotateZ}
for move in solution.split('\n'):
movelist = list(move)
subcube = getsubcube(newcube, int(movelist[0]), int(movelist[1]), int(movelist[2]))
subcube = funclist[movelist[3]](subcube, int(movelist[4]))
newcube = replacesubcube(newcube, subcube, int(movelist[0]), int(movelist[1]), int(movelist[2]))
return newcube == target
# Code to generaterandom cubes - Uncomment/Comment as necessary
# answer = randomisecube(target)
# print "Cube:"
# print output(answer[2])
# print "Generated by:"
# print answer[0]
# print "Possible solution:"
# print answer[1]
# Code to verify solution - Uncomment/Comment as necessary
[cube, solution] = getinput('testsolution.txt')
print verifysoltuion(cube, solution)
```
## Tests
These tests were generated by the above randomiser, and so were scrambled by at most 100 moves. Your solution can be as long as it needs to be, but maybe the 100 move limit will help optimise your solution?
Please provide the solutions to these 3 test input in your answer.
```
Test input 1:
123456789
234567891
345678912
456789123
789891234
876912567
452123456
891234345
912345678
234567343
567878432
494519521
389891234
678212563
787823898
876934747
932145456
143256789
367178219
656269321
585491432
473539887
567643478
841298787
999145658
341256567
569367891
671784748
589855639
476966521
932129776
343778327
234145696
583991565
492312891
121498912
782395434
678214325
219761216
121656732
654283676
147858989
454789143
543678762
432565123
893989123
767391214
188896395
932595488
823214582
982397151
323654737
456562673
567456234
782193876
843218765
952931654
145859915
954823491
165758963
212517631
567651264
678912345
893214987
936727876
145326765
234941691
365634212
476732473
565696714
678789145
789123456
912345678
121478789
232345891
321834912
474787123
585498214
678919195
789123456
891234567
Test input 2:
185636789
678739121
519278992
141447183
589128734
633462125
784723456
891234567
912345678
298549121
267393832
455767823
567871244
867759645
269367236
178936767
912349478
123474589
369458912
654952363
543641434
432916575
732127236
821952912
939567891
367876789
414545691
476757893
562797914
678584189
782123678
697416367
714369554
821896365
258525219
323656712
517897654
698914565
282863873
563618741
236599478
188638387
934513698
145691383
256345123
645954345
762323456
158232167
732595252
743256541
452348691
349698262
414719873
593828934
787489436
878954347
989147298
193981213
288582371
585432832
678817943
789923554
698734145
891298567
914981178
115494319
652149626
145671787
476352173
569121634
678732645
787643556
912345678
123452789
214265178
395226739
494989628
167211984
454915125
523121236
891234567
Test input 3:
123451989
234569191
345328252
456234741
237343128
126936765
713843412
828754587
912345678
234262871
367173982
623782193
512398873
571216319
277388484
619218545
986145456
126436789
567671782
178986783
955897676
544226619
969891856
881294145
592347934
153289345
235341671
678567523
745167854
363476523
465341976
168816567
979317432
524498132
452368119
355244782
789823434
654758929
914871838
846936797
967127256
828876952
652985148
586792767
257965893
678934345
712597456
163996745
967168692
823779385
784193941
565874315
476963894
345158234
789165456
895276195
214325294
891861983
936319871
125176912
454789123
367128954
691219765
891254367
912387678
345476589
932157991
143498162
276987493
789456912
678725843
745854654
912343278
123476589
456565491
123914312
234165123
567328234
678934321
767123432
856212543
```
[Answer]
# Rust, ~~38250~~ 14716 bytes
```
use std::{io::{stdin,Read},ops::{Add,Index,IndexMut,Sub},collections::HashSet,fmt::{self,Write}};use lazy_static::lazy_static;use regex::Regex;use tap::Tap;use hashbag::HashBag;trait Ta:l+Sized{fn V(&mut self,d(A,o,D):d){let mut ha=A;if A[o]>1{ha[o]-=1;}else{ha[o]+=1;}let Da=if o==c::X{c::Y}else{c::X};self.u(d(ha,o,D));self.u(d(A,Da,2));self.u(d(ha,o,-D));self.u(d(A,Da,2));self.u(d(A,o,-D));}fn Bb(&mut self,q:Vec<d>){for m in q{self.V(m);}}}impl<T:l>Ta for T{}trait l{fn get(&self,e:b)->B;fn K(&self,e:b)->B;fn u(&mut self,m:d);fn j(&self)->b;fn ia(&mut self,q:Vec<d>){for m in q{self.u(m);}}}impl<T:l+?Sized>l for&mut T{fn get(&self,e:b)->B{(**self).get(e)}fn K(&self,e:b)->B{(**self).K(e)}fn u(&mut self,m:d){(**self).u(m)}fn j(&self)->b{(**self).j()}}lazy_static!{static ref Ea:[[[B;9];9];9]={#[inline(never)]fn pa<F:Fn((u8,I))->T,I:Copy,T>(N:F)->impl Fn(I)->[T;9]{move|i|{[N((0,i)),N((1,i)),N((2,i)),N((3,i)),N((4,i)),N((5,i)),N((6,i)),N((7,i)),N((8,i)),]}}pa(pa(pa(|(x,(y,(z,_)))|B((x+y+z)%18))))(())};}impl l for[[[B;9];9];9]{fn get(&self,e:b)->B{self[e.0][e.1][e.2]}fn K(&self,e:b)->B{Ea[e.0][e.1][e.2]}fn u(&mut self,mut m:d){m.2=m.2.rem_euclid(4);if m.2==0{return;}let Fa=m.0-b(1,1,1);let Ua:Vec<_>=self.slice(Fa,b(3,3,3)).iter().map(|(p,v)|(p.M(m.1,m.2,3)+Fa,v)).collect();for(e,ja)in Ua{self[e.0][e.1][e.2]=ja;}}fn j(&self)->b{b(9,9,9)}}struct qa<'a,C:l>{g:&'a C,e:b,}impl<'a,C:l>Iterator for qa<'a,C>{type Item=(b,B);fn next(&mut self)->Option<Self::Item>{let j=self.g.j();if self.e.2==j.2{return None;}let Va=Some((self.e,self.g.get(self.e)));self.e.0+=1;if self.e.0>=j.0{self.e.0=0;self.e.1+=1;if self.e.1>=j.1{self.e.1=0;self.e.2+=1;}}Va}fn size_hint(&self)->(usize,Option<usize>){let j=self.g.j();let Ga=j.0*j.1*j.2-self.e.0-self.e.1*j.0-self.e.2*j.0*j.1;(Ga,Some(Ga))}}trait Wa:l+Sized{fn iter<'a>(&'a self)->qa<'a,Self>{qa{g:self,e:b(0,0,0),}}}impl<T:l>Wa for T{}struct ka<C:l>{g:C,o:c,}impl<C:l>ka<C>{fn sa(&self,e:b)->b{e.P(self.o,self.j()[self.o])}}impl<C:l>l for ka<C>{fn get(&self,e:b)->B{self.g.get(self.sa(e))}fn K(&self,e:b)->B{self.g.K(self.sa(e))}fn u(&mut self,mut m:d){m.0=self.sa(m.0);if m.1!=self.o{m.2=-m.2;}self.g.u(m);}fn j(&self)->b{self.g.j()}}trait Xa:l+Sized{fn P(self,o:c)->ka<Self>{ka{g:self,o}}}impl<T:l>Xa for T{}trait Ya:l{fn Cb(&mut self)->bool{self.iter().all(|(e,ja)|ja==self.K(e))}}impl<T:l>Ya for T{}fn main(){let mut Ha=String::new();stdin().read_to_string(&mut Ha).unwrap();let mut g=Ia(Zb(&Ha[..]).unwrap());g.ab();}struct Ia([[[B;9];9];9]);impl l for Ia{fn get(&self,e:b)->B{self.0.get(e)}fn K(&self,e:b)->B{self.0.K(e)}fn j(&self)->b{self.0.j()}fn u(&mut self,m:d){println!("{}",db(&m));self.0.u(m);}}#[derive(Clone)]struct d(b,c,i8);trait eb{fn ba(self)->Self;}impl eb for Vec<d>{fn ba(mut self)->Self{self.reverse();for m in self.iter_mut(){m.2=-m.2;}self}}fn db(d(b(x,y,z),o,D):&d)->String{format!("{}{}{}{}{}",x,y,z,match o{c::X=>"X",c::Y=>"Y",c::Z=>"Z",},D.rem_euclid(4).to_string())}fn Zb(str:&str)->Result<[[[B;9];9];9],String>{let str=str.to_lowercase();let str=str.trim();let charset=if str.contains('a'){"0a1b2c3d4e5f6g7h8i"}else if str.contains('0'){"012345678"}else{"123456789"};let mut z=0;let mut g:[[[B;9];9];9]=Default::default();lazy_static!{static ref fb:Regex=Regex::new(r"\s*\n\s*\n\s*").unwrap();}for ua in fb.split(str){let ua=ua.trim();let mut O=z;for(y,la)in ua.split("\n").enumerate(){let la=la.trim();O=z;let gb=if la.chars().nth(1)==Some(' '){""}else{""};for ra in la.split(gb).filter(|x|*x!=""){let ra=ra.trim();for(x,char)in ra.chars().filter(|x|*x!=' ').enumerate(){if x>=9||y>=9||O>=9{dbg!((x,y,O));return Err(format!("Invalid g j{:?}",(x,y,O)));}let mut ta=if let Some(index)=charset.find(char){index as u8}else{return Err(format!("Invalid character{:?}",char));};if ta%2!=((x+y+O)%2)as u8{if charset.len()==9{ta+=9}else{return Err(format!("Invalid parity at position{:?}",(x,y,O)));}};g[x][y][O].0=ta;}O+=1;}}z=O;}if<[_]>::iter(&g).flatten().flatten().collect::<HashBag<_>>()!=<[_]>::iter(&*Ea).flatten().flatten().collect(){return Err(format!("Invalid piece counts"));}Ok(g)}#[derive(Clone,Copy,PartialEq,Eq,Hash)]struct b(usize,usize,usize);impl b{fn H(mut self,h:c,k:c)->b{let f=self[h];self[h]=self[k];self[k]=f;self}fn P(mut self,o:c,E:usize)->b{self[o]=E-1-self[o];self}fn M(self,o:c,D:i8,E:usize)->b{let mut ca=self;for _ in 0..(D.rem_euclid(4)){ca=match o{c::X=>ca.H(c::Y,c::Z).P(c::Y,E),c::Y=>ca.H(c::Z,c::X).P(c::Z,E),c::Z=>ca.H(c::X,c::Y).P(c::X,E),};}ca}fn parity(self)->usize{(self.0+self.1+self.2)%2}fn va(self,min:b,E:b)->bool{true&&self.0>=min.0&&self.0<=E.0&&self.1>=min.1&&self.1<=E.1&&self.2>=min.2&&self.2<=E.2}}impl Add for b{type Output=b;fn add(self,Q:Self)->Self::Output{b(self.0+Q.0,self.1+Q.1,self.2+Q.2)}}impl Sub for b{type Output=b;fn sub(self,Q:Self)->Self::Output{b(self.0-Q.0,self.1-Q.1,self.2-Q.2)}}#[derive(Copy,Clone,PartialEq,Eq)]enum c{X=0,Y=1,Z=2,}impl Index<c>for b{type Output=usize;fn index(&self,index:c)->&Self::Output{match index{c::X=>&self.0,c::Y=>&self.1,c::Z=>&self.2,}}}impl IndexMut<c>for b{fn index_mut(&mut self,index:c)->&mut Self::Output{match index{c::X=>&mut self.0,c::Y=>&mut self.1,c::Z=>&mut self.2,}}}struct wa<C:l>{g:C,min:b,j:b,}impl<C:l>l for wa<C>{fn get(&self,e:b)->B{self.g.get(e+self.min)}fn K(&self,e:b)->B{self.g.K(e+self.min)}fn u(&mut self,mut m:d){m.0=m.0+self.min;self.g.u(m)}fn j(&self)->b{self.j}}trait hb:l+Sized{fn slice(self,min:b,j:b)->wa<Self>{wa{g:self,min,j,}}}impl<T:l>hb for T{}trait ib:l+Sized{fn ab(&mut self){let j=self.j();let mut min=b(0,0,0);let mut E=j;for&o in[c::Z,c::Y,c::X].iter(){for _ in 0..((j[o]-5+1/*round Eb*/)/2){self.jb(o,min,E);min[o]+=1;}for _ in 0..((j[o]-5)/2){self.kb(o,min,E);E[o]-=1;}}self.slice(min,b(5,5,5)).W(Ja).W(Ka).W(La).W(Ma);}}trait lb:l{fn jb(&mut self,o:c,min:b,E:b){self.slice(min,E-min).H(c::Z,o).W(xa);}fn kb(&mut self,o:c,min:b,E:b){self.slice(min,E-min).H(c::Z,o).P(c::X).P(c::Y).P(c::Z).W(xa);}}impl<T:l>ib for T{}impl<T:l>lb for T{}struct xa;impl aa for xa{fn L<C:l>(&self,g:&C,e:b)->t{let j=g.j();let b(x,y,z)=e;if z!=0{return t::da;};let index=y*j.0+x;if y+2>=j.1{if x+2>=j.0{t::G{index,w:b(j.0-4+j.1-y,j.1-1,5+x-j.0),q:vec![d(b(j.0-2,j.1-2,1),c::X,1),d(b(j.0-2,j.1-2,1),c::Y,-1),d(b(j.0+j.1-5-y,j.1-2,4+x-j.0),c::Y,1,),d(b(j.0-2,j.1-2,1),c::Y,1),d(b(j.0-2,j.1-2,1),c::X,-1),],}}else{t::G{index,w:b(x,j.1-1,5+y-j.1),q:vec![d(b(x+1,j.1-2,1),c::X,1),d(b(x+1,j.1-2,4+y-j.1),c::X,-1),d(b(x+1,j.1-2,1),c::X,-1),],}}}else{if x+2>=j.0{t::G{index,w:b(j.0-1,y,5+x-j.0),q:vec![d(b(j.0-2,y+1,1),c::Y,-1),d(b(j.0-2,y+1,4+x-j.0),c::Y,1),d(b(j.0-2,y+1,1),c::Y,1),],}}else{t::G{index,w:e+b(0,0,2),q:vec![d(e+b(1,1,1),c::Y,-1)],}}}}fn J<C:l>(&self,g:&mut C,h:b,k:b){mb(g.slice(b(0,0,1),g.j()-b(0,0,1)),h-b(0,0,1),k-b(0,0,1),);}}fn mb<C:l>(mut g:C,mut h:b,k:b){if h.parity()!=k.parity(){panic!("Cannot move between positions of different parities");}while h!=k{ya(&mut g,c::X,&mut h,k);ya(&mut g,c::Y,&mut h,k);ya(&mut g,c::Z,&mut h,k);}}fn ya<C:l>(g:C,o:c,h:&mut b,k:b){let nb=g.H(c::X,o);let mut Na=h.H(c::X,o);ob(nb,&mut Na,k.H(c::X,o));*h=Na.H(c::X,o)}fn ob<C:l>(mut g:C,h:&mut b,k:b){let ja=g.get(*h);let j=g.j();while h.0!=k.0{let mut A=b(0,0,0);let D;if h.0<k.0{A.0=h.0+1}else{A.0=h.0-1}if(h.0+1==k.0||k.0+1==h.0)&&h.0!=0&&h.0!=j.0-1{A.0=h.0}if h.1<=1{A.1=h.1+1;D=if h.0<k.0{1}else{3}}else{A.1=h.1-1;D=if h.0<k.0{3}else{1}}if h.2<=1{A.2=1}else{A.2=h.2-1}g.u(d(A,c::Z,D));*h=(*h-(A-b(1,1,1))).M(c::Z,D,3)+(A-b(1,1,1));}}struct Ma;impl aa for Ma{fn J<C:l>(&self,ma:&mut C,h:b,k:b){}fn L<C:l>(&self,ma:&C,e:b)->t{let ea=true&&e.0>=1&&e.0<=3&&e.1>=1&&e.1<=3&&e.2>=1&&e.2<=3&&e.parity()==1&&e.0!=2&&e.1!=2&&e.2!=2;if!ea{return t::na;}let fa=match e{b(1,1,1)=>return t::da,b(3,3,1)=>vec![],b(1,3,1)=>vec![d(b(2,3,2),c::Y,-1)],b(3,1,1)=>vec![d(b(3,2,2),c::X,1)],b(x,y,3)=>vec![d(b(2,2,3),c::Z,if x==1{if y==1{2}else{-1}}else{if y==1{1}else{0}},),d(b(2,3,2),c::Y,1),],_=>unreachable!(),};let mut q=fa.clone();q.extend_from_slice(&pb);q.extend(fa.ba());t::G{index:if e==b(3,2,1){1}else{0},w:b(1,1,1),q,}}fn u<C:l>(&self,g:&mut C,m:d){g.V(m);}}static pb:[d;17]=[d(b(2,3,2),c::Y,-1),d(b(3,2,2),c::X,-1),d(b(2,2,1),c::Z,-1),d(b(3,2,2),c::X,1),d(b(2,2,1),c::Z,-1),d(b(3,2,2),c::X,-1),d(b(2,2,1),c::Z,1),d(b(3,2,2),c::X,1),d(b(2,3,2),c::Y,1),d(b(3,2,2),c::X,-1),d(b(2,2,1),c::Z,1),d(b(3,2,2),c::X,1),d(b(2,2,1),c::Z,-1),d(b(3,2,2),c::X,1),d(b(2,3,2),c::Y,-1),d(b(3,2,2),c::X,-1),d(b(2,3,2),c::Y,1),];struct Ka;impl aa for Ka{fn J<C:l>(&self,g:&mut C,h:b,k:b){fn f(e:b)->i8{if e.0==1{if e.1==1{0}else{1}}else{if e.1==1{3}else{2}}}g.V(d(b(2,2,h.2),c::Z,f(h)-f(k)));if k.2!=h.2{g.V(d(b(2,k.1,2),c::Y,-((k.0+k.2-1)as i8)));}}fn L<C:l>(&self,ma:&C,e:b)->t{let ea=e.va(b(1,1,1),b(3,3,3))&&e.parity()==1;if!ea{return t::na;}match e{b(x,2,2)=>t::G{index:0,w:b(x,1,1),q:vec![d(b(x,2,1),c::X,1),d(b(x,1,2),c::X,-1),d(b(x,2,1),c::X,-1),d(b(x,1,2),c::X,1),],},b(2,y,2)=>t::G{index:0,w:b(1,y,1),q:vec![d(b(1,y,2),c::Y,1),d(b(2,y,1),c::Y,-1),d(b(1,y,2),c::Y,-1),d(b(2,y,1),c::Y,1),],},b(2,2,z)=>t::G{index:0,w:b(1,1,z),q:vec![d(b(2,1,z),c::Z,1),d(b(1,2,z),c::Z,-1),d(b(2,1,z),c::Z,-1),d(b(1,2,z),c::Z,1),],},_=>t::da,}}fn u<C:l>(&self,g:&mut C,m:d){g.V(m);}}struct La;impl aa for La{fn J<C:l>(&self,ma:&mut C,h:b,k:b){}fn L<C:l>(&self,ma:&C,e:b)->t{let ea=e.va(b(1,1,1),b(3,3,3))&&e.parity()==0&&e!=b(2,2,2);if!ea{return t::na;}let fa=match e{b(3,2,1)=>return t::da,b(1,2,1)=>vec![],b(x,y,3)=>vec![d(b(2,2,3),c::Z,if x==3{2}else if y==3{1}else if y==1{-1}else{0},),d(b(1,2,2),c::X,2),],b(x,y,2)=>vec![d(b(2,2,2),c::Z,if x==3{if y==3{1}else{2}}else{if y==3{0}else{-1}},),d(b(1,2,2),c::X,-1),],b(2,y,1)=>vec![d(b(2,2,2),c::X,2),d(b(2,2,3),c::Z,if y==3{-1}else{1}),d(b(1,2,2),c::X,2),],_=>unreachable!(),};let mut q=fa.clone();q.extend_from_slice(&qb);q.extend(fa.ba());t::G{index:if e==b(3,2,1){1}else{0},w:b(3,2,1),q,}}fn u<C:l>(&self,g:&mut C,m:d){g.V(m);}}static qb:[d;14]=[d(b(3,2,2),c::X,-1),d(b(2,2,1),c::Z,1),d(b(3,2,2),c::X,1),d(b(2,2,1),c::Z,-1),d(b(3,2,2),c::X,1),d(b(2,3,2),c::Y,-1),d(b(3,2,2),c::X,2),d(b(2,2,1),c::Z,-1),d(b(3,2,2),c::X,1),d(b(2,2,1),c::Z,-1),d(b(3,2,2),c::X,-1),d(b(2,2,1),c::Z,1),d(b(3,2,2),c::X,1),d(b(2,3,2),c::Y,1),];lazy_static!{static ref za:Vec<d>=vec![d(b(1,2,2),c::Z,1),d(b(2,3,2),c::Z,-1),d(b(1,2,2),c::Z,-1),d(b(2,3,2),c::Z,1),];static ref Oa:Vec<d>=za.clone().ba();}struct Ja;impl aa for Ja{fn J<C:l>(&self,g:&mut C,h:b,k:b){let A=b(2,2,2);if h.parity()!=k.parity(){panic!("Cannot move between positions of different parities");}if h==k{return;}if h.parity()==1{fn Aa(e:b)->bool{((e.0==2)as u8+(e.1==2)as u8+(e.2==2)as u8)==2}if Aa(h){if Aa(k){fn Pa(e:b)->(c,i8){let o=if e.0!=2{c::X}else if e.1!=2{c::Y}else{c::Z};(o,if e[o]==3{1}else{-1})}let(Qa,rb)=Pa(h);let(Ba,sb)=Pa(k);if Qa==Ba{g.u(d(A,if Ba==c::X{c::Y}else{c::X},2,))}else{let(tb,ub)=match(Qa,Ba){(c::X,c::Y)=>(c::Z,1),(c::Y,c::X)=>(c::Z,-1),(c::Z,c::X)=>(c::Y,1),(c::X,c::Z)=>(c::Y,-1),(c::Y,c::Z)=>(c::X,1),(c::Z,c::Y)=>(c::X,-1),_=>unreachable!(),};g.u(d(A,tb,rb*sb*ub));}}else{self.J(g,h,b(2,2,1));g.ia(Oa.clone());self.J(g,b(1,3,1),k);}}else{if Aa(k){self.J(g,h,b(1,3,1));g.ia(za.clone());self.J(g,b(2,2,1),k);}else{fn f(e:b)->i8{if e.0==1{if e.1==1{0}else{1}}else{if e.1==1{3}else{2}}}g.u(d(A,c::Z,f(h)-f(k)));if k.2!=h.2{g.u(d(A,c::Y,-((k.0+k.2-1)as i8)));}}}}else{if h==A{g.ia(Oa.clone());self.J(g,b(1,3,2),k);}else if k==A{self.J(g,h,b(1,3,2));g.ia(za.clone());}else if h.2!=k.2{let mut h=h;while h.2!=k.2{let o=if h.0==2{c::Y}else{c::X};let ga=if o==c::Y{-1}else{1};g.u(d(A,o,ga));h=h.M(o,ga,5);}self.J(g,h,k);}else{fn f(e:b)->i8{if e.0<=2&&e.1==1{3}else if e.0==3&&e.1<=2{2}else if e.0>=2&&e.1==3{1}else{0}}g.u(d(A,c::Z,f(h)-f(k)));}}}fn L<C:l>(&self,g:&C,e:b)->t{match e{b(2,2,2)=>t::G{index:100,w:b(2,2,2),q:vec![],},p if vb(p)=>t::da,_=>match e{p if p.0>=3||p.1>=3=>self.L(g,e.M(c::Z,1,5)).tap_mut(|x|x.M(c::Z,-1,5)),p if p.2>=1=>{let(o,ga)=if p.1==0{(c::X,1)}else{(c::Y,-1)};self.L(g,e.M(o,ga,5)).tap_mut(|x|x.M(o,-ga,5))}p if p.1>p.0=>self.L(g,e.H(c::X,c::Y)).tap_mut(|x|x.H(c::X,c::Y)),b(0,0,0)=>t::G{index:0,w:b(2,2,2),q:vec![d(b(1,1,1),c::Z,2),d(b(1,1,1),c::X,1),],},b(1,0,0)=>t::G{index:1,w:b(2,3,2),q:vec![d(b(1,1,1),c::Z,1),d(b(1,1,1),c::Y,-1),d(b(2,2,2),c::Z,2),d(b(1,1,1),c::Y,1),d(b(1,1,1),c::Z,-1),],},b(2,0,0)=>t::G{index:2,w:b(2,2,2),q:vec![d(b(2,3,2),c::Z,-1),d(b(1,1,1),c::Z,1),d(b(1,1,1),c::Y,-1),d(b(2,3,2),c::Z,1),d(b(1,1,1),c::Y,1),d(b(1,1,1),c::Z,-1),],},b(1,1,0)=>t::G{index:3,w:b(3,3,2),q:vec![d(b(1,1,1),c::Z,1),d(b(1,1,1),c::Y,2),d(b(2,2,2),c::Z,2),d(b(1,1,1),c::Y,2),d(b(1,1,1),c::Z,-1),],},b(2,1,0)=>t::G{index:4,w:b(1,2,2),q:vec![d(b(2,3,2),c::Z,-1),d(b(1,1,1),c::Z,-1),d(b(1,1,1),c::X,2),d(b(2,3,2),c::Z,1),d(b(1,1,1),c::X,2),d(b(1,1,1),c::Z,1),],},b(2,2,0)=>t::G{index:5,w:b(2,3,3),q:vec![d(b(1,1,1),c::Z,1),d(b(1,1,1),c::Y,2),d(b(3,3,2),c::X,1),d(b(1,1,1),c::Y,2),d(b(1,1,1),c::Z,-1),d(b(3,3,2),c::X,-1),],},_=>unreachable!(),},}}}fn vb(p:b)->bool{p.va(b(1,1,1),b(3,3,3))}trait aa{fn L<C:l>(&self,g:&C,e:b)->t;fn J<C:l>(&self,g:&mut C,h:b,k:b);fn u<C:l>(&self,g:&mut C,m:d){g.u(m);}fn wb<C:l>(&self,g:&mut C){let mut oa=<HashSet<b>>::new();let mut Ra:Vec<_>=g.iter().filter_map(|(e,_)|match self.L(g,e){t::G{index,w,q,}=>Some((e,index,w,q)),_=>None,}).collect();Ra.sort_by_key(|x|x.1);for(e,_,w,q)in Ra{oa.insert(e);let Sa=g.K(e);if g.get(e)==Sa{continue;}let h=g.iter().find(|&(p,v)|{v==Sa&&!matches!(self.L(g,p),t::na)&&!oa.contains(&p)}).unwrap().0;if let t::G{q:xb,w:yb,..}=self.L(g,h){for m in xb.ba(){self.u(g,m);}self.J(g,yb,w);}else{self.J(g,h,w);}for m in q{self.u(g,m);}}}}trait zb:l+Sized{fn W<S:aa>(&mut self,bb:S)->&mut Self{bb.wb(self);self}}impl<T:l>zb for T{}enum t{G{index:usize,w:b,q:Vec<d>,},da,na,}impl t{fn H(&mut self,h:c,k:c){match self{Self::G{w,q,..}=>{*w=w.H(h,k);for m in q.iter_mut(){m.2=-m.2;m.0=m.0.H(h,k);if m.1==h{m.1=k;}else if m.1==k{m.1=h;}else{m.1;}}}_=>{}}}fn M(&mut self,o:c,D:i8,E:usize){let D=D.rem_euclid(4);if D==0{return;}match self{Self::G{w,q,..}=>{*w=w.M(o,D,E);for m in q.iter_mut(){m.0=m.0.M(o,D,E);if match(o,D){(c::X,1)|(c::Y,3)=>m.1==c::Z,(c::Y,1)|(c::Z,3)=>m.1==c::X,(c::Z,1)|(c::X,3)=>m.1==c::Y,(_,_)=>m.1!=o,}{m.2=-m.2;}if D!=2{m.1=match(o,m.1){(c::Y,c::Z)|(c::Z,c::Y)=>c::X,(c::Z,c::X)|(c::X,c::Z)=>c::Y,(c::X,c::Y)|(c::Y,c::X)=>c::Z,_=>o,};}}}_=>{}}}}struct Ca<C:l>{g:C,h:c,k:c,}impl<C:l>l for Ca<C>{fn get(&self,e:b)->B{self.g.get(e.H(self.h,self.k))}fn K(&self,e:b)->B{self.g.K(e.H(self.h,self.k))}fn u(&mut self,mut m:d){if self.h!=self.k{m.0=m.0.H(self.h,self.k);m.2=-m.2;if m.1==self.h{m.1=self.k;}else if m.1==self.k{m.1=self.h;}}self.g.u(m)}fn j(&self)->b{self.g.j().H(self.h,self.k)}}trait Ab:l+Sized{fn H(self,h:c,k:c)->Ca<Self>{Ca{g:self,h,k,}}}impl<T:l>Ab for T{}#[derive(PartialEq,Eq,Copy,Clone,Hash,Default)]struct B(u8);
```
The solution is hosted [on GitHub](https://github.com/tjjfvi/cubular/tree/main/src/main.rs). Running `cargo run` in the root
directory will take the cube from stdin and output a list of moves that solves
the inputted cube. Input can be in any of the forms from the question and this
answer. The output will use a modified coordinate system by default, but can be
changed to use the question's coordinate system by changing line 27.
If you'd like to play with the cube and see how it's solved, I've created [an
interactive visualization](https://cubular.t6.fyi/).
If you'd like to read about how it's solved, I've written a long detailed
explanation with interactive illustrations of the process.
## Explanation
### Coordinate System
This explanation will use a slightly different coordinate system than the challenge.
`X` is left-to-right, `Y` is top-to-bottom, and `Z` is front-to-back.
Here are 3 different visualizations of the axes:
```
z
/ E F
/ G H
* - - x
| A B
| C D
y
A B E F
C D G H
```
```
0 x z ·
y · · ·
```
```
Positions as 'xyz':
000 100 001 101
010 110 011 111
```
Rotations are clockwise looking down the axis (right-hand rule).
Here is a visualization of the 3 unit rotations:
```
cube: X1(cube):
0 x z · z · · ·
y · · · 0 x y ·
cube: Y1(cube):
0 x z · x · 0 z
y · · · · · y ·
cube: Z1(cube):
0 x z · y 0 · z
y · · · · x · ·
```
### 0-indexing
The original challenge 1-indexes the pieces, which complicates
the modulo arithmetic. This explanation will use 0-indexing, where the pieces
are numbered 0-8.
```
1-indexing
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
...
0-indexing
0 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 0
...
```
### Parity
Pieces are locked in to a checkerboard pattern; pieces from odd places
can only go to odd places, and likewise for even.
This means that there are actually 18 kinds of pieces.
```
0 in an even position --> 0 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 0 <-- 0 in an odd position
...
```
This brings us to...
### Alternate Notation
Because there are 18 kinds of pieces, it's helpful to have 18 distinct symbols.
From now on, this explanation will use an adapted, alpha-numeric notation, where
all even-parity pieces are numbers, and all odd-parity pieces are letters.
```
0-indexed
0 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 0
2 3 4 5 6 7 8 0 1
3 4 5 6 7 8 0 1 2
...
Alpha-numeric
0 a 1 b 2 c 3 d 4
a 1 b 2 c 3 d 4 e
1 b 2 c 3 d 4 e 5
b 2 c 3 d 4 e 5 f
...
```
### Links
Throughout this explanation, links to cube states will be used to illustrate the
process. Here's [a scrambled cube](https://cubular.t6.fyi/#unsolved), and [a solved cube](https://cubular.t6.fyi/#solved).
Some links will illustrate a set of moves. First, it will show the goal state,
followed by the start state of the cube. Then, for each move, it will first
highlight the positions that will be affected, and then show the result of the
move. Here's an example of [a small algorithm](https://cubular.t6.fyi/#small-algorithm).
Additionally, some links with moves will emphasize certain pieces. The bordered
pieces are the focus, and the highlighted pieces are pieces that will/must
remain unchanged. Here's an example of [the previous algorithm with
highlights](https://cubular.t6.fyi/#small-algorithm-highlighted). Sometimes, only a subset of the
unchanged pieces will be highlighted, to make it easier to track the rotations.
### Approach to Solving
To solve the cube, we iterate through the positions in some order and solve each of
them without unsolving the previous positions.
Positions can be in two states: solved & unsolved. When solving a position,
pieces in solved positions may be moved but must be restored to ensure the solved
positions are ultimately unchanged.
A position is solved by the following process:
1. Locate a piece of the correct value in any unsolved position.
2. Move the piece to the correct position without ultimately changing any solved
position.
#1 is fairly self-explanatory, so the rest of this explanation focuses on #2.
At various times throughout solving the cube, we'll denote an unsolved section of the
cube as the "pool". We'll then divide #2 into 3 parts:
1. Move the piece into the pool.
2. Move the piece around in the pool.
3. Move the piece out of the pool into the correct position.
To accomplish this, we'll need to define two helpers:
1. We'll figure out how to move a piece from any position in the pool to any
other position of the same parity in the pool.
2. Then, for each unsolved position outside of the pool, we'll choose a convenient
"source" position in the pool and figure out a list of moves that will move a piece
from the source position to the position we're solving.
Using these two helpers, we can refine the above process:
1. Move the piece into the pool.
* Execute the reverse of the moves supplied by helper #2.
2. Move the piece around in the pool.
* Use helper #1.
3. Move the piece out of the pool into the correct position.
* Execute the moves supplied by helper #2.
We will now formalize and define this logic.
### Overview
At a high level, the solving method is broken into three stages.
1. Solving the outer shell (everything but the center 5×5×5)
2. Solving the inner shell (the center 5×5×5 excluding the center 3×3×3)
3. Solving the center 3×3×3
Each stage consists of a few steps.
### Step Structure
In each step, the puzzle positions are paritioned into 3 classifications:
1. 'active': unsolved positions that will be solved by the step
2. 'done': previously solved positions
3. 'pool': unsolved positions
A step is executed by iterating through the 'active' positions and solving each
position by executing the following prodecure:
1. Locate a piece of the correct value in any unsolved position.
2. Move the piece into the pool.
3. Move the piece within the pool to a 'source' position in the pool.
4. Move the piece from the 'source' position to the target position.
All of the above steps must be performed without ultimately changing any piece
in a previously solved 'active' position or any piece in a 'done' position.
### Step Definition
Thus, a step is defined by:
1. A partition of the puzzle pieces
2. A way to move a piece from any 'pool' position to any other 'pool'
position of the same parity (without ultimately changing any piece in an
'active' or 'done' position)
3. For each 'active' position:
* An index indicating when to solve this position
* A convenient source 'pool' position
* A list of moves that will move a piece from the specified 'pool' position
to this position (without ultimately changing any piece in an 'active'
position with a lower index or any piece in a 'done' position)
### Stage 1: Solving the outer shell
In this stage, we'll [solve everything but the center 5×5×5](https://cubular.t6.fyi/#after-stage-1).
We'll accomplish this with 12 steps, each step solving a face of the unsolved
portion of the 9×9×9. We could go in any order; the implementation follows this
ordering (as it looked nice):
1. The `Z=0` plane ([after](https://cubular.t6.fyi/#after-stage1-step1))
2. The `Z=1` plane ([after](https://cubular.t6.fyi/#after-stage1-step2))
3. The `Z=8` plane ([after](https://cubular.t6.fyi/#after-stage1-step3))
4. The `Z=7` plane ([after](https://cubular.t6.fyi/#after-stage1-step4))
5. The `Y=0` plane ([after](https://cubular.t6.fyi/#after-stage1-step5))
6. The `Y=1` plane ([after](https://cubular.t6.fyi/#after-stage1-step6))
7. The `Y=8` plane ([after](https://cubular.t6.fyi/#after-stage1-step7))
8. ...
9. ...
10. ...
11. ...
12. The `X=7` plane ([after](https://cubular.t6.fyi/#after-stage-1))
### Stage 1, Step 1: Solving the `Z=0` face
All positions with `Z=0` are 'active', and all other positions are 'pool'.
The most interesting part of this step involves the 'active' positions. The
'active' positions fall into 3 categories based on their location:
```
A A A A A A A A B B
A A A A A A A A B B
A A A A A A A A B B
A A A A A A A A B B
A A A A A A A A B B
A A A A A A A A B B
A A A A A A A A B B
B B B B B B B B C C
B B B B B B B B C C
```
We'll solve each 'active' position from left-to-right, then top-to-bottom.
The examples that follow focus solely on the moves after the piece is moved
into the 'source' position.
`A` positions are the easiest to solve, as they only require one rotation;
here's an [example for one `A` position](https://cubular.t6.fyi/#stage1-step1-A).
`B` positions are a little more complicated. Because they're near the
edge, we can't use the same technique as in `A`. This means that we'll have to
move some of the pieces we've previously solved, but we also need to make sure
to restore them to the correct position afterwards. Here's an [example
of how this is accomplished for one `B` position](https://cubular.t6.fyi/#stage1-step1-B).
If you've played with puzzle cubes before, the technique used in that algorithm
may be familiar. Essentially, we're rotating the target position to a more
convenient place, moving the piece in, and then undoing the rotation of the
target position.
Last and certainly not least, we have `C` positions, which are surrounded on all
sides. Solving them is similar to `B` positions, but a little more complicated.
Here's an [example for one `C` position](https://cubular.t6.fyi/#stage1-step1-C).
Moving pieces within the pool is rather simple, as there's a lot of room, and the
pool is a rectangular prism; here is an [example for one case](https://cubular.t6.fyi/#stage1-step1-pool-example). A full
explanation of the algorithm is omitted, as it is not very novel.
### Stage 1, Steps 2-12
These steps follow the same pattern as Step 1, just on different faces within
the cube.
### Stage 2: Solving the inner shell
At this point, [everything is solved except for the inner 5×5×5](https://cubular.t6.fyi/#after-stage-1).
After this stage, [everything except the inner 3×3×3 will be solved](https://cubular.t6.fyi/#after-stage2).
This stage is not part of Stage 1 because some of the algorithms used in Stage 1
require more space than is available in the 5×5×5.
This stage consists of a single step.
All positions outside of in center 5×5×5 are 'done' and will not be changed
(even temporarily). Positions in the center 3×3×3 are 'pool', and the remainder
are 'active'.
### Stage 2, Moving between 'pool' positions
Moving pieces between 'pool' positions is more complex in this step, because of
the limited space. To describe how pieces are moved, we'll first divide the pool
into 4 sections, pictured below.
```
P T P T Q T P T P
T Q T Q U Q T Q T
P T P T Q T P T P
```
`P` positions are the corners, `Q` positions are the face centers, `T` positions
are the edges, and the singular `U` position is the cube center.
`P` and `Q` positions all have odd parity, and `T` and `U` positions all have
even. Thus, pieces can be moved freely between `P` and `Q` positions, and `T` and
`U` positions, but not between `P` and `T` positions, `P` and `U` positions,
etc.
Thus, there are 8 possible cases:
* P: From a `P` position to another `P` position
* Q: From a `Q` position to another `Q` position
* T: From a `T` position to another `T` position
* U: From the `U` position to itself
* PQ: From a `P` position to a `Q` position
* QP: From a `Q` position to a `P` position
* TU: From a `T` position to the `U` position
* UT: From the `U` position to a `T` position
Case U is very trivial, since it is accomplished by doing nothing. Cases P, Q,
T are fairly trivial, and can be accomplished simply by rotating the center
3×3×3.
Cases PQ, QP, TU, UT are where things get interesting — remember that these
must be accomplished without ultimately changing any piece outside of the pool,
the center 3×3×3.
Cases QP & UT are the reverse of cases PQ & TU, respectively, so we will focus
on the later two cases.
Cases PQ & TU are both based off of the following algorithm that we'll call
`INTO_CENTER`, which moves a piece from position `X` into position `U` whilst
preserving everything outside of the center 3×3×3.
```
· · · · · · · · ·
· · · · U · · · ·
· · · X · · · · ·
```
Here is [`INTO_CENTER` in action](https://cubular.t6.fyi/#INTO_CENTER-demo).
First, Case TU. We can accomplish it with the follwing procedure:
1. Move the piece from the original `T` position to position `V` using Case T.
2. Use `INTO_CENTER` to move the piece from position `V` to position `U`.
```
· · · · · · · T ·
· · · · U · · · ·
· · · V · · · · ·
```
Onto Case PQ. If you look at the moves in `INTO_CENTER` (linked above), you
might notice two things:
1. All of the moves rotate around the `Z` axis
2. All of the moves are at `Z=4`
These two properties mean that `INTO_CENTER` has the same effect on the `Z=3`
and `Z=5` layers as it does on the `Z=4` layer we focused on.
This means that we can accomplish Case PQ with the following procedure:
1. Move the piece from the original `P` position to position `R`, using Case P.
2. Use `INTO_CENTER` to move the piece from position `R` to position `S`.
3. Move the piece from position `S` to the destination `Q` position, using Case
Q.
```
· · · · · · · · P
· S · · · · · · ·
R · · · Q · · · ·
```
### Stage 2, Moving pieces to 'active' positions
Now that we have a method to move pieces between 'pool' positions, we can move
on to describing the 'active' positions.
First, we'll break up the 'active' positions into a few categories, and then
we'll describe each category.
We'll label the categories `A`-`F`; the partition is pictured below.
```
A B C B A B D E D B C E F E C B D E D B A B C B A
B D E D B D · · · D E · · · E D · · · D B D E D B
C E F E C E · · · E F · · · F E · · · E C E F E C
B D E D B D · · · D E · · · E D · · · D B D E D B
A B C B A B D E D B C E F E C B D E D B A B C B A
```
The categories will be solved in alphabetical order; all `A` positions are
solved, then all `B` positions, etc.
For each category, we'll focus on the behavior of only one position; all of the
others follow by symmetry. Specifically, we'll focus on the following positions:
```
A B C · · · · · · · · · · · · · · · · · · · · · ·
· D E · · · · · · · · · · · · · · · · · · · · · ·
· · F · · · · · · · · · · · · · · · · · · · · · ·
· · · · · · · · · · · · · · · · · · · · · · · · ·
· · · · · · · · · · · · · · · · · · · · · · · · ·
```
When solving a position, care must be taken to not ultimately change any other
position that is outside of the 5×5×5 or in an earlier or current category.
The below diagrams are maps of the 5×5×5. `#` represents a position that must be
ultimately unchanged, `+` represents a 'pool' position, and `X` is the 'pool'
position that we'll later establish as our source 'pool' position.
First up are `A` positions.
```
A · · · # · · · · · · · · · · · · · · · # · · · #
· · · · · · + + + · · + + + · · + + + · · · · · ·
· · · · · · + + + · · + X + · · + + + · · · · · ·
· · · · · · + + + · · + + + · · + + + · · · · · ·
# · · · # · · · · · · · · · · · · · · · # · · · #
```
Solving this position is rather trivial. We'll set our source 'pool' position to
be in the center, and to solve the `A` position we'll simply [rotate the piece in](https://cubular.t6.fyi/#stage2-step1-A).
Let's move on to `B` positions.
```
# B · # # # · · · # · · · · · # · · · # # # · # #
# · · · # · + + + · · + + + · · + + + · # · · · #
· · · · · · + + + · · + + + · · + + + · · · · · ·
# · · · # · + + + · · + X + · · + + + · # · · · #
# # · # # # · · · # · · · · · # · · · # # # · # #
```
Here, there are more locked-in pieces, meaning that we can't just simply rotate
the piece in. Thus, we'll have to do [a little bit of maneuvering](https://cubular.t6.fyi/#stage2-step1-B).
It's getting a bit tighter, but [`C` positions are rather similar to `B`
positions](https://cubular.t6.fyi/#stage2-step1-C).
```
# # C # # # · · · # # · · · # # · · · # # # # # #
# · · · # · + + + · · + + + · · + + + · # · · · #
# · · · # · + + + · · + X + · · + + + · # · · · #
# · · · # · + + + · · + + + · · + + + · # · · · #
# # # # # # · · · # # · · · # # · · · # # # # # #
```
Onto [`D` positions](https://cubular.t6.fyi/#stage2-step1-D).
```
# # # # # # # · # # # · · · # # # · # # # # # # #
# D · # # # + + + # · + + + · # + + + # # # · # #
# · · · # · + + + · · + + + · · + + + · # · · · #
# # · # # # + + + # · + + + · # + + X # # # · # #
# # # # # # # · # # # · · · # # # · # # # # # # #
```
It's getting cramped! Time for [`E` positions](https://cubular.t6.fyi/#stage2-step1-E).
```
# # # # # # # # # # # # · # # # # # # # # # # # #
# # E # # # + + + # # + + + # # + + + # # # # # #
# # · # # # + + + # · X + + · # + + + # # # · # #
# # # # # # + + + # # + + + # # + + + # # # # # #
# # # # # # # # # # # # · # # # # # # # # # # # #
```
Finally, `F` positions. There is almost no room to work with here, but we can
[squeeze the piece in by rotating the corner cube and then one of the edge
cubes](https://cubular.t6.fyi/#stage2-step1-F).
```
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # + + + # # + + + # # + + + # # # # # #
# # F # # # + + + # # + + + # # + + + # # # # # #
# # # # # # + + + # # + + + # # + X + # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
```
### Stage 3: Solving the center 3×3×3
At this point, [everything but the center 3×3×3 is solved](https://cubular.t6.fyi/#after-stage2). At the
end of this stage, it will be [entirely solved](https://cubular.t6.fyi/#solved).
Stage 3 will be broken into 3 steps:
1. Solving [the center cross](https://cubular.t6.fyi/#stage3-step1-pieces)
2. Solving [the edges](https://cubular.t6.fyi/#stage3-step2-pieces)
3. Solving [the corners](https://cubular.t6.fyi/#stage3-step3-pieces)
### Thin Moves
Before moving on to Step 1, we're going to introduce a very useful set of
algorithms: thin moves. These allow us to rotate "flat" 1×3×3 sections of the
cube, without affecting other pieces.
In subsequent examples, thin moves are shown as lines labeled with a `t` — this
is a shorthand for the sequence of regular moves that comprise the thin move.
Here's an example of [the shorthand for a quarter-turn rotation on
Z](https://cubular.t6.fyi/#thin-move-example).
Here are [the moves that comprise the previous thin move](https://cubular.t6.fyi/#thin-move-dissection).
### Stage 3, Step 1: Solving the center cross
Again, the center cross is [this set of pieces](https://cubular.t6.fyi/#stage3-step1-pieces).
As a precursor, we're going to solve the center-most piece first, because we can
simply use the 'pool'-to-'pool' algorithm from Stage 2, Step 1. Afterwards,
[everything but the outer shell of the 3×3×3 will be solved](https://cubular.t6.fyi/#stage3-step1-done) and we
can proceed to the novel parts of this step.
The partition for this step is as follows:
* ['active'](https://cubular.t6.fyi/#stage3-step1-active): all pieces in the center cross other than the center
piece that we just solved.
* ['done'](https://cubular.t6.fyi/#stage3-step1-done): all pieces outside of the center 3×3×3, along with the
center piece.
* ['pool'](https://cubular.t6.fyi/#stage3-step1-pool): all of the corners and edges.
Here's a diagram of the positions like in the previous stage.
```
X · + · # · + · +
· A · # # # · # ·
+ · + · # · + · +
```
Moving pieces between 'pool' positions is rather simple. We can use thin moves
to rotate the corners and edges of a face of the 3×3×3 without affecting the
center cross. Here's an example of [moving one of the
corners](https://cubular.t6.fyi/#stage3-step1-pool-example).
To move pieces from a 'pool' position to an 'active' position, we use [a
planar variation of `INTO_CENTER` that uses thin
moves](https://cubular.t6.fyi/#stage3-step1-pool-to-active) (`THINTO_CENTER`).
### Similarity to a Rubik's Cube
At this point, [all positions except the corners and edges of the 3×3×3 are
solved](https://cubular.t6.fyi/#after-stage3-step1).
The center 3×3×3 is now rather similar to a Rubik's Cube:
* The center cross is solved, and the unsolved pieces are either edges or
corners; in a Rubik's Cube, the center cross is fixed and is therefore always
solved.
* Because corners and edges are of different parities, corners cannot swap with
edges. Likewise, in a Rubik's Cube, corners cannot swap with edges.
* We can either use thin moves to rotate 1×3×3 slices, or regular moves to
rotate the whole 3×3×3. These are the same moves you can make in a Rubik's
Cube.
In fact, the rest of the puzzle is simpler than a Rubik's Cube:
* In a Rubik's Cube, every piece in unique, but in this, some of the pieces are
interchangable.
* In a Rubik's Cube, corners can be in one of three orientations, and edges can
be in one of two; in this, pieces don't have orientations.
To solve the rest of the cube, we'll use thin moves to solve it like a Rubik's
Cube, using the Old Pochmann ([1](https://www.speedsolving.com/wiki/index.php/Classic_Pochmann), [2](https://ruwix.com/the-rubiks-cube/how-to-solve-the-rubiks-cube-blindfolded-tutorial/)) method.
### Stage 3, Step 2
In this step, the remainder of the cube will be divided as follows, where `A`
and `B` represent 'active' positions, and `C` represents the singular 'pool'
position.
```
· A · A · A · A ·
B · C · · · A · A
· A · A · A · A ·
```
First, we'll solve all `A` positions. Then, we'll solve the `B` position.
Nothing needs to be done to solve the `C` position, as all other pieces of the
same parity will have been solved.
We'll focus on this `A` position; other `A` positions are solved similarly:
```
· # · # # # · # ·
# # + # # # # # #
· A · # # # · # ·
```
Since the `C` position is the only 'pool' position, our source position will
always be `C`.
To solve this `A` position, we'll execute the following procedure:
1. Use thin moves to [rotate the piece in this `A` position to the `B` position](https://cubular.t6.fyi/#stage3-step1-A).
2. Swap the pieces in the `B` and `C` positions.
3. Reverse the moves in #1.
To accomplish #2, we'll use an algortihm known as the
[T Permutation](https://ruwix.com/the-rubiks-cube/how-to-solve-the-rubiks-cube-blindfolded-tutorial/#:%7E:text=T%20Permutation), which swaps the pieces in the `B` and `C`
positions, and swaps the pieces in the `P` and `Q` positions:
```
· · P · · · · · ·
B · C · · · · · ·
· · Q · · · · · ·
```
Thus, the above procedure will swap the pieces in the `B` and `C` positions and
swap the pieces in the `P` and `Q` positions. Note that we must be careful not
to disturb the pieces in the `P` and `Q` positions in #1, as otherwise #2 will
have undesirable effects on the rest of the cube.
As we solve all of the `B` positions, the pieces in the `P` and `Q` positions
keep swapping back and forth, but we don't care, as they are both unsolved.
Finally, to solve the `B` and `C` positions, if they're not already solved, we'll
apply the T Permutation to swap them.
*Note: usually, Old Pochmann will involve two additional algorithms for this
step, the [Ja](https://ruwix.com/the-rubiks-cube/how-to-solve-the-rubiks-cube-blindfolded-tutorial/#:%7E:text=Ja%20Permutation) and [Jb](https://ruwix.com/the-rubiks-cube/how-to-solve-the-rubiks-cube-blindfolded-tutorial/#:%7E:text=Jb%20Permutation) permutations. These are
used to simplify some of the swaps, but are not strictly necessary.*
### Stage 3, Step 3
This step is rather similar to Step 2.
In this step, the remainder of the cube will be divided as follows, where `A`
and `B` represent 'active' positions, and `C` represents the singular 'pool'
position.
```
C · A · · · A · A
· · · · · · · · ·
A · B · · · A · A
```
Like the previous step, we'll first solve all `A` positions, and then solve the
`B` position. As before, nothing needs to be done to solve the `C` position, as
all other pieces of the same parity will have been solved.
We'll focus on this `A` position; other `A` positions are solved similarly:
```
+ # # # # # # # #
# # # # # # # # #
A # # # # # # # #
```
To solve this `A` position, we'll execute the following procedure:
1. Use thin moves to rotate the piece in this `A` position to the `B` position.
2. Swap the pieces in the `B` and `C` positions.
3. Reverse the moves in #1.
To accomplish #2, we'll use an algorithm known as the
[Y Permutation](https://ruwix.com/the-rubiks-cube/how-to-solve-the-rubiks-cube-blindfolded-tutorial/#:%7E:text=T%20Permutation), which swaps the pieces in the`B` and `C`
positions, and swaps the pieces in the `P` and `Q` positions:
```
C P · · · · · · ·
Q · · · · · · · ·
· · B · · · · · ·
```
Thus, the above procedure will swap the pieces in the `B` and `C` positions and
swap the pieces in the `P` and `Q` positions. The `P` and `Q` positions were
previously solved and have the same solved value, so swapping them does nothing.
Finally, to solve the `B` and `C` positions, if they're not already solved, we'll
apply the Y Permutation to swap them.
The puzzle is now [entirely solved](https://cubular.t6.fyi/#solved).
*Note: in the Old Pochmann method, there is usually a step in between solving
the edges and corners: possibly using the [Ra Permutation](https://ruwix.com/the-rubiks-cube/how-to-solve-the-rubiks-cube-blindfolded-tutorial/#:%7E:text=Jb%20Permutation) to
resolve parity. However, because the edges that the Y Permutation swaps are of
equal value, this is unnecessary in our case.*
### Conclusion
We did it!
Thanks for reading the explanation; I hope you enjoyed it! If you haven't
already, I highly suggest checking out [the interactive visualization](https://cubular.t6.fyi/).
If you have any questions, comments, or feedback, please leave a comment or ping
me in chat!
] |
[Question]
[
### Background
I like my old 8-bit 6502 chip. It's even fun to solve some of the challenges here on PPCG in 6502 machine code. But some things that should be simple (like, read in data or output to stdout) are unnecessarily cumbersome to do in machine code. So there's a rough idea in my mind: Invent my own 8-bit virtual machine that's inspired by the 6502, but with the design modified to be more usable for challenges. Starting to implement something, I realized this might be a nice challenge itself if the design of the VM is reduced to a bare minimum :)
### Task
Implement an 8-bit virtual machine conforming to the following specification. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the implementation with the fewest bytes wins.
### Input
Your implementation should take the following inputs:
* A single unsigned byte `pc`, this is the initial program counter (the address in memory where the VM starts execution, `0`-based)
* A list of bytes with a maximum length of `256` entries, this is the RAM for the virtual machine (with its initial contents)
You may take this input in any sensible format.
### Output
A list of bytes which are the final contents of the RAM after the VM terminates (see below). You can assume you only get input that leads to terminating eventually. Any sensible format is allowed.
### Virtual CPU
The virtual CPU has
* an 8-bit program counter,
* an 8-bit accumulator register called `A` and
* an 8-bit index register called `X`.
There are three status flags:
* `Z` - the zero flag is set after some operation results in `0`
* `N` - the negative flag is set after some operation results in a negative number (iow bit 7 of the result is set)
* `C` - the carry flag is set by additions and shifts for the "missing" bit of the result
Upon start, the flags are all cleared, the program counter is set to a given value and the contents of `A` and `X` are indeterminate.
The 8-bit values represent either
* an *unsigned* integer in the range `[0..255]`
* a *signed* integer, 2's complement, in the range `[-128..127]`
depending on context. If an operation over- or underflows, the value *wraps around* (and in case of an addition, the carry flag is affected).
### Termination
The virtual machine terminates when
* A `HLT` instruction is reached
* A non-existing memory address is accessed
* The program counter runs outside the memory (note it doesn't wrap around even if the VM is given the full 256 bytes of memory)
### Adressing modes
* *implicit* -- the instruction has no argument, the operand is implied
* *immediate* -- the operand is the byte directly after the instruction
* *relative* -- (for branching only) the byte after the instruction is signed (2's complement) and determines the offset to add to the program counter if the branch is taken. `0` is the location of the following instruction
* *absolute* -- the byte after the instruction is the address of the operand
* *indexed* -- the byte after the instruction plus `X` (the register) is the address of the operand
### Instructions
Each instruction consists of an opcode (one byte) and, in the addressing modes *immediate*, *relative*, *absolute* and *indexed* a second argument byte. When the virtual CPU executes an instruction, it increments the program counter accordingly (by `1` or `2`).
All opcodes shown here are in hex.
* `LDA` -- load operand into `A`
+ Opcodes: immediate: `00`, absolute: `02`, indexed: `04`
+ Flags: `Z`, `N`
* `STA` -- store `A` into operand
+ Opcodes: immediate: `08`, absolute: `0a`, indexed: `0c`
* `LDX` -- load operand into `X`
+ Opcodes: immediate: `10`, absolute: `12`, indexed: `14`
+ Flags: `Z`, `N`
* `STX` -- store `X` into operand
+ Opcodes: immediate: `18`, absolute: `1a`, indexed: `1c`
* `AND` -- bitwise *and* of `A` and operand into `A`
+ Opcodes: immediate: `30`, absolute: `32`, indexed: `34`
+ Flags: `Z`, `N`
* `ORA` -- bitwise *or* of `A` and operand into `A`
+ Opcodes: immediate: `38`, absolute: `3a`, indexed: `3c`
+ Flags: `Z`, `N`
* `EOR` -- bitwise *xor* (exclusive or) of `A` and operand into `A`
+ Opcodes: immediate: `40`, absolute: `42`, indexed: `44`
+ Flags: `Z`, `N`
* `LSR` -- logical shift right, shift all bits of operand one place to the right, bit 0 goes to carry
+ Opcodes: immediate: `48`, absolute: `4a`, indexed: `4c`
+ Flags: `Z`, `N`, `C`
* `ASL` -- arithmetic shift left, shift all bits of the operand one place to the left, bit 7 goes to carry
+ Opcodes: immediate: `50`, absolute: `52`, indexed: `54`
+ Flags: `Z`, `N`, `C`
* `ROR` -- rotate right, shift all bits of operand one place to the right, carry goes to bit 7, bit 0 goes to carry
+ Opcodes: immediate: `58`, absolute: `5a`, indexed: `5c`
+ Flags: `Z`, `N`, `C`
* `ROL` -- rotate left, shift all bits of the operand one place to the left, carry goes to bit 0, bit 7 goes to carry
+ Opcodes: immediate: `60`, absolute: `62`, indexed: `64`
+ Flags: `Z`, `N`, `C`
* `ADC` -- add with carry, operand plus carry is added to `A`, carry is set on overflow
+ Opcodes: immediate: `68`, absolute: `6a`, indexed: `6c`
+ Flags: `Z`, `N`, `C`
* `INC` -- increment operand by one
+ Opcodes: immediate: `78`, absolute: `7a`, indexed: `7c`
+ Flags: `Z`, `N`
* `DEC` -- decrement operand by one
+ Opcodes: immediate: `80`, absolute: `82`, indexed: `84`
+ Flags: `Z`, `N`
* `CMP` -- compare `A` with operand by subtracting operand from `A`, forget result. Carry is cleared on underflow, set otherwise
+ Opcodes: immediate: `88`, absolute: `8a`, indexed: `8c`
+ Flags: `Z`, `N`, `C`
* `CPX` -- compare `X` -- same as `CMP` for `X`
+ Opcodes: immediate: `90`, absolute: `92`, indexed: `94`
+ Flags: `Z`, `N`, `C`
* `HLT` -- terminate
+ Opcodes: implicit: `c0`
* `INX` -- increment `X` by one
+ Opcodes: implicit: `c8`
+ Flags: `Z`, `N`
* `DEX` -- decrement `X` by one
+ Opcodes: implicit: `c9`
+ Flags: `Z`, `N`
* `SEC` -- set carry flag
+ Opcodes: implicit: `d0`
+ Flags: `C`
* `CLC` -- clear carry flag
+ Opcodes: implicit: `d1`
+ Flags: `C`
* `BRA` -- branch always
+ Opcodes: relative: `f2`
* `BNE` -- branch if `Z` flag cleared
+ Opcodes: relative: `f4`
* `BEQ` -- branch if `Z` flag set
+ Opcodes: relative: `f6`
* `BPL` -- branch if `N` flag cleared
+ Opcodes: relative: `f8`
* `BMI` -- branch if `N` flag set
+ Opcodes: relative: `fa`
* `BCC` -- branch if `C` flag cleared
+ Opcodes: relative: `fc`
* `BCS` -- branch if `C` flag set
+ Opcodes: relative: `fe`
### Opcodes
The behavior of the VM is undefined if any opcode is found that doesn't map to a valid instruction from the above list.
As per [Jonathan Allan's request](https://codegolf.stackexchange.com/questions/171095/8bit-virtual-machine?noredirect=1#comment412971_171095), you **may** choose your own set of opcodes instead of the opcodes shown in the **Instructions** section. If you do so, you **must** add a full mapping to the opcodes used above in your answer.
The mapping should be a hex file with pairs `<official opcode> <your opcode>`, e.g. if you replaced two opcodes:
```
f4 f5
10 11
```
Newlines don't matter here.
### Test cases (official opcodes)
```
// some increments and decrements
pc: 0
ram: 10 10 7a 01 c9 f4 fb
output: 10 20 7a 01 c9 f4 fb
// a 16bit addition
pc: 4
ram: e0 08 2a 02 02 00 6a 02 0a 00 02 01 6a 03 0a 01
output: 0a 0b 2a 02 02 00 6a 02 0a 00 02 01 6a 03 0a 01
// a 16bit multiplication
pc: 4
ram: 5e 01 28 00 10 10 4a 01 5a 00 fc 0d 02 02 d1 6a 21 0a 21 02 03 6a 22 0a 22 52
02 62 03 c9 f8 e6 c0 00 00
output: 00 00 00 00 10 10 4a 01 5a 00 fc 0d 02 02 d1 6a 21 0a 21 02 03 6a 22 0a 22 52
02 62 03 c9 f8 e6 c0 b0 36
```
I might add more testcases later.
### Reference and testing
To help with own experiments, here's some (totally not golfed) [reference implementation](https://github.com/Zirias/gvm/tree/challenge) -- it can output tracing information (including disassembled instructions) to `stderr` and convert opcodes while running.
Recommended way to get the source:
```
git clone https://github.com/zirias/gvm --branch challenge --single-branch --recurse-submodules
```
Or checkout branch `challenge` and do a `git submodule update --init --recursive` after cloning, to get my custom build system.
Build the tool with GNU make (just type `make`, or `gmake` if on your system, the default make isn't GNU make).
**Usage**: `gvm [-s startpc] [-h] [-t] [-c convfile] [-d] [-x] <initial_ram`
* `-s startpc` -- the initial program counter, defaults to `0`
* `-h` -- input is in hex (otherwise binary)
* `-t` -- trace execution to `stderr`
* `-c convfile` -- convert opcodes according to a mapping given in `convfile`
* `-d` -- dump resulting memory as binary data
* `-x` -- dump resulting memory as hex
* `initial_ram` -- the initial RAM contents, either hex or binary
**Note** the conversion feature will fail on programs that modify opcodes while running.
**Disclaimer:** The rules and specs above are authorative for the challenge, not this tool. This especially applies to the opcode conversion feature. If you think the tool presented here has a bug wrt the specs, please report in a comment :)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~1381~~ ~~1338~~ ~~1255~~ 1073 bytes
Huge improvement thanks to ceilingcat and Rogem.
```
#include<stdio.h>
C*F="%02hhx ";m[256],p,a,x,z,n,c,e;g;*I(){R++p+m;}*A(){R*I()+m;}*X(){R*I()+m+x;}C*Q(){W(printf,m[g],1)exit(a);}C*(*L[])()={I,Q,A,Q,X,Q,Q,Q};l(C*i){R 254/p?*i=*L[m[p]&7]():*Q();}s(i){R 254/p?*L[m[p]&7]()=i:*Q();}q(){p>254?Q():++p;}C*y(){p+=e;}B(U,z)B(V,!z)B(_,n)B(BM,!n)B(BC,c)B(BS,!c)C*(*b[])()={Q,Q,y,Q,U,Q,V,Q,_,Q,BM,Q,BC,Q,BS,Q};j(){z=!l(&a);v}o(){s(a);}t(){z=!l(&x);n=x&H;}D(){s(x);}f(K(&=)h(K(|=)i(K(^=)J(E;c=e&1;z=!(e/=2);s(e);w}k(E;c=w;z=!e;s(e*=2);}T(E;g=e&1;z=!(e=e/2|H*!!c);c=g;s(e);w}M(E;g=w z=!(e=e*2|H*!!c);c=g;s(e);}N(E;z=!(a=g=a+e+!!c);c=g>>8%2;G}P(E;z=!~e;--p;s(g=e+1);G}u(E;g=e-1;z=!g;--p;s(g);G}r(E;g=a-e;z=!g;c=G}S(E;g=x-e;z=!g;c=G}Y(){z=!(x=g=1-m[p]%2*2);n=x&H;}Z(){c=~m[p]&1;}d(){p<255||Q();e=m[++p];b[m[p-1]&15]();}(*O[])()={j,o,t,D,Q,Q,f,h,i,J,k,T,M,N,Q,P,u,r,S,Q,Q,Q,Q,Q,Q,Y,Z,Q,Q,Q,d,d};main(){scanf(F,&p);W(scanf,&m[g],0)for(;;q())O[m[p]/8]();}
```
[Try it online!](https://tio.run/##ZVTpUuJAEP7vUwS3TM0knYVEcSnHwRLwXk@8KdaKYRKikEQOiUp89GV7JnhUbYWZPr6vMz3dHTwr8LzZ7EcYeb1xR6wPR50w/tmtLtSNbb64VHK63VRbZP2WU15tQwIupPAKEXggWMCMPULfzkwzMfssMzalIV3Kuv6yzJRldeMUHVckGYTRyId@K2iDTUUajohLJUyM3602JZS/7cEpbOK6xoVPxnqkboT4Ns0prxSTDSPkyO23krb@q03omnwzy4bkO@UbzsM54wkTSKpI2EBzDbOWx75Ip8kFy2rkAl5pjVxCQYo7iHCvHUJByTp4UjSh4FGZ7P08WZniC64LXJe47nBhEG51uTVl/g94xisv9IiOV33OYjSH6tajTyClLOKpvsuyhkLRznxyQHROuyimnIYo/nC6T7aYx4VuMwwkosgdyoZEUDbJHhU0kYCQPkNi2Tl6g68ALorOdNco4DWQHHzEHirWRJtzjP852RFSJOzygLumMD/garWy5LCd7CTH3wWzrARj8FDTpgiM8wwslUHwgUpkoBDXEjni8Z2sqVzpd9dNXiWS4sG2Jfu65BjOZ8FuEfb4u@q3zbKObOi6Uy5Pp7Lrgvdb2Oo2u5cTYdnIKbflNBDjeN7CB4hhBA01bT50IYR9eIRzOIQj9JzAGAbQzGdx/tzA7VzrQCdjfTeMZNc8N/LJNugJZVdEWaCrQS9RPx4QxnAC6bGazGJFJTGblVY0UdJKFc1xtZKjfiVtNdddqUvFVp5l5bEX/np@zw2GM6tR5@NoGAaR6Ghe1x2gZ5fbTgXlGR@I0XgQofrMI@5ioVCdoCpydQfVIFe3OH3DERQU9RoZwRPldUOO5tN0@qKytBpXJMavHxF5kYBjL00zwCqv6jpBWsEXsU/kn0dEKaMxVgGLgHEHJKZ8PjdarAk5//8A "C (gcc) – Try It Online")
A lot of defines moved to compiler flags.
Explanation (VERY ungolfed):
```
#include<stdio.h>
// useful defines
#define C unsigned char
#define H 128 // highest bit
#define R return
// code generator for I/O
#define W(o,p,q)for(g=-1;++g<256&&((q)||!feof(stdin));)(o)(F,(p));
// code generator for branching instruction handlers
#define BB(q)(){(q)||Y();}
// frequent pieces of code
#define NA n=a&H;
#define NE n=e&H;
#define NG n=g&H;
#define E l(&e)
// printf/scanf template
C * F = "%02hhx ";
// global state: m=memory, pax=registers, znc=flags
// e and g are for temporaries and type conversions
C m[256],p,a,x,z,n,c,e;g;
// get the pointer to a memory location:
C * I() {R &m[++p];} // immediate
C * A() {R &m[m[++p]];} // absolute
C * X() {R &m[m[++p]+x];} // indexed
// terminate the VM (and dump memory contents)
C * Q() { W(printf,m[g],1) exit(a);}
// an array of functions for accessing the memory
// They either return the pointer to memory location
// or terminate the program.
C * (*L[])()={I,Q,A,Q,X,Q,Q,Q};
// load a byte from the memory into the variable pointed by i
// terminate the program if we cannot access the address byte
l (C * i) {return 254 / p ? *i = *L[m[p]&7] () : *Q ();}
// save a byte i to the memory
// terminate the program if we cannot access the address byte
s (C i) {return 254 / p ? *L[m[p]&7]() = i : *Q ();}
// advance the instruction pointer (or fail if we fall outside the memory)
q () {p > 254 ? Q () : ++p;}
// branch
C * Y() {p += e;}
// generated functions for conditional branches
C * BN BB(z)
C * BZ BB(!z)
C * BP BB(n)
C * BM BB(!n)
C * BC BB(c)
C * BS BB(!c)
// a list of branch functions
C * (*B[])() = {Q,Q,Y,Q,BN,Q,BZ,Q,BP,Q,BM,Q,BC,Q,BS,Q};
// Instruction handling functions
OA () {z = !l (&a); NA} // lda
OB () {s (a);} // sta
OC () {z = !l (&x); n = x & H;} // ldx
OD () {s (x);} // stx
OG () {E; z = !(a &= e); NA} // and
OH () {E; z = !(a |= e); NA} // ora
OI () {E; z = !(a ^= e); NA} // eor
OJ () {E; c = e & 1; z = !(e /= 2); s (e); NE} // lsr
OK () {E; c = NE; z = !e; s (e *= 2);} // asl
OL () {E; g = e & 1; z = !(e = e / 2 | H * !!c); c = g; s (e); NE} // ror
OM () {E; g = e & H; z = !(e = e * 2 | H * !!c); c = g; s (e); NE} // rol
ON () {E; z = !(a = g = a + e + !!c); c = !!(g & 256); NG} // adc
OP () {E; z = !~e; --p; s (g = e + 1); NG} // inc
OQ () {E; g = e - 1; z = !g; --p; s (g); NG} // dec
OR () {E; g = a - e; z = !g; c = NG} // cmp
OS () {E; g = x - e; z = !g; c = NG} // cpx
OY () {z = !(x = g = ~m[p] & 1 * 2 - 1); n = x & H;} // inx/dex
OZ () {c = ~m[p] & 1;} // sec/clc
Od () {p < 255 || Q (); e = m[++p]; B[m[p-1]&15] ();} // branching
// list of opcode handlers
(*O[]) () = {OA,OB,OC,OD,Q,Q,OG,OH,OI,OJ,OK,OL,OM,ON,Q,OP,OQ,OR,OS,Q,Q,Q,Q,Q,Q,OY,OZ,Q,Q,Q,Od,Od};
// main function
main ()
{
// read the instruction pointer
scanf (F, &p);
// read memory contents
W(scanf, &m[g], 0)
// repeatedly invoke instruction handlers until we eventually terminate
for (;; q())
O[m[p]/8] ();
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~487~~, ~~480~~, ~~463~~, ~~452~~, ~~447~~, 438 bytes
Uses [this instruction mapping](https://pastebin.com/SJSxhh8q). The update to the instructions shaved off 9 bytes, and potentially more in the future. Returns by modifying the memory pointed to by the first argument (`M`). Thanks to @ceilingcat for shaving off some bytes.
Must be compiled with flags `-DO=*o -DD=*d -DI(e,a,b)=if(e){a;}else{b;} -Du="unsigned char"` (already included in bytes).
```
e(M,Z,C)u*M,C;{for(u r[2],S=0,D,O,c,t;o=C<Z?M+C++:0;){I(c=O,d=r+!(c&4),break)I(o=c&3?C<Z&&C?M+C++:0:d,o=c&2?O+c%2**r+M:o,break)t=(c/=8)&7;I(c<24&c>4&&t,t&=3;I(c&8,I(c&4,c&=S&1;S=O>>7*!(t/=2);O=t=O<<!t>>t|c<<7*t,t=O+=t%2*2-1),I(c&4,D=t=t?t&2?t&1?O^D:O|D:O&D:O,I(c&1,S=D>(t=D+=O+S%2),t=D-O;S=t>D)))S=S&1|t>>6&2|4*!t,I(c&8,C+=!(t&~-t?~t&S:t&~S)*O,I(t,S=S&6|c%2,O=D)))I(C,,Z=0)}}
```
[Try it online!](https://tio.run/##nVVhb@I4EP1sfoVL1WAT0zqGAgIMYpNqDwmaHqmqqtteRZPQja4NFRhdtYX96cfZSSAE6N7pPiRkZt7MvLGfsVt6dt3VykcDckdMPC8OiNn8GE@maA6n39gDcTglFrGJS0Rzws3WXWegm7reoE380UMut4nHp/oRcrUKJk9Tf/Qn7qEJd7VyR4I1zVzjGx5RbtaxdfeEFYtTfdCYJBmCI/eM17FWa8qaLVbR3HZF0wQRGi8rl1Yn6l0hrsYdzWg63G63a8UjJM44w02bC263Wkei3RYLt9WqFWUqt3UuZCdWMnCSbUmc6AhJQmhGx/7DatgL@WjyiRCGHNdqI8EtXWY7JwzLMlbJlv1E28IYO6r7QrapamxRKR4JEpMzdS65aD9LovNTaE5Dfjq4qIoKonKqCzkzsbmq0UMmIXec4uXy7KxkWbzowZJl8@JE/vSQT0bkCfNgjHz8MWou/ZeZ//HUXMrgnOfn4Sx4Dn0Put9H0/wqlzsOQvdl7vmwNRPeaPp8@r2dy72OghDhjxw49vxxEPqwC2lq3MJKavQGA3SDATAIvNnCf3EiL8t4e9Zt5C1nvPaVHGhATk9PMQQImbjVKmO4gAMCj48fH2@6j93hV@fxMQfSnL6FhuQmSoGUVaiED@WzVdW53iAAZfQAonuZFgGSBGXnJMbgLXLDtFEMqu6DblNUjKntY8zB1U43tg/qWma2UDnFpKgvQ2ReyjOVFCrThbIxgXYG1nX6SGEikFGJw5sFdIYymMSq2djQ7qex893YVl4tG@tdmmmsnI1ZF1sxtkvVubiW@w6AnHgR7X8a@q1/DQCglGZG64Naal38DrYEeXkBttKv@uA8tQY9wLa2xATVLcsBhuqROSFQng7Pd789cHkYAJCyuyVK8fTdoBgT5VNTK7nTd2okLjXsbfwp9@ryIkkZP2E5NViqwMjzjOq6LGNyd@oEVuTCMJI06pKk6rqREsfGyRKnlPkecDvZOJRcPpBspNxe5y8pN/p@7hOoAOrN6tE3JZ@thtLVTmslmR2GSsFmkkq9A7Q340lh0P0J2Lq2PNmMKHuvQvnA4IztpMWLrQ7KTl91BHYKZTf1qp/Q96tJXAo1rq2WJ1oktZ7NXA68zcUM5XuhO/Vf/VDM4Cj0oFRVYjbyWKF8FGuNwFnww5@M4dqkMix1qe7UIBQwgBzSJgxaGZh06LrawbepBI1R/oSy9xM3TxIBBw8RORToBj6pdwqw0Ii/jWqncC8KjcJ9WFCNAFgTvg/vQ6NaegoElGoNRDAJI6oRxEeRgjdkE6vya64R6lOq8Zn4X0wTnlK5Inh7CdxRylZxjRS94ZpY/8I1Qn3KNT4j/5XrcvW3O34ZPc9Wv7qhV/Etvorv9JW6rzN/RqvSX/8A "C (gcc) – Try It Online")
### Preprocessor
```
-DO=*o -DD=*d
```
These two provide a shorter way to dereference the pointers.
```
-DI(e,a,b)=if(e){a;}else{b;} -Du="unsigned char"
```
Reduce the number of bytes needed for if-elses and type declarations.
### Code
The below is a human-readable version of the code, with the preprocessor directives expanded, and variables renamed for readability.
```
exec_8bit(unsigned char *ram, int ramSize, unsigned char PC)
{
for(unsigned char reg[2], SR=0, // The registers.
// reg[0] is X, reg[1] is A.
// SR contains the flags.
*dst, *op, opCode, tmp;
// Load the next instruction as long as we haven't gone out of ram.
op = PC < ramSize ? ram + PC++ : 0;)
{ // Check for HLT.
if(opCode=*op)
{ // Take a pointer to the register selected by complement of bit 3.
dst = reg+!(opCode&4);
} else break;
// Load operand as indicated by bits 0 and 1. Also check that we don't
// go out of bounds and that the PC doesn't overflow.
if(op = opCode&3 ? PC<ramSize && PC ? ram + PC++ : 0 : dst)
{
op = opCode&2 ? *op + opCode%2 * *reg + ram: op
} else break;
// Store the bits 3-5 in tmp.
tmp = (opCode/=8) & 7;
if(opCode<24 & opCode>4 && tmp)
{ // If not HLT, CLC, SEC or ST, enter this block.
tmp &= 3; // We only care about bits 3&4 here.
if(opCode&8) // Determine whether the operation is binary or unary.
{ // Unary
if(opCode&4)
{ // Bitshift
opCode &= SR&1; // Extract carry flag and AND it with bit 3 in opCode.
SR=*op >> 7*!(tmp/=2);// Update carry flag.
// Shift to left if bit 4 unset, to right if set. Inclusive-OR
// the carry/bit 3 onto the correct end.
*op = tmp = *op << !tmp >> tmp | opCode << 7*tmp;
} else tmp=*o+=tmp%2*2-1;
} else if(opCode&4) {
// Bitwise operations and LD.
// Ternary conditional to determine which operation.
*dst = tmp = tmp? tmp&2? tmp&1? *op^*dst: *op|*dst: *op&*dst: *op
} else if(opCode&1) {
// ADC. Abuse precedence to do this in fewer bytes.
// Updates carry flag.
SR = *dst > (tmp = *dst += *op + SR%2);
} else tmp=*dst-*op; SR = tmp > *dst; // Comparison.
SR = SR&1 | tmp >> 6&2 | 4*!tmp; // Update Z and N flags, leaving C as it is.
} else if(opCode&8) {
// Branch.
// tmp&~-tmp returns a truthy value when tmp has more than one bit set
// We use this to detect the "unset" and "always" conditions.
// Then, we bitwise-AND either ~tmp&SR or tmp&~SR to get a falsy value
// when the condition is fulfilled. Finally, we take logical complement,
// and multiply the resulting value (`1` or `0`) with the operand,
// and add the result to program counter to perform the jump.
PC += !(tmp & ~-tmp? ~tmp&SR : tmp&~SR) * *op;
} else if (tmp) { // SEC, CLC
SR = SR&6 | opCode % 2;
} else {
*op = *dst; // ST
}
if(!PC){ // If program counter looped around, null out ramSize to stop.
// There's likely a bug here that will kill the program when it
// branches back to address 0x00
ramSize=0;
}
}
}
```
### Instructions
The instructions are structured as follows:
* Bits 6-7 indicate the arity of the instruction (`00` Nullary, `01` Unary, `10` Binary, `11` Binary)
* Bits 0-2 determine the operand(s): `R=0` selects `A` and `R=1` selects `X`. `OP=00` uses the register as an operand, `OP=01` selects immediate operand, `OP=10` selects absolute operand and `OP=11` selects indexed operand.
+ As you may have noticed, this allows for any operations to be performed on either register (although you can still only index from `X`) even when they normally couldn't be used per specification. E.g. `INC A`, `ADC X, 10` and `ASL X` all work.
* Bits 3-5 determine the condition for branching: having one of the bits indicates which flag to test (bit 3->C, bit 4->N, bit 5->Z). If only one bit is set, the instruction tests for a set flag. To test for an unset flag, take the complement of the bits. For example `110` tests for unset carry and `001` for set carry. `111` and `000` branch always.
* You can also branch to an address offset stored in a register, allowing you to write functions, or you can use the standard indexing modes. `OP=01` behaves like specification branch.
```
+-----+----------+-------+-----------------------------------------------+
| OP | BINARY | FLAGS | INFO |
+-----+----------+-------+-----------------------------------------------+
| ST | 10000ROP | | Register -> Operand |
| LD | 10100ROP | Z N | Operand -> Register |
| AND | 10101ROP | Z N | Register &= Operand |
| XOR | 10111ROP | Z N | Register ^= Operand |
| IOR | 10110ROP | Z N | Register |= Operand |
| ADC | 10011ROP | Z N C | Register += Operand + Carry |
| INC | 01011ROP | Z N | Operand += 1 |
| DEC | 01010ROP | Z N | Operand -= 1 |
| ASL | 01100ROP | Z N C | Operand <<= 1 |
| LSR | 01110ROP | Z N C | Operand >>= 1 |
| ROL | 01101ROP | Z N C | Operand = Operand << 1 | Carry |
| ROR | 01111ROP | Z N C | Operand = Operand >> 1 | Carry << 7 |
| CMP | 10010ROP | Z N C | Update ZNC based on Register - Operand |
| BR | 11CNDROP | | PC += Condition ? Operand : 0 |
| SEC | 00011000 | C | Set carry |
| CLC | 00010000 | C | Clear carry |
| HLT | 00000000 | | Halt execution. |
+-----+----------+-------+-----------------------------------------------+
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~397~~ ~~332~~ 330 bytes
thanks @Adám for -8 bytes
```
f←{q←2⍴a x c←≡B←256⋄{0::m
⍺←(∇q∘←)0∘=,B≤+⍨
30≤u←⌊8÷⍨b←p⊃m:∇p+←129-B|127-1⊃p↓m×⊃b⌽2/(,~,⍪)1,q,c
p+←1
u=25:⍺x⊢←B|x+¯1*b
u=26:∇c⊢←~2|b
p+←≢o←m⊃⍨i←⍎'p⊃m+x'↑⍨1+8|b
⍎u⊃(,⍉'⍺ax⊢←o' '∇m[i]←ax'∘.~'xa'),5 4 2 3 2/'⍺⌽⊃'∘,¨'a⊢←2⊥(⍕⊃u⌽''∧∨≠'')/o a⊤⍨8⍴2' 'c(i⊃m)←u⌽d⊤(⌽d←u⌽2B)⊥u⌽o,c×u>10' 'c a⊢←2B⊤a+o+c' 'm[i]←B|o-¯1*u' 'c⊢←⊃2B⊤o-⍨⊃u⌽x a'}p m←⍵}
```
[Try it online!](https://tio.run/##tVJNb9NAEL37V8yJtbFDdzeJm0YqB5/4D6WHtdOQiEROPyKCmvQCKkmoKxCq2iNUrai4cICAhMSl/Sf7R8KbdXrixAHJWs@@eW/e7OyaQa/Seml6@bNK1jP7@91saU/Purk9fieXbayHu1i0Lb4bGlGG2M4@JQzVY/v29aFsNvueLX4B8e30za6dXiAMJP6bUWJnV6EtbryqRDRk8cm8cfcTUIrNwM5f9ZtQDULslN6oJGOl1ysK@MAef@jfnSNK7clvveZHR5EtvgQq2o0yrxR4w01db8J8ZOeXAJLxKLz9qh6mnIi5cFYmjvQ4LTV2dslH66MumugyUpwK10g4Evb4PVAVNkAHPgTsw3Um4GFWJrkggcr9re42dgai6cWjIzEyIojqVCNNVdJrrEDfKMD56PZGmFKu7fzat8UZMkMQBNKf7fTGzj4KEazlBNoVemhg4BpOmd/l3gIomd5C1nf/cq@TAPU4yqPs7nz4WEkW0b1ZAr4J8zADuuo4GecVHtKQiSUNDo6ZV@C8amxERkwG1HcTWkyWyw7ffUNt2JMfeCCtCIshvAB6wo9E4boiVORpdbItFZOK3UkW2xPH6jgWsGsUKr6BhmGLpy9CgUL74oHgVmDkHTAREZ7ZHsI2BtkU@XOBIrh/0TbdnhtusdjDHBebe8HE86XfEUoSvnVDUlG2Qe0atVMRBAfkUvqvlOfXoNqRJBukkdLukxSXseGYA@WQqkPUqiDH6T@oSq/6DuO6wZyy25prqe5U7Yxka1Ww5eRasZxXzaUYcRZY644WO5xP1KCdmDLp3OV9k6vtf7RLJVVj8Qc "APL (Dyalog Classic) – Try It Online")
```
p program counter
m memory
a accumulator register
x index register
q flags z (zero) and n (negative) as a length-2 vector
c flag for carry
⍺ function to update z and n
b current instruction
u highest 5 bits of b
o operand
i target address in memory
```
[Answer]
# JavaScript (ES6), 361 bytes
Takes input as `(memory)(program_counter)`, where `memory` is an [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array). [Outputs by modifying](https://codegolf.meta.stackexchange.com/a/4942/58563) this array.
```
M=>p=>{for(_='M[\u0011\u0011A]\u0010\u0010=\u000fc=\u000e,\u0011p]\f(n=\u000b128)\t=\u0010\b&=255\u0007,z=!(n\u0007),n&=\t;\u0006\u0006\u000b\u0005-\u0010,\u000en>=0\u0005\u0004\u0011c\b>>7,A]*2\u0005\u0003\u0011c\b&1,A]/2\u0005\u000f\u0002&&(p+=(\u0010^\t-\t;\u0001for(a=n=z=\u000ex=0;a\u0007,x\u0007,A=[i=\u0011p++],p\f\f+x][i&3],i&3&&p++,i&&A<256;)eval(`\u000ba\b\u0006\u000fa;\u000bx\b\u0006\u000fx;\u000ba&\b\u0005a|\b\u0005a^\b\u0005\u000f\u0002\u0003\u000fc*128|\u0002c|\u0003a+\b+c,\u000ea>>8\u0005++\u0010\u0005--\u0010\u0005a\u0004x\u0004++x\u0005--x\u0006\u000e1;\u000e0;1\u0001!z\u0001z\u0001!n\u0001n\u0001!c\u0001c\u0001`.split`;`[i>>2])';G=/[\u0001-\u0011]/.exec(_);)with(_.split(G))_=join(shift());eval(_)}
```
*NB: The code is compressed with [RegPack](https://siorki.github.io/regPack.html) and contains a lot of unprintable characters, which are all escaped in the above representation of the source.*
[Try it online!](https://tio.run/##nVOPb9o4FFbW0tJSUfgPXF2V2E0ItvkxtsyRUph2k1g3tVSaxGU0DWHNBCGCqMt13d/eswPJkttOkw4pjrG/977vfe/li3PvrN2VH0aNYDn1nu4XgD29Y2bIzG@z5QpOmPJuXK9bdq3Gjl1W1eqhfQQDViG0hw5YrSwz2unsaw/sBAb7SAtkdmDs7VVKjZpWDUyGS7t1t2yazzXLPqOlHf5HJnzfpKXjZ7IMQ5XB2qeDxoEhCTqHBeyBVWOGDWdfi/c1i419Vg9V1dbCoyM1tse@3LI1vsgyP@Ub2XpFO10DeffOHN5UnPLesWNUYv6KjYojl0vOI38@lTnfzrF7xnU/PnMfdxy1rLpa1THNXklVa6VGo1ZyduNdVY35Pt6rEqOKDSKdPEgP0kkgBdKJK7nSjb4O5350Y9yMfdOkNlKMN6w5lhp1u6l7sefCCTLQVz@6g5MNFL5BaMK@LP0Aru/8WQQRMhKtE/T96c6LHcBAAJgJoIIVoIJAj5ZX0coPPkPSRUhfz33Xgw2KDg8jbx1xNFxoIEQi5NshAAsR730F134Q9azVyvkbLhA/d5fBejn39PnyM1TeXny4Hr1U/n0@1nV9YesLJ4SJBCEHBpw0kasABYmI@wXPCMOfkr6/Hv3PrLxM5a@AB37fFAXHPEXzDGAMGmA4@Aj@OCUYnDUBjvELja8Ea1sE5Yi3F31wignYIFpUIDBJEW2OGLz@CJJfgmi307sOvzu/eA1OZ7fbu05HRM9uD23@Rr@QAwfWyEJpKg8nZD2xUifZ0zzxcGBxaXiLxhtpmfguR1iDPi@P15EgqFfM0eOIq1EhR7eYw8lYSJElM8D9wdIqsLRShJexkCILETa0f29Dx9tSiuS9osD2b3sobBheXeboiVcsQdhw@f4yZwP9hQ3nfTEH0y2im3QST/M2bIyiRaNo3ob@sJ@fFDe9m21NPKWpxo2JNNVISGoiLZr4A9HKFLSKCtJGkE7GQossqUbyPGOhRZYM8ULkuBrm6qTFOslt4uYwp2M7upmO6X9/M0S4dP6BR3vdtPtTEe11twgq5uPP4SgXnfWJkp9mB28@IbwZtad/AA "JavaScript (Node.js) – Try It Online")
## Opcode mapping and test cases
The virtual machine uses [this opcode mapping](https://pastebin.com/2kG0DxRu).
Below are the translated test cases, along with the expected outputs.
### Test case #1
```
00 - LDX #$10 09 10
02 - INC $01 32 01
04 - DEX 44
05 - BNE $fb 55 fb
```
Expected output:
$$\text{09 }\color{red}{\text{20}}\text{ 32 01 44 55 fb}$$
### Test case #2
```
00 - (DATA) e0 08 2a 02
04 - LDA $00 02 00
06 - ADC $02 2e 02
08 - STA $00 06 00
0a - LDA $01 02 01
0c - ADC $03 2e 03
0e - STA $01 06 01
```
Expected output:
$$\color{red}{\text{0a 0b}}\text{ 2a 02 02 00 2e 02 06 00 02 01 2e 03 06 01}$$
### Test case #3
```
00 - (DATA) 5e 01 28 00
04 - LDX #$10 09 10
06 - LSR $01 1e 01
08 - ROR $00 26 00
0a - BCC $0d 65 0d
0c - LDA $02 02 02
0e - CLC 4c
0f - ADC $21 2e 21
11 - STA $21 06 21
13 - LDA $03 02 03
15 - ADC $22 2e 22
17 - STA $22 06 22
19 - ASL $02 22 02
1b - ROL $03 2a 03
1d - DEX 44
1e - BPL $e6 5d e6
20 - HLT 00
21 - (DATA) 00 00
```
Expected output:
$$\color{red}{\text{00 00 00 00}}\text{ 09 10 1e 01 }\dots\text{ 44 5d e6 00 }\color{red}{\text{b0 36}}$$
## Unpacked and formatted
Because the code is compressed with an algorithm that replaces frequently repeated strings with a single character, it is more efficient to use the same code blocks over and over than defining and invoking helper functions, or storing intermediate results (such as `M[A]`) in additional variables.
```
M => p => {
for(
a = n = z = c = x = 0;
a &= 255, x &= 255,
A = [i = M[p++], p, M[p], M[p] + x][i & 3],
i & 3 && p++,
i && A < 256;
) eval((
'(n = a = M[A], z = !(n &= 255), n &= 128);' + // LDA
'M[A] = a;' + // STA
'(n = x = M[A], z = !(n &= 255), n &= 128);' + // LDX
'M[A] = x;' + // STX
'(n = a &= M[A], z = !(n &= 255), n &= 128);' + // AND
'(n = a |= M[A], z = !(n &= 255), n &= 128);' + // ORA
'(n = a ^= M[A], z = !(n &= 255), n &= 128);' + // EOR
'(n = M[A] = M[c = M[A] & 1, A] / 2, z = !(n &= 255), n &= 128);' + // LSR
'(n = M[A] = M[c = M[A] >> 7, A] * 2, z = !(n &= 255), n &= 128);' + // ASL
'(n = M[A] = c * 128 | M[c = M[A] & 1, A] / 2, z = !(n &= 255), n &= 128);' + // ROR
'(n = M[A] = c | M[c = M[A] >> 7, A] * 2, z = !(n &= 255), n &= 128);' + // ROL
'(n = a += M[A] + c, c = a >> 8, z = !(n &= 255), n &= 128);' + // ADC
'(n = ++M[A], z = !(n &= 255), n &= 128);' + // INC
'(n = --M[A], z = !(n &= 255), n &= 128);' + // DEC
'(n = a - M[A], c = n >= 0, z = !(n &= 255), n &= 128);' + // CMP
'(n = x - M[A], c = n >= 0, z = !(n &= 255), n &= 128);' + // CPX
'(n = ++x, z = !(n &= 255), n &= 128);' + // INX
'(n = --x, z = !(n &= 255), n &= 128);' + // DEX
'c = 1;' + // SEC
'c = 0;' + // CLC
' 1 && (p += (M[A] ^ 128) - 128);' + // BRA
'!z && (p += (M[A] ^ 128) - 128);' + // BNE
' z && (p += (M[A] ^ 128) - 128);' + // BEQ
'!n && (p += (M[A] ^ 128) - 128);' + // BPL
' n && (p += (M[A] ^ 128) - 128);' + // BMI
'!c && (p += (M[A] ^ 128) - 128);' + // BCC
' c && (p += (M[A] ^ 128) - 128);') // BCS
.split`;`[i >> 2]
)
}
```
[Answer]
# PHP, ~~581 585 555~~ 532 bytes (not -yet- competing)
```
function t($v){global$f,$c;$f=8*$c|4&$v>>5|2*!$v;}$m=array_slice($argv,2);for($f=0;$p>-1&&$p<$argc-1&&$i=$m[$p=&$argv[1]];$p++)$i&3?eval(explode(_,'$a=$y_$a&=$y_$a|=$y_$a^=$y_$a+=$y+$c;$c=$a>>8_$x=$y_$c=$y&1;$y>>=1_$c=($y*=2)>>8_$y+=$y+$c;$c=$y>>8_$y+=$c<<8;$c=$y&1;$y>>=1_$y--_$y++_$z=$a-$y,$c=$a<$y_$z=$x-$y,$c=$x<$y_$y=$a_$y=$x_'.$y=&$m[[0,++$p,$g=$m[$p],$g+$x][$i&3]])[$i>>=2].'$i<14&&t(${[aaaaaxyyyyyyzz][$i]}&=255);'):($i&32?$p+=($f>>$i/8-4^$i)&1?($y=$m[++$p])-($y>>7<<8):1:($i&8?$f=$f&7|8*$c=$i/4:t($x+=$i/2-9)));print_r($m);
```
takes PC and and OP codes as base 10 integers from command line arguments,
prints memory as a list of `[base 10 address] => base 10 value`.
This is **not tested thoroughly yet**; but there is a [breakdown](http://sandbox.onlinephpfunctions.com/code/88473caca74d9d6b7519c8d3f3f768c69b9f4f7c).
There´s [the code map](https://pastebin.com/raw/z2A8QzeB)
and here´s an overview for my mapping:
```
3-mode instructions:
00: LDA 04: AND 08: ORA 0C: EOR
10: ADC 14: LDX 18: LSR 1C: ASL
20: ROL 24: ROR 28: DEC 2C: INC
30: CMP 34: CPX 38: STA 3C: STX
+1: immediate
+2: absolute
+3: relative
implicit:
00: HLT
10: DEX 14: INX
18: CLC 1C: SEC
relative:
20: BRA (0)
28: BNE 2C: BEQ (Z)
30: BPL 34: BMI (N)
38: BCC 3C: BCS (C)
```
side note:
code `24` results in a `BNV` (branch never = 2 byte `NOP`);
`04`, `08`, `0C` are aliases for `INX`, `CLC` and `SEC`
and anything above `3F` is either a two byte `NOP` or an alias for the single mode instructions.
] |
[Question]
[
You are a medieval overlord tasked with designing a road network between three kingdoms placed on a \$9 \times 9\$ grid. A sample placement of kingdoms might look like this:
[![](https://i.stack.imgur.com/3gdSB.png)](https://i.stack.imgur.com/3gdSB.png)
Non-commercial use of tileset by [douteigami](https://douteigami.itch.io/16x16-tiles). Thanks!
The kingdoms make the following three demands:
1. The *road network must be connected*: for any tile on the road network, you must be able to reach any other tile on the road network by just moving horizontally or vertically only along road tiles.
2. The *kingdoms must be connected*: Every kingdom has at least one road tile immediately adjacent horizontally or vertically.
3. The *road network must be thin*: No block of \$2\times2\$ squares can all be road tiles.
Both of the following road networks satisfy all three criteria:
[![](https://i.stack.imgur.com/jz7Yw.png)](https://i.stack.imgur.com/jz7Yw.png) [![](https://i.stack.imgur.com/ZsxuV.png)](https://i.stack.imgur.com/ZsxuV.png)
The following setups fail to satisfy one of the three criteria:
[![Roads not connected](https://i.stack.imgur.com/DmQmI.png)](https://i.stack.imgur.com/DmQmI.png) [![Kingdoms not connected](https://i.stack.imgur.com/HTZ9x.png)](https://i.stack.imgur.com/HTZ9x.png) [![2x2 block of road](https://i.stack.imgur.com/VEgW8.png)](https://i.stack.imgur.com/VEgW8.png)
## Challenge
Take input of a \$9\times9\$ grid with three kingdoms in any format. This may be a multiline string with spaces and characters, a list of single-line strings, a list of zeros and ones, a matrix, or any other reasonable format for your language.
As output, add a road network to the input (indicated in any suitable way) that satisfies the above three criteria. Note that:
* The kingdoms will never be horizontally or vertically adjacent.
* There is no requirement that your road network be minimal in any sense, just that it follows the three rules.
* You may not place roads on top of kingdoms.
* A \$2\times2\$ block where three tiles are road and a single tile is a kingdom is OK; the third restriction only concerns four road tiles.
## Test Cases
The test cases use `.` for an empty space, `k` for a kingdom and `#` for a road, but you may take inputs in other formats/use any three distinct characters or integers as described in the previous section.
```
Input -> Possible output
......... .........
....k.... ....k....
......... ....#....
......... ....#....
.k....... -> .k####...
......... .....#...
.....k... .....k...
......... .........
......... .........
k.k...... k#k......
......... .#.......
k........ k#.......
......... .........
......... -> .........
......... .........
......... .........
......... .........
......... .........
.k....... .k.......
k........ k#.......
.k....... .k.......
......... .........
......... -> .........
......... .........
......... .........
......... .........
......... .........
......... .........
......... .........
k........ k#.......
......... .#.......
k........ -> k#.......
......... .#.......
k........ k#.......
......... .........
......... .........
........k ...#####k
....k.... ...#k....
......... ...#.....
......... ...#.....
......... -> ...#.....
......... ####.....
......... ...#.....
....k.... ...#k....
......... ...#.....
......... .........
......... .........
......... .........
......... .........
......... -> .........
......... .........
k........ k........
.k....... #k.......
..k...... ##k......
```
Here's the inputs as a list of list of lists, should you prefer that:
```
[[[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, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], [[1, 0, 1, 0, 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, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], [[0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 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], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 1], [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, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0]]]
```
## Scoring
Shortest code in bytes wins.
[Answer]
# JavaScript (ES7), ~~166 153 149~~ 137 bytes
Slower and even less subtle than my first answer, but also shorter. This simply looks for a path touching all kingdoms without generating any \$2\times 2\$ road blocks.
Takes input as a flat list of 81 entries, with \$0\$ for an empty cell and \$2\$ for a kingdom. Returns another list with \$0\$ for an empty cell, \$1\$ for a road and \$3\$ for a kingdom.
```
f=(a,X)=>+(z=/.*1,1.{15}1,1|2/.exec(a))?a.some((v,x)=>(a[x]++,(d=(x-X)**2)-1|x/9^X/9&&d-81?0:v?1/X&&v==2?f(a,X):0:f(a,x))||!a[x]--)&&a:!z
```
[Try it online!](https://tio.run/##pVDdboIwGL33KeoNbfn5EJMlE1O52l7AGxJ1SQPFYbE4YIYpPrsDI9MsLGrWi34np@ec76QrvuV5kMWbwlJpKI7HiBFu@pRNDLJjNuiO6cDeeTrUsxraIEoREE6pxyFP14KQrVnWYsJn5cIwTBIyUlo@1fUhtZyqtEdvvj3StNB6dryBu/Uc29e0LWNDLzrtcQduA0pKq6rfhFgW1TTu9nfHTHx8xpkgOMoxhUzw8DVOxPRLBWRAoUinRRarJaGQb5K4IHiu5qoWRmn2woN3kiM2QfseQhwxNAOA/CKsZas0VgRjuoA135CgEQ@RjhrEEJaY0vHZW/c74SBVeZoISNIl4SeXalwYDJB4phaXzPqxqBvYsB8d7GXLN2uRgU5z3DvQI7Sn11zyB8FvJDu41tLp6MnWc0VK@CPmIXTVRt5u@GB0Byn/wXVEy1t/fRPJe1rfi7q/8Ay/AQ "JavaScript (Node.js) – Try It Online")
### How?
We use the regular expression `/.*1,1.{15}1,1|2/` to detect either a \$2\times 2\$ block of roads or a remaining kingdom. We get `null` if nothing is matched, a string that is coerced to *NaN* by the unary `+` if a block is matched, or a string that is coerced to \$2\$ if a kingdom is matched.
Because the left and right boundaries are ignored, the condition on the road block is a little more restrictive than it really should, as it will also match something like that:
```
.........
........X
X.......X
X........
.........
```
However, we have plenty of room to find a path that will work even without including that kind of pattern.
---
# JavaScript (ES7), ~~243 236~~ 226 bytes
*I'm not very happy with this method, as it heavily relies on a brute-force search. There must exist more elegant and more straightforwards ways of solving this. But it does work!*
Expects a matrix with \$0\$ for an empty cell and \$3\$ for a kingdom. Returns another matrix with \$0\$ for an empty cell, \$2\$ for a kingdom and \$4\$ for a road.
```
f=(m,k)=>(M=m.map((r,y)=>r.map((v,x)=>x^k%8&&x^k%8+2+k/8%8&&y^(q=k/64&7)&&y^q+2+k/512?v:v?3:(X=x,Y=y,1))),g=(X,Y)=>M.map((r,y)=>r.map((v,x)=>(x-X)**2+(y-Y)**2-1?0:v-1?v-3?0:r[x]=2:g(x,y,r[x]=4))))(X,Y)|/1|3/.test(M)?f(m,-~k):M
```
[Try it online!](https://tio.run/##pZDBT8IwFMbv/BW9SF9ZV2CgkpHCSW@cvEAQk2UOHGUddHPZAvqvYztBiJlB4w7t73t97@u3Lr3MS3wVrlNbxs/Bfj/nEFFB@ABGPGKRtwZQtNBafYqM5lrkT@KqV6@Xm@VYotkzsniCDRfNm279lhi1KY@u284wc7Nhx4Uxz@mEF7RNCKELDmM60WajH6@B3B6TRsOxoLAnBuz2sOVmes3sjiY1zWfccReQ04KWoqudSem7a7Z3nSZLgySFERnO9W/Z74K4o70KNq@hCgDPE0yYCrzn@3AVPBTShxZhafyQqlAugLBkvQpTwI/yUerGeazuPP8FEsQHaFtDKEIcJacm3WKiK3M8ZYypWal9ozuogQxxhAXWCfuHcZ2qZD@WSbwK2CpeQHSy@XwMaRC2LRdhhilyXGNCUVfvFn4jUzkjbBmHErC2PpCJgyxU7v3aG9mz41czi/gi9p1ERe04UjlRE8eZs6JgP9j8ic7SiMsJ/2hdURT/qFVYi0tvfZHEb1L/lqqf8IAf "JavaScript (Node.js) – Try It Online")
### How?
All puzzles can be solved1 by putting at most 2 horizontal roads and at most 2 vertical roads across the entire grid, either next to or 'over' the kingdoms.
1: this was empirically verified
*Example:*
[![example](https://i.stack.imgur.com/ktDf8.png)](https://i.stack.imgur.com/ktDf8.png)
Given \$k\ge 0\$, we compute:
$$x\_0=k\bmod 8$$
$$x\_1=x\_0+2+(\lfloor k/8\rfloor \bmod 8)$$
$$y\_0=\lfloor k/64\rfloor \bmod 8$$
$$y\_1=y\_0+2+\lfloor k/512\rfloor$$
We put vertical roads at \$x\_0\$ and \$x\_1\$ and horizontal roads at \$y\_0\$ and \$y\_1\$. If any value is greater than \$8\$, it's simply ignored.
Because \$x\_1\ge x\_0+2\$ and \$y\_1\ge y\_0+2\$, we will never end up we a \$2\times 2\$ block of roads.
Starting from a road cell, we flood-fill the grid to make sure that the two other criteria are fulfilled.
[Answer]
# [Perl 5](https://www.perl.org/), ~~251~~ ~~317~~ ~~298~~ 258 bytes
```
sub f{eval'forP(0..80){forT(0,1){my@r;forK(@_){X=intP/9;Y=P%9;I=intK/9;J=K%9;push@r,X*9+Y andT&&Y-J?Y-=Y<=>J:X-I?X-=X<=>I:Y-J?Y-=Y<=>J:0 whileX.Y neI.J}D="."x81;substrD,$_,1,1for@_;substrD,$_,1,0for@r;3==D=~y/1/1/&&D!~/00.{7}00/&&returnD}}'=~s/[A-Z]/\$$&/gr}
```
[Try it online!](https://tio.run/##bVJNk5pAFLz7K14M4SMZmMF1AZdMllRxUS8e9gBhKcqU6JJVpAZM1qLgr5uBManCBA49/fr1o5l6Rcr295dLefoO2zr9ud4r2yNbqcQwHKLV/PykEmRq9eHsMZfTpeolWh3QLK9WeOaGdPVh5s47uuR0QZecFqfyxWMo@Dj7FMI63zzJcqgvHkOdhp/pl8VDoM8fA50GnMwfBgqBXy/ZPg2MEPJ0biwan46N8ZtjujxgWTEfSQkykcmDeMmwRroac@8o9Wl7xiZ/Zdl/12JCjNpuCOGUpdWJ5X7TKLQtcfRV/xbjZ0mS8Y41F69Ky4qqEEUmmsYIoikyO7DQfRyjEVyfKCKIdHWCJh1MOLuRe5spuiacDeSJqE8FWP@6HeHuI9gcBrIlbLb4hsMjDGQHWaJuC3Buh1siuS3A@e@P/U1ObpP30e4ETK9uzR3xm1f729Pqvv1wBu81y3eb4wEoHNYFSFISkZjvQ3foontS4va9m6ws9uuzClv1j0frZjajbiWvKtRQML5i8OOY5aqioH6oIKAg3pNVGGvG@DkfIyiOBW2xUc8avNOAtsC3geDX95ghUHTlzbQRdJ3QXH4D "Perl 5 – Try It Online")
Somewhat ungolfed:
```
sub f {
for$p(0..80){ #loop through all possible starting points p,
#... the crossroads in the 9x9 board
#... from which each road to each kingdom starts
for$t(0,1){ #for each starting point, try two strategies
#...of movement: vertical first or horizontal first
my @r; #init list of road tiles to empty
for(@_){ #loop through all the three kingdoms from input
$x=int$p/9; $y=$p%9; #x,y = start roads at current starting point p
$X=int$_/9; $Y=$_%9; #X,Y = current kingdom
push @r, $x*9+$y #register road tile while x,y not yet reached X,Y
and # move x,y towards X,Y
$t && $y-$Y ? $y-=$y<=>$Y :
$x-$X ? $x-=$x<=>$X :
$y-$Y ? $y-=$y<=>$Y :0 # move horizontally or vertically first
# ...depending on current strategy t=0 or 1
while $x.$y ne $X.$Y # continue towards current kingdom unless there
}
$d='.'x81; # init current board string of 81 dots
substr $d,$_,1,1 for @_; # put 1's at kingdoms
substr $d,$_,1,0 for @r; # put 0's at road tiles
3==$d=~s/1/1/g # if board has 3 kingdoms (none overrun by road)
&& $d!~/00.{7}00/ # and current board has no 2x2 road tiles
&& return $d # then the board is valid and is returned
# otherwise try the next of the 81 starting points
}
}
}
```
Can run like this:
```
@test=( [[1,4], [4,1], [6,5]],
[[0,0], [0,2], [2,0]],
[[0,1], [1,0], [2,1]],
[[2,0], [4,0], [6,0]],
[[0,8], [1,4], [7,4]],
[[6,0], [7,1], [8,2]] );
for(@test){
my @kingdom = map $$\_[0]\*9+$$_[1], @$_;
print display( f(@kingdom) );
}
sub display{join('',map join(' ',split//)."\n",pop=~y/10/k#/r=~/.{9}/g).('-'x17)."\n"}
```
First lines of output: (see '*Try it online*' link above for more)
```
# . . . . . . . .
# # # # k . . . .
# . . . . . . . .
# . . . . . . . .
# k . . . . . . .
# . . . . . . . .
# # # # # k . . .
. . . . . . . . .
. . . . . . . . .
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 97 93 bytes
This actually is fast – brute force in Brachylog! You can't believe how surprised I was when I kept upping the board size. However, this assumes that a road doesn't need to fork. If anyone finds a counterexample – be warned, the other version will not run in time on TIO! :-)
Takes castles as 2, and returns roads as 1.
```
∧ċ{Ċℕᵐ≤ᵛ⁹}ᵐ{s₂{;.\-ᵐȧᵐ+1∧}ᵈ}ᵇP{,1↻₁}ᵐX&{iiʰgᵗc}ᶠT{ṗʰb}ˢ{,.≠&↰₃ᵐ∈ᵛ}P∧T,X≜bᵍtᵐhᵐḍ₉.¬{s₂\s₂c=₁}∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HH8iPd1Ue6HrVMfbh1wqPOJQ@3zn7UuLMWyKkuftTUVG2tF6ML5JxYDiS0DYHKgVIdQNweUK1j@Kht96OmRpDiCLXqzMxTG9Ifbp2eXPtw24KQ6oc7p5/akFR7elG1jt6jzgVqj9o2PGpqBlnS0QG0pDYAaFaITsSjzjlJD7f2lgAlMoD44Y7eR02deofWgG2PARHJtiA7gKr//4@ONtBBg7E6aGJGWMQQ6ozw6iXdPMJisf@jAA "Brachylog – Try It Online") or [Try all testcases!](https://tio.run/##SypKTM6ozMlPN/pf/XBX58OtEx51LFdS0LVTUAJy7R@1bXjU1ISQ0NXVBYnXArn/gfwj3dU5QPlHLVNB8p1LHm6d/ahxJ0i2GKRta3t1jC6Qc2I5kNAGCs8@tDMDyAyo1jF81Lb7UVMjSGmEWjXYmo6HO6ef2pBU@3DbAmedgEedC4AWOFdb64ElWwyBvFqwKzqA5gCl56hVZ2ae2pD@cOv0ZJAenYikh1t7S4BKQFY83NH7qKlT79CaapBLYkBEsi3IQqAx//9HR0cb6ChgR7E6CiiSRvgkDUiVNCJbJ3Y3UeAgkGy0EaYfiTTYiJJgGESS4GDAGzNGdInTQRIMZBpsNKR0khkMRrQtG2gtaUS31DAQkpTmUmxlYGwsAA)
### How the original version works
Many bytes got lost for getting the output into a matrix form, as I didn't find a neat way to go from list of coordinates to its matrix representation. The rough story is:
```
ċ{l₂ℕᵐ≤ᵛ⁹}ᵐ
```
We are looking for a path: a list of coordinates, each 0 ≤ X ≤ 9.
```
s₂ᵇ{\-ᵐȧᵐ+}ᵛ¹hᵐ
```
And every pair of consecutive coordinates has a distance of 1.
```
P{,1↻₁}ᵐX
```
We'll store the path as `P`, and a version with a 1 before every coordinate as `X`.
```
&{iiʰgᵗc}ᶠT
```
Transform the matrix to a list of `[Type, Y, X]` and store it as `T`.
```
{ṗʰb}ˢ
```
However, we are only interested in cities for now, so the `Type` must be prime (that's why they are marked with 2).
```
C,P≠
```
The city and path coordinates must all be different to each other.
```
∧C{;.↰₂1∧}ᵐ∈ᵛP≜
```
Every city coordinate, shifted by a distance of 1, must be in the path.
```
∧T,Xbᵍtᵐhᵐḍ₉
```
To the tiles `T` append `X` (the path with `Type = 1` prepended), group the tiles by their coordinates and take the last one – so roads will overwrite empty tiles. Reduce the list to the `Type` and split it into a 9x9 matrix.
```
.¬{s₂\\s₂c=₁}∧
```
This is already the output, but make sure there is no 2x2 submatrix of roads.
[Answer]
# [R](https://www.r-project.org/), ~~248~~ ~~257~~ ~~251~~ ~~264~~ ~~250~~ 245 bytes
*Edit: +9 bytes to fix corner-case (literally; see #1 below), then some golfing, then +13 bytes to fix another corner-case (#2, below), then some more golfing...*
```
function(g,s=setdiff,S=0:8%/%3-1,`^`=`%in%`){k=which(g>0,T);v=k[,1];w=k[,2]
g[r<-max(s(v+S,v)%%9),]=g[,c<-max(s(w+S,w)%%9)]=1
for(i in 1:3){x=v[i];y=w[i]
if(!(x^(r+S)|y^(c+S)))`if`(F|x^v[-i],g[x:r,y--y^w[-i]**(y<2)]<-1,g[x,y:c]<-F<-1)}
g[k]=2;g}
```
[Try it online!](https://tio.run/##bZDPbsIwDMbvfQp2qGSDq9EittGSHXkBdotSylIaoopUSrv@EfDsXYrETjv9bH@29Pmzo6yMOcnm0JxPh1IblVeXmo3Fj5GNrgwoqll9anJdFLRny/jDf/VXQUhZmrHM18bP8Fqy7qzlGdTnkr4waVnJKRRJNzESnuJ2G1yOPdTQLvbUou9vkARTnORT6JzQPQTBQq@oLOiZNrMwXuG1Zy3XIhlY5@DpAl6gT8Eu9ngbUpCOiJkuMtjd@rTlgRakeB9bGoJgSLtpMJ/DsI1QbJ1zp9EQS1fvXIt3568ULErUfVRW5@xybKzuYUkb2qD3F4n91iYHT0JEayTHNUUPvtMbojed8ufy9MN/ucK0heMv "R – Try It Online")
This is a 'constructive' rather than 'brute-force' solution: we build a single set of roads in such a way that the conditions will be satisfied, rather than trying-out various possibilities and checking whether-or-not we've violated one or more of the conditions.
Input is a matrix with non-zero elements representing the three kingdoms. Output is a matrix with roads represented by 1, and the kingdoms by 2.
**How?**
First we construct 'main' roads in the form of a '+' from north-to-south and from east-to-west across empty elements of the grid, and touching at least one of the 3 kingdoms (*take care: corner-case 2 was when all kingdoms are in edge rows/columns, so we need to make sure that our 'adjacent' roads are still in the grid*).
Now there at most 2 kingdoms left that still need to be connected.
For each kingdom that isn't already connected to the 'main' roads, we construct an 'access road' from the kingdom to one of the 'main' roads.
We need to be careful that the 'access road' won't be split by one of the kingdoms: therefore, we check whether the unconnected kingdom is on the same row as another kingdom, and, if it isn't, we construct an east-west access road.
If the unconnected kingdom shares its row with another kingdom, we check if it also shares its column: if not, we build a north-south access road. If it does (and it also shared a row), then we can be sure that the adjacent columns are empty, so we build a north-south access road in a column adjacent to the kingdom (*corner case 1: for this, we need to check if the kingdom is in column 1: if it is, we build the access road in column 2, otherwise in column y-1*).
Here are the roads (orange) built for each of the 6 test cases (kingdoms indicated in whiteish):
[![enter image description here](https://i.stack.imgur.com/Xy0Qo.png)](https://i.stack.imgur.com/Xy0Qo.png)
**Commented code:**
```
function(g, # g=input grid with kingdoms
s=setdiff, # s=alias to 'setdiff()' function
S=0:8%/%3-1, # S=defines adjacent indices
`^`=`%in%`){ # ^=alias to '%in%' function
k=which(g>0,T) # k=get indices of the kingdoms
v=k[,1];w=k[,2] # v=x-coordinates, w=y-coordinates of kingdoms
r<-max(s(v+S,v)%%9) # r=empty row next-to a kingdom
# (elements of v±1 that are different to v, avoiding zero and >8)
c<-max(s(w+S,w)%%9) # c=first empty column next-to a kingdom
g[r,]=g[,c]=1 # build the 'main' roads
for(i in 1:3){ # loop through each of the 3 kingdoms:
x=v[i];y=w[i] # (x,y=x- and y-coordinates of current kingdom)
if(!(xin%(r+S)|y%in%(c+S))) # if x or y are not adjacent to r or s
# (so this kingdom isn't connected to the 'main' roads)
`if`(F|x%in%v[-i], # if x is shared with the row of another kingdom, or
# 'F' indicates that we've already built an east-west 'access road':
g[x:r,y # build an north-south 'access road' from x to r
- # (either on the same row, y, or on an adjacent row
(-(y%in%w[-i]))**(y<2)<-1, # if y is shared with the col of another kingdom);
g[x,y:c]<-F<-1) # otherwise build an east-west 'access road' from y to c
}
g[k]=2; # mark the kingdoms on the grid
g # and return the grid
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 196 bytes
```
≔E⁹SθF⁹F⌕A§θιk⊞υ⟦ικ⟧FυF⁴F⁴«θJ§ι¹§ι⁰M✳⊗λ≔⁰ζW⁼KK.«✳⊗κ#≦⊕ζ»≔ωηF⁻υ⟦ι⟧F⁴F⁴«J§μ¹§μ⁰M✳⊗ξ≔KD⁹✳⊗νδM⌕δ#✳⊗ν¿∧№δ#¬№…δ⌕δ#¦k¿⁼⌕υμ¬⌕υι≔⟦μⅈⅉν⌕δ#ξ⟧η¿∧η⊖ΣE⟦ⅈⅉ⟧↔⁻π§η⊕ρ≔⟦⟦ικζλ⟧η⟦μν⌕δ#ξ⟧⟧ε»⎚»θFε«J⊟§ι⁰⊟§ι⁰M✳⊗⊟ι✳⊗⊟ι×#⊟ι
```
[Try it online!](https://tio.run/##fVLLbtswEDzLX0E4lyXAGinaS5KT4LSAA7gw0PRQGD4oEhMRokhZIpM@4G9XdylKTuKkPEh8zO7s7GxeZm1uM933adepBwPrrIELwVam8e67a5V5AM4F2/Or2b1tGVxwFv5flSlSrSF1K1PIX7AXTCFuXs05ZxvfleAF2yrBqh2GxuQb24BHlBuzfeLs7yzZII0DokhufN3c2imrE@wj4p8dzznB1vZRwrVqZe6UNXBt/Z2WBSgeXiPbuWB/6PhUKi0ZfNn7THewkbICqnRBlSJ7pL/80eDl2ZwiEuxCTLIyeStraZwsYrrDRPAkWEk3QYqPjfl8/FPyV4Kql4KqUdB7iupB0chIxR9B6NNphObkVxGi1D2D1BSwtB4VFoM@wb5ZF6@Wv3MtlyXago9k6QgareQc04Q84RU9rWLXjtlLLENOXYL0rrPaOwlrZXwHP@GZ3pLk02JR0HZLFmNncXx22E6cGeyJflmMYPUOH2XQRP1PEqk7OeXAiMDyRlh0CGOWWmYt4OEwO85bcEoGQdEoGtGxWhXcEez07j8zSGCaQ4IMRO9jBLtVtewAqx1YhgE@9P1iXDP6VNNucbKrTu@qt3Bx9R8e9T8 "Charcoal – Try It Online") Link is to verbose version of code. Works by drawing a line from a square adjacent to one kingdom to the edge of the grid, then drawing lines from squares adjacent to each of the other kingdoms to intersect the first line, except not allowing the two lines to be exactly one row apart. Explanation:
```
≔E⁹Sθ
```
Input the grid.
```
F⁹F⌕A§θιk⊞υ⟦ικ⟧
```
Locate all of the kingdoms.
```
FυF⁴F⁴«
```
Loop through each direction from each square adjacent to each kingdom.
```
θ
```
Print the grid.
```
J§ι¹§ι⁰M✳⊗λ
```
Jump to the selected kingdom and move to the selected adjacent square.
```
≔⁰ζ
```
Count the number of empty squares.
```
W⁼KK.«
```
Repeat while the current square is empty...
```
✳⊗κ#
```
... mark it with a `#`...
```
≦⊕ζ
```
... and increment the count.
```
»≔ωη
```
Start with no line for the second kingdom.
```
F⁻υ⟦ι⟧
```
Loop through the remaining kingdoms.
```
F⁴F⁴«
```
Loop through each direction from each square adjacent to this kingdom.
```
J§μ¹§μ⁰M✳⊗ξ
```
Jump to this kingdom and move to the selected adjacent square.
```
≔KD⁹✳⊗νδ
```
Grab the line in the selected direction.
```
M⌕δ#✳⊗ν
```
Move to where the line would intersect if it was valid.
```
¿∧№δ#¬№…δ⌕δ#¦k
```
Does this line cross the first kingdom's line? If so:
```
¿⁼⌕υμ¬⌕υι
```
If this is the second kingdom's line...
```
≔⟦μⅈⅉν⌕δ#ξ⟧η
```
... then save this as its line.
```
¿∧η⊖ΣE⟦ⅈⅉ⟧↔⁻π§η⊕ρ
```
Otherwise if the second kingdom's line does not intersect exactly one square away...
```
≔⟦⟦ικζλ⟧η⟦μν⌕δ#ξ⟧⟧ε
```
... then save this as a solution.
```
»⎚
```
Clear the canvas ready for the first kingdom's next adjacent square or the final output.
```
»θ
```
Print the grid.
```
Fε«
```
Loop over the kingdoms in the last solution found.
```
J⊟§ι⁰⊟§ι⁰M✳⊗⊟ι
```
Jump to the position of the kingdom and move to the found adjacent square.
```
✳⊗⊟ι×#⊟ι
```
Print the found line.
Note that this code tries all combinations of kingdoms and directions. It's probably unnecessary to try them all, for instance I think it's likely that you can always draw a line up from one of three sides of the bottommost kingdom and connecting the other two kingdoms to that line. If this is true then the code can be simplified, currently saving ~~10~~ 24 bytes: [Try it online!](https://tio.run/##fVLLbtswEDzLX0E4lyXAGinaS5KT4LSAA7gw0PRQGD4oEhMRokhZIpM@4G9XdylKTuKkPEh8zO7s7GxeZm1uM933adepBwPrrIELwVam8e67a5V5AM4F2/Or2b1tGVxwFv5flSlSrSF1K1PIX7AXTCFuXs05ZxvfleAF2yrBqh2GxuQb24BHlBuzfeLs7yzZII0DokhufN3c2imrE@wj4p8dzznB1vZRwrVqZe6UNXBt/Z2WBSgeXiPbuWB/6PhUKi0ZfNn7THewkbICqnRBlSJ7pL/80eDl2ZwiEuxCTLIyeStraZwsYrrDRPAkWEk3QYqPjfl8/FPyV4Kql4KqUdB7iupB0chIxR9B6NNphObkVxGi1D2D1BSwtB4VFoM@wb5ZF6@Wv3MtlyXago9k6QgareQc04Q84RU9rWLXjtlLLENOXYL0rrPaOwlrZXwHP@GZ3pLk02JR0HZLFmNncXx22E6cGeyJflmMYPUOH2XQRP1PEqk7OeXAiMDyRlh0CGOWWmYt4OEwO85bcEoGQdEoGtGxWhXcEez07j8zSGCaQ4IMRO9jBLtVtewAqx1YhgE@9P1iXDP6VNNucbKrTu@qt3Bx9R8e9T8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔E⁹SθF⁹F⌕A§θιk⊞υ⟦ικ⟧
```
Input the grid and locate all of the kingdoms.
```
≔⊟υτ
```
Get the bottommost kingdom.
```
F³«
```
Check the squares to its right, above and left.
```
θJ§τ¹§τ⁰M✳⊗ι
```
Print the grid and jump to the selected adjacent square.
```
≔⁰ζW⁼KK.«↑#≦⊕ζ»
```
Draw a line up as far as possible.
```
≔ωη
```
Start with no line for the second kingdom.
```
FυF⁴F⁴«
```
Loop over the other two kingdoms, considering all lines for all four adjacent squares. (I could just do left and right lines but it turns out that all lines is golfier.)
```
J§κ¹§κ⁰M✳⊗μ
```
Jump to this kingdom's adjacent square.
```
≔KD⁹✳⊗λδ
```
Grab the line in the selected direction.
```
¿∧№δ#¬№…δ⌕δ#¦k
```
Does this line cross the first kingdom's line? If so:
```
¿⌕υκ«
```
If this is the third kingdom's line, then...
```
¿∧η⊖↔⁻ⅉ§η¹
```
... if the second kingdom's line isn't exactly one row away, then...
```
≔⟦⟦τ¹ζι⟧η⟦κλ⌕δ#μ⟧⟧ε
```
... save this as a solution.
```
»≔⟦κⅉλ⌕δ#μ⟧η
```
Otherwise for the second kingdom save this as its line.
```
»⎚
```
Clear the canvas ready for the first kingdom's next adjacent square or the final output.
```
»θFε«J⊟§ι⁰⊟§ι⁰M✳⊗⊟ι✳⊗⊟ι×#⊟ι
```
Print the solution.
[Answer]
# [Perl 5](https://www.perl.org/) `-00ap`, ~~114~~, 109 bytes
```
$_|=substr'iiiiiiiii
iaiaiaiai
'x5,10*!(grep/k/,@F[1,7]),90;1while s/(?<!i.{9})(?<!ii)i(?!iii|.{9}i.{9}i)/a/s
```
6 bytes saved thanks to @DomHastings, but 1 lost to fix [a case](https://tio.run/##pY3RCoIwFIbvfYokURdrmxcSssSueomIWDTqoOXYjJTs1VvT8gn6fjj/x39zlNRVajtKqKBhqOWp5tcuaHnQ54zb4NDn5n40jY5gwgPxixe1KU7Ywo/PWipaUrzZ7hK82iOcMZ48LlDJmaFxsfaBPLMXGg0QxIWrfpjGHZB7bizvuABO5pY4yuF45bedkYm/7F2rBuqbsUvGRKU@ "Perl 5 – Try It Online").
[Try it online!](https://tio.run/##pZHRCoIwFIbvfYoiMQ3b5oWErKirXiIijKQOx1JcUZK9ekujRcRCpTPYPv5x/v2cpVEW@zKnhIbUsrJok/B9bl64WUwYl@aqmIjTWhyzPqgyIHwto3/xXY8NuvY2i1KK1J3NF547WjpuwLh33kEcdQS1p@MukGtwc54EDtjT8oCi0p4X4JSvC8lzHgInPUlUGdWGbyLfhBpNtWg7DFQ9HyKSHzat6CMN1idsaa0R8Q9NY411s64lbJK6KelHqP7unqRHSA5CDhkL4/QB "Perl 5 – Try It Online")
Another perl answer, with a different approach, I've also upvoted the other perl answer.
I had to fix several times because of some cases (in addition to those of the question) for which it didn't work.
# Solution
The idea is to start from the grid of roads which almost works and fix for the different cases.
If there's a kingdom in the square region of `o`s rows: 1 or 7 (after golfing), the grid is aligned on (0,0), otherwise on (0,1)
```
......... ######### # # # # #
ooooooooo # # # # # #########
......... ######### # # # # #
......... # # # # # #########
......... ? ######### : # # # # #
......... # # # # # #########
......... ######### # # # # #
ooooooooo # # # # # #########
......... ######### # # # # #
```
Then the remaining roads can be fixed by removing squares when all the squares in the four directions, empirically (haven't a proof yet), at a distance of 3 (right), 2 (left, bottom) or 1 (up), are not a road (or are out of the map).
```
?
??#???
?
?
```
# Justification
Looking for a counter-example. Starting from a grid of roads and putting kingdoms so that road a kingdom could be disconnected.
Because of the symmetries only the first corner is shown.
For grid 1, the only case which causes a problem:
```
k.k###
. # #
k#####
# # #
```
and as there is no kingdom in the region described in solution it can't occur.
For grid 2, one example but other configurations exist:
```
k # #
..k###
k # #
######
```
One of the 2 kingdoms that cut the roads must be in the region described in solution, so this can't occur.
[Answer]
# [J](http://jsoftware.com/), 139 127 bytes
Starting from `[0,1]` or `[0,2]` forming two grids
```
#XX#… and .X.#…
#.#.… ####…
####… .#.#…
#.#.… ####…
```
at least one of the 3 attempts will succeed (based on a hacked together J script.) For some byte saving, this tries some more grids:
```
+u({.@\:#@~.@,"3)0|:(d|.!.0]*1+i.@$)*"2/u=:(}:"2}:"{d|.10$#:1023 682)(2=_(d=:(,-)#:i.3)&(*@]*[:>./|.!.0)(9 9$!.1]1 2 2)*1=+)"2]
```
[Try it online!](https://tio.run/##rZFNa8MwDIbv@RVqEmLLSVXbgbF6eBgGO@3U62Z66NcyH3bqqd3@ehYC6cZwSfdhEDzI0vtK6KVNiW3BGmBQgQTTxZTgbvFw35Z7fiD3ZDL3Tq5Ka5RHw9dHmpD0QpUNuRxFqmd7a/ibSXUXh@5byTwzSuoarq41cm2XfN1VVFPMTEM1Flw4Lx7NLc16LeRzmOcTUl6BBo1C2RJT7VtMdtYwYBVsC@KMssCKhjBJNqvnV9iBv6GlBt4PjQkNr6dwIvpOIZIbWqIdGDcMg9KX0kBnxH9EZww/Jw/j2/yLYaQ0/CF3sWEYu@Eohd9veCnFjxBOhu0H "J – Try It Online")
### How it roughly works
There should still be some bytes golfable. But for now:
```
(}:"2}:"{d|.10$#:1023 682)
```
The grid – first as a 10x10 matrix so we can easily shift via the 4 `d`irections, we'll define later. Drawback: we have to cut it down to 9x9. Now, for every grid:
```
(9 9$!.1]1 2 2)*1=+
```
Whenever a castle is on a road, set the tile to empty. Also, give the roads at `[0,1]` and `[0,2]` value 2 (if they exist). From there we'll find the biggest connected road network now:
```
2=_(d=:(,-)#:i.3)&(*@]*[:>./|.!.0)
```
Until the map does not change: shift it around and give each road a new road number: the maximum of the current number and the ones of the connected roads (but keep 0 as 0). Finally, keep the roads marked with 2 – those are connected to the starting nodes
```
(d|.!.0]*1+i.@$)*"2/
```
Now to check that all castles are connected: Take the original input, and shift it into the 4 directions. Give each castle a unique number.
```
+u({.@\:#@~.@,"3)0|:
```
Sort the grids by the number of connected castle (the unique numbers after the shifted castle numbers are multiplied with the 1's of the road network.) Take the best one, add the castles back in – et voilà, a kingdom for you!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes
```
F⁹F⌕ASk⊞υ⟦ικ⟧B⁹ψF⁹F⁹«Jκι¿¬№﹪⟦ικ⟧²﹪ΠEυΠ⊕λ² »Fυ«J⊟ι⊟ιk»F³F³«J⁺³κ⁺³ι¤#
```
[Try it online!](https://tio.run/##bVDBSgMxFDx3v@IRLy8Qe3BPxZMKhQrKgt7Ew7K7bUPSvCVNRBG/Pb50U2mp75CZhJk3Q7pt6ztqbUpr8oALCQdcatffWYsrN8bwErx2G5QKhBFSQhP3W4wK3rQC8y5vq3v6xIWCL6ZnWxi/q9lj3I2vhEaBZsFMrwGfKeADRRfwifpoCadVCm44pDw1nrFjRTvmsON15To/7AYXhh6t5MkmmVtxyYACBIf8TD3iaX5DI2pWT5ibFIc5cdSleX3mtHGPNRfM7sKnDUvNfySuDgtSmh@nyof5Y/MLZi7fzH@6Mun6w/4C "Charcoal – Try It Online") Link is to verbose version of code. Outputs using spaces for empty tiles, but anything except `k` serves as empty on input. This is an entirely different approach to my previous answer, so I thought it deserved a separate answer. It relies on the observation that the grid with 16 holes solves all problems except those with three kingdoms near the corners. The one thing those problems have in common is that all three kingdoms lie on even rows and columns. In such cases the grid is offset diagonally resulting in a grid with 25 holes. Explanation:
```
F⁹F⌕ASk⊞υ⟦ικ⟧
```
Read in the grid and save the coordinates of the kingdoms.
```
B⁹ψ
```
Prepare an empty area for the grid.
```
F⁹F⁹
```
Loop through each square on the grid.
```
«Jκι
```
Jump to that position.
```
¿¬№﹪⟦ικ⟧²﹪ΠEυΠ⊕λ² »
```
If both the row and column have the same parity as the bitwise OR of all of the coordinates, then place an explicit space at that position, preventing it from being flood filled. Since I don't have a good way of taking the bitwise OR of a list, I use De Morgan's laws to check whether neither row nor column contain have the parity of the bitwise AND of the complement of the list, noting that for the purposes of parity, product is equivalent to bitwise AND and increment is equivalent to complement.
```
Fυ«J⊟ι⊟ιk»
```
Place the kingdoms on the grid.
```
F³F³«J⁺³κ⁺³ι¤#
```
Try to flood fill starting at each of the nine centre squares. This guarantees that the result is a single connected road. It's not possible for only three kingdoms to disconnect the centre of the grid, so this is always safe.
] |
[Question]
[
A simple contest, inspired by [this stackoverflow question](https://stackoverflow.com/questions/11936073/can-counting-contiguous-regions-in-a-bitmap-be-solved-in-better-than-or-c/11936456):
>
> You are given an image of a surface photographed by a satellite.The image is a bitmap where water is marked by '`.`' and land is marked by '`*`'. Groups of adjacent '`*`'s form an island. (Two '`*`' are adjacent if they are horizontal, vertical or diagonal neighbours). Your task is to print the number of islands in the bitmap.
>
>
>
A single `*` also counts as an island.
Sample Input:
```
.........**
**......***
...........
...*.......
*........*.
*.........*
```
Sample Output:
```
5
```
Winner is entry with smallest number of bytes in the code.
[Answer]
# Mathematica 188 185 170 115 130 46 48 chars
**Explanation**
In earlier versions, I made a graph of positions having a chessboard distance of 1 from each other. `GraphComponents` then revealed the number of islands, one per component.
The present version uses `MorphologicalComponents` to find and number clusters of ones in the array--regions where `1`'s are physically contiguous. Because graphing is unnecessary, this results in a huge economy of code.
---
**Code**
```
Max@MorphologicalComponents[#/.{"."->0,"*"->1}]&
```
---
## Example
```
Max@MorphologicalComponents[#/.{"."->0,"*"->1}]&[{{".", ".", ".", ".", ".", ".", ".", ".", ".", "*", "*"}, {"*", "*", ".", ".", ".", ".", ".", ".", "*", "*", "*"}, {".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."}, {".", ".", ".", "*", ".", ".", ".", ".", ".", ".", "."}, {"*", ".", ".", ".", ".", ".", ".", ".", ".", "*", "."}, {"*", ".", ".", ".", ".", ".", ".", ".", ".", ".", "*"}}]
```
5
---
**How it works**
Data are input as an array; in Mathematica, this is a list of lists.
In the input array, data are converted to `1`'s and `0`'s by the replacement
```
/.{"."->0,"*"->1}
```
where `/.` is an infix form of `ReplaceAll` followed by replacement rules. This essentially converts the array into a black and white image. All we need to do is apply the function, `Image`.
```
Image[{{".", ".", ".", ".", ".", ".", ".", ".", ".", "*", "*"}, {"*", "*", ".", ".", ".", ".", ".", ".", "*", "*", "*"}, {".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."}, {".", ".", ".", "*", ".", ".", ".", ".", ".", ".", "."}, {"*", ".", ".", ".", ".", ".", ".", ".", ".", "*", "."}, {"*", ".", ".", ".", ".", ".", ".", ".", ".", ".", "*"}} /. {"." -> 0, "*" -> 1}]
```
[![islands](https://i.stack.imgur.com/8Gp45.png)](https://i.stack.imgur.com/8Gp45.png)
The white squares correspond to the cells having the value, 1.
The picture below shows a some steps the approach uses. The input matrix contains only `1`'s and `0`'s. The output matrix labels each morphological cluster with a number. (I wrapped both the input and output matrices in `MatrixForm` to highlight their two dimensional structure.)
`MorphologicalComponents` replaces `1`s with an integer corresponding to the cluster number of each cell.
![processing](https://i.stack.imgur.com/nyNg4.png)
`Max` returns the largest cluster number.
---
**Displaying the Islands**
`Colorize` will color each island uniquely.
![colorize](https://i.stack.imgur.com/rRhU6.png)
[Answer]
## Ruby 1.9 (~~134~~ ~~121~~ ~~113~~ 110)
Takes the map on stdin or the file name of the map as the first command-line argument, and prints the number of islands to stdout. Using a basic recursive flood-fill. Improvements welcome as always!
```
c=0
gets$!
c+=1while(f=->i{9.times{|o|$_[i]=?.;f[o]if$_[o=i+(o/3-1)*(~/$/+1)+o%3-1]==?*&&o>0}if i})[~/\*/]
p c
```
Similar to David's colorize, you can also get it to display the different islands by changing `$_[i]=?.` to `$_[i]=c.to_s` and `p c` to `puts$_`, which would give you something like this:
```
.........00
11......000
...........
...2.......
3........4.
3.........4
```
(at least until you run out of digits!)
Some test cases:
```
.........**
**......***
...........
...*.......
*........*.
*.........*
```
5
```
......*..**....*
**...*..***....*
....*..........*
...*.*.........*
*........***....
*.....*...***...
*.....*...*....*
****..........**
*.........*.....
```
9
```
*
```
1
```
****
****
....
****
```
2
```
**********
*........*
*.******.*
*.*....*.*
*.*.**.*.*
*.*.**.*.*
*.*....*.*
*.******.*
*........*
**********
```
3
[Answer]
## C, 169 chars
Reads map from stdin. Had no luck improving the recursive flood-fill function `r(j)` although it looks like it could be.
```
c,g,x,w;char m[9999];r(j){if(m[j]==42)m[j]=c,r(j+1),r(j+w-1),r(j+w),r(j+w+1),c+=j==g;}main(){while((m[x++]=g=getchar())+1)w=g<11*!w?x:w;for(;g++<x;)r(g);printf("%i",c);}
```
[Answer]
# Python 2, ~~223~~ 203 Bytes
Thank you to [Step Hen](https://codegolf.stackexchange.com/users/65836/step-hen) and [Arnold Palmer](https://codegolf.stackexchange.com/users/72137/arnold-palmer) for shaving off 20 characters of spaces and unnecessary parenthesis!
```
s=input()
c=[(s.index(l),i)for l in s for i,v in enumerate(l)if'*'==v]
n=[set([d for d in c if-2<d[0]-v[0]<2and-2<d[1]-v[1]<2])for v in c]
f=lambda x,p=0:p if x&n[p]else f(x,p+1)
print len(set(map(f,n)))
```
I thought that using list comprehensions might decrease the number of bytes, but it didn't provide any significant improvement.
[Try it here.](https://tio.run/##VY3NbsMgEITvfoo9hZ8SK/YxCk@COFADKhLeIEMs9@ldcJRE3cNqv9HMTvotP3cc9z3LgOlRKOsmqWjuA1q30chEYP6@QISAkKGdQawNHD5mt5jiqil4womUq@5QquwKVfaw2macIPjzeLPqos9rXbfRoD2EoQlDFfTRcbyddOdlNPO3NbCJJC/XVPOwnVAl7WJ24GnVvwbWpSVggeiQtsrZJOoFMsb2XZH@NZwTQTh/QaP@M0/iH@Lv3D/qOdF/)
I keep trying to trim it around the n (neighbors) list, but I haven't been successful. Maybe someone else will have some ideas for that section.
[Answer]
# [Perl 5](https://www.perl.org/), 100 bytes
98 bytes of code + 2 bytes for `-p0` flags.
```
/.*/;$@="@+"-1;$~="(.?.?.{$@})?";(s/X$~\*/X$1X/s||s/\*$~X/X$1X/s)&&redo;s/\*/X/&&++$\&&redo}{$\|=0
```
[Try it online!](https://tio.run/nexus/perl5#TYrBDoMgGIPvPsXG/hAtkV/PhMhjcOA4b0tm5Cjy6kyzsa1Nmq9Nb9dlXh@XfhkKa7AhZ4VToh8NZStaPR3eyO3dJEwb2VMOOHL0HFOKHEDZf3on5Trfn@Zc2bOUSlF4b/tGIdmhFF0FNEBFNPqnk1EZ3/8fa7wA "Perl 5 – TIO Nexus")
An adaptation (or rather a simplification) of my [answer](https://codegolf.stackexchange.com/a/113778/55508) to the challenge [How Many Holes?](https://codegolf.stackexchange.com/questions/113764/how-many-holes). You can find explanations of how this code works on this other answer (it's a bit long to explain, so I prefer not to retype the entire explanations).
[Answer]
## Python 2, 233 bytes
Too long, compared to other answers. Port of my answer to [this question](https://codegolf.stackexchange.com/questions/113764/how-many-holes).
[Try it online](https://tio.run/nexus/python2#nU9BboMwELz7FZaiymuzUFBvUB8QX8iByPIhIkS1FCzUJqrpoV@npklbUqGGctjR7MzOrrbPpbHt6QicVDImpTzUFnIVax4mZHPuBrqr97SANU8JddjJNaFmT3PVaeX0I4tYeuHS86zZtlDgm2nBK@IhUI2x4IIES35utw5cmGA8tKg6HPzO@xuOg9d9eZyT1ydzqJlgxtKXUwM5Ks1TI795ZOyuduAneFYFMskKAHMXvpdo7j36De2zsUda9Sul2IrhqDT@KPRKoZMzF0X3flPEkM4GMWo1UqpG8r/gM64mts6F4Z1f4VsXr29Ppm/9/HdaTIzPuh0tvS2W/r0EtP4A)
```
A=input()
c=0
X=len(A[0])-1
Y=len(A)-1
def C(T):
x,y=T
if A[y][x]<'.':A[y][x]='.';map(C,zip([x]*3+[min(x+1,X)]*3+[max(x-1,0)]*3,[y,min(y+1,Y),max(y-1,0)]*3))
while'*'in sum(A,[]):i=sum(A,[]).index('*');c+=1;C((i%-~X,i/-~X))
print c
```
[Answer]
## JavaScript, 158 bytes
```
function f(s){w=s.search('\n');t=s.replace(RegExp('([*@])([^]{'+w+','+(w+2)+'})?(?!\\1)[*@]'),'@$2@');return t!=s?f(t):/\*/.test(s)?f(s.replace('*','@'))+1:0}
```
Noncompeting ES6 answer (language postdates challenge) for 132 bytes:
```
f=s=>s!=(s=s.replace(RegExp(`([*@])([^]{${w=s.search`
`},${w+2}})?(?!\\1)[*@]`),`@$2@`))?f(s):/\*/.test(s)?f(s.replace(`*`,`@`))+1:0
```
Port of my answer to [How Many Holes?](https://codegolf.stackexchange.com/questions/113764/how-many-holes) (yes I'm jumping on the bandwagon, now that I've seen two other people port their answers).
[Answer]
# [Python 2](https://docs.python.org/2/), 225 bytes
```
g=map(list,input())
q,w,t,r=len(g),len(g[0]),0,range
def l(i,j):
if 0<=i<q and 0<=j<w and g[i][j]=='1':g[i][j]=0;l(i+1,j);l(i-1,j);l(i,j+1);l(i,j-1)
return 1
print sum(l(i,j)if g[i][j]=='1'else 0 for j in r(w)for i in r(q))
```
[Try it online!](https://tio.run/##ZY3BjoMwDETv@QqLS2PVlew9dsmXIA5IDWwimkIIQvv1LIEiVVpf/Maj8Qy/6ecVvta1M89m0L2bErkwzEkjqpEWShRNb4PukPZVcY3EFJvQWfWwLfTakce7AtcCl8aVIzThkdGXy45d5erK18Zc5HI/BX9vwats0Qy3E8hf5Q03QQXRpjkGEDVEFxJM81MfhVvb51/bTxYY2lcEDy5A1Atm4Q4xIq5rVYgIs0hBxQGZ@JhM2@105b/Le7qo/wA "Python 2 – Try It Online")
] |
[Question]
[
Disclaimer: while I have been on this site for entertainment purposes for a little while now, this is my first question, so please forgive any minor errors.
# Background
When assigning us homework, my teacher is really annoying and writes out *all* the problems we have to do individually. As such, it takes me *forever* to copy down which problems I have to do. I thought to make my life easier, I would send him a program that could make the list of problems take up less space.
While writing down a list of page or problem numbers, we use a dash to denote a range. For example, `19-21` becomes `19, 20, 21`. If there is a gap in between, two comma-separated ranges are used: `19-21, 27-31` becomes `19, 20, 21, 27, 28, 29, 30, 31`.
Right about now, you're probably thinking: "this seems pretty trivial". In fact, this has already been answered [here](https://codegolf.stackexchange.com/questions/52321/determine-ranges-from-a-list-of-values) and [here](https://codegolf.stackexchange.com/questions/20545/string-of-alphanumeric-characters-to-a-sorted-list-of-comma-separated-ranges).
However, there is a catch. If we have a range with equal consecutive digits, the repeated digits can be left out. For example: `15, 16, 17` becomes `15-7`, and `107, 108, 109` becomes `107-9`. For a bonus, if the last consecutive equal digit is 1 greater and the upper limit's last digit is less than or equal to that of the lower, the following can be omitted (sorry if that sounded confusing; perhaps some examples will clear it up). `109-113` becomes `109-3`, as a lower last digit implies increasing the 10s place.
# Challenge
Your program should take a list of integers via input (whatever is standard for your language, or a function). You can decide whether this list is comma-separated, space-separated, or as an actual list/array.
Output the **shortest way** (first sorted by number of ranges, then the sum of the characters included in the ranges) to represent that list using this notation. Each dashed range must be on the same line, but the ranges can be separated by commas or newlines (trailing newlines or commas are allowed). These ranges must be in order.
Since our school Wi-Fi is **terrible**, I have to make the file as small as possible in order to send it to him. The shortest code (in bytes) wins.
# Bonuses
My teacher is sloppy, so there are a few things that would help him out.
Multiple bonuses stack through multiplication, e.g. a -10% bonus (x 90%) and a -25% (x 75%) bonus = 90% \* 75% = x 67.5% (-32.5% bonus).
* Sometimes he puts them in the wrong order (he's not a math teacher). Take a -20% bonus if your program can accept integers that are not sorted least-to-greatest.
* Our book is weird, and each section starts counting the problems at -10. If your program can accept negative numbers, take a -25%.
* If it accepts the bonus of a lower last digit increasing 10's place, e.g. `25-32` reducing to `25-2`, take a -50% bonus.
# Test Cases
```
In: 1, 2, 3, 4, 5
Out: 1-5
In: 3, 4, 5, 9, 10, 11, 12
Out: 3-5, 9-12
In: 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160
Out: 149-60
In: 1 2 3 4
Out: 1-4
For bonuses:
In: 109, 110, 111, 112, 113
Out: 109-3
In: 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
Out: 19-9
In: -3, -2, -1, 0, 1, 2
Out: -3-2
In: -3, -2, -1
Out: -3--1
```
An answer will be accepted on Saturday, 19 December 2015.
GLHF!
[Answer]
## C++11, 451 \* 80% \* 75% \* 50% = 135.3 bytes
Saved 9 bytes thanks to @kirbyfan64sos.
Saved 19 bytes thanks to @JosephMalle and @cat.
Saved 11 bytes thanks to @pinkfloydx33.
```
#include<vector>
#include<cmath>
#include<algorithm>
#include<string>
#define T string
#define P append
using namespace std;T f(vector<int>v){sort(v.begin(),v.end());T r=to_T(v[0]);int b=1;int m=v[0];for(int i=1;i<=v.size();i++){if(i!=v.size()&&v[i]==v[i-1]+1){if(!b){m=v[i-1];}b=1;}else{if(b){T s=to_T(v[i-1]);r.P("-").P(s.substr(s.size()-(v[i-1]-m==1?1:log10(v[i-1]-m)),s.size()));}if(i!=v.size()){r.P(", ").P(to_T(v[i]));}b=0;}}return r;}
```
This qualifies for all the bonuses.
Sample parameter test and result:
```
In: [1, 2, 3, 4, 5]
Out: 1-5
In: [3, 4, 5, 9, 10, 11, 12]
Out: 3-5, 9-12
In: [149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160]
Out: 149-60
In: [1, 2, 3, 4]
Out: 1-4
In: [109, 110, 111, 112, 113]
Out: 109-3
In: [19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
Out: 19-9
```
[Answer]
## Ruby, ~~120~~ 118 \* 0.8 \* 0.75 \* 0.5 = 35.4 bytes
Takes command-line arguments as input (commas are okay); prints one range per line to standard output.
```
c=(b=(a=$*.map(&:to_i).sort).map &:succ)-a
puts (a-b).map{|m|(m<n=c.shift-1)?"#{m}-#{m<0?n:n%10**"#{n-m-1}".size}":m}
```
With whitespace/comments:
```
c=(
b=(
# a is the sorted input
a=$*.map(&:to_i).sort
# b is the set of successors of elements of a
).map &:succ
# c=b-a is the set of not-quite-least upper bounds of our ranges
)-a
# a-b is the set of greatest lower bounds of our ranges
puts (a-b).map {|m|
# for each range [m,n], if there are multiple elements
(m < n = c.shift-1) ?
# yield the range, abbreviating n appropriately if positive
"#{m}-#{m<0 ? n : n % 10 ** "#{n-m-1}".size}" :
# in the one-element case, just yield that
m
}
```
**Test cases**
```
$ ruby homework.rb 1, 2, 3, 4, 5
1-5
$ ruby homework.rb 3, 4, 5, 9, 10, 11, 12
3-5
9-2
$ ruby homework.rb 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160
149-60
$ ruby homework.rb 1 2 3 4
1-4
$ ruby homework.rb 109, 110, 111, 112, 113
109-3
$ ruby homework.rb 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
19-9
```
**Features not covered by test cases**
Unordered input & single-element ranges:
```
$ ruby homework.rb 2 17 19 22 0 1 8 20 18
0-2
8
17-0
22
```
Negative ranges (not possible to abbreviate the larger number with these):
```
$ ruby homework.rb -17 -18 -19 -20 -21
-21--17
```
Abbreviation of arbitrary numbers of digits (ordinary bash expansion used for the input here):
```
$ ruby homework.rb {1234567..1235467} 2345999 2346000 2346001
1234567-467
2345999-1
```
[Answer]
# LabVIEW, 97\*0.8\*0.75\*0.5 = 29.1 [LabVIEW Primitives](https://codegolf.meta.stackexchange.com/a/7589/39490)
this works by counting upwards if sucessive elemts are 1 apart and then creates a string from the the number and the number - count modulo 10 and some multiplication cause negatives are a bitch.
The gif showcases an input of `8,9,10,11` and outputs `8-1`. For input `-5,-4,-3,1,3,4,5` `-5--3,1,3-5`comes out.
[![](https://i.stack.imgur.com/kelGW.gif)](https://i.stack.imgur.com/kelGW.gif)
[Answer]
# Javascript ES6, 229 \* 80% \* 75% \* 50% = 68.7 bytes
## Test Input
I'm using the following test data:
```
var A1=[
5,6,7, // => 5-7 # (a) group pages
2,3, // => 2-3,5-7 # (b) must be properly sorted
-9,-8,-7, // => -10--8 # (c) allow negative numbers
29,30,31,32, // => 29-2 # (d) lower last digit implies increasing the 10s place
9,10,11,12, // => 9-11 # NOT 9-2
36,37,38,39,40,41,42,43,44,45,46,47,
// => 36-47 # NOT 36-7
99,100,101,102, // => 99-102 # NOT 99-2
109,110,111,112, // => 109-2 # NOT 109-12
],
// more tests, not specified in the question
A2=[
120,124, // => 120,124 # (e) handle single pages
],
A3=[
135,136,135 // => 135-6 # (f) handle duplicates
];
```
## Basic: 229 bytes
This version satisfies the requirements of the question (a) with all bonuses (c,d,e), but hangs on single pages. It can also handle duplicates(f). It handles negative pages down to -10,000, which can be easily increased with (large) loss of speed.
```
F=(a)=>{var R=[],i=NaN,l,u;a.map(x=>R[1e4+x]=x);R.concat('').map(x=>(i!=i&&(l=x,u=l-1),i=0,u=(x+="")-u-1?l=console.log(l+'-'+(u>0?(l.length-u.length||(z=>{for(;l[i]==u[i];i++);})(),u.length-i-2||u-l>9||i++,u.slice(i)):u))||x:x))}
F(A1.concat(A3)) --> -9--7 2-3 5-7 9-12 29-2 36-47 99-102 109-2 135-136
```
(The output above shows spaces instead of actual newlines for brevity)
## Single pages: 233 bytes
This slightly longer version additionally satisfies (e) and displays single pages as a range with equal lower and upper limits
```
G=(a)=>{var R=[],i=NaN,l,u;a.map(x=>R[1e4+x]=x);R.concat('').map(x=>(i!=i&&(l=x,u=l-1),i=0,u=(x+="")-u-1?l=console.log(l+'-'+(u-l&u>0?(l.length-u.length||(z=>{for(;l[i]==u[i];i++);})(),u.length-i-2||u-l>9||i++,u.slice(i)):u))||x:x))}
G(A1.concat(A2,A3)) --> -9--7 2-3 5-7 9-12 29-2 36-47 99-102 109-2 120-120 124-124
```
[Answer]
# [GAP](http://www.gap-system.org), 355 Bytes \*0.8\*0.75\*0.5 = 106.5
This satisfies all the bonuses. It cost me almost 100 extra bytes to make everything work nicely. This function only omits leading digits if the gap does not overflow the ones place once. For example `9 10 11` outputs `9-1` but `9 10 11 12 .. 20 21` outputs `9-21`.
If GAP was a little less verbose, I could have gotten this pretty short (also could have saved many bytes if I didn't follow the exact syntax.) I'll probably try golfing this a bit harder tomorrow. See below for test cases.
```
g:=function(l)local n;if not l=[] then Sort(l);n:=1;while not l=[] do;if not IsSubset(l,[l[1]..l[1]+n]) then if not n=1 then if n-1>10-l[1] mod 10 and n-1<11 then Print(l[1],"-",(l[1]+n-1) mod 10);else Print(l[1],"-",l[1]+n-1);fi;else Print(l[1]);fi;Print(", ");SubtractSet(l,[l[1]..l[1]+n-1]);g(l);fi;n:=n+1;od;fi;Print("\b\b ");end;
```
ungolfed:
```
g:=function(l)
local n;
if not l=[] then
Sort(l);
n:=1;
while not l=[] do;
if not IsSubset(l,[l[1]..l[1]+n]) then
if not n=1 then
if n-1>10-l[1] mod 10 and n-1<11 then
Print(l[1],"-",(l[1]+n-1) mod 10);
else
Print(l[1],"-",l[1]+n-1);
fi;
else
Print(l[1]);
fi;
Print(", ");
SubtractSet(l,[l[1]..l[1]+n-1]);
g(l);
fi;
n:=n+1;
od;
fi;
Print("\b\b ");
end;
```
Note that in GAP syntax, `[a..b]` is equivalent to `[a,a+1,...,b]`. I believe that these test cases demonstrate that this program meets all the requirements. If something is wrong, let me know.
```
gap> h([1..5]);
1-5
gap> h([3,4,5,9,10,11,12]);
3-5, 9-2
gap> h([149..160]);
149-160
gap> h([109..113]);
109-3
gap> h([19..29]);
19-9
gap> h([-1,-2,-3,-7,-20000,9,10,110101,110102]);
-20000, -7, -3--1, 9-10, 110101-110102
gap> h([10101,10102,10103,10,11,12,13,14,15,16,234,999,1000,1001,1002]);
10-16, 234, 999-2, 10101-10103
```
[Answer]
# Lua, 322\*80%\*75%\*50% = 96.6 Bytes
Finally done with the 3 challenges, Scores under 100 bytes :D
### Golfed
```
function f(l)table.sort(l)l[#l+1]=-13 a=l[1]t,s=a,"" for _,v in next,l do if v-t>1 or t-v>1 then s,p,r=s..a.."-",""..t,""..a r:gsub("%d",function(c)p=r:find(c)~=r:len()and p:gsub("^(-?)"..c,"%1")or p r=r:gsub("^"..c,"")end)p=t-a<10 and t%10<a%10 and p:gsub("^(%d)","")or p s,a,t=s..p..",",v,v else t=v end end return s end
```
### Ungolfed
```
function f(l)
table.sort(l)
l[#l+1]=-13
a=l[1]
t,s=a,""
for _,v in next,l
do
if v-t>1 or t-v>1
then
s,p,r=s..a.."-",""..t,""..a
r:gsub("%d",function(c)
p=r:find(c)~=#r and p:gsub("^(-?)"..c,"%1")or p
r=r:gsub("^"..c,"")
end)
p=t-a<10 and t%10<a%10 and p:gsub("^(%d)","")or p
s=s..p..","
a,t=v,v
else
t=v
end
end
return s
end
```
You can test lua [online](http://www.lua.org/cgi-bin/demo), to see how it perform against the test cases, copy paste the function, followed by this code :
```
a={1,2,3,4,5}
b={3,4,5,9,10,11,12,13,14,15,16,17,18,19,20,21}
c={149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160}
d={-7,8,5,-6,-5,6,7}
print(f(a))
print(f(b))
print(f(c))
print(f(d))
```
[Answer]
# Java, 252 \* 80% \* 75% \* 50% = 75.6 bytes
I've decided to go for a method (is much smaller in Java), here is the golfed version:
### Golfed
```
int p,c,s;String m(int[]a){p=s=c=0;c--;String o="";Arrays.sort(a);for(int n:a){if(s==0)o+=s=n;else if(n-p==1)c++;else{o+=t()+", "+(s=n);c=-1;}p=n;}return o+t();}String t(){return c>=0?"-"+(""+p).substring((""+Math.abs(p)).length()-(""+c).length()):"";}
```
And here is the readable version:
```
int p, c, s;
String m(int[] a) {
p = s = c = 0;
c--;
String o = "";
Arrays.sort(a);
for (int n : a) {
if (s == 0)
o += s = n;
else if (n - p == 1)
c++;
else {
o += t() + ", " + (s = n);
c = -1;
}
p = n;
}
return o + t();
}
String t() {
return c >= 0 ? "-" + ("" + p).substring(("" + Math.abs(p)).length() - ("" + c).length()) : "";
}
```
When tested these are the results:
```
import java.util.Arrays;
public class A {
public static void main(String...s) {
A a = new A();
System.out.println(a.m(new int[] {1, 2, 3, 4, 5}));
System.out.println(a.m(new int[] {3, 4, 5, 9, 10, 11, 12}));
System.out.println(a.m(new int[] {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160}));
System.out.println(a.m(new int[] {109, 110, 111, 112, 113}));
System.out.println(a.m(new int[] {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29}));
System.out.println(a.m(new int[] {1,10,11,16}));
System.out.println(a.m(new int[] {-3,-2,-1,0,1,2,3}));
System.out.println(a.m(new int[] {-3,-2,-1}));
}
int p,c,s;String m(int[]a){p=s=c=0;c--;String o="";Arrays.sort(a);for(int n:a){if(s==0)o+=s=n;else if(n-p==1)c++;else{o+=t()+", "+(s=n);c=-1;}p=n;}return o+t();}String t(){return c>=0?"-"+(""+p).substring((""+Math.abs(p)).length()-(""+c).length()):"";}
}
```
Output:
```
1-5
3-5, 9-2
149-60
109-3
19-9
1, 10-1, 16
-3-3
-3--1
```
### Update:
It can now handle negative numbers as well, adding to the bonus.
[Answer]
# Japt, 127 bytes \* 80% \* 75% \* 50% = 38.1
Wow, that was one heck of a challenge to include all the bonuses. It could probably be made shorter.
```
D=[]N=Nn-;DpNr@Y-1¥Xg1 ?[Xg Y]:DpX ©[YY]}D;Ds1 £[BC]=Xms;B¥C?B:B+'-+CsBg ¦'-©Cl ¥Bl ©C¬r@B¯Z ¥C¯Z ªC-B§ApCl -Z ©ÂBsX <ÂCsX ?Z:X
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=RD1bXU49Tm4tO0RwTnJAWS0xpVhnMSA/W1hnIFldOkRwWCCpW1lZXX1EO0RzMSCjW0JDXT1YbXM7QqVDP0I6QisnLStDc0OsckBCr1ogpUOvWiCqQy1Cp0FwQ2wgLVogqcJCc1ggPMJDc1ggP1o6WA==&input=MTAwOCwxMDA5LDEwMTAsMTAxMSwxMDEyLDEwMTMsMTAxNCwxMDE1LDEwMTYsMTAxNywxMDE4LDEwMTksMTAyOSwxMDMw)
### How it works
The explanation is very rough; don't hesitate to ask any questions you might have.
```
/* Setting up basic variables */
// Implicit: A = 10, N = list of input numbers.
D=[],N=Nn-; // D = empty array, N = N sorted by subtraction.
/* Finding ranges of page numbers */
Dp // Push into D the result of
NrXYZ{ // reducing each previous value X and item Y in N by this function,
}[]; // starting with an empty array:
Y-1==Xg1 ? // If Y is 1 more than the second item of X,
[Xg Y]: // return [X[0], Y].
DpX &&[YY] // Otherwise, push X into D and return [Y, Y].
/* Formatting result */
Ds1 mXYZ{ // Take the first item off of D and map each item X by this function:
[BC]=Xms; // Set B and C to the first to items in X as strings.
B==C?B // If B is the same as C, return B.
:B+'-+Cs // Otherwise, return B + a hyphen + C.slice(
Bg !='-&& // If B[0] is not a hyphen (B is not negative), AND
Cl ==Bl && // B and C are the same length,
/* Cutting off unnecessary digits */
Cq r // then C split into digits, reduced with
rXYZ{ // each previous value X, item Y, and index Z mapped by this function:
Bs0,Z ==Cs0,Z || // If B.slice(0,Z) equals C.slice(0,Z), OR
C-B<=ApCl -Z // C - B <= 10 to the power of (C.length - Z);
&&~~BsX <~~CsX // AND B.slice(X) is a smaller number than C.slice(X),
?Z:X // then Z; otherwise, X.
// Otherwise, 0.
```
[Answer]
# R, 167 bytes x 80% x 75% x 50% -> 50.1
```
s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];z=tail(x,1);r=c(r,paste0(x[1],"-",ifelse(z-x[1]<=10,z%%10,z%%100)))};cat(r,sep=", ")
```
Indented, with new lines:
```
s=sort(scan(se=","))
r=c()
while(length(s)){
w=s==1:length(s)+s[1]-1
x=s[w]
s=s[!w]
z=tail(x,1)
r=c(r, paste0(x[1],"-", ifelse(z-x[1]<=10,
z%%10,
z%%100)))}
cat(r,sep=", ")
```
Test cases:
```
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 3, 4, 5, 9, 10, 11, 12
8:
Read 7 items
3-5, 9-2
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160
13:
Read 12 items
149-60
```
It works for the -50% bonus:
```
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
12:
Read 11 items
19-9
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 109, 110, 111, 112, 113
6:
Read 5 items
109-3
```
It accepts unsorted input:
```
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 114, 109, 110, 111, 112, 113
7:
Read 6 items
109-4
```
It accepts negative numbers:
```
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: -1,0,1,2
4:
Read 3 items
-1-2
```
[Answer]
# sh, 135 \* .8 \* .75 \* .5 = 40.5
```
tr , \\n|sort -n|awk -vORS="" '$1-o>1||!c{print p c$1;s=$1}{o=$1;c=", ";p=""}o>s{p="-"substr(o,length(o)-length(o-s-1)+1)}END{print p}'
```
shell script
```
tr , \\n| # comma separated -> newline separated
sort -n| # sort
awk -vORS="" # suppress automatic newlines in output
```
awk script
```
# on step > 1 or first run, end the current sequence and start a new one.
# on first run, p and c are empty strings.
$1-o>1||!c
{print p c$1;s=$1}
# old = current, c = ", " except for first run, clear end string.
{o=$1;c=", ";p=""}
# if the sequence is not a single number, its end is denoted by "-o".
# print only the last n digits of o.
o>s
{p="-"substr(o,length(o)-length(o-s-1)+1)}
# end the current sequence without starting a new one.
END
{print p}'
```
where `s` is the start of the current sequence and `o` is the previous input value.
] |
[Question]
[
Input will consist of the following characters:
* `^`: Go up one
* `v`: Go down one
* `▲` or `k`: Go up two
* `▼` or `j`: Go down two
For example, the following input:
```
^^▲^v▼▲^^v
```
would produce the following output:
```
^
^ ^ v
▲ v ▲
^ ▼
^
```
Escape sequences that move the cursor such as `\e[B` are not allowed. You must produce the output using spaces and newlines.
Here are a few more test cases.
```
▲v^v^v^v^v^v^v^v▲
```
```
▲
▲ ^ ^ ^ ^ ^ ^ ^
v v v v v v v v
```
```
^^^^^^^▲▲▲▼▼▼vvvvvv
```
```
▲
▲ ▼
▲ ▼
^ ▼
^ v
^ v
^ v
^ v
^ v
^ v
```
```
v^^vv^^vvv^v^v^^^vvvv^^v^^vv
```
```
^ ^ ^
^ v ^ v ^ v ^
v v v ^ ^ ^ v ^ ^ v
v v v v ^ v v
v
```
[Answer]
# [Unreadable](https://esolangs.org/wiki/Unreadable), ~~2199~~ ~~2145~~ ~~2134~~ ~~2104~~ ~~2087~~ 2084 bytes
Supports both `k`/`j` as well as `▲`/`▼` syntax.
In good Unreadable tradition, here is the program formatted in proportional font, to obfuscate the distinction between apostrophes and double-quotes:
>
> '""""""'""""""""'"""'""'""'""'""'"""'"""""'""""""'""'""'""'""'"""'""'""""""'""""""'""""""""'"""'""'""'"""""""'""""""""'"""'""""""""""'""""'""""'""""'""""'""""'""""""'""'""'""'""'""'"""'""'"""'""""""'""'""'""'""'"""'"""""""""'"""""'""""""'""'""'""'""'"""'""""""""'"""""""'""'""'""'""'"""'""""'""""""'""'""'""'""'""'"""'"""""""""'"""""""'""'""'""'""'""'"""'""""""""'"""""""'""'""'""'""'""'"""'""'""'"""'""""""'"""'"""""""""'"""""""'"""'""'"""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'"""'"""""""""'""'"""""""'"""'"""""""""'""'""'""'"""""""'"""'"""'""'""'"""'""'"""'"""""""""'"""""""'""'""'""'""'""'"""'"""'""'""'"""'""""""'"""'"""""""""'"""""""'"""'"""""""""'""'""'"""""""'"""'"""""""""'""'""'""'""'"""""""'"""'"""'""'""'"""'""'"""'"""""""""'"""""""'""'""'""'""'""'"""'""'""'"""'"""'"""""'""""""'""'""'""'""'"""'""""""""'"""""""'""'""'""'""'"""'""""'""""'"""""""""'"""""""'""'""'""'"""'""""""'""'""'""'"""'""'"""""""'""'""'""'"""'"""'""""""'""'""'"""'""'"""""""'""'""'"""'""""""'""'"""'""""""""'"""""""'""'"""'"""""'""""""'"""'""""""""'"""""""'"""'""""'""""'""""""'""'""'""'"""'""""""""'"""""""'""'""'""'"""'"""""""""'"""""""'""'""'"""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'"""'""""""'""'"""'""'"""""""'""'"""'""""""'""'"""""""'""""""""'"""'""'"""""""'""'"""'"""""'""""""""'""""""'""'""'""'"""'""'"""""""'""'""'""'"""'""""'""""""'""'"""'""""""""'"""""""'""'"""'""""""'""'""'"""'""'"""""""'""'""'"""'"""""'""""""""'""""""'""'"""'""'"""""""'""'"""'""""'""""""'"""'""'"""""""'""""""""'"""'"""""'""""""""'""""""""'""""""'"""'""""""""'""""""""'"""""""'"""'""""""'"""""""'"""'""'"""""""'"""""""'"""'"""""'""'""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""""'""""'""""'""""""'""'"""'""'""'""'""'""'""""""'"""'""'""'""'""'"""'"""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""'""""""""'"""'""""""""'""""""""'"""""""'""""""""'"""'"'"""""""""'""""""'""'""""""'"""'""'""'"""""""'"""'""""""""'"""""""'""'"""""""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""'"""'"""""""'"""""""'"""'""""""'""""""""'"""'""'""'"""""""'"""'"'"""""""'""'"""
>
>
>
This was an amazing challenge. Thank you for posting!
## Explanation
To get a feel for what Unreadable can and can’t do, imagine Brainfuck with an infinite tape in both directions, but instead of a memory pointer moving one cell at a time, you can access any memory cell by dereferencing a pointer. This comes in quite handy in this solution, although other arithmetic operations — including modulo — have to be done by hand.
Here is the program as pseudocode with director’s commentary:
```
// Initialize memory pointer. Why 5 will be explained at the very end!
ptr = 5
// FIRST PASS:
// Read all characters from stdin, store them in memory, and also keep track of the
// current line number at each character.
// We need the +1 here so that EOF, which is -1, ends the loop. We increment ptr by 2
// because we use two memory cells for each input character: one contains the actual
// character (which we store here); the other will contain the line number at which the
// character occurs (updated at the end of this loop body).
while ch = (*(ptr += 2) = read) + 1:
// At this point, ch will be one more than the actual value.
// However, the most code-economical way for the following loop is to
// decrement inside the while condition. This way we get one fewer
// iteration than the value of ch. Thus, the +1 comes in handy.
// We are now going to calculate modulo 4 and 5. Why? Because
// the mod 4 and 5 values of the desired input characters are:
//
// ch %5 %4
// ^ 1
// v 2
// k 3
// j 4
// ▲ 0 2
// ▼ 0 0
//
// As you can see, %5 allows us to differentiate all of them except ▲/▼,
// so we use %4 to differentiate between those two.
mod4 = 0 // read Update 2 to find out why mod5 = 0 is missing
while --ch:
mod5 = mod5 ? mod5 + 1 : -4
mod4 = mod4 ? mod4 + 1 : -3
// At the end of this loop, the value of mod5 is ch % 5, except that it
// uses negative numbers: -4 instead of 1, -3 instead of 2, etc. up to 0.
// Similarly, mod4 is ch % 4 with negative numbers.
// How many lines do we need to go up or down?
// We deliberately store a value 1 higher here, which serves two purposes.
// One, as already stated, while loops are shorter in code if the decrement
// happens inside the while condition. Secondly, the number 1 ('""") is
// much shorter than 0 ('""""""""'""").
up = (mod5 ? mod5+1 ? mod5+3 ? 1 : 3 : 2 : mod4 ? 3 : 1)
dn = (mod5 ? mod5+2 ? mod5+4 ? 1 : 3 : 2 : mod4 ? 1 : 3)
// As an aside, here’s the reason I made the modulos negative. The -1 instruction
// is much longer than the +1 instruction. In the above while loop, we only have
// two negative numbers (-3 and -4). If they were positive, then the conditions in
// the above ternaries, such as mod5+3, would have to be mod5-3 etc. instead. There
// are many more of those, so the code would be longer.
// Update the line numbers. The variables updated here are:
// curLine = current line number (initially 0)
// minLine = smallest linenum so far, relative to curLine (always non-positive)
// maxLine = highest linenum so far, relative to curLine (always non-negative)
// This way, we will know the vertical extent of our foray at the end.
while --up:
curLine--
minLine ? minLine++ : no-op
maxLine++
while --dn:
curLine++
minLine--
maxLine ? maxLine-- : no-op
// Store the current line number in memory, but +1 (for a later while loop)
*(ptr + 1) = curLine + 1
// At the end of this, minLine and maxLine are still relative to curLine.
// The real minimum line number is curLine + minLine.
// The real maximum line number is curLine + maxLine.
// The total number of lines to output is maxLine - minLine.
// Calculate the number of lines (into maxLine) and the real minimum
// line number (into curLine) in a single loop. Note that maxLine is
// now off by 1 because it started at 0 and thus the very line in which
// everything began was never counted.
while (++minLine) - 1:
curLine--
maxLine++
// Make all the row numbers in memory positive by adding curLine to all of them.
while (++curLine) - 1:
ptr2 = ptr + 1
while (ptr2 -= 2) - 2: // Why -2? Read until end!
*ptr2++
// Finally, output line by line. At each line, we go through the memory, output the
// characters whose the line number is 0, and decrement that line number. This way,
// characters “come into view” in each line by passing across the line number 0.
while (--maxLine) + 2: // +2 because maxLine is off by 1
ptr3 = 5
while (ptr -= 2) - 5:
print (*((ptr3 += 2) + 1) = *(ptr3 + 1) - 1) ? 32 : *ptr3 // 32 = space
ptr = ptr3 + 2
print 10 // newline
```
So much for the program logic. Now we need to **translate this to Unreadable** and use a few more interesting golfing tricks.
Variables are always dereferenced numerically in Unreadable (e.g. `a = 1` becomes something like `*(1) = 1`). Some numerical literals are longer than others; the shortest is 1, followed by 2, etc. To show just how much longer negative numbers are, here are the numbers from -1 to 7:
```
-1 '""""""""'""""""""'""" 22
0 '""""""""'""" 13
1 '""" 4
2 '""'""" 7
3 '""'""'""" 10
4 '""'""'""'""" 13
5 '""'""'""'""'""" 16
6 '""'""'""'""'""'""" 19
7 '""'""'""'""'""'""'""" 22
```
Clearly, we want to **allocate variable #1 to the one that occurs most frequently** in the code. In the first while loop, this is definitely `mod5`, which comes up 10 times. But we don’t need `mod5` anymore after the first while loop, so we can re-allocate the same memory location to other variables we use later on. These are `ptr2` and `ptr3`. Now the variable is referenced 21 times in total. (If you’re trying to count the number of occurrences yourself, remember to count something like `a++` twice, once for getting the value and once for setting it.)
There’s only one other variable that we can re-use; after we calculated the modulo values, `ch` is no longer needed. `up` and `dn` come up the same number of times, so either is fine. Let’s merge `ch` with `up`.
This leaves a total of 8 unique variables. We could allocate variables 0 to 7 and then start the memory block (containing the characters and line numbers) at 8. But! Since 7 is the same length in code as −1, we could as well use variables −1 to 6 and start the memory block at 7. This way, every reference to the start position of the memory block is slightly shorter in code! This leaves us with the following assignments:
```
-1 dn
0 ← ptr or minLine?
1 mod5, ptr2, ptr3
2 curLine
3 maxLine
4 ← ptr or minLine?
5 ch, up
6 mod4
7... [data block]
```
Now **this explains the initialization at the very top:** it’s 5 because it’s 7 (the beginning of the memory block) minus 2 (the obligatory increment in the first while condition). The same goes for the other two occurrences of 5 in the last loop.
Note that, since 0 and 4 are the same length in code, `ptr` and `minLine` could be allocated either way around. ... Or could they?
**What about the mysterious 2 in the second-last while loop?** Shouldn’t this be a 6? We only want to decrement the numbers in the data block, right? Once we reach 6, we’re outside the data block and we should stop! It would be a buffer overflow bug error failure security vulnerability!
Well, think about what happens if we don’t stop. We decrement variables 6 and 4. Variable 6 is `mod4`. That’s only used in the first while loop and no longer needed here, so no harm done. What about variable 4? What do you think, should variable 4 be `ptr` or should it be `minLine`? That’s right, `minLine` is no longer used at this point either! Thus, variable #4 is `minLine` and we can safely decrement it and do no damage!
**UPDATE 1!** Golfed from 2199 to 2145 bytes by realizing that `dn` can *also* be merged with `mod5`, even though `mod5` is still used in the calculation of the value for `dn`! New variable assignment is now:
```
0 ptr
1 mod5, dn, ptr2, ptr3
2 curLine
3 maxLine
4 minLine
5 ch, up
6 mod4
7... [data block]
```
**UPDATE 2!** Golfed from 2145 to 2134 bytes by realizing that, since `mod5` is now in the same variable as `dn`, which is counted to 0 in a while loop, `mod5` no longer needs to be explicitly initialized to 0.
**UPDATE 3!** Golfed from 2134 to 2104 bytes by realizing two things. First, although the “negative modulo” idea was worth it for `mod5`, the same reasoning does not apply to `mod4` because we never test against `mod4+2` etc. Therefore, changing `mod4 ? mod4+1 : -3` to `mod4 ? mod4-1 : 3` takes us to 2110 bytes. Second, since `mod4` is always 0 or 2, we can initialize `mod4` to 2 instead of 0 and reverse the two ternaries (`mod4 ? 3 : 1` instead of `mod4 ? 1 : 3`).
**UPDATE 4!** Golfed from 2104 to 2087 bytes by realizing that the while loop that calculates the modulo values always runs at least once, and in such a case, Unreadable allows you to re-use the last statement’s value in another expression. Thus, instead of `while --ch: [...]; up = (mod5 ? mod5+1 ? [...]` we now have `up = ((while --ch: [...]) ? mod5+1 ? [...]` (and inside that while loop, we calculate `mod4` first, so that `mod5` is the last statement).
**UPDATE 5!** Golfed from 2087 to 2084 bytes by realizing that instead of writing out the constants `32` and `10` (space and newline), I can store the number 10 in the (now unused) variable #2 (let’s call it `ten`). Instead of `ptr3 = 5` we write `ten = (ptr3 = 5) + 5`, then `32` becomes `ten+22` and `print 10` becomes `print ten`.
[Answer]
# Pyth, 27 bytes
```
jCm.<.[*5lzd\ =+Ztx"v ^k"dz
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=jCm.%3C.%5B%2a5lzd%5C+%3D%2BZtx%22v+%5Ek%22dz&input=%5E%5Ek%5Evjk%5E%5Ev&test_suite_input=%5E%5Ek%5Evjk%5E%5Ev%0Akv%5Ev%5Ev%5Ev%5Ev%5Ev%5Ev%5Evk%0A%5E%5E%5E%5E%5E%5E%5Ekkkjjjvvvvvv%0Av%5E%5Evv%5E%5Evvv%5Ev%5Ev%5E%5E%5Evvvv%5E%5Ev%5E%5Evv&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=jCm.%3C.%5B%2a5lzd%5C+%3D%2BZtx%22v+%5Ek%22dz&input=%5E%5Ek%5Evjk%5E%5Ev&test_suite=1&test_suite_input=%5E%5Ek%5Evjk%5E%5Ev%0Akv%5Ev%5Ev%5Ev%5Ev%5Ev%5Ev%5Evk%0A%5E%5E%5E%5E%5E%5E%5Ekkkjjjvvvvvv%0Av%5E%5Evv%5E%5Evvv%5Ev%5Ev%5E%5E%5Evvvv%5E%5Ev%5E%5Evv&debug=0)
I use `k` and `j` instead of `▲` and `▼`. There are lots of leading and trailing empty lines. You have to search quite a bit to find the image. Here's a **34 byte** version, that removes all leading and trailing empty lines.
```
j.sCm.<.[*5lzd\ =+Ztx"v ^k"dz]*lzd
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=j.sCm.%3C.%5B%2A5lzd%5C%20%3D%2BZtx%22v%20%5Ek%22dz%5D%2Alzd&input=%5E%5Ek%5Evjk%5E%5Ev&test_suite_input=%5E%5Ek%5Evjk%5E%5Ev%0Akv%5Ev%5Ev%5Ev%5Ev%5Ev%5Ev%5Evk%0A%5E%5E%5E%5E%5E%5E%5Ekkkjjjvvvvvv%0Av%5E%5Evv%5E%5Evvv%5Ev%5Ev%5E%5E%5Evvvv%5E%5Ev%5E%5Evv&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=j.sCm.%3C.%5B%2A5lzd%5C%20%3D%2BZtx%22v%20%5Ek%22dz%5D%2Alzd&input=%5E%5Ek%5Evjk%5E%5Ev&test_suite=1&test_suite_input=%5E%5Ek%5Evjk%5E%5Ev%0Akv%5Ev%5Ev%5Ev%5Ev%5Ev%5Ev%5Evk%0A%5E%5E%5E%5E%5E%5E%5Ekkkjjjvvvvvv%0Av%5E%5Evv%5E%5Evvv%5Ev%5Ev%5E%5E%5Evvvv%5E%5Ev%5E%5Evv&debug=0)
### Explanation:
```
jCm.<.[*5lzd\ =+Ztx"v ^k"dz implicit: Z = 0
m z map each char d from input string z to:
x"v ^k"d find d in the string "v ^k", -1 if not found
t -1, that gives -2 for j, -1 for v, 1 for ^ and 2 for k
=+Z add this number to Z
.[*5lzd\ append spaces on the left and on the right of d,
creating a 5*len(input_string) long string
.< Z rotate this string to the left by Z chars
jC transpose and print on lines
```
[Answer]
# CJam, 37 bytes
```
r_,2*:L3*S*f{\_iImd8-g\8>)*L+:L\t}zN*
```
This prints empty lines before and after the desired output, [which has been allowed by the OP](https://codegolf.stackexchange.com/questions/58759/this-question-has-its-ups-and-downs/58765?noredirect=1#comment141570_58759).
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r_%2C2*%3AL3*S*f%7B%5C_iImd8-g%5C8%3E)*L%2B%3AL%5Ct%7DzN*&input=%E2%96%BC%E2%96%BC).
### How it works
```
r_ e# Read a token from STDIN and push a copy.
,2*:L e# Compute its length, double it and save it in L.
3*S* e# Push a string of 6L spaces.
f{ e# For each character C in the input, push C and the string of spaces; then
\ e# Swap C with the string of spaces.
_i e# Push a copy of C and cast it to integer.
Imd e# Push quotient and remainder of its division by 18.
8-g e# Push the sign((C%18) - 8). Gives -1 for ^ and ▲, 1 for v and ▼.
\ e# Swap the result with the quotient.
8>) e# Push ((C/18) > 1) + 1. Gives 2 for ▲ and ▼, 1 for ^ and v.
* e# Multiply both results. This pushes the correct step value.
L+:L e# Add the product to L, updating L.
\t e# Replace the space at index L with C.
} e# We've built the columns of the output.
z e# Zip; transpose rows with columns.
N* e# Join the rows, separating by linefeeds.
```
[Answer]
## Python 2, 102
```
s=input()
j=3*len(s)
exec"w='';i=j=j-1\nfor c in s:i-='kv_^j'.find(c)-2;w+=i and' 'or c\nprint w;"*2*j
```
Prints line by line.
Loops through characters in the input and tracks the current height. The height is updated by one of `+2, +1, -1, -2` as computed by `'kv_^j'.find(c)-2`. There's probably a mod chain that's shorter
When the current height equals the line number (which can be negative), we append the current character to the line, and otherwise append a space. Then, we print the line. Actually, it's shorter to start the height at the current line number and subtract the height changes, appending the character when the value hits `0`.
The line numbers encompass a large enough range that a sequence of up-two or down-two will stay within it. Actually, there's a good amount of excess. If we had an upper bound on the input length, it would be shorter to write, say `j=999`.
Surprisingly, `i and' 'or c` was shorter than the usual `[' ',c][i==0]`. Note that `i` can be negative, which cuts out some usual tricks.
[Answer]
# MATLAB, 116
```
function o=u(a)
x=0;y=1;o='';for c=a b=find(c=='j^ vk')-3;y=y+b;if y<1 o=[zeros(1-y,x);o];y=1;end
x=x+1;o(y,x)=c;end
```
It's a start. The `j` and `k` make it a pain in the neck as I can't find a way to mathematically map from `j^vk` to `[-2 -1 1 2]` and with MATLAB not recognising the Unicode (apparently both up and down have a value of 26 in MATLAB. Go figure!), there are a lot of bytes wasted doing the mapping.
By drawing inspiration from @xnors solution, the code can be reduced by another 14 characters by mapping the control character inside the for loop.
There are also many bytes wasted trying to account for if the input string sends the pattern back below the index at which it started (maybe if there was a limit on the string length I could simplify that bit).
And in its readable form:
```
function o=u(a)
%We start in the top left corner.
x=0; %Although the x coordinate is 1 less than it should be as we add one before storing the character
y=1;
o=''; %Start with a blank array
for c=a
%Map the current character to [-2 -1 1 2] for 'j^vk' respectively.
b=find(c=='j^ vk')-3;
y=y+b; %Offset y by our character
if y<1 %If it goes out of range of the array
o=[zeros(1-y,x); o]; %Add enough extra lines to the array. This is a bit of a hack as 0 prints as a space in MATLAB.
y=1; %Reset the y index as we have now rearranged the array
end
x=x+1; %Move to the next x coordinate (this is why we start at x=0
o(y,x)=c; %Store the control character in the x'th position at the correct height.
end
```
[Answer]
# JavaScript (ES6), 140
Test running the snippet below in a EcmaScript 6 compliant browser (tested on Firefox)
.
```
f=s=>[...s].map(c=>{for(t=r[y+=c>'▲'?2:c>'v'?-2:c>'^'?1:-1]||x;y<0;y++)r=[,...r];r[y]=t+x.slice(t.length)+c,x+=' '},y=0,r=[x=''])&&r.join`
`
// Less golfed
f=s=>(
y=0,
x='',
r=[],
[...s].forEach( c =>
{
y += c > '▲' ? 2 : c > 'v' ? -2 : c > '^' ? 1 : -1;
t = r[y] || x;
while (y < 0)
{
y++;
r = [,...r]
}
r[y] = t + x.slice(t.length) + c;
x += ' '
}
),
r.join`\n`
)
//Test
;[
'^^▲^v▼▲^^v'
, '▲v^v^v^v^v^v^v^v▲'
, '^^^^^^^▲▲▲▼▼▼vvvvvv'
, 'v^^vv^^vvv^v^v^^^vvvv^^v^^vv'
].forEach(t=>document.write(`${t}<pre>${f(t)}</pre>`))
```
```
pre { border:1px solid #777 }
```
[Answer]
## GS2, 34 bytes
This one correctly calculates the output bounds so no excess whitespace is produced. Here's my solution in hex
```
5e 20 76 6a 05 3e 26 ea 30 e0 6d 40 28 26 cf d3
31 e9 d0 4d 42 5e e2 b1 40 2e e8 29 cf d3 5c e9
9a 54
```
A little explanation is in order. On the stack we have user input as an array of ascii codes. The program starts in a string literal because of the `05`. Here we go.
```
5e 20 76 6a # ascii for "^ vj"
05 # finish string literal and push to stack
3e # index - find index in array or -1 if not found
26 # decrement
ea # map array using block of 3 instructions (indented)
30 # add
e0 # create a block of 1 instruction
6d # scan (create running total array of array using block)
40 # duplicate top of stack
28 # get minimum of array
26 # decrement
cf # pop from stack into register D (this is the "highest" the path goes)
d3 # push onto stack from register D
31 # subtract
e9 # map array using block of 2 instructions
d0 # push onto stack from register A (unitialized, so it contains stdin)
4d # itemize - make singleton array (also is single char string)
42 # swap top two elements in stack
5e # rjust - right justify string
e2 # make block from 3 instructions
b1 # zipwith - evaluate block using parallel inputs from two arrays
40 # duplicate top of stack
2e # get length of array/string
e8 # map array using block of 1 instruction
29 # get maximum of array
cf # pop from stack into register D (this is the "lowest" the path goes)
d3 # push from register D onto stack
5c # ljust - left justify string
e9 # map array using block of two instructions
9a # transpose array of arrays
54 # show-lines - add a newline to end of each element in array
```
## GS2, 24 bytes
I also have a 24 byte solution that doesn't take as much care calculating output size, and ends up with extra whitespace. I prefer the one with the whitespace kept to a minimum though.
```
5e 20 76 6a 05 3e 26 ea 30 e0 6d d0 08 4d 42 d1
30 5e d1 5c 09 b1 9a 54
```
[Answer]
# [Crayon](https://github.com/ETHproductions/Crayon), 13 bytes (non-competing)
```
O"^ vj"\CynIq
```
[Try it online!](https://tio.run/nexus/crayon#@@@vFKdQ9mjaHqUY58o8z8L////HxT2atikOJAai48oA "Crayon – TIO Nexus") Uses the real arrows because why not.
Non-competing because Crayon is way newer than this challenge.
### How it works
Crayon is a stack-based language designed to be killer at ASCII-art challenges. It is built around the basis of a 2-dimensional output "canvas", and a "crayon", a cursor that travels around this canvas. Anything that is sent to output is drawn on the canvas at the position of the crayon, and in the direction the crayon is facing. By default, the crayon points East (to the right).
```
O"^ v▼"\CynIq Implicit: input string is on top of the stack
O For each char I in the input string:
"^ v▼" Push this string.
\ Swap the top two items (so I is on top).
C Take the index of I in the string.
This returns 3 for ▼, 2 for v, 0 for ^, and -1 for ▲.
y Move the crayon by this number of spaces on the Y-axis (south).
n Move the crayon one position north.
The crayon has now been translated 2 positions south for ▼,
1 south for v, 1 north for ^, and 2 north for ▲.
Iq Draw I at the crayon. This automatically moves the crayon forward
by the length of I, which is 1 in this case.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 30 bytes
```
↔T' z:mR' λm+a▼¹)∫m-2m€"v ^▲"¹
```
[Try it online!](https://tio.run/##yygtzv7//1HblBB1hSqr3CB1hXO7c7UTH03bc2in5qOO1bm6RrmPmtYolSnEPZq2SenQzv///5fFxZWBcVkcCIJZID6IAQA "Husk – Try It Online") or [Verify all tests](https://tio.run/##yygtzv6fm39o26Omxv@P2qaEqCtUWeUGqSuc252rnfho2p5DOzUfdazO1TXKfdS0RqlMIe7RtE1Kh3b@//8/WikOxIkrA6oC0XFlSjpKQEZZHAoEqdcBKgUDIAeG9kBQGRgAVZQBDQBjiD4wC8QHMZRiAQ "Husk – Try It Online")
Uses a few ideas from the Pyth answer, and the lambda can be shortened.
Since `▲` and `▼` are in Husk's codepage, you can see the testcases in their full glory!
## Explanation
```
↔T' z:mR' λm+a▼¹)∫m-2m€"v ^▲"¹
m€"v ^▲" get the indices of each char in the string
m-2 subtract 2 from each
∫ cumulative sum
λm+a▼¹) add abs(minimum) to each
mR' map each n to n spaces
z: join the spaces with the input
T' Transpose. padding with spaces
↔ reverse
```
[Answer]
# [pb](https://esolangs.org/wiki/pb) - 136 bytes
```
^w[B!0]{>}v[3*X]<[X]<b[1]^[Y]^>w[B!0]{t[B]<vw[B=0]{v}>w[T=107]{^^b[T]t[0]}w[T=94]{^b[T]t[0]}w[T=118]{vb[T]t[0]}w[T!0]{vvb[T]t[0]}^[Y]^>}
```
Uses `k` and `j` instead of `▲` and `▼`.
A couple of notes:
* `Escape sequences that move the cursor such as \e[B are not allowed. You must produce the output using spaces and newlines.` I do follow this rule! pb uses the concept of a "brush" to output characters. The brush moves around the "canvas" and can print a character immediately below it. However, the actual implementation prints the character using spaces and newlines.
* I wasn't going to bother with this challenge even though I thought it would be fun with pb until I saw the ruling that `You are allowed trailing spaces and/or empty lines`. This is for a couple of reasons:
+ pb can't *not* have trailing spaces. It always produces rectangular output, padding with spaces if necessary.
+ This program produces a lot of empty lines. It doesn't know how tall the output is going to be when it starts making it, so for an input of length `n` it starts at `Y=3n+1`. The `-1` is because it's going down `3n` from `Y=-1`, and starting at `Y=2n-1` fails for an input of all `k`.
[You can watch this program in action on YouTube!](https://www.youtube.com/watch?v=8k1M4yX4BUE) This version is slightly modified in that it only goes down to `n-1`. It works for this input, but will fail for others. It does, however, capture a lot nicer.
With comments:
```
^w[B!0]{>} # Go to the end of the input
v[3*X] # Go down 3 times the current X value
<[X]< # Go to X=-1 (off screen, won't be printed)
b[1] # Leave a non-zero value to find later
^[Y]^> # Back to the beginning of the input
w[B!0]{ # For every byte of input:
t[B] # Copy it to T
<vw[B=0]{v}> # Go 1 to the right of the character to the left
# (either the last one printed or the value at X=-1)
# Move the correct amount for each character and print it:
w[T=107]{^^b[T]t[0]} # k
w[T=94]{^b[T]t[0]} # ^
w[T=118]{vb[T]t[0]} # v
w[T!0]{vvb[T]t[0]} # j (Every other possibility sets T to 0, so if T is not 0
# it must be j. T!0 is shorter than T=106)
^[Y]^> # To the next byte of input to restart the loop
}
```
[Answer]
# Ceylon, 447 bytes
```
import ceylon.language{o=null,v=variable,s=shared}s void y(){v L c;v L f;v L l;v Integer i=0;class L(v L?p,v L?n){s v String t="";s L u=>p else(f=p=L(o,this));s L d=>n else(l=n=L(this,o));s void a(Character c)=>t=t+" ".repeat(i-t.size)+c.string;}f=l=c=L(o,o);for(x in process.readLine()else""){switch(x)case('^'){c=c.u;}case('v'){c=c.d;}case('▲'|'k'){c=c.u.u;}case('▼'|'j'){c=c.d.d;}else{}c.a(x);i++;}print(f.t);while(f!=l){f=f.d;print(f.t);}}
```
Or with line breaks for "readability":
`import ceylon.language{o=null,v=variable,s=shared}s void y(){v L c;v L f;v L l;v Integer i=0;class L(v L?p,v L?n){s v String t="";s L u=>p else(f=p=L(o,this));s L d=>n else(l=n=L(this,o));s void a(Character c)=>t=t+" ".repeat(i-t.size)+c.string;}f=l=c=L(o,o);for(x in process.readLine()else""){switch(x)case('^'){c=c.u;}case('v'){c=c.d;}case('▲'|'k'){c=c.u.u;}case('▼'|'j'){c=c.d.d;}else{}c.a(x);i++;}print(f.t);while(f!=l){f=f.d;print(f.t);}}`
This works with both the ▲/▼ and the j/k input (If we had to support just one of them, the program would be 8 bytes shorter). The last output line is empty when the starting position was on it (i.e. the first input was a `▲` or `^` and we never got below that again later).
Input which is not one of the specified characters will simply be printed as-is, without switching the line:
```
v^^vv^^vvv^v^v^^^Hellovvvv^^v^^vv
```
→
```
^ ^ ^Hello
^ v ^ v ^ v ^
v v v ^ ^ ^ v ^ ^ v
v v v v ^ v v
v
```
Here is a formatted version (753 bytes):
```
shared void y() {
variable L c;
variable L f;
variable L l;
variable Integer i = 0;
class L(variable L? p, variable L? n) {
shared variable String t = "";
shared L u => p else (f = p = L(null, this));
shared L d => n else (l = n = L(this, null));
shared void a(Character c) => t = t + " ".repeat(i - t.size) + c.string;
}
f = l = c = L(null, null);
for (x in process.readLine() else "") {
switch (x)
case ('^') { c = c.u; }
case ('v') { c = c.d; }
case ('▲' | 'k') { c = c.u.u; }
case ('▼' | 'j') { c = c.d.d; }
else {}
c.a(x);
i++;
}
print(f.t);
while (f != l) {
f = f.d;
print(f.t);
}
}
```
This is an almost straight-forward "object-oriented" program ... the (local) class `L` (line buffer) stores a line of text (in `t`), as well as (nullable) pointers to the next (`n`) and previous (`p`) line. The (not nullable) attributes `u` (for up) and `d` (for down) initialize those if needed (with a reverse pointer to itself), and in this case also keep track of the first and last line overall (in the `f` and `l` variables).
The `a` (append) method appends a character to this line, including some spaces eventually necessary.
`c` is the current line. We parse the input string (using `readLine` as the input should be on one line) using a switch statement which updates the current line, and then calls the append method.
After parsing is done, we iterate over the lines from the first to the last, printing each of them. (This destroys the `f` pointer, if it were needed afterwards, we should have used a separate variable for this.)
Some used tricks for golfing:
* Some stuff which in other languages would be keywords are actually just identifiers in the `ceylon.language` package, and can be renamed with an alias import – we used this for the annotations `shared` (used 5×) and `variable` (used 6×), as well as for the object `null` (used 4×):
```
import ceylon.language{o=null,v=variable,s=shared}
```
(Trivia: The Formatter in the Ceylon IDE formats some built-in language annotations, between them `variable` and `shared`, by putting them in the same line as the annotated declaration, contrasted to custom annotations, which are put on a separate line above the declaration. This makes the formatted version of the golfed program unreadable, therefore I changed the alias-imports back for this version.)
`this`, `void`, `case`, `else` are actual keywords and cannot be renamed this way, and `Integer`, `String` and `Character` appear just once each, so there is nothing to be gained by importing.
* Originally I also had a separate ScreenBuffer class (which kept track of the linked list of line buffers, the current index, and so on), but as there was only ever one object of it, it was optimized away.
* That Screenbuffer class also had `up` and `down` methods, which were called from the parser (and just did `currentLine = currentLine.up` respectively `currentLine = currentLine.down`). It showed that directly doing this in the parser's switch is shorter. It also allowed to write `currentLine = currentLine.up.up` (which later became `c = c.u.u`) instead of `currentLine = currentLine.up;currentLine = currentLine.up`.
* Originally we did pass the current index as an argument into the append method (and even to the parser from the loop) – having it a variable in the containing function is shorter.
* Originally my printAll method used the current pointer and moved it first up until the current line was empty, and then down while printing each line. This broke when using ▲ and ▼ to jump over lines, so we had to explicitly append something in those jumped lines instead. Keeping track of first/last line proved easier (though it made it necessary to use two print statements, because there is no do-while-loop in Ceylon).
* Originally I had something like this:
```
String? input = process.readLine();
if(exists input) {
for(x in input) {
...
}
}
```
[`process.readLine`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/process.object.html#readLine) returns `null` if there is no line which can be read (because the input has been closed), and the Ceylon compiler requires me to checkfor that before I access `input`. As in this case I want to do nothing, I can equivalently use the `else` operator which returns its first argument if not null, and otherwise its second argument, saving the variable and the if-statement. (This also would allow us to encode a default input for testing: `for (x in process.readLine() else "^^▲^v▼▲^^v") {`)
[Answer]
# JavaScript (ES6), 228 bytes
```
E=(r,p=(' '[M='repeat'](Z=r.length)+',')[M](Z*4),i=Z*2,k=0)=>Z>k?E(r,(p.split(',').map((o,q)=>q==i?o.slice(0,k)+r[k]+o.slice(k++):o)).join`,`,i+(H={'^':-1,k:-2,j:2,v:1})[r[k]],k):p.split(',').join`
`.replace(/\s+\n$|^\s+\n/g,'')
```
Well, here is a (rather long) recursive solution that passes all of the test cases given. It was a nice challenge. This uses `k` and `j` in place of `▼` and `▲`.
## Test Snippet
Although the submission itself can only handle `k,j`, the following snippet can handle both `k,j` and `▼,▲`.
```
E=(r,p=(' '[M='repeat'](Z=r.length)+',')[M](Z*4),i=Z*2,k=0)=>Z>k?E(r,(p.split(',').map((o,q)=>q==i?o.slice(0,k)+r[k]+o.slice(k++):o)).join`,`,i+(H={'^':-1,k:-2,j:2,v:1})[r[k]],k):p.split(',').join`
`.replace(/\s+\n$|^\s+\n/g,'')
```
```
Input: <input type="text" oninput=o.textContent=E(this.value.replace(/▲/g,'k').replace(/▼/g,'j'))></input>
<pre id='o'></pre>
```
] |
[Question]
[
Given only a straightedge and compass, inscribe a rhombus inside the given rectangle, sharing two opposite points.
[![rhombus-in-rectangle](https://i.stack.imgur.com/Yv2lq.png)](https://i.stack.imgur.com/Yv2lq.png)
### Input
Input is the dimensions of the rectangle. In the example shown, that would be `125, 50`. You can take input in whatever way is most convenient (as two integers, list, strings, etc).
The larger dimension will be 100 minimum, while the smaller will be 25 minimum. Both cap at 200.
### Output
Output will be an image (displayed on screen or saved as a file) showing
* The input rectangle
* All "working" lines/circles
* The inscribed rhombus
in distinct colors. In the image above, The rectangle is black, working lines blue, and rhombus orange. The lines should be drawn in the order shown in the list (eg rhombus overwrites working lines and rectangle).
The output image needs to be large enough to contain everything. For example, the circles shown cannot go out of bounds.
### Method
The method used in the example image above is:
* Draw a circle using the lower left corner as center, and the upper right as a point on the perimeter, giving a radius equal to the rectangle's diagonal.
* Do the same, but swapping center and perimeter points.
* Draw a line between the intersections of the two circles, giving a perpendicular bisector to the rectangle's diagonal.
* Use the intersections of the new line and rectangle to draw the rhombus.
This works because the interior diagonals of a rhombus always perpendicularly bisect each other. I'm not including a full proof of this here, though.
This is not the *only* method to get your rhombus, and you can use another, given that you explain what you are doing. I *believe* it's probably the easiest, though.
### Rules
You can only draw circles and lines (or rather, line segments). A circle is defined with a center point and perimeter point. A line is defined by any two points. Lines do not have to be any specified length, but they must *at least* cover the defining points (note the example image: the line goes a bit past the circle intersections, but not to the edge). For circles, the radius from center to the chosen perimeter point is considered a working line, and must be shown.
To rasterize the lines, you can use any recognized algorithm (e.g. Bresenham's), or rely on whatever builtins your language might have. If your output is vector-based, please ensure that it is show at a resolution *at least* as large as the input rectangle in pixels. Also, you'll be drawing on a plain canvas, so please suppress any grid marks or extraneous output.
No cheating! You can only determine placement of points/lines/circles using what you've established so far. If you can't explain how to use your working lines/circles to show it's a rhombus, you're doing it wrong.
You can use whichever pair of opposite points you want, and the rectangle does not *need* to be drawn axis-aligned, so long as the output is correct.
Input will always be a non-square rectangle, so don't worry about special-casing that.
Lastly, this is standard code golf, so lowest size in bytes wins.
[Answer]
## HTML + JavaScript (ES6), 34 + 353 = 387 bytes
Input should be given in the format `[125,50]`.
```
[w,h]=eval(prompt(c=C.getContext("2d"))).sort();d=q=>(c.strokeStyle=q,b);l=(x,y=Z)=>x?c.lineTo(x,y)||l:c.stroke();b=(x,y=H,r)=>(c.beginPath(),r?c.arc(x,y,Math.sqrt(r),0,2*Math.PI):c.moveTo(x,y),l);b(Z=300,Z)(W=Z+w)(W,H=Z+h)(Z,H)(Z)();d`red`(Z,H,s=w*w+h*h)();b(W,Z,s)();b(Z)(W)();b(Z+w/2-h,Z+h/2-w)(H+w/2,W+h/2)();d`lime`(Z)(W-s/2/w)(W)(Z+s/2/w,H)(Z,H)()
```
```
<canvas id=C width=800 height=800>
```
Just a lot of math and drawing... The rectangle is drawn sideways if the height is greater than the width, which I believe is allowed.
[Answer]
# Mathematica, ~~157~~ ~~148~~ 158 bytes
*Thanks to Martin Ender for comments with their usual high quality! 9 bytes saved in this case.*
*Edited once it was clarified that the arguments can come in either order; 10 bytes added to compensate.*
```
Graphics@{(m=Line)@{o=0{,},{#,0},c={##},{0,#2},o},Blue,m[l={o,c}],Circle[#,(c.c)^.5]&/@l,m[{k={#2,-#},-k}+{c,c}/2],Red,m@{o,p={0,c.c/2/#2},c,c-p,o}}&@@Sort@#&
```
Again, this is where Mathematica shines: high-level graphics output involving mathematical computation. The same code with spaces and newlines for human readability:
```
Graphics@{
(m=Line)@{o = 0{,}, {#, 0}, c = {##}, {0, #2}, o},
Blue, m[l = {o, c}], Circle[#, (c.c)^.5] & /@ l,
m[{k = {#2, -#}, -k} + {c, c}/2],
Red, m@{o, p = {c.c/2/#2, 0}, c, c - p, o}
} & @@ Sort@# &
```
Unnamed function of a single argument which is an ordered pair of positive numbers; the final `@@ Sort@# &` converts that pair into two numerical arguments where the first number is the smaller. `Line` produces a polygonal path from point to point, which will turn into a closed polygon if the first and last points are the same; `Circle` produces a circle with given center and radius. Special points `o` and `c` (the lower-left and upper-right rectangle corners), `p` (a third rhombus corner, given by a mathematical formula), and `k` (helping to draw the perpendicular bisector) are given names along the way to save bytes when called again, as is the special pair of points `l = {o,c}`. Mathematica is happy to add points directly, multiply both coordinates by the same factor, take their dot product, etc., all of which simplify the code.
Sample output, with arguments `125` and `50`:
[![enter image description here](https://i.stack.imgur.com/W62hL.jpg)](https://i.stack.imgur.com/W62hL.jpg)
[Answer]
# MetaPost, 473 (with color) 353 (without color)
## Colored (473 bytes):
```
A:=170;B:=100;pair X,Y;path C,D,E,F,G,R,T;X=(0,0);Y=(A,B);R=X--(A,0)--Y--(0,B)--cycle;T=(0,B)--(A,B);draw R;E=X--Y;C=X..Y*2..cycle;D=Y..-Y..cycle;F=(D intersectionpoint C)--(C intersectionpoint D);draw C withcolor green;draw D withcolor green;draw E withcolor red;draw F withcolor red;draw (F intersectionpoint R)--Y withcolor blue;draw X--(F intersectionpoint T) withcolor blue;draw (F intersectionpoint T)--Y withcolor blue;draw (F intersectionpoint R)--X withcolor blue;
```
## Noncolored (353 bytes):
```
A:=170;B:=100;pair X,Y;path C,D,E,F,G,R,T;X=(0,0);Y=(A,B);R=X--(A,0)--Y--(0,B)--cycle;T=(0,B)--(A,B);draw R;E=X--Y;C=X..Y*2..cycle;D=Y..-Y..cycle;F=(D intersectionpoint C)--(C intersectionpoint D);draw C;draw D;draw E;draw F;draw (F intersectionpoint R)--Y;draw X--(F intersectionpoint T);draw (F intersectionpoint T)--Y;draw (F intersectionpoint R)--X;
```
Never EVER used this before, and I'm sure I butchered it...
But when you run that on this website:
<http://www.tlhiv.org/mppreview/>
It uses the intersection of the circles to draw the second axis, and then uses the intersection of the axis and the rectangle to draw the final rhombus. Though I could've cheated and just drawn a line perpendicular to the first axis haha.
To change the dimensions, just alter A and B.
Regardless, you end up with (for L=170, H=100):
[![Image](https://i.stack.imgur.com/kIbXg.png)](https://i.stack.imgur.com/kIbXg.png)
[Answer]
## Desmos, 375 (or 163) bytes
```
w=125
h=50
\left(wt,\left[0,h\right]\right)
\left(\left[0,w\right],ht\right)
\left(x-\left[0,w\right]\right)^2+\left(y-\left[0,h\right]\right)^2=w^2+h^2
\frac{h}{w}x\left\{0\le x\le w\right\}
-\frac{w}{h}\left(x-\frac{w}{2}\right)+\frac{h}{2}
a=\frac{h^2}{2w}+\frac{w}{2}
\left(t\left(w-a\right)+\left[0,1\right]a,ht\right)
\left(at-\left[0,a-w\right],\left[0,h\right]\right)
```
`w` and `h` are the inputs. [Try it on Desmos!](https://www.desmos.com/calculator/aa4g6dlkwx)
**Alternate 163-byte version:**
```
w=125
h=50
(wt,[0,h])
([0,w],ht)
(x-[0,w])^2+(y-[0,h])^2=w^2+h^2
hx/w\left\{0\le x\le w\right\}
-w(x-w/2)/h+h/2
a=h^2/2/w+w/2
(t(w-a)+[0,1]a,ht)
(at-[0,a-w],[0,h])
```
This version requires each line to be copy and pasted into each separate line into Desmos. Meta still needs to decide if this is a valid counting method, but the former method is definitely fine.
[Answer]
# ImageMagick Version 7.0.3 + bash + sed, 496 bytes
```
M=magick
L=$((400-$(($1))/2)),$((400+$(($2))/2))
R=$((400+$(($1))/2)),$((400-$(($2))/2))
Z=" $L $R" Y=" -1 x";D=' -draw' K=' -stroke'
A=' -strokewidth 3 +antialias -fill'
$M xc:[800x]$A none$K \#000$D "rectangle$Z"$D "line$Z"$K \#00F8$D "circle$Z"$K \#0F08$D "circle $R $L" -depth 8 png:a
$M a txt:-|sed "/38C/!d;s/:.*//">x;P=`head$Y`;Q=`tail$Y`
$M a$A \#F008$K \#F008$D "line $P $Q" b
$M b txt:-|sed "/C70/!d;s/:.*//">x;S=`head$Y`;T=`tail$Y`
$M b$A \#F804$K \#F80$D "polyline $L $S $R $T $L" x:
```
# Result with "rhombus.sh 180 120"
[![enter image description here](https://i.stack.imgur.com/s1pnp.png)](https://i.stack.imgur.com/s1pnp.png)
# More precise (using 6400x6400 canvas instead of 800x800), 570 bytes
The intersections aren't exact; the "strokewidth" directive makes the lines wide enough to make sure at least one entire pixel gets mixed with just the colors of the two intersecting lines, but in the worst cases (25x200 and 200x25) the crossings are at a small angle so the cloud of mixed pixels is several pixels long, and since we select the first and last mixed pixel, there is a slight error. Using an 8x larger canvas with the same strokewidth and then scaling the result down reduces the error to less than one pixel, but at about a 64x time penalty.
```
M=magick
L=$((3200-$(($1))*4)),$((3200+$(($2))*4))
R=$((3200+$(($1))*4)),$((3200-$(($2))*4))
K=-stroke;A='-strokewidth 3 +antialias'
$M xc:[6400x] $A -fill none $K \#000 -draw "rectangle $L $R" \
-draw "line $L $R" $K \#00F8 -draw "circle $L $R" \
$K \#0F08 -draw "circle $R $L" -depth 8 png:a
$M a txt:-|grep 38C077|sed -e "s/:.*//p">x
P=`head -1 x`;Q=`tail -1 x`
$M a $A -fill \#F008 $K \#F008 -draw "line $P $Q" png:b
$M b txt:-|grep C70000|sed -e "s/:.*//p">x
S=`head -1 x`;T=`tail -1 x`
$M b $A -fill \#F804 $K \#F80 -draw "polyline $L $S $R $T $L" -resize 800 x:
```
# Results of normal 800x800 versus precise 6400x6400:
[![normal vs precise results](https://i.stack.imgur.com/mqYbq.png)](https://i.stack.imgur.com/mqYbq.png)
# Ungolfed:
```
# rhombus.sh
# Inscribe a rhombus in the rectangle with dimensions 2*$1, 2*$2
# Run with "rhombus.sh W H"
M=magick
W=${1:-100};H=${2:-40}
# L locates the lower left corner of the rectangle
L=$((400-$((W))/2)),$((400+$((H))/2))
# R locates the upper right corner of the rectangle
R=$((400+$((W))/2)),$((400-$((H))/2))
# We'll need this several times
A='-strokewidth 3 +antialias'
# Establish 800x800 canvas (white) (circles + rectangle will
# always fit in 764x764)
#
# Draw the W x H rectangle (black) in center of canvas
#
# Draw two circles (blue, 50% alpha [#00F8] and green, 50% alpha [#0F08])
# one centered at point L with peripheral point R
# the other centered at point R with peripheral point L
$M xc:[800x] $A -fill none \
-stroke \#000 -draw "rectangle $L $R" \
-draw "line $L $R" \
-stroke \#00F8 -draw "circle $L $R" \
-stroke \#0F08 -draw "circle $R $L" \
-depth 8 a.png
# Find P and Q, the 2 intersections of the circles,
# that have mixed color #38C077
$M a.png txt:-|grep 38C077|sed -e "s/:.*//p">x
P=`head -1 x`;Q=`tail -1 x`
# Draw line connecting the intersections P and Q
$M a.png $A -fill \#F008 -stroke \#F008 -draw "line $P $Q" b.png
# Find S and T, the 2 intersections of the line with the original rectangle,
# that have mixed color #C70000
$M b.png txt:-|grep C70000|sed -e "s/:.*//p">x
S=`head -1 x`;T=`tail -1 x`
# Draw the rhombus
$M b.png $A -fill \#F804 -stroke \#F80 -draw "polyline $L $S $R $T $L" d.png
```
[Answer]
# R, 290 bytes
```
function(A,B,p=polygon){R=A^2+B^2
D=2*A
a=sqrt(R)*cbind(cos(t<-seq(0,2*pi,.01)),sin(t))
b=t(t(a)+c(A,B))
x=range(a,b)
plot(NA,xli=x,yli=x,as=1,ax=F,an=F)
rect(0,0,A,B)
segments(0,0,A,B,c=4)
p(a,b=4)
p(b,b=4)
curve(B/2-A*x/B+A^2/2/B,co=4,a=T)
p(cbind(c((R-2*B^2)/D,A,R/D,0),c(B,B,0,0)),b=3)}
```
Anonymous function, output is displayed on screen.
Slightly ungolfed, with comments:
```
function(A,B){
R=A^2+B^2
D=2*A
t=seq(0,2*pi,.01)
a=sqrt(R)*cbind(cos(t),sin(t)) #Circle with (0,0) as center
b=t(t(a)+c(A,B)) #Second circle transposed to (A,B) center
x=range(a,b)
#Empty plot, large enough to fit the 2 circles:
plot(NA,xlim=x,ylim=x,asp=1,axes=F,ann=F)
rect(0,0,A,B) #Initial rectangle
segments(0,0,A,B,col=4) #Rectangle diagonal
polygon(a,border=4) #Circle 1 (border is b thanks to partial matching)
polygon(b,border=4) #Circle 2
curve(B/2-A*x/B+A^2/2/B,col=4,add=T) #Line joining circles intersection
polygon(cbind(c((R-2*B^2)/D,A,R/D,0),c(B,B,0,0)),border=3) #Rhombus
}
```
Example output for (120,100):
[![enter image description here](https://i.stack.imgur.com/0fIqC.png)](https://i.stack.imgur.com/0fIqC.png)
[Answer]
# [LibreLogo](https://help.libreoffice.org/Writer/LibreLogo_Toolbar#LibreLogo_programming_language), 270 bytes
>
> User input is taken as an array: `[width, height]` or `[height, width]`.
>
>
>
**Code:**
```
fc [24]
D=180
R=sorted(eval(input "))
W=R[1]
H=R[0]
L=sqrt W**2+H**2
A=D/π*asin(H/L)
Z=A*2
S=L/2/cos A*π/D rectangle[W,H]pc 255 lt A fd 400 bk 800 fd 400 rt A pu bk H/2 lt 90 fd W/2 pd circle L*2 rt D-A fd L circle L*2 pc [5]lt D-A fd S lt Z fd S rt D+Z fd S lt Z fd S
```
**Result:**
[![enter image description here](https://i.stack.imgur.com/meEVA.gif)](https://i.stack.imgur.com/meEVA.gif)
**Explanation:**
```
fc [24] ; Fill Color = Invisible
D = 180 ; D = 180° (Saved Bytes)
R = sorted( eval( input " ) ) ; R = Sorted Array of Rectangle Width and Height (User Input)
W = R[1] ; W = Rectangle Width
H = R[0] ; H = Rectangle Height
L = sqrt W**2 + H**2 ; L = Rectangle Diagonal Length
A = D / π * asin( H / L ) ; A = Rectangle Diagonal Angle°
Z = A * 2 ; Z = Rectangle Diagonal Angle° * 2 (Saved Bytes)
S = L / 2 / cos A * π / D ; S = Rhombus Side Length
rectangle [W, H] ; Draw Rectangle
pc 255 ; Pen Color = Blue
lt A ; Left = Rectangle Diagonal Angle°
fd 400 ; Forward = 400 pt
bk 800 ; Back = 800 pt
fd 400 ; Forward = 400 pt
rt A ; Right = Rectangle Diagonal Angle°
pu ; Pen Up
bk H / 2 ; Back = Rectangle Height / 2
lt 90 ; Left = 90°
fd W / 2 ; Forward = Rectangle Width / 2
pd ; Pen Down
circle L * 2 ; Draw Left Circle (Radius = Rectangle Diagonal Length)
rt D - A ; Right = 180° - Rectangle Diagonal Angle°
fd L ; Forward = Rectangle Diagonal Length
circle L * 2 ; Draw Right Circle (Radius = Rectangle Diagonal Length)
pc [5] ; Pen Color = Red
lt D - A ; Left = 180° - Rectangle Diagonal Angle°
fd S ; Forward = Rhombus Side Length
lt Z ; Left = Rectangle Diagonal Angle° * 2
fd S ; Forward = Rhombus Side Length
rt D + Z ; Right = 180° + Rectangle Diagonal Angle° * 2
fd S ; Forward = Rhombus Side Length
lt Z ; Left = Rectangle Diagonal Angle° * 2
fd S ; Forward = Rhombus Side Length
```
[Answer]
# Python 3.5 + Tkinter, 433 or 515 bytes
## Non-Colored (433 bytes):
```
from tkinter import*
def V(a,b):S=500;Y,Z=S+a,S-b;M=(a**2+b**2)**0.5;D=Tk();C=Canvas(D);B=C.create_oval;X=C.create_line;B(S+M,S-M,S-M,S+M);B(Y-M,Z+M,Y+M,Z-M);X(Y,Z,S,S);C.create_rectangle(Y,S,S,Z);Q=-((Z-S)/(Y-S))**-1;U,V=(Y+S)/2,(Z+S)/2;X(U+M,V+M*Q,U-M,V-M*Q);P=[(Y,Q*(Y-U)+V),(((Z-V)/Q)+U,Z)][a>b];L=[(S,Q*(S-U)+V),(((S-V)/Q)+U,S)][a>b];X(S,S,P[0],P[1]);X(Y,Z,P[0],P[1]);X(Y,Z,L[0],L[1]);X(S,S,L[0],L[1]);C.pack(fill=BOTH,expand=1)
```
## Colored (515 bytes):
```
from tkinter import*
def V(a,b):S=500;t='blue';Y,Z=S+a,S-b;M=(a**2+b**2)**0.5;D=Tk();C=Canvas(D);B=C.create_oval;X=C.create_line;B(S+M,S-M,S-M,S+M,outline=t);B(Y-M,Z+M,Y+M,Z-M,outline=t);X(Y,Z,S,S,fill=t);C.create_rectangle(Y,S,S,Z);Q=-((Z-S)/(Y-S))**-1;U,V=(Y+S)/2,(Z+S)/2;X(U+M,V+M*Q,U-M,V-M*Q,fill=t);P=[(Y,Q*(Y-U)+V),(((Z-V)/Q)+U,Z)][a>b];L=[(S,Q*(S-U)+V),(((S-V)/Q)+U,S)][a>b];o='orange';X(S,S,P[0],P[1],fill=o);X(Y,Z,P[0],P[1],fill=o);X(Y,Z,L[0],L[1],fill=o);X(S,S,L[0],L[1],fill=o);C.pack(fill=BOTH,expand=1)
```
A named function that takes input as 2 comma-separated numbers. The output is given in a separate window that you may have to resize to see the full output. Here is a sample colored output for `V(180,130)`:
[![Sample Output](https://i.stack.imgur.com/nfh13.png)](https://i.stack.imgur.com/nfh13.png)
[Answer]
# SmileBASIC, 280 bytes
```
INPUT W,H
W=MAX(W,H)/4H=MIN(W,H)/4D=SQR(W*W+H*H)N=D+W
M+D+H
GBOX D,D,N,M,#RED
GCIRCLE D,M,D
GCIRCLE N,D,D
GLINE D,M,N,D
X=D+W/2Y=D+H/2A=ATAN(W,H)E=D*H/W/2S=E*COS(A)T=E*SIN(A)GLINE X-S*9,Y-T*9,X+S*9,Y+T*9GCOLOR-#L
GLINE D,M,X-S,Y-T
GLINE D,M,X+S,M
GLINE N,D,X+S,Y+T
GLINE N,D,X-S,D
```
(Screenshot/explanation will be posted soon)
Background color is black, rectangle is red, circles and lines are white, and the rhombus is yellow.
] |
[Question]
[
>
> [Robber's Thread here](https://codegolf.stackexchange.com/questions/140794/im-thinking-of-a-number-robbers-thread)
>
>
>
In this [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge cops will think of a positive integer. They will then write a program or function that outputs one value when provided the number as input and another value for all other positive integer inputs. Cops will then reveal the program in an answer keeping the number a secret. Robbers can crack an answer by finding the number.
Here's the catch: this is *not* [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), instead your score will be the secret number with a lower score being better. Obviously you cannot reveal your score while robbers are still trying to find it. An answer that has not been cracked one week after its posting may have its score revealed and be marked safe. Safe answers cannot be cracked.
It probably goes without saying but you should be able to score your answer. That is you should know exactly what value is accepted by your decision machine. Simply knowing that there is one is not enough.
## Use of Cryptographic functions
Unlike most cops and robbers challenge which ask you not to use cryptographic functions, this challenge not only entirely allows them but encourages them. You are free to create answers in any way as long as you are trying to win. That being said, answers using other methods are also welcome here. The goal of the challenge is to win, and as long as you don't cheat nothing is off the table.
[Answer]
# [Tampio](https://github.com/fergusq/tampio), [Cracked](https://codegolf.stackexchange.com/a/140954/66323)
```
m:n tulos on luvun funktio tulostettuna m:ään, missä luku on x:n kerrottuna kahdella seuraaja, kun x on luku m:stä luettuna
x:n funktio on luku sadalla kerrottuna sadalla salattuna, missä luku on x alempana sadan seuraajaa tai nolla
x:n seuraajan edeltäjä on x
x:n negatiivisena edeltäjä on x:n seuraaja negatiivisena
nollan edeltäjä on yksi negatiivisena
x salattuna y:llä on örkin edeltäjä, missä örkki on x:n seuraajan seuraaja jaettuna y:llä korotettuna kahteen
sata on kiven kolo, missä kivi on kallio katkaistuna maanjäristyksestä
kallio on yhteenlasku sovellettuna mannerlaatan jäseniin ja tulivuoren jäseniin
tulivuori on nolla lisättynä kallioon
mannerlaatta on yksi lisättynä mannerlaattaan
maanjäristys on kallion törmäys
a:n lisättynä b:hen kolo on yhteenlasku kutsuttuna a:lla ja b:n kololla
tyhjyyden kolo on nolla
x:n törmäys on x tutkittuna kahdellatoista, missä kaksitoista on 15 ynnä 6
x ynnä y on y vähennettynä x:stä
```
Run with:
```
python3 suomi.py file.suomi --io
```
The instructions for installing the interpreter are included in the Github page. Please tell if you have any difficulties running this.
>
> [The program in pseudocode.](https://pastebin.com/DRgJZTUT) The program performs very slowly because my interpreter is super inefficient. Also, I didn't use any opt-in optimizations available, which can reduce the evaluation time from several minutes to about 10 seconds.
>
>
>
[Answer]
# [Perl 6](https://perl6.org) — [Cracked!](https://codegolf.stackexchange.com/a/140880/69059)
In a strict sense, this isn't an acceptable submission because it doesn't try very hard to win. Instead, it hopes to offer a pleasant puzzle.
It is a "pure math" program which is intended to be cracked by contemplation. I'm sure that you could bruteforce the solution (after cleaning up some sloppy programming I've purposefully committed), but for "full credit" (:--)), you should be able to explain what it does on the math grounds.
```
sub postfix:<!>(Int $n where $n >= 0)
{
[*] 1 .. $n;
}
sub series($x)
{
[+] (0 .. 107).map({ (i*($x % (8*π))) ** $_ / $_! });
}
sub prefix:<∫>(Callable $f)
{
my $n = 87931;
([+] (0 .. $n).map({
π/$n * ($_ == 0 || $_ == $n ?? 1 !! 2) * $f(2*π * $_/$n)
})).round(.01);
}
sub f(Int $in where $in >= 0)
{
∫ { series($_)**11 / series($in * $_) }
}
```
You are supposed to crack the function f(). (That's the function that takes one natural number and returns one of the two results.) **Warning:** As shown by @Nitrodon, the program actually behaves wrongly and "accepts" an *infinite* number of inputs. Since I have no idea of how to fix it, I just remark for the future solvers that *the number I had in mind is less than 70000*.
If you try to run this in TIO, it **will** time out. This is intentional. (Since it's not supposed to be run at all!)
Finally, I tried to write some reasonably clear code. You should be mostly able to read it fluently even if you're not familiar with the language. Only two remarks: the square brackets [*op*] mean reducing ("folding", in Haskell lingo) a list with the operator *op*; and the sub called `postfix:<!>` actually defines a postfix operator named ! (i. e. used like `5!` -- it does exactly what you would expect). Similarly for the `prefix:<∫>` one.
I hope that somebody enjoys this one, but I'm not sure if I got the difficulty right. Feel free to bash me in the comments :—).
[Try it online!](https://tio.run/##TZHPTgIxEMbP26f4iJi0q64sGkEQOHjy7s0QUqQLDUuXtF3@BEg4@i4@DO/gi@AsIHhpJt/MfPOb6VTZ9Gm/d3kf08z5RC8aL6U2fzMeZYP5SFlVBO0WKoKtWPARdhEjikhssg1jRaNTVivHy4tjxU0XvFKUxJWaiCZyylfgOqQ8rsHr4W4rhEAYotzDPT0lbMTZa2rVgeHn67vNX2Wayn5KBMnBerIsWFqo154f4iYL@GVW2ZxGsSDYbe@pLASnAS0Cx3qNY0hyp0P8pRKqhEC@vEo8RdSjHsGCjRCRzXIz4FElvmAlx4vo80n0v5sQK1bnK/REGMYxbfYnaHPwF9iQ2/4K7yNFa2ZDKyfQDrlTA/SXmChpHLIEnvJJbj69zgwNFiRIDy/HitJGFf@kvZ4paOPVUFlIM4BVPrfmWHDy8PMMM5nmyt0i1WMSRto1mJNLcr17FM39Lw "Perl 6 – Try It Online")
[Answer]
# JavaScript, [Cracked](https://codegolf.stackexchange.com/a/140913/73026)
I've obfuscated this as much as I can, to the point where it can't fit within this answer.
[Try it here!](https://repl.it/K4qT/0)
Click Run, then type in console `guess(n)`
Returns undefined if you get the wrong answer, returns true otherwise.
Edit: Somehow I overlooked the part about my score being the number. Oh well, my number is very very big. Good luck solving it anyways.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score: ...1 ([cracked](https://codegolf.stackexchange.com/a/140801/41024))
```
5ȷ2_c⁼“ḍtṚøWoḂRf¦ẓ)ṿẒƓSÑÞ=v7&ðþạẆ®GȯżʠṬƑḋɓḋ⁼Ụ9ḌṢE¹’
```
[Try it online!](https://tio.run/##AW8AkP9qZWxsef//Nci3Ml9j4oG84oCc4biNdOG5msO4V2/huIJSZsKm4bqTKeG5v@G6ksaTU8ORw549djcmw7DDvuG6oeG6hsKuR8ivxbzKoOG5rMaR4biLyZPhuIvigbzhu6Q54biM4bmiRcK54oCZ//8 "Jelly – Try It Online")
1Really expected me to reveal it? Come on! Oh well, it has a score of 134. There, I said it!
[Answer]
# Python 2 [(cracked)](https://codegolf.stackexchange.com/a/140908/48931)
I wouldn't suggest brute force. Hope you like generators!
```
print~~[all([c[1](c[0](l))==h and c[0](l)[p]==c[0](p^q) for c in [(str,len)] for o in [2] for h in [(o*o*o+o/o)**o] for p,q in [(60,59),(40,44),(19,20),(63,58),(61,53),(12,10),(43,42),(1,3),(35,33),(37,45),(17,18),(32,35),(20,16),(22,30),(45,43),(48,53),(58,59),(79,75),(68,77)]] + [{i+1 for i in f(r[5])}=={j(i) for j in [q[3]] for i in l} for q in [(range,zip,str,int)] for r in [[3,1,4,1,5,9]] for g in [q[1]] for s in [[p(l)[i:i+r[5]] for p in [q[2]] for i in [r[5]*u for f in [q[0]] for u in f(r[5])]]] for l in s + g(*s) + [[z for y in [s[i+a][j:j+r[0]] for g in [q[0]] for a in g(r[0])] for z in y] for k in [[w*r[0] for i in [q[0]] for w in i(r[0])]] for i in k for j in k] for f in [q[0]]]) for l in [int(raw_input())]][0]
```
[Try it online!](https://tio.run/##XVHtjoIwEHwVfrawydEvUROepOldiOdHkQACxqjRV@e6bS8aY8h2ZmfbnbG/Toeu5fPcD7adnk9dNQ3RG80M2ejckIbSsjwkVfubRKx7U5b@3H@faLLrhmST2DbRZJwGaLYtNZ7sPMkDOARFl7pf1n11NE270OnhFHqLHNSKApE5SOkqWwHPXV0IUEusDJRAngNDXgqQHDEgKxQIXwuQCtkCGE4JDgIxz4EtsDrspxVI1MtluFUtw@vFCgrUL5ZQFNSYJEv03WbM72px0x0ZtDL0UZb3mtgQQO0tnLQw5iVsHv4c7Q1Vu9/CzfaAMbmsY0yDb2sBDKT7FKziHft4J4t4DMIe/wK7thluESOMSv7@usZ@evbELgryKDi/@TCRa5Abnd09SUeKtvXNN65@eNQ2q4yu17V7OP9Y8R9XiPcEBdHdDZlrOB@DgUuK/bdFX/MXxDbOv0mOr5CP5tORoa/9tcvVJX35sW1/ngh1tzjJPDMu/gA "Python 2 – Try It Online")
Outputs `1` for the correct number, `0` otherwise.
[Answer]
# [Haskell](https://www.haskell.org/), [cracked](https://codegolf.stackexchange.com/questions/140794/im-thinking-of-a-number-robbers-thread/140869#140869)
This is purely based on arithmetic. Note that `myfun` is the actual function, while `h` is just a helper function.
```
h k = sum $ map (\x -> (x*x)**(-1) - 1/(x**(2-1/(fromIntegral k)))) [1..2*3*3*47*14593]
myfun inp | inp == (last $ filter (\k -> h k < (-7.8015e-5) )[1..37*333667-1]) = 1
| otherwise = 0
main = print $ show $ myfun 42 -- replace 42 with your input
```
[Try it online!](https://tio.run/##PY/BboMwEETvfMUcerAtmcYYQiqF3PsNbQ5WZYqFDcg2gkj5d2rn0F1pNaOVdt4OKoza2uMYMKJDWB3e4NQC8r2D30B2tlPGCBcUHOI9eUYqnkTvZ/c5Rf3rlcVIU@FLlGXFZOq6ZaJuPuS9cI9@nWCmBc/X7DoQq0JMMb2xUfuUNOakDHAF4W15OYlG84YCNF@ULZNSns8tF3eaGEWB/3pijoP2mwk6bU5F4ZSZklq8mXJEGOYtP/SCqCtwDq8Xq350dpuJAx7z6jPZGo/jDw "Haskell – Try It Online")
[Answer]
# Java, [Cracked by Nitrodon](https://codegolf.stackexchange.com/a/141028/42199)
```
import java.math.BigDecimal;
public class Main {
private static final BigDecimal A = BigDecimal.valueOf(4);
private static final BigDecimal B = BigDecimal.valueOf(5, 1);
private static final BigDecimal C = BigDecimal.valueOf(-191222921, 9);
private static BigDecimal a;
private static BigDecimal b;
private static int c;
private static boolean f(BigDecimal i, BigDecimal j, BigDecimal k, BigDecimal l, BigDecimal m) {
return i.compareTo(j) == 0 && k.compareTo(l) >= 0 && k.compareTo(m) <= 0;
}
private static boolean g(int i, int j, BigDecimal k) {
c = (c + i) % 4;
if (j == 0) {
BigDecimal l = a; BigDecimal m = b;
switch (c) {
case 0: a = a.add(k); return f(C, b, B, l, a);
case 1: b = b.add(k); return f(B, a, C, m, b);
case 2: a = a.subtract(k); return f(C, b, B, a, l);
case 3: b = b.subtract(k); return f(B, a, C, b, m);
default: return false;
}
} else {
--j;
k = k.divide(A);
return g(0, j, k) || g(1, j, k) || g(3, j, k) || g(3, j, k) || g(0, j, k) || g(1, j, k) || g(1, j, k) || g(3, j, k);
}
}
private static boolean h(int i) {
a = BigDecimal.ZERO; b = BigDecimal.ZERO; c = 0;
return g(0, i, BigDecimal.ONE);
}
public static void main(String[] args) {
int i = Integer.valueOf(args[0]);
System.out.println(!h(i) && h(i - 1) ? 1 : 0);
}
}
```
I wanted to try something different than the usual hash and random functions. You can pass the number as a command line argument. Outputs `1` if the correct number is given and `0` otherwise. For small numbers you can also [try it online](https://tio.run/##jZRNc5swEIbP@FdsD82IKWaMnRxs6naSNIceWs80PSWTwwICCwR4QLjTafjt7gpsB2Li9gKzKz3vfmilGLc4zjc8i4NktxPpJi8UxOS0U1Rr@0ZEX7gvUpTuaLSpPCl88CWWJXxDkcGfkbEpxBYVh1KhosVQZCjhBYNrWHZMe4uy4quQXZruv9mbYfbKAud/8NthfOzMnel0Op86FswHdDoKeHbVO10VmQKfWvXa7@W55JhByDq8sLpqcc9KepbsWampG28UXFVFBsL283SDBf@Zs9iE5RImcHEBScctTfg04Cadj@SmKuq3M46YrolS1b9XObZ5@NRm5sMHECa8h0uSM0QILG5SabcY3VpoO7q9esije2kY5S@h/DWp7THDx5LDZAGoIRuDgCWmC/vKQ3ZrgUcpWbpBaLoviLMAT6ueIrQZLSAwJbaLTA9RyspTBfrqjVBEyy43O4Qa5o7xiE73XMBDrKRaHHehLHmzVNOnBk5m24DxOG78CUVI7EBsRcDZdSuzhyM2sfTB0Gk8P5Pl9KzZGescN6yi49Znx2Xdjkt7fti/gA93P1Zu06wTp54hPYi9onr3w159vzMPo9o@RPvQ21wEkNJzxO5VIbLo8QmwiMo2hSYbEv@aKR7x4vgI6B2Pk6emovvfpeKpnVfKpqoyJTP2juow9X2hP4zpuYHP4MCC5rlJod7tdrO/ "Java (OpenJDK 8) – Try It Online").
**Hint:**
>
> The main part of the program implements a *variant* of a very well known algorithm. Once you know what it does, you will be able to optimize the given program to calculate the secret number.
>
>
>
**Explanation:**
>
> This program implements the traversal of the quadratic variant (type 2) of the well known [Koch curve](https://en.wikipedia.org/wiki/Koch_snowflake) (image from Wikipedia):
>
>
>
> [![Quadratic_Koch_curve_type2_iterations.png](https://i.stack.imgur.com/6eJVq.png)](https://i.stack.imgur.com/6eJVq.png)
>
>
>
> The secret number is the first iteration which doesn't pass through the point (B, C). As correctly recognized by [Nitrodon](https://codegolf.stackexchange.com/users/69059/nitrodon), except of the first iteration we can safely ignore the recursion of all parts of the curve, which don't pass through the given point. By changing a line in the original program accordingly, we can check the correct number even in the [online interpreter](https://tio.run/##jVTBcptADD3jr1AOzSxTzBg7PdjU6SRuDj20nml6aiYHAQteWMADizudxN/uaoE4EFO3F2Np9Z6etFrFuMNxvuVZHCSHg0i3eaEgJqedotrYtyL6zH2RonRHo23lSeGDL7Es4SuKDJ5GxrYQO1QcSoWKDkORoYRXGNzAsmPaO5QVX4fsynT/jb0dxn6wwPkf@GoYPnbmznQ6nU8dC@YDPB0GPHvqnZ6KTIFPrXrr9/JccswgZB28sLpscc9KepbsWampG28UXFVFBsL283SLBf@Rs9iE5RImcHkJScctTbgecBPPR3JTFfu/K46Yromk6s8bjY0On9rMfHgPwoR3cEV0hgiBxY2U52dg2EnauZCfd9/XJly0yoiC/s40oBffRJja73X8KxLf0Ht2WXmqQF@xxOxHXBOwEWl0u0mC0e11lDz6Ng2j/CWUvyExLczwseQwWQBqkI1BQElcaHsfspUFHjXF0leEpvsKcRbgadZTCAWjBQRMCduFTF@ydOoZSkVo2cXNXlIN4475CJ22uICHWEm1OEahLHl9tKefPXAymwaMx3HtTyhDYgdiJwLObhqaFhyxiaVHI6kvKWJOz5qdsc7hhll03v3Zgd00A9vcH/ZXgJ44t27WiVNPsX4KvaJ6L9Ref7szXx5Lswrb1LtcBJDSQmT3qhBZ9PAIWERlI6FWQ@RfMsUjXhzXkI54mDzWFd3/LhVP7bxSNlWVKZmxC6rD1O@CvjCmhQefwIEFDXQtYX84HKazPw "Java (OpenJDK 8) – Try It Online").
>
>
>
[Answer]
# PHP, safe, score:
>
> 60256
>
>
>
```
<?php
$a = $argv[1];
$b ='0123456789abcdefghijklmnopqrstuvwxyz';
$c = strlen($b);
$d = '';
$e = $a;
while ($e) {
$d .= $b[$e % $c];
$e = floor($e / $c);
}
echo ((function_exists($d) && $d($a) === '731f62943ddf6733f493a812fc7aeb7ec07d97b6') ? 1 : 0) . "\n";
```
Outputs 1 if correct, 0 otherwise.
Edit: I don't think anyone even tried to crack this because:
>
> it would be easy to brute force.
>
>
>
Explanation:
>
> I take the input and convert it to "base 36", but I don't reverse the remainders to produce the final number. The number 60256 is "1ahs" in base 36. Unreversed, that is "sha1", which is a function in PHP. The final check is that sha1(60256) equals the hash.
>
>
>
[Answer]
# Pyth, [Cracked by Erik the Outgolfer](https://codegolf.stackexchange.com/a/140802/59487)\*
I tried to obfuscate this as much as possible.
```
hqQl+r@G7hZ@c." y|çEC#nZÙ¦Y;åê½9{ü/ãѪ#¤
ØìjX\"¦Hó¤Ê#§T£®úåâ«B'3£zÞz~Уë"\,a67Cr@G7hZ
```
**[Try it here!](https://pyth.herokuapp.com/?code=hqQl%2Br%40G7hZ%40c.%22+y%08%7C%C3%A7%C2%85%C2%87EC%23nZ%C3%99%C2%A6Y%3B%C3%A5%C3%AA%C2%BD%C2%819%06%7B%C3%BC%2F%C3%A3%C3%91%C2%8A%C2%AA%23%06%C2%95%12%C2%A4%0A%C3%98%C3%AC%1AjX%5C%22%C2%8E%0F%C2%93%C2%A6H%C3%B3%C2%90%C2%A4%C3%8A%23%1D%0B%1D%C2%A7T%C2%85%C2%A3%04%07%10%C2%99%1D%C2%AE%18%C3%BA%C3%A5%C2%91%C3%A2%0B%C2%91%C2%ABB%14%273%C2%A3z%C3%9Ez%7E%C2%81%C3%90%16%C2%A3%C3%AB%19%22%5C%2Ca67Cr%40G7hZ&input=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0)**
>
> \*The number was 9.
>
>
>
[Answer]
# Octave, score: ???
It's pretty much guaranteed that no other number will have the exact same 20 random numbers in the end of the list of `1e8` of numbers.
```
function val = cnr(num)
rand("seed", num);
randomints = randi(flintmax-1,1e4,1e4);
val = isequal(randomints(end+(-20:0))(:), ...
[7918995738984448
7706857103687680
1846690847916032
6527244872712192
5318889109979136
7877935851634688
3899749505695744
4256732691824640
2803292404973568
1410614496854016
2592550976225280
4221573015797760
5165372483305472
7184095696125952
6588467484033024
6670217354674176
4537379545153536
3669953454538752
5365211942879232
1471052739772416
5355814017564672](:));
end
```
Outputs `1` for the secret number, `0` otherwise.
I ran this in Octave 4.2.0.
---
*"Sleeps and other slowdowns can be removed when bruteforcing."*
Good luck with that :)
[Answer]
# [Ly](https://github.com/LyricLy/Ly), score 239, [cracked](https://codegolf.stackexchange.com/questions/140794/im-thinking-of-a-number-robbers-thread/140857#140857)
```
(1014750)1sp[l1+sp1-]28^RrnI24^=u;
```
[Try it online!](https://tio.run/##y6n8/1/D0MDQxNzUQNOwuCA6x1C7uMBQN9bIIi6oKM/TyCTOttT6/38A "Ly – Try It Online")
I'm banking on nobody knowing Ly here, although I know how easily that could change... *sweats*
Explanation:
```
(1014750)1sp[l1+sp1-] # meaningless code that counts up to 1014750 and discards the result
28^Rr # range from 255 to 0
nI # get the index from the range equal to the input
24^= # check if it's 16
u; # print the result
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), score 1574 ([cracked](https://codegolf.stackexchange.com/a/140888/69059))
```
<>(((((((((((((((((((([([(((()()()){}){}){}])]){})))){}{}{}{}()){}){})){}{})){}{})){}((((((((()()){}){}){}){}[()]){}){}){}){}())){})){}){}{}{}){})(((((((((((((((((((()()){}){}()){}){}){}()){}){}()){}){})){}{}())){}{})){}{}){}){}){})(((((((((((((((()()){}()){}()){}){}){}()){}){}){}()){}){}){}()){}()){}()){})<>{({}[()])<>({}({})<({}({})<({}({})<({}({}))>)>)>)<>}({}<>(){[()](<{}>)}<>)
```
[Try it online!](https://tio.run/##dVAxDoAgDPxOb3BxJv0IYdDBxGgcXIlvxxYQMCJ3KfRoL4X5nNZjWPZpC8EwdZYVyIIC/kp0cHqAKgnlMio1Fp@2XWgpWTyk6JVLYrOwN0/xafw@EvJI7TCFfccafu1fVUk07Ck/Rr5PVNV@dnCEYc2kGl77yPiLITlCGG8 "Brain-Flak – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html)
```
#!/bin/dc
[[yes]P] sy [[no]P] sn [ly sp] sq [ln sp] sr [lp ss] st [ln ss] su
? sa
119560046169484541198922343958138057249252666454948744274520813687698868044973597713429463135512055466078366508770799591124879298416357795802621986464667571278338128259356758545026669650713817588084391470449324204624551285340087267973444310321615325862852648829135607602791474437312218673178016667591286378293
la %
d 0 r 0
=q !=r
10 154 ^ 10 153 ^ +
d la r la
<t !<u
1 la 1 la
>s !>n
```
[Try it online!](https://tio.run/##JY/LSgNBEEX3/RUVxJUL6/0AH7/gflCIiQshjElGF/n6WKMM9Bxu3a57e7@7Xm829@@f8/1@N6bp8rG8vrzCcoFpmr/@cIbpcIHl2HhqnP/x3HiEZWn8/ldX/BnPAMt2EJU5ojp5aappC1nMolKWJIkWrMXG7t7jNoUqhxpjjz3DK9MTVSvEKoJEudSFxIwYzdQdI8XdMCMwqqyIuBcVVyq5WESHITt3uGt/HhbEfUuSONlKrKU0NVyLVO/qoKTWErO7ksZaQVi5H8O6ZqeJYmeyR3dTVSEUJicTtvSes2smV1ftio4c6572hRAzpfc/EsnXPtULXaLtMg5buB17QDgDjscTbB7PgxDIFN7gD6Thri3tPPcxHr5h8/AzaBXWYzwtsHmar9df "dc – Try It Online")
---
**Note:** This submission has been modified since it was submitted. The original submission (below) was invalid and cracked by Sleafar in the comments below. (An input of `1` gives rise to the output `yes`, but there is one other number that gives the same result.)
```
#!/bin/dc
[[yes]P] sy [[no]P] sn [ly sp] sq [ln sp] sr
? sa
119560046169484541198922343958138057249252666454948744274520813687698868044973597713429463135512055466078366508770799591124879298416357795802621986464667571278338128259356758545026669650713817588084391470449324204624551285340087267973444310321615325862852648829135607602791474437312218673178016667591286378293
la %
d 0 r 0
=q !=r
10 154 ^ 10 153 ^ +
d la r la
<p !<n
```
[Try it online!](https://tio.run/##JY9LasNAEET3c4oxIass3P8P2OQK2QsHHDuLgFFsaaXTKy0Hwajorql6c72s68tu//Uz7q@XNgzL93z6OPV56cMw/j7l2Ifb0ud7yUfJ8V9O7b33@dwQUw1ADC0lRKUGkUQsnBrIAeokSUpmVusyuQi5KEGtLdwywgJE0lnTHVkoxRhZFQlUxQw82Ewh3MEzNRGpgpIyBI3VvcqAjKrcpD5zdaS6xYEUpMlao1BR2ECysqoosGYBUawoviEwCdVjSLbuUBaoTjIvNhFhBCY0VCYNqz2ZRFAWaiEakG855XNGIgyrvwegbTxZgcZedm63c39t1w596tCOj747Tg2ho0r/7E/BJd7KUs6pjna4991hXNc/ "dc – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), safe, score:
>
> 63105425988599693916
>
>
>
```
#!ruby -lnaF|
if /^#{eval [$F,0]*"**#{~/$/}+"}$/ && $_.to_i.to_s(36)=~/joe|tim/
p true
else
p false
end
```
[Try it online!](https://tio.run/##KypNqvz/PzNNQT9OuTq1LDFHIVrFTccgVktJS0u5uk5fRb9WW6lWRV9BTU1BJV6vJD8@E0QUaxibadrW6Wflp9aUZObqcykoFCiUFJWmcqXmFKeCeWmJIFZqXsr//8b/8gtKMvPziv/rutX81038r5sHAA "Ruby – Try It Online")
Explanation:
>
> The first conditional checks the input number for [narcissism](https://codegolf.stackexchange.com/questions/15244/test-a-number-for-narcissism). The thread I originally wrote for was coincidentally bumped around the same time I posted this, but I guess nobody noticed. The second converts the number to base 36, which uses letters as digits, and checks if the string contains "joe" or "tim". It can be proven (through exhaustion) that there is only one narcissistic number named either Joe or Tim (Joe), because the narcissistic numbers are finite. Proof that they're finite: the result of taking an n-digit number, raising each digit to the nth power, and summing is bounded above by `n*9^n`, while the value of an n-digit number is bounded below by n^10. The ratio between these terms is n\*(9/10)^n, which eventually decreases monotonically as n increases. Once it falls below 1, there can be no n-digit narcissistic numbers.
>
>
>
[Answer]
# Swift 3 (53 bytes) - [Cracked](https://codegolf.stackexchange.com/a/140809/59487)
```
func f(n:Int){print(n==1+Int(.pi*123456.0) ?222:212)}
```
How to run this? – `f(n:1)`.
**[Test Here.](http://swift.sandbox.bluemix.net/#/repl/59a46197dcc75d533468baab)**
[Answer]
# Java, score: 3141592 ([Cracked](https://codegolf.stackexchange.com/questions/140794/im-thinking-of-a-number-robbers-thread/140974#140974))
```
\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0063\u006c\u0061\u0073\u0073\u0020\u004d\u0061\u006e\u0067\u006f\u0020\u007b
\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006f\u0069\u0064\u0020\u0063\u006f\u006e\u0076\u0065\u0072\u0074\u0028\u0053\u0074\u0072\u0069\u006e\u0067\u0020\u0073\u0029\u007b\u0066\u006f\u0072\u0028\u0063\u0068\u0061\u0072\u0020\u0063\u0020\u003a\u0020\u0073\u002e\u0074\u006f\u0043\u0068\u0061\u0072\u0041\u0072\u0072\u0061\u0079\u0028\u0029\u0029\u007b\u0020\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074\u002e\u0070\u0072\u0069\u006e\u0074\u0028\u0022\u005c\u005c\u0075\u0030\u0030\u0022\u002b\u0049\u006e\u0074\u0065\u0067\u0065\u0072\u002e\u0074\u006f\u0048\u0065\u0078\u0053\u0074\u0072\u0069\u006e\u0067\u0028\u0063\u0029\u0029\u003b\u007d\u007d
\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0061\u0072\u0067\u0073\u0029\u0020\u007b\u0069\u006e\u0074\u0020\u0078\u0020\u0020\u003d\u0020\u0049\u006e\u0074\u0065\u0067\u0065\u0072\u002e\u0070\u0061\u0072\u0073\u0065\u0049\u006e\u0074\u0028\u0061\u0072\u0067\u0073\u005b\u0030\u005d\u0029\u003b
\u0064\u006f\u0075\u0062\u006c\u0065\u0020\u0061\u003d\u0020\u0078\u002f\u0038\u002e\u002d\u0033\u0039\u0032\u0036\u0039\u0039\u003b\u0064\u006f\u0075\u0062\u006c\u0065\u0020\u0062\u0020\u003d\u0020\u004d\u0061\u0074\u0068\u002e\u006c\u006f\u0067\u0031\u0030\u0028\u0028\u0069\u006e\u0074\u0029\u0020\u0028\u0078\u002f\u004d\u0061\u0074\u0068\u002e\u0050\u0049\u002b\u0031\u0029\u0029\u002d\u0036\u003b
\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0028\u0061\u002f\u0062\u003d\u003d\u0061\u002f\u0062\u003f\u0022\u0046\u0061\u0069\u006c\u0022\u003a\u0022\u004f\u004b\u0022\u0020\u0029\u0029\u003b
\u007d\u007d
```
[Answer]
# Python 3, score 1 (safe)
Not a very interesting solution, but better a safe cop than a dead cop.
```
import hashlib
def sha(x):
return hashlib.sha256(x).digest()
x = input().encode()
original = x
for _ in range(1000000000):
x = sha(x)
print(int(x==b'3\xdf\x11\x81\xd4\xfd\x1b\xab19\xbd\xc0\xc3|Y~}\xea83\xaf\xa5\xb4]\xae\x15wN*!\xbe\xd5' and int(original.decode())<1000))
```
Outputs `1` for the target number, `0` otherwise. Input is taken from stdin. The last part (`and int(original.decode())<1000`) exists only to ensure only one answer, otherwise there would obviously be infinitely many answers.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), score ???
```
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <wmmintrin.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
union State
{
uint8_t u8[128];
__m128i i128[8];
} state;
void encrypt()
{
BIO *key = BIO_new_mem_buf
(
"-----BEGIN PUBLIC KEY-----\n"
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5CBa50oQ3gOPHNt0TLxp96t+6\n"
"i2KvOp0CedPHdJ+T/wr/ATo7Rz+K/hzC7kQvsrEcr0Zkx7Ll/0tpFxekEk/9PaDt\n"
"wyFyEntgz8SGUl4aPJkPCgHuJhFMyUflDTywpke3KkSv3V/VjRosn+yRu5mbA/9G\n"
"mnOvSVBFn3P2rAOTbwIDAQAB\n"
"-----END PUBLIC KEY-----\n",
-1
);
RSA *rsa = PEM_read_bio_RSA_PUBKEY(key, &rsa, NULL, NULL);
uint8_t ciphertext[128];
RSA_public_encrypt(128, state.u8, ciphertext, rsa, RSA_NO_PADDING);
memcpy(state.u8, ciphertext, 128);
}
void verify()
{
if (memcmp
(
"\x93\xfd\x38\xf6\x22\xf8\xaa\x2f\x7c\x74\xef\x38\x01\xec\x44\x19"
"\x76\x56\x27\x7e\xc6\x6d\xe9\xaf\x60\x2e\x68\xc7\x62\xfd\x2a\xd8"
"\xb7\x3c\xc9\x78\xc9\x0f\x6b\xf0\x7c\xf8\xe5\x3c\x4f\x1c\x39\x6e"
"\xc8\xa8\x99\x91\x3b\x73\x7a\xb8\x56\xf9\x28\xe7\x2e\xb2\x82\x5c"
"\xb8\x36\x24\xfb\x26\x96\x32\x91\xe5\xee\x9f\x98\xdf\x44\x49\x7b"
"\xbc\x6c\xdf\xe9\xe7\xdd\x26\x37\xe5\x3c\xe7\xc0\x2d\x60\xa5\x2e"
"\xb8\x1f\x7e\xfd\x4f\xe0\x83\x38\x20\x48\x47\x49\x78\x18\xfb\xd8"
"\x62\xaf\x0a\xfb\x5f\x64\xd1\x3a\xfd\xaf\x4b\xaf\x93\x23\xf4\x36",
state.u8,
128
))
exit(0);
}
static inline void quarterround(int offset)
{
int dest = (offset + 1) % 8, src = offset % 8;
state.i128[dest] = _mm_aesenc_si128(state.i128[src], state.i128[dest]);
}
int main(int argc, char *argv[])
{
if (argc != 2)
exit(0);
uint64_t input = strtoull(argv[1], NULL, 0);
state.i128[0] = _mm_set_epi32(0, 0, input >> 32, input);
for (uint64_t round = 0; round < 0x1p45; round += 2)
{
quarterround(0);
quarterround(2);
quarterround(4);
quarterround(6);
quarterround(7);
quarterround(1);
quarterround(3);
quarterround(5);
}
encrypt();
verify();
puts("something");
}
```
Since cryptographic solutions are encouraged, here. Exactly one positive integer will print **something**, all others will print nothing. This takes a *long* time, so it cannot be tested online.
[Answer]
# Java, 164517378918, safe
```
import java.math.*;import java.util.*;
public class T{
static boolean f(BigInteger i){if(i.compareTo(BigInteger.valueOf(2).pow(38))>0)return false;if(i.longValue()==0)return false;if(i.compareTo(BigInteger.ONE)<0)return false;int j=i.multiply(i).hashCode();for(int k=3^3;k<2000;k+=Math.abs(j%300+1)){j+=1+(short)k+i.hashCode()%(k+1);}return i.remainder(BigInteger.valueOf(5*(125+(i.hashCode()<<11))-7)).equals(BigInteger.valueOf(0));}
@SuppressWarnings("resource")
public static void main(String[]a){long l=new Scanner(System.in).nextLong();boolean b=false;for(long j=1;j<10;j++){b|=f(BigInteger.valueOf(l-j));}System.out.println(f(BigInteger.valueOf(l))&&b);}
}
```
[Answer]
# TI-BASIC, ~~score: 196164532~~ non-competing
Returns 1 for secret number, 0 otherwise.
```
Ans→rand
rand=1
```
Refer to the note on this page on the [`rand` command](http://tibasicdev.wikidot.com/rand) for more info.
[Answer]
# [Aceto](https://github.com/aceto/aceto), safe
```
P'*o*7-9JxriM'lo7*9Yxx.P',xe*ikCKxlI.D+∑\a€'#o*84/si5s:i»I9Ji8:i+∑€isi.s1+.i2\H/iQxsUxsxxsxiss*i1dJi/3d2*Ji-d*id*IILCh98*2JixM'e9hxBNRb!p
```
Outputs TrueFalse if correct, FalseFalse otherwise
The number was
>
> 15752963
>
>
>
[Try it online!](https://tio.run/##FckxDoIwFADQq2AcmnykBNRAGcXBVjFo4mDCgpaEH0lqrMOfnVy9hzdw8yhcpGLytlefm7txzvNKBgaSQCi6YcE6k4A4EvGSTagBvORr6iRf@v3zVdX9483GBtJZaHFuM/x@pFCYZvjvIdEit5HPMa5WIe7IHsjSAK0FjLTCcKpjUBhoQA1SbvJWpBArpII1oqXFdn8aXZ37AQ "Aceto – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), score unknown, [Cracked by Bubbler](https://codegolf.stackexchange.com/a/171455/100664)
```
def check(x):
if x < 0 or x >= 5754820589765829850934909 or pow(x, 18446744073709551616, 5754820589765829850934909) != 2093489574700401569580277 or x % 4 != 1:
return "No way ;-("
return "Cool B-)"
```
[Try it online!](https://tio.run/##dY9BC4JAEIXv/opJCFxQmNWZnd3KDnXvP0QpSuGKGOqvN8VLl95p3uMbZl479ZVvsnl@FiU8quLxikZ1CGBRXcIIJ0Dw3TKcc2BhsimydWLYps4yuowcupVo/RCNMWhLZIQIJRN0zNpoE//fVLDLIV2NdSwkiISajWOLqch2eQ@0Unr7alVX9J@ugfDmYbhPcEyiMPjNr96/4ZKoMAjarm76aCumlZrnLw "Python 3 – Try It Online")
Simple, but may take some time to brute-force ;-) Looking forward to a fast crack ;-)
Footnote: the first two and the last conditions make the answer unique.
BTW how the score is calculated?
Hint 1
>
> You may expect there will be 264 answers within `0 <= x < [the 25-digit prime]`, but actually there are only 4, and the last condition eliminates the other 3. If you can crack this, then you will also know the other 3 solutions.
>
>
>
] |
[Question]
[
[Pyramid Scheme](https://github.com/ConorOBrien-Foxx/PyramidScheme) is a language being developed by [@ConorO'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien). In Pyramid Scheme, the code that you write looks like this:
```
^ ^
/ \ /3\
/ \ ---
/ + \
^-------^
/9\ /3\
/123\ ---
-----
```
Now, that code has two obvious qualities: It's difficult to parse, and it's difficult to write. Conor has solved the first one, however it will be your job to solve that second issue.
---
The above code is processed by the PyramidScheme interpreter into a nested string array, like this:
```
[["+", ["9123", "3"]], "3"]
```
Your task is to write a program or function, which given a nested array of strings, outputs or returns the recreated PyramidScheme code. You may assume that the input array will always be valid.
A pyramid is an isosceles triangle. The top is `^`, the sides slope diagonally away with `/` and `\`, and the bottom is `-`. The two bottom corners are either empty or contain the start of other pyramids, which are arguments. The middle is filled with the pyramid's name, ignoring line breaks.
Here's how the parser converts the code into a useable format. First, it scans for a top-level pyramid. If it takes no arguments, it represents it with a single string and moves on. Otherwise, it represents is as an array `["name",[arg1,arg2]]` or `["name",[arg1]]`. The arguments are the pyramids at the bottom left and bottom right of the pyramid, which may be either string or more arrays described as above. You may notice that this somewhat resembles Lisp, in which case you may also have noticed the awful pun that is the language name. After the pyramid is fully represented, the parser moves on to the next one.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins!
## Test Cases: These are not the only valid outputs, these are example of valid outputs.
```
[["+", ["9123", "3"]], "3"]
^ ^
/ \ /3\
/ \ ---
/ + \
^-------^
/9\ /3\
/123\ ---
-----
```
---
```
[["out", [["chr", ["72"]], ["chr", ["101"]]]], ["out", [["chr", ["108"]]]], ["out", [["chr", ["108"]]]], ["out", [["chr", ["111"]]]]]
^ ^ ^ ^
/ \ / \ / \ / \
/out\ /out\ /out\ /out\
^-----^ -----^----- -----^
/ \ / \ / \ / \
/chr\ /chr\ /chr\ /chr\
^----- -----^ -----^ ^-----
/ \ / \ / \ / \
/72 \ /101\ /108\ /111\
----- ----- ----- -----
```
---
```
[ ["+", [ ["asdfghjkl"], ["do", [ "1" ]] ]] ]
^
/ \
/ + \
/ \
^-------^
/a\ /d\
/sdf\ /o \
/ghjkl\ ^-----
-------/1\
---
```
Notice in the second test case, the second and third `out` pyramid both have a `["chr", ["108"]]` as a parameter, which is collapsed into one pyramid stack shared by two top-level ones. This is a valid optimization your code may support, but it is completely optional; scoring is not based on the length of your output.
For the curious, the first case displays `9126 3` due to implicit printing of toplevel pyramids, the second one prints `Hello`, and the last one is a syntax error, included just because it has a neat structure.
---
You may assume that the input only contains printable ASCII, excluding spaces, `^`, `/`, `\`, and `-`. The input will always be valid, and contain at least one pyramid. There is no limit on the size of the array or the input strings, however you may write your code as if your language's default integer type was infinite precision and that your computer has arbitrary memory. If taking input as a single string, you may use anything reasonable (comma, space, etc. as long as it's in printable ascii and not `"` or `[]`) to delimit arrays. You do not have to include brackets surrounding the entire thing, and instead take multiple arrays separated by your delimiter.
Your output does not have to be golfed, you may insert extra space or make your pyramids larger than necessary. Toplevel pyramids *should* be on the first line. Output should be a string with newlines or a list of strings.
Anyone who *does* include a version of their code which optimally golfs the pyramids may receive some rep in the form of upvotes/bounties (but probably just upvotes).
[Answer]
## Common Lisp - ~~2524~~ 1890 bytes
```
(defun f(i)(let((s(loop as r in i collect(g r)))(n())(output""))(loop until n do(setf n T)(loop as r in s do(if(cdr r)(progn(setf output(c output(e r))(cdr r)(cdr(cdr r)))(setf n()))(setf output(c output(b(car r))))))(setf output(c output(format()"~%"))))output))(defun g(r)(if(stringp r)(d(m(length r))r)(if(<(length r)2)(d(m(length(car r)))(car r))(if(=(length(e r))1)(let((h(g(car(e r))))(p(d(m(length(car r)))(car r))))(let((o(+ 1(position #\^(e h))))(parent_length(car p)))(if(<(-(car h)o)parent_length)(l(cons(+ o parent_length)())(loop as n in(butlast(cdr p))collect(c(b o)n))(cons(c(subseq(e h)0 o)(car(last p)))())(loop as n in(cdr(cdr h))collect(c n(b (- parent_length(-(car h)o))))))(let((i(-(- o 1)parent_length)))(l(cons(car h)())(loop as n in(butlast(cdr p))collect(c(b o)n(b i)))(cons(c(subseq(nth 1 h)0 o)(car(last p))(b i))())(cddr h))))))(let((l-h(g(car(e r))))(r-h(g(e(e r)))))(let((ll(position #\^(e l-h)))(rl(position #\^(e r-h))))(let((lr(-(car l-h)ll 1))(rr(-(car r-h)rl 1)))(let((p(d(max(m(length(car r)))(ceiling(+ lr rl)2))(car r))))(let((m-pad(if(>(car p)(+ lr rl))(-(car p)lr rl)0)))(l(cons(+ ll 1(car p)1 rr)())(loop as n in(butlast(cdr p))collect(c(b(+ 1 ll))n(b(+ 1 rr))))(cons(c(subseq(e l-h)0(+ 1 ll))(car(last p))(subseq(e r-h)rl))())(loop as y in(append(cddr l-h)(make-list(length l-h):initial-element(b(car l-h))))as z in(append(cdr(cdr r-h))(make-list(length r-h):initial-element(b(car r-h))))collect(c y(b m-pad)z))))))))))))(defun d(r n)(cons(+(* 2 r)1)(l(cons(c(b r)"^"(b r))())(loop as i from 1 to r collect(c(b(- r i))"/"(subseq(c n(b(expt i 2)))(expt(- i 1)2)(expt i 2))"\\"(b(- r i))))(cons(make-string(+ 1(* 2 r)):initial-element #\-)()))))(defun m(l)(+ 1(floor(sqrt l))))(defun b(n)(make-string n :initial-element #\space))(defun c(&rest a)(apply 'concatenate 'string a))(defun l(&rest a)(apply 'concatenate 'list a))(defun e(tree)(nth 1 tree))
```
Thanks to @coredump for a number of golfing tricks. Sample output from the question:
```
> (f '(("out" (("chr" ("72")) ("chr" ("101")))) ("out" (("chr" ("108")))) ("out" (("chr" ("108")))) ("out" (("chr" ("111"))))))
^ ^ ^ ^
/o\ /o\ /o\ /o\
/ut \ /ut \ /ut \ /ut \
/ \ ^----- ^----- ^-----
/ \ /c\ /c\ /c\
^---------^ /hr \ /hr \ /hr \
/c\ /c\ ^----- ^----- ^-----
/hr \ /hr \ /1\ /1\ /1\
^----- ^-----/08 \ /08 \ /11 \
/7\ /1\ ----- ----- -----
/2 \ /01 \
----- -----
> (f '( ("+" ( ("asdfghjkl") ("do" ( "1" )) )) ))
^
/+\
/ \
/ \
/ \
/ \
^-----------^
/a\ /d\
/sdf\ /o \
/ghjkl\ ^-----
/ \ /1\
--------- / \
-----
> (f '(("+" ("9123" "3")) "3"))
^ ^
/+\ /3\
/ \ / \
/ \ -----
^-------^
/9\ /3\
/123\ / \
/ \ -----
-------
```
Here is the original, (mostly) ungolfed version:
```
(defun f (input)
(let ((trees (loop for tree in input collect (g tree)))
(done nil)
(output ""))
(loop while (not done)
do (setf done T)
(loop for tree in trees
do (if (cdr tree)
(progn
(setf output (conStr output (car (cdr tree))))
(setf (cdr tree) (cdr (cdr tree)))
(setf done nil))
(setf output (conStr output (blank (car tree))))))
(setf output (conStr output (format nil "~%"))))
output))
;creates a single tree
;output is a list, first element is the length of each line, the rest are the lines of text
(defun g (tree)
(if (stringp tree)
;strings should be drawn as just the pyramid for the name
(draw-body (min-rows (length tree)) tree)
(if (< (length tree) 2)
;lists with no arguments should be drawn as just the pyramid for the name
(draw-body (min-rows (length (car tree))) (car tree))
(if (= (length (car (cdr tree))) 1)
;single child
(let ((child (g (car (car (cdr tree))))) (parent (draw-body (min-rows (length (car tree))) (car tree))))
(let ((parent_offset (+ 1 (position #\^ (first-line child)))) (parent_length (car parent)))
(if (< (- (car child) parent_offset) parent_length)
(let ((child-fill (- parent_length (- (car child) parent_offset))))
(concatenate 'list
(cons (+ parent_offset parent_length) nil)
(loop for line in (butlast (cdr parent))
collect (conStr (blank parent_offset) line))
(cons (conStr (subseq (nth 1 child) 0 parent_offset) (car (last parent))) nil)
(loop for line in (cdr (cdr child))
collect (conStr line (blank child-fill)))))
(let ((parent-fill (- (- parent_offset 1) parent_length)))
(concatenate 'list
(cons (car child) nil)
(loop for line in (butlast (cdr parent))
collect (conStr (blank parent_offset) line (blank parent-fill)))
(cons (conStr (subseq (nth 1 child) 0 parent_offset) (car (last parent)) (blank parent-fill)) nil)
(cdr (cdr child)))))))
;two children
(let ((l-child (g (car (car (cdr tree))))) (r-child (g (car (cdr (car (cdr tree)))))))
(let ((lc-l-width (position #\^ (first-line l-child))) (rc-l-width (position #\^ (first-line r-child))))
(let ((lc-r-width (- (car l-child) lc-l-width 1)) (rc-r-width (- (car r-child) rc-l-width 1)))
(let ((parent (draw-body (max (min-rows (length (car tree))) (ceiling (+ lc-r-width rc-l-width) 2)) (car tree))))
(let ((m-pad (if (> (car parent) (+ lc-r-width rc-l-width))
(- (car parent) lc-r-width rc-l-width)
0)))
(concatenate 'list
(cons (+ lc-l-width 1 (car parent) 1 rc-r-width) nil)
(loop for line in (butlast (cdr parent))
collect (conStr (blank (+ 1 lc-l-width)) line (blank (+ 1 rc-r-width))))
(cons (conStr (subseq (first-line l-child) 0 (+ 1 lc-l-width)) (car (last parent)) (subseq (first-line r-child) rc-l-width)) nil)
(loop for left in (append (cdr (cdr l-child)) (make-list (length l-child) :initial-element (blank (car l-child))))
for right in (append (cdr (cdr r-child)) (make-list (length r-child) :initial-element (blank (car r-child))))
collect (conStr left (blank m-pad) right))))))))))))
;create a single pyramid
; output is a list, first element is the length of each line, the rest are the lines of text
(defun draw-body (rows name)
(print rows)
(print name)
(cons (+ (* 2 rows) 1)
(concatenate 'list (cons (conStr (blank rows) "^" (blank rows)) nil)
(loop for i from 1 to rows
collect (conStr (blank (- rows i)) "/" (subseq (conStr name (blank (expt i 2))) (expt (- i 1) 2) (expt i 2)) "\\" (blank (- rows i))))
(cons (make-string (+ 1 (* 2 rows)) :initial-element #\-) nil))))
(defun min-rows (l)
(+ 1 (floor (sqrt l))))
(defun blank (n)
(make-string n :initial-element #\space))
(defun conStr (&rest args)
(apply 'concatenate 'string args))
(defun first-line (tree)
(car (cdr tree)))
```
[Try it Online!](https://tio.run/nexus/clisp#xVXLbtswELznKwgWbXYbCLWcQx9o@xU9BilkibLV0KRC0UCSQ349HT4ky3YSIECBGolE7c4O9zGinqhR7c6IljomrTzRQNraXlSDcKIzohO11VrVntbCMTMZwsXufL/zUmIZ0TvjOy2MaCwNyrdY/eJDniH4upbqxoGHemfXJmETF9XjQoV9RhxueQlboqZpeRy5orpK0BchrXXbyhPLx/cyoJIZ6NSGNWFPZDl415l1HzJoaIvGmLXfBObk/r63LOeIaf9xEcA/RmcsrMxt3tA6gJIRwP41Gs5Bli5ESb0dOt9ZI95dXSN@k@Irp4z/PSPomXOyRXzesOUDFEiptmYAqRVHHt6PDxowtNp5XQ0@zgLEoyZqWgnLJmQaiGoadqtB3casFvDEEkNgyuaYdZzuZsaIAa8EFYcJzUrgfTs6mAvkXh7VxVNlKeiN1eDa8UlJBuMunysrwSlqNtWyz1AXx3N20aLG5xGnj6eKyAg/cbhiM4tzuTMBrjU6gZDRFpAu2jI6aqy6e05nqtMQPJSgYdFQ9Yn2tkVfNUFPP7O6JjDn/XpOz4vZAIBBBtldCufeMoygdsRzGElcu5TPsdZC8YsJfDicCZS6cSjC@7B/1ffKNGl4gQktulGF7pBSfsuD9VtnMIVKF0qrLbSWD5s0JgbXwwFXPrWC95TPvcyXp7t/G@4hr9h6fuDZL59XDTlhckMu6KNYYmLlXv2IdSyvZbwfVN6J1tktOuYtzud5z4twXjPLT3LsXXwlSd31HmHLsHlYA9hBW0ueeeTVldxTjJOK9acTNZ5fKc2TDkDfRchxXx10yjGiRdqOhlvnhZ75V2R4zg49PUM69FWtppiaPjgFbVQchqXvxTlyrCuvDP7FeSaqJrx@HR/GOkMr8k4pzodFXPNT/ugIL@RjIwW14pxI4suDNcl643CXn5f4HonpsVyU8fskToDl4svbPWViw@/sKBtZ/OPfmTzZI1aMNC6wxK0amna9@XOjZUi1scEqSymQefz7fzmmFOXXcnmJXS/DROKVn/4C)
[Answer]
## [Python 3](https://docs.python.org/3/), ~41.3KB + tests and examples
So, I didn't realise this was a challenge, and I wrote a whole language which compiles into Pyramid scheme... üòÖ It's called psll, and you can find it [here](https://github.com/MarcinKonowalczyk/psll-lang). It has a bunch of bells and whistles, syntactic sugar constructs: functions (kinda) and strings, compiler optimisation etc.
This is not exactly a competing answer, but I feel it's heavily relevant so I should post it here.
] |
[Question]
[
# Challenge
Given a binary matrix and a binary string, determine if that binary string can be found starting at any point in the matrix and moving in any direction at any subsequent point to form the binary string. That is, can the string be found folded up however inside the matrix?
The string can only be folded at 90 degrees or 180 degrees (edge connections; Manhattan Distance 1) and cannot overlap itself at any point.
# Example
Let's take the following example:
```
Matrix:
010101
111011
011010
011011
Snake: 0111111100101
```
This is a truthy test case. We can see the snake folded up in the following position:
```
0-1 0 1 0 1
|
1 1 1-0 1 1
| | | |
0 1 1 0-1-0
| |
0 1-1 0 1 1
```
# Rules
* Standard Loopholes Apply
* You may take the length of the string and the width and height of the matrix as input if you'd like
* You may take the binary matrix and the binary string as a multiline string/array of strings/newline-joined string/anything else-joined string and a string
* You may take the dimensions as a flat array instead of several arguments
* Your program must finish for any 5 x 5 matrix with any string of up to length 10 in under a minute
# Limitations
* The matrix is not necessarily square
* The string will be non-empty
* The string can be length-1
* The string will not contain more squares than available (that is, `len(string) <= width(matrix) * height(matrix)`
# Test Cases
Truthy
```
01010
10101
01010
10101
01010
0101010101010101010101010
01110
01100
10010
10110
01101
011111000110100
0
0
10
01
1010
100
010
001
100010001
```
Falsy
```
00000
00000
00000
00000
00000
1
10101
01010
10101
01010
10101
11
100
010
001
111
10001
01010
00100
01010
10001
1000100010001000101010100
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~275~~ ~~271~~ ~~264~~ 249 bytes
* Saved four bytes by replacing `-1` with `H` and removing one slicing operation (`[:]`).
* Saved seven bytes thanks to [Halvard Hummel](https://codegolf.stackexchange.com/users/72350/halvard-hummel); removing yet another slicing operation (`[:]`), using multiple-target assignment to give a visited entry a value `v not in "01"` (`S=S[1:];M[y][x]=H;` -> `S=M[y][x]=S[1:];`) and switching from a ternary if/else to a simple logical or (`any(...)if S else 1` -> `not S or any(...)`).
* If you somewhat extend your definition of *truthy* and *falsey*, you could allow this [257 byte long solution](https://tio.run/##fU/PT4MwFL73r6jdpchTW4@MetJlF@Jhl21dD5iBNEIhQAQu/OvYgk5NjG3Sl/f9eN9rNbRZae6njThNeVy8nGMcwQ46yAK5pbKQgUrLGhdYGxyphYEeBs@hg0Pr2LwmNJuB/hvoPJ3inWRKiEgOSvZKXTN0TlK8pdGPOcHuixc7yQO1/ifW38PgH@akPRwsJ@nIgHlA@fwyGJfCPaXTkYXWEXYPLBTWFmZX4rKPf7CJ/l4ptyRO8iYZ2R2biritdS8IIYhxdxHn9uW2c@1SOLL8ujHxW@KUFpgPc3rnREd4FpIwokASThRapgKeLVjgIq5orpsW8MLYb99wddtUuW4pORnieYCdgM4OD3WAM@vLE0M/HUw5yaX3EFrhY1KXj/pdN7o0T3Vd1mhV1dq0eEN/bQDYzZstSVG1wxyF/pT6x0/x9AE "Python 2 – Try It Online"). It raises an exception (`ZeroDivisionError`) when the snake is found and returns an empty list (`[]`) when there is no snake to be found, which are two distinct behaviours.
* Saved fourteen bytes thanks to [user202729](https://codegolf.stackexchange.com/users/69850/user202729); golfing two array deep copies
* Saved a byte; golfed `not S or` to `S<[1]or` ~ `S==[]or`.
```
lambda M,S,w,h:any(H(eval(`M`),S,w,h,x,y)for y in range(h)for x in range(w)if S[0]==M[y][x])
def H(M,S,w,h,x,y):S=M[y][x]=S[1:];return S<[1]or any(H(eval(`M`),S,w,h,x+X,y+Y)for X,Y in[(~0,0),(1,0),(0,~0),(0,1)]if~0<x+X<w>0<=y+Y<h!=S[0]==M[y+Y][x+X])
```
[Try it online!](https://tio.run/##nY8/b8IwEMX3fIqrJ1u5VnZHiNsNsSCGdIAES7giaaIGg0IoycJXT50/QKUWiWJLtu7u996zt1WRbMxzPZKLOtPr95WGCfp4wGSgTUXHNPrSGV1OlqzrYokVizc5VJAayLX5iGjSNspL48DSGPyQKyknYaXCUjFnFcUwppMfLgP/NJV@KAZqmEfFPjfge6FQ1vBKvjvDyp23kTOc29CQHjlyhlS0J8djdwmm0vjIPavwDi/ck1bmJQ/y/DB3bsPdmWL1Whd5WkpCiMNFsx0h7Cls1ZTdJRw7H@6M/owa0jbaxRu@UToBTmVIOFEYEkGU07kitBKQsNZbmqW7AqGb2E8/CvW022ZpQcnCEMYQGoC2CuYcEBKryyJDewVXDXKumbPNU1PAiJ6yoE8DhEZtaQLyFd7yfUR@wYH7D7h3doMLbNmRznbXnW@Dp/c8Y3oL3DvfBgfuHc5/fbD@Bg "Python 2 – Try It Online")
# Explanation
Lambda function which takes in the matrix as a two-dimensional list of strings (either `"0"` or `"1"`), the snake as a one-dimensional list and the matrix dimensions as two integers.
The lambda function searches the matrix for entries that match the snake's first element. For every found match, it calls `H` with a deep copy of the matrix, no copy of the snake, the matrix dimensions and the match's position.
When `H` is called, it removes `S`' first entry and sets the given position's matrix entry to something else than `"0", "1"`. If `S`' length is zero, it returns `True`; as it calls itself recursively, the snake was found somewhere in the matrix.
If `S`' length is non-zero, it loops through the four cardinal directions, tests if that position is in the matrix, compares the matrix' element at that position with the first element of `S` and -- if it matches -- calls itself recursively.
`H`'s return values are funneled up the stack frames, always checking if at least one function found a possible snake.
# Formatted Output
I have augmented my program to also output the path the snake slithers (if there is one). It uses the same ASCII output design as the question. [TIO link](https://tio.run/##hVNNb@IwED3jXzFrqZJNDIo5BswR0QNiJVYVxPUhVcOSXRKiJBVEWvWvs@N8lRZQQXIynvfePHsmaVnsDsno/Bpu4SdbiJU4ip14FL5IuUd6aRYlBdBVEvwN4SH34Ff2FlJ4AEqHfw5RwnxOeqQXB0UWnUCBNqS3PWRQQpRAFiS/Q7azOg3CUVobhFSY0wfmyL0aoEvjqEdc9ckICrRj4pbq3rQ3kDcKDWQrM4ySPMwKVvZHjhSgUcn02bE/QggaXosNek2H6SFlLq@FTqKSSq3ZaIvmJrD2oC3ZH6EjK2aQSAe0BU1vgAafQSUqbS5BKGJhFehfB5p@Bg2@gtYCrOmTgLJry3PSdKHtRsztUWJ7kFqKOxZEellYvGUJSEJso5/aRtvWYPXkUMDsYw@uuj4L9nmIQheNX3FCZur5vA/il9cAGrIXJCWbMx1rz3RWFqYZK7xjcZ3CmF/NzNWAoM2Vdo1Si3o6eHWSeTeyVrsaW6UN91ZqpaVnxg1YzcfNDdzzh3Et46xF6WxqKUczlOW1PTs0UaLZuytcLpisVle81w/JTbR9dyfInxyn7kShyGT3Q3WenQ0acdamOgiEeJ9fv7eu2rnunaKUElfaP5ESV4mRDeuHJJgf57ZHFokb1c@1eMskvlgqTV1qhKaSGlKrCqgoOEpxkLJ9lBeiHTtpP6thnu6jgtmx4VyABbCKwclRwA55@xAHrWa4xkK6mJMn1laBpg4IsLzLlO/cTTUsx7/LupVafi@4vMu6lfKdb1mtjfN/).
[Answer]
# JavaScript (ES6), ~~138~~ 134
Not so different from @Neil's, but what else could it be?
Input: matrix as a multi line string, binary string, width (not counting newline)
NB: the logic in the recursive function `r` is somewhat inverted to save a couple of bytes
```
(m,s,w)=>[...m].some((c,p,m,r=(p,o)=>s[m[p]=r,o]&&([~w,-~w,1,-1].every(d=>m[d+=p]!=s[o]||r(d,o+1))&&(m[p]=s[o-1])))=>c==s[0]&&!r(p,1))
```
*Less golfed*
```
(m,s,w)=>(
m=[...m],
r= (p, o) =>
(m[p] = -w, s[o])
&& (
[~w, -~w, 1, -1].every( d =>
m[d+=p] != s[o] || r(d, o+1)
)
&& (m[p]=s[o-1])
),
m.some((c,p) =>c == s[0] && !r(p,1))
)
```
**Test**
```
var F=
(m,s,w)=>[...m].some((c,p,m,r=(p,o)=>s[m[p]=r,o]&&([~w,-~w,1,-1].every(d=>m[d+=p]!=s[o]||r(d,o+1))&&(m[p]=s[o-1])))=>c==s[0]&&!r(p,1))
// this slightly modified version tracks the path
var Mark=
(m,s,w)=>(m=[...m]).some((c,p,m,r=(p,o)=>s[m[p]=-o,o]&&([~w,-~w,1,-1].every(d=>m[d+=p]!=s[o]||r(d,o+1))&&(m[p]=s[o-1])))=>c==s[0]&&!r(p,1))
?m.map((c,p)=>c<-1?'.───│┘└.│┐┌.│'[((m[p-1]-c)**2<2)+((m[p+1]-c)**2<2)*2+((m[p+~w]-c)**2<2)*4+((m[p-~w]-c)**2<2)*8]:c<0?'*':c).join``:''
function go()
{
O.textContent =F(M.value, S.value, M.value.search('\n'))+'\n\n'
+Mark(M.value, S.value, M.value.search('\n'))
}
go()
```
```
#M {width:100px; height:100px }
```
```
<textarea id=M>010101
111011
011010
011011</textarea><br>
<input id=S value='0111111100101' oninput='go()'>
<button onclick='go()'>go</button>
<pre id=O></pre>
```
[Answer]
## JavaScript (ES6), 149 bytes
```
(m,s,w)=>[...m].some((c,i)=>c==s[0]&&g(m,s,i),g=(m,s,i)=>!(s=s.slice(1))||[~w,-1,1,-~w].some(o=>m[o+=i]==s[0]&&g(m.slice(0,i)+' '+m.slice(i+1),s,o)))
```
Takes the matrix as a newline-delimited string, the snake as a string and the width (as an integer). Loosely based on @JonathanFrech's answer.
[Answer]
# Mathematica, ~~180~~ ~~156~~ ~~141~~ ~~153~~ ~~138~~ ~~136~~ 104 bytes
```
MemberQ[#|Table[""<>Part[Join@@#,p],{x,1##4},{y,1##4},{p,FindPath[GridGraph@{##4},x,y,#3,All]}],#2,All]&
```
## Example input
```
[{{"1","1","1","1","1"},{"0","0","0","0","0"}},"10011001",8,5,2]
```
## Explanation
1. `GridGraph@{##4}` is a `Graph` object for a grid of vertices with adjacent vertices connected by edges, with dimensions `{##4}` - that is, `{#4,#5}` or `{width,height}`.
2. We iterate over all starting vertices `x` (numbered `1` to `1##4 = width*height`), all ending vertices `y`, and all paths `p` of length at most `#3` from `x` to `y`.
3. For each such path, `""<>Part[Join@@#,p]` extracts the corresponding characters of the matrix and puts them into a string.
4. We also include the matrix itself, whose characters are all the strings of length 1 that can be found in it.
5. We see if one of these strings matches `s`, searching at all levels because this is a very multidimensional list we've built.
Note: Replacing `#3` by `{#3-1}` in `FindPath`, so that we only find paths of exactly the right length, is a huge improvement in terms of speed - but costs 4 more bytes.
---
*-24 bytes: taking dimensions of things as input*
*-15 bytes: using `StringPart` and `StringJoin` properly*
*+12 bytes: fixing the length-1 case*
*-15 bytes: ...*
*-2 bytes: taking size of the matrix as input as an array*
*-32 bytes: using `Table` to iterate over the path lets us avoid using `Function`, and using `MemberQ[...,s,All]` lets us just sort of stick the matrix onto the table when dealing with snakes of length 1.*
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 346 341 336 302 297 bytes
```
(m,h,w,s,l)=>{for(int y=0;y<h;y++)for(int x=0;x<w;x++)if(N(x,y,l-1))return 0<1;return 1<0;bool N(int x,int y,int p){if(p<0)return 0<1;if(y<0|x<0|y==h|x==w||m[y,x]>1||s[p]!=m[y,x])return 1<0;int g=m[y,x];m[y,x]=2;if(N(x,y-1,--p)||N(x-1,y,p)||N(x,y+1,p)||N(x+1,y,p))return 0<1;m[y,x]=g;return 1<0;}}
```
[Try it online!](https://tio.run/##pVLBbqMwED2Xr5jesDJEdtqbcS4r7V66UaUe9hDlkFInQQUTYdJgAd@eNRhSElVtV4sH43m8eTNjO9JBlOXydNCx2sKT0YVMuRcla63hsfJ0sS7iCH4eVBTGqljiCsF@36flADxnWTKHJ7V@lSDg5Ke4wyNqTIiYV5ss9y0LjKDchDtuJhMyYKXFyvDIS4vFG3/hl2gwCRghuSwOuQIaMt4vWUh5mwgWLhQ70W7ek8pG70M6DrOICWld2tcIsatLIY51nS4Nlqs5q2u93K9uhfPJKEcruO1x7j5ixofqAoZBsCd1bT27Ntiv0UzYsJ44fFxMr7MdN9M0J@4Nu/yWxS/wex0rn3iVd@P2G1Jm97PyYPRUQBEYjmZo8IrBsDdH@oBBLxn0S4bVOBMaW/ZQYXt1kvbUqzYGmu7nQOzuCGjbxBm6bOac5MrouL@LvFfSs0@k3fjXBDe98l3XE22xAbrvIOZoPzKls0RO/@RxIR9iJf3u/vspw5RNf8niQaptsfMpufQZQc2sTZ1PCP8/rZm172i5g0Jmh75D9m3uveM2XnP6Cw "C# (.NET Core) – Try It Online")
5 bytes saved by golfing the `p` increment
5 bytes saved by taking in the snake length and starting at its tail, and removing an unnecessary space
34 bytes saved by reading the challenge properly and seeing I can take in the matrix's height and width
5 bytes saved, the single element test case failed, and the fix was beneficial
### Ungolfed
```
(m,h,w,s,l)=>{
// Go through every potential starting point
for(int y=0; y<h; y++)
for(int x=0; x<w; x++)
if(N(x,y,l-1)) // start the recursive steps
return 0<1; // return true if N returns true, otherwise check the next element
return 1<0; // return false as the snake doesn't fit into the matrix
// C#7 local function in a Func
bool N(int x, int y, int p)
{
// if there is no more snake to fit return true
if(p<0)
return 0<1;
// if m element has part of the snake or
// snake part doesn't match matrix element then return false
if(y<0 | x<0 | y==h | x==w || m[y,x]>1 || s[p] != m[y,x])
return 1<0;
// hold the current matrix element
int g=m[y,x];
// set the current matrix element to 2 to indicate it has a part of the snake
m[y,x]=2;
// check each of the four neighbours and recurse down that neighbour
// except if they are outside the matrix
if(N(x,y-1,--p) ||
N(x-1,y,p) ||
N(x,y+1,p) ||
N(x+1,y,p))
return 0<1; // return true if remainder of the snake fits into the matrix
// if snake doesn't fit then set the matrix element as not having part of the snake
m[y,x]=g;
// return false to indicate this neighbour direction doesn't fit the snake
return 1<0;
}
}
```
[Answer]
# [Kotlin](https://kotlinlang.org), 413 bytes
```
var x:(Array<Array<Char>>,String)->Boolean={b,s->fun f(s:String,x:Int,y:Int):Boolean{if(b[x][y]!=s[0])
return 0>1
if(s.length<2)
return 1>0
val v=b[x][y]
b[x][y]='Z'
try{return(-1..1).map{x+it}.flatMap{t->(-1..1).map{y+it}.map{t to it}}.filter{(X,Y)->(x-X)*(x-X)+(y-Y)*(y-Y)==1&&X in b.indices&&Y in b[0].indices&&f(s.substring(1),X,Y)}.any()}finally{b[x][y]=v}}
b.indices.any{x->(0..b[0].size-1).any{f(s,x,it)}}}
```
## Beautified
```
var x: (Array<Array<Char>>, String) -> Boolean = { b, s ->
fun f(s: String, x: Int, y: Int): Boolean {
if (b[x][y] != s[0])
return 0 > 1
if (s.length < 2)
return 1 > 0
val v = b[x][y]
b[x][y] = 'Z'
try {
return (-1..1).map{ x + it }
.flatMap { t -> (-1..1).map{y+it}.map { t to it } }
.filter { (X, Y) ->
(x - X)*(x - X) + (y - Y)*(y - Y) == 1 &&
X in b.indices && Y in b[0].indices &&
f(s.substring(1), X, Y) }
.any()
} finally {
b[x][y] = v
}
}
b.indices.any { x -> (0..b[0].size - 1).any { f(s, x, it) } }
}
```
## Test
```
var x:(Array<Array<Char>>,String)->Boolean={b,s->fun f(s:String,x:Int,y:Int):Boolean{if(b[x][y]!=s[0])
return 0>1
if(s.length<2)
return 1>0
val v=b[x][y]
b[x][y]='Z'
try{return(-1..1).map{x+it}.flatMap{t->(-1..1).map{y+it}.map{t to it}}.filter{(X,Y)->(x-X)*(x-X)+(y-Y)*(y-Y)==1&&X in b.indices&&Y in b[0].indices&&f(s.substring(1),X,Y)}.any()}finally{b[x][y]=v}}
b.indices.any{x->(0..b[0].size-1).any{f(s,x,it)}}}
data class Test(val board: String, val snake: String, val output: Boolean)
val tests = listOf(
Test("""01010
|10101
|01010
|10101
|01010""", "0101010101010101010101010", true),
Test("""01110
|01100
|10010
|10110
|01101""", "011111000110100", true),
Test("""0""", "0", true),
Test("""10
|01""", "1010", true),
Test("""100
|010
|001""", "100010001", true),
Test("""00000
|00000
|00000
|00000
|00000""", "1", false),
Test("""10101
|01010
|10101
|01010
|10101""", "11", false),
Test("""100
|010
|001""", "111", false),
Test("""10001
|01010
|00100
|01010
|10001""", "1000100010001000101010100", false)
)
fun main(args: Array<String>) {
tests.filter {(board, snake, expected) ->
val boardR = board.trimMargin().lines().map { it.toCharArray().toTypedArray() }.toTypedArray()
val result = x(boardR, snake)
result != expected
}.forEach { throw AssertionError(it) }
println("Test Passed")
}
```
] |
[Question]
[
>
> A [Pythagorean triple](https://en.wikipedia.org/wiki/Pythagorean_triple) consists of three positive integers a, b, and c, such that a2 + b2 = c2. Such a triple is commonly written (a, b, c), and a well-known example is (3, 4, 5). If (a, b, c) is a Pythagorean triple, then so is (ka, kb, kc) for any positive integer k. A primitive Pythagorean triple is one in which a, b and c are [coprime](https://en.wikipedia.org/wiki/Coprime).
>
>
>
Using this knowledge, we can create a sequence by chaining together the least lengths of triples, where the next element in the sequence is the hypotenuse (largest number) of the smallest primitive Pythagorean triple containing the previous element as the smallest one of its lengths.
Start with the smallest primitive Pythagorean triple (3, 4, 5). The sequence begins with `3`, and the hypotenuse (next element in the sequence) is `5`. Then find the smallest primitive Pythagorean triple with `5` as a leg, and you get (5, 12, 13). So the sequence continues with `13`.
Either output the sequence forever, or take an integer input `n` and output the first `n` elements of the sequence, either zero or one indexed.
You need to support output at least through and including `28455997`, but if the limit of the data type you are using was suddenly raised, it would need to work for that new limit. So you cannot hard code a list of numbers.
```
3
5
13
85
157
12325
90733
2449525
28455997
295742792965
171480834409967437
656310093705697045
1616599508725767821225590944157
4461691012090851100342993272805
115366949386695884000892071602798585632943213
12002377162350258332845595301471273220420939451301220405
```
[**OEIS A239381**](http://oeis.org/A239381)
Similar sequences (don't output these!):
* [A018928](http://oeis.org/A018928)
* [A077034](http://oeis.org/A077034) (the odd terms)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 19 bytes
```
o3ṄÆF*/€ŒPP€²+Ṛ$HṂß
```
Saved a byte thanks to @[Dennis](https://codegolf.stackexchange.com/users/12012/dennis) by refactoring to an infinite sequence.
Takes no input and arguments, then outputs the sequence infinitely by printing each term as it computes them. This method slows down as the numbers get larger since it depends on prime factorization.
[Try it online!](http://jelly.tryitonline.net/#code=bzPhuYTDhkYqL-KCrMWSUFDigqzCsivhuZokSOG5gsOf&input=)
This calculates the next term by computing the prime power factorization of the current term. For 12325, this is {52, 17, 29}. There is a variant of Euclid's formula for calculating Pythagorean triples {*a*, *b*, *c*},
![formula](https://i.stack.imgur.com/duO3u.png)
where *m* > *n* and the triple is primitive iff *m* and *n* are coprime.
To calculate the next primitive root from 12325, find *m* and *n* such that *mn* = 12325 and choose *m*,*n* so that gcd(*m*, *n*) = 1. Then generate all pairs of *m*,*n* by creating all subsets of {52, 17, 29} and finding the product of each of those subsets which are {1, 25, 17, 29, 425, 725, 493, 12325}. Then divide 12325 by each value and pair so that each pair is *m*,*n*. Compute the formula for *c* using each pair and take the minimum which is 90733.
* The previous method failed for determining the next term after 228034970321525477033478437478475683098735674620405573717049066152557390539189785244849203205. The previous method chose the last value as a factor when the correct choice was the 3rd and last primes. The new method is slower but will always work since it tests all pairs of coprimes to find the minimal hypotenuse.
## Explanation
```
o3ṄÆF*/€ŒPP€²+Ṛ$HṂß Main link. Input: 0 if none, else an integer P
o3 Logical OR with 3, returns P if non-zero else 3
Ṅ Println and pass the value
ÆF Factor into [prime, exponent] pairs
*/€ Reduce each pair using exponentation to get the prime powers
ŒP Powerset of those
P€ Product of each
² Square each
$ Monadic chain
+ Add vectorized with
Ṛ the reverse
H Halve
Ṃ Minimum
ß Call recursively on this value
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 36 bytes
```
3{@wB:?>:^a+~^=C:B:?:{$pd}ac#d,C:1&}
```
[Try it online!](http://brachylog.tryitonline.net/#code=M3tAd0I6Pz46XmErfl49QzpCOj86eyRwZH1hYyNkLEM6MSZ9&input=)
You have to wait for the program to time out (1 minute) before TIO flushes the output. In SWI-Prolog's REPL this prints as soon as it finds the value.
This will print the sequence forever.
After a few minutes on the offline SWI-Prolog's interpreter, I obtained `90733` after `12325`. I stopped it after this point.
This isn't complete bruteforce as it uses constraints to find pythagorean triples, though it is obviously not optimised for speed.
### Explanation
```
3{ } Call this predicate with 3 as Input
@w Write the Input followed by a line break
B:?> B > Input
+ The sum...
:^a ...of Input^2 with B^2...
~^ ...must equal a number which is itself a square
=C Assign a fitting value to that number and call it C
C:B:?:{$pd}a Get the lists of prime factors of C, B and Input
without duplicates
c#d, Concatenate into a single list; all values must be
different
C:1& Call recursively with C as Input
```
[Answer]
# Perl, 73 bytes
```
for($_=3;$_<1e9;$_=$a**2+$b**2){$a++until($b=($_+$a**2)**.5)==($b|0);say}
```
All Pythagorean Triples `a²+b²=c²` satisfy `a=r(m²-n²), b=2rmn, c=r(m²+n²)` for some integers `r,m,n`. When `r=1` and `m,n` are coprime with exactly one being divisible by 2, then `a,b,c` is a primitive triple, where `a,b,c` are all pairwise coprime.
With this in mind, given some `a`, I use a brute-force algorithm to calculate the smallest `n` such that `a²-n²` is a square, namely `m²`. Then, `c` is equal to `n²+m²`.
[Answer]
# Python 3, 178 bytes
```
from math import*
p,n=[3,5],int(input())
while len(p)<n:
for i in range(p[-1],p[-1]**2):
v=sqrt(i**2+p[-1]**2)
if v==int(v)and gcd(i,p[-1])==1:
p+=[int(v)];break
print(p)
```
This is basically just a brute force algorithm, and thus is very slow. It takes the amount of terms to output as the input.
I'm not 100% sure about the correctness of this algorithm, the program checks for the other leg up to the first leg squared, which I believe is enough, but I haven't done the math.
[**Try it on repl.it! (Outdated)**](https://repl.it/EIsx/0) (Please don't try it for numbers greater than 10, it will be very slow)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 27 bytes
```
Ii:"`I@Yyt1\~?3MZdZdq]}6MXI
```
This produces the first terms of the sequence. Input is 0-based.
The code is very inefficient. The online compiler times out for inputs greater than `5`. Input `6` took a minute and a half offline (and produced the correct `90733` as 6-th term).
[Try it online!](http://matl.tryitonline.net/#code=SWk6ImBJQFl5dDFcfj8zTVpkWmRxXX02TVhJ&input=NQ)
```
I % Push 3 (predefined value of clipboard I)
i % Input n
:" % For each (i.e. execute n times)
` % Do...while
I % Push clipboard I. This is the latest term of the sequence
@ % Push iteration index, starting at 1
Yy % Hypotenuse of those two values
t1\ % Duplicate. Decimal part
~? % If it is zero: we may have found the next term. But we still
% need to test for co-primality
3M % Push the two inputs of the latest call to the hypotenuse
% function. The stack now contains the hypotenuse and the
% two legs
ZdZd % Call GCD twice, to obtain the GCD of those three numbers
q % Subtract 1. If the three numbers were co-prime this gives
% 0, so the do...while loop will be exited (but the "finally"
% part will be executed first). If they were not co-prime
% this gives non-zero, so the do...while loop proceeds
% with the next iteration
] % End if
% If the decimal part was non-zero: the duplicate of the
% hypotenuse that is now on the top of the stack will be used
% as the (do...while) loop condition. Since it is non-zero,
% the loop will proceed with the next iteration
} % Finally (i.e. execute before exiting the do...while loop)
6M % Push the second input to the hypotenuse function, which is
% the new term of the sequence
XI % Copy this new term into clipboard I
% Implicitly end do...while
% Implicitly end for each
% Implicitly display the stack, containing the sequence terms
```
[Answer]
## Racket 106 bytes
```
(let p((h 3))(println h)(let p2((i 1))(define g(sqrt(+(* h h)(* i i))))(if(integer? g)(p g)(p2(add1 i)))))
```
Ungolfed:
```
(define (f)
(let loop ((h 3))
(let loop2 ((i 1))
(define g (sqrt (+(* h h) (* i i))))
(if (not(integer? g))
(loop2 (add1 i))
(begin (printf "~a ~a ~a~n" h i g)
(loop g))))))
```
Testing:
```
(f)
```
Output of golfed version:
```
3
5
13
85
157
12325
12461
106285
276341
339709
10363909
17238541
```
Output of ungolfed version:
```
3 4 5
5 12 13
13 84 85
85 132 157
157 12324 12325
12325 1836 12461
12461 105552 106285
106285 255084 276341
276341 197580 339709
339709 10358340 10363909
10363909 13775220 17238541
```
(Error after this on my machine)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 74 bytes
```
Nest[c/.#&@@Solve[{#^2+b^2==c^2,#<b<c&&GCD[b,c]==1},{b,c},Integers]&,3,#]&
```
[Try it online!](https://tio.run/##Dca9CsIwEADgVzkIZPH8acStkYIFcRHB8bhAElIt2BTa4BLy7NFv@iab3mGyafS2DqDrPayJ/H4nZNc95883UBZGbZxRWnujULSu9VJeLz059Kx1UzD/V/AWU3iFZWWJRxQsaz/TYxljogjbMwwUmRFyRDggNKfC9Qc "Wolfram Language (Mathematica) – Try It Online")
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 74 bytes
```
Nest[#&@@Cases[Divisors@#,d_/;GCD[d,#/d]<2&&d^2>#:>(d^2+(#/d)^2)/2]&,3,#]&
```
[Try it online!](https://tio.run/##Dci9CsIwEADgVzkIhBZPohEXf0KgBTdxP64STIoZmkITXMRnj50@@CZX3mFyJb5cHeFa7yEXEtLazuWQqY@fmOclW4H@qc63riePQnm@aCn9oI04mWZ106zZDrpVmiUeULCs/UyPJaZCCbYGRkrMCN@EsEPYH39c/w "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# PHP, 139 bytes
```
for($k=3;$i=$k,print("$k\n");)for($j=$i+1;($k=sqrt($m=$i*$i+$j*$j))>(int)$k||gmp_intval(gmp_gcd(gmp_gcd((int)$i,(int)$j),(int)$k))>1;$j++);
```
The above code breaks after 28455997 on 32-bit systems. If higher numbers are needed, it becomes 156 bytes:
```
for($k=3;$i=$k,print("$k\n");)for($j=$i+1;!gmp_perfect_square($m=bcadd(bcpow($i,2),bcpow($j,2)))||gmp_intval(gmp_gcd(gmp_gcd($i,$j),$k=bcsqrt($m)))>1;$j++);
```
[Answer]
# Java 8, 133 Bytes
-25 bytes thanks to miles ***Using n\*n instead of Math.pow(n, 2)***
-24 bytes thanks to miles ***Using for loops instead of while, changing datatype, eliminating () due to order of operations***
```
()->{long b=3,c,n;for(;;){for(n=1;;n++){c=b+2*n*n;double d=Math.sqrt(c*c-b*b);if(d==(int)d&b<d){System.out.println(b);break;}}b=c;}};
```
Uses the fact that
![Relation](https://wikimedia.org/api/rest_v1/media/math/render/svg/c5f23769007c289d0faf2092cbb00a4cb5630f1d)
for any pair of integers m > n > 0. Therefore, C is equal to A plus 2(N)2. The function above finds the least value of N that satisfies this relation, while making the second element of the Pythagorean triple an integer and greater than the first element. Then it sets the value of the first element to the third element and repeats with the updated first element.
Ungolfed:
```
void printPythagoreanTriples() {
long firstElement = 3, thirdElement, n;
while (true) {
for (n = 1; ; n++) {
thirdElement = firstElement + (2 * n * n);
double secondElement = Math.sqrt(thirdElement * thirdElement - firstElement * firstElement);
if (secondElement == (int) secondElement && firstElement < secondElement) {
System.out.println("Found Pythagorean Triple [" +
firstElement + ", " +
secondElement + ", " +
thirdElement + "]");
break;
}
}
firstElement = thirdElement;
}
}
```
[Ideone it!](https://ideone.com/4kyVX2)
\*The ideone does not print the last required element due to time limits, however as you can see through the logic of the program and the ungolfed version (which prints the 28455997 as the third element of the previous Pythagorean triple rather than the first element of the next), the values are, with a higher time limit, printed.
[Answer]
# Python 3.5, 97 bytes
*Wrong output after `28455997`, because of the limits of the floating point data type. The `sqrt` function isn't good enough, but if the precision was magically increased, it'd work.*
Pretty simple to understand. Incrementing `c` by two instead of one cuts the runtime in half, and only odd numbers need to be checked anyway, because the elements are always odd.
```
import math
c=a=3
while 1:
c+=2;b=(c*c-a*a)**.5;i=int(b)
if math.gcd(a,i)<2<a<b==i:print(a);a=c
```
[**Try it online**](https://repl.it/EIlM/5)
The program cannot be run on Ideone, because Ideone uses Python 3.4
---
For output to stay accurate longer, I'd have to use `decimal`:
```
import math
from decimal import*
c=a=3
while 1:
c+=2;b=Decimal(c*c-a*a).sqrt();i=int(b)
if i==b>a>2>math.gcd(a,i):print(a);a=c
```
[**Try it online**](https://repl.it/EIlM/6)
To stay accurate indefinitely, I could do something horrid like this (increasing the precision required *every single iteration*:
```
import math
from decimal import*
c=a=3
while 1:
c+=2;b=Decimal(c*c-a*a).sqrt();i=int(b);getcontext().prec+=1
if i==b>a>2>math.gcd(a,i):print(a);a=c
```
[Answer]
# [J](http://jsoftware.com/), ~~54~~ 47 bytes
```
-:@+/@:*:@((*/:~)/)@,.&1@x:@(^/)@(2&p:)^:(<12)3
```
[TIO](https://tio.run/##y/qfZmtloABEunoKzkE@bv91rRy09R2stKwcNDS09K3qNPU1HXT01AwdKoAicUCOhpFagZVmnJWGjaGRpvF/zf9KemkA "J – Try It Online")
greedy split of prime factors into coprime factors
[~~old 54 bytes TIO~~](https://tio.run/##y/qfpmBrpWCgAMK6egrOQT5u/zU0DLVjNRNiHfSALFttPU0tDVsbPU0HVSsHDY1YrVhNXY1orWhNTc04q3g7KyCpYWOhafxf87@SXhoA "J – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 71 bytes
```
n->a=3;for(i=1,n,a=[d^2+e^2|d<-divisors(a),gcd(d,e=a/d)<2&&d>e][1]/2);a
```
[Try it online!](https://tio.run/##FcwxDoMwDEDRq1gdUKw6oknVCZyLIJCsOkFZAgqoU@@e0uUPb/i71GzXvSXgVmwQfg5pqyazo0LCky7@Hhf/1dFq/uRjq4cRpPWtRimy9Iqj7zoNcZ7c3HscpP0HBRgeBO5FsNdczgtuYMOVZAoith8 "Pari/GP – Try It Online")
[Answer]
# APL(NARS), 169 chars, 338 bytes
```
h←{{(m n)←⍵⋄(mm nn)←⍵*2⋄(2÷⍨nn+mm),(2÷⍨nn-mm),m×n}a⊃⍨b⍳⌊/b←{⍵[2]}¨a←a/⍨{(≤/⍵)∧1=∨/⍵}¨a←(w÷a),¨a←∪×/¨{k←≢b←1,π⍵⋄∪{b[⍵]}¨↑∪/101 1‼k k}w←⍵}⋄p←{⍺=1:⍵⋄⍵,(⍺-1)∇↑h ⍵}⋄q←{⍵p 3x}
```
test ok until 14 as argument of q:
```
q 1
3
q 2
3 5
q 10
3 5 13 85 157 12325 90733 2449525 28455997 295742792965
q 12
3 5 13 85 157 12325 90733 2449525 28455997 295742792965 171480834409967437 656310093705697045
q 13
3 5 13 85 157 12325 90733 2449525 28455997 295742792965 171480834409967437 656310093705697045
1616599508725767821225590944157
q 14
NONCE ERROR
q 14
∧
```
this below would find all divisors of its argument...
```
∪×/¨{k←≢b←1,π⍵⋄∪{b[⍵]}¨↑∪/101 1‼k k}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
m√¡ȯ`ḟİ□o£İ□-9
```
[Try it online!](https://tio.run/##yygtzv7/qG2i6aOmxv@5jzpmHVp4Yn3Cwx3zj2x4NG1h/qHFYFrX8v9/AA "Husk – Try It Online")
This times out after the fifth element, but it’s an infinite list.
```
m√¡ȯ`ḟİ□o£İ□-9
9 Starting with 9
¡ Make an infinite list of legs^2 by applying this function repeatedly:
ȯ`ḟİ□o£İ□- This function finds the next leg, squared
`ḟ Find a number in
İ□ The infinite list of perfect squares, such that
- It minus the previous leg^2 is
£ An element of
İ□ The infinite list of perfect squares
m Then map each to
√ Its square root
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 101 bytes
```
_=>{for(var a=3,b,c;;){for(c=1;;c++)if(b=a+2*c*c,d=Math.sqrt(b*b-a*a),d==+d&a<d){alert(a);break}a=b}}
```
[Try it online!](https://tio.run/##Tc0xDsIgFAbg3VM4GR60TdQRnzfwDObnAVptilLSpenZ0Ti5fsv3wIxJcv8q7Zh8qBhCLixpnNIQuiHdNpHrlc9LTFnNyFvwsXGNWEs/Et5bK8ZQH5VjmIMWLY3nC8q9m965KKddCw36Ihu/w8nT8lsUyLoc8FzBbl3rX6qiIqof "JavaScript (Node.js) – Try It Online")
Suggestions on golfing are welcome
] |
[Question]
[
In this code golf challenge, you'll be computing the placement of ([open](https://en.wikipedia.org/wiki/Disk_(mathematics))) circles of areas \$\pi, 2\pi, 3\pi, \dots\$ when greedily placed along integer points in a square spiral in such a way that no two overlap.
A [square spiral](https://oeis.org/plot2a?name1=A174344&name2=A274923&tform1=untransformed&tform2=untransformed&shift=0&radiop1=xy&drawlines=true) is a sequence in \$\mathbb Z^2\$ that starts at \$(0,0)\$ and successively wraps around the origin. (Like [Arnauld](https://codegolf.stackexchange.com/a/222543/53884), you might find inspiration from [this CGSE question](https://codegolf.stackexchange.com/q/87178/53884).)
```
(0, 0) -> (1, 0) -> (1, 1) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (-1, -1) -> (0, -1) -> (1, -1) -> (2, -1) -> (2, 0) -> (2, 1) -> (2, 2) -> (1, 2) -> (0, 2) -> (-1, 2) -> (-2, 2) -> (-2, 1) -> (-2, 0) -> (-2, -1) -> (-2, -2) -> (-1, -2) -> (0, -2) -> (1, -2) -> (2, -2) -> (3, -2) -> (3, -1) -> (3, 0) -> (3, 1) -> (3, 2) -> ...
```
[![Example of a square spiral.](https://i.stack.imgur.com/mm2jS.png)](https://i.stack.imgur.com/mm2jS.png)
---
In this challenge, you will start at the origin, walk around the spiral, and place circles with areas \$\pi, 2\pi, 3\pi\$, at integer points in a greedy fashion, as shown in the GIF below.
The first seven circles are:
* a circle of area \$\pi\$ placed at \$(0,0)\$,
* a circle of area \$2\pi\$ placed at \$(2,2)\$,
* a circle of area \$3\pi\$ placed at \$(-2,2)\$,
* a circle of area \$4\pi\$ placed at \$(3,-2)\$,
* a circle of area \$5\pi\$ placed at \$(-3,-3)\$,
* a circle of area \$6\pi\$ placed at \$(5,5)\$, and
* a circle of area \$7\pi\$ placed at \$(0,6)\$.
![](https://i.stack.imgur.com/x9Q7c.gif)
Again, the circles are placed as soon as they fit. The second circle could not be placed at \$(1,0)\$, \$(1,1)\$, \$(0,1)\$, \$(-1,1)\$, \$(-1,0)\$, \$(-1, -1)\$, \$(0,-1)\$, \$(1, -1)\$, \$(2, -1)\$, \$(2, 0)\$, or \$(2, 1)\$ without overlapping with the first circle, but it could be—and is—placed at \$(2,2)\$.
Once we've placed "all" of the blue circles, we start over. In the second generation, we place "red" circles with areas \$\pi, 2\pi, 3\pi\$, in a greedy fashion:
![](https://i.stack.imgur.com/ZyUOV.gif)
Once we've placed all of the red circles from the second generation, we move onto yellow circles, cyan circles, magenta, dark green, purple, light green, orange, brown circles, and so on.
[![Process for ten generations](https://i.stack.imgur.com/XjL6W.gif)](https://i.stack.imgur.com/XjL6W.gif)
# Challenge
Okay! That's a lot of setup! Here's your [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge:
Write a program that takes in two positive (alternatively, \$0\$-indexed) integers, `g` and `k`, and outputs the position of the circle of area \$k\pi\$ in the \$g\$-th generation.
When \$g=1\$, this corresponds to the blue circles; when \$g=2\$, this corresponds to the red circles; when \$g=3\$, the yellow circles, and so on.
Your program should be able to compute all of the values in the following table in practice, and it should be able to compute bigger values (without running into floating point errors) in principle.
### Data table
```
g | k | position | (color in GIFs; for reference only)
---+----+------------+------------------------------------
1 | 1 | (0, 0) | blue
1 | 2 | (2, 2) | blue
1 | 3 | (-2, 2) | blue
1 | 50 | (36, -18) | blue
2 | 1 | (0, -4) | red
2 | 2 | (-3, 9) | red
2 | 14 | (-2, -59) | red
2 | 15 | (-66, 28) | red
3 | 1 | (-5, 2) | yellow
3 | 2 | (4, -10) | yellow
3 | 10 | (-58, 3) | yellow
8 | 1 | (-6, 10) | orange
8 | 2 | (16, 21) | orange
8 | 3 | (-27, -19) | orange
9 | 1 | (-10, 6) | crimson
9 | 2 | (-25, 4) | crimson
9 | 3 | (17, -27) | crimson
```
[Answer]
# JavaScript (ES7), ~~319~~ 309 bytes
Expects `(g)(k)` and returns `[x,y]`.
The formula for the spiral coordinates was inspired by [this answer from Neil](https://codegolf.stackexchange.com/a/87394/58563).
```
g=>k=>{a=[];p=[];r=[];H=Math.hypot;F=n=>{while((j=p[n]=-~p[n],C=_=>((i+2>>2)-i%2*j)*~-(i--&2),x=C(i=(--j*4+1)**.5|0,j-=i*i>>2),y=C(),n)&&a.every(([N,X,Y])=>~N+n|H(X,Y)<2*H(x,y))&&!F(n-1,p[n]--)||a.some(([_,X,Y,R])=>H(X-x,Y-y)<R**.5+q**.5,q=-~r[n]));a.push([n,x,y,r[n]=q])};while(~~r[g-1]<k)F(g-1);return[x,y]}
```
[Try it online!](https://tio.run/##dZBNb4JAEIbv/RX0UDODOyiLmDa4XEyMl/bgqYYQQywqaBfEj0qq/nW7m1ZTK73MfuR5d57ZNNpGq3GR5GuS2Vt8mojTVPhz4X9GIgi9XJdCl754jtYza1bm2drrCamIj1myiAFSkQcyFHTUC@uKkfABkjr3fY6UPHAzRfNIkBDVOLKd6EIigCg1W3UbTdNy902WkkjMRCdYqQBkEmu1yIq3cVECBC/slQ1DFP7xpS73fVAn7HCzDztWoiLveyDJZlqACPf7yFpl70otGOkgG@ioStGODanEzkB3rS91ZUslXqgcohdZ@WY1g0Ay9SzTl2IZ4sH7nvOosCnZYWeOPVAb9Ip4vSlkoODwcBpncpUtYmuRTWECNoJhIxqNhgGG0WSGKnh3y/ALwzXDqxjnzNC/jNs8M06bGWQ//mX4jQ@1qpiLDzm611MFY7eufNxKxv1hqK18DH7j4/z2IbdyLufqf1p6riaevgA "JavaScript (Node.js) – Try It Online")
### How?
One tricky point in the challenge is to figure out how many circles of generation \$n-1\$ must be processed before we can start generation \$n\$.
In this implementation, we don't attempt to put a new circle of generation \$n\$ at \$(x\_0,y\_0)\$ until there's at least one circle of generation \$n-1\$ at \$(x\_1,y\_1)\$ which is at least twice as far from the center of the spiral:
$$\sqrt{{x\_1}^2+{y\_1}^2}\ge2\times \sqrt{{x\_0}^2+{y\_0}^2}$$
[Answer]
# JavaScript (ES2020), ~~417~~ ~~338~~ ~~331~~ ~~323~~ ~~321~~ ~~318~~ ~~316~~ ~~304~~ ~~303~~ ~~290~~ ~~283~~ ~~273~~ ~~269~~ ~~261~~ ~~257~~ ~~252~~ ~~247~~ ~~244~~ ~~237~~ ~~234~~ ~~238~~ ~~234~~ ~~207~~ ~~206~~ ~~205~~ ~~200~~ ~~194~~ ~~193~~ ~~186~~ ~~182~~ ~~183~~ 182 bytes
```
G=>K=>eval('for(l=[];G--;)for(x=y=d=0,L=t=i=1,X=l[G]=[];t--,K<<3*G>=i;d%2?y+=2-d%4:x+=1-d%4,t||=L+=d++%2)X[l.some(Z=>Z.some(([M,N],R)=>Math.hypot(M-x,N-y)<R**.5+i**.5))||i++]=[x,y]')
```
[Try It Online?](https://ato.pxeger.com/run?1=ZY7BasJAFEX3_Y_gvMxMMFFBmtwpXWWhceFKDFlIJ5rA6JQ6LQnkT7oJpf2F_kv_pgbduXnv3sPj3vf5fbK67L8q_Ly7vZz__aZQC6jyY2fYaG_fmEFexKmUMQ2uQQuNsVjCoUYoNjB5WgwnTkqxSJKJnyrUsfaip5YjktqbPjYc4SCE6zosOTTnXkSb3ARneyzZFmp7VSzPxKoQa4LKdq4KqvbVOpbJRqxkS8na94MZr4dJ1HU155fmRrTFiG7fP7_Y09maMjD2wCoWEQunRA_3dHZHJxc6pltQ31_3Pw)
Severely golfed. Very inefficient. Thanks to @Neil for getting rid of all the spare bytes I had lying around, and @tsh for removing a lot more. Takes G 1-indexed and K 1-indexed. -1 byte thanks to ophact.
Somehow beat @Arnauld, ~~but still losing to @tsh by a lot~~ somehow outgolfed tsh as well.
# Explanation
Slightly different to actual code.
```
G => // A function taking G (generation)
K => { // and K (circle number)
for( // Start a loop...
l = []; // l = 2d list of circles we've already found, starts empty
G--; // Looping G times...
)
for( // Another loop
// Initialise some variables
x = y = // x, y = current coordinates in the spiral
d = 0 // d = direction of current leg of spiral, initialise them all to 0
t = // t = distance to end of spiral
i = // i = current radius
L = 1, // L = total length of current leg of spiral
X = l[G] = []; // Add an empty list to l, which gets assigned to X.
t--,
K << 3 * G >= i; // Every generation, search for 8x less circles (probably enough, can always be increased)
d % 2 ? // If moving vertically
y += 2 - d % 4 // Change y
: x += 1 - d % 4, // Else change x
t ||= // If t is falsy, set t to...
L += // L incremented by...
d++ % 2 // direction modulo 2
)
l.some( // Do any values in l have the property that...
Z=>Z.some( // Any of their values have the property that...
([M,N],R) => // (M, N = coords, R = radius)
Math.hypot(M - x, N - y) // Is the distance to the point we're on right now...
< R ** .5 + i ** .5 // Less than the sum of their radii?
)
) ? 0 : // If not, we can place a circle.
X[i++] = [x,y] // Increment i (radius of circle we're trying to place), and append the coordinate to X
// The above is returned when the loop ends because i is too large.
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 211 bytes
```
g=>k=>{for(N=1;n=N;N*=2)for(G=g,C=[];G--;n-=r*3)for(o=[x=X=0,Y=y=s=1];x<n;o[[x+Y,y+X]]?0:[X,Y]=[Y,-X])if(!(o[[x+=X,y-=Y]]=C.some(([X,Y,R])=>Math.hypot(X-x,Y-y)<R+r,r=s**.5)||s++-k|G*C.push([x,y,r])))return[x,y]}
```
[Try it online!](https://tio.run/##bc@xboMwEIDhvU/RbjbYKECRQp2jAwNTGTKBLA9RCiRNipFNKlDps9MkysaN9@n06@5r97Oze3Pset7qz2quYW4gOUHyW2tDcvBFC7nIHQjoDTJoWApSiYxz0XIwTnh3DXKAAlashBEs@EoMm1ZoKQe3ZKNbKPW@epMFKxXIkvFC0WNNXsh9AQo2ciiVgtSz@rsi5LbItopC8rHrD95h7HRPCj6wko90s3UNM2Adx4voNFnX5acpc1Kvu9gDkQMbmVGUUlP1F9PeZvU373Vr9bnyzrohNfEpefYpFU9LDnAOUY5WSw7wdoC3r@y/4hwtOcTbId6@so8cuMYjazyyxp@P8UiMR@JHZP4H "JavaScript (Node.js) – Try It Online")
* -3 bytes by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
---
```
g=> // input: generation
k=>{ // input: circle area
for(
N=1; // Search bound, we try to search generation 1
// circles in [-N,N]x[-N,N]
n=N; // Search bound of current generation
N*=2 // If we cannot locate (g,k) circle
// we try a larger bound later
)
for(
G=g, // Number of generation (count down)
C=[]; // All Circles found yet
G--; // Count down 1 generation
// I'm not quite sure if next line is correct.
// But it passes all testcases, at least.
// Change to `n=n/4-r*4` would somehow ensure
// its correctness, but also make it slow as hell.
n-=r*3 // A smaller search bound for next generation
)
for(
o=[ // All points visited, stored by key
// For example, if (3, 4) is visited
// o['3,4'] would be something truthy
x= // Current x
X=0, // Current x axis direction
Y= // -Y is current y axis direction
y= // current y
s=1 // current circle area is s*PI
]; // Values initialized in Array o are harmless garbage
// As index `0` or `1` is not in `x,y` format
x<n; // Search in the bound
o[[x+Y,y+X]]?0: // If the left side point is not visited
[X,Y]=[Y,-X] // we turn left
)
if(!( // !(a||b) iff !a&&!b, known as De Morgan's laws
o[
[x+=X,y-=Y] // Move one step forward
]= // Mark current point visited
// Is there a circle intersect with current one (if
// we placed it here)?
C.some(([X,Y,R])=>Math.hypot(X-x,Y-y)<R+r,r=s**.5)||
// If no such circle, we need to place a circle here
s++-k| // Is current area equals to user input `k`?
// Increase the area for next circle by `s++`
// `|` do not use short-circuit evaluation
G* // Is current generation counted down to 0?
C.push([x,y,r]) // Push it to list of circles
// C.push(...) always returns positive
// So multiply by G is harmless
))
return[x,y] // Return current circle if it is asked for
}
```
] |
[Question]
[
There is a "sorting algorithm" sometimes called Stalin sort in which in order to sort a list you simply remove elements from the list until it is sorted in increasing order. For example the list
```
[1, 2, 4, 5, 3, 6, 6]
```
When "sorted" using Stalin sort becomes
```
[1, 2, 4, 5, 6, 6]
```
The three was removed because it was out of order.
Now obviously there are many ways to remove elements to sort a list. For example any list with less than two elements must be sorted so by just removing enough elements blindly we can always sort a list. Since this is the case we only care about the *longest* possible result from a Stalin sort.
Your task will be to take a list of positive integers and output the length of the longest sorted (increasing) list that can be arrived at by removing elements from the original list. That is find the length of the longest sorted (possibly non-contiguous) sub-list.
Sorted lists can have the same element more than once in a row. You do not need to support the empty list unless your program itself is empty.
# Scoring
Your answer will be scored by the length of its own longest possible Stalin sort. Programs will be interpreted as a sequence of bytes rather than characters, and their order will be the natural one that arises by interpreting the bytes as numbers. Lower scores are better.
# *This is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")*
Here's [a neat-o tool](https://ptpb.pw/SVSt.html) to help you score your answers.
# Test cases
```
[1, 2, 4, 5, 3, 6, 6] -> 6
[19, 2] -> 1
[3, 3, 4, 3] -> 3
[10] -> 1
[1, 2, 4, 9] -> 4
[1, 90, 2, 3, 4, 5] -> 5
[1, 90, 91, 2, 3, 4, 5] -> 5
```
[Answer]
# [Python 2](https://docs.python.org/2/), length ~~14~~ ~~12~~ ~~10~~ 9
```
M=max;X=exit;i=input();L=[0]*M(i)
for a in i:L[a-1]=M(L[:a])+1
X(M(L))
```
Output is via exit code.
[Try it online!](https://tio.run/##XY9da4MwFIavza84lA6TTsXoOvCru9qdhbLddGReZJpiYEvEOtZC/7uLOvcFIeE87znnffPCj3Vf8g7SFDy4QC14BW4JLoUNlLoSXnPut9kbPyX7TJxkl8hMqua9wyTJM@YXqy2WBB10a3FLKkvGOeMuLbItzlnMC3JN0R6bgpDeQ@ijlq8CWmOSQKWR1bRSdQewr9wgPIK7ARsWy4f7Xf60MOK5q7UK5hgmYvpLFWWtYXmHKq0EQvOiZ/VY6lbEYKNpPBx@Y48yZivdCIV94g0JMPGEGnZjUhAb0m@fC/xzRl9ePaMOBA7cOLB2IHTg1pwCMRoZbN5whEYNB@gP19wfTUXkj2DqWv@wiP7lnw "Bash – Try It Online")
### How it works
At all times, the array \$L\$ keeps track of the longest sorted subarrays encountered so far; \$L[a-1]\$ is the length of longest one that ends with \$a\$.
Initially, we haven't processed an array elements, so \$L\$ consists entirely of zeroes.
When processing the array element \$a\$, we first take the maximum of \$[L[0], \dots, L[a-1]]\$, which is length of the longest sorted subarray encountered so far that ends with \$a\$ or a smaller integer. Appending \$a\$ to such an array will keep it sorted, so the longest sorted subarray ending in \$a\$ is one element longer than that maximum. We update \$L[a-1]\$ with the computed value.
The final result is the maximum of \$L\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score 9
```
Length@*LongestOrderedSequence
```
[Try it online!](https://tio.run/##ZZBRS8MwEMff8ylCBFHJcF23Qa0ZhakgDBS6t9iH0l7boEtqmsFgbF@93jJWFCEv9/vd/bnLJncNbHKniryvOmdF6qzS9Tr/BMn6FejaNcndyugaOvdmS7BQpvC9BV1Az/h@wkeTQ0YqsTbPu9ZC1ymjk1MSITdkrzQ3W3cQV8dzbtp@KXdkdLSgLCZK/xmTbKU6xx4XSmcxjokXazZPqlauS7CMyTtGOMledbt1VFDGMZ5xiu4CquSMYNdC4aD0EP2JFcZahEOfEAJNFpPb6/vk13qSyYDTCadTTmechpzO8WWnnedEBhE6XwREhl5jX@hJiHp8cUNG5MnUk2js6Xlo5sVsEFHwXzLOPjTLyOX2FK@AB3/B2iyb3OZ4pl2aEvynZ/0P "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), length ~~4~~ 2
```
ṢƑƇZLƲ}ŒP
```
[Try it online!](https://tio.run/##y0rNyan8///hzkXHJh5rj/I5tqn26KSA/4fbHzWtUXi4c7GBgvv//xpcCrmJBRrJ@Smp8QWJ6al6aZl5KToK6mi61DV1FKJjdRSUFYqT84tSuRSiDXUUjHQUTHQUTHUUjHUUzIAoVgckbgmUALOMwRJAFcYQCQMIBdNnCeNaGoCFIGpNkUUtDdFkNAE "Jelly – Try It Online")
### Bytes in [Jelly's code page](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page "Code page · DennisMitchell/jellylanguage Wiki")
```
183 146 144 90 76 169 125 19 80
```
### How it works
```
ṢƑƇZLƲ}ŒP Main link. Argument: A (array)
ŒP Powerset; yield P, the array of all sub-arrays of A.
Ʋ Vier; combine the preceding four links into a monadic chain...
} and apply the chain to the right argument (P).
Ƈ Comb; only keep arrays for which the link to the left returns 1.
ṢƑ Sort fixed; yield 1 if sorting doesn't alter the array.
Z Zip; read the filtered powerset by columns.
L Take the length.
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), score 9
```
*.combinations.map({@^a*[<=] @a}).max
```
[Try it online!](https://tio.run/##jVFha4MwEP1cf8WjhFVtGrSuBecU/4fE4pxuKbMWHWVF/O3uEldovw0Cl/cu9@7d5Vx1X/upueKpRjy5omybN3UqvlV76kVTnO0hzQs3e40l0mJ0iPqZIqsvrqhtdnBQt51l@xxbjmeOHUfAsafjcKJD4vUlMDTlA0N73IRbUfiHQs8w88vdHRn6D4nIsgZrQZbTPjKRNYjBDhufYNpnrJGENSBzmt8KITxsEjAFqjQlF3pixrNFxvKjTGKKSjquFjjKkTOVC5GvaUY9M9ZG0MgrLc8uGs6dFVStFZMYc3tKjdZCL2nZl21XvWCYE@MymnmRkWuOAdT81kiKj64iRw@G5pXbpv5ACCNomhxe4kKK8rOjHYz26l8ftxJt99470y8 "Perl 6 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), Score ~~8~~ 7, 48 bytes
```
(l:k)%d|d>l=k%d|3>2=max(1+k%l)(k%d)
c%b=0
a=(%0)
```
[Try it online!](https://tio.run/##jY5BasMwEEX3OsUQ2zBDQ7GTnWG0aW6RdDGSTSwsy0ZRIAvd3RVtD5DVvHn8xZvkMY/e727Z1pjgIkk@vyaJO/p@pmbIg/Y8l3vWJ17khd3H3HjCokjZxnCrhLFpaX@CgMl@DPc0FdTwjwa4vBk63RYySio0vaUs2rBUNhfPT5TeVJawCCoLw1f5Vo4Pb1Tcwm/GLfx1HNQiLvAWXUg1JnG@RjtFaKlyR6kX2WCNAzjafwA "Haskell – Try It Online")
The longest sorted sublist is
```
%%%%%%)
```
[Answer]
# Pyth, score ~~3~~ 2 (~~7~~ bytes)
```
leSI#y
```
Saved a point thanks to Anders Kaseorg.
[Try it here](http://pyth.herokuapp.com/?code=leSI%23y&input=%22leSI%23y%22&debug=0)
### Explanation
```
leSI#y
yQ Take the power set of the (implicit) input (preserving order).
SI# Get the ones that are sorted.
e Take the last (longest).
l Get the length.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 4 maximal length stalin sort
```
S{:^fF%|M
```
[Run and debug it](https://staxlang.xyz/#c=S%7B%3A%5EfF%25%7CM&i=%22S%7B%3A%5EfF%25%7CM%22%0A[1,+2,+4,+5,+3,+6,+6]+%0A[19,+2]+%0A[3,+3,+4,+3]+%0A[10]+%0A[1,+2,+4,+9]+%0A[1,+90,+2,+3,+4,+5]+%0A[1,+90,+91,+2,+3,+4,+5]%0A&a=1&m=2)
It works like this.
```
S powerset of input
{:^f filter by non-descending sequences
F%|M take the maximum length remaining
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), length 2 (4 bytes)
```
⊇≤₁l
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/1FX@6POJY@aGnP@/4@ONtRRMNJRMNFRMNVRMNZRMAOiWB2FaEtLHTMdI2MQ0wIsYWgEpA0NLGJjAQ "Brachylog – Try It Online")
An answer which makes up for being so concise by not being that much shorter sorted.
(`08 03 80 6C` in Brachylog's code page)
```
Output
l the length of
≤₁ a non-decreasing
⊇ sublist of
the input.
(maximizing the size of the sublist)
```
[Answer]
# [R](https://www.r-project.org/), Score ~~15~~ 11, ~~72~~ 62 bytes
```
function(L,M=max,A=1:M(L)*0){for(Y in L)A[Y]=M(A[1:Y])+1;M(A)}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NHx9c2N7FCx9HW0MpXw0dTy0CzOi2/SCNSITNPwUfTMToy1tZXwzHa0CoyVlPb0BrI1qz9n6aRrGGsY6xjomOsqckF4hnqGAF5lnCepYGOJUgMpMYULFpakmYRku@ZV6KhRJntSpqaCsoKJZm5qcUK@aUl/wE "R – Try It Online")
Ports [Dennis' Python answer](https://codegolf.stackexchange.com/a/174994/67312) to R.
] |
[Question]
[
The [happy ending problem](https://en.wikipedia.org/wiki/Happy_ending_problem) (actually a theorem) states that
>
> Any set of five points in the plane in general position has a subset of four points that form the vertices of a convex quadrilateral.
>
>
>
The problem was [so named by Paul Erdős](http://mathworld.wolfram.com/HappyEndProblem.html) when two mathematicians who first worked on the problem, Ester Klein and George Szekeres, became engaged and subsequently married.
Clarifications:
* *[General position](http://mathworld.wolfram.com/GeneralPosition.html)* here means that no three points are collinear.
* The quadrilateral formed by the four vertices will always be considered to be non-intersecting, irrespective of the order of the points. For example, given the four points `[1 1]`, `[1 2]`, `[2 1]`, `[2 2]` the intended quadrilateral is the square, not the bow-tie:
[![enter image description here](https://i.stack.imgur.com/uciCw.png)](https://i.stack.imgur.com/uciCw.png)
* A non-intersecting quadrilateral is [convex](http://www.cut-the-knot.org/Curriculum/Geometry/Quadrilaterals.shtml) if no interior angle exceeds 180 degrees; or equivalently if both diagonals lie inside the quadrilateral.
## The challenge
Given 5 points with positive integer coordinates, output 4 of those points that form a convex quadrilateral.
## Rules
If there are several solutions (that is, several sets of 4 points), you can consistently choose to output one of them or all.
Input and output formats are flexible as usual (arrays, lists, list of lists, strings with reasonable separators, etc).
Code golf, fewest bytes wins.
## Test cases
1. Input:
```
[6 8] [1 10] [6 6] [5 9] [8 10]
```
There is only one possible output:
```
[6 8] [1 10] [6 6] [5 9]
```
2. Input:
```
[3 8] [7 5] [6 9] [7 8] [5 1]
```
There are five solutions:
```
[3 8] [7 5] [6 9] [7 8]
[3 8] [7 5] [6 9] [5 1]
[3 8] [7 5] [7 8] [5 1]
[3 8] [6 9] [7 8] [5 1]
[7 5] [6 9] [7 8] [5 1]
```
3. Input:
```
[4 8] [1 9] [9 9] [10 2] [1 6]
```
There are three solutions:
```
[4 8] [1 9] [10 2] [1 6]
[4 8] [9 9] [10 2] [1 6]
[1 9] [9 9] [10 2] [1 6]
```
To illustrate, here are the three solutions to this case:
[![enter image description here](https://i.stack.imgur.com/pFERO.png)](https://i.stack.imgur.com/pFERO.png)
[Answer]
## CJam, ~~37~~ ~~34~~ 32 bytes
```
{e!Wf<{2*3ew{)f.-~W%.*:-V>},!}=}
```
Not sure if `:-V` is happy enough, but as K Zhang points out, there's the `=}` at the end. :)
This only prints one solution because removing duplicates would be more expensive.
[Test it here.](http://cjam.aditsu.net/#code=%5B%5B4%208%5D%20%5B1%209%5D%20%5B9%209%5D%20%5B10%202%5D%20%5B1%206%5D%5D%0A%0A%7Be!Wf%3C%7B2*3ew%7B)f.-~W%25.*%3A-V%3E%7D%2C!%7D%3D%7D%0A%0A~p)
### Explanation
The idea is fairly simple. We generate all possible quadrilaterals (including all orderings of the points) and then just select the convex ones. We test convexity by looking at every pair of edges and checking that they're all turning in the same direction.
The turning sense can be obtained quite easily from a dot product. If you take the three consecutive points on a quadrilateral, and draw lines from the first to the second, and the first to the third, and then project the latter onto the perpendicular of the former... you get a number whose sign tells you whether these three points turn left or right. (I should probably add a diagram for this.) This "projecting onto the perpendicular" is sounds quite involved, but really just means that we reverse one of the two vectors and subtract the components after multiplication instead of adding them. So here's the code...
```
e! e# Generate all permutations of the five input points.
Wf< e# Discard the fifth point in each permutations, giving all
e# possible quadrilaterals.
{ e# Select the first for which this block gives a truthy result...
2* e# Double the list of points, so that it includes each cyclically
e# adjacent set of three points.
3ew e# Get all sublists of length 3, i.e. all sets of three consecutive
e# points (with two duplicates).
{ e# Filter these sets of three points...
) e# Pull off the last point.
f.- e# Subtract it from the other two, giving vectors from it to
e# to those.
~ e# Unwrap the array dumping both vectors on the stack.
W% e# Reverse one of them.
.* e# Element-wise multiplication.
:- e# Subtract the second element from the first. This completes
e# the projection.
V> e# Check whether it's greater than 0. This is *false* for right-
e# turning sets of three points.
}, e# If all corners are right-turning, this will result
e# in an empty array.
! e# Logical NOT - hence, only quadrilaterals where all corners
e# are right-turning give something truthy.
}=
```
[Answer]
# MATLAB, 67 bytes
```
I=input('');for k=~eye(5);if nnz(convhull(I(k,:)))>4;I(k,:),end;end
```
Input is in the form of a 2D matrix where the columns are X and Y respectively:
```
[6 8; 1 10; 6 6; 5 9; 8 10]
[3 8; 7 5; 6 9; 7 8; 5 1]
[4 8; 1 9; 9 9; 10 2; 1 6]
```
All sets of 4 points that create convex quadrilaterals are displayed in the same format.
Here is [a demo](http://ideone.com/8WQ5w0) that is slightly modified to work with Octave
**Explanation**
This solution takes all subsets of 4 points of the input (order doesn't matter). To do this, we create the identity matrix and negate it: `~eye(5)`. We loop through the columns of this matrix and `k` (the loop index) is a logical array which specifies which of the 4 points to consider. We then use this to grab these 4 XY points from the input (`I(k,:)`).
We then compute the convex hull of these 4 points (`convhull`). The output of `convhull` is the indices of the input that correspond with the points that make up the convex hull (with the first index duplicated to close the hull).
For a convex quadrilateral, all four points will be part of the convex hull of the same points (`nnz(convhull(points)) > 4`). If we detect that this is the case, we display the points that were used for this particular iteration.
[Answer]
# Javascript (ES6), ~~306~~ ~~293~~ 283 bytes
```
c=(v,w,x)=>(w[0]-v[0])*(w[1]-x[1])-(w[1]-v[1])*(w[0]-x[0])>0?1:0
i=(v,w,x,y)=>(c(v,w,x)+c(w,x,y)+c(x,y,v)+c(y,v,w))%4==0&&r.push([v,w,x,y])
j=(v,w,x,y)=>{i(v,w,x,y);i(v,w,y,x);i(v,x,w,y)}
k=(v,w,x,y,z)=>{j(v,w,x,y);j(v,w,x,z);j(v,w,y,z);j(v,x,y,z);j(w,x,y,z)}
f=(v)=>(r=[],k(...v),r)
```
**Explanation**:
The function `c` computes the cross product of the vector between 3 adjacent points of the polygon and returns 1 if it is positive and 0 otherwise (note: the cross product cannot be zero as the points cannot be co-linear).
```
j=(v,w,x,y)=>{i(v,w,x,y);i(v,w,y,x);i(v,x,w,y)}
k=(v,w,x,y,z)=>{j(v,w,x,y);j(v,w,x,z);j(v,w,y,z);j(v,x,y,z);j(w,x,y,z)}
```
The function `k` and `j` generate all cyclic permutations (ignoring reversing the order) of the input array.
```
i=(v,w,x,y)=>(c(v,w,x)+c(w,x,y)+c(x,y,v)+c(y,v,w))%4==0&&r.push([v,w,x,y])
```
The function 'i' is then called for each cyclic permutation to calculate the sum of the function `c` for each of the 4 triplets of adjacent co-ordinates. If the cross products all have the same sign then they will all either be 0 or 1 and total to 0 (modulo 4) and the polygon is concave and is pushed into the output array. If any triplet has a different sign then the total will be non-zero (modulo 4) and the polygon is convex.
```
f=(v)=>(r=[],k(...v),r)
```
The function `f` is used to initialise the output array and then call the above functions before returning the output.
**Tests**:
```
c=(v,w,x)=>(w[0]-v[0])*(w[1]-x[1])-(w[1]-v[1])*(w[0]-x[0])>0?1:0
i=(v,w,x,y)=>(c(v,w,x)+c(w,x,y)+c(x,y,v)+c(y,v,w))%4==0&&r.push([v,w,x,y])
j=(v,w,x,y)=>{i(v,w,x,y);i(v,w,y,x);i(v,x,w,y)}
k=(v,w,x,y,z)=>{j(v,w,x,y);j(v,w,x,z);j(v,w,y,z);j(v,x,y,z);j(w,x,y,z)}
f=(v)=>(r=[],k(...v),r)
tests = [
[[6,8],[1,10],[6,6],[5,9],[8,10]],
[[3,8],[7,5],[6,9],[7,8],[5,1]],
[[4,8],[1,9],[9,9],[10,2],[1,6]]
];
tests.forEach(
(test,i)=>{
console.log( "Test " + (i+1) );
f(test).forEach(
(x)=>console.log( " " + x.map((e)=>"("+e[0]+","+e[1]+")").join(','))
);
}
);
```
**Edit**:
Can also handle co-linear points using the original version and changing the first two lines to:
```
t=(a,b,c)=>Math.sign((b[0]-a[0])*(b[1]-c[1])-(b[1]-a[1])*(b[0]-c[0]))
p=(a,b,c,d)=>[t(a,b,c),t(b,c,d),t(c,d,a),t(d,a,b)].filter(x=>x).reduce((p,c,i,a)=>p&c==a[0],1)
q=(a,m,n,o)=>[a[0],a[m],a[n],a[o]]
f=(a)=>{r=[];for(i=0;i<5;i++){b=a.slice();b.splice(i,1);r.push(q(b,1,2,3));r.push(q(b,1,3,2));r.push(q(b,2,1,3))}return r.filter((a)=>p(...a))}
```
However, since that case is specifically excluded in the question then the extra characters aren't necessary.
[Answer]
# Mathematica ~~105~~ 96 bytes
`Select[#~Subsets~{4},f@#&]&` selects, from a list of (5) points, those subsets of 4 points that satisfy `f`.
`f` is satisfied when each point, of the 4 points in a set, lies on the `RegionBoundary` of the `ConvexHull` of the 4 points.
```
f@p_:=Apply[And,RegionBoundary@ConvexHullMesh@p~RegionMember~#&/@p];
Select[#~Subsets~{4},f@#&]&
```
---
## Test Cases
**1.** Let's look at at the 5 convex hulls of subsets (each of 4 points) of {{6, 8}, {1, 10}, {6, 6}, {5, 9}, {8, 10}}.
```
Select[#~Subsets~{4},f@#&[{{6, 8}, {1, 10}, {6, 6}, {5, 9}, {8, 10}}]
```
{{{6, 8}, {1, 10}, {6, 6}, {5, 9}}}
---
{{6, 8}, {1, 10}, {6, 6}, {5, 9}} is the only solution; each of the four points serves as a vertex of the convex hull (of the same 4 points).
[![solution](https://i.stack.imgur.com/nlOih.png)](https://i.stack.imgur.com/nlOih.png)
---
{{6, 8}, {1, 10}, {6, 6},{8, 10}} is not a solution; the convex hull has only 3 vertices. {6, 8} lies within the hull.
[![fail1](https://i.stack.imgur.com/wsTYZ.png)](https://i.stack.imgur.com/wsTYZ.png)
---
The remaining subsets also are not solutions:
[![fail2](https://i.stack.imgur.com/T4SMc.png)](https://i.stack.imgur.com/T4SMc.png)
[![fail3](https://i.stack.imgur.com/kUuY3.png)](https://i.stack.imgur.com/kUuY3.png)
[![fail4](https://i.stack.imgur.com/8ulVz.png)](https://i.stack.imgur.com/8ulVz.png)
---
**2.** {{4, 8}, {1, 9}, {9, 9}, {10, 2}, {1, 6}} has three solutions.
```
Select[#~Subsets~{4},f@#&[{{4, 8}, {1, 9}, {9, 9}, {10, 2}, {1, 6}}]
```
{
{{4, 8}, {1, 9}, {10, 2}, {1, 6}},
{{4, 8}, {9, 9}, {10, 2}, {1, 6}},
{{1, 9}, {9, 9}, {10, 2}, {1, 6}}
}
---
**3.** {{3, 8}, {7, 5}, {6, 9}, {7, 8}, {5, 1}} has 5 solutions.
```
Select[#~Subsets~{4},f@#&[{{3, 8}, {7, 5}, {6, 9}, {7, 8}, {5, 1}}]
```
{
{{3, 8}, {7, 5}, {6, 9}, {7, 8}},
{{3, 8}, {7, 5}, {6, 9}, {5, 1}},
{{3, 8}, {7, 5}, {7, 8}, {5, 1}},
{{3, 8}, {6, 9}, {7, 8}, {5, 1}},
{{7, 5}, {6, 9}, {7, 8}, {5, 1}}
}
Note that each of the five points lies on the boundary of the convex hull of all points.
If any one of the points is removed, the remaining 4 points will each be vertices of the reduced convex hull.
[![sol2](https://i.stack.imgur.com/pkMi5.png)](https://i.stack.imgur.com/pkMi5.png)
] |
[Question]
[
## Introduction
Similar to the Fibonacci Sequence, the [Padovan Sequence](https://en.wikipedia.org/wiki/Padovan_sequence) ([OEIS A000931](https://oeis.org/A000931)) is a sequence of numbers that is produced by adding previous terms in the sequence. The initial values are defined as:
```
P(0) = P(1) = P(2) = 1
```
The 0th, 1st, and 2nd terms are all 1. The recurrence relation is stated below:
```
P(n) = P(n - 2) + P(n - 3)
```
Thus, it yields the following sequence:
```
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, 351, ...
```
Using these numbers as side lengths of equilateral triangles yields a nice spiral when you place them all together, much like the Fibonacci Spiral:
[![enter image description here](https://i.stack.imgur.com/pSDh5.png)](https://i.stack.imgur.com/pSDh5.png)
Image courtesy of [Wikipedia](https://en.wikipedia.org/wiki/Padovan_sequence#/media/File:Padovan_triangles_(1).png)
---
## Task
Your task is to write a program that recreates this spiral by graphical output, with input corresponding to which term.
## Rules
* Your submission must be able to handle at least up to the 10th term (9)
* Your submission must be a full program or function that takes input and displays a graphical result (either outputs an image or graphs, etc)
* You must show proof of your graphical output in your submission
* Rotations of the output are allowed, in 60 degree multiples, with the same representation
* Going counter-clockwise is also allowed
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
You may assume that input will be >0 and that correct format of input will be given.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. Happy New Years everyone!
[Answer]
# Mathematica, ~~119~~ 108 bytes
*Thanks to Martin Ender for saving 11 bytes!*
```
±n_:=If[n<4,1,±(n-2)+±(n-3)];Graphics@Line@ReIm@Accumulate@Flatten@{0,z=I^(2/3),±# z^(#+{2,4,1})&~Array~#}&@
```
Unnamed function taking a positive integer argument (1-indexed) and returning graphics output. Example output for the input `16`:
[![enter image description here](https://i.stack.imgur.com/ZgnGy.png)](https://i.stack.imgur.com/ZgnGy.png)
Developed simulataneously with [flawr's Matlab answer](https://codegolf.stackexchange.com/a/105300/56178) but with many similarities in design—even including the definition `I^(2/3)` for the sixth root of unity! Easier-to-read version:
```
1 (±n_:=If[n<4,1,±(n-2)+±(n-3)];
2 Graphics@Line@ReIm@
3 Accumulate@Flatten@
4 {0,z=I^(2/3),±# z^(#+{2,4,1})&~Array~#}
5 ])&
```
Line 1 defines the Padovan sequence `±n = P(n)`. Line 4 creates a nested array of complex numbers, defining `z` along the way; the last part `±# z^(#+{2,4,1})&~Array~#` generates many triples, each of which corresponds to the vectors we need to draw to complete the corresponding triangle (the `±#` controls the length while the `z^(#+{2,4,1})` controls the directions). Line 3 gets rid of the list nesting and then calculates running totals of the complex numbers, to convert from vectors to pure coordinates; line 2 then converts complex numbers to ordered pairs of real numbers, and outputs the corresponding polygonal line.
[Answer]
# Matlab, ~~202~~ 190 bytes
```
N=input('');e=i^(2/3);f=1/e;s=[0,e,1,f,-e,e-2];l=[1,1,1,2];M=N+9;T=[l,2:M-3;2:M+1;3:M+2];for k=5:N;l(k)=l(k-2)+l(k-3);s(k+2)=s(k+1)+e*l(k);e=e*f;end;T=[T;T(1,:)];plot(s(T(:,1:N)));axis equal
```
Output for `N=19` (1-based indexing):
[![enter image description here](https://i.stack.imgur.com/nxT4f.png)](https://i.stack.imgur.com/nxT4f.png)
### Explanation
The rough idea is basically working with complex numbers. Then the edges of the triangles point always in the direction of a sixth root of unity.
```
N=input(''); % Fetch input
e=i^(2/3); % 6th root of unity
f=1/e; % "
s=[0,e,1,f,-e,e-2]; % "s" is a list of vertices in the order as the spiral is defined
l=[1,1,1,2]; % "l" is a list of edge-lengths of the triangles
for k=5:N; % if we need more values in "l"/"s" we calculate those
l(k)=l(k-2)+l(k-3);
s(k+2)=s(k+1)+e*l(k);
e=e*f;
end;
M=N+9;
T=[[1,1,1,2,2:M-3];2:M+1;3:M+2]'; % this matrix describes which vertices from s are needed for each triangle (the cannonical way how meshes of triangles are stored)
trimesh(T(1:N,:),real(s),imag(s)); % plotting the mesh, according to "T"
axis equal
```
[Answer]
# PHP + SVG , 738 Bytes
```
<?php
$a=[1,1,1];
for($i=0;$i<99;)$a[]=$a[$i]+$a[++$i];
$d=$e=$f=$g=$x=$y=0;
$c=[333,999];
$z="";
foreach($a as$k=>$v){
if($k==$_GET['n'])break;
$h=$v/2*sqrt(3);
if($k%6<1){$r=$x+$v/2;$s=$y+$h;$t=$r-$v;$u=$s;}
if($k%6==1){$r=$x-$v/2;$s=$y+$h;$t=$x-$v;$u=$y;}
if($k%6==2){$r=$x-$v;$s=$y;$t=$r+$v/2;$u=$y-$h;}
if($k%6==3){$r=$x-$v/2;$s=$y-$h;$t=$r+$v;$u=$s;}
if($k%6==4){$r=$x+$v/2;$s=$y-$h;$t=$r+$v/2;$u=$y;}
if($k%6>4){$r=$x+$v;$s=$y;$t=$r-$v/2;$u=$y+$h;}
$d=min([$d,$r,$t]);
$e=max([$e,$r,$t]);
$f=min([$f,$s,$u]);
$g=max([$g,$s,$u]);
$p="M$x,{$y}L$r,{$s}L$t,{$u}Z";
$z.="<path d=$p fill=#{$c[$k%2]} />";
$x=$r;
$y=$s;
}
?>
<svg viewBox=<?="$d,$f,".($e-$d).",".($g-$f)?> width=100% height=100%>
<?=$z?>
</svg>
```
## Output for 16
```
<svg viewBox=-53,-12.124355652982,75.5,42.435244785437 width=100% height=100%>
<path d=M0,0L0.5,0.86602540378444L-0.5,0.86602540378444Z fill=#333 /><path d=M0.5,0.86602540378444L0,1.7320508075689L-0.5,0.86602540378444Z fill=#999 /><path d=M0,1.7320508075689L-1,1.7320508075689L-0.5,0.86602540378444Z fill=#333 /><path d=M-1,1.7320508075689L-2,0L0,0Z fill=#999 /><path d=M-2,0L-1,-1.7320508075689L0,0Z fill=#333 /><path d=M-1,-1.7320508075689L2,-1.7320508075689L0.5,0.86602540378444Z fill=#999 /><path d=M2,-1.7320508075689L4,1.7320508075689L0,1.7320508075689Z fill=#333 /><path d=M4,1.7320508075689L1.5,6.0621778264911L-1,1.7320508075689Z fill=#999 /><path d=M1.5,6.0621778264911L-5.5,6.0621778264911L-2,-8.8817841970013E-16Z fill=#333 /><path d=M-5.5,6.0621778264911L-10,-1.7320508075689L-1,-1.7320508075689Z fill=#999 /><path d=M-10,-1.7320508075689L-4,-12.124355652982L2,-1.7320508075689Z fill=#333 /><path d=M-4,-12.124355652982L12,-12.124355652982L4,1.7320508075689Z fill=#999 /><path d=M12,-12.124355652982L22.5,6.0621778264911L1.5,6.0621778264911Z fill=#333 /><path d=M22.5,6.0621778264911L8.5,30.310889132455L-5.5,6.0621778264911Z fill=#999 /><path d=M8.5,30.310889132455L-28.5,30.310889132455L-10,-1.7320508075689Z fill=#333 /><path d=M-28.5,30.310889132455L-53,-12.124355652982L-4,-12.124355652982Z fill=#999 /></svg>
```
[Answer]
# Python 3, 280, 262 bytes
18 bytes saved thanks to ovs
Golfed:
```
import turtle
P=lambda n:n<4or P(n-3)+P(n-2)
N=int(input())
M=9
t=turtle.Turtle()
Q=range
R=t.right
L=t.left
F=t.forward
S=[P(x)*M for x in Q(N,0,-1)]
A=S[0]
F(A)
R(120)
F(A)
R(120)
F(A)
L(120)
i=1
while i<N:
A=S[i]
for j in Q(3):F(A);L(120)
F(A)
L(60)
i+=1
```
Same thing with some comments:
```
import turtle
# P(n) returns nth term in the sequence
P=lambda n:n<4or P(n-3)+P(n-2)
# M: scales the triangle side-length
M=9
# N: show triangles from 1 to (and including) N from sequence
N=int(input())
t=turtle.Turtle()
Q=range
R=t.right # R(a) -> turn right "a" degrees
L=t.left # L(a) -> turn left "a" degrees
F=t.forward # F(l) -> move forward "l" units
# S: M*P(N),M*P(N-1), ... M*P(1)
S=[P(x)*M for x in Q(N,0,-1)]
# draw the largest triangle
A=S[0]
F(A)
R(120)
F(A)
R(120)
F(A)
L(120)
i=1
# draw the next N-1 smaller triangles
while i<N:
A=S[i]
for j in Q(3):F(A);L(120)
F(A)
L(60)
i+=1
```
Screenshot for `N=9`:
[![N=9](https://i.stack.imgur.com/aOXfh.png)](https://i.stack.imgur.com/aOXfh.png)
[Answer]
# dwitter 151
```
s=(n)=>{P=(N)=>N<3||P(N-3)+P(N-2)
for(a=i=0,X=Y=500,x.moveTo(X,Y);i<n*4;i++)k=9*P(i/4),x.lineTo(X+=C(a)
*k,Y+=S(a)*k),x.stroke(),a+=i%4>2?1.047:2.094}
```
can be tested on <http://dwitter.net> (use fullscreen)
[![enter image description here](https://i.stack.imgur.com/S8H2v.png)](https://i.stack.imgur.com/S8H2v.png)
basic idea is logo turtle, golfed. stole the P() func from above!
i imagine more could be golfed by recursion but this is not bad.
[Answer]
## LOGO, 119 bytes
```
to s:n
make"x 10
make"y:x
make"z:y
bk:z
repeat:n[lt 60
fw:z
rt 120
fw:z
bk:z
make"w:y+:z
make"z:y
make"y:x
make"x:w]end
```
To use, do something like [this](http://logo.twentygototen.org/S71TN02g):
```
reset
lt 150
s 12
```
[Sample output](http://logo.twentygototen.org/S71TN02g.png) (can't embed because it's not HTTPS and it failed to upload to imgur)
] |
[Question]
[
Your task is to write a [program or a function](https://codegolf.meta.stackexchange.com/a/2422/60340) that [outputs](https://codegolf.meta.stackexchange.com/q/2447/60340) `n` random numbers from interval [0,1] with fixed sum `s`.
# Input
`n, n≥1`, number of random numbers to generate
`s, s>=0, s<=n`, sum of numbers to be generated
# Output
A random `n`-tuple of floating point numbers with all elements **from the interval [0,1]** and sum of all elements equal to `s`, output in any convenient unambiguous way. All valid `n`-tuples have to be equally likely within the limitations of floating point numbers.
This is equal to uniformly sampling from the intersection of the points inside the `n`-dimensional unit cube and the `n-1`-dimensional hyperplane that goes through `(s/n, s/n, …, s/n)` and is perpendicular to the vector `(1, 1, …, 1)` (see red area in Figure 1 for three examples).
[![Examples with n=3 and sums 0.75, 1.75 and 2.75](https://i.stack.imgur.com/N6b7k.png)](https://i.stack.imgur.com/N6b7k.png)
Figure 1: The plane of valid outputs with n=3 and sums 0.75, 1.75 and 2.75
# Examples
```
n=1, s=0.8 → [0.8]
n=3, s=3.0 → [1.0, 1.0, 1.0]
n=2, s=0.0 → [0.0, 0.0]
n=4, s=2.0 → [0.2509075946818119, 0.14887693388076845, 0.9449661625992032, 0.6552493088382167]
n=10, s=9.999999999999 → [0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999]
```
# Rules
* Your program should finish under a second on your machine at least with `n≤10` and any valid s.
* If you so wish, your program can be exclusive on the upper end, i.e. `s<n` and the output numbers from the half-open interval [0,1) (breaking the second example)
* If your language doesn't support floating point numbers, you can fake the output with at least ten decimal digits after the decimal point.
* Standard loopholes are disallowed and standard input/output methods are allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest entry, measured in bytes, wins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~122~~ 115 bytes
```
N=>W=S=>2*S>N?W(N-S).map(t=>1-t):(t=(Q=s=>n?[r=s-s*Math.random()**(1/--n),...r>1?[++Q]:Q(s-r)]:[])(S,n=N),Q?t:W(S))
```
[Try it online!](https://tio.run/##fY3BbsIwEETv@ZLdJN7aIA5JWefGrZEiH3KIImEFKEFgI9vq76ccqVQ4zZPmaeZif2ycwnxPwvnDcdnx0rLu2bBe5Ua3TQ@tMEg3e4fEWomE9QOg48jaNUPgKGL@ZdOZgnUHfwPMc1AfQjgsiSho1QxF0Y11B1EEHOthRDCl4xbLrkl1DwZxySbvor8e6eq/YQdKImyQLn52@3KP/7SSpFRvjYqqqnphYJadfICZ5ee8VVI@oijw78Ya4elg@QU "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~144~~ ~~128~~ 119 bytes
```
from random import*
def f(n,s):
r=min(s,1);x=uniform(max(0,r-(r-s/n)*2),r);return n<2and[s]or sample([x]+f(n-1,s-x),n)
```
[Try it online!](https://tio.run/##RY3BDoIwEETv/Yo9dnVBqJqIypcYDySAktgt2UJSvx6riO5lXmayM/1zuDs209SKsyAV11E62zsZVqpuWmg1k8ejAiltx9pTjqdQjty1Tqy2VdAZSaIl8RvGlUESPEkzjMLAZxP7Lv7qBHxl@0ejL@G6jo1JTj4JSIzTe@O2bIRynlPQS8cDBPKj1QGVuuktQZ5mGCknyNLDm8yPYrqd04/3oR2B@X5kBEVa/G8x9zGfXg "Python 2 – Try It Online")
---
* -20 bytes, thanks to Kevin Cruijssen
[Answer]
# Java 8, ~~194~~ ~~188~~ ~~196~~ ~~237~~ 236 bytes
```
n->s->{double r[]=new double[n+1],d[]=new double[n],t;int f=0,i=n,x=2*s>n?1:0;for(r[n]=s=x>0?n-s:s;f<1;){for(f=1;i-->1;)r[i]=Math.random()*s;for(java.util.Arrays.sort(r);i<n;d[i++]=x>0?1-t:t)f=(t=Math.abs(r[i]-r[i+1]))>1?0:f;}return d;}
```
+49 bytes (188 → 196 and 196 → 237) to fix the speed of test cases nearing 1, as well as fix the algorithm in general.
[Try it online](https://tio.run/##lZRNb6MwEIbv/RUWJ2jAQCjqAoWo0mqlPexlu7eIgxtM6y4xkW3aRlV@e3YwJORb2VEExn7nYTwx7xt5J85b8Xc9q4iU6Bdh/OsGIamIYjP0Bqu4UazCZcNnitUc/@gHDz@5oi9U2BdF3@vmuaI2KvR9mmcZKlGK1tzJpJN9ddNITPOU04@Nio/83C4O5nJbJYwrVKaezVJuf6bjW5nxiR97SVkLU4Akleln5k24I2OZlA9@Yn21S2XqJ8xxMngWU5anv4h6xYLwop6b1q3U6cMmHoUgS4llLZQprIQ98KSYstEo12zfUbGyytRUHYY8S7OFOnCBsi0r8ydeXCYrQVUjOCqS1TqBhsJvARuBnvatfa9ZgebQbvNJCcZfpjkiVtt6hBSVyvRthDz8zUrQXrgu@vNKkYQMaBxTdI6YRKT6gJpbvetDe@E@gMYa5J0APVaVJkC@oAPDc8ea4e0U49n/y/C9M5Au/C2rhbxTQV4oqsuexWS8I92yNhOHmwtPFXaaGfabG4cDJACIf3p3pyAgdQOABDgIAozxALoD0Ph6EEjdO11NuN@l8HpGOLR6BxJCIXfXtwWkbqgZ0X4hEb4/hJxjtNJNJdF9eMiJoqs5UbTlRNExZwhNvMQZYoc4xP4JCK4/30F/AvzD4@0ffyTnGP72I@koq84kdt1BY1vP4xsDRbK3iI2fIkFlUymglJgsFtXS5FY/kFaipU9LCe/GdaPwAoxGVdw0eGqM@MhIkITBBeGRK6q6cyuze6/Vp258XE8@NXOo59hQlaBkvknEsgHzPV9hC4H/k7S5MTJGW/SFnN9a4wAZzWoh6ExNINPcpqapnBhLKo3Y4LVhnSfpldXNav0P)
**Explanation:**
Uses the approach in [this StackoverFlow answer](https://stackoverflow.com/a/8064754/1682559), inside a loop as long as one of the items is still larger than 1.
Also, if `2*s>n`, `s` will be changed into `n-s`, and a flag is set to indicate we should use `1-diff` instead of `diff` in the result-array (thanks for the tip *@soktinpk* and *@l4m2*).
```
n->s->{ // Method with integer & double parameters and Object return-type
double r[]=new double[n+1]
// Double-array of random values of size `n+1`
d[]=new double[n],
// Resulting double-array of size `n`
t; // Temp double
int f=0, // Integer-flag (every item below 1), starting at 0
i=n, // Index-integer, starting at `n`
x= // Integer-flag (average below 0.5), starting at:
2*s>n? // If two times `s` is larger than `n`:
1 // Set this flag to 1
: // Else:
0; // Set this flag to 0
for(r[n]=s= // Set both the last item of `r` and `s` to:
x>0? // If the flag `x` is 1:
n-s // Set both to `n-s`
: // Else:
s; // Set both to `s`
f<1;){ // Loop as long as flag `f` is still 0
for(f=1; // Reset the flag `f` to 1
i-->1;) // Inner loop `i` in range (n,1] (skipping the first item)
r[i]=Math.random()*s;
// Set the i'th item in `r` to a random value in the range [0,s)
for(java.util.Arrays.sort(r);
// Sort the array `r` from lowest to highest
i<n; // Inner loop `i` in the range [1,n)
;d[i++]= // After every iteration: Set the i'th item in `d` to:
x>0? // If the flag `x` is 1:
1-t // Set it to `1-t`
: // Else:
t) // Set it to `t`
f=(t=Math.abs( // Set `t` to the absolute difference of:
r[i]-r[i+1]))
// The i'th & (i+1)'th items in `r`
>1? // And if `t` is larger than 1 (out of the [0,1] boundary)
0 // Set the flag `f` to 0
: // Else:
f;} // Leave the flag `f` unchanged
return d;} // Return the array `d` as result
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 153 bytes
```
(n,s)=>s+s>n?g(n,n-s).map(r=>1-r):g(n,s)
g=(n,s)=>{do(a=[...Array(n-1)].map(_=>Math.random()*(s<1?s:1))).map(r=>t-=r,t=s);while(t<0|t>=1);return[...a,t]}
```
[Try it online!](https://tio.run/##bYxBbsIwEEX3nCLLGWqPYuiiEMaIA3CCClUWCYEq2GjGBVWlZ08BVVWr8nf/6f3/Go5B17I7ZBtT3fQb7iEaRfb6oD7O20uLVpH24QDC3lnBaXtTBi1/qx91gsDPRLQQCe8QrcPVbfHCfhnyliTEOu0Bh6AzN9epQ/y5zJbFZFasTttd10Celefs2WElTX6TeP0NJq8@@3WKmrqGutTCBpwpSnpCrAZ/@dgUYyr/89HVv8MfTTG6x11piglNfuXi9F8 "JavaScript (Node.js) – Try It Online")
[Answer]
## C++11, ~~284~~ 267 bytes
-17 bytes thanks to Zacharý
Uses C++ random library, output on the standard output
```
#include<iostream>
#include<random>
typedef float z;template<int N>void g(z s){z a[N],d=s/N;int i=N;for(;i;)a[--i]=d;std::uniform_real_distribution<z>u(.0,d<.5?d:1-d);std::default_random_engine e;for(;i<N;){z c=u(e);a[i]+=c;a[++i]-=c;}for(;i;)std::cout<<a[--i]<<' ';}
```
To call, you just need to do that :
```
g<2>(0.0);
```
Where the template parameter ( here, 2 ) is N, and the actual parameter ( here, 0.0 ) is S
[Answer]
# C, ~~132~~ ~~127~~ ~~125~~ ~~118~~ ~~110~~ 107 bytes
*-2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
i;f(s,n,o,d)float*o,s,d;{for(i=n;i;o[--i]=d=s/n);for(;i<n;o[++i%n]-=s)o[i]+=s=(d<.5?d:1-d)*rand()/(1<<31);}
```
[Try it online!](https://tio.run/##XZJPb9QwEMXPyacYFVVyduMNy78DTkAIATdAcOBQrdA0dlKriSeyHcS26lcnjLMLSJzijH8z815eWtkO6PplsaoToXQllbroBsK4oTKUWt135IVtnLKKrqS0h0Y3oXKFSnVla8fl7dZeuoNsQkFX9rBtQiN0vXv@Wr/cS11sPDotikrs6/rpvlAPS1W9@4njNBiYPPUeR4gE0YQI8cZAN7s2WnIlaDIBHEVoaXYRMMCEPgJ1Kxfm69GGwOQuzx9Z1w6zNlCHqC3tbl7lueWeEa0TRX6fZ1X1xvfzaFwMebY6hAANPNm9UHkW7J35HsFx4ZnKE/zVGA1fPn4A8WlKanAoGFuttAO1t6IoTuBbbzAaQAfoPR6TlRDJm1WjxojnbRtAnt7iwN2CzaWV1In17u8sGqc5plbr@iSTIwFmke@zBHz2yRTNpy@1LmSKkzgbsLziseJHDU4B58Kisyk1deLisoMLnsURnde998b8G5SU4w@yGkYzkj/CYPA2iWBKJAUPy6@2G7APi/zmSHoTZ@9kPE7mVDDjFI/ymvTx9G45YtvaKP8kKrXhv81jOv@HsMLf)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~221~~ 201 bytes
*Clean, code-golf, or random numbers. Pick two.*
```
import StdEnv,Math.Random,System._Unsafe,System.Time
g l n s#k=toReal n
|s/k>0.5=[s/k-e\\e<-g l n(k-s)]
#r=take n l
#r=[e*s/sum r\\e<-r]
|all((>)1.0)r=r=g(tl l)n s
```
#
```
g(genRandReal(toInt(accUnsafe time)))
```
[Try it online!](https://tio.run/##PY8xT8MwEIX3/ApLWWzUpOnAhjvBUAkk1MDUVuhwLiGKfUb2BalSfzvBaUS3@07vvbtnLAJNzjejReGgp6l33z6wqLl5op/VC/BXuQdqvFvV58joyo93itDiP771DrNOWEEi5oNmv0dIkF3iethW5b0@pKHA4xEfiqtMDkVUpywPmmHAZLPzfMC7uI6jE@GqDKfsAtZKuVWbslJBB91JtsKqdGaqGQJnuUCLDomj0GJTJabRfWJIVJUztiMZ7j2lRSc7pLnH/J1kvyOWYMxSRXDqoJTKtLxZbtFLppp@TWuhi1Oxe54ezwSuNwu8WuDWB/cH "Clean – Try It Online")
Partial function literal `:: (Int Real -> [Real])`. Will only produce new results once per second.
Accurate up to at least 10 decimal places.
[Answer]
# [R](https://www.r-project.org/), 99 bytes (with `gtools` package)
```
f=function(n,s){if(s>n/2)return(1-f(n,n-s))
while(any(T>=1)){T=gtools::rdirichlet(1,rep(1,n))*s}
T}
```
[Try it online!](https://tio.run/##TYpNCoMwEIX3niLLmRKt0VKqEE/hBYomOiCjJJFSxLOncde3eB/vx8Votd15CLQysPR4kAXf8b1CZ8LuGFRu08C5R8w@My0G3vyFvtMK8ej1FNZ18W3rRnI0zIsJoKQzW3JGvPkz689oUxJl8cLMQi1FfbFKzcWHFBVmmyMOkH6lFE3R/AmlGGmi4LV6YvwB "R – Try It Online")
We wish to sample uniformly from the set \$\tilde{\mathcal A}=\{w\_1,\ldots,w\_n: \forall i, 0<w\_i<1; \sum w\_i=s\}\$. I'll divide all the \$w\_i\$ by \$s\$ and instead sample from \$\mathcal A=\{w\_1,\ldots,w\_n: \forall i, 0<w\_i<\frac1s; \sum w\_i=1\}\$.
If \$s=1\$, this is easy: it corresponds to sampling from the \$Dirichlet(1, 1, \ldots, 1)\$ [distribution](https://en.wikipedia.org/wiki/Dirichlet_distribution) (which is the uniform over the simplex). For the general case \$s\neq 1\$, we use rejection sampling: sample from the Dirichlet distribution until all entries are \$<1/s\$, then multiply by \$s\$.
The trick to mirror when \$s>n/2\$ (which I think [l4m2 was the first](https://codegolf.stackexchange.com/a/165050/86301) to figure out) is essential. Before I saw that, the number of iterations in the rejection sampler exploded for the last test case, so I spent a *lot* of time trying to sample efficiently from well-chosen truncated Beta distributions, but it is not necessary in the end.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~92~~ 90 bytes
```
If[2#2>#,1-#0[#,#-#2],While[Max[v=Differences@Sort@Join[{0,#2},RandomReal[#2,#-1]]]>1];v]&
```
[Try it online!](https://tio.run/##VcuxCsIwFIXh3acoXHC6lSR1sEhLBxcFQeLgcLlDqCkNtCnUUATxXXwWXyw6tmf7Dvy9Ca3tTXC1iTop4rEhBaoElCkIAoQUFOOtdZ2ls3nSVBxc09jR@to@quswhuo0OE8vgaDeqI2/D722piNQ/1gycyl5P/E6XkbnQ1J9P5okis2OV7Mnw2xhhWLhLaqFpcB8k8/G8Qc "Wolfram Language (Mathematica) – Try It Online")
Un-golfed code:
```
R[n_, s_] := Module[{v},
If[s <= n/2, (* rejection sampling for s <= n/2: *)
While[
v = Differences[Sort[
Join[{0},RandomReal[s,n-1],{s}]]]; (* trial randoms that sum to s *)
Max[v] > 1 (* loop until good solution found *)
];
v, (* return the good solution *)
1 - R[n, n - s]]] (* for s > n/2, invert the cube and rejection-sample *)
```
---
Here is a solution that works in **55 bytes** but for now (Mathematica version 12) is restricted to `n=1,2,3` because `RandomPoint` refuses to draw points from higher-dimensional hyperplanes (in TIO's version 11.3 it also fails for `n=1`). It may work for higher `n` in the future though:
```
RandomPoint[1&~Array~#~Hyperplane~#2,1,{0,1}&~Array~#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H6Rg@z8oMS8lPzcgPzOvJNpQrc6xqCixsk65zqOyILWoICcxL7VO2UjHUKfaQMewFi4dq/Y/oAioQ8Hh0IKgaCMdAz2LWC4kEWMdYxQ@UAWavBE6X88SCcT@BwA "Wolfram Language (Mathematica) – Try It Online")
Un-golfed code:
```
R[n_, s_] :=
RandomPoint[ (* draw a random point from *)
Hyperplane[ConstantArray[1, n], s], (* the hyperplane where the sum of coordinates is s *)
1, (* draw only one point *)
ConstantArray[{0, 1}, n]] (* restrict each coordinate to [0,1] *)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~122~~ ~~217~~ 208 bytes
```
import System.Random
r p=randomR p
(n#s)g|n<1=[]|(x,q)<-r(max 0$s-n+1,min 1 s)g=x:((n-1)#(s-x)$q)
g![]=[]
g!a|(i,q)<-r(0,length a-1)g=a!!i:q![x|(j,x)<-zip[0..]a,i/=j]
n%s=uncurry(!).(n#s<$>).split<$>newStdGen
```
[Try it online!](https://tio.run/##TY5Ba4QwEIXv/oqRdSGhmuqhlIrpqVB6KuwexUO2BjdbM8Yk0mzxv9t06aFzeW/mfQ/mLNynHMdtU9pM1sPx6rzU7CCwn3RiwXB7swcwCcGdo8OKTcXbbiUhn2lTWKJFgDJzBd5VuVYIFUSKh5oQLCq6I64INJtpMqRtF4tRxUrUX7nMR4mDP4OI7MBFmqp6TtuwkkseIvGtTFsy1olc3fNLl@De8QU/FmuvJKXs96Ume6bMmVH56FB@HX3/KnHTQiHvpwTi9K4pqnL/xB4foK7h7b19mZbTKLtbaqxCH5l/SwZu0fG0/QA "Haskell – Try It Online")
Sometimes the answers are slightly off due, I assume, to floating point error. If it's an issue I can fix it at a cost of 1 byte. I'm also not sure how uniform this is (pretty sure it's fine but I'm not all that good at this kind of thing), so I'll describe my algorithm.
Basic idea is to generate a number `x` then subtract it from `s` and recur until we have `n` elements then shuffle them. I generate `x` with an upper bound of either 1 or `s` (whichever is smaller) and a lower bound of `s-n+1` or 0 (whichever is greater). That lower bound is there so that on the next iteration `s` will still be less than or equal to `n` (derivation: `s-x<=n-1` -> `s<=n-1+x` -> `s-(n-1)<=x` -> `s-n+1<=x`).
EDIT: Thanks to @michi7x7 for pointing out a flaw in my uniformity. I think I've fixed it with shuffling but let me know if there's another problem
EDIT2: Improved byte count plus fixed type restriction
[Answer]
# [Haskell](https://www.haskell.org/), 188 bytes
```
import System.Random
import Data.List
n!s|s>n/2=map(1-)<$>n!(n-s)|1>0=(zipWith(-)=<<tail).sort.map(*s).(++[0,1::Double])<$>mapM(\a->randomIO)[2..n]>>= \a->if all(<=1)a then pure a else n!s
```
Ungolfed:
```
n!s
|s>n/2 = map (1-) <$> n!(n-s) --If total more than half the # of numbers, mirror calculation
|otherwise = (zipWith(-)=<<tail) --Calculate interval lengths between consecutive numbers
. sort --Sort
. map(*s) --Scale
. (++[0,1::Double]) --Add endpoints
<$> mapM(\a->randomIO)[2..n] --Calculate n-1 random numbers
>>= \a->if all(<=1)a then pure a else n!s --Retry if a number was too large
```
[Try it online!](https://tio.run/##PY9BT4QwEIXv/RXDRpPWlQoYDxDa015MNBp3Ew/LxozZEhpLIbQkYPa/I6y6t3nvTb55U6H7UsZMum6bzsNODZ6/dtr68t/ajs6rmr@hPTY1@TM36JE/aeeJDdzJSXuXiBpbGocsv5I2oDZ07BTLSNBv3b5rX9GQiTz3qA3jbkbwZf3GMU7X6310G2fZpuk/jTosgDl7pgWGsjtffXxh@4Rze5BSwGLrEtAYmouYIfhKWWj7TgGCMk7BXGnyynkYYAQBx4bMSR7CEIwEFvQHtMuLgOR3KGG1azyaDK7LwhZ2BdT1NSAjNWo7I860OIIHkPIioou4h4SnaTr9AA "Haskell – Try It Online")
] |
[Question]
[
The Enigma machine is a fairly complex cipher machine used by the Germans and others to encrypt their messages. It is your job to implement this machine\*.
# Step 1, Rotation
Our enigma machine has 3 slots for rotors, and 5 available rotors for each of these slots. Each rotor has 26 different possible positions (from `A` to `Z`). Each rotor has a predefined *notch position*:
```
Rotor Notch
------------
1 Q
2 E
3 V
4 J
5 Z
```
On keypress the following steps occur:
1. The rotor in Slot 1 rotates
2. If the rotor in Slot 1 moves past its notch, then it rotates the rotor in Slot 2.
3. If the rotor in Slot 2 is in its notch (but didn't just move there), both rotor 2 and 3 rotate once.
*If we are using rotors 1,3,5 and they are in positions `P,U,H` then the sequence of positions is: `P,U,H` > `Q,U,H` > `R,V,H` > `S,W,I`*
# Step 2, Substitution
Each of the rotors performs a simple character substitution. The following is a chart of each of the rotors in the `A` position:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
--------------------------
1 EKMFLGDQVZNTOWYHXUSPAIBRCJ
2 AJDKSIRUXBLHWTMCQGZNPYFVOE
3 BDFHJLCPRTXVZNYEIWGAKMUSQO
4 ESOVPZJAYQUIRHXLNFTGKDCMWB
5 VZBRGITYUPSDNHLXAWMJQOFECK
R YRUHQSLDPXNGOKMIEBFZCWVJAT
```
*Rotor 1 in position T is `PAIBRCJEKMFLGDQVZNTOWYHXUS`, which would substitute the letter `C` for `I`.*
After the three rotors perform their substitution, the *reflector* is hit (listed as `R` above). It performs its own substitution, and then reflects the signal back through the rotors. The rotors then perform a reverse substitution in reverse order.
*Reverse substitution means that instead of Rotor 1 substituting `A` with `E`, it substitutes `E` with `A`*
*Slots are filled with rotors 1,2,3 all in position `A`. The letter `Q` follows the path `Q>X>V>M` through the rotors. `M` reflects to `O`, which then follows the reverse path of `O>Z>S>S`. Therefore, `A` is substituted with `S`.*
# Input/Output
You are passed:
1. A list of 3 rotors (as integers)
2. A list of 3 starting rotor positions (as letters)
3. A string that needs to be encrypted.
You can assume that your input will be well formed, and all characters will be uppercase letters, no spaces.
You must return the encrypted string.
You can optionally accept the rotors, notches, and reflectors as input. For those that don't can take off 95 bytes from their score, as `95 = ceil(log2(26 letters ^(26*6 rotors +5 notches))/8 bytes)`
# Test cases
```
Rotor Position Input Output
4,1,5 H,P,G AAAAAAAAA PXSHJMMHR
1,2,3 A,A,A PROGRAMMINGPUZZLES RTFKHDOCCDAHRJJDFC
1,2,3 A,A,A RTFKHDOVZSXTRMVPFC PROGRAMRXGVGUVFCES
2,5,3 U,L,I GIBDZNJLGXZ UNCRAUPSCTK
```
My implementation can be found on [Github](https://gist.github.com/nathanmerrill/12c8ce109cd40e673db0). I've tested it, but I may have bugs in my implementation (which would mean that my test cases are likely wrong).
\*I've tried to make this as [accurate as possible](https://en.wikipedia.org/wiki/Enigma_rotor_details), but due to the variations between machines, I may have some details wrong. However, your task is to implement what I've described, even if I'm inaccurate. I'm not including the plugboard for simplicity
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~42~~ ~~38~~ 37 bytes
```
="⁵Ḣ€Ṗ1;ṙ@"µɼ⁶ṭØAiịɗƒµ®Ṛi@ịØAɗƒ
ḷ⁹©Ç€
```
[Try it online!](https://tio.run/##FY/NSsNQEIX3fYoQuxGKYKULETGN/W@sv601uBJctHbhQhAFIRE00FZBBbXipo0uBBWKjb03iZsbKsS3mPsi18lmYM43czinud9qnQixKHPTATLg5@9A72cXgPYUmTmhz81voB/BY7oBXid8@L1lDvsE@tRQcEc5kmJAxtyk7C2w8F8g4MZzboab3jFQG0ib2UfgXQG5CIdI2GsaaB9IF7wR3h5w068W5hEEN@GQ/UyB2/7rgEsZjQjQAaLyqXoYDAMLPRCDew3kC4gdufWbqdA/ixy90d4us1Wgl9zoSZO7JQkDTkvYBduNow5xBHHMyF5igSUlJ4YiRDKRSswJOV9UM3qlpOXruizkrF7DubNRLaxvapm1eiW/Wl4pZtWcvrxdK6W3EFa1ovwP "Jelly – Try It Online")
[Verify](https://tio.run/##NY/NSsNQEIX3fYoQuxGKULELETGJ2sbWv1brT3EluGjtwoUgCkIiaKGtggpqxU0bXQgqBBt7bxI391IhvsXcF7lOFs5iYM43c5hT26vXj6WcVoXtAemJszegd@kpoB1NZV4UCvsL6Dt/0KsQtKL7nxvmsQ@gj1UNZ5RjKQFkIGzKXnkD7yUCYT1lx4QdHAF1gDSZcwjBJZDzyEXCXnSgXSBtCPq4uy/ssGxOIuDXkcu@R8Bv/rbAp4zGBGgPUeHEOOAub6AHYvCvgHwCcWK3bi0ThaexY9Df3WGOAfRCWB1leDuj4IOjCmbBdIM4QxJBEn9kzwneUMaHliblRCqdykhV/y9VqvliBft2qWwW1xbnVreWcyuFpYV5I1uZ3dzI6@sIzVJO/QM) [each](https://tio.run/##FY9PSwJRFMX3fophchNIoNEiIppn6Wj@GzWthlZBC81FiyAKgpmgBK2ggspoo1OLoAJJ8z3HNm8wmL7FfV/kdWdz4Z7fvYdz6nuNxrGUy6qwh0B74uwd2H10CVhHU/nQnwj7G9iH90hq4Lb9h99bPuSfwJ5qGu4oB1II6EjYjL95TfyXCIT1nJwTtnsEzAHa4s4huFdAz/0@Ev5KgHWBXoI7wNt9YU8qqUUE3o3f5z8zMG79tWHMOAsIsB6izEn8wOt7TfRADONroF9AncCtW1/wJ6eBozvY3eFOHNiFsDrK9G5FwYCzCnbBdqOgQxhBGDPyl5DXVGJTS5MyGolF5qVqlAp6ieRy6bxuVEwzmyirUi0mqji3S5VUsZxdM7byeiGTSyfiSXN1s7pONhASQtR/) [test](https://tio.run/##FY9PSwJRFMX3fophchNIoNEiInL8M1mTqeM4mbQKWmguWgRREDhBCVpBBZXRRqcWQQWSk@/N2OYNBtO3uO@LvO5sLtzzu/dwTmOv2TwWYlnmlgNkwM/egd7Hl4D2kjJzggm3voF@@I9KHbxu8PB7yxz2CfSpnsQd5VCKABlzi7I3v43/AgFvPatz3PKOgNpAOsw@BO8KyHkwRMJeFaB9IJfgjfB2n1uTSm4RgX8TDNnPDLidvy64lNGQAB0g0k5SB/7Qb6MHYnCvgXwBsUO3fmMhmJyGjt5od4fZKaAXvNWTpncrEgaclbALthuHHaIIopiRvUT8tpSYtpJCxGOJ2LyQdUPVcpmCWStXDT1vFtW0LORS1sS5rVdypfJGpljdXC1o@bVsSq2lt8x1xUCoKIr8Dw) [case](https://tio.run/##FY/NSsNQEIX3fYoQuxGKYKULETGN/W@sv601uBJctHbhQhAFIRE00FZBBbXipo0uBBWKjb03iZsbKsS3mPsi18lmYM43czinud9qnQixKHPTATLg5@9A72cXgPYUmTmhz81voB/BY7oBXid8@L1lDvsE@tRQcEc5kmJAxtyk7C2w8F8g4MZzboab3jFQG0ib2UfgXQG5CIdI2GsaaB9IF7wR3h5w068W5hEEN@GQ/UyB2/7rgEsZjQjQAaLyqXoYDAMLPRCDew3kC4gdufWbqdA/ixy90d4us1Wgl9zoSZO7JQkDTkvYBduNow5xBHHMyF5igSUlJ4YiRDKRSswJOV9UM3qlpOXruizkrF7DubNRLaxvapm1eiW/Wl4pZtWcvrxdK6W3EFa1ovwP)
This is *extremely* liberal with the input format. It takes input in the following way:
* The three rotors (the strings, not the numbers) as the first command line argument, each rotated so that the starting points are the first characters
* The message as the second command line argument
* The 3 specific notches as the third command line argument
* The reflector as the fourth command line argument
In the above TIO link, the Footer converts a triple of numbers (the rotors) into the rotor strings, then rotates them to the correct order, so that you don't have to do it yourself.
However, for [45 bytes](https://tio.run/##HY5fS8JQGMbv/RTjdGtBhUFE5JY6p6b902wEQdCF5kUXQRQELihBLaigsrpIVxdBBSMXO24RnFWwvsV7vsjpXZfP83v48VQ3a7U9IaYJN/rg9PjhM9DL0SmgnThhduBxwwb64l/LFXBbwdXPObPZK9CbShwz1mEVwTVhT9x4L6xPxNgD0Nvg3m@gS@CI1@9SI9xwd4Ga4DSZuQPuCThHgYWEPcpAu@C0we3jdosbXjE9icA/Cyz2MQSD5m8LBpTRkADtIcruK9u@5TfQgRgGp@C8gWOGtm41FngHodHtb6wxUwF6zOsd6ftiRsKzkf9TErOl4a9PoWpKQs9ncmpZF2PRWHRckKReIoKsLhbTC0u5xHw5rxayc1pSSemzK6WMvIywmNPIHw) we can have a program which takes input in the following way:
* The message, on STDIN
* The three rotors (as the strings) as the first command line argument
* The 3 specific notches as the second command line argument
* The reflector as the third command line argument
* The three starting points for the rotors as the fourth command line argument
Again, the Footer converts the rotors from integers to the corresponding strings.
Finally, if we want to go all the way and just accept 3 inputs (the rotors, as integers, the starting positions and the message (thus have -95 to our score)), we get a [score of 44](https://tio.run/##PU9NS8NAEL37M@K1CCoRRMQmqLW1KB4qEoSK4KG1Bw9CURASQQuNClqwVi21jR4EFUJT2U3iZZcW1n8x@0fWiYKnYea9eR/lvUrlSKl5jfUhcqX9uLG0mbOk3WbPQHry9A3o7eQc0FZaYwMRI4F1R20g7rAB9B5oE8hnVTrE4J0dabeGjQV@Z@AvfcdZQknRHN2wAftAdimNO56T09if2/KEdKIqUA9InXmHEF0CORN@YvNiAO0CuYAoQO6@dOLCyiwC/Fr47Gscwvq3CyFlNEGA9hBaPTYPuM9rqIEwhFdA@kC839BlXcQniWIU7G4zzwR6/p8X62nsVTrBenFGT8I/iCdew/JKZbLmorWWy2e2LDWV0lPTSivks9oP)
---
## How it works
As they all use the same underlying algorithm, I'll just explain the 38 byte version in full, and I'll cover how the other two versions adapt the inputs to match the shortest version. For this explanation: `M` is the message, `R` are the three rotor strings, `N` are the notches, `F` is the reflector and `C` is the value in the register (initially 0).
```
ḷ⁹©Ç€ - Main link. Takes M on the left and R on the right
⁹ - Yield R
© - And copy it into the register. C = R
ḷ - Discard R and yield M
€ - Over each character in M:
Ç - Call the helper link
Implicitly output the final result
="⁵Ḣ€Ṗ1;ṙ@"µɼ⁶ṭØAiịɗƒµ®Ṛi@ịØAɗƒ - Helper link. Takes a character X on the left
="⁵Ḣ€Ṗ1;ṙ@"µɼ - Rotate the rotors
ɼ - Yield C, run the following on it, save the result to C:
µ - Initially, C = R, the list of rotors
⁵ - Yield the notches, N
" - Pair each notch with each rotor, then:
= - Vectorised equality
Ḣ€ - Take the head of each
This yields a triple of bits [a, b, c]
which indicate which rotor hits its notch
Ṗ - Remove c as rotor 3 has no affect
1; - Prepend 1 as rotor 1 always moves; [1, a, b]
" - Pair 1 with rotor 1, a with rotor 2 and b with rotor 3,
then for each pair:
ṙ@ - Rotate the rotor if the bit is 1
⁶ṭØAiịɗƒ - Send the character through the rotors
⁶ - Yield the reflector F
ṭ - Tack it to the end of the rotors, call this C'
ɗ - Group the previous 3 links into a dyad f(U, L):
where U is a character and L a list of characters
ØA - "ABC...XYZ"
i - Index of U in the alphabet
ị - Index into L
ƒ - Starting with X, reduce C' by the dyad f(U, L)
As C is a triple of lists of characters, this returns
A = f(f(f(f(X, C[1]), C[2]), C[3]), F), a single character
µ®Ṛi@ịØAɗƒ - Send A back through the rotors
µ - Begin a new link with A as the argument
ɗ - Group the previous 3 links into a dyad g(U, L)
i@ - Index of U in L, i
ịØA - i'th letter of the alphabet
® - Yield C
Ṛ - Reverse C
ƒ - Starting with A, reduce rev(C) by the dyad g(U, L)
This yields g(g(g(A, C[3]), C[2]), C[1]),
which is our intended result
```
## How the other 2 work
### The 45 byte version
Taking a look at the code, we notice that the only thing that's changed is that the last line is now
```
ṙ"©⁶O_65¤ṛɠÇ€
```
The difference between this version and the 37 byte version is how the rotors are taken as input:
>
> The three rotors (the strings, not the numbers) as the first command line argument, **each rotated so that the starting points are the first characters**
>
>
>
>
> The three rotors (as the strings) as the first command line argument
>
>
>
The new bits here just rotate the rotors for us and take `M` from STDIN:
```
ṙ"©⁶O_65¤ṛɠÇ€ - Main link. Takes R on the left
¤ - Create a nilad:
⁶ - The 3 starting points of the rotors
O - Converted to char points
_65 - Minus 65
" - Zip with each rotor:
ṙ - Rotate the rotor that many steps
© - Save this to the register
ɠ - Read M from STDIN
ṛ - Discard the rotors and yield M
Ç€ - Call the helper link on each character of M
```
### The 139 byte version
Let's take a look at the full code:
```
="³ị“QEVJZ”¤Ḣ€Ṗ1;ṙ@"µɼ“¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤ṭØAiịɗƒµ®Ṛi@ịØAɗƒ
ị“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’œ?ØAṙ"©⁴O_65¤ṛɠÇ€
```
[Try it online!](https://tio.run/##PU9NS8NAEL37M@K1CCoRRMQmqLW1KB4qEoSK4KG1Bw9CURASQQuNClqwVi21jR4EFUJT2U3iZZcW1n8x@0fWiYKnYea9eR/lvUrlSKl5jfUhcqX9uLG0mbOk3WbPQHry9A3o7eQc0FZaYwMRI4F1R20g7rAB9B5oE8hnVTrE4J0dabeGjQV@Z@AvfcdZQknRHN2wAftAdimNO56T09if2/KEdKIqUA9InXmHEF0CORN@YvNiAO0CuYAoQO6@dOLCyiwC/Fr47Gscwvq3CyFlNEGA9hBaPTYPuM9rqIEwhFdA@kC839BlXcQniWIU7G4zzwR6/p8X62nsVTrBenFGT8I/iCdew/JKZbLmorWWy2e2LDWV0lPTSivks9oP "Jelly – Try It Online")
This is very similar to our 45 byte version. In fact, here's what's different in the first lines, with everything that is unchanged, replaced with `.`
```
..³ị“QEVJZ”¤..........“¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤.................
```
Furthermore, you'll note that the end of the first line is `ṙ"©⁴O_65¤ṛɠÇ€`, which is the first line of the 45 byte version, meaning that there are really only three changes. In this case, those changes are because of the changes to the input system. Here's the first 2:
* `⁴` \$\to\$ `³ị“QEVJZ”¤`. Rather than take the notches as input, we use the rotor list (`³`) to `ị`ndex into the string of notches `“QEVJZ”`. The `¤` is simply a precedence marker, telling the program to treat this as a constant
* `⁵` \$\to\$ `“¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤`. Again, this is changing an input into program data, the reflector in this case. `¤` Once again acts as a precedence marker. However, we have 3 new commands here:
+ `œ?` is a dyad which takes 2 arguments - on the left, an integer `x`, and on the right a string, `s` - and returns the `x`'th permutation of `s`
+ `ØA` we've already encountered, and is the uppercase alphabet. In this context, it acts as the right argument to `œ?`
+ `“¡ƝḋœṚṗḶw⁸Aß`’` is the compressed integer \$383316524290458478707255597\$, which is the left argument to `œ?`Together, this returns the \$383316524290458478707255597\$th permutation of the uppercase alphabet, or the string `"YRUHQSLDPXNGOKMIEBFZCWVJAT"`
The final change is the entire start of the last line:
```
ị“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’œ?ØA
```
Here, we have a list of massive compressed numbers:
```
“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’
```
Each `“` marks the beginning of a new compressed number, and the entire list is
```
[67892310845892591685803413, 5023890671354916271018308, 16834429128340685633834184, 72949485053238139997554738, 340670280577577536609579431]
```
We then take the three integers which correspond to the three rotor inputs with `ị`, and then use `œ?ØA` to generate the alphabet permutations we want for each rotor. Finally, these permutations are fed into the rest of the program, already covered above.
[Answer]
# Python 3, 403 bytes
I think this is working correctly. The rotors passed to it:
```
def z(p,o,m,f,g,h):
O=ord;b=lambda a:a[1:]+a[:1];d=lambda a:chr(a+O('A'));e=lambda a:O(a)-O('A');i=[list(g[i-1])for i in p];j=[f[i-1]for i in p];i=[x[e(y):]+x[:e(y)]for x,y in zip(i,o)];k=[]
for l in m:
if i[0][0]==j[0]:i[1]=b(i[1])
elif i[1][0]==j[1]:i[1]=b(i[1]);i[2]=b(i[2])
i[0]=b(i[0]);c=l
for n in i:c=n[e(c)]
c=h[e(c)]
for n in reversed(i):c=d(n.index(c))
k+=[c]
return''.join(k)
```
`f` is the notch, `g` is the rotors and `h` is the reflector.
Ungolfed:
```
shift = lambda rotor: rotor[1:] + rotor[:1]
letter = lambda num: chr(num + ord('A'))
number = lambda chr: ord(chr) - ord('A')
def encode(rotors, rotorStart, message, defaultRotors, reflector, rotorNotchPositions):
usedRotors = [list(defaultRotors[i - 1]) for i in rotors]
notches = [rotorNotchPositions[i - 1] for i in rotors]
usedRotors = [rotor[number(offset):] + rotor[:number(offset)] for rotor, offset in zip(usedRotors, rotorStart)]
sub = []
for char in message:
# print([''.join(rotor) for rotor in usedRotors])
if usedRotors[0][0] == notches[0]:
usedRotors[1] = shift(usedRotors[1])
elif usedRotors[1][0] == notches[1]:
usedRotors[1] = shift(usedRotors[1])
usedRotors[2] = shift(usedRotors[2])
usedRotors[0] = shift(usedRotors[0])
c = char
for rotor in usedRotors:
c = rotor[number(c)]
c = reflector[number(c)]
for rotor in reversed(usedRotors):
c = letter(rotor.index(c))
sub += [c]
print([''.join(rotor) for rotor in usedRotors], char, c, message)
return ''.join(sub)
rotorNotchPositions = 'QEVJZ'
*defaultRotors, reflector = [
#ABCDEFGHIJKLMNOPQRSTUVWXYZ#
"EKMFLGDQVZNTOWYHXUSPAIBRCJ", # 1
"AJDKSIRUXBLHWTMCQGZNPYFVOE", # 2
"BDFHJLCPRTXVZNYEIWGAKMUSQO", # 3
"ESOVPZJAYQUIRHXLNFTGKDCMWB", # 4
"VZBRGITYUPSDNHLXAWMJQOFECK", # 5
"YRUHQSLDPXNGOKMIEBFZCWVJAT" # R
]
# Rotor Position Input Output
assert encode((4, 1, 5), ('H', 'R', 'G'), 'AAAAAAAAA',
defaultRotors, reflector, rotorNotchPositions) == 'PXSHJMMHR'
assert encode((1, 2, 3), ('A', 'A', 'A'), 'PROGRAMMINGPUZZLES',
defaultRotors, reflector, rotorNotchPositions) == 'RTFKHDOCCDAHRJJDFC'
assert encode((1, 2, 3), ('A', 'A', 'A'), 'RTFKHDOVZSXTRMVPFC',
defaultRotors, reflector, rotorNotchPositions) == 'PROGRAMRXGVGUVFCES'
assert encode((2, 5, 3), ('U', 'L', 'I'), 'GIBDZNJLGXZ',
defaultRotors, reflector, rotorNotchPositions) == 'UNCRAUPSCTK'
```
I think this is working, but it produces a different output, due to what (I think) is a bug in the reference impl.
] |
[Question]
[
# Input:
A maze containing the characters:
* `--` (horizontal wall);
* `|` (vertical wall);
* `+` (connection);
* (walking space);
* `I` (entrance);
* `U` (exit).
I.e. an input could look like this:
```
+--+--+--+--+--+--+--+--+--+--+
I | | |
+ +--+--+--+ + + + +--+ +
| | | | | |
+--+--+--+ +--+--+ + + +--+
| | | | |
+ +--+--+ + +--+--+ +--+ +
| | | | | |
+--+ + +--+--+ +--+--+ + +
| | | | | |
+ +--+--+--+ +--+--+ + + +
| | | | | |
+--+ + +--+--+ +--+--+--+--+
| | | | |
+ + +--+--+--+ +--+ + + +
| | | | | | | |
+--+--+ + +--+ + + +--+ +
| | | | | |
+ +--+--+--+ + + + + +--+
| | | | U
+--+--+--+--+--+--+--+--+--+--+
```
# Output:
The *most efficient* path you should walk to get from the entrance to the exit of the maze (through the maze), indicated by the characters indicating left, right, up and down (i.e. `>`; `<`; `^`; `v`).
**Challenge rules:**
* You can take the input in any reasonable format. String-array, single String with new-lines, 2D char-array, etc. are all possible input formats.
* The output can consist of any four distinct characters. I.e. `><^v`; `→←↑↓`; `⇒⇐⇑⇓`; `RLUD`; `0123`; `ABCD`; etc.).
* You are allowed to add spaces or trailing new-line to the output if preferred; this is optional.
* The steps are counted per square (see four `+`-symbols for the squares), and not per character.
* The maze can be of size 5x5 through 15x15, and will always be a square (so there won't be any test cases for 5x10 mazes).
* You can assume that every maze has one or more valid paths from start to finish, and you always output the shortest (see test cases 4 and 5).
* If there are multiple paths with the same length, you can choose which one to output (see test case 6).
* You cannot 'walk' outside the borders of the maze (see test cases 7 and 8).
**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, 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.
* Also, please add an explanation if necessary.
**Test cases:**
```
1. Input:
+--+--+--+--+--+--+--+--+--+--+
I | | |
+ +--+--+--+ + + + +--+ +
| | | | | |
+--+--+--+ +--+--+ + + +--+
| | | | |
+ +--+--+ + +--+--+ +--+ +
| | | | | |
+--+ + +--+--+ +--+--+ + +
| | | | | |
+ +--+--+--+ +--+--+ + + +
| | | | | |
+--+ + +--+--+ +--+--+--+--+
| | | | |
+ + +--+--+--+ +--+ + + +
| | | | | | | |
+--+--+ + +--+ + + +--+ +
| | | | | |
+ +--+--+--+ + + + + +--+
| | | | U
+--+--+--+--+--+--+--+--+--+--+
1. Output:
>v>>>vv<v>>v>v>>vvv>>>
2. Input:
+--+--+--+--+--+
I | | |
+ +--+--+ + +
| | | |
+ +--+ + + +
| | | | |
+ + +--+ + +
| | |
+--+ + +--+--+
| | U
+--+--+--+--+--+
2. Output:
>vvv>>v>>>
3. Input:
+--+--+--+--+--+
U | |
+ + +--+--+ +
| | | |
+--+--+ + +--+
| | |
+ +--+--+--+ +
| | | |
+ + + + +--+
| | I
+--+--+--+--+--+
3. Output:
<<<^<v<^^>>^<^<<
4. Input (test case with two valid paths):
+--+--+--+--+--+
U | |
+ + +--+--+ +
| | |
+--+--+ + +--+
| | |
+ +--+--+--+ +
| | | |
+ + + + +--+
| | I
+--+--+--+--+--+
4. Output:
<<^>^<^<<^<< (<<<^<v<^^>>^<^<< is less efficient, and therefore not a valid output)
5. Input (test case with two valid paths):
I
+--+--+--+--+--+--+--+--+--+--+ +--+--+--+--+
| | | | |
+ + + +--+--+--+ + +--+--+ +--+--+ + +
| | | | | | | |
+--+--+--+ +--+ + +--+--+--+--+ +--+--+--+
| | | | | | | | |
+ + + + + +--+ + + + +--+--+ +--+ +
| | | | | | | |
+ +--+--+--+ +--+--+ + +--+ +--+--+ +--+
| | | | | | | | |
+ +--+ + +--+ +--+--+ +--+--+ + +--+ +
| | | | | | |
+ + +--+--+--+--+ + +--+--+--+ +--+ +--+
| | | | | | | |
+--+--+--+ + +--+--+ +--+ + +--+ +--+ +
| | | | | | | |
+ +--+--+--+--+ + + +--+--+--+ + + + +
| | | | | | | | | |
+--+ + + + + + +--+--+ + + +--+ + +
| | | | | | | | | |
+--+ +--+--+ + + + +--+--+--+ + + + +
| | | | | | | | | |
+ +--+ +--+--+ + +--+--+ + +--+ + + +
| | | | | | | | | |
+--+--+--+ + + +--+ + +--+--+ +--+ + +
| | | | | | | |
+ + +--+--+--+--+ +--+--+ +--+--+ +--+ +
| | | | | |
+ + + +--+--+--+--+--+--+--+--+ +--+ +--+
| | | |
+--+--+--+--+--+--+--+--+--+ +--+--+--+--+--+
U
5. Output:
v<<<v<vv<<v<v>>^>>^^>vvv>>>v>vv<vv<<v<v<^<^^^^<vvvvv<^<v<<v>v>>>>>>>v (v<<<v<vv<<v<v>>^>>^^>vvv>>>v>vv<vv<<v<v<^<^^^^<vvvvv>v>>>^>>^>^^>vvv<v<v<<v is less efficient, and therefore not a valid output)
6. Input:
+--+--+--+--+--+
I |
+ + + + + +
| |
+ + + + + +
| |
+ + + + + +
| |
+ + + + + +
| U
+--+--+--+--+--+
6. Output:
>>v>v>v>v> or >v>v>v>v>> or >>>>>vvvv> or etc. (all are equally efficient, so all 10-length outputs are valid)
7. Input:
I U
+ + +--+--+--+
| | | |
+ +--+--+ + +
| | | |
+--+ + +--+ +
| | | |
+ +--+ + + +
| | |
+--+ +--+--+ +
| | |
+--+--+--+--+--+
7. Output:
vv>v>^>^<<^
8. Input:
+--+--+--+--+--+
| | |
+ +--+ +--+ +
I | | | |
+ + +--+ + +
U | | | |
+--+--+ + + +
| | | |
+ +--+--+--+ +
|
+--+--+--+--+--+
8. Output:
>v<
```
Mazes generated using [this tool](http://www.delorie.com/game-room/mazes/genmaze.cgi) (and in some cases slightly modified).
[Answer]
# [Perl 6](http://perl6.org/), ~~259~~ 295 bytes
```
{my \a=S:g/(.)$0+/{$0 x($/.comb+.5)*2/3}/;sub f (\c,\v,*@p) {with (c ne any v)&&a.lines».comb[+c[0];+c[1]] ->$_ {for (/\s/??10011221!!/I/??a~~/^\N*I|I\N*$/??2101!!1012!!'').comb X-1 {f [c Z+$^a,$^b],(|v,c),@p,chr 8592+$++}
take @p if /U/}}
[~] (gather f a~~/(\N+\n)*(.)*I/,[]).min(+*)[1,3...*]}
```
### How it works
1. ```
my \a = S:g/ (.) $0+ /{ $0 x ($/.chars + .5) * 2/3 }/;
```
This squeezes the maze so that the inside of each cell is 1x1 instead of 2x1 space characters:
```
+--+--+--+--+--+ +-+-+-+-+-+
I | | | I | | |
+ +--+--+ + + + +-+-+ + +
| | | | | | | |
+ +--+ + + + + +-+ + + +
| | | | | --> | | | | |
+ + +--+ + + + + +-+ + +
| | | | | |
+--+ + +--+--+ +-+ + +-+-+
| | U | | U
+--+--+--+--+--+ +-+-+-+-+-+
```
2. ```
sub f (\c,\v,*@p) {
with (c ne any v) && # If the coordinate wasn't visited yet
lines».comb[+c[0];+c[1]] -> $_ { # and a character exists there...
for ( # For each vector...
/\s/ ?? 10011221 !! # from a cell: (0,-1), (-1,0), (0,1), (1,0)
/I/ ?? a~~/^\N*I|I\N*$/
?? 2101 # from a top/bottom entrance: (1,0), (-1,0)
!! 1012 # from a left/right entrance: (0,-1), (0,1)
!! '' # otherwise: none
).comb X-1 {
f # Recurse with arguments:
[c Z+ $^a, $^b], # c plus the vector
(|v, c), # v with c appended
@p, chr 8592 + $++ # p with the correct Unicode arrow appended
}
take @p if /U/
}
}
```
This is the recursive path-finding function. It takes three parameters: The current coordinate `c=(y,x)`, the list of already visited coordinates `v`, and the path `p` taken so far (as a list of arrow characters).
If the character at the current coordinate is a space, it recurses to its four neighbors.
If the character at the current coordinate is a `I`, it recurses to the two neighbors that aren't "along the edge", to force solutions to go through the maze and not around it.
If the character at the current coordinate is a `U`, it calls `take` on the accumulated path string.
3. ```
[~] (gather f a ~~ /(\N+\n)*(.)*I/, []).min(+*)[1,3...*]
```
The recursive function is initially called with the coordinate of the letter `I`, which is found using a regex.
The `gather` keyword collects all values on which `take` was called inside the function, i.e. all valid non-cyclical paths through the maze.
The shortest path is chosen, every second arrow is dropped to account for the fact that two identical moves are required to get from one cell to the next, and the remaining arrows are concatenated to form the string that is returned from the lambda.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~338~~ ~~281~~ ~~275~~ ~~273~~ 261 bytes
```
¶U
¶&
+`·(\w.+)$
|$1
((.)+I.+¶.+¶(?<-2>.)+)·
$1v
+`((.)*)\+(.).*(¶(?<-2>.)*.)((\w)|·)·?
$1$4$.4$3$6
·v
-v
G`1
·U
&
{`\B·\d+.(\w+)
$1K$&
(\w+)·\d+.\B
$&$1r
(?<=\D\2.(\w+).+?¶.*\D(\d+)[·&])\B
$1v
)`\D(\d+).\B(?=.+¶.*\D\1·(\w+))
$&$2A
^.+\d·(\w+)
&$1A
M!`&\w+
I|&
```
[Try it online!](https://tio.run/##pVa7asMwFN3vXxSEkCwscBo6NTUJgRJKx0xViwPp0KVDKOlQfVe068fSazuQ2HpYTnCsyFdH0tG5R7J3nz9f35vj0R7WYA8URGUNU79ScAKaFMCY5GIlhT3UNysf88kTRrg1QIo9wmtAxpXAP5mxMySTnOFAXFuD4BLRZErklNyTB7BmD/kenqsCq2ug8FephTVqKyR2ERzBL4RCU2/DagGEkmIHOPxMLdWkBUpRIrFMLRmC@Js19J3XUGTGq1MU@7Jy1qwAgapo1ic4rweczOFDCrU9xQCnmMPrXUXxCVaaAgpjbrlWsUYQeR771ZhOAPS5s46NrFP5NUAN7VTnokvhItSvNkVLK8ZtfJsGVwcPP0clR6JeMczHR6UnT4dIINzn7YgUkyNVL/Cly5M5DykYo0ka9oLO0OxeyG0@CnWBmG/88nU1GmXhYb1geHd51buQKGHbp2VTe13kmjoUdzh5Fz7a@a1GwU3nNZGrXSx7EV6xhUDQw9dqFcnL6OyFNpfXUX5OEbXSmnTY46FjPJS5RMcktsXPgWA1xif5jasT3ytDHwID59J1V@BsSvgcqZlcO@t6GPIP "Retina – Try It Online")
---
**Notes**
* Due to significant whitespaces, all spaces (`0x20`) are replaced with interpunct (`·`) both in this answer and the TIO link. The program works fine if the spaces are restored.
* Uses `AvKr` for up, down, left, and right, respectively. Those can be replaced with any **letters** except `I`.
* ~~Takes about 40s on TIO for the 15×15 test case. Be patient.~~ Reworked the part for finding the shortest path once the path reached the exit. Turns out that was taking a lot of time.
* Could completely break on mazes that are 66 or more cells wide but can handle mazes of arbitrary height. A fix for arbitrary width takes +1 byte.
---
# Explanation
The program consists of 3 phases:
* A **construction phase** to convert the maze to a compact format that is easier to work with (detailed below).
* A **fill phase** to actually solve the maze using a flood fill algorithm.
* A **return phase** to return the shortest path at the exit.
---
# Format
Since the original maze format is quite unwieldy, the first part of the program converts it into a different format.
**Cells**
In the original format, each cell is represented as a 2×3 region:
```
+ <top wall> <top wall>
<left wall> <data/space> <space>
```
Since the right column contains no information, the program identifies cells as any 2×2 region with a `+` at the top-left.
This leaves us with 3 kinds of cells:
* **I Cells**: Cells that are properly inside the maze.
* **R Cells**: Cells that are to the right of the maze. These are created by the padding used to house the entrance or exit. For example, the exit `U` in test case 1 is in an R-Cell.
* **B Cells**: Cells that are below the maze. Like R-Cells, these are created by padding.
In the new format, cells are represented as a variable-length string:
```
<left wall> <column number> <top wall/exit marker> <path>
```
The left and top wall are copied from the original format. The column number is based on the horizontal position of the cell and is used for alignment (identifying cells directly on top of/beneath each other). Path is an alphabetical string used during the fill phase to save the shortest path to reach that cell. Path and exit marker will be further explained.
**Half-cells**
Although most of the maze are cells, there are regions of the maze that are not cells:
* **R Half-cells**: If there is no right padding, the `+`s along the right wall does not form cells since they are on the last column.
* **L Half-cells**: If there is left padding, cells cannot form there since there are no `+` to the left of them. For example, the entrance `I` in test case 1 is in an L Half-cell.
Technically, there are **T half-cells** above the maze (when there is top padding) and **B half-cells** (along the bottom wall when there is no bottom padding) but they are not represented in the new format.
The top row of a half-cell would be removed as part of constructing full cells in the same row, so half-cells are represented in the new format as
```
<wall/exit marker>? <path>
```
An R Half-cells is just `|`. An L Half-cells has just `I` as the path, just the exit marker and an empty path, or just an empty wall.
**Entrances and exits**
If the entrance is to the left, right or bottom of the maze, then the entrance marker `I` would naturally be included in the (half-)cell as the path, which can be removed when returning the final path.
If the entrance is above the maze, the first (downward) step is taken during the construction phase since T half-cells are removed during construction. This keeps a workable path in a full cell. The top wall is closed afterwards.
If the exit is to the left, right or bottom of the maze, then `U` would naturally be included in the (half-)cell. To avoid being mistaken as a path, the non-alphanum exit marker `&` is used instead of `U`. The exit marker is embedded into a cell or half-cell (as specified above).
If the exit is above the maze, then it would be the only hole that can go above the top row of cells (since the one for the entrance, if present, would be closed already). Any path reaching that hole can exit the maze by taking an upward step.
Lastly, any B Cell containing the entrance or exit must close its left wall to prevent "solving" the maze by walking along the B Cells. Entrances and exits in R Cells or L Half-cells need no further processing since the flood fill algorithm does not permit vertical movements to/from them.
**Example**
As an example, the first test case
```
·+--+--+--+--+--+--+--+--+--+--+·
I···············|·····|········|·
·+··+--+--+--+··+··+··+··+--+··+·
·|···········|·····|··|··|·····|·
·+--+--+--+··+--+--+··+··+··+--+·
·|···········|·····|·····|·····|·
·+··+--+--+··+··+--+--+··+--+··+·
·|·····|·····|·····|·····|·····|·
·+--+··+··+--+--+··+--+--+··+··+·
·|·····|········|········|··|··|·
·+··+--+--+--+··+--+--+··+··+··+·
·|·····|·····|·····|········|··|·
·+--+··+··+--+--+··+--+--+--+--+·
·|··|··|·················|·····|·
·+··+··+--+--+--+··+--+··+··+··+·
·|·····|········|··|··|··|··|··|·
·+--+--+··+··+--+··+··+··+--+··+·
·|········|·····|·····|··|·····|·
·+··+--+--+--+··+··+··+··+··+--+·
·|···········|·····|··|·········U
·+--+--+--+--+--+--+--+--+--+--+·
```
is
```
I·3-·6-·9-·12-·15-|18-·21-|24-·27-·30-|33·
·|3··6-·9-·12-|15··18·|21·|24·|27-·30·|33·
·|3-·6-·9-·12·|15-·18-|21··24·|27··30-|33·
·|3··6-|9-·12·|15··18-|21-·24·|27-·30·|33·
·|3-·6·|9··12-·15-|18··21-·24-|27·|30·|33·
·|3··6-|9-·12-|15··18-|21-·24··27·|30·|33·
·|3-|6·|9··12-·15-·18··21-·24-|27-·30-|33·
·|3··6·|9-·12-·15-|18·|21-|24·|27·|30·|33·
·|3-·6-·9·|12··15-|18··21·|24·|27-·30·|33·
·|3··6-·9-·12-|15··18·|21·|24··27··30-·33&
```
in the new format. You can convert other mazes [here](https://tio.run/##nVTLDoIwELzvdzSmpWkTlHgycjR8ADcOePDgxYMxeOl30Xt/DJcYeS6FGl6byWQnwww8b6/749o0rs7B1TuQpbO8eGspGBgWA@dayExLV7cXT09qf0ZEOAssrpDeEiJRSHzoiPeUSAuOi4RxFskpslnCdMIO7AjOVqAquJQxjjnsUN5KpXwn6mXO@g5Djh2ASrIdhyt/UH/rYSDW0EJmDsJMh5T8@tosRI0TW6PdA23SlAmX8khM7MFqIgRg/GEt5Bboaqy37qor4ELe2woJ0@TJgMLe38IN6DoEVd2s9D3wu/qn7gQthw0/ig8).
---
# Construction phase
The construction phase makes up the first 13 lines of the program.
```
¶U
¶&
```
Converts exit in L Half-cell to exit marker
```
+`·(\w.+)$
|$1
```
Adds walls to the left of entrance and exit in B Cells
```
((.)+I.+¶.+¶(?<-2>.)+)·
$1v
```
Takes the first step if entrance is above the maze
```
+`((.)*)\+(.).*(¶(?<-2>.)*.)((\w)|·)·?
$1$4$.4$3$6
```
Performs the actual conversion
```
·v
-v
```
Closes the top-entrance hole
```
G`1
```
Keeps only lines with a `1`. Since mazes are at least 5 cells wide and column numbers occurs at increments of 3, a line with new-format cells must have a contain a column number between 10 and 19.
```
·U
&
```
Converts exit in R Cell or B Cell to exit marker
---
# Fill phase
The fill phase makes up the next 8 lines of the program. It uses a flood fill algorithm to fill all cells with the shortest path to reach there from the entrance.
```
{`
```
Puts the whole fill phase on a loop to fill the whole maze.
```
\B·\d+.(\w+)
$1K$&
```
Each cell able to move left does so. A cell is able to move left if
1. it has a non-empty path
2. it has an empty left wall; and
3. the cell or L half-cell to its left has an empty path
```
(\w+)·\d+.\B
$&$1r
```
Then, each cell able to move right does so. A cell is able to move right if
1. it has a non-empty path
2. the cell to its right has an empty left wall; and
3. the cell to its right has an empty path
```
(?<=\D\2.(\w+).+?¶.*\D(\d+)[·&])\B
$1v
```
Then, each cell able to move down does so. A cell is able to move down if
1. it has a non-empty path
2. it has at least one cell or half-cell to its right (i.e. it is not an R Cell)
3. the cell below it (i.e. the cell on the next line with the same column number) has an empty top wall or has the exit marker; and
4. the cell below it has an empty path
Note that L Half-cells cannot move down since they don't have column numbers.
```
\D(\d+).\B(?=.+¶.*\D\1·(\w+))
$&$2A
```
Then, each cell able to move up does so. A cell is able to move up if
1. it has a non-empty path
2. it has an empty top wall
3. the cell above it has at least one cell or half-cell to its right; and
4. the cell above it has an empty path
---
# Return phase
The return phase makes up the last 5 lines of the program. This phase searches for and returns the path filled into the exit cell.
The pattern of the path at the exit depends on where the exit is:
1. If the exit is in an L Half-cell, then that half-cell would be `& <path>`
2. If the exit is in an R Cell or B Cell, then that cell would be `<left wall> <column number> & <path>`
3. If the exit is in a T Half-cell, then as noted above, the the I Cell leading to the exit would be `<left wall> <column number> · <path>` and on the top row.
```
^.+\d·(\w+)
&$1A
```
Finds a cell on the top line with an empty top wall and a non-empty path. This takes care of the last case by adding the last step and the exit marker.
```
M!`&\w+
```
Matches and returns a non-empty path following an exit marker.
```
I|&
```
Removes the exit marker and the `I` prefix of the path.
[Answer]
# Python 2: 302 bytes
```
from re import*
r=lambda x:[''.join(_)for _ in zip(*x)][::-1]
z=',l)for l in s]'
def f(s,b=1,o=0,n=0):
exec("s=[sub('(..).(?!$)',r'\\1'%s;"%z+"s=r([sub(' I ','+I+'%s);"%z*4)*b+"t=[sub('I ','@@I'"+z
if'I U'in`s`or n>3:return`o%4`+n/4*`s`
return min(`o%4`+f(t,0,o,4*(t==s)),f(r(s),0,o+1,n+1),key=len)
```
Takes input as an array of strings all with the same length. Prints `0` for right, `1` for down, `2` for left, and `3` for up.
### Explanation
I took a different approach than the other answers. General idea: recursively search by finding the shortest path between going straight forward and rotating the board 90 degrees.
```
from re import*
r=lambda x:[''.join(_)for _ in zip(*x)][::-1] #Rotates the board counterclockwise
z=',l)for l in s]' #Suffix for hacky exec golfing
def f(s,b=1,o=0,n=0): #b is 1 on initial call, 0 on every recursion
#o is orientation
#n is number of rotations
exec("s=[sub('(..).(?!$)',r'\\1'%s;"%z #Squeeze the maze
+"s=r([sub(' I ','+I+'%s);"%z*4) #Add walls around the I to keep it in the maze
*b #Only if b is 1
+"t=[sub('I ','@@I'"+z #Attempt to move right
if'I U'in`s`or n>3:return`o%4`+n/4*`s` #If the I is next to the U, return the orientation
#If there were 4 rotations, return a long string
return min( #Return the path with the shortest length:
`o%4`+f(t,0,o,4*(t==s)), #Moving forward if possible
f(r(s),0,o+1,n+1), #Rotating the board
key=len)
```
[Try it online!](https://tio.run/##zVdRb5swEH6/X3GLVtkObtZseWJi6ys/IE9p1DQraGwJREClNOK/Z5CkAZ/P0KdqyIqMbb7cfXf@fN69lr@z9OvxGOfZFvMIk@0uy8sx5MHmabt@fsK9vxBi8idLUvmo4izHR0xSPCQ7Od6r5cL3b6dLOARCb06zm2a2WAp4jmKMZaHXwVRnwZ1OgzvlA0b76JccFcGieFlLIScTNZE/P31WQufi4WEqborvo5uDV6/I5XkNhii08EKvnlPN5HimxmtvVF4wQmzm7@9DMfIOgElcj8xFkq6KVW1P@uObn0flS56uspvZyku/zMb1DOB5ELe1X@eZWJb6Tmd6NpZlEBRK6VjmslDNoDfVqTdV@m/0GmyiVB3LqChrJ0AIAejd3vY1hNpE46k6v6dOjYEdGMS2XV6hXd4FqNo@mAAE6WQHj4EGBvm0i9e1o@rDYL9urQGbgLZT8XxQYtx2YIvhsuMtLgaDXIAADQCDCbcvZgOL0J7YVlZ4h/KjP7bt4Hw4T@tkXkz9pQY@rc95bJHsii4XTsJbZVgKaFHEMMOE1YoB5@ywd3Pkt6XhIBhGoyPAvN00hDyWK7Ktd@FHeIf/sXf9D1FbGEp78@@A2sO9tukNhjsu5bwOQoW8@PEKALzwuMyHypIg@w@66IyQIHXoOg6VW7IZD6BPwsnIxXa3mDPMEEJcjFPbXbwbU8ATzR4ENGcGKSJRZQ5ZtHjH3oPbiDnwhrvOD7AOG@yJ89l2kjZ8tUHQ7by0ybmis2VQn@3IFEROZlwlDtkBUDmOU54x4Bl3Rdi5m9hXV0ayHYqObkWzlaBfJpl873nsfB@U3wa9D3JujbyrakF6ptEUBpufj171nqolNBmwsoJmVVcNHDsSOK0ke57fGV29JFnIr@i2gbDZdTXYwhhSabFLyFPdQ9eQXWrdJSq7nLGjZdt8cWkJ0NyEi@YmvH3ayetFej8pdpuklOIhFUqfrpDK3@VJWjY3ZXX8Bw)
[Answer]
# JavaScript (ES6), 356 bytes
```
a=>(a=a.map(s=>s.filter((_,i)=>!i|i%3)),g=([x,y])=>a[y]&&a[y][x],o=[],c=([x,y],m="",v=[])=>[[0,1],[1,0],[0,-1],[-1,0]].map(([j,k],i)=>(p=[x+j,y+k],!m&(!y|y>a[l="length"]-2)==i%2|v.includes(""+p)||(g(p)<"!"?c(p,m+"v>^<"[i],[...v,""+p]):g(p)=="U"?o.push(m.replace(/(.)\1/g,"$1")):0))),a.map((h,i)=>h.map((k,j)=>k=="I"&&c([j,i]))),o.sort((a,b)=>a[l]-b[l])[0])
```
Takes input as a 2D array of characters. Each line must be left-padded by one space and have no trailing space, no matter where the start/end points are.
Uses [smls's idea](https://codegolf.stackexchange.com/a/109555/69583) of squishing the maze to make each cell 1x1 and removing repeated arrows from the output.
## Ungolfed and Explained
```
a=>(
a=a.map(s=>s.filter((_,i)=>!i|i%3)), // squish the maze to 1x1 cells
g=([x,y])=>a[y]&&a[y][x], // helper func to get maze value
o=[], // resulting movesets
c=([x,y], m="", v=[]) => // recursive func to search
// takes current point, moves, and visited spots
[[0,1],[1,0],[0,-1],[-1,0]].map(([j,k],i)=>(// for each direction
p=[x+j,y+k],
!m & (!y | y>a[l="length"]-2) == i%2 | // if first move, prevent moving out of maze
v.includes(""+p) || ( // also prevent if already visited
g(p)<"!" ? // is this a space?
c(p, m+"v>^<"[i], [...v,""+p]) // check this spot recursively
: g(p)=="U" ? // if this the end?
o.push( // add moves to moveset
m.replace(/(.)\1/g,"$1")) // with double arrows removed
: 0
)
)),
a.map((h,i)=>h.map((k,j)=> // find the starting "I" and
k=="I" && c([j,i]) // begin recursion at that point
)),
o.sort((a,b)=>a[l]-b[l])[0] // get shortest path
)
```
## Test Snippet
```
f=
a=>(a=a.map(s=>s.filter((_,i)=>!i|i%3)),g=([x,y])=>a[y]&&a[y][x],o=[],c=([x,y],m="",v=[])=>[[0,1],[1,0],[0,-1],[-1,0]].map(([j,k],i)=>(p=[x+j,y+k],!m&(!y|y>a[l="length"]-2)==i%2|v.includes(""+p)||(g(p)<"!"?c(p,m+"v>^<"[i],[...v,""+p]):g(p)=="U"?o.push(m.replace(/(.)\1/g,"$1")):0))),a.map((h,i)=>h.map((k,j)=>k=="I"&&c([j,i]))),o.sort((a,b)=>a[l]-b[l])[0])
let tests = [" +--+--+--+--+--+--+--+--+--+--+\nI | | |\n + +--+--+--+ + + + +--+ +\n | | | | | |\n +--+--+--+ +--+--+ + + +--+\n | | | | |\n + +--+--+ + +--+--+ +--+ +\n | | | | | |\n +--+ + +--+--+ +--+--+ + +\n | | | | | |\n + +--+--+--+ +--+--+ + + +\n | | | | | |\n +--+ + +--+--+ +--+--+--+--+\n | | | | |\n + + +--+--+--+ +--+ + + +\n | | | | | | | |\n +--+--+ + +--+ + + +--+ +\n | | | | | |\n + +--+--+--+ + + + + +--+\n | | | | U\n +--+--+--+--+--+--+--+--+--+--+"," +--+--+--+--+--+\nI | | |\n + +--+--+ + +\n | | | |\n + +--+ + + +\n | | | | |\n + + +--+ + +\n | | |\n +--+ + +--+--+\n | | U\n +--+--+--+--+--+"," +--+--+--+--+--+\nU | |\n + + +--+--+ +\n | | | |\n +--+--+ + +--+\n | | |\n + +--+--+--+ +\n | | | |\n + + + + +--+\n | | I\n +--+--+--+--+--+"," +--+--+--+--+--+\nU | |\n + + +--+--+ +\n | | |\n +--+--+ + +--+\n | | |\n + +--+--+--+ +\n | | | |\n + + + + +--+\n | | I\n +--+--+--+--+--+"," I\n +--+--+--+--+--+--+--+--+--+--+ +--+--+--+--+\n | | | | |\n + + + +--+--+--+ + +--+--+ +--+--+ + +\n | | | | | | | |\n +--+--+--+ +--+ + +--+--+--+--+ +--+--+--+\n | | | | | | | | |\n + + + + + +--+ + + + +--+--+ +--+ +\n | | | | | | | |\n + +--+--+--+ +--+--+ + +--+ +--+--+ +--+\n | | | | | | | | |\n + +--+ + +--+ +--+--+ +--+--+ + +--+ +\n | | | | | | |\n + + +--+--+--+--+ + +--+--+--+ +--+ +--+\n | | | | | | | |\n +--+--+--+ + +--+--+ +--+ + +--+ +--+ +\n | | | | | | | |\n + +--+--+--+--+ + + +--+--+--+ + + + +\n | | | | | | | | | |\n +--+ + + + + + +--+--+ + + +--+ + +\n | | | | | | | | | |\n +--+ +--+--+ + + + +--+--+--+ + + + +\n | | | | | | | | | |\n + +--+ +--+--+ + +--+--+ + +--+ + + +\n | | | | | | | | | |\n +--+--+--+ + + +--+ + +--+--+ +--+ + +\n | | | | | | | |\n + + +--+--+--+--+ +--+--+ +--+--+ +--+ +\n | | | | | |\n + + + +--+--+--+--+--+--+--+--+ +--+ +--+\n | | | |\n +--+--+--+--+--+--+--+--+--+ +--+--+--+--+--+\n U"," +--+--+--+--+--+\nI |\n + + + + + +\n | |\n + + + + + +\n | |\n + + + + + +\n | |\n + + + + + +\n | U\n +--+--+--+--+--+"," I U\n + + +--+--+--+\n | | | |\n + +--+--+ + +\n | | | |\n +--+ + +--+ +\n | | | |\n + +--+ + + +\n | | |\n +--+ +--+--+ +\n | | |\n +--+--+--+--+--+"," +--+--+--+--+--+\n | | |\n + +--+ +--+ +\nI | | | |\n + + +--+ + +\nU | | | |\n +--+--+ + + +\n | | | |\n + +--+--+--+ +\n | \n +--+--+--+--+--+"];
S.innerHTML="<option>Tests"+Array(tests.length).fill().map((_,i)=>"<option>"+(i+1)).join``;
```
```
<select id=S oninput="I.value=S.selectedIndex?tests[S.value-1]:''"></select><br>
<textarea id=I rows=20 cols=50></textarea><br><button onclick="O.innerHTML=f(I.value.split`\n`.map(x=>[...x]))">Run</button>
<pre id=O>
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 416 bytes
```
T` `+`^.*| ?¶.|.*$
I
#
{+` (\w)
d$1
+`(\w)
$1a
+`(¶(.)*) (.*¶(?<-2>.)*(?(2)(?!))\w)
$1s$3
}+m`(^(.)*\w.*¶(?<-2>.)*(?(2)(?!)))
$1w
^
w¶
w((.|¶)*(¶(.)*#.*¶(?<-4>.)*(?(4)(?!))(s)|#(d)|(a)#))
$4$5$6¶$1
{`^(.*d)(¶(.|¶)*)#(\w)
$1$4$2 #
^(.*a)(¶(.|¶)*)(\w)#
$1$4$2#
^(.*s)(¶(.|¶)*¶(.)*)#(.*¶(?<-4>.)*(?(4)(?!)))(\w)
$1$6$2 $5#
}`^(.*w)(¶(.|¶)*¶(.)*)(\w)(.*¶(?<-4>.)*(?(4)(?!)))#
$1$5$2#$6
s`U.*
(a|d)\1\1?
$1
ss
s
ww
w
```
[Try it online!](https://tio.run/##hZK/bsMgEMb3e4qrYDhsBclpkqmq5@zNZkVYcocO7VAqMYS8lh/AL@YCcWSI/8RC1uHv7sfnO34//75@6r7/UKhydZaZxbJrpZUZhyMwuOQKqTICGl5ArnyIwIvax11LUmQCSWYuLN8223e3p5K2gsoXIXwZLzR/hWv@rejssyuzkBywBs5guhYMkbRd6/TbGexetBuKdrci0sIyaoSlWjDhTtvxPT90rfN6Ue68rBGBEFiC0c2Ry9oiA6/Xse5lNugMg64jffhdRgtmxB1/cHi@Z3ANFswU4RMXKcHB3jngBwStTjIDoNo2oiqqonQiaA0ajAHT95hvNmsL4YjpY6N3CABzjDCI4xq2MKbHADvGkAIeSMHHPAMTxkNpzIt92DXGbPXoBqYNGAM734/Hxiz7wJGx5OM@l6SDcwMCTABJJ5b/JV0waejKbO1kvM/ux/psx48neHpP/wE "Retina – Try It Online") Had I seen this question when it was originally posted, this is probably the answer I would have given, so I'm posting it anyway, even though there's a much better answer in Retina. Explanation:
```
T` `+`^.*| ?¶.|.*$
```
Fill in the border. This avoids walking around the outside of the maze (e.g. for test case 7).
```
I
#
```
Place a non-alphabetic marker at the entrance.
```
{+` (\w)
d$1
+`(\w)
$1a
+`(¶(.)*) (.*¶(?<-2>.)*(?(2)(?!))\w)
$1s$3
}+m`(^(.)*\w.*¶(?<-2>.)*(?(2)(?!)))
$1w
```
Flood fill from the exit to the entrance. At each step, use a letter to indicate the best direction to go (wasd - this might be familiar to gamers; I had also considered hjkl but I found it too confusing). Additionally, prefer to repeat the same direction; this avoids going left/right in between two vertically adjacent cells.
```
^
w¶
```
Assume the first step is down.
```
w((.|¶)*(¶(.)*#.*¶(?<-4>.)*(?(4)(?!))(s)|#(d)|(a)#))
$4$5$6¶$1
```
But if there's a letter above, left or right of the entrance, change that to the first step.
```
{`^(.*d)(¶(.|¶)*)#(\w)
$1$4$2 #
^(.*a)(¶(.|¶)*)(\w)#
$1$4$2#
^(.*s)(¶(.|¶)*¶(.)*)#(.*¶(?<-4>.)*(?(4)(?!)))(\w)
$1$6$2 $5#
}`^(.*w)(¶(.|¶)*¶(.)*)(\w)(.*¶(?<-4>.)*(?(4)(?!)))#
$1$5$2#$6
```
Move the marker in the direction of the last move, reading the direction of the next move from the square that the marker is moving to, and add that to the list of directions. This repeats until the `U` is reached.
```
s`U.*
```
Delete everything after the directions as it's not needed any more.
```
(a|d)\1\1?
$1
ss
s
ww
w
```
The original grid is on a 3×2 layout. While moving vertically if we zig-zag horizontally the flood fill will optimise the movement and only move 3n-1 characters horizontally, so when dividing by three, we need to round up. Vertically we just divide by 2.
I also investigated a true square grid solution i.e where the character matrix is itself square rather than being a 3×2 layout with an optional border. While probably nonconforming to the question, the ability to transpose reduced the byte count to 350: [Try it online!](https://tio.run/##jZLBTsMwDIbvfgpPCZKdaZGGBidGzztxYTdUpVI5cIADRcqB8Fp9gL5YSbONJF3XUUWVE9tfftv5fP16@6j6/tmgWZpSK4dF12qnlYQdCHg3VCxKJq1Zg1zDt0F6sQy1twcD/WEFT0Ia79Y3Bg7uJnFb@En8JdiuBUukXdeyoq4lzUpo5Y3iYbV59DsqaMP@XmZq2Amq2VHFghnkRt7J@64NSkrSquZACCwWdbhcrn3YLdYChogqjRj8lThGiAqDcn/v1tes@CTRZzUZt0m5zYFrx1z7x7V4KHkMXhjta9vuue/x2ge4XK3mFsJulOKSfzA8AxMMYlzHLcTwFOCiDTlgRAo6phmYMUapKS/V4eYYk9lRDZw3IBpuuh/jxlzWgZFxScdpLlkHpwYEmAGyTlyuJV9w1tCZ2bqz8V57H/OzjYf7f7zTq2/9Fw "Retina – Try It Online")
] |
[Question]
[
I'm sure everyone has seen before that cups can be stacked into pyramids (and other shapes):
```
A
A A A
A A A A A
A A A A A A A A
```
Yes, `A` is definitely an adequate character to represent a cup.
New cups could be added either on the ground, to the right of the structure, or on top of two adjacent cups. Here is the above structure again, but all available spots for new cups are marked with `_`:
```
_ A
A A A
A _ _ A A A A
A A A A A A A A _ _ _
```
Let's say we want to build a robot which can assemble these cup stacks. The robot will understand two simple instructions to manipulate such a structure:
* `a`: Add a new cup in the first available spot in left-to-right *reading* order (that is, scan the rows from top to bottom, left to right until you find an available spot, then place the cup there). The above example would become:
```
A A
A A A
A A A A A
A A A A A A A A
```
* `r`: Remove the first cup in left-to-right reading order. The above example would become:
```
A A A
A A A A A
A A A A A A A A
```
It turns out that *any* structure can be constructed from scratch using only these two operations. E.g.
```
A
A A A
A A A A A
```
Can be built with the sequence of instructions
```
aaaaaaaaaaaarrrrraa
```
The larger example above can be built using
```
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrrrrraaaaaaarr
```
Here is an even bigger one:
```
A
A A A
A A A A A A A
A A A A A A A A A A A A
A A A A A A A A A A A A A A A
```
which can be built with
```
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrraaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrraaaaaaaaaaaaaarrrrrrrrrrraaaaaaaa
```
**Note:** If spots on the ground are freed up by removal instructions they will be reused *before* placing cups to the right of all existing cups. E.g.
```
aaaarrra
```
will yield
```
A A
```
not
```
A A
```
You can think of the ground as being on top of a semi-infinite row of cups.
## The Challenge
Given a structure of stacked cups, return a sequence representing the instructions to build this structure. Your primary score is the sum of the numbers of instructions for the test cases provided at the bottom. In the event of a tie (which is likely, because I'm convinced that an efficient optimal solution is possible), the shortest solution wins.
Here are some more details about the rules:
* You may assume that there are no leading spaces on the bottom row of the input, so the left-most ground spot for a cup with always be used.
* You may assume any reasonable amount of trailing spaces (no spaces, one space, padded to a rectangle, padded to a rectangle with a single trailing space).
* You may optionally expect the input to end in a single trailing newline.
* You may choose any two distinct printable ASCII characters (0x20 to 0x7E, inclusive) instead of `A` and spaces (the rules about spaces then transfer to your chosen character).
* Your output should contain only two distinct characters representing the operations (you may choose other characters than `a` and `r`). You may optionally print a single trailing newline.
* Your code must be able to solve **any of the test cases below in less than a minute** on a reasonable desktop PC (if it takes two minutes on mine, I'll give you the benefit of the doubt, but if it takes ten I won't - I believe an optimal algorithm is possible which solves any of them in less than a second).
* You must not optimise your code towards individual test cases (e.g. by hardcoding them). If I suspect anyone of doing so, I reserve the right to change the test cases.
You can use [this CJam script](http://cjam.aditsu.net/#code=r_e%600%5C%7B~'a%3D2*(*1%24%2B%7D%25%24_%40%3DW%3E%0A%7B%0A%20%20W%3D2*mQ2%2B%3ALS*aL(*'_L*a%2BN*%5C%0A%20%20%7B%0A%20%20%20%20'a%3D%0A%20%20%20%20%7B%0A%20%20%20%20%20%20_'_%23%3AI'At_I(%3D'A%3D%7BI(L)-'_t%7D%26_I)%3D'A%3D%7BIL)-'_t%7D%26%0A%20%20%20%20%7D%7B%0A%20%20%20%20%20%20_'A%23%3AI'_t_I(L)-%3D'_%3D%7BI(L)-'%20t%7D%26_IL)-%3D'_%3D%7BIL)-'%20t%7D%26%0A%20%20%20%20%7D%3F%0A%20%20%7D%2F%0A%20%20N%2F%7BS-%7D%2CW%25ee%7B~S*%5CS*%5C%2B%7D%25_0%3D%2Cf%3CW%25N*'_'%20er%0A%7D%7B%0A%20%20%26%0A%7D%3F&input=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrraaaaaaaaaaaaaaaaaaarrrrrrrrrrrrrrraaaaaaaaaaaaaarrrrrrrrrrraaaaaaaa) for the reverse operation: it will take a string of building instructions and print the resulting stack of cups. (Thanks to Dennis for rewriting the snippet and significantly speeding it up.)
Sp3000 also kindly provided [this alternative Python script](http://ideone.com/kNh1Y2) for the same purpose.
## Test Cases
After each test case, there's a number indicating the optimal number of instructions as per Ell's answer.
```
A
A A
A A A
A A A A
A A A A A
A A A A A A
A A A A A A A
A A A A A A A A
A A A A A A A A A
A A A A A A A A A A
A A A A A A A A A A A
A A A A A A A A A A A A
A A A A A A A A A A A A A
A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
820
A
A A
A A A
A A A A
A A A A A
A A A A A A
A A A A A A A
A A A A A A A A
A A A A A A A A A A
A A A A A A A A A A A A
A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
1946
A
A A
A A A
A A A A
A A A A A
A A A A A A
A A A A A A A
A A A A A A A A
A A A A A A A A A A
A A A A A A A A A A A A
A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
2252
A A
A A A A
A A A A A A
A A A A A A A A
A A A A A A A A A A
A A A A A A A A A A A A
A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
9958
A A
A A A A
A A A A A A
A A A A A A A A
A A A A A A A A A A
A A A A A A A A A A A A
A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
5540
A A A A A A A A A A A A A A A A A A A A
10280
A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
10320
A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
5794
A
A A
A A A
A A A A A
A A A A A A A
A A A A A A A A A A
A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
3297
A A
A A A
A A A A
A A A A A
A A A A A A
A A A A A A A
A A A A A A A A
A A A A A A A A A
A A A A A A A A A A A
A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
4081
A
A A A A
A A A A A A A A A
A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
4475
A
A A A A A A A A
A A A A A A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
5752
```
That means, the best possible score is **64,515** instructions.
[Answer]
# Python 2, 64,515
```
import sys
input = map(str.rstrip, sys.stdin.readlines())
width = (len(input[-1]) + 1) / 2
for i in range(len(input)):
indent = len(input) - i - 1
input[i] = [c != " " for c in input[i][indent::2]]
input[i] += [False] * (width - indent - len(input[i]))
input = [[False] * n for n in range(width - len(input) + 1)] + input
working_area = [[False] * n for n in range(width + 1)]
def add():
sys.stdout.write("a")
for row in range(width + 1):
for i in range(row):
if not working_area[row][i] and (
row == width or
(working_area[row + 1][i] and working_area[row + 1][i + 1])
):
working_area[row][i] = True
return
def remove():
sys.stdout.write("r")
for row in range(width + 1):
if True in working_area[row]:
working_area[row][working_area[row].index(True)] = False
return
for row in range(width, -1, -1):
r = input[row]; R = working_area[row]
for i in range(len(r) - 1, -1, -1):
if r[i]:
while not R[i]: add()
else:
while R[i]: remove()
```
## Results
[![Test 1](https://i.stack.imgur.com/FGBsZ.gif)](https://i.stack.imgur.com/M6xZO.gif) **#1** - [820](https://gist.githubusercontent.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test1)
[![Test 2](https://i.stack.imgur.com/LbqwF.gif)](https://i.stack.imgur.com/LufCh.gif) **#2** - [1,946](https://gist.githubusercontent.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test2)
[![Test 3](https://i.stack.imgur.com/PES2L.gif)](https://i.stack.imgur.com/T3gKA.gif) **#3** - [2,252](https://gist.githubusercontent.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test3)
[![Test 4](https://i.stack.imgur.com/T7f6f.gif)](https://i.stack.imgur.com/rKkkV.gif) **#4** - [9,958](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test4)
[![Test 5](https://i.stack.imgur.com/fELhA.gif)](https://i.stack.imgur.com/czBFQ.gif) **#5** - [5,540](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test5)
[![Test 6](https://i.stack.imgur.com/TQW4i.gif)](https://i.stack.imgur.com/T4LyW.gif) **#6** - [10,280](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test6)
[![Test 7](https://i.stack.imgur.com/SWpvk.gif)](https://i.stack.imgur.com/osCj1.gif) **#7** - [10,320](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test7)
[![Test 8](https://i.stack.imgur.com/TNFBi.gif)](https://i.stack.imgur.com/pIlXQ.gif) **#8** - [5,794](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test8)
[![Test 9](https://i.stack.imgur.com/JRj0E.gif)](https://i.stack.imgur.com/eMGsQ.gif) **#9** - [3,297](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test9)
[![Test 10](https://i.stack.imgur.com/vfOGr.gif)](https://i.stack.imgur.com/cMfoZ.gif) **#10** - [4,081](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test10)
[![Test 11](https://i.stack.imgur.com/8sPpa.gif)](https://i.stack.imgur.com/YhC8j.gif) **#11** - [4,475](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test11)
[![Test 12](https://i.stack.imgur.com/yjCuH.gif)](https://i.stack.imgur.com/DF6xV.gif) **#12** - [5,752](https://gist.github.com/anonymous/bee1a2949430e04d9b6e/raw/ff6ad031168259f43f3d33be5459d1529e5d3fb0/test12)
**Total** 64,515
## Explanation
We start with an empty "working area".
We scan the input in *reverse* reading order, i.e., right-to-left and bottom-to-top.
If there's a mismatch between the input and the working area at the current location (i.e., a cup is present in the input but not in the working area, or vice versa,) we add, or remove, cups to the working area, according to the rules, until the mismatch is resolved, at which point we continue to the next location.
**Correctness**
To show that this method is correct, i.e., that the resulting sequence generates the input structure, it's enough to show that we never modify (i.e., add or remove cups at) locations we've already visited (since, at each location we visit, we make sure that the working area matches the input.)
This is an easy consequence of the fact that we work in the reverse order in which cups are added and removed:
* A cup at location *l* will always be removed before a cup at a location that succeeds *l* in reading order, and therefore, that precedes *l* in scan order, hence there's no danger of removing a cup we've already visited.
* Similarly, a cup at location *l* will always be added before a cup that precedes it in scan order, **given that** there are already two cups below it (or that it's at the bottom);
however, since we will have already visited these locations, and hence added the necessary cups, and since, as noted above, there's no danger of later having removed those cups, this condition is met, and so there's no danger of adding a cup at a location we've already visited.
**Optimality**
Note that the effect of adding, or removing, a cup from a structure doesn't depend on the sequence of operations used to generate the structure, only on its current configuration.
As a result, given an optimal sequence *Sn* = {*s*1, ..., *sn*} of operations that generate a certain structure, every initial segment of *Sn*, i.e., any sequence *Sm* = {*s*1, ..., *sm*}, where *m* ≤ *n*, is also an optimal sequence, for the corresponding structure it generates, or else there would be a shorter sequence than *Sn*, generating the same structure.
We can show that our method is optimal by induction on the length of the optimal generating sequence:
Our method clearly generates an optimal sequence for any structure whose optimal generating sequence is empty (there's only one such structure—the empty structure.)
Suppose that our method generates an optimal sequence for all structures whose optimal sequence (or sequences) is of length *n*, and consider a structure generated by an optimal sequence *S**n*+1.
We want to show that, given the structure generated by *S**n*+1 as input, our method produces the same sequence (or, at least, a sequence of the same length.)
As noted above, *Sn* is also an optimal sequence, and so, by hypothesis, our method produces an optimal sequence given the structure generated by *Sn* as input.
Suppose, without loss of generality, that *Sn* is the sequence produced by our method (if it isn't, we can always replace the first *n* elements of *S**n*+1 with the said sequence, and get a sequence of length *n* + 1 that generates the same structure.)
Let *l* be the location modified by the last operation in *S**n*+1 (namely, *s**n*+1), and let *Sm* be the initial segment of *Sn*, that our program will have produced once it reaches *l* (but before processing *l*).
Note that, since the structures generated by *Sn* and *S**n*+1 agree in all locations that follow *l*, in reading order, *Sm* is the same given either structure as input.
If *s**n*+1 is `a` (i.e., cup addition), then there must not be any location preceding *l*, in reading order, where a cup can be added to the structure generated by *Sn*. As a result, the subsequence of *Sn* following *Sm* must be all `a` (since an `r` would imply that either there's an empty space before *l*, or that *Sn* is not optimal.)
When we come to process *l*, we'll need to add exactly *n - m* cups before we can add a cup at *l*, hence the resulting sequence will be *Sm*, followed by *n - m* + 1 `a` elements, which equals *S**n*+1 (there won't be any mismatch after this point, hence this is the complete sequence produced.)
Likewise, if *s**n*+1 is `r`, then there must not be any cup at a location preceding *l*, in reading order, in the structure generated by *Sn*. As a result, the subsequence of *Sn* following *Sm* must be all `r`.
When we come to process *l*, we'll need to remove exactly *n - m* cups before we can remove the cup at *l*, hence the resulting sequence will be *Sm*, followed by *n - m* + 1 `r` elements, which again equals *S**n*+1.
In other words, our method produces an optimal sequence for the said input structure, and therefore, by induction, for any input structure.
Note that this doesn't mean that this implementation is the most efficient one.
It's definitely possible, for example, to calculate the number of cups that has to be added, or removed, at each point directly, instead of actually performing these operations.
**Uniqueness**
We can use the optimality of our method to show that optimal sequences are, in fact, unique (that is, that no two distinct optimal sequences generate the same structure.)
We use, again, induction on the size of the optimal generating sequence:
The empty sequence is obviously the unique optimal generating sequence of the empty structure.
Suppose that all optimal generating sequences of length *n* are unique, and consider a structure, Σ, generated by the two optimal sequences *S**n*+1 and *T**n*+1.
Recall that *Sn* and *Tn* are themselves optimal, and therefore, by hypothesis, unique.
Since our method produces optimal sequences, *Sn* and *Tn* can be thought of as generated by our method.
Let *lS* and *lT* be the locations modified by the last operation in *S**n*+1 and *T**n*+1, respectively, and suppose, without loss of generality, that *lS* follows, or equals, *lT* in reading order.
Since the structures generated by *Sn* and *Tn* agree in all locations following *lS*, in reading order, the sequence produced by our method, given either structure as input, once it reaches *lS* (but before processing it), is the same for both; call this sequence *U*.
Since the last action of *S**n*+1 modifies *lS*, if Σ has a cup at *lS* then there must not be any vacancy before *lS*, and if Σ doesn't have a cup at *lS* then there must not be any cup before *lS*, in reading order.
Therefore, the rest of the sequence generating Σ, following *U*, must consist of repeated application of the same instruction, dictated by the presence or absence of a cup at *lS* (or else it wouldn't be optimal).
In other words, *S**n*+1 and *T**n*+1 are equal (they both start with *U*, and end with the said sequence of repeated instructions,) that is, the optimal generating sequence of Σ is unique, and so, by induction, all optimal generating sequences are unique.
] |
[Question]
[
Last month I borrowed a plenty of books from the library. They all were good books, packed with emotions and plot-twists. Unfortunately, at some points I got very angry/sad/disappointed, so I tore some pages out.
Now the library wants to know how many pages I have torn out for each book.
Your goal is to write a program, which takes a sorted, comma-delimited list of numbers as input and prints the minimum and maximum possible page count I could have torn out. Each line represents a book, each number represents a missing page from the book.
Example input:
```
7,8,100,101,222,223
2,3,88,89,90,103,177
2,3,6,7,10,11
1
1,2
```
Example output:
```
4/5
5/6
3/6
1/1
1/2
```
`4/5` means, that I may have torn out either 4 or 5 pages, depending on which side the book's page numbering starts. One could have torn out page 6/7, page 8/9, page 100/101, and page 222/223 (4 pages). Alternatively, one could have torn out page 7/8, page 99/100, page 101/102, page 221/222, and page 223/224 (5 pages).
Remember that a book page always has a front and a back side. Also the page numbering differs from book to book. Some books have even page numbers on the left page; some on the right page. All books are read from left to right.
Shortest code in bytes win. Strict I/O format is **not** required. Your programs must be able to take one or more books as input. Have fun.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
εD>)ÅÈε€θγg}{
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3FYXO83DrYc7zm191LTm3I5zm9Nrq///j44217HQMTQwAGJDHSMjIyA2jtWJNtIx1rGw0LGw1LEESRnrGJqbQ4XNdMyBIjqGhkA@UEtsLAA "05AB1E – Try It Online")
Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for the heads-up on spec changes.
### Explanation
```
εD>)ÅÈε€θγg}{ – Full program.
ε – For each book...
D – Push two copies of it.
> – Increment all the elements of the second copy.
) – Wrap the whole stack into a list.
ÅÈ – Produces the lists of even natural numbers lower or equal to each element.
ε – For each (the modified copies of the book):
€θ – Get the last item of each.
γg – And split into chunks of equal adjacent elements.
} – Close the loop.
{ – Sort the resulting list.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~72~~ ~~56~~ ~~68~~ 67 bytes
```
lambda b:[map(len,map(set,zip(*[[p/2,-p/2]for p in t])))for t in b]
```
[Try it online!](https://tio.run/##LU1LDoMgEN17CnZK80wFk4Im7UUoC001NVEkyqa9PB1IF2/ebybjP@G9Oxnn@zOuwza@Bjb2Zht8tU4Oic8p4Lv46mKMv0rUNOy8H8yzxbFgOefJheRGG7OezmxNYYyChmgagoCUktBaC0aNRAutoTt0qW4hlLLI8Q2KEgjxXxVEhu7JFrYvmD8WF/IblPWjxFwlzeMP "Python 2 – Try It Online")
[Answer]
# JavaScript, ~~104~~ ~~93~~ ~~92~~ ~~85~~ ~~80~~ ~~79~~ 74 bytes
Would be [57 bytes](https://tio.run/##dZCxasMwEIb3PIUJHSR8EZZManuQtg7t0AwZHYGUWA4OqWxsp41b99ndS1IoLfRAB/r@D06ng3213a6tmn7h68JNpZysVJa92Iacpcoj4Pp68VJ59xasXU/OVzBINYReKU4p66p3R@m0q31XHx071ntigkffnPrgvxqD1alHYePvPszCsNY1zvYk5vRz/EUEko03YT7L8wRS4BG@KeIghMATaw0YCIghTSHNILukMfAk@UnuIUEInN8QR7RElCEBju4SdeDpd6oBDYH9Mkvr2W3/rVQmMOHTevXMur6t/L4qB7KlrLHFgy9IHNFwPgbzv0aJDv7Qoa68wTXo9AU) if not for the unnecessary (in my opinion) requirement that each pair of numbers in the output be consistently sorted, or [47 bytes](https://tio.run/##dZCxboMwEIZ3nsKKOtjiYmGjFBjw1qEdmiEjQbITTESUGgROK1r67PRI1aGVasmW7vs/6e58Nq9mOPZN59eurexc57PJVRGBKPmL6ajLlbNvZGc9NTcw5moMnVKCMT4075bNx9YN7cXyS3uimjy67urJf2ci26tHYe/uPvRa89521ngaC/Y5/SISyd7psAiKBFIQEU4UCZBS4o1LCAoJMaQppBlkSxaDSJIffg8JIhBiAQLBBkGGNQj0NqiCSG9ZCZhLfJceZfC99CFXmujwabd95oPvG3dq6pEeGO9M9eAqGkcsXE1k9deo0cFvObeN0zg8m78A) if we only needed to take one book as input.
Input and output are both an array of arrays.
```
a=>a.map(x=>[0,1].map(n=>new Set(x.map(y=>y+n>>1)).size).sort((x,y)=>x-y))
```
* Initially inspired by [Olivier's Java solution](https://codegolf.stackexchange.com/a/154997/58974) and my own (currently deleted) Japt solution.
* 2 bytes saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) (plus another 3 we both spotted at the same time) and 10 bytes *added* thanks to him spotting the broken sorting I'd hoped nobody would notice while that requirement was still under discussion!
---
## Test cases
Test cases are split into individual books for better readability with the last case (which includes the `[1,2]` edge case) serving to illustrate that this solution supports multiple books in the input.
```
f=
a=>a.map(x=>[0,1].map(n=>new Set(x.map(y=>y+n>>1)).size).sort((x,y)=>x-y))
o.innerText=` Input | Output\n${`-`.repeat(31)}|${`-`.repeat(21)}\n`+[[[7,8,100,101,222,223]],[[2,3,88,89,90,103,177]],[[2,3,6,7,10,11]],[[1,3,5,7,9,11,13,15,17,18]],[[1],[1,2],[8,10]]].map(b=>` `+JSON.stringify(b).padEnd(30)+"| "+JSON.stringify(f(b))).join`\n`
```
```
<pre id=o></pre>
```
---
## History
```
//104
a=>a.map(x=>x.map(y=>b.add(y/2|0)&c.add(++y/2|0),b=new Set,c=new Set)&&[b.size,c.size].sort((x,y)=>x-y)))
// 93
a=>a.map(x=>[new Set(x.map(y=>y/2|0)).size,new Set(x.map(y=>++y/2|0)).size].sort((x,y)=>x-y)))
// 92
a=>a.map(x=>[(g=z=>new Set(z).size)(x.map(y=>y/2|0)),g(x.map(y=>++y/2|0))].sort((x,y)=>x-y))
// 85
a=>a.map(x=>[(g=h=>new Set(x.map(h)).size)(y=>y/2|0),g(y=>++y/2|0)].sort((x,y)=>x-y))
// 80
a=>a.map(x=>[(g=n=>new Set(x.map(y=>(y+n)/2|0)).size)(0),g(1)].sort((x,y)=>x-y))
// 79
a=>a.map(x=>[(g=n=>new Set(x.map(y=>y/2+n|0)).size)(0),g(.5)].sort((x,y)=>x-y))
// 76
a=>a.map(x=>[0,.5].map(n=>new Set(x.map(y=>y/2+n|0)).size).sort((x,y)=>x-y))
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes
```
\d+
$*
.+
$&,/$&,
,(?=.*/)
1,
((11)+,)1\1|1+,
1
%O`1+
1+
$.&
```
[Try it online!](https://tio.run/##HYkxCsMwFEN3nSMNdiycyIbYGUqPkAtkSKEdunQoHXt356egJ3jS5/l9ve@tbY@AbkC07jkaoLtd4zB6iHBO8oFem34KhHBZdwVYuti3VlipaTLElJKRkZhZK@vC5TwyVcp/nFnMKR0 "Retina 0.8.2 – Try It Online") Explanation:
```
\d+
$*
```
Convert the page numbers to unary.
```
.+
$&,/$&,
```
Duplicate the list, interposing a `/`.
```
,(?=.*/)
1,
```
Increment the page numbers in one copy of the list.
```
((11)+,)1\1|1+,
1
```
Count the number of pages, but consecutive even and odd numbers only counts as one page.
```
%O`1+
```
Sort the counts into order.
```
1+
$.&
```
Convert the counts back to decimal.
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
import Data.List
p t=sort[length$nub[div(p+o)2|p<-t]|o<-[0,1]]
```
[Try it online!](https://tio.run/##LcyxCsIwFIXh3afI0EHxVpIUTArt5ugbXDJELDbYJJf26tR3ryk4nOX74Yx@eQ/TtG0hUp5Z3Dz7yz0sfCDB/VIIpyG9eKzS54HP8D3SOZ/0Sl3Nbs1djRKUc1v0IfU0h8RV9CQI0YAFJUuVCrTWZY0D1NCAtWBbaPfUgDLmz1cwRUDtdz8 "Haskell – Try It Online")
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 163 bytes
```
import java.util.*;
n->{for(int i=n.length;i-->0;){Set s=new HashSet(),t=new HashSet();for(int p:n[i]){s.add(p/2);t.add(++p/2);}n[i]=new int[]{s.size(),t.size()};}}
```
[Try it online!](https://tio.run/##ZU@xboMwFNzzFW@ExriBSIWUEqnq0qVTuiEGF0ziFGyEH6lS5G@nhhC1UYcn37t7Z90d2Yl5quHyWHxuBlE3qkU4WpJ2KCp6Fy/@cWUncxRKjmLTfVQih7xiWsMbExL6BYBGhpZ9UVJ3NW@fhMQ0S7MtlMkgvW1fqtaxHIhE0orLPR5i4XnbVez2O46gE8m/4JXpg90cl@DtHl/tzaNMReb2mrKicJr7wI1xgsvltJhRnrxTAHunxTcfP5yBiY0ZYht4rjHnPilRQG3LODtshdynGbB2r92pG8DcBpBrhGQmAfqQRMRfrez4JAgCO2tDrmJA1iSKSLQhm/FiTfwwvFUfSGgF4vu/9F9IAjNhE09PSVme8wadMYV74XZnjbymqkPa2NxYSee5bdlZ04Lz5l1d2lwck8UszPAD "Java (OpenJDK 9) – Try It Online")
## Explanations
```
n->{ // Input-output of int[][]
for(int i=n.length;i-->0;){ // Iterate on books
Set s=new HashSet(),t=new HashSet(); // Create two hashsets
for (int p:n[i]) { // Iterate over each page
s.add(p/2); // Add the sheet-of-page of books [ even | odd ] to one set.
t.add(++p/2); // Add the sheet-of-page of books [ odd | even ] to the other set.
}
n[i]=new int[] { // change the input to the number of sheets used.
s.size(),
t.size()
};
}
}
```
Note: since there is no requirement about it, the min and max numbers of pages aren't ordered.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 37 bytes
```
{(≢⍵)≤2:⌽≢∘∪¨⌊⍵(1+⍵)÷2⋄≢∘∪¨⌊⍵(1+⍵)÷2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqjUedix71btV81LnEyOpRz14Qt2PGo45Vh1Y86ukCymgYaoPkD283etTdgke2FmjgoRUa5goWCoYGBkBsqGBkZATExpoaRgrGChYWChaWCpYgGWMFQ3NziKiZgjlQQMHQUFMDhBSMNAE "APL (Dyalog Unicode) – Try It Online")
This can be done for less than half the byte count if the output order of pages doesn't matter:
```
{≢∘∪¨⌊⍵(1+⍵)÷2}
```
### How?
```
{(≢⍵)≤2:⌽≢∘∪¨⌊⍵(1+⍵)÷2⋄≢∘∪¨⌊⍵(1+⍵)÷2}⍝ Prefix dfn
{(≢⍵)≤2: ⍝ If argument length ≤2
÷2 ⍝ Divide by 2
⍵(1+⍵) ⍝ Both the argument and 1+argument
⌊ ⍝ Round down to the nearest integer
∪¨ ⍝ Get the unique values of each
∘ ⍝ And then
≢ ⍝ Get the tally of elements of each
⌽ ⍝ And reverse the result
⋄ ⍝ Else
≢∘∪¨⌊⍵(1+⍵)÷2} ⍝ Same as above, without reverting the result.
```
[Answer]
# [Perl 5](https://www.perl.org/), 95 + 1 (`-a`) = 96 bytes
```
@0=@1=0;map{$i=-1;$F[$i]+1==$F[$i+1]&&$F[$i]%2==$_&&$i++while++$i<@F&&++@{$_}[0]}0,1;say"@0/@1"
```
[Try it online!](https://tio.run/##JYnBCoJAFEX3fsVDJjcv670RmxEbmJW7vkBEXAgNWEoGEeKvN03G5cI95079Y8i9t2QsGypv3bQIZ1IuRVUL1yAbsy3kJkn@bieDawM5xNfVDT2icGdbJQmiXUS71tSstOdy7t6xpaPl2HsFGpgolEFKGZpFEjLQGnQBxe/IgJXa5AlUYGCOQkB@xunpxvvs00t@ICafdl8 "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes
Thanks @MartinEnder for 8 bytes!
```
Sort[Length@*Split/@{#,#+1}~Floor~2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T84v6gk2ic1L70kw0EruCAns0TfoVpZR1nbsLbOLSc/v6jOKFbtv6Y1V0BRZl6Jg1YaUJqLq9pQx6hWh6vaXMdCx9DAAIiBAkZGQGwMEjbSMdaxsNCxsNSxBMkZ6xiam9dycdX@BwA "Wolfram Language (Mathematica) – Try It Online")
### Explanation
In: `{3, 4, 5}`
```
{#,#+1}
```
Take (input) and (input + 1). `{{3, 4, 5}, {4, 5, 6}}`
```
... ~Floor~2
```
For each number from above, take the largest even number less it. `{{2, 4, 4}, {4, 4, 6}}`
```
Length@*Split/@
```
For each list from above, split the list by same elements `{{{2}, {4, 4}}, {{4, 4}, {6}}}`
and take the length of each: `{2, 2}`
```
Sort[ ... ]
```
Sort the output.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~222~~ ~~210~~ ~~204~~ 196 bytes
```
import StdEnv,ArgEnv,Data.Maybe,qualified GenLib as G
Start=tl[let(Just l)='G'.parseString i;?s=sum[1\\n<-[s,s+2..last(sort l)]|isAnyMember[n,n+1]l]in zip2(sort[?0,?1])['/\n']\\i<-:getCommandLine]
```
[Try it online!](https://tio.run/##TZDRSsMwFIbvfYrcdWOndenAdroxhpOhbCDsMs3F6ZqVQJLOJBUmPrsxqwpe/Jx8/wkc@I5KoAm6a3oliEZpgtTnznpy8M2TeYe1ba9jgx6zPV5qAW89KnmSoiFbYXayJujI9ubg0fqlV0wJP3rpnSdqvEy2SXZG68TBW2laIh9Wbul6zWhVmUXKHLhJnmUKnR@561E15p/Src1lL3QtLDNgJpQrLg35kOd8@MRWU1hRPmbJbWUSXlVykd63wj92WqNpdtIIHkJgBZRAp9MYCnmex8x4YDnMoCyhnMP8upoBLYrf@g6K2AClkYdAzr@OJ4WtC2kd0uZiUMtjhOdd2PyHH0nDMzoR9q9/VehPndUDRKHR1jc "Clean – Try It Online")
Full-program requirements absolutely murder Clean's ability to compete.
For those who have been paying attention to my answers in Clean, you'll notice `import qualified`, which is an ugly hack to get around using modules that shouldn't be used together, together - which is only needed here because of another ugly hack to do with `GenLib` depending on `Data.Maybe` instead of `StdMaybe`, which is the result of *yet another* ugly hack in the libraries translated from Haskell's `Data` to get functionality before Clean's own libraries are equally complete.
Takes input via command-line arguments.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
½₍⌈⌊vUvLs
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCveKCjeKMiOKMinZVdkxzIiwiIiwiNyw4LDEwMCwxMDEsMjIyLDIyMyJd)
Append a `\/j` for strict I/O compliance (12 bytes)
```
½ # Halve each
₍⌈⌊ # Floor and ceiling of each, paired
vUvL # Count unique items in each
s # Sort
```
[Answer]
# Perl, 40 bytes
Inludes `+1` for `a`
```
perl -aE 'say/$/*grep${$.}{$_*$`|1}^=1,@F for-1,1' <<< "7 8 100 101 222 223"
```
Output is not ordered.
Assumes positive page numbers (especially no page `0`). Assumes missing pages are only mentioned once. Doesn't care if the input is ordered or not.
Processing only one book per run saves `3` bytes for `37`:
```
perl -aE 'say/$/*grep$z{$_*$`|1}^=1,@F for-1,1' <<< "7 8 100 101 222 223"
```
] |
[Question]
[
Given an integer N >= 2, produce an image showing a Sierpiński knot of degree N.
For example, here are knots of degree 2, 3, 4 and 5:
[![Degree 2](https://i.stack.imgur.com/wURaQt.png "Degree 2 Sierpiński knot")](https://i.stack.imgur.com/wURaQ.png)
[![Degree 3](https://i.stack.imgur.com/34PRpt.png "Degree 3 Sierpiński knot")](https://i.stack.imgur.com/34PRp.png)
[![Degree 4](https://i.stack.imgur.com/A5vjTt.png "Degree 4 Sierpiński knot")](https://i.stack.imgur.com/A5vjT.png)
[![Degree 5](https://i.stack.imgur.com/pxA4mt.png "Degree 5 Sierpiński knot")](https://i.stack.imgur.com/pxA4m.png)
Click on the images to view full size (the higher the degree the larger the image).
# Specification
1. A Sierpiński knot of degree N is drawn using the vertices of a Sierpiński triangle of degree N as guide points. A Sierpiński triangle of degree N is three Sierpiński triangles of degree N-1 arranged into a larger triangle. A Sierpiński triangle of degree 0 is an equilateral triangle.
2. The smallest component triangles have side length 64, giving the Sierpiński triangle on which the knot is based an overall side length of [![64*2^N](https://i.stack.imgur.com/TqBI4.png)](https://i.stack.imgur.com/TqBI4.png)
3. The centre of the outer triangle is positioned at the centre of the image. This does *not* give equal white space at top and bottom.
4. The output is a square image of side length [![ceiling(64*2^N*2/ROOT3)](https://i.stack.imgur.com/OCeQU.png)](https://i.stack.imgur.com/OCeQU.png) where [![ceiling(x)](https://i.stack.imgur.com/SpL4f.png)](https://i.stack.imgur.com/SpL4f.png) is `ceiling(x)`, the smallest integer greater than or equal to x. This is just large enough for the top vertex of the underlying Sierpiński triangle to be contained within the image when the centre of the triangle is at the centre of the image.
5. The single curve must pass over and under itself, strictly alternating. Solutions can choose between under then over, or over then under.
6. The example images show black foreground and white background. You may choose any two easily distinguished colours. Anti-aliasing is permitted but not necessary.
7. There must not be gaps where two arcs meet or where the curve passes over or under itself.
8. Output may be to any raster format image file, or to any vector format image file that includes a correct default display size. If you display directly to screen, this must be in a form that allows scrolling to see the full image when larger than the screen.
### Determining arc centre, radius and thickness
9. The knot is constructed as a series of circular arcs that meet at points where their tangents are parallel, to give a seamless join. These arcs are displayed as annular sectors (arcs with thickness).
10. The centres of these arcs are the vertices of the smallest upside down triangles. Each such vertex is the centre of exactly one arc.
11. Each arc has a radius of [![64*ROOT3/2](https://i.stack.imgur.com/h0H2h.png)](https://i.stack.imgur.com/h0H2h.png)
12. The exception is that the arcs in the three outermost triangles (at the corners of the large triangle) have a centre which is the midpoint of the two adjacent inner vertices, and thus have a radius of [![64*(ROOT3/2-1/2)](https://i.stack.imgur.com/2iyZX.png)](https://i.stack.imgur.com/2iyZX.png)
13. Each arc is represented with a total thickness (difference between inner radius and outer radius) of [![64*(ROOT3/2)/4](https://i.stack.imgur.com/HthEZ.png)](https://i.stack.imgur.com/HthEZ.png) and the black borders of this each have a thickness of [![64*(ROOT3/2)/16](https://i.stack.imgur.com/wYh7u.png)](https://i.stack.imgur.com/wYh7u.png) The curve must have these borders, and not just be a solid strip.
### Units of measure
14. All distances are in pixels (1 is the horizontal or vertical distance between 2 adjacent pixels).
15. The square root of 3 must be accurate to 7 significant figures. That is, your calculations must be equivalent to using a ROOT3 such that `1.7320505 <= ROOT3 < 1.7320515`
# Scoring
The shortest code in bytes wins.
---
*For those wondering, N=0 and N=1 are not included because they correspond to a circle and a trefoil, which don't quite match the pattern that applies for N>=2. I would expect that most approaches to this challenge would need to add special case code for 0 and 1, so I decided to omit them.*
[Answer]
# Ruby, ~~1168~~ 932
Corrected a mistake from last night, more golfing to do after clarifying.
This is (currently) a full program that accepts a number from stdin and outputs an `svg` file to stdout. I chose svg because I knew it was possible to meet all the requirements of the question, but it did have some issues. in particular SVG only supports arcs of circles as part of the `path` object, and does not define them in terms of their centre but rather the two endpoints.
**Code**
```
n=gets.to_i
r=64*w=0.75**0.5
m=1<<n-2
z=128*m/w
a=(s="<path style='fill:none;stroke:black;stroke-width:3.464102' transform='translate(%f %f)'
")%[0,r-r*m*8/3]+"d='M18.11943,-2A#{b=r-6*w-32} #{b} 0 0,0 #{-b} 0#{k='A%f %f 0 0 '%([58*w]*2)}0 0,38.71692
M28.58980,1.968882#{l='A%f %f 0 0 '%([70*w]*2)}0 #{c=r+6*w-32} 0A#{c} #{c} 0 0,0 #{-c} 0#{l}0 -9 44.65423'/>"
p=2
m.times{|i|(i*2+1).times{|j|(p>>j)%8%3==2&&a<<s%[128*(j-i),r*3+r*i*4-r*m*8/3]+
"d='M-55,44.65423#{k}0 11.5,25.11473#{l}1 35.41020,1.968882
M-64,51.48786#{l}0 20.5,30.31089#{k}1 36.82830,13.17993
M-82.17170,-2.408529#{l}1 -11.5,25.11473#{k}0 0,38.71692
M-81.52984 8.35435#{k}1 -20.5,30.31089#{l}0 -9,44.65423
M9,44.65423#{k}0 81.52984,8.35435
M0,51.48786#{l}0 91.17169,13.17993'/>"}
p^=p*4}
puts "<svg xmlns='http://www.w3.org/2000/svg' viewBox='#{-z} #{-z} #{e=2*z+1} #{e}' width='#{e}px' height='#{e}px'>"+
"<g transform='rotate(%d)'>#{a}</g>"*3%[0,120,240]+"</svg>"
```
**Output N=4**
rescaled by Stack exchange. Looks much better as original.
[![enter image description here](https://i.stack.imgur.com/Z6slm.png)](https://i.stack.imgur.com/Z6slm.png)
**Explanation**
At first I considered something like [http://euler.nmt.edu/~jstarret/sierpinski.html](http://euler.nmt.edu/%7Ejstarret/sierpinski.html) where the triangle is broken down into three differently coloured strands, each of which forms a path from one corner to another. The incomplete circles are shown as incomplete hexagons there. inscribing circles inside the hexagons shows that the circle radius should be `sqrt(3)/2` times the sidelength. The strands could be built up recursively as shown, but there is an added complication because the corners need to be rounded and it is difficult to know in which direction to curve, so I did not use this approach.
What I did was the following.
In the image below you can see there are horizontal twists belonging to the N=2 units (in green) arranged in a sierpinski triangle and additional bridging twists (in blue.)
It is common knowledge that the odd numbers on Pascal's triangle form a sierpinski triangle. A sierpinski triangle of binary digits can be obtained in an analogous manner by starting with the number `p=1` and iteratively xoring it with `p<<1`.
I modified this approach, starting at `p=2` and iteratively xoring with `p*4`. This gives a sierpinski triangle alternating with columns of zeros.
Now we can rightshift p and inspect the last three bits using `%8`. If they are `010` we need to draw a green twist belonging to an N=2 unit. if they are `101` we need to draw a blue, bridging twist. To test for both of these numbers together we find the modulo `%3` and if this is 2 we need to draw the twist.
Finally, in additional to the horizontal twists, we make two copies rotated through 120 and 240 degrees to draw the diagonal twists and complete the picture. All that remains is to add the corners.
**Commented code**
```
n=gets.to_i
#r=vertical distance between rows
r=64*w=0.75**0.5
#m=number of rows of horizontal twists
m=1<<n-2
#z=half the size of the viewport
z=128*m/w
#s=SVG common to all paths
s="<path style='fill:none;stroke:black;stroke-width:3.464102' transform='translate(%f %f)'
"
#initialize a with SVG to draw top corner loop. Set k and l to the SVG common to all arcs of 58*w and 70*w radius
a=s%[0,r-r*m*8/3]+
"d='M18.11943,-2A#{b=r-6*w-32} #{b} 0 0,0 #{-b} 0#{k='A%f %f 0 0 '%([58*w]*2)}0 0,38.71692
M28.58980,1.968882#{l='A%f %f 0 0 '%([70*w]*2)}0 #{c=r+6*w-32} 0A#{c} #{c} 0 0,0 #{-c} 0#{l}0 -9 44.65423'/>"
#p is the pattern variable, top row of twists has one twist so set to binary 00000010
p=2
#loop vertically and horizontally
m.times{|i|
(i*2+1).times{|j|
#leftshift p. if 3 digits inspected are 010 or 101
(p>>j)%8%3==2&&
#append to a, the common parts of a path...
a<<s%[128*(j-i),r*3+r*i*4-r*m*8/3]+
#...and the SVG for the front strand and left and right parts of the back strand (each strand has 2 borders)
"d='M-55,44.65423#{k}0 11.5,25.11473#{l}1 35.41020,1.968882
M-64,51.48786#{l}0 20.5,30.31089#{k}1 36.82830,13.17993
M-82.17170,-2.408529#{l}1 -11.5,25.11473#{k}0 0,38.71692
M-81.52984 8.35435#{k}1 -20.5,30.31089#{l}0 -9,44.65423
M9,44.65423#{k}0 81.52984,8.35435
M0,51.48786#{l}0 91.17169,13.17993'/>"}
#modify the pattern by xoring with 4 times itself for the next row
p^=p*4}
#output complete SVG of correct size with three copies of the finished pattern rotated through 0,120,240 degrees.
puts "<svg xmlns='http://www.w3.org/2000/svg' viewBox='#{-z} #{-z} #{e=2*z+1} #{e}' width='#{e}px' height='#{e}px'>"+
"<g transform='rotate(%d)'>#{a}</g>"*3%[0,120,240]+"</svg>"
```
[![enter image description here](https://i.stack.imgur.com/6Wdl7.png)](https://i.stack.imgur.com/6Wdl7.png)
] |
[Question]
[
## Task
Implement a program in minimum bytes of source or binary code that does voice recognition of a voice sample (me saying "yes", "yeah" or "no" in voice or in whisper, plainly or quirkily) based on training samples with maximum accuracy.
The program should read `train/yes0.wav`, `train/no0.wav`, `train/yes1.wav` and so on (there are 400 yeses and 400 noes in training dataset), then start reading `inputs/0.wav`, `inputs/1.wav` until it fails to find the file, analysing it and outputting "yes" or "no" (or other word for intermediate answer).
If you want, you may pre-train the program instead of reading `train/`, but the resulting data table counts towards the score (and beware of overfitting to training samples - they don't overlap with examination ones). Better to include the program used to produce the data table as an addendum in this case.
All sample files are little endian 16-bit stereo WAV files, just from laptop mic, without filtering/noise reduction.
## Limits
Forbidden features:
* Using network;
* Trying to reach the answers file `inputs/key`;
* Subverting the `runner` program that calculates accuracy;
* Using existing recognition libraries. Linking to FFT implementation not allowed: only external math functions taking constant amount of information (like `sin` or `atan2`) are allowed; If you want FFT, just add it's implementation to your program source code (it can be multilingual if needed).
Resource limits:
* The program should not take more than 30 minutes of CPU time on my i5 laptop. If it takes more, only output produced in the first 30 minutes are counted and eveything else is assumed a half-match;
* Memory limit: 1GB (including any temporary files);
## Tools
The `tools/runner` program automatically runs your solution and calculates the accuracy.
```
$ tools/runner solutions/example train train/key
Accuracy: 548 ‰
```
It can examine the program using training data or using actual exam data. I'm going to try submitted answers on examination dataset and publish results (accuracy percentage) until I make the dataset public.
## Scoring
There are 5 classes of solution depending on accuracy:
* All samples guessed correctly: Class 0;
* Accuracy 950-999: Class 1;
* Accuracy 835-950: Class 2;
* Accuracy 720-834: Class 3;
* Accuracy 615-719: Class 4;
Inside each class, the score is number of bytes the solution takes.
Accepted answer: smallest solution in the best nonempty class.
## Links
* Github project with tools: <https://github.com/vi/codegolf-jein>
* Training dataset: <http://vi-server.org/pub/codegolf-jein-train.tar.xz>
* Examination dataset is kept private so far, there are checksums (HMAC) available in the Github repository.
All samples should be considered CC-0 (Public Domain), scripts and programs should be considered MIT.
## Example solution
It provides very poor quality of recognition, just shows how to read files and output answers
```
#define _BSD_SOURCE
#include <stdio.h>
#include <assert.h>
#include <endian.h>
#define Nvols 30
#define BASS_WINDOW 60
#define MID_WINDOW 4
struct training_info {
double bass_volumes[Nvols];
double mid_volumes[Nvols];
double treble_volumes[Nvols];
int n;
};
struct training_info yes;
struct training_info no;
static int __attribute__((const)) mod(int n, int d) {
int m = n % d;
if (m < 0) m+=d;
return m;
}
// harccoded to 2 channel s16le
int get_file_info(const char* name, struct training_info *inf) {
FILE* in = fopen(name, "rb");
if (!in) return -1;
setvbuf(in, NULL, _IOFBF, 65536);
inf->n = 1;
fseek(in, 0, SEEK_END);
long filesize = ftell(in);
fseek(in, 128, SEEK_SET);
filesize -= 128; // exclude header and some initial samples
int nsamples = filesize / 4;
double bass_a=0, mid_a=0;
const int HISTSIZE = 101;
double xhistory[HISTSIZE];
int histpointer=0;
int histsize = 0;
//FILE* out = fopen("debug.raw", "wb");
int i;
for (i=0; i<Nvols; ++i) {
int j;
double total_vol = 0;
double bass_vol = 0;
double mid_vol = 0;
double treble_vol = 0;
for (j=0; j<nsamples / Nvols; ++j) {
signed short int l, r; // a sample
if(fread(&l, 2, 1, in)!=1) break;
if(fread(&r, 2, 1, in)!=1) break;
double x = 1/65536.0 * ( le16toh(l) + le16toh(r) );
bass_a += x;
mid_a += x;
if (histsize == HISTSIZE-1) bass_a -= xhistory[mod(histpointer-BASS_WINDOW,HISTSIZE)];
if (histsize == HISTSIZE-1) mid_a -= xhistory[mod(histpointer-MID_WINDOW ,HISTSIZE)];
double bass = bass_a / BASS_WINDOW;
double mid = mid_a / MID_WINDOW - bass;
double treble = x - mid_a/MID_WINDOW;
xhistory[histpointer++] = x;
if(histpointer>=HISTSIZE) histpointer=0;
if(histsize < HISTSIZE-1) ++histsize;
total_vol += bass*bass + mid*mid + treble*treble;
bass_vol += bass*bass;
mid_vol += mid*mid;
treble_vol += treble*treble;
/*
signed short int y;
y = 65536 * bass;
y = htole16(y);
fwrite(&y, 2, 1, out);
fwrite(&y, 2, 1, out);
*/
}
inf->bass_volumes[i] = bass_vol / total_vol;
inf->mid_volumes[i] = mid_vol / total_vol;
inf->treble_volumes[i] = treble_vol / total_vol;
//fprintf(stderr, "%lf %lf %lf %s\n", inf->bass_volumes[i], inf->mid_volumes[i], inf->treble_volumes[i], name);
}
fclose(in);
return 0;
}
static void zerotrdata(struct training_info *inf) {
int i;
inf->n = 0;
for (i=0; i<Nvols; ++i) {
inf->bass_volumes[i] = 0;
inf->mid_volumes[i] = 0;
inf->treble_volumes[i] = 0;
}
}
static void train1(const char* prefix, struct training_info *inf)
{
char buf[50];
int i;
for(i=0;; ++i) {
sprintf(buf, "%s%d.wav", prefix, i);
struct training_info ti;
if(get_file_info(buf, &ti)) break;
++inf->n;
int j;
for (j=0; j<Nvols; ++j) {
inf->bass_volumes[j] += ti.bass_volumes[j];
inf->mid_volumes[j] += ti.mid_volumes[j];
inf->treble_volumes[j] += ti.treble_volumes[j];
}
}
int j;
for (j=0; j<Nvols; ++j) {
inf->bass_volumes[j] /= inf->n;
inf->mid_volumes[j] /= inf->n;
inf->treble_volumes[j] /= inf->n;
}
}
static void print_part(struct training_info *inf, FILE* f) {
fprintf(f, "%d\n", inf->n);
int j;
for (j=0; j<Nvols; ++j) {
fprintf(f, "%lf %lf %lf\n", inf->bass_volumes[j], inf->mid_volumes[j], inf->treble_volumes[j]);
}
}
static void train() {
zerotrdata(&yes);
zerotrdata(&no);
fprintf(stderr, "Training...\n");
train1("train/yes", &yes);
train1("train/no", &no);
fprintf(stderr, "Training completed.\n");
//print_part(&yes, stderr);
//print_part(&no, stderr);
int j;
for (j=0; j<Nvols; ++j) {
if (yes.bass_volumes[j] > no.bass_volumes[j]) { yes.bass_volumes[j] = 1; no.bass_volumes[j] = 0; }
if (yes.mid_volumes[j] > no.mid_volumes[j]) { yes.mid_volumes[j] = 1; no.mid_volumes[j] = 0; }
if (yes.treble_volumes[j] > no.treble_volumes[j]) { yes.treble_volumes[j] = 1; no.treble_volumes[j] = 0; }
}
}
double delta(struct training_info *t1, struct training_info *t2) {
int j;
double d = 0;
for (j=0; j<Nvols; ++j) {
double rb = t1->bass_volumes[j] - t2->bass_volumes[j];
double rm = t1->mid_volumes[j] - t2->mid_volumes[j];
double rt = t1->treble_volumes[j] - t2->treble_volumes[j];
d += rb*rb + rm*rm + rt*rt;
}
return d;
}
int main(int argc, char* argv[])
{
(void)argc; (void)argv;
train();
int i;
int yes_count = 0;
int no_count = 0;
for (i=0;; ++i) {
char buf[60];
sprintf(buf, "inputs/%d.wav", i);
struct training_info ti;
if(get_file_info(buf, &ti)) break;
double dyes = delta(&yes, &ti);
double dno = delta(&no, &ti);
//printf("%lf %lf %s ", dyes, dno, buf);
if (dyes > dno) {
printf("no\n");
++no_count;
} else {
printf("yes\n");
++yes_count;
}
}
fprintf(stderr, "yeses: %d noes: %d\n", yes_count, no_count);
}
```
[Answer]
# C++11 (gcc; ~~1639~~ ~~1625~~ 1635 bytes, Class 1, score=983, 960)
Let's get it started. It's probably the longest code I've ever shortened...
```
#include <bits/stdc++.h>
#define $ complex<double>
#define C vector<$>
#define I int
#define D double
#define P pair<D,I>
#define Q pair<D,D>
#define E vector<D>
#define V vector<P>
#define W vector<Q>
#define S char*
#define Z(x)if(fread(&x,2,1,y)!=1)break;
#define B push_back
#define F(i,f,t)for(I i=f;i<t;i++)
#define _ return
#define J first
#define L second
const I K=75,O=16384;using namespace std;C R(C&i,I s,I o=0,I d=1){if(!s)_ C(1,i[o]);C l=R(i,s/2,o,d*2),h=R(i,s/2,o+d,d*2);C r(s*2);$ b=exp($(0,-M_PI/s)),f=1;F(k,0,s){r[k]=l[k]+f*h[k];r[k+s]=l[k]-f*h[k];f*=b;}_ r;}C T(C&i){_ R(i,i.size()/2);}char b[O];E U(S m){FILE*y;if(!(y=fopen(m,"r")))_ E();setvbuf(y,b,0,O);fseek(y,0,2);I z=ftell(y)/4-32;fseek(y,128,0);C p;F(i,0,z){short l,r;Z(l);Z(r);if(i&1)p.B($(0.5/O*le16toh(l),0));}p.resize(O);E h(O),n(O);p=T(p);F(j,0,O)h[j]=norm(p[j])/O;F(i,1,O-1)n[i]=(h[i-1]+h[i+1]+h[i]*8)/10;fclose(y);_ n;}W G(E&d){V p;F(i,3,O/2-3)if(d[i]==*max_element(d.begin()+i-3,d.begin()+i+4))p.B({d[i],i});sort(p.begin(),p.end(),greater<P>());W r;F(i,3,K+3)r.B({D(p[i].L)/O*22050,log(p[i].J)+10});D s=0;F(i,0,K)s+=r[i].L;F(i,0,K)r[i].L/=s;_ r;}char m[O];I X(S p,W&r){E t(O),h(t);I f=0;while(1){sprintf(m,"%s%d.wav",p,f++);h=U(m);if(!h.size())break;F(j,0,O)t[j]+=h[j];}F(j,0,O)t[j]/=f;r=G(t);}D Y(W&a,W&b){D r=0;F(i,0,K){D d=b[i].L;F(j,0,K)if(abs((b[i].J-a[j].J)/b[i].J)<0.015)d=min(d,abs(b[i].L-a[j].L));r+=d;}_ r;}I H(S p,W&y,W&n){I f=0;while(1){sprintf(m,"%s%d.wav",p,f++);E h=U(m);if(!h.size())break;W p=G(h);D q=Y(p,y),r=Y(p,n);printf(abs(q-r)<=0.01?"?\n":q<r?"yes\n":"no\n");}}I main(){W y,n;X("train/yes",y);X("train/no",n);H("inputs/",y,n);}
```
"Ungolfed" (although it's hard to call an over 1.5K source code golfed):
```
#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <vector>
#include <math.h>
#include <complex>
#include <endian.h>
#include <functional>
using namespace std;
typedef complex<double> CD;
vector<CD> run_fft(vector<CD>& input, int offset, int size, int dist){
if(size == 1){
return vector<CD>(1, input[offset]);
}
vector<CD> partLow = run_fft(input, offset, size/2, dist*2),
partHi = run_fft(input, offset+dist, size/2, dist*2);
vector<CD> result(size);
CD factorBase = exp(CD(0, (inv?2:-2)*M_PI/size)), factor = 1;
for(int k = 0; k < size/2; k++){
result[k] = partLow[k] + factor*partHi[k];
result[k+size/2] = partLow[k] - factor*partHi[k];
factor *= factorBase;
}
return result;
}
vector<CD> fft(vector<CD>& input){
int N = input.size();
return run_fft(input, 0, N, 1);
}
const int MAX_BUF = 65536;
const int PWR_TWO = 16384;
const int NUM_CHECK = 75;
int sampling;
char buf[MAX_BUF];
vector<double> read_data(char* filenam){
FILE* fp = fopen(filenam, "r");
if(!fp)
return vector<double>();
setvbuf(fp, buf, _IOFBF, MAX_BUF);
fseek(fp, 0, SEEK_END);
int filesiz = ftell(fp);
fseek(fp, 128, SEEK_SET);
filesiz -= 128;
int insamp = filesiz / 4;
int freqsamp = 2,
act_mod = 0;
sampling = 44100 / freqsamp;
int inputSize;
vector<CD> input;
for(int i = 0; i < insamp; i++){
signed short int l, r;
if(fread(&l, 2, 1, fp) != 1) break;
if(fread(&r, 2, 1, fp) != 1) break;
double act = 1/32768.0 * (le16toh(l));
if((++act_mod) == freqsamp){
inputSize++;
input.push_back(CD(act,0));
act_mod = 0;
}
}
inputSize = input.size();
//printf("%s\n", filenam);
int numParts = (inputSize+PWR_TWO-1)/PWR_TWO;
double partDelta = (double)inputSize / numParts, actDelta = 0;
vector<CD> ndata(PWR_TWO);
for(int i = 0; i < numParts; i++){
vector<CD> partInput(PWR_TWO);
int from = floor(actDelta),
to = floor(actDelta)+PWR_TWO;
for(int j = from; j < to; j++)
partInput[j-from] = input[j];
vector<CD> partData = fft(partInput);
for(int j = 0; j < PWR_TWO; j++)
ndata[j] += partData[j]*(1.0/numParts);
}
vector<double> height(PWR_TWO);
for(int i = 0; i < PWR_TWO; i++)
height[i] = norm(ndata[i])/PWR_TWO;
vector<double> nheight(height);
nheight[0] = (height[0]*0.8 + height[1]*0.1)/0.9;
nheight[PWR_TWO-1] = (height[PWR_TWO]*0.8 + height[PWR_TWO-1]*0.1)/0.9;
for(int i = 1; i < PWR_TWO-1; i++)
nheight[i] = height[i-1]*0.1 + height[i]*0.8 + height[i+1]*0.1;
fclose(fp);
return nheight;
}
vector< pair<double,double> > get_highest_peaks(vector<double>& freqData){
vector< pair<double,int> > peaks;
for(int i = 3; i < PWR_TWO/2-3; i++){
if(freqData[i] == *max_element(freqData.begin()+i-3, freqData.begin()+i+4)){
peaks.push_back(make_pair(freqData[i], i));
}
}
sort(peaks.begin(), peaks.end(), greater< pair<double,int> >());
vector< pair<double,double> > res;
for(int i = 3; i < NUM_CHECK+3; i++){
res.push_back(make_pair((double)(peaks[i].second)/PWR_TWO*sampling, log(peaks[i].first)+10));
}
double sum_res = 0;
for(int i = 0; i < NUM_CHECK; i++)
sum_res += res[i].second;
for(int i = 0; i < NUM_CHECK; i++)
res[i].second /= sum_res;
/*for(int i = 0; i < NUM_CHECK; i++)
printf("%12lf %12lf\n", res[i].first, res[i].second);
printf("\n");*/
return res;
}
void train(char* dir, const char* type, vector< pair<double,double> >& res){
vector<double> result(PWR_TWO), height(PWR_TWO);
int numFile = 0;
while(true){
char filenam[256];
snprintf(filenam, 255, "%s/%s%d.wav", dir, type, numFile);
height = read_data(filenam);
if(height.size() == 0)
break;
for(int j = 0; j < PWR_TWO; j++)
result[j] += height[j];
numFile++;
}
fprintf(stderr, "trained %s on %d files\n", type, numFile);
for(int j = 0; j < PWR_TWO; j++)
result[j] /= numFile;
res = get_highest_peaks(result);
}
double dist_ab(vector< pair<double,double> >& A, vector< pair<double,double> >& B){
double result = 0;
for(int i = 0; i < NUM_CHECK; i++){
double add = B[i].second;
for(int j = 0; j < NUM_CHECK; j++){
double dist = (B[i].first-A[j].first)/B[i].first;
if(abs(dist) < 0.015)
add = min(add, abs(B[i].second - A[j].second));
}
result += add;
}
return result;
}
void trial(char* dir, const char* pref, vector< pair<double,double> >& yes,
vector< pair<double,double> >& no){
int numFile = 0;
int numYes = 0, numDunno = 0, numNo = 0;
while(true){
char filenam[256];
snprintf(filenam, 255, "%s/%s%d.wav", dir, pref, numFile);
vector<double> height = read_data(filenam);
if(height.size() == 0)
break;
vector< pair<double,double> > peaks = get_highest_peaks(height);
double distYes = dist_ab(peaks, yes),
distNo = dist_ab(peaks, no);
if(abs(distYes-distNo) <= 0.01){
printf("dunno\n");
numDunno++;
} else if(distYes < distNo){
printf("yes\n");
numYes++;
} else {
printf("no\n");
numNo++;
}
//printf(" (%lf %lf)\n", distYes, distNo);
numFile++;
}
}
int main(int argc, char** argv){
vector< pair<double,double> > yes, no;
train("train", "yes", yes);
train("train", "no", no);
trial("inputs", "", yes, no);
}
```
I have no freaking idea if it will work correctly on real data set (I bet it won't, but I must have a try).
How it works:
1. Take N=214 samples from left channel, each in equal time span. Normalize them so that min value=0 and max value=1.
2. Process them using FFT. Now we switched from time domain to frequency domain. We might say that 0th cell of resulting array is 0Hz equivalent and 213-1st cell is 22050Hz equivalent (that is because I took every other sample from L channel, so my sampling is 22050Hz instead of WAV's frequency, 44100Hz).
3. Find the mean of all such signals - call it "mean frequency distribution". Find K highest peaks in such distribution (here K=75), omitting first few (probably noise) and find their strength. I used `log(mean distribution)+10` and then normalized so that the sum of the biggest peaks was 1.
4. We have two "peak distributions" - one for Yes, second for No. If we have a WAV to test, we transform it in the same way as before (steps 1, 2, 3) and get distribution D. Then we have to check which distribution (Y/N) D is more similar to. I used the following approach: for each peak in Y/N, try to find it in D. If we find it (approximately), the score for this peak is absolute difference between Y/N's and D's strength; in opposite case, it's Y/N's strength (we assume it's always positive). Better (smaller) score wins. If the results are very close (I used 0.01 absolute difference), output `dunno`.
As I said, probably on final tests it will be classified as "even worse than random". Of course, I hope it won't :D
**Edit:** fixed bug (forgot to close the files).
] |
[Question]
[
Bernd is a high school student who has some problems in chemistry. In class he has to design chemical equations for some experiments they are doing, such as the combustion of heptane `C7H16`:
>
> C7H16 + 11O2 → 7CO2 + 8H2O
>
>
>
Since mathematics isn't exactly Bernd's strongest subject, he often has a hard time finding the exact ratios between the pro- and educts of the reaction. Since you are Bernd's tutor, it is your job to help him! Write a program, that calculates the amount of each substance needed to get a valid chemical equation.
## Input
The input is a chemical equation without amounts. In order to make this possible in pure ASCII, we write any subscriptions as ordinary numbers. Element names always start with a capital letter and may be followed by a minuscule. The molecules are separated with `+` signs, an ASCII-art arrow `->` is inserted between both sides of the equation:
```
Al+Fe2O4->Fe+Al2O3
```
The input is terminated with a newline and won't contain any spaces. If the input is invalid, your program may do whatever you like.
You may assume, that the input is never longer than `1024` characters. Your program may either read the input from standard input, from the first argument or in an implementation defined way at runtime if neither is possible.
## Output
The output of your program is the input equation augmented with extra numbers. The number of atoms for each element must be the same on both sides of the arrow. For the example above, a valid output is:
```
2Al+Fe2O3->2Fe+Al2O3
```
If the number for a molecule is `1`, drop it. A number must always be a positive integer. Your program must yield numbers such that their sum is minimal. For instance, the following is illegal:
```
40Al+20Fe2O3->40Fe+20Al2O3
```
If there is no solution, print
```
Nope!
```
instead. A sample input that has no solution is
```
Pb->Au
```
# Testcases
Input->Output
```
C7H16+O2->CO2+H2O
C7H16+11O2->7CO2+8H2O
Al+Fe2O3->Fe+Al2O3
2Al+Fe2O3->2Fe+Al2O3
Pb->Au
Nope!
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
Your program must terminate in reasonable time for all reasonable inputs
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 442 bytes
```
u,t[99];char*s,*m[99];c,v[99][99];i,j,n;
b(k){if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j];else for(t[k]=0;n&&t[k]++<30;)b(k-1);}
main(int r,char**a){for(s=m[0]=a[1];*s;){if(*s==45)r=0,s++;if(*s<65)m[++c]=++s;j=*s++;if(*s>96)j=*s+++j<<8;for(i=0,t[u]=j;t[i]-j;i++);u+=i==u;for(n=0;*s>>4==3;)n=n*10+*s++-48;n+=!n;v[c][i]=r?n:-n;}b(c);for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;putchar(10);}
```
[Try it online!](https://tio.run/##PVDLbsIwEPwVQCqKvYnk8Cqw2XDgwql8QORDcKG1aQyKEy6Ib0/t0HKxd8ee3ZlRyZdSXdfGTbFaSVTfZc1dzKtnF9/C3dc6NrHFQ3Rmd32Kzplgp0sdWTIkcGjHY5O1aAB6VHtMZ6RQe8ACNYWW/OaPwkg8/rjjIPxqirP0Hz03VADZVCDzC5KU4aMqtY20bQZ13GviJbsHkqOqEJLKIpXIHfZiuCOazVlNInYA2CPZYs6qAkBJAnBoiL@e8tWCPXswWbbEP8U@gVaSwSA2Mb10bIE0UYtPq8JvzPMZ0RSZJctTAWFKMluiNzm0eCuU9GyqN3adWHwcIsVe4x3Zzejjcj0OR@t/@de2Ce6iMIYxb6Py9JCH3y7zdHOtfQSnaPT2OfLydJJKthYvVip8UF3Xbd936QL2kyTf7iewm@x/AQ "C (gcc) – Try It Online")
Ungolfed version
```
// element use table, then once parsed reused as molecule weights
u,t[99];
// molecules
char*s,*m[99]; // name and following separator
c,v[99][99]; // count-1, element vector
i,j,n;
// brute force solver, n==0 upon solution - assume at most 30 of each molecule
b(k){
if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j]; // check if sums to zero
else for(t[k]=0;n&&t[k]++<30;)b(k-1); // loop through all combos of weights
}
main(int r,char**a){
// parse
for(s=m[0]=a[1];*s;){
// parse separator, advance next molecule
if(*s==45)r=0,s++;
if(*s<65)m[++c]=++s;
// parse element
j=*s++;
if(*s>96)j=*s+++j<<8;
// lookup element index
for(i=0,t[u]=j;t[i]-j;i++);
u+=i==u;
// parse amount
for(n=0;*s>>4==3;)n=n*10+*s++-48;
n+=!n;
// store element count in molecule vector, flip sign for other side of '->'
v[c][i]=r?n:-n;
}
// solve
b(c);
// output
for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;
putchar(10);
}
```
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 510 bytes
I employed the augmented chemical composition matrix approach described in
L.R.Thorne, An innovative approach to balancing chemical - reaction equations : a simplified matrix - inverse technique for determining the matrix null space. *Chem.Educator*, 2010, 15, 304 - 308.
One slight tweak was added: I divided the transpose of the null-space vector by the greatest common divisor of the elements to ensure integer values in any solutions. My implementation does not yet handle cases where there is more than one solution to balancing the equation.
```
b@t_ :=Quiet@Check[Module[{s = StringSplit[t, "+" | "->"], g = StringCases, k = Length,
e, v, f, z, r},
e = Union@Flatten[g[#, _?UpperCaseQ ~~ ___?LowerCaseQ] & /@ s];v = k@e;
s_~f~e_ := If[g[s, e] == {}, 0, If[(r = g[s, e ~~ p__?DigitQ :> p]) == {}, 1,
r /. {{x_} :> ToExpression@x}]];z = k@s - v;
r = #/(GCD @@ #) &[Inverse[Join[SparseArray[{{i_, j_} :> f[s[[j]], e[[i]]]}, k /@ {e, s}],
Table[Join[ConstantArray[0, {z, v}][[i]], #[[i]]], {i, k[#]}]]][[All, -1]] &
[IdentityMatrix@z]];
Row@Flatten[ReplacePart[Riffle[Partition[Riffle[Abs@r, s], 2], " + "],2 Count[r,_?Negative]->" -> "]]],"Nope!"]
```
[Try it online!](https://tio.run/##PVJdb@IwEHzPr9gLUtUKcxw83ElFQFB6d6VqS4H2ybIiQzfBJXUi26SUXPjr3AbaPlhazaxnZz9epVvhq3RqKQ@HReAiuOxPNwpdEK5wueZ32fMmRV5a6MPcGaWTeZ4qxx0Dv@nDP/BbA18wSL74UFq0DNYE3KJO3IqBB4AMCgYxgx0DUzEPiX7SKtPBn1Q6h5onvMEgGj7lOZpaYwr7PURRNLzN3j4QAWfQDsCKXkHf1wH2PBvt4z3WrmEckwZVRgH9PpQVgx@sBs8NJZ@YWjInySuVKDeFywHk4uIzu3M0Cgba36Est1FV84/Z721u0Nra6rYSorc7lrbQgqLn1dKN9vnf8AqCABoXcMbHukBjkd9kSvN5LikeGSPfeVmqiMHLSTfmlvMXQZNDzpUQoqpHRs2VNClbEe49ykX6IRNm2jqp3UmI2ippjEUljl8ZNE4SBCtS4Q1BPokbpSmDVkfQ2OrG@PgZtVPu/U7SorbBjprxZtnb1wZmmKdyiQ/SOD5TcUzV61g56v0TGC1sYMghFevS86EJtP4uhNlGO25YNLzHhM6pQEGHAa0B0eTMv89y/OaLwwOdiOML7oe/rjs/m5NuaxBOus3r7oTyDof/ "Wolfram Language (Mathematica) – Try It Online")
**Analysis**
It works by setting up the following chemical composition table, consisting of chemical species by elements, to which an addition nullity vector is added (becoming the augmented chemical composition table:
![chemical composition table](https://i.stack.imgur.com/pjLf6.png)
The inner cells are removed as a matrix and inverted, yielding.
![inversion](https://i.stack.imgur.com/M6Mqx.png)
The right-most column is extracted, yielding:
>
> {-(1/8), -(11/8), 7/8, 1}
>
>
>
Each element in the vector is divided by the gcd of the elements (1/8), giving:
>
> {-1, -11, 7, 8}
>
>
>
where the negative values will be placed on the left side of the arrow.
The absolute values of these are the numbers needed to balance the original equation:
![solution](https://i.stack.imgur.com/psbPN.png)
[Answer]
# [Python 2](https://docs.python.org/2/), 879 bytes
```
import sys,re
from sympy.solvers import solve
from sympy import Symbol
from fractions import gcd
from collections import defaultdict
Ls=list('abcdefghijklmnopqrstuvwxyz')
eq=sys.argv[1]
Ss,Os,Es,a,i=defaultdict(list),Ls[:],[],1,1
for p in eq.split('->'):
for k in p.split('+'):
c = [Ls.pop(0), 1]
for e,m in re.findall('([A-Z][a-z]?)([0-9]*)',k):
m=1 if m=='' else int(m)
a*=m
d=[c[0],c[1]*m*i]
Ss[e][:0],Es[:0]=[d],[[e,d]]
i=-1
Ys=dict((s,eval('Symbol("'+s+'")')) for s in Os if s not in Ls)
Qs=[eval('+'.join('%d*%s'%(c[1],c[0]) for c in Ss[s]),{},Ys) for s in Ss]+[Ys['a']-a]
k=solve(Qs,*Ys)
if k:
N=[k[Ys[s]] for s in sorted(Ys)]
g=N[0]
for a1, a2 in zip(N[0::2],N[1::2]):g=gcd(g,a2)
N=[i/g for i in N]
pM=lambda c: str(c) if c!=1 else ''
print '->'.join('+'.join(pM(N.pop(0))+str(t) for t in p.split('+')) for p in eq.split('->'))
else:print 'Nope!'
```
[Try it online!](https://tio.run/##bVLBbtswDL37K9QChaRYzmofNsyAOgxFgR7SBEVOnaCDaiuuGttyTTdbWuzbM8putm7YiTbfe@SjyG4/PPg2Oxxc0/l@ILAH0dto0/sGv5tuPwdf72wP5EgIv@/wY369b@59PQGb3hSD8@1vUVWUE1L4urZ/Y6XdmOd6KF0xRNECZO1gYNTcFwhUD@5xWzet7556GJ5333/sXyiP7JNEn3PTVzuV6mgNYgXiCoQRTr4rx0IpLhagci2UFqlIo43vSUdcS@zTHLraYavkgvI8IgHZBqQ7AvGYJwWRRC1g3vmOnXNBsCMZ2VY0gd/b@ca1palrRpn6mnzTyiQv@gtn6jz5rGeciu1YiDQyJW6DQVJKbA0W5QNreMDMTDYhllIV6lyLAiebNTMXmpE1KKtVjukrCEGqEidSVpQacSeTNLoDOc7MQNidQSvTQtgpjSGmp5xyPpqGYHkFwQeQ1g/hdwE8ugWpJmFM54/etYyelbMzoGcsWBHB1FShCBJ0BJqL15/iDt4VXoOO1R0oaqhOjI62crwXdgtihsQIu27xKZZSbQMNtP6jBbwGWzKk4UyVXGLDaSsmFcRkgfLiOob5PM@0WKo0RJ5XEs@LVcJkfKzsPlSjzAXFEmt0N7I2zX1pSJETGHpW8DB@cYLrGLdAKZJ63AUJx/A2/fEZuhu2fNs9j4N6mOYd/r2VKf2f48KDxS75W4el7@wJPRwOl5@u04/xKksuLldZfJ2tfgE "Python 2 – Try It Online")
Could be much less than 880, but my eyes are killing me already...
[Answer]
# [Python 2](https://docs.python.org/2/), 640 bytes
previous byte counts: 794, 776, 774, 765, 759, 747, 735, 734, 720, 683, 658, 655, 654, 653, 651, 640
The second indentation level is only a tab, the third is a tab then a space.
To be honest, this is jadkik94's answer, but so many bytes were shaved, I had to do it. Tell me if I can shave any bytes off!
```
from sympy import*
import sys,re
from sympy.solvers import*
from collections import*
P=str.split
L=map(chr,range(97,123))
q=sys.argv[1]
S,O,a,i,u,v=defaultdict(list),L[:],1,1,'+','->'
w=u.join
for p in P(q,v):
for k in P(p,u):
c=L.pop(0)
for e,m in re.findall('([A-Z][a-z]*)(\d*)',k):
m=int(m or 1)
a*=m
S[e][:0]=[c,m*i],
i=-1
Y=dict((s,Symbol(s))for s in set(O)-set(L))
Q=[eval(w('%d*%s'%(c[1],c[0])for c in S[s]),{},Y)for s in S]+[Y['a']-a]
k=solve(Q,*Y)
if k:
N=[k[Y[s]]for s in sorted(Y)]
g=gcd(N[:1]+N[1::2])
print v.join(w((lambda c:str(c)*(c!=1))(N.pop(0)/g)+str(t)for t in P(p,u))for p in P(q,v))
else:print'Nope!'
```
[Try it online!](https://tio.run/##XVHPb9sgGL3zV9BDBNjYiz1p1SxRaeqlhyhplVPGOFBMUhZsU0NcZVP/9gzcaZEmDp94732/3ufO4WXo68tlPw4d9OfOnaHp3DCGDHzECHo6anAVlH6wkx79P@FMqcFarYIZ@ivxyHwYS@@sCWDFOumwehnpKPuDxl9vaVV/JgS8stihlONh4pUAW7qhkhp6ohNr9V6ebGiNCtgaHwhd8UbQKj6UI4qKOwTe2Kn8OZge7IcROmh6@Ihf6UQaABNy/EAcPSUEKrYq3eDwksRP4jXtkmLU5d70rbQWI8y/Fd8Fl8UvkRH8o80Iosc5G3bM9AF3MCZWqQKUGetS3HIteLMUjCvaZUZQAA0rKrBj8/DY0@25ex4s9oSktj419TrgDSlSWEUfnhjXk7T4DaNFmy08WmAVHaGKL8WcpFLSlntB6O93ursW2oqc7ziSSBRSgCOb74OfaLYjwOzhMc6@ZvwYNV6Ia/t4It3iHREAHthBtXjNm0rka141TS3ifm6M68Jp9jeOha3snlsJVROvihXJsLphFSF4/dfTTweSJyrMo4Wr9eS/4xCgrdfNXB@tB6dv0OVyub99qL7km7q4u9/U@UO9@QM)
[Answer]
# JavaScript, 682 bytes
```
x=>{m=1;x.split(/\D+/g).map(i=>i?m*=i:0);e=new Set(x.replace(/\d+|\+|->/g,"").match(/([A-Z][a-z]*)/g));e.delete``;A=[];for(let z of e){t=x.split`->`;u=[];for(c=1;Q=t.shift();c=-1)Q.split`+`.map(p=>u.push(c*((i=p.indexOf(z))==-1?0:(N=p.substring(i+z.length).match(/^\d+/g))?N[0]:1)));A.push(u)}J=A.length;for(P=0;P<J;P++){for(i=P;!A[i][P];i++);W=A.splice(i,1)[0];W=W.map(t=>t*m/W[P]);A=A.map(r=>r[P]?r.map((t,j)=>t-W[j]*r[P]/m):r);A.splice(P,0,W)}f=e.size;if(!A[0][f])return"Nope!";g=m=-m;_=(a,b)=>b?_(b,a%b):a;c=[];A.map(p=>c.push(t=p.pop())&(g=_(g,t)));c.push(m);j=x.match(/[^+>]+/g);return c.map(k=>k/g).map(t=>(t^1?t:"")+(z=j.shift())+(z.endsWith`-`?">":"+")).join``.slice(0,-1);}
```
This is a much more golfed (decades of characters!) of Kuilin's answer. Might be noncompeting because certain JS features postdate the challenge.
[Answer]
# Javascript, 705 bytes
**(non-competing, some features postdate the challenge)**
Other solutions all had elements of brute-forcing. I tried for a more deterministic approach by representing the chemical equation as a set of linear equations, and then solving using the Gauss-Jordan algorithm to take the reduced row-echelon form of that matrix. In order to isolate out the trivial case where everything is zero, I assume that one of the elements is a constant number - and that number is determined by just all the numbers multiplied together, in order to not have fractions. Then as a final step we'll divide each by the gcd to satisfy the last condition.
Ungolfed:
```
function solve(x) {
//firstly we find bigNumber, which will be all numbers multiplied together, in order to assume the last element is a constant amount of that
bigNumber = 1;
arrayOfNumbers = new Set(x.split(/\D+/g));
arrayOfNumbers.delete("");
for (let i of arrayOfNumbers) bigNumber *= parseInt(i);
//first actual step, we split into left hand side and right hand side, and then into separate molecules
//number of molecules is number of variables, number of elements is number of equations, variables refer to the coefficients of the chemical equation
//note, the structure of this is changed a lot in the golfed version since right is the same as negative left
left = x.split("->")[0].split("+");
righ = x.split("->")[1].split("+");
molecules = left.length + righ.length;
//then let's find what elements there are - this will also become how many equations we have, or the columns of our matrix minus one
//we replace all the non-element characters, and then split based on the uppercase characters
//this also sometimes adds a "" to the array, we don't need that so we just delete it
//turn into a set in order to remove repeats
elems = new Set(x.replace(/\d+|\+|->/g,"").match(/([A-Z][a-z]*)/g));
elems.delete("");
rrefArray = [];//first index is rows, second index columns - each row is an equation x*(A11)+y*(A21)+z*(A31)=A41 etc etc, to solve for xyz as coefficients
//loop thru the elements, since for each element we'll have an equation, or a row in the array
for (let elem of elems) {
buildArr = [];
//loop thru the sides
for (let molecule of left) {
//let's see how many of element elem are in molecule molecule
//ASSUMPTION: each element happens only once per molecule (no shenanigans like CH3COOH)
index = molecule.indexOf(elem);
if (index == -1) buildArr.push(0);
else {
index += elem.length;
numberAfterElement = molecule.substring(index).match(/^\d+/g);
if (numberAfterElement == null) buildArr.push(1);
else buildArr.push(parseInt(numberAfterElement));
}
}
//same for right, except each item is negative
for (let molecule of righ) {
index = molecule.indexOf(elem);
if (index == -1) buildArr.push(0);
else {
index += elem.length;
numberAfterElement = molecule.substring(index).match(/^\d+/g);
if (numberAfterElement == null) buildArr.push(-1);
else buildArr.push(parseInt(numberAfterElement)*(-1));
}
}
rrefArray.push(buildArr);
}
//Gauss-Jordan algorithm starts here, on rrefArray
for (pivot=0;pivot<Math.min(molecules, elems.size);pivot++) {
//for each pivot element, first we search for a row in which the pivot is nonzero
//this is guaranteed to exist because there are no empty molecules
for (i=pivot;i<rrefArray.length;i++) {
row = rrefArray[i];
if (row[pivot] != 0) {
workingOnThisRow = rrefArray.splice(rrefArray.indexOf(row), 1)[0];
}
}
//then multiply elements so the pivot element of workingOnThisRow is equal to bigNumber we determined above, this is all to keep everything in integer-space
multiplyWhat = bigNumber / workingOnThisRow[pivot]
for (i=0;i<workingOnThisRow.length;i++) workingOnThisRow[i] *= multiplyWhat
//then we make sure the other rows don't have this column as a number, the other rows have to be zero, if not we can normalize to bigNumber and subtract
for (let i in rrefArray) {
row = rrefArray[i];
if (row[pivot] != 0) {
multiplyWhat = bigNumber / row[pivot]
for (j=0;j<row.length;j++) {
row[j] *= multiplyWhat;
row[j] -= workingOnThisRow[j];
row[j] /= multiplyWhat;
}
rrefArray[i]=row;
}
}
//finally we put the row back
rrefArray.splice(pivot, 0, workingOnThisRow);
}
//and finally we're done!
//sanity check to make sure it succeeded, if not then the matrix is insolvable
if (rrefArray[0][elems.size] == 0 || rrefArray[0][elems.size] == undefined) return "Nope!";
//last step - get the results of the rref, which will be the coefficients of em except for the last one, which would be bigNumber (1 with typical implementation of the algorithm)
bigNumber *= -1;
gcd_calc = function(a, b) {
if (!b) return a;
return gcd_calc(b, a%b);
};
coEffs = [];
gcd = bigNumber;
for (i=0;i<rrefArray.length;i++) {
num = rrefArray[i][molecules-1];
coEffs.push(num);
gcd = gcd_calc(gcd, num)
}
coEffs.push(bigNumber);
for (i=0;i<coEffs.length;i++) coEffs[i] /= gcd;
//now we make it human readable
//we have left and right from before, let's not forget those!
out = "";
for (i=0;i<coEffs.length;i++) {
coEff = coEffs[i];
if (coEff != 1) out += coEff;
out += left.shift();
if (left.length == 0 && righ.length != 0) {
out += "->";
left = righ;
} else if (i != coEffs.length-1) out += "+";
}
return out;
}
console.log(solve("Al+Fe2O4->Fe+Al2O3"));
console.log(solve("Al+Fe2O3->Fe+Al2O3"));
console.log(solve("C7H16+O2->CO2+H2O"));
console.log(solve("Pb->Au"));
```
Golfed
```
s=x=>{m=1;x.split(/\D+/g).map(i=>i!=""?m*=i:0);e=(new Set(x.replace(/\d+|\+|->/g,"").match(/([A-Z][a-z]*)/g)));e.delete("");A=[];for(let z of e){t=x.split("->");u=[];for(c=1;Q=t.shift();c=-1)Q.split("+").map(p=>u.push(c*((i=p.indexOf(z))==-1?0:(N=p.substring(i+z.length).match(/^\d+/g))?N[0]:1)));A.push(u)}J=A.length;for(P=0;P<J;P++){for(i=P;!A[i][P];i++);W=A.splice(i,1)[0];W=W.map(t=>t*m/W[P]);A=A.map(r=>!r[P]?r:r.map((t,j)=>t-W[j]*r[P]/m));A.splice(P,0,W)}f=e.size;if (!A[0][f])return "Nope!";g=m=-m;_=(a,b)=>b?_(b,a%b):a;c=[];A.map(p=>c.push(t=p.pop())&(g=_(g,t)));c.push(m);j=x.match(/[^+>]+/g);return c.map(k=>k/g).map(t=>(t==1?"":t)+(z=j.shift())+(z.endsWith("-")?">":"+")).join("").slice(0,-1);}
console.log(s("Al+Fe2O4->Fe+Al2O3"));
console.log(s("Al+Fe2O3->Fe+Al2O3"));
console.log(s("C7H16+O2->CO2+H2O"));
console.log(s("Pb->Au"));
```
] |
[Question]
[
>
> **Synopsis:** Given the output of a generalised FizzBuzz program, return the list of factors and words used for the program.
>
>
>
## Challenge Description
Imagine a generalised FizzBuzz program that takes in as input a list of factors and words to use and the number to start from. For instance, if the input of this program was
```
3 2,Ninja 5,Bear 7,Monkey
```
The program would print out numbers from `3` to `100`, replacing numbers divisible by `2` with `Ninja`, numbers divisible by `5` with `Bear`, and numbers divisible by `7` with `Monkey`. For numbers that are divisible then more than one of those terms, the program will concatenate the words, printing things such as `NinjaBear` or `BearMonkey` or `NinjaMonkey` or `NinjaBearMonkey`. Here's the output of that input:
```
3
Ninja
Bear
Ninja
Monkey
Ninja
9
NinjaBear
11
Ninja
13
NinjaMonkey
Bear
Ninja
17
Ninja
19
NinjaBear
Monkey
Ninja
23
Ninja
Bear
Ninja
27
NinjaMonkey
29
NinjaBear
31
Ninja
33
Ninja
BearMonkey
Ninja
37
Ninja
39
NinjaBear
41
NinjaMonkey
43
Ninja
Bear
Ninja
47
Ninja
Monkey
NinjaBear
51
Ninja
53
Ninja
Bear
NinjaMonkey
57
Ninja
59
NinjaBear
61
Ninja
Monkey
Ninja
Bear
Ninja
67
Ninja
69
NinjaBearMonkey
71
Ninja
73
Ninja
Bear
Ninja
Monkey
Ninja
79
NinjaBear
81
Ninja
83
NinjaMonkey
Bear
Ninja
87
Ninja
89
NinjaBear
Monkey
Ninja
93
Ninja
Bear
Ninja
97
NinjaMonkey
99
NinjaBear
```
Note that whenever the program needs to combine words together, it always goes from **lowest number to highest number**. So it won't print out something like `MonkeyBear` (since Monkey is a higher number than Bear is).
Your program should take in the *output* of the generalised FizzBuzz program as *input*, and *output* the *input* given to the generalised FizzBuzz program. In other words, write a "reverse program" for the generalised FizzBuzz program. For instance, given the code block above as input, your program should output `3 2,Ninja 5,Bear, 7,Monkey`.
There are some rules that the words will always follow:
* It will always be possible to tell exactly what the factors and words are from the input.
* Each word will begin with a capital letter and will not contain any other capital letters, or numbers.
* Each factor is unique.
## Sample Inputs and Outputs
Input:
```
Calvins
7
Hobbies
9
10
11
Calvins
13
14
15
Hobbies
17
Calvins
19
20
21
22
23
CalvinsHobbies
25
26
27
28
29
Calvins
31
Hobbies
33
34
35
Calvins
37
38
39
Hobbies
41
Calvins
43
44
45
46
47
CalvinsHobbies
49
50
51
52
53
Calvins
55
Hobbies
57
58
59
Calvins
61
62
63
Hobbies
65
Calvins
67
68
69
70
71
CalvinsHobbies
73
74
75
76
77
Calvins
79
Hobbies
81
82
83
Calvins
85
86
87
Hobbies
89
Calvins
91
92
93
94
95
CalvinsHobbies
97
98
99
100
```
Output:
```
6 6,Calvins 8,Hobbies
```
Input:
```
FryEggman
7
Am
Fry
The
11
FryAmEggman
13
14
FryThe
Am
17
FryEggman
19
AmThe
Fry
22
23
FryAmEggman
The
26
Fry
Am
29
FryTheEggman
31
Am
Fry
34
The
FryAmEggman
37
38
Fry
AmThe
41
FryEggman
43
Am
FryThe
46
47
FryAmEggman
49
The
Fry
Am
53
FryEggman
The
Am
Fry
58
59
FryAmTheEggman
61
62
Fry
Am
The
FryEggman
67
Am
Fry
The
71
FryAmEggman
73
74
FryThe
Am
77
FryEggman
79
AmThe
Fry
82
83
FryAmEggman
The
86
Fry
Am
89
FryTheEggman
91
Am
Fry
94
The
FryAmEggman
97
98
Fry
AmThe
```
Output:
```
6 3,Fry 4,Am 5,The 6,Eggman
```
Input:
```
DeliciousTartApplePie
DeliciousCreamPancakeStrawberry
DeliciousProfiterole
DeliciousCream
DeliciousPancake
DeliciousCreamStrawberryTart
```
Output:
```
95 1,Delicious 2,Cream 3,Pancake 4,Strawberry 5,Tart 19,Apple 95,Pie 97,Profiterole
```
You can get the code I used to generate the inputs [here](https://gist.github.com/katyaka/6e026738b45ba03f385f).
[Answer]
# Pyth, 73 bytes
```
jd+J-101lK.zjL\,Sm,_-F>2+_Jf}d@KTUKd{smtcdf-@dTGUdf>T\:K
```
That was certaintly a tough one. I think I've covered all the edge cases, including everything in @MartinBüttner's example, and the no repeat factors example.
[NinjaBearMonkey](https://pyth.herokuapp.com/?code=jd%2BJ-101lK.zjL%5C%2CSm%2Cf%26qm!%25kTrJ101m%7Dd%40KkUK-T~%2BYT1doxsKN%7Bsmtcdf-%40dTGUdf%3ET%5C%3AK&input=3%0ANinja%0ABear%0ANinja%0AMonkey%0ANinja%0A9%0ANinjaBear%0A11%0ANinja%0A13%0ANinjaMonkey%0ABear%0ANinja%0A17%0ANinja%0A19%0ANinjaBear%0AMonkey%0ANinja%0A23%0ANinja%0ABear%0ANinja%0A27%0ANinjaMonkey%0A29%0ANinjaBear%0A31%0ANinja%0A33%0ANinja%0ABearMonkey%0ANinja%0A37%0ANinja%0A39%0ANinjaBear%0A41%0ANinjaMonkey%0A43%0ANinja%0ABear%0ANinja%0A47%0ANinja%0AMonkey%0ANinjaBear%0A51%0ANinja%0A53%0ANinja%0ABear%0ANinjaMonkey%0A57%0ANinja%0A59%0ANinjaBear%0A61%0ANinja%0AMonkey%0ANinja%0ABear%0ANinja%0A67%0ANinja%0A69%0ANinjaBearMonkey%0A71%0ANinja%0A73%0ANinja%0ABear%0ANinja%0AMonkey%0ANinja%0A79%0ANinjaBear%0A81%0ANinja%0A83%0ANinjaMonkey%0ABear%0ANinja%0A87%0ANinja%0A89%0ANinjaBear%0AMonkey%0ANinja%0A93%0ANinja%0ABear%0ANinja%0A97%0ANinjaMonkey%0A99%0ANinjaBear&debug=0), [Deliciousness](https://pyth.herokuapp.com/?code=jd%2BJ-101lK.zjL%5C%2CSm%2Cf%26qm!%25kTrJ101m%7Dd%40KkUK-T~%2BYT1doxsKN%7Bsmtcdf-%40dTGUdf%3ET%5C%3AK&input=DeliciousTartApplePie%0ADeliciousCreamPancakeStrawberry%0ADeliciousProfiterole%0ADeliciousCream%0ADeliciousPancake%0ADeliciousCreamStrawberryTart&debug=0)
At the high level, the program first finds all of the words by chopping up the alphabetical strings on capital letters.
Then, the rows are mapped to whether or not each string appears in the row, and each possible factor is tested to see if it produces the same ordering. If it does, the factor is added to a gobal list, which is check to see if the factor was already present. If it was not already present, the factor is used. The strings are ordered by first appearance in the input, which disambiguates the ordering of strings that each appear only once in the same row.
After that, it's just formatting and printing.
[Answer]
# Scala, 350 characters
```
(s:String)⇒{def g(a:Int,b:Int):Int=if(b==0)a.abs else g(b,a%b);val(j,q)=(s.lines:\100→Map.empty[String,Int]){case(l,(n,m))⇒if(l(0).isDigit)(n-1,m)else(n-1,m++(Seq(Seq(l(0)))/:l.tail){case(x,c)⇒if(c.isUpper)Seq(c)+:x else (x(0):+c)+:x.tail}.map{t⇒val w=t.mkString;w→g(m.getOrElse(w,n),n)})};s"${j+1}"+q.map{case(k,v)=>s" $v,$k"}.toSeq.sorted.mkString}
```
not winning... but nice question.
### tested results:
```
scala> (s:String)⇒{def g(a:Int,b:Int):Int=if(b==0)a.abs else g(b,a%b);val(j,q)=(s.lines:\100→Map.empty[String,Int]){case(l,(n,m))⇒if(l(0).isDigit)(n-1,m)else(n-1,m++(Seq(Seq(l(0)))/:l.tail){case(x,c)⇒if(c.isUpper)Seq(c)+:x else (x(0):+c)+:x.tail}.map{t⇒val w=t.mkString;w→g(m.getOrElse(w,n),n)})};s"${j+1}"+q.map{case(k,v)=>s" $v,$k"}.toSeq.sorted.mkString}
res0: String => String = <function1>
scala> res0("""DeliciousTartApplePie
| DeliciousCreamPancakeStrawberry
| DeliciousProfiterole
| DeliciousCream
| DeliciousPancake
| DeliciousCreamStrawberryTart""")
res1: String = 95 1,Delicious 2,Cream 3,Pancake 4,Strawberry 5,Tart 95,Apple 95,Pie 97,Profiterole
scala> res0("""FryEggman
| 7
| Am
| Fry
| The
| 11
| FryAmEggman
| 13
| 14
| FryThe
| Am
| 17
| FryEggman
| 19
| AmThe
| Fry
| 22
| 23
| FryAmEggman
| The
| 26
| Fry
| Am
| 29
| FryTheEggman
| 31
| Am
| Fry
| 34
| The
| FryAmEggman
| 37
| 38
| Fry
| AmThe
| 41
| FryEggman
| 43
| Am
| FryThe
| 46
| 47
| FryAmEggman
| 49
| The
| Fry
| Am
| 53
| FryEggman
| The
| Am
| Fry
| 58
| 59
| FryAmTheEggman
| 61
| 62
| Fry
| Am
| The
| FryEggman
| 67
| Am
| Fry
| The
| 71
| FryAmEggman
| 73
| 74
| FryThe
| Am
| 77
| FryEggman
| 79
| AmThe
| Fry
| 82
| 83
| FryAmEggman
| The
| 86
| Fry
| Am
| 89
| FryTheEggman
| 91
| Am
| Fry
| 94
| The
| FryAmEggman
| 97
| 98
| Fry
| AmThe""")
res2: String = 6 3,Fry 4,Am 5,The 6,Eggman
```
[Answer]
# Python 2, ~~366~~ ~~340~~ 331 bytes
This program receive input via stdin.
New approach:
Calculate the factor of only one occurrence's words by the distance from the end of the line. For example (from the last sample): `DeliciousTartApplePie` Pie is calculate as: `[95,19,5,1][0]` and Apple is: `[95,19,5,1][1]`.
```
import sys
import re
d=[(i,re.findall('[A-Z][a-z]*',l)[::-1])for i,l in enumerate(sys.stdin)]
e=101-len(d)
print e," ".join(`x`+','+`y`[1:-1]for x,y in sorted({next((j-i for j,t in d if j>i and w in t),[x for x in range(i+e,0,-1)if(i+e)%x==0][d[i][1].index(w)]):w for w,i in{w:i for i,l in d[::-1]for w in l}.items()}.iteritems()))
```
Old approach:
```
import sys
import re
l=[(i,re.findall('[A-Z][a-z]*',l))for i,l in enumerate(sys.stdin)]
e=101-len(l)
d={}
for i,s in l:
for w in s[::-1]:
if w not in d.values():
d[next((j-i for j,t in l[i+1:]if w in t),next(m for m in range(i+e,0,-1)if(i+e)%m==0and m not in d))]=w
print e," ".join(`x`+','+`y`[1:-1]for x,y in sorted(d.iteritems()))
```
# Usage:
```
python FizzBuzzReverseSolver.py < Sample1.txt
```
# Explanation (of Old approach):
* In general, the program creates a list of line number and list of
words (e.g. `[(0, []), (1, ['Ninja']), (2, ['Bear']), ...]`.
* For each word in every line (starting from the end of the line):
+ Find the next occurrence of the word and insert the difference and the word to a predefined dictionary.
+ If it doesn't found, insert the biggest factor of the line number (including itself) that doesnt already exist in the dictionary and the word to the dictionary.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 65 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
|ā¤тα©+øUáεDS.uÅ¡J¦}˜ÙDεVXʒнYå}€θ0š¥θ}øí.¡н}εRεćÑRNèš]€`{',ý®>šðý
```
[Try it online.](https://tio.run/##yy9OTMpM/f@/5kjjoSUXm85tPLRS@/CO0MMLz211CdYrPdx6aKHXoWW1p@ccnulybmtYxKlJF/ZGHl5a@6hpzbkdBkcXHlp6bkft4R2H1@odWnhhb@25rUHnth5pPzwxyO/wiqMLY4HKEqrVdQ7vPbTO7ujCwxsO7/3/3yU1JzM5M7@0OCSxqMSxoCAnNSAzlQsu6lyUmpgbkJiXnJidGlxSlFielFpUVImQDyjKT8ssSS3Kz0HXhKQGoh1NHmEayGYA)
**Explanation:**
Step 1: Pair all input-lines with their corresponding value:
```
| # Get all inputs as a list of strings
ā # Push a list in the range [1,length] (without popping the list itself)
¤ # Push its last/largest value (without popping)
тα # Get the absolute difference with 100
© # Store this value in variable `®` (without popping)
+ # Add it to each value in the [1,length]-list
ø # Create pairs with the list of strings
```
[Try just step 1, one builtin at a time.](https://tio.run/##XY2xagJREEV7v2LYSlFBWyGIJI1gsWA6sZhdJ7tDnu8t82Y1gk3yLWlSpgmp19SBfNEmz8UoljPn3Hudx4SprqOpLUrtG/Y6gmi8v6k@xq1o9ncCW9CcQNBmBIthz5DNNF8G7eu58TDx7TU@QR@Gg0EnkOr15@X7vXpr@GS1AlZQB4RpDhs0JZ16T5PdRr0VQiUokMXDljU/Sl6FbeaDd/js1fUdGU7Zlf4eRSdFYShmav1/Q8k6RpviI81VcJuQyO7MY3EPrCTOXIcunCZ@xc9tYfkX)
Step 2: Get all unique words:
```
U # Pop and store the paired-list in variable `X`
á # Only leave the letters of each string in the (implicit) input-list
# (note that it'll use the entire list as input after we've used `|` once)
ε # Map each string to:
D # Duplicate the string
S # Convert the copy to a list of characters
.u # Check for each character whether it's uppercase
Å¡ # Split at the truthy indices (while keeping them)
J # Join each inner list of characters back to a string
¦ # Remove the leading item, which is always an empty string
}˜ # After the map: flatten the list of lists
Ù # And uniquify it
```
[Try just step 2, one builtin at a time.](https://tio.run/##XZBBSgMxFIb3PUWYjQtrDyBIKS2CBbE4eoDX9I0TmiZj5qWloAsLHkJwUxBBcONCcT3jTih4BS8yJhNtpauE5P/@/39P5zAUWFXRkcos7UmR0z6L2lcHxVubfdwUD1@L1UvxtFu@N6ITJedMIkyRUYruRoQmZzphCDxlORmhLjx9Xi4934iOIWsyUCPGtZqioSAkzYD5JI/yFAxwb@TJ3vfiOQ5sN0U@Zok2AZql6EINE7STO0tmswwNhxw3Dt6gZZs1HWdSEAOqm5KxlM6ZUCPBsc5Zvfbili1vi@V1SOtroUKQUMrF1PVIX9ShnugH3SlO9Hp@GLmBXSOc/C3BK90IxWNQH0pwO1JB/juwP@sOn/dB1HH7sUpcWpG4jvX6y7tmVfVQCi60zc/AUCfLJA4ENtavXYMwGYDiMMaYDMyGaMx88z8wOnHVjJbb0D9NwLf@N24@@Qc)
Step 3: Map each word to a list of pairs containing that word:
```
D # Duplicate the list of words
ε # Map over each:
V # Pop and store the current word in variable `Y`
X # Push the paired-list `X`
ʒ # Filter it by:
н # Where its first item (the string)
Yå # Contains word `Y`
} # Close the filter
```
[Try just step 3.](https://tio.run/##yy9OTMpM/f9fyTOvoLRENyezuMRKQcm@xvbQNnsupYDEzKLUFLCoQn6aQnFJaoGCIUj@SOOhJRebzm08tFL78A6I2vD8IjSVRiCVoYcXntvqEqxXerj10EKvQ8tqT885PBOiwzexQCE1MTlDoRyoVaEkXyFRAaa/AGhxsUJyfl5JYmZeZl66QklGYglYHchMl3NbwyJOTbqwN/Lw0lid//9dUnMykzPzS4tDEotKHAsKclIDMlO54KLORamJuQGJecmJ2anBJUWJ5UmpRUWVCPmAovy0zJLUovwcdE1IaiDa0eQRpoFsBgA)
Step 4: Convert each to the step-size, and pair it with the words:
```
€ # Map over each inner list
θ # And only leave the last item (the value)
0š # Prepend a 0 to this list
¥ # Get the deltas/forward-differences
θ # And only leave the last one
}ø # After the map: pair each together with its word
```
[Try just step 4, one builtin at a time.](https://tio.run/##XZC9SgNBFIX7PMWQ1r@onSAhZBtFcCH@FhY3u3fN6GRnmZlNCGhhwBewE2wCRhBsBCNpbHa1UVj0FXyRdWY3fwamGOae79wzh0uoU0zT4pYfhGqJUak2SLF8sRm9lgtFG6hAN3sl3CNSYUBWzfz9Krr/6SbP0eNCPMy1h1zMKdeMcj/uJQOrthzG11FvO3q4/LqLb3NiR4slCVCQtmYn2LrBrGRwcPR58/12HPdPRnKEFpKzUG9QDSQtYCEaCMFpGOS3@6RPMopjCwzQdwmQEqE@8QT31ay6lLx89HJpFZgTMlCY@brIFMgVj4s26B@51PNQoO@gHONk3JJeF/Vzj12fdQjLEhoTBjrlv4Sz0DhjRecLdMUGaRLFT1FfdBtUNTIXU4s0TDxcTFMLGXUoD@UeCFUJAoY2xcLktSoQmjb4DpxjTQlo11GIznRuC@5RhYKzeWhGk@Nz86mb2fwH)
Step 5: Fix any duplicated items (i.e. `Apple` & `Pie` both having value `95` now for the last test case):
```
í # Reverse each pair
.¡ # Then group all pairs by:
н # Their first item (the value)
}ε # After the group-by, map over each list of pairs:
R # Reverse the list of pairs
ε # Map over each pair:
ć # Extract head; pop and push remainder-list and first item separated
Ñ # Pop this value, and get all its divisors
R # Reverse this list
Nè # Index the map-index into it
š # And prepend this value back to the list
]€` # After both maps: flatten the list of lists of pairs one level down
```
[Try just step 5, one builtin at a time.](https://tio.run/##bZFBSwJBFMfvforBaxodOgUhkRR2CNGKOgiNu88cXGeWmVlNyENCdK5b0GUho6AOHQwvXnb0UrDYV@iLbDO7liXd9r3/@//@780ygasEoihdoK4nsw4Rcg2lc2frwWsulS5iwsGOu4jVkJDgolWjj8@Du49e@BI8LqnhvvLDQb687KmLwN8J7rvvt@omHw4ODt@up6Mj1e9@9p7C4crED/rhsKuGCbwELeACEGCrjlydZMDqORG3OfPcuYSqHSTroD9a2PFAmNHlwJ@Ouv@wCKXA0fcpOrs0Y4I0EGSTFhGMC3OSqRNkRvuQDcICahN6ghi3IV5JXxIOxpfqqlRJOAVqw2nsbGI3S@KKUMlMS@9gguMFjW9XPVQyyVtycDV6NlTFVgMlFtTWUcKkm4JDExskz/7hxPkaNvFnS2w5WEqgiOg/Q3WofgAH2axNZzcfZ6IoDw6xCPPEHuZyw3UdKBJI/XQ3OeBmEVMLN6AsOW5XgfPOXC9yViMSOHMWTb9mEvuCPqeZ5C8)
Step 6: Print the output, including starting item:
```
{ # Sort this list of pairs (based on their first item, the value)
',ý '# Join each pair with "," delimiter
®> # Push value `®`, and increase it by 1
š # Prepend it in front of the list
ðý # Join the list by spaces
# (after which it is output implicitly as result)
```
[Try just step 6, one builtin at a time.](https://tio.run/##XVC/SsNAGN/7FEeXDk2LDi6CFrGLHSS0KjoIvaZf6WGaC3cXStEMFsRZN8ElYEVBiw6RLFnu2kUh1FfwRWJira0dvuX3n49y3CAQx9kdy3ZEwSRcrKNs6WxDvpUyWR0TBs0fFNEW4gJstJbyo3N599mPXuVjXgX7yov8cq3oqAvpVeS9@3GrbsqRf3D4fj0Jj9TA/eo/RcHK2JODKHBVoJ6L0puEbuRXI390qa6qu@ph7B0nsvq0uEaZQKINaDbodIpXKLEQYKON7GQaavRQTssVmmCSDhHAUmVOU@HvegY2WE1Ul8N6fhUJ@i9RDjfH3kLqjEtDuY0N4BrqtklSRTiiDktOJC9KrepFhVocl5Nag1CH72EmtmzbBJ1A5g/dZoA7OrYMfAI1wXC3AYz15rzOaCsdTc1l04Jmal/i52lp8zc)
] |
[Question]
[
# Introduction
Decide whether a [Hexagony](https://esolangs.org/wiki/Hexagony) program composed solely of the characters `.)_|\/><@` will halt using least bytes.
# Challenge
[Hexagony](https://github.com/m-ender/hexagony) is a language developed by Martin Ender in which the source code is presented in the form of a hexagon. It has been extensively used in PPCG and there has been many impressive submissions using this language. Your task is to take a Hexagony program in its short form (one liner) that contains the characters `.)_|\/><@` only and decide whether it will halt.
Since a challenge should be self-contained (per comment by @Mr.Xcoder), the language specifications related to this challenge is given in the appendix. If there is anything unclear you can refer to the document itself, which I believe is pretty clear.
You can use a set of output values as truthy and another set as falsy provided that the intersection of the two sets is empty, and at least one of them should be finite (Thanks@JonathanAllan for fixing the loophole). Please indicate in the answer which sets you will use.
You can use [TIO](https://tio.run/#hexagony) to check whether a Hexagony program halts within 60 seconds.
Bonus point for solutions in Hexagony!
# Test cases
```
Input
Hexagonal Form
Output
.
.
False
.....@
. .
. . .
@ .
False
)\..@
) \
. . @
. .
True
.\|<..@
. \
| < .
. @
False
)\|<..@
) \
| < .
. @
True
..\...@|.<.\....>._
. . \
. . . @
| . < . \
. . . .
> . _
False
```
# Specs
* The input is a string or an array of characters of a Hexagony program in its short form
* The length of the program will be less than or equal to 169 characters (side length of 8)
* To reiterate, please clarify the truthy/falsy value sets you use in the answer
* Your program should halt for all valid inputs. Halting with error is fine as long as a truthy/falsy value is written to stdout or its closest equivalent in your language. (Thanks
@moonheart08 for pointing out this)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest number of bytes wins.
* As usual, [default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here.
# Appendix: Hexagony language specs related to this challenge
## Overview
### Source code
The source code consists of printable ASCII characters and line feeds and is interpreted as a [pointy-topped hexagonal grid](http://www.redblobgames.com/grids/hexagons/#basics), where each cell holds a single-character command. The full form of the source code must always be a regular hexagon. A convenient way to represent hexagonal layouts in ASCII is to insert a space after each cell and offset every other row. A hexagon of side-length 3 could be represented as
```
. . .
. . . .
. . . . .
. . . .
. . .
```
Within the scope of this challenge, the source code is padded to the next centered hexagonal number with no-ops (`.`s) and rearranged it into a regular hexagon. This means that the spaces in the examples above were only inserted for cosmetic reasons but don't have to be included in the source code.
For example, `abcdefgh` and `abcdef` will be padded to
```
a b c
d e f g a b
h . . . . and c d e , respectively.
. . . . f .
. . .
```
### Control flow
Within the scope of this challenge, the IP of Hexagony start at the top left corner of the hexagon moving to the right. There are commands which let you change the directions of IP movement based on its current direction and the value in the memory.
The edges of the hexagon wrap around to the opposite edge. In all of the following grids, if an IP starts out on the `a` moving towards the `b`, the letters will be executed in alphabetical order before returning to `a`:
```
. . . . . a . . . . k . . g . .
a b c d e . . b . . . . j . . . h . . a
. . . . . . g . . c . . . . i . . e . i . . b .
. . . . . . . . h . . d . . . . h . . d . . j . . c . .
f g h i j k . i . . e . . g . . c . k . . d . .
. . . . . . j . . f f . . b . . . e . .
. . . . . k . . . . a . . f . .
```
If the IP leaves the grid through a corner *in the direction of the corner* there are two possibilities:
```
-> . . . .
. . . . .
. . . . . .
. . . . . . . ->
. . . . . .
. . . . .
-> . . . .
```
If value in the memory is non-zero, the IP will continue on the bottom row. If it's zero, the IP will continue on the top row. For the other 5 corners, just rotate the picture. Note that if the IP leaves the grid in a corner but doesn't point at a corner, the wrapping happens normally. This means that there are two paths that lead *to* each corner:
```
. . . . ->
. . . . .
. . . . . .
-> . . . . . . .
. . . . . .
. . . . .
. . . . ->
```
### Memory model
In the scope of this challenge, the memory is a single cell containing an unbounded unsigned integer, and is initialized to zero before the start of the program.
## Command list
The following is a reference of all commands relevant to this challenge.
* `.` is a no-op: the IP will simply pass through.
* `@` terminates the program.
* `)` increments the value in the memory
* `_`, `|`, `/`, `\` are mirrors. They reflect the IP in the direction you'd expect. For completeness, the following table shows how they deflect an incoming IP. The top row corresponds to the current direction of the IP, the left column to the mirror, and the table cell shows the outgoing direction of the IP:
```
cmd E SE SW W NW NE
/ NW W SW SE E NE
\ SW SE E NE NW W
_ E NE NW W SW SE
| W SW SE E NE NW
```
* `<` and `>` act as either mirrors or branches, depending on the incoming direction:
```
cmd E SE SW W NW NE
< ?? NW W E W SW
> W E NE ?? SE E
```
The cells indicated as `??` are where they act as branches. In these cases, if the value in the memory is non-zero, the IP takes a 60 degree right turn (e.g. `<` turns `E` into `SE`). If the value is zero, the IP takes a 60 degree left turn (e.g. `<` turns `E` into `NE`).
## Example
This is a program taken from the test case: `)\..@`. Its full form is
```
) \
. . @
. .
```
And here is how it executes before coming to a halt. To make it terse I will number the cells in the hexagon and use the notation `1E)` if the IP is currently at cell `1`, executes the instruction `)` and is heading east after execution of the instruction.
```
1 2
3 4 5
6 7
```
The IP starts from cell `1` heading east. The memory cell was initialized to `0`.
1. `1E)`, memory cell is now `1`
2. `2\SW`, the IP is reflected
3. `4SW.`, no-op.
4. `6SW.`, no-op. Then it branches, as the memory cell is nonzero, it wraps to cell `1` instead of cell `5`.
5. `1SW)`, memory cell is now `2`.
6. `3SW.`, no-op.
7. `2E\`, the IP is reflected then wrapped.
8. `3E.`, no-op.
9. `4E.`, no-op.
10. `5E@`, the program halts.
---
Credits to @MartinEnder, @FryAmTheEggman and @Nitrodon for their helpful comments.
@FryAmTheEggman brought the issue of decidablity of halting problems of programs with both `(` and `)` to attention.
@MartinEnder pointed out that if `(` and `)` cannot appear in the same program then `(` can be dropped entirely.
@Nitrodon gave a simple proof for the decidability of the halting problem for programs with both `(` and `)`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 616 bytesSBCS
```
{l←3 3 1⊥⍨s←⌊.5+.5*⍨3÷⍨¯1+≢⍵
X d n←(s 0)(2 0)0
'@'∊⍵{V W←X+d⊢←⍎'d⊣n∨←1' 'd×1 ¯1' 'dׯ1 1' '(¯1 ¯1)(1 1)(2 0)(¯2 0)d⊃⍨(2 0)(¯2 0)(¯1 ¯1)(1 1)⍳⊂d' '(¯1 1)(1 ¯1)(2 0)(¯2 0)d⊃⍨(2 0)(¯2 0)(¯1 1)(1 ¯1)⍳⊂d' '(1,¯1+2×n)(¯2 0)(-d)⊃⍨2 ¯1⍳⊃d' '(¯1,1-2×n)(2 0)(-d)⊃⍨¯2 1⍳⊃d' 'd'⊃⍨')_|/\<>'⍳o←X⌷⍉(l↑⍺)@{(((¯3×s)≤-)∧(s≥-)∧((5×s)≥+)∧(s≤+)∧0=2|s++)/¨⍵}⍳1+2 4×s
⍵,o⊣X⊢←(s×1,2×n)(s×3,2×~n)(s×(1+3×n),2-n)(s×(3×n),1+n)(s×(4-3×n),~n)(s×(3-3×n),n)(X+3 1×s)(X+0 2×s)(X+¯3 1×s)(X-3 1×s)(X×1 0)(X+3 ¯1×s)(V W)⊃⍨(V=2+4×s)(V=¯2)((W<0)∧V<s)((W<0)∧V>3×s)((W>2×s)∧V<s)((W>2×s)∧V>3×s)(s>V+W)(W<0)((3×s)<V-W)((5×s)<V+W)(W>2×s)(s<W-V)⍳1}⍣(12×l)⊢''}
```
[Try it online!](https://tio.run/##jVKxbtswFNz9FdxIliIjSvYmC147dZM9GAgCCO5i2AU4BXY6NEBhC1HQDoV3J0a9dSiKAh3jP@GPuEdSsp0tAkTd3bv3RL7Hm09TWd7eTOcfj/bxx/sP9uu3@DjBuphiSUlKtK12tt4bUPtQqZ5QvXfg6eEv1pdfWtj11tZ/OiNSkhlMzJCYswRL3KEDalcVoouCDBEbidJWW1epfqSATzO72oNqSmh52GiCegECEAeZA3g5Aw9lIbkP0u@xg0vptdnWv231pWyLeNUH31DkZL4ooiN32uSwmZ2ssuShQOLM3nvf/jDSMnhfO13mhbOkQab8enk1znKK0Nx1yj6gv2uGKXy39T8@WDCGqulhY7hdP0tuVz@ZsetdQKwXAjvRBp49ivvJ0gjBr172mMIdiuMEpAtzBzyaYwSjMBFm0P8o7BgwdfBzwEyL1OlRIhshUC0a2pVBaP1pw0FHAjfI7Q0oJkmDcJBWlSfk5h@HDLTPa7g1TdtY0U9EN4h99JAzNsxid8QiMxck9x0Cz/2/zvEzbywmL8SQ@0TGvJQVEkJoZRaCIYuZbCgLdxc0WvjENNQpNral9O54nJCIKtqZEKrcM/CQj1ukxsvsrJ6xUmPnXqrMA5Wra/of "APL (Dyalog Unicode) – Try It Online")
The function accepts a Simplified Hexagony source code as a character vector, and returns 1 if `@` is included in the first `12 * full program size` instructions run, 0 otherwise.
Uses the [property pointed out by user202729](https://codegolf.stackexchange.com/questions/156849/halting-problem-for-simplified-hexagony#comment383883_156849), which is
>
> Theorem: If a Simplified Hexagony doesn't halt after `(full program size) * 12` steps (= `12 * ((side length) * (side length - 1) * 3 + 1)`), it will run forever.
>
>
>
Simple proof: A Simplified Hexagony program can have `"full program size=N" PC positions × 6 directions × 2 memory states (zero or nonzero)` distinct internal states. If the program doesn't halt within that many steps, it leads to `12N+1`th internal state which is identical to some previous state (by pigeonhole principle). This means the program has a cycle in the internal state, so it never terminates.
Other than that, it runs the Hexagony code very literally, with a small number trick that using `side length - 1` as a variable allows cleaner expressions here and there.
### Ungolfed & How it works
```
f←{
⍝ length of the input program
l←≢⍵
⍝ side length - 1
side←⌊.5+.5*⍨3÷⍨l-1
⍝ full program length
full←side⊥3 3 1
⍝ pad the input program with spaces
p←full↑⍵
⍝ create a dummy grid of the size of the full hexagon grid
grid←⍳1+2 4×side
⍝ replace the appropriate positions of the grid with the padded program
grid←p@{(((¯3×side)≤-)∧(side≥-)∧((5×side)≥+)∧(side≤+)∧0=2|side++)/¨⍵}grid
⍝ initialize the positions(x y), directions(dx dy), memory state(n) and the PC trajectory(t)
x y dx dy n t←side 0 2 0 0 ''
⍝ run the program (12×full) steps and check if the trajectory contains a '@'
'@'∊t⊣{
⍝ extract the opcode from the grid
op←grid[y;x]
⍝ append to the trajectory
t,←op
⍝ classify the op so that we can choose which code fragment to run
idx←')_|/\<>'⍳op
⍝ specify the code fragments for the opcodes (which includes dummy '⍬' for no-op)
fns←'n∨←1' 'dy×←¯1' 'dx×←¯1' 'dx dy⊢←(¯1 ¯1)(1 1)(2 0)(¯2 0)(dx dy)⊃⍨(2 0)(¯2 0)(¯1 ¯1)(1 1)⍳⊂dx dy'
fns,←⊂'dx dy⊢←(¯1 1)(1 ¯1)(2 0)(¯2 0)(dx dy)⊃⍨(2 0)(¯2 0)(¯1 1)(1 ¯1)⍳⊂dx dy'
fns,←'dx dy⊢←(1,¯1+2×n)(¯2 0)(-dx dy)⊃⍨2 ¯1⍳dx' 'dx dy⊢←(¯1,1-2×n)(2 0)(-dx dy)⊃⍨¯2 1⍳dx' '⍬'
⍝ choose the code fragment, run it, and move the PC one step forward
x2 y2←x y+dx dy⊣⍎idx⊃fns
⍝ check for boundary conditions (first 6 are "branching" outs, next 6 are non-branching outs)
idx2←(x2=2+4×side)(x2=¯2)((y2<0)∧x2<side)((y2<0)∧x2>3×side)((y2>2×side)∧x2<side)((y2>2×side)∧x2>3×side)(side>x2+y2)(y2<0)((3×side)<x2-y2)((5×side)<x2+y2)(y2>2×side)(side<y2-x2)⍳1
⍝ specify the code fragments for destination coordinates
fns2←'side×1,2×n' 'side×3,2×~n' 'side×(1+3×n),2-n' 'side×(3×n),1+n' 'side×(4-3×n),~n' 'side×(3-3×n),n' 'x y+3 1×side' 'x,2×side' 'x y+¯3 1×side' 'x y-3 1×side' 'x 0' 'x y+3 ¯1×side' 'x2 y2'
⍝ run the selected opcode and return a dummy value via ⊢
⊢x y⊢←⍎idx2⊃fns2
}⍣(12×full)⊢⍬
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 979 bytes
```
R=range
p=input()
l=len(p)
s=int((~-l/3)**.5+.5)
f=s*-~s*3+1
p+=(f-l)*'.'
o=0
g=[]
for i in[*R(s,s*2),*R(s*2,s-1,-1)]:
w=[' ']*(s*4+1)
for j in R(i+1):w[j*2+s*2-i]=p[o+j]
g+=w,
o+=i+1
x=s;y=0;u=2;v=0;n=0;t=''
M={'/':lambda e:{(2,0):(-1,-1),(-2,0):(1,1),(-1,-1):(2,0),(1,1):(-2,0)}.get(e,e),'\\':lambda e:{(2,0):(-1,1),(-2,0):(1,-1),(-1,1):(2,0),(1,-1):(-2,0)}.get(e,e),'<':lambda e:(1,2*n-1)if e[0]>1else(-2,0)if-1==e[0]else(-e[0],-e[1]),'>':lambda e:(-1,1-2*n)if-1>e[0]else(2,0)if e[0]==1else(-e[0],-e[1])}
exec("""
o=g[y][x];t+=o
if')'==o:n=1
elif'_'==o:v*=-1
elif'|'==o:u*=-1
elif o in M:u,v=M[o]((u,v))
X,Y=x+u,y+v
if X==s*4+2:X=s;Y=2*s*n
if X==-2:X=3*s;Y=2*s*(1-n)
if Y<0and X<s:X=s*(1+3*n);Y=s*(2-n)
if Y<0and X>s*3:X=s*3*n;Y=s*(1+n)
if Y>s*2and X<s:X=s*(4-3*n);Y=s*(1-n)
if Y>s*2and X>s*3:X=s*(3-3*n);Y=s*n
if X+Y<s:X=x+3*s;Y=y+s
if Y<0:X=x;Y=2*s
if X-Y>3*s:X=x-3*s;Y=y+s
if X+Y>5*s:X=x-3*s;Y=y-s
if Y>2*s:X=x;Y=0
if Y-X>s:X=x+3*s;Y=y-s
x,y=X,Y"""*12*f)
print('@'in t)
```
[Try it online!](https://tio.run/##bZPbbqMwEIbv/RRWb3ymMWn3gmRQX6A3vUpEUJXdQpaIBVRImqiHV8@O7TRNdosEzPz@5/PAQLcffrfN@FDsil@cMXZ4gOdlsypIB1XTbQYuSA110fBOkB6lgfMPU1@PhZTRrYpuBSmhl@ajl2NlSaeAl6YWkkWMtDAiK8hyUrbPtKJVk8kH3utexkK7SMa6N1YbK/KE0BfIGGW5RP1GWUGoq1pjFX3gFQrJS7aWscIqU@XQZa1a54SuFLxoQlsF6CE76Cd7GE02EE@2eG/wHIAxcg@v7Jol9fLPz6clLZJXHuuRSHjYXnMTUqt94sXEW7TXkmB4j1bFwAtdCM0WeHwPvOCZI/CcZ74FTs9oaIplg76qpEU2ylNb1H0RaqrSWACnBs1FGq82R0h6DnHbGuT4kvRUESCeC2D/g7wT/ylcXV3hAFfZPs92@WRQ0JKqZIIBtEkDlhQ1po8@3UowR@HNC5uTQFs3wPtko7dwn7U55xgJQWZ6Dju10Xu1RSydAbipx8kMBziHWPayOerGiWP5KXNrGuGW5tPRsnmis2nvilBXY3xSdGEc/@NJ8eP0LrQEh1VHBy7FF5wb88U57XVynUh8/OULraq5R@xUaHav@mMLTgzde5@Zp@hworlwIiC9vVwwAZHGQUZp5AWDfZxvhb6d3gO@VJyatLEsBeme3b/K7hi@/0Ec8M@WP8QhIpE77ohYuGu0eJuGLNyjaOFW36KpD6I0evwL "Python 3 – Try It Online")
A full program. Prints `True` to stdout if the input program halts, `False` otherwise. Note that TIO version has four backslashes instead of two, in order to wrap the entire program in `exec` call.
Port of [my own APL answer](https://codegolf.stackexchange.com/a/199608/78410). The underlying algorithm is the same; it just uses different language-specific constructs to do the same thing. Golfing suggestions are welcome.
### Ungolfed
```
p=input() # one line of input program from stdin
l=len(p) # length of the original program
s=int((~-l/3)**.5+.5) # side length - 1
f=s*-~s*3+1 # length of the full program
p=p.ljust(f,'.') # pad with dots
o=0 # offset in the original program for doing the layout
g=[] # grid to format the program as a hexagon
# loop for generating hexagonal layout
for i in[*range(s,s*2),*range(s*2,s-1,-1)]:
row=[' ']*(s*4+1)
for j in range(i+1):row[j*2+s*2-i]=p[o+j]
g+=[row]
o+=i+1
# initial condition: position(x,y),direction(dx,dy),memory(n),trajectory(t)
x=s;y=0;dx=2;dy=0;n=0;t=''
# mirror maps just for '/\<>' because '_|' are relatively easy
M={
'/':lambda e:{(2,0):(-1,-1),(-2,0):(1,1),(-1,-1):(2,0),(1,1):(-2,0)}.get(e,e),
'\\':lambda e:{(2,0):(-1,1),(-2,0):(1,-1),(-1,1):(2,0),(1,-1):(-2,0)}.get(e,e),
'<':lambda e:(1,2*n-1)if e[0]==2else(-2,0)if e[0]==-1else(-e[0],-e[1]),
'>':lambda e:(-1,1-2*n)if e[0]==-2else(2,0)if e[0]==1else(-e[0],-e[1])
}
# run the loop f*12 times
for _ in range(f*12):
# run the opcode
op=g[y][x];t+=op
if op==')':n=1
elif op=='_':dy*=-1
elif op=='|':dx*=-1
elif op in M:dx,dy=M[op]((dx,dy))
# one step forward
x2,y2=x+dx,y+dy
# handle "branching outs"
if x2==s*4+2:x2=s;y2=2*s*n
if x2==-2:x2=3*s;y2=2*s*(1-n)
if y2<0and x2<s:x2=s*(1+3*n);y2=s*(2-n)
if y2<0and x2>s*3:x2=s*3*n;y2=s*(1+n)
if y2>s*2and x2<s:x2=s*(4-3*n);y2=s*(1-n)
if y2>s*2and x2>s*3:x2=s*(3-3*n);y2=s*n
# handle "non-branching outs"
if x2+y2<s:x2=x+3*s;y2=y+s
if y2<0:x2=x;y2=2*s
if x2-y2>3*s:x2=x-3*s;y2=y+s
if x2+y2>5*s:x2=x-3*s;y2=y-s
if y2>2*s:x2=x;y2=0
if y2-x2>s:x2=x+3*s;y2=y-s
x,y=x2,y2
# finally, does the trajectory include '@'?
print('@'in t)
```
] |
[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/12056/edit).
Closed 8 years ago.
[Improve this question](/posts/12056/edit)
Everyone likes a good puzzle. After all, that's the basis for Code Golf and Code Challenge! What better puzzle exists than the famous Rubik's Cube? Well what else but her slightly larger sister, the [Rubik's Revenge](http://en.wikipedia.org/wiki/Rubik%27s_revenge)!
![Solved Rubik's Revenge](https://i.stack.imgur.com/Co0rh.jpg)
# Rubik's Revenge Background
Released in 1982 following the success of the classic Rubik's Cube invented by Hungarian sculptor and professor of architecture Ernő Rubik, a Rubik's Revenge is a cubic combination puzzle.
Each face contains sixteen stickers (as opposed to the traditional nine), each of which is one of six colours. An internal pivot mechanism enables each face to turn independently, effectively mixing up the colours.
The puzzle is solved when each face contains only one colour.
The biggest difference between the Rubik's Revenge and the Rubik's Cube is that the Revenge contains no fixed facets; the two inner facets are freely movable, allowing for **every** face to move freely.
# Move Notation
A move is defined as a change of state for the Rubik's Revenge. This challenge will stick with the basic 12 moves:
1. **F** (Outer Front): the outer side currently facing the solver
2. **f** (Inner Front): the inner side currently facing the solver
3. **B** (Outer Back): the outer side opposite the front
4. **b** (Inner Back): the inner side opposite the front
5. **U** (Outer Up): the outer side above (on top of) the front side
6. **u** (Inner Up): the inner side above (on top of) the front side
7. **D** (Outer Down): the outer side opposite the top (underneath the Revenge)
8. **d** (Inner Down): the inner side opposite the top (underneath the Revenge)
9. **L** (Outer Left): the outer side directly to the left of the front
10. **l** (Inner Left): the inner side directly to the left of the front
11. **R** (Outer Right): the outer side directly to the right of the front
12. **r** (Inner Right): the inner side directly to the right of the front
All moves are clockwise turns associated with the respective face of the cube. To denote a counter-clockwise turn, a prime symbol (') is used. Example moves and their equivalences follow.
1. **Move:** b (clockwise inner back)
1. Rotate the cube clockwise 180° horizontally (such that the back side of the cube now faces the front)
2. Rotate the inner front face clockwise
3. Rotate the cube counter-clockwise 180° horizontally (such that the original front side of the cube now faces the front)
2. **Move:** l' (counter-clockwise inner left)
1. Rotate the cube counter-clockwise 90° horizontally (such that the left side of the cube now faces the front)
2. Rotate the inner front face counter-clockwise
3. Rotate the cube clockwise 90° horizontally (such that the original front side of the cube now faces the front)
3. **Move:** D (clockwise outer down)
1. Rotate the cube clockwise 90° vertically (such that the down side of the cube now faces the front)
2. Rotate the outer front face clockwise
3. Rotate the cube counter-clockwise 90° vertically (such that the original front side of the cube now faces the front)
More examples will be provided upon request.
# Color Scheme
The Rubik's Revenge uses six basic colours for each of the stickers on a face. In this challenge, the colours will be represented as numbers.
* White (W): 0
* Red (R): 1
* Blue (B): 2
* Green (G): 3
* Yellow (Y): 4
* Orange (O): 5
A 2-Dimensional representation of the solved cube is as follows:
```
O O O O 5 5 5 5
O O O O 5 5 5 5
O O O O 5 5 5 5
O O O O 5 5 5 5
G G G G W W W W B B B B 3 3 3 3 0 0 0 0 2 2 2 2
G G G G W W W W B B B B ===> 3 3 3 3 0 0 0 0 2 2 2 2
G G G G W W W W B B B B ===> 3 3 3 3 0 0 0 0 2 2 2 2
G G G G W W W W B B B B 3 3 3 3 0 0 0 0 2 2 2 2
R R R R 1 1 1 1
R R R R 1 1 1 1
R R R R 1 1 1 1
R R R R 1 1 1 1
Y Y Y Y 4 4 4 4
Y Y Y Y 4 4 4 4
Y Y Y Y 4 4 4 4
Y Y Y Y 4 4 4 4
```
Where the corresponding faces are arranged as follows:
```
U U U U
U U U U
U U U U
U U U U
L L L L F F F F R R R R
L L L L F F F F R R R R
L L L L F F F F R R R R
L L L L F F F F R R R R
D D D D
D D D D
D D D D
D D D D
B B B B
B B B B
B B B B
B B B B
```
# The Task
In this challenge, the goal will be to write the shortest **and** most efficient Rubik's Revenge solver. Efficiency in this challenge is defined with respect to the total number of moves to solve a given input. Further, to promote the design of good heuristics, each input should run in less than 5 minutes and take less than 1,000 moves to solve.
# Input
The input will be a single value consisting of a sequence of the numbers 0-5. Each input will have exactly 96 digits. The faces of the Revenge will be represented as the following ranges of numbers within the input:
* [0-15] : Front
* [16-31] : Right
* [32-47] : Back
* [48-63] : Left
* [64-79] : Up
* [80-95] : Down
For a single face, the 16 corresponding digits will be represented as follows:
```
[ 0][ 1][ 2][ 3]
[ 4][ 5][ 6][ 7]
[ 8][ 9][10][11]
[12][13][14][15]
```
where the upper left digit (i.e. 0) corresponds to the upper left digit in the 2-dimensional representation above. The indices of the input sequence corresponding to the spaces on the Rubik's Revenge are as follows:
```
[64][65][66][67]
[68][69][70][71]
[72][73][74][75]
[76][77][78][79]
[48][49][50][51][ 0][ 1][ 2][ 3][16][17][18][19]
[52][53][54][55][ 4][ 5][ 6][ 7][20][21][22][23]
[56][57][58][59][ 8][ 9][10][11][24][25][26][27]
[60][61][62][63][12][13][14][15][28][29][30][31]
[80][81][82][83]
[84][85][86][87]
[88][89][90][91]
[92][93][94][95]
[32][33][34][35]
[36][37][38][39]
[40][41][42][43]
[44][45][46][47]
```
An example solved Revenge can be represented as follows:
```
000000000000000022222222222222224444444444444444333333333333333355555555555555551111111111111111
```
Where the front face is white (0), the right face is blue (2), the back face is yellow (4), the left face is green (3), the up face is orange (5), and the down face is red (1).
Note that there are many different possible representations of a solved Revenge, depending on the colour of the front face and the overall orientation of the Revenge.
**Assume that a valid solution is reachable from any input.**
# Output
The output should be the sequence of moves taken to find a solution. The output may or may not have a delimiter between moves; it is up to the coder.
# Scoring
Scoring for each test case will be based on the criteria defined in the **The Task** section.
1. Points for length are calculated as follows (**integer division**): `100,000 / (characters in code)`
2. Points for efficiency are calculated as follows (**integer division**): `500 / (number of moves)`
The total points for a single test is the sum of the above two calculations. The total points for your code will be the sum of the points for all tests. The winner of the challenge will be the highest number of points.
Note that since your score increases with the fewer amount of moves for a solution, it is recommended to find optimal moves for certain patterns.
To preserve readability, white-space and newlines will not count toward code length.
# Tests
Tests will be provided (ideally) within a week of posting. Each code must run each of the provided inputs and report total score as well as scores for each test.
---
Since solving the Rubik's Revenge is considerably more difficult than solving the Rubik's Cube and can require many more algorithms to produce optimized solutions, this challenge will be open for an undetermined amount of time.
I project the challenge will remain open for at least three (3) weeks, possibly more. Suggestions on the length of the challenge are encouraged.
Remember to have fun, and happy coding!
]
|
[Question]
[
[Cops challenge](https://codegolf.stackexchange.com/questions/155018/the-programming-language-quiz-mark-ii-cops)
## The Robbers' Challenge
1. **Find a vulnerable answer.** That is, an answer which hasn't been cracked yet and which isn't *safe* yet either.
2. **Crack it by figuring out its language.** That is, find *any* language in which the given program is a valid program (subject to the rules outlined in the Cops' Challenge above). It doesn't matter if this is the language the cop intended.
Once you have found a working language, post an answer to the Robbers' thread and comment below the Cop's answer. If you don't have enough reputation to comment, say this in your answer and someone will comment for you.
**The output format must be the same as the cop's intended solution in order to constitute a valid crack.**
**Every user only gets one guess per answer.** This includes telling other people the answer, or hints towards your guesses. You must not crack your own answer (obviously...).
The user who cracked the largest number of answers wins the robbers' challenge. Ties are broken by the sum of bytes of cracked answers (more is better).
**Good luck Robbers!**
[Answer]
# Game save of [the Powder Toy](http://powdertoy.co.uk/Download.html), [posted](https://codegolf.stackexchange.com/a/155079/44718) by [moonheart08](https://codegolf.stackexchange.com/users/77964/moonheart08)
`xxd` dump:
```
00000000: 4f50 5331 5c04 9960 961c 0c00 425a 6839 OPS1\..`....BZh9
00000010: 3141 5926 5359 b855 1468 00c2 eaff f6ff 1AY&SY.U.h......
00000020: 5446 0c4a 01ef 403f 2f5f 74bf f7df f040 TF.J..@?/_t....@
00000030: 0203 0000 4050 8000 1002 0840 01bc 16a5 ....@P.....@....
00000040: 61a2 6909 18c1 4c64 4f22 7a83 4030 08c9 a.i...LdO"z.@0..
00000050: a323 6932 0c8f 536a 0d0a 34f4 a635 31aa .#i2..Sj..4..51.
00000060: 7a4d 0c8f 5000 0006 4681 ea00 3469 e90e zM..P...F...4i..
00000070: 1a69 8219 0d34 c8c9 8403 4d00 6134 6993 .i...4....M.a4i.
00000080: 0008 1a09 1453 4ca0 311a 7a9a 68d3 468d .....SL.1.z.h.F.
00000090: 0003 d4c8 000d 000d 0f98 debe 75b8 487f ............u.H.
000000a0: 2256 900d a121 2107 bb12 1208 4409 e89e "V...!!.....D...
000000b0: ddeb 1f17 e331 5ead 7cec db16 65d5 6090 .....1^.|...e.`.
000000c0: 2422 b0ca cc2a 5585 c9c9 dc44 4ac0 f14d $"...*U....DJ..M
000000d0: 6076 5a40 8484 536a 953b b44b 190a 90f0 `[[email protected]](/cdn-cgi/l/email-protection).;.K....
000000e0: 8a20 310e 95ad ca24 2d4b 0097 1a69 a919 . 1....$-K...i..
000000f0: 8d5b 0010 0242 1c59 8981 409a ec10 9024 .[...B.Y..@....$
00000100: 2369 e1d8 a222 53dc 8231 dc4f a891 4b0b #i..."S..1.O..K.
00000110: cf61 20d8 c1b4 4269 e25b 072d 5fb4 f1c4 .a ...Bi.[.-_...
00000120: a66b 62c8 069c ebc6 0225 9900 9852 21e9 .kb......%...R!.
00000130: d2e3 63d8 069a 7a69 124e eafc 3c5d 4028 ..c...zi.N..<]@(
00000140: dd15 6f81 0d2b 8007 816d f581 36f9 e58f ..o..+...m..6...
00000150: 8cec 30e0 0378 40f9 b52c 4a17 b999 808d ..0..x@..,J.....
00000160: d583 106f fd5e aaf5 ea8f a01b f5fc 9be5 ...o.^..........
00000170: 8e40 e05d 3a0a 2470 964d ef31 4c17 45da .@.]:.$p.M.1L.E.
00000180: 3242 6692 251a aacc 6523 220c 73a7 7e3b 2Bf.%...e#".s.~;
00000190: cecf 635d 3cb6 08a0 7930 9566 0833 1d90 ..c]<...y0.f.3..
000001a0: 993a 5b8a e548 b34c 3fa8 0cbe 84aa d23e .:[..H.L?......>
000001b0: 0129 c73b 1859 afa8 a984 990d cb0c db77 .).;.Y.........w
000001c0: 8fa8 df2f eda2 b779 72a7 4333 9382 0794 .../...yr.C3....
000001d0: 1f14 2340 c199 344a 48e1 6214 85a8 82a9 ..#@..4JH.b.....
000001e0: 5f6a 5a55 6993 6395 4350 41a2 396f 3613 _jZUi.c.CPA.9o6.
000001f0: 20f1 4d52 d289 b60f 2ea1 0040 8009 08ea .MR.......@....
00000200: e782 4084 847f 8bb9 229c 2848 5c2a 8a34 ..@.....".(H\*.4
00000210: 00
```
* First, de-compress it with 7zip
* Then, run `strings` on it, you will find some strings like "gravityEnable", "aheat\_enable"
* Google these magic words, and you will got this game's source code page
[Answer]
# [Beatnik](https://esolangs.org/wiki/Beatnik), [posted](https://codegolf.stackexchange.com/a/155052) by [fergusq](https://codegolf.stackexchange.com/users/66323/fergusq)
Output as `xxd` dump:
```
00000000: 0102 0304 0506 0708 090a 0b0c 0d0e 0f10 ................
00000010: 1112 1314 1516 1718 191a 1b1c 1d1e 1f20 ...............
00000020: 2122 2324 2526 2728 292a 2b2c 2d2e 2f30 !"#$%&'()*+,-./0
00000030: 3132 3334 3536 3738 393a 3b3c 3d3e 3f40 123456789:;<=>?@
00000040: 4142 4344 4546 4748 494a 4b4c 4d4e 4f50 ABCDEFGHIJKLMNOP
00000050: 5152 5354 5556 5758 595a 5b5c 5d5e 5f60 QRSTUVWXYZ[\]^_`
00000060: 6162 6364 abcd
```
I tried it with [this interpreter](https://github.com/graue/esofiles/blob/master/beatnik/impl/BEATNIK.c).
[Try it online!](https://tio.run/##tVdbcts2FP0WV3GdfIiyKFu0nTS1wqRumsxk0sQex19O/QGBoIiIAjAEaNnNeDdZQzeQhbkX4EOiKmWsNvUDMi@Ae859gDimgwml9/u78Ovrk4sPb98BF4blKmc4wozEDMa38IoYYqTgFM5kriTXDJ5PclKwXyRlRIyJZnsyn7zwAIBAJsUEDJ8xIBO5Bxcp15ASDUIaGDMmwDBtWFzN4I8qxhn6juWMcLEHu/ue95gLmhWI/lybmMu99EXLlHMxaduouVXMmjyakhx2SXxNBGV@@RTYsHqjag6DyxkxK3M4gqY5GY@zehtaC6H5RLAYnEVJ5V9LHuOE/UDmOvVbS2oQOxCKSZwwU29xEDZGvwdfvE6JoQKgs/hTOMSvq5HXsWt4NAw@B9MoDHRgcF9nnnIk5X@O0Bv1bUpEr7cTvT594zx1rAd@FX3G/R3e7@PHndfZ309oJjXzE8Sul3ShOypX1IZk1SBXDTerhtsuPqgIHxfkpiUTPeeGpn6TSNUr7R2KTQJPjgFb7QyzBoLdGJjLPLb1xnn0V9dMBaFlbG02v8u@RhuXjrGk01GD9LREkgpEMRtjLxMRQ8w1JYjITQOKBX24058ap2YuK8c6ABLHYFI2C1w/QM50kS0QbAgOpu/Gh6M9c2hvhSrMop1cHA7mmmQFa6G0em4LoJ@bsEqfFkIWpo3bABlr87eMJRw2GAclCuZNF2NjvUPCc41jLmegGZUiXptJEy1Xq0nrwGxBI1xHY05UVb8mufYRxoRO14LrfzAxrYbdgtBBO/dV4NigZs4p2xy6WfvwAMDDVUA95QpIykgMoh@6I4lv5aTqBXw9/8ly@b1DaqKlE1qaeOLvlB0CyztqnixDJg8he7QtWdE1/5Lvj6D7ZC1d10bif0hsfY8h0364LdenW3H9AXn9T2zLN@9HI91JBZVL1B@zms00Gq5ui1lC8N3htp2g8kjxFWajGmRMTExq009QkQzQ4caQ7uw16nWQeJELQIg7b51KUO6Gc/d2UE99uoq@hMEhfh8EYXCE4xF@PgueBNYaluPQ/RG6BUc4iUuGdwicyNxHCTDaVTs4qn6/vEJ5P@KaZColPmK@bKCMzOSc5dY46JLu1bFLBqaea60IxrNrL@E6NXdNQNwFtE4uKaeJwCwCW2LFnxsrB0pOyumCSgLstABbU2tmFkTUEpG2NmsRwUp@kIYdYwdg9ZJCUMOlAKJ1MWMaF9ui2u4YswkXAiUiyASrbMuO7Y2966tB2LOceJbhKkBuqEUtMdcEdaRqMNgU77po3Or1KXBTGGgZcSvctrDUBg/ep8NSA7oeU7anWzI442MncDdIUsuvPUWtnEx8rSqRGJUog4FWVml2ykd8KI9PRY9WlFFjm8R/9Obk4uR3eH1@fnp@jAcGZjJn1dUJmH3n4w/xyB4YdsONf9gbrRyZDUoZqKNVk@j3ryLq1j/mCZ5e@O3046vzkzPPw7pfuKpim9sSY2HsJKJntyv/LKB2KP9Z2CTCG91to6ROTqfuXsU80SgKD3uwbF2kxPKyb6vveIZqtduOEqk3ArdLxDy5v79/z00XzLev377ClBSCc0FgyjJCXnrveVbNfPuLa44tUto/Fpjgolis10RIeey9y6VMU3V7mw4uLy/t7yVceh@KaWEMIYrDVF5zsfM3)
[Answer]
# [Element](https://esolangs.org/wiki/Element), [posted](https://codegolf.stackexchange.com/a/155054/78059) by [NoOneIsHere](https://codegolf.stackexchange.com/users/48922/nooneishere)
```
1 100'[2:`1+a`]
```
[Try it online!](https://tio.run/##S81JzU3NK/n/31DB0MBAPdrIKsFQOzEh9v9/AA "Element – Try It Online")
Don't have enough rep to comment.
[Answer]
# [COM file](https://en.wikipedia.org/wiki/COM_file), [posted](https://codegolf.stackexchange.com/a/155023/44718) by [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob)
```
huCX5DBP^h~0_GG1<h32X542P[18F18h42X%AAP[h!.X%OOS`M a@<euws
```
* Download [DOSBox](https://www.dosbox.com/) (if you are not working on 32 bit windows / dos)
* save the content as `1.com`
* execute it
btw, I know nothing about COM file. The code looks similar to EICAR-STANDARD-ANTIVIRUS-TEST-FILE for me. So I just tried to download DOSBox and run it.
[Answer]
# [festival](https://en.wikipedia.org/wiki/Festival_Speech_Synthesis_System), [posted](https://codegolf.stackexchange.com/a/155471/66323) by [quartata](https://codegolf.stackexchange.com/users/45151/quartata)
```
;#.#;
;echo {1..99};
(SayText "")
(SayText "hs sh (but which?) fl")
(SayText "link herring obscure, blame2 premier")
(SayText "don't forget to look up")
(define(f x)(cond((> x 100)())((print x))((f(+ x 1)))))
(f 1)
```
Run with `festival -b file.txt`. It prints some warnings for me like `Linux: can't open /dev/dsp` but I guess that's allowed in the rules. Alternatively it may play some noises if the system has audio enabled.
[Answer]
# [Milky Way](https://github.com/zachgates/Milky-Way), [posted](https://codegolf.stackexchange.com/a/155039/64121) by [tfbninja](https://codegolf.stackexchange.com/users/69912/tfbninja)
```
print-ZL¡;
```
[Try it online!](https://tio.run/##y83Mya7ULU@s/P@/oCgzr0Q3yufQQuv//wE "Milky Way – Try It Online")
The actual code is `ZL¡` which works as following:
```
Z push 100 to stack
L inclusive range
¡ output ToS and exit
```
[Answer]
# [Befunge-98](https://github.com/catseye/FBBI), [posted](/a/155043) by [ovs](/u/64121)
```
"0" < q <= s' * 1e' * g * 1061 * 19 * 77
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X8lAScFGoVDBxlahWF1BS8EwFUSmg1gGZoYgyhJImJv//w8A "Befunge-98 (FBBI) – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), [posted](https://codegolf.stackexchange.com/a/155093/9365) by [Conor O'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien)
```
??MultivariateHypergeometricDistribution
Map[Print,1..100]
```
[Try it online!](https://tio.run/##SywpSUzOSP3/397etzSnJLMssSgzsSTVo7IgtSg9NT83taQoM9klsxhIJZWWZObncfkmFkQHFGXmlegY6ukZGhjE/v8PAA "Attache – Try It Online")
[Answer]
# [Huginn](https://codestation.org/?h-action=menu-project&menu=submenu-project&page=&project=huginn), [posted](https://codegolf.stackexchange.com/a/155058/12012) by [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
```
main(){i=1;while(i<101){print("{} ".format(i));i+=1;}}
```
[Try it online!](https://tio.run/##DcoxDoAgEATArxgqiMFIjT6GQmETOQiiFoSvezr1hMuDiDk6kFQNq7FPwLFJLGY2quUCqlK0PohpTyW6KqGUxfjH3pnflCsSnaw1Je2Kvz8 "Huginn – Try It Online")
[Answer]
# [Golunar](https://esolangs.org/wiki/Golunar), [Posted](https://codegolf.stackexchange.com/a/155094/76162) by Esolanging Fruit
```
814918243305927192311963944207
```
Translates to the brainfuck program:
```
++++++++++[->++++++++++<]>[->+.<]
```
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), [posted](/a/155102) by [Adyrem](/u/77759)
```
i=100 while(i>0){p(100-i+"d")!}i=%<>--1;if(_@==0){_@=-100}end;
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/z/T1tDAQKE8IzMnVSPTzkCzukADKKCbqa2UoqSpWJtpq2pjp6traJ2ZphHvYGsLVACkdIFKalPzUqwV/v8HAA "Hexagony – Try It Online")
[Answer]
# [Unbalanced](https://github.com/Wheatwizard/Unbalanced), [posted](https://codegolf.stackexchange.com/questions/155018/the-programming-language-quiz-mark-ii-cops/155036#155036) by [Wheat Wizard](https://codegolf.stackexchange.com/users/56656)
I can't write any program in this language, just that there are a lot of unbalanced parentheses. Which reminds me of this language.
[Try it online!](https://tio.run/##vVfbbuM2EH3XVwyEBUzClzq9V7AN9LKLDdBiC2z7ZBu7jEzHQmXJIOWsso6/PZ0hdSElOy1QoEpiS8PDM2eGw6GyE/ovmabPz8n@kKsC3j/qQu4nr7OHROXZXmZFUI38Igox@TXRvuHnnVBBECSZTjYSogjeFyrJ7mG8gNusoC9raCBscB5EHzjcwByW69Z6GkSi5PAZzXTPqgFRAvs8vOHcm98gzx3k2EWKBidc1GceBPmx@EfBNabxSJJF6di7muuRVnSPo1HtYcce1tPt4Eh4sPU1syWqlvdSrUfQ3PLrI0SwXEOJ5CXdswGzwhhLo7TkI1D4MIetEYZGlNbYPfxy7WOX45t1i@Ivsw67rPwaa01qUOsOK1MRjjnMaaR83vUFXsc6XfehaYkJW3ehxjpdW@iy1aEuxOer685AbldLPZJG02jpyFleVN5Yp6Opm5mFI7OXlU5OFl6ggJeDnVrssop09sI6Gl9pG@PMUUyXt45oQ26DNeBTEzbRNAE65X6Do@qYgbN10ZQC23ZMLUcl5HQxdafuogfE3u0AtE3@9cZy9hVxaShcp62p9thYGsUBPOHzfI5xzXvmL6y5mbXFLyfYIDiIzYak@y0BRY0oFO4/tfCmAdQGkxxNyRGjO5JeD@jSmHC7Othzg532sMMbNF7EXuIdu7wfDBKuYa1@P9S6VdMARcSUPKRJLArsoltdvKopkAH3C24JjJPDcIgG/HDROttcQJ8H6BV97Mlts9jkuXmoxjGl5jwzD1jopgDMQxlUX7ikqdAFCZ3DtBp@BUmWFHY0L3ZSfUq0xCSY9pygD3VQsvCjviakhev8qGKJ1Idj0ThiK5tZKgolH6RCR8Jk447TnqIk2om03@2cGmeYbFvAjJAtyZ2901jmEP6Z3YlUZLHcwHQyDVGWfpOKTo3@lOdpPcAG40EUR7boZSr3EEM4vfnyq6@/@fa7738IkfSNSLXspqi@5vCHOsqarWzggcbV7abO3q6rsXrV7BMro1LTuuENBhoxa0YbVRimgRxoUwoVjUvp0Ttw9CHoKHdtzMRMfyU3PoWp92a81KRB8P6cCk/XhTm1YrOqgmSrPJZa35pC6ApvKsdDoZ9wED1q44hyzkzVPlJm8N0lHKDbvTgAK/KKYJKrDaeenBiYv05zkErlCsLb7EGkycaWUtjzuRq84BQH/4PXK06pUpZKYtULSk3d@5/wcTaGEjfUTqaH32R2dAq9Mc3hmKVJJnGBw3AUgFf4b@1bteE0O1KqCqPFvYzs/apwZizzQ4EbSK@rLfhhm6S4PdW9nkwmFm8/ceHHYgTjsdBxkozxvFzhz7tjgSFpEPSLdojxvVzE6BfifCP1pJ0sabIsZXwsJE19bW/xgNlJ2CYK0x7n@73INhQeSTjSvwFE7eglVod0R6SUm5WR8zvmqiDGRMOesoVsIMukcIU80JyqcXiTJNTtJDvu7zCEfGusSZtNlxAXapNg4YvHegmd1WwPiQ6GVl/v8k/2KAgBG9VeJKan3b4Dxu3THDY5BBCnpibuZfEjrkgAKfbYrdl13hZkuGgkrmpFOItTdzFwWkrqVRWEZXkxsThOwABw/VApHn8J9mJm@mC4C60b/vRUWzDHtZFTVvD9qK7J4TBcZSHHHoo7gF7gLnI@9DirbHdpK3OflcKh3FNPxcaWPQL7SEwflyh4ZCWO0M@oYcYXJ8Md1CcTJpM01SzkMAD3whOqOKoMq567A9KcAx7QCU32Qqvq3A/NJ2h9YSKpGSgC@pi@WzNLbN7QLr0@z3usMrfN1V5UGxbTR/KtVtFT32zxeqRamVVpDvF4pyZble@rkuZgji27UH6115Xw6sWsh2FwPeQ4z/BNCRg1YS8E1nvtYH5vL0SSVtnx8sOD5@fnsXzms//h4jN@WpwW5xk78dn5vGALhr8zsszY3w "Haskell – Try It Online")
The language seems to be not on TIO, so I just run the Haskell interpreter.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), [posted](/a/155099) by [boboquack](/u/60483)
```
#define ss "/}O'=){/'HI}-){"
+1<2+3
"}@"$>!'d'/1
> ss ss {<}
1/1=2-1;
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/185JTUtMy9VobhYQUm/1l/dVrNaX93Ds1ZXs1qJS9vQxkjbmEup1kFJxU5RPUVd35DLDqQUiKptarkM9Q1tjXQNrf//BwA "Hexagony – Try It Online")
[Answer]
# [Quartic](https://esolangs.org/wiki/User:Conor_O%27Brien/Compilers/Quartic), [posted](https://codegolf.stackexchange.com/a/155274/61384) by Conor O'Brien
```
decl a,z,e
set a,1
set z,1
loop z
print a
cmp e,a,'d'
if e
dec z
end
inc a
end
```
The program made perfect sense. The challenge is to figure out what language it was. Luckily, I was able to use [complex techniques](https://www.google.com/search?q=%22decl%22+%22set%22+%22loop%22+%22print%22+%22cmp%22&oq=%22decl%22+%22set%22+%22loop%22+%22print%22+%22cmp%22&safe=active&ssui=on) to find an esolang with the right commands.
[Answer]
# [Curry](http://www-ps.informatik.uni-kiel.de/currywiki/start), [posted](https://codegolf.stackexchange.com/a/155091/69655) by [Wheat Wizard](https://codegolf.stackexchange.com/users/56656)
```
f[]=""
f([x]++s)=show x++" "++f s
main=putStr(f[1..100])
```
Curry is a language that happens to be both a functional language and a logic language. The logic features allow patterns like `([x]++s)` to be valid.
This crack requires a Curry implementation such as PAKCS or KICS2 that is more full-featured than the one on TIO.
[Answer]
# [C (8cc + ELVM)](https://github.com/shinh/8cc/tree/eir), [posted](https://codegolf.stackexchange.com/a/155533/71256) by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)
```
main(X){while(X++<100)putchar(X);}
```
You can [Try it online!](https://tio.run/##S0oszvj/PzU5I19BPTcxM08jQrO6PCMzJ1UjQlvbxtDAQLOgtCQ5I7EIKGFdq65gp@Csl8yln19Qop@aU5arm1mkn5SZp2@RnKygG6ygm6/gil1Bak6mguv//wA) In a shell
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), [posted](https://codegolf.stackexchange.com/a/155574/76162) by [TheNumberOne](https://codegolf.stackexchange.com/users/32700/thenumberone)
```
/**/ inter\u0066ace S{/*//Hello World!*/static void main(/**/String[]a){for(char b=0;b++
<10/**/*10;)System\u002e/**/out/**/.print(b);}}
```
[Try it online!](https://tio.run/##LY2xDoIwGIR3n6Ju8BP9iwMLuLszOKhDhapFaEkpJIaQ8EL4ULxIpYbpcpfv7grWsZ2quSzyt7UI8/gFJEIarq8tpVHEMk7SeZx6BMQTL0tFzkqX@fZPNoYZkZFOiZxUTEgPATA1Wsjn5cYWxO8fSnvZi2lyX@yRxk6CYJOEdH2DkMZ@@mkMr9zlgbt8AlStWYl9vQwazzX9eBis/QE "Java (OpenJDK 8) – Try It Online")
All the commented out [right to left override](https://www.fileformat.info/info/unicode/char/202e/index.htm) characters really mess with the flow of the code. Along with replacing the escaped characters, the actual code looks like:
```
interface S{static void main(String[]a){for(char b=0;b++
<10*10;)System.out.print(b);}}
```
[Answer]
# [23](http://web.archive.org/web/20071012224934/http://www.philipp-winterberg.de/software/23e.php), [posted](/a/155255) by [jimmy23013](/u/25180)
```
22,1,16,10,10,-1,1,10,2,12,27,0,211
```
[Answer]
# [Commentator](https://github.com/cairdcoinheringaahing/Commentator), [posted](/a/155033) by [caird coinheringaahing](/u/66833)
```
print "H e l l o, W o r l d!", end = 10
for i in range( 1 0 0 ):
print i
;{-Haskell ?-}
#Python?
(({- Execute some# brainflak here#}))
;-}Perl: bvgk,l/;'juhedwsed/*{-:
05AB1E: 12DD/* Way to convert to float, nice :)
```
[Try it online!](https://tio.run/##LYwxb4MwFAZ3/4qvYShEWEClLEZVlCqRMmbL7MAjuBi/yDhpI8Rvp1Tt3XLTVdz35IIO7Of55o0LWB1BsIuc4gyGX7J@WaUgV@MdRS4a9jAwDl67K8UokC8mSuCfv5ER5SiPeujIWmzlJKLTM7TstiKOR4nDN1X3QBi4pwgXr41rrO7QkqdoShJRyulE3ipcHtcutVn5@nlvqf4aqM7Wo1Qi3@w@ioNC8bbfZ2uc9ROBUbF7kA@/2VjWIYUzFUEl8/wD "Commentator – Try It Online")
[Answer]
# Fortress, [posted by Zachary](https://codegolf.stackexchange.com/a/155083/77964)
```
export Executable
run(args) = do
for i<-seq(1#100) do
println(i)
end
end
```
[Answer]
# [MiLambda](http://esolangs.org/wiki/MiLambda), [posted](https://codegolf.stackexchange.com/a/155086/41024) by [Esolanging Fruit](https://codegolf.stackexchange.com/users/61384/esolanging-fruit)
```
v
E
Ξ
ς
v<
E`A:*[>+.<]
υ^
ε
Ξ
ς
v<
Δ
Θ
>σλ
```
[Online interpreter](http://alc.comuf.com/milambda.php)
I just remembered this language exists, so I searched up for its name. The `[>+.<]` part made it look an awful lot like brainfuck.
[Answer]
# [Prelude](https://esolangs.org/wiki/Prelude), [posted](https://codegolf.stackexchange.com/a/155129/31957) by [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)
```
for{# [1+1];
64+(1-v(1-)++);
100^x; rev!}
```
[Try it online!](https://tio.run/##KyhKzSlNSf3/Py2/qFpZIdpQ2zDWmsvMRFvDULcMiDW1tTWtuQwNDOIqrBWKUssUa///BwA "Prelude – Try It Online")
I thought the `v` and `^` chain placement looked familiar!
[Answer]
# [AutoHotkey](https://autohotkey.com), [posted](https://codegolf.stackexchange.com/a/155297) by [nelsontruran](https://codegolf.stackexchange.com/users/71883/nelsontruran)
```
i=1
loop,100
send % i++ . ","
```
I'm not sure if this is valid language defined by OP (free as in beer) since it seems only works on MS Windows.
// Btw, I'm a Dvorak layout user on Windows. That's why I know this language.
[Answer]
# [???](https://github.com/ararslan/qqq-lang), [posted](https://codegolf.stackexchange.com/a/155082/12012) by [Unihedron](https://codegolf.stackexchange.com/users/21830/unihedron)
```
......";........-,'";'";.;;.---,'"....'"-........;,'".........'";.!--!;,'".........'";;;.--,,,,,,,,,,;..........";!--.!--!;;;,'"--,";,,,,,,,,!,!!
```
[Try it online!](https://tio.run/##XY25EQAxCANrgcQJUgOqiv4DzvgLTkPCzgoys4orLp4ghmsOJQK9NR2OK@ggbi4aYH@4yvHyrven6e@OujU11/UszKo@ "??? – Try It Online")
[Answer]
# [brainfuck](https://esolangs.org/wiki/brainfuck), [posted](https://codegolf.stackexchange.com/a/155545/61563) by MickyT
```
+ . : + . + . + . v + . + . + . ^ +
. + . + . + . + . ; + .
+ . + . + . + . " " + .
+ . + . + . +
. + . @ + . + .
+ . + . ( " + .
+ . ) + . + . + .
+ . + .
+ . + . ; + . (
+ . ) + .
+ . + . ) +
. | + . + .
+ . + .
+ . + . ^
( + . + .
+ . " + .
+ . : : + .
+ . ( + .
^ + . +
. | + . (
+ . ^|^ + .
+ . ||| ) + .
+ . AAA + .
VVV + . "
+ . " + .
+ . ; + .
+ .
+ . ) + .
) 1 + . (
+ . ( + .
+ .
^ + . ; + .
+ . ;
+ . )
+ . + .
" + .
+ .
+ . ^ + .
+ .
+ .
+ . ; ^ + .
+ .
( + . )
+ .
+ . " d + .
) + . )
+ . )
+ . )
( " + .
```
[Try it online!](https://tio.run/##xVg9a8QwDN31K4Qnm0Kga7I0fyKjoe1xUAodCu2U/57S0LvaiT8kWSEeDs6RpWe9Jyl3L5/Pbx/Xr9f3ZcF1PayfHWJ//9ohhs@CjX9rxO/YJraLLMOtdcOHWxAbbSDkveVMN7tD2RrybgqXS1mknwfITbBr9qCgfDrvPf@0ejxNQPqGsdETEwkNDZBSWg5qdykmgVtjb@ycNO8Cw9ASKLbkJHGRAA93znpoUoLdZWIjC9d4bWhBJ02vSxyC9LlZSVaFU4Da0pGfAwUK4qieF9VSGzpSi5N@HiQCNJoQoE5eX3HRt8sGyPewAkY6ruxvy4uJlc5cSjvgF6UtjFuSJz/7YxrFjhaCo3meST2WigqYShrHEZtXKvlcfU7TVCwZ00pHo@6N1oht65mDeHwBai35tYFbdE4BaAyWlIZs2EdqOVphLoQqtTLa4GxB/ELwh/muFU7oW6880uIbNIpEcVBlRQ6pn2caDHAJBtlbo@DfjTYWVMggYMlXglcX7RFdQquo4URGgBVkkITwzIzBOdTIwloyP05TC1pDhPrS/xfL4GHrks0hSHMpS6M7UI7Mxu1UkFS6huPKwlbn1r3pLssP)
Running `tr -d ' \n:v^;"@()|AV1d'` (i.e. deleting everything except `.` and `+`) gives this:
```
+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), [posted](https://codegolf.stackexchange.com/a/155762/71256) by [Magic Octopus Urn](https://codegolf.stackexchange.com/users/59376/magic-octopus-urn)
```
2̵̨̛̆̈̈́̂ͦͣ̅̐͐ͪͬͤͨ̊̊ͭ̑͛̋͏̠̰̦̥̼̟̟̀3̶̵̨̥̜̼̳̞̺̲̹̦͈̻̫͇̯̬̮͖̔̅ͮͭͨͧ̾͑ͣ̑̑̃̄̚͝5̸̸̧͖̼͚̩ͧͦ͋ͭ̐ͤͣ̄̆ͦ2̶̢̻͕̼̹̟̦̮̮͇͕̥̱͙͙̻͔̫̞̈̓̿̎ͦ͑ͩ͐̔̿̓͟͠A̴̺͍̮̠̤̫̙̜̹͎͒͂̌ͣ̊ͤͨ͂͒ͣ̉͌̄ͭ̑͟͠͡͝à̄̍̿̎ͯ̑̀̃̂ͣ̆̂̓̂ͬ̉̉͝҉̹̠̤̻s̏̓̓̃ͮ̌͋̅̎҉͈̝̩̻͡a̵̛̬̩̙͈͍̙͇͖͈͔̝̘̼̤͚ͨͣ̍̇̐ͧͥ̅̊ͥͅs̷̡̝̰̟̲͚̱̦͓͙̖̅̊̉̒̀͡A̢̛͓̜͇̻̦̮̭̣̮̱͎͒ͪ̿̇̓ͫ̍ͯ̀R̵̴̴̸̹̰̪͎̹̗̹̟̱̘͊̋̎̋̅ͫͬ͐̐͌A̸̧̝͍͍͔̣̮̾̓ͣ̓̍́ͬ͝g̨͕̣͎͕̳̟̱̭̲ͭ͛̎͆̔̃́8̶̬͓̱ͧ̄͌́̉́̀͜6̢̡͈̭̟̳̮̦̞͖̘͍̗ͩ̑̎̄̑ͮ̊̉ͯ̓̽͝8̾ͪ̉͊̑͏̤̩͈̤̣͙̭̟̳̮͎̣͈͖̖͕͕̫͠͠5̶̳̲̹̳̣̪͈̝̝̯̩̲̰̭̘̭̗ͮ́ͯ̐ͧ͑͛̇̂ͩ̓ͫͦ̔̽͐ͯ̅ͦ̕͠͠͡6̴̪͇̣͙̦͖̝̠̤̻̩̰̣͉̰̯̟͕ͯͩͮ̋̒̍ͦ̎̇ͦͮͣ̉̃͗8̷ͨͬͫ̌̀̅͊͐̇͐̚͝҉̰͔̫̤̱̦̯̟̼̝̼̣̀͡6̸̫͔̜̾̓̒̚ͅ7̀ͮ̄̊ͧ͐͗͑̾̊ͨ̚̕͞҉̣̮͙̝͔̻̯̫̥͔8̶̮̭̭̪̯͖̯̭͖̆ͣ̊ͩ̊ͨͧ͗̋̐ͧͫ̅́͘ͅ
̨̛̝̬̠̯̗͓̦ͦ̀͂̐͛̆ͬ̏̀ͣͭ͊̒͌͝3̶̧̡͇̤̩̘̦͍̜ͦͣ̋̚5̶̴̨̥̩̭̩̰̀̌̽͒̃̋ͭ́͛͠1͕̺̺̩͖̾̃̾̈̑͂ͣ̉́́́̚2͇̻͙̖̮̖̩͓͚̣̞̯̦̱̤̝͍̩̔ͪͦ̾͆͐͐͒͗ͧͦ̿͗́̓͜ͅ5ͣ̒͂̆ͦͥ̑̕҉҉̜͈̮̳̟̺̤̥̰̹̮̺̣̻̞͕̟1̢̛̃̉̔̽̊ͣͮ͋ͪ͗̆ͪͦ̐̇͑ͧ̚͘҉̛̫͕̙͕2̸̣̫̳͍͎̼̤͚̱̲͓͌̀͗̈́̓̈́̂̄ͪ̉̄̄̉̋͗ͩ̅̆͢͞͝4̴̢̺͙̺̞͕̻̥͍͆̿̄̐͒͗̈́ͫ̑ͫ̇͐͠͠ͅ2̸̛͕̩͕ͣͫ̒́6̴̵̢̘̫̟͖͙̲̲̮̣̘͈͉͖͓̮͖̊́ͬ̆̎͒ͩ̏ͨͥͧ̿̆̄͐́̏T̛͕̟̫̮̊̇̾ͦ̋̋̎̆̄͗̕͝n̴̡̤̞̣̦̱̻̰̟̻͈͈̠͇̣ͮͭ̐̎ͭ͋͛͌ͩ͡L̎ͮ̐͑ͫ̃ͪ̌͆̂̂ͯ̕̕͏̢̢͚̥̰̹̫͍̠̼̩̟̲,̨̨̘̱͚̗̖̺͓̘̼͍̘͚̹ͫ̂̏̈́ͥͬͥ̃̅͐̐͞q̨͍͕̠͍͖͇̠͉̮̭̦̜̣̼̜̩̠̓̊̀̈́̊͆̀̎̌͋̅̐͊͘͘͟͡ͅe̵̶̡̛͎̱͕͉̞̳͗ͭ̇ͪ͋̓̚͡r̨͚̘̖̝̫̳͂̈́ͣ͂ͧ͒̎ͧ̍͆̏ͪ̓ͥ̇̾̏͘ļ̴̴̝͉̪͎̊͂̾̑ͬ̐͡2̷ͯ̓̓͂̈͠҉̦̤̹̻͚̠̘̘͓̫̤͚̣̬̙͉͙̜3̸̮̝̮̰̘̰̇̿ͫͪ̑̈́ͦ̇̿̏̿ͥ͞͡5̶̲͔̣̞͚͇͒ͨ̂ͪ́̓̐̅͊͋̎͋̅́ͨ̿͟͞jͯ͂͋̉ͯͣ̃͊ͫ̋͊̊ͪͭ͏̸͠҉̝̣̬̥̻͉̖̮̫̘̤͕̭ͅģ̵͖̯̠͉̟̬̗͎͈͍̪̙̲̙͓̳͂͑̏̉͐͊ͩ̽͗̍͜͡ͅr̴̵̡̓̓̂̕͏̰̟̩̪g̶̡̢̠̲̱͚̋͊͆̂̔̑̕͜
̂͐ͥ̇҉̬͇̥̪͝ͅ2̴̸̷̞͕̦͚̪̩̺͇̭͖̪̫ͮ̈̃ͭ̓̾̓͂͑͊ͭ́̔̍ͭ3̶̸̼̤̩̣̤̆ͤ͊̂͆͘ͅ4̋̐̍̅̐̓͂̽͊ͥ̒͆ͮ̌ͫͧ͘͟͡͠͏̠̬͚̬͕̤͇̤̣͖͇̠̰͚͙̘͎͕̥6̓̄ͥ̂ͦ̽͌͋̍̓̄̈́͑̋̎ͧ͂͘͜͝͠҉͕̼͕̮͔3͎̤͖̦̟̱̟͍̺̞̜̞̳̳̯̾͛̓̇̾̒ͫͮ͌ͩ̄̓̔̔̓ͯ̐̀̀́͘͠2̷̡̰͚͙͙̤͎̺̜̳͍̩̋̍ͫ̔ͦ̉́̎ͣ͒̈͑̽́͢͞ͅͅ6̨̯͇̼͚͇͉͈̼̩̮͍̣̖ͭ̎ͯ͑̓͆͋͑ͅ3̳͉̥̰̖͓͇̞̩̳̩͙̜͇̗̼͖ͩ͑ͫ͛͊̋̈͌̋ͯ̔͛̀͛͟͞ͅ2̆̃ͥ̓ͪ̍ͯͨ͜͝͝͏̗͍͚͕͔̝̟͚̦6̭̤͕̰̙̼͌̎̇̓̽ͤ͌ͫ̀͠ḫ̷̢͔̪͈̠͖̪̹̮̣̩͊̽̿ͭ͋̂̊̂͝e̶͕͔͍̙̟̟̱̤͓̯̪̮̠͉̖ͧͩ̋̂ͤͦͭ̽̎͗̅͊̅̽̅̀͜͞r͊̀̍ͨ̀̍̓ͤ͗ͨ̊̅͊̿̚҉̴̪͖̝̙̭̖̹͔̻̦̖̳͔5͚̻͕̪͓̹̼̎ͥ̍̈̓̇ͬ̊ͧ̏̾͑̚͘͝2̶̸̖͙̟͉̜̤͔̦͍̖͖̝͖̳̝ͦͬ̅͒ͭ͆͊́3̴̻̺̮̞̖͛̌̇ͨ̆͒̊͛ͯ͐̇6̭͙͇͇̘̭̫͖̣̲̬͕͔̜̰̽̒ͮ͑̒ͩͨ̎̒̃͛ͦͥͭ̏̇́ͅ5̴̷̙̠̙̝̭̼̥̝̼̞͉̱̟̰̠̖͚͓̑͂̿͗͑ͭͬ̒ͣ̅̓̏ͥ̅̚͜ͅ2̷̾͛̈́ͯͭ̿̏̇̒͛ͧ̀͝҉̡̯̦̜͔̱̰͓͍̲̣̳3̢̡̈́͆ͯ̚͢͜͏̖͓͖̥̻̗̭͉̤̗̗2̸̸̨͎͉̥͚̜̗̩̰̮͙̟̳ͥ̑̉̊ͤͧ͑̊̕2̃͊̓͒̂͐̏ͭ͑̅͂͂ͤ̚҉͙͈̞͖̪͓̹̰͕̹̮̰̼͎̦̪͜2̸̿͆͊́̔́҉̧̙͇͚͍̗̝̤͚̝̻̣͉̳̹͟2̡̛̗͖̟͔̳̹̭͇͕̼͉͓̙̑̌̆͑̔̒̎
̇̈́ͯͫͫ͐̎͒͆̎̌͐̾ͧ̈́͐ͭ̆҉̬̯̳̮͖͚̭̼̱̳̪͉̥̪̞̱̘̹̖̀3̢̡̡̟̰͙͉̪̰̱̱͕̟̼͚̟̭͉͔̌ͭ͗ͨͮ̀̂́͂ͯ̔̿̈̉͜͜4̴̢͚̫͉ͥͭ͛̿́̽͛̄͐͝6̡̾͐̿̄͌̒́͜҉̶̯̩̟̼̯̰̙̝̟͕̬̳̳͖̹̱2̨̤̝̮̞̺̟̪̠̱̺̱̠̹͉͍̺̩̈ͯͬ͘͟͜ͅ3͗ͨ̅̋̆͆͌̾ͪͪ͛͆̐ͣ҉́҉̱̖̫͍̣̤̬̱̬̠̫̠̻͔̞̰6̶̢̖͕̻̾̅̔ͧͧ̇̑͗̂͊̿̓̐̍̂ͪͪ͟3̈ͨͤ͐̅̏̋ͬ̄͊̅̀ͦͭ̇ͤͩ̇̈҉͓͚̮̲̣͕͙̣͙̮̖̫̟4̵̧͙̠̱̟͐͗ͦ̓̍̎̾̈̽̆̈̈ͥ̾͗ͫ̐͠2̴͕̳̗͈̟̲͖̝̙̼̭̲̳̹̬̈́̎͂̅̆͌̇ͣ̑̏͜͞6̋͋̀͛̓ͭ̿̊͂̍ͤ̃̎̓̃̌̏҉͎̰̬̟̲͙̼̪̯͍͕̭̦4̸̢͔̱͔̖̝̪̙̼̻͍̗̟̳͔̱͑̈͒ͤͬͅ2͖̯̫̂́ͧ͆͛̄̆ͦͨͧ̅͘͢ͅ3͚̟̱̖̖̯̳̰͎͓͍̮̝͍͊͗̒́̀͞4̨̨͓͔̲̝͎̣͇̲̹ͨͨͯ͂̈ͤ̈́̈́̇̈́̀͟͠6̡̛͍̤̩͖̰̙͇͖̀̇͐̊̆̽̏̍͢͢gͨͩ̆ͮ̈ͩ̍ͩ̑̀̎̌ͭ͏̵̝̯͎̜̭̟s͉̥̥̣̗͍̭̩͍̮͉͓̲͕͍̱̗̮̟ͩ̑͋̓̂ͭͤ̉̕͞ť͍̩͚̹̠̥̥̳̩̻̦̬̤͓̞͓̄̄͒ͫ̀̽́̎ͥ̍̌̚͘͡3̷̬̝̘͍͊ͯ̈́ͮ̀̋̓ͩͧ͂̆͐̂ͤ̓ͮ̚̕͜6̷̘̖̻̤̟̗̦̼͎͕̳̥̫̘̲̥́̄̊ͪ͂̈́͐͛̓́̚̕4̶̷̛͕͇͎̲̺̤̯͈̱̹͉̮̭̳̗̤ͣ̏ͣ̾̀͠3͖̟̳͓̲͓̫̝̗̟̮̺̮̭͈̿ͬͫͣ͐̾͗ͧ̓̌̅͛́͘͟͡2̛̹͓̫̫̮̺̙̟͙̳̤̺̠̞̩̠̞͙ͩͪ̀ͬͪ͌͗̽ͣ̈́͜ͅ6̴̳̪̩͉̳͓̞̘̙̦̏ͭ̃͊ͭ͑̀̚
̵̙̝̘̝̲̳͖̣̝͕̥͍̥͖̗̹͉̎̽ͥ̑̾̎͢ͅḧ̶̵͇̭͍̠̣̗͖͍̜͕̰̘̰̑̃̀͒̈́ͤ̏̓ͩͬ̐͐̑̽ͯ̚̕͠͠4̫̬̦̜͕̺̱̖̼͋̄ͨ̾̔ͤ̓͊̐ͧ̔ͤ̎̄̀̏́͢ͅe̶̡ͯ̓ͮͤ̏ͦͬ͗̈́̽ͯ̌̽͌͆͊ͭ҉̡̝̺̜̝̗̗5̢̳͔̯͍̰̗̻͖͎̜͕̺̙͙͙̬͂͐̽͗͝ͅẆ̵̤̣̠͉̩̳̗͈̆̃̀̈́̋́̉̒ͯͭͥ͒̀ͭͦ́̓͗͘ͅR̴̍ͩ̓ͮ́̿ͨ̇̊̾̃̄̌̍͞҉̖̻̹̙̯́D̸̨̛̝̹̮͇̣̿ͧ͌̍̚ͅ3̨̛̛̫̫̣̝͈͔̰̖͕̮͉͔͖̈́ͨ̉̌̇́̃̍ͧ̈̈͐ͨ͛̚2͎̟̱̪̖͈͕͔͓̘͉̙̍̃̓ͪͦ͋͆̃̈̄̂̄ͦͥ̍̏̃̀͢͢͟5̸̶͛̀̿̄ͦ͊̏҉̷̼͇͍͚̘̺̱̜̤̻̞̲̜̰͙͔yͨ͐̍ͪ̑̀̾̌̊ͤ̿͗̄͑͐̑͌͋̽̕͏̰͔̮͈̦̤̫̗̫̯w̵̧̗̣̙̠̬̺̩͚̬̎́ͭ̃͛̈́2̴͚̫̮͍̼̠̺̠͕̬̳̮͕̱̟̙̘̹̑ͮͧ͗̓̎́́ͯ̓̐̉ͮͫͪ͢2̥̯͚̼͉̦͙ͧ͌͛̒̃ͯͭͥ͋̚̕̕͜͡ͅ2͇̖̭͆̒ͪ̾̎ͥͣ̂ͨͩ͋͒ͪ͊́̚͠͠2̑͗ͬ̃͆͂̓͗̏ͯ͟҉̴͘҉̳̭̗̘̤̝ͅ3̴̵̲̗̘̹̠̰̳͙̮͙̍̉̓ͦ̐ͧ̾̍̚̚̚̕ͅ4̨̲̜̱̦͓̝͍̳͕̩͌̔ͪ̾͗̉̇͗͐͛͆̀ͅͅ2̵̱̦̬̜͓̻̥̲͓̀͐ͫ͟͝6͔̮̣̮ͩͨ̀ͭͯ̏ͣ͂͡5̷͕̠̭̜͕͙̦̘̦̱̖̬ͤ̌ͫ̈̅͒̇ͯ͢
̸̵̵̡̛͓̻̗̖̻̗̼̤̰̂͛̆͌͗ͯͭ̂ͥ̈̂ͤͪ͐3̤̘̫͉̘̗̜̲̝͇̙̫̯̲̥͙̦͐̈̇̏͊̓̇̈́ͫ́͘͡ͅ2̛̣͓̪̖͔̺͍̝̫̳̱͊ͦ̿ͨ͌̀6̗̪̠̻̤̤͓̜̫͈͓̐͂̎͗̆͗̂͋͋̊̈́̃́3̰͈̠͚̙͉̲̗̭̤̝͇̩͔͖̦͓̹̯̉̊ͩͧ͐̃ͦ̾̀͘͟͢2̵̧̡̧̻̟̰̻̰̪͔͔̲̮͚̝̖̹̣̞̠̍̿̄͆͌́ͤ̀̅6̴̜̩̝̯͌͊̿ͫ̆̕͘5̵̡͓͍̬͔̒̍ͩ̅̎̍ͩ̉̈́ͫ͐͊̓̄͊̒͠͞ụ̡̜̥͙̗̻̺̤͇̥̦̗̠̪̳̗̼ͤ̈̓̾̆ͥ̅ͥ̿̿̒̇̓͟n̵̑͂̎ͪ́̾̃ͨ͗͛́́̚̚҉̶͙̰͓̱̳̯͓̟̺̤͈̥ͅn͒̿̏̆͏̳̯͍͎̫͇̮̳̼͎͚̜͓̦̝͜͟͡5ͨ̃͐ͬ̔̉͜҉̨̯̥̗͕̪̙̭͚̳͚͇͎̭̪͙̣̺́e̶̡̧͈̬̻̼̮͕̯͈̖͚͙̬̗͕̲ͬ̾̾̓̔͑͊ͨ͂ͪ̅͋̀ͪ̂̑̚͟ͅb̸̧͉̝̜̗͉̫͕͎͓͖̙̱ͩ͌ͪ͒̊̓ͦ͂̎͗ͨ̀̀ͮ͊̿͐͜y̅ͦͮ̽́ͥ͆ͫ̊ͩͪ̿ͩͭ͋͟҉̶̧̰̦̳̥̬̼̩̟̹͖͕̟̞͈͓̰̠͈ͅ3̷͕̮̤̩̳̙̳̮̹͕͇̱͖͖̋ͦͩͧ̃͊́ͩ̽̉̓̌̋́͟͝2̴̗̯͉̦̪̯̠͙̩̩̦̝̪̯̘̈ͨ̏́ͅ4̧̡̣̮̖͚̫̙̿̃ͫͫ̊̍̄̀̓̔̏͒ͦ́ͅͅ6̷̼̳͇̱̖̙̯̲̤͈̼͍̤̰̬̺̺͕ͭ̂͗̇̆̿͋ͥ͛̏ͫ̀ͣͧ̏̈́͞ͅ2̨̰̺̬̮̤̬̬̰̄̇̔̽ͫ͛͗̓ͯ̌ͫ̑̈́͘ͅ3͍͈͇͔̯͍͓͙̺̮͈̖͍̮̟̗̝̝͂ͫ̃ͤ̏͐̌́́́ͩ̀͘͡ͅ6̺̞̦̻͕̪̫̹̩͓ͫ͌̋̃͋̀̕͡͝ͅ3̏̈́ͧͬ̈́́̊̈̿ͯ̑̆̇̊̽̌͐́҉҉̡̨̪͉̖̖͇̯͉̥4̴̧̰͈̭̼̗̹̻͕͉͈̱̜̺̳̘̣̠̼̹̓ͩͮ̾̎̅̂̉̾̐͑̿͋͆̋͐̏͘
̴̢̭̰͚͎̦̟̜̫̟̰ͣͦ́͗̓̄̒͘͟3̢͙̹͍̹͖͈̙͚̱̰̝͙̗̙̹̗͖̺̟ͦ̑́̒̆̊̐̀͠͠4ͬͪͤ̏́҉͡͏̦͚̮͚̖̩̖̞̱̹̥̫̥͉6̡̡̛̜̮̭̞̰͗̾ͧ̇̃ͩ́͊͘͞3̜̘̘̤̬͚̫͉̹͖̘̰̩͇̖̳̺͇͙̆͐̈ͤͥ́ͬͩ͌̂̌̂͗͗͒̆̔̀͟͡͡2ͨͦͥ̓ͪ̎͏̵̵͈̯̩̼̬̦4̭̼͚͕̪̤̱̹̞̩̤̬̞͇̭͔͔̰̰͋̎͑ͫ͌̐̑͑̿̄ͯ́͡6̉̋́̾̌̍̒͌ͮ̕҉̯̘͙̳̲͙͍̞v̨̢͊ͦ̀҉̧̺̳͚̫̟͚͍̘̼̹̳̘̱̥͙͕͍͍̀w̵̨̳̭̖̘̮̩͔̘̱̭͍̰̗ͤ̇͊ͣ͂̆̋͢͠t̪̯̹̯̩̝̝̪͖̯ͭ̒̍̔ͤ̈̈̿̍̌̆ͮ͌ͯͮ͜͞ͅͅͅj̦̳̫̙̫̝͇̟̩͉͇̲̻̙̼ͬͯ̾̀ͫͦ̾̑̇̔ͪ͜͡r̴ͧ̈͗͋̑ͩ̾̽ͧ̌͌̉̋͛͗̔̔ͦ͏͇̦̥̝̮̳̦̺͕̫̹͍͔̞͝ͅͅͅw̴̛̖̙̻̞̭̼̘̹̼̫̲͕͓̗̘̹̋̏̅͊̎͋̉̾ͅt̡̧̳͇͚̲̮̻̣̺̝ͧ̏͂̅ͤ̕͝ả̗̜̯̻̗̝̜̼̪͕͓̭͍͂̇̐ͦͨ͌̽́́͝ͅ3̶͉͕̹̥̟̺̘͍̗̾̂ͫ̌ͯ̿̋̇͛ͪ̾ͭ͒͛̄̂̓̚͜͞7ͧ̒͂͊̆̽̓͏̵̢҉̞̭͖̼͙͎͚̟͉̻̹̙͉̣͎͍̪4̇ͫͧ̃́̾̎͛͆̿̈́ͭͪ͑ͭͤ̚҉̨͚̙̝̺̯̪͕̬͇̠͖̘̞̬̩̣̲͜͡͝5̵͓̘̝̻̺̺͈̟̯̟̬̲̘̠̜̥̻̦̬̓̋ͪͪͦͫ̚͘6̵̧̺̟͈̜̱͚̜̱̪̯͖̞͙̳̲͍̃͊ͫ͊̽̒̐͢͝8̶̷͔̦̹͙̔̂͐̈̆́̆ͤͪ̽̇̆͜͞5̸̴͉͈̺̮̥͇͍͕̦̗̏̂̐͒ͦ̃̌͌ͧͨͮ̆́͘͢7̹̤̪̺͕ͮͫ͊ͤͣ͛̉́͢3̷̨͍͓̱̼͓̥̘̼͔͎̲̗͈͕͖̭̽̑ͧ̃̏ͤ̊̂
̵̲̖̪̜̫̱̫̻̜̫̞ͭ͆̈́ͯ̋̆̓̀5̢̢̱̺̞͇̭̩͇̹̙̰̰̳̰̫͓̮̙͈̘͒ͮ̄̎͛̓͊̌ͩ̚͢͝4̷̩̱͈͓̺̘̓̉͐̑͗̉ͩ̆͊̂̒̑̈͑̑͌ͤͥ͘͘̕͝6̡̫̭͍̤̝͔̯̟̗̬̣͈͉͇̜͐ͯ͆̌3̸̷̨̦͚̱̭͈̖̖̈́́̎͛̒͌̽ͫ͢͠4̵̏̐̄̍ͦͭ͒̒҉̢̠̯͕̱͢͡ͅ6̨̯͖͎̮͖͈̩̤̺͚̥͚͈̰͔̭ͫ͆̽̀̿͡7̱̩̹̟̖̭̗̤̮̦̭͕̳͒̑ͫ̊̉̄̇ͥ̈́̽̊͆͝v̷̴̛̟̮̳͈̘̰̿͂ͤ̀̄̀ͤ̍͊ͯ͗́ͨͭ̊̏s̗̬̜̥̟̬̅ͬͣ̇̐̒ͭ̇́̓̍̅̀̕ķ̷̺͈̬̺̠̩̣̭̗͈̪͆ͩ͑ͦ͗̈ͧͧ́̚͡͡h̴̢̧̛͍͍̗̻̘̮͍̀̽̾̓̏ͅb̨̳̜̘͕͛̀ͫͦ͐ͮ͛́͛̏̇̀̕r̛͔̦̼̀̔ͮ͛͋ͪͧ̃͛̂͛̂̉̐́̚̕4̢̡̻͚̮̹̹̙͖̙͓͚̮̘̟̼̝̮̂̇͛̃̈ͮͧ̊̎̿̽ͯͥ́͟͠͝5̨̨͎̪̮͎͖̩̙̫̤̫̹̟̩̮ͨͭ͋ͯ͋ͮͯ̋ͪ̑̄ͧͭ̆ͤ̈́ͭͩ̚̕͠3ͤͭ̎͆̽͒̈́̌̈̽̍̓̏҉̫͓̗̩̺͕̬̼̦̘̦͎7̨͎̮̯̼̙̜̪͕̭̺̞̯͚ͫͤ̆̋͑ͮ̉̅̇͐ͫ̀3͊̀͆̈́ͩ̊͛̍́ͣͤ̓ͬ̿ͨ̓͑͗͗͘̕҉͉̗̥̮ͅ4̴̴̢͈̦̤̼͎̼͍͔̝̳ͣ̾́͑͗̒̎̐ͤ̀ͯ̋̚̕͝7̡̡̛̻̩̺͉͆ͦ͗̒ͦ̽͒͊̉͌͌̌̏̇́4̨͛ͩ̍̽̋̉ͪ̅͛̄͐̈ͩ̄̚̕҉̻̘͔͕̤̬̗̹̟̫3͈̥̘̼͙̤̖̬̺̥̠̜̖̯̦̐ͪͮ̈́̐͗ͤ̔ͯ̈́̐͊̚͟͡ͅ5̢̘̭̬̺͚͔̱͓͇̘͙̗̫̮͙̲̜̃͂̈́̏ͥ̐̇̐̈̇͆͂ͅ6̵̷̛͍͇̥̺̼̻̺̥̦͕̆ͧ͐̓͐̏ͦ͌̾ͫͭ́ͫͦ͆͛̍̕͝
```
[Try it online!](https://tio.run/##NZpJb2vXcoXn/i0ZxOqupw/IMKOHABnbgGHjJTAQ@@UZb8ZepCRSFHtSJEVJbMReEq@kq/4P7D3xH3K@tXQDgaQknrN3NauqVtU@/7r7/Q/f/vjnn1shF/IxE1JxHC9DNpRjOc7iIg7jVTgIB3EZTuJpOAxX4TTcxeOYCINwHcZhFF7CWTjbDrWQjau4jFdxEt7iSeiwzAk/6ZAJ9@Eq9sIdF3e5fBP64SnchscwjvnwHOZxP6zDIqxiYzdO2P@Q3crsfMmtuTgOk/AlfImN8BI7YbqFmOnwHkpceBKnsczO76EaLuJZHLDTc6yzxyNCjcOKNff5exRuYju2@a4W5qH/l1iJqXDE@gfSL6b4@zIU4lHISM/wOQ7ieezFs/AUiywyCENuayP8Yyx9HxKIVbQEay5OoGGK23O867dFKLBU748CMujG59/CcajyVTqu2PMQ25b@KLB@PvTCNDx/jwCXrLePypM44usD3jEyFpmGdswjQhstGvxW45YW2g1jNnZ@06VsVmGtRHgI53x5jdq3WOkG01ZRuCFVZ8i6H9NxHopxzaWn2Koaulj92TZahkveb2Lpr/EAD5d4ZeMc35cR6QhBPvPzBXWuwyyW@GzavDeh9Rc8nUb6KvIn0fxLmODnXizyU9OqPwGIUwyVw0npmAQG9XAZS7xvvMIy3H4HXjJsk8RqXS65R8IF8t3sxSnmLWHsEyyHppi7Gl4RvhdkvSUrbBB8HPpgo4WZmt8hz4wLD7jlGCfK/lMuHbJp@/9vQIVLbNkIjVhHkPkuqydZW@YXxvdx4lTmAnm18EocrLHHONQFLyGDRQTeDQrO7MUe8J3yv2u2aPFq7mHnKcsehgo2H6PEPmhdCWSYoYk5Z1hfMo2Ro/eBE5a45n8F3tfhLNa/AxgLnHYExDpIcIA/9nk9CFwxgRzXhvNQ3tYtAKPH63JPXmHnDv6Yc0k3Zj@FBOJ0sOUBWpZjkwB94/er2A91oIqrEKbHxc@sNA@jWPuO0FOATH3ZBKkPbaI5sLuPydgScmIWdWdhjRZr/mp8g7IJYquMHXMA4pi/LsHAASg9AnhKAz2APeDyJk4ebzvdHCLaBADfYxU8hhHHuLO7i@ZHeKBCiCknJFn1Sj7AgCMuW8pk36JImlcn5PF6yoGc9E@dLPOE/xtboUYuG2OWXFReq6A/eSa8o1SS2HQoKFpQqcENVSLokiS1xq43CjZBOkx3WVuJg5REhJ7IcJiuCwRWhvMTso/w3iN/P7HAM8Csh7NvEa8Akjpg9wBrrMhvM3bOWSb59IQQUFC2WO4Ul9UJ@PoWBksgaAYokpaJEZCNAzO8H/L/KX7IxYvYx6Rf2G0eNkRdydlBCeA2VneIu3du@NA4g@tOeIEhWZDXBfmtjaiIiY7PeL24hYBztEyy5imCTGN9j9hTcOeI4wrbHgOHERK/858MeEzi5c@sdYfb5gC3wZq3/KwQqkWgFfhPVcn9P1hoHyeM8bfSjG5vIv1pUByecfPqF5UQbFICM4fxNB6x32eQfo5p@6wnfzw7yz2zcj4MFEb/zuUrlJRyaax0hNopgngd6qx8jGgXWOTDM3McOcBGUyXKf@GGFPpk0GeBS9NEGTkvKCqu0OaG25og4gn5Sbvc2uI/j/9DdB3gGwVTDoiWvqb1MiHaogq1WOAcX9QRr4jy@xh3QFwr044pIpfs30WCwY@goIO@@yDhkNx2R14jCDB8ib3r3NIPm1/BdAavpIBsBU0nZJQcQs8A7kj2xPxXUYK1gnIJOPhvBEvxxQleK7PixBm8x3rk7y1yU5qfFHV0EB6A3BjjPmLQDpZpoWJVScUhsACIBdzZ3WajdzLijDUzOJC/2PYdu/WpzOeo1uN1ze3Xu4DkCuvPFFoYU4kLb9tCSb55p6zec9utK0Q/duL@3xApxQVkeEIszQ1zIC7WMQMHJPLwBTF7FmiEoAVFKkads98QMy9/4vYTBCpE@WBKymhipfPYxaQT5ybZ/4zbmxQfVdRZEEjbhHoWEyNoFSScY6W62I0RNg2znySG0VRD8S4XXOAe/Mq9gOMb1CzLCeRjshpYHGHh7BZozKPGEpyoPiJbFIFKskqRTxXTB@eGMVaesdETt5I9@X2@TVAP0T3FtvfY9mu556LLMNxRDqbWCmvy4GsUV6iQ1kQt5iDk3AgcoMIAgTq86ty@7woIEkXasHgbL6sIj/YQEfSL9bGYYFzEEhl8fKIQZcEUPGhAhiQ3iVjxWsXaNnqdcqHQV2HflQOVTIWGNSRTMU3wM0CaJGAeotvYBf8M25NwwD/Q5me9xT5F/F1DggImKgH1CtA8IVs@cHOfmLj4EBqxhyz2xM0bCFBRVtnDnvAwLq9ihUM@r6hGirgXIQv05h3tK/a9DI1tyjJpgswippMnxR4ibA1lEvyvDzQ3AEWpgpyFufq2/IY02DZharJsQ1Q5jdGqYFyMiqKGgXrYvIlQHQJXPO0M64/32IHiL96CV@UijEIaEGqvgeDLzwjySkyQ7kCZ3N4DGxcyssnFwKh4dDKd/og/psidYq0xir@ielMBBiBe@UwAUUJLAog0ipe7flUJgJl4rCLnVy5PIPeV39NxSApqmuRroXcCTexEmUSMqQHlrZknNjBNbZcdR2Akb@d3yC/wCQIPwo@re6gs@j1jx8fwsoWQC1atoF2Ote9dVVQezhCki2A11/mGduO1Cb1tPHFEPrwiCiqsfYp5qZCI9IzfV4CmsYeqFRB3wvuUC0swnTQXUpMxyTE3J4klMeYsDhMdm7P2JRG7sGe6pCgRBVV/pF4ioti/GFaatCoC/hk7PqD@gFePBV5ABMwKLPQRHBDjuwFid2J1S5FAuKzZWylxn8VOcVNCfsSW5yYRXfa9AcRVtL1Fls02xaODUdYU8C7uPgc8QlxD@Q2ULdlnyGdzy0yj4EYFeoqX6iBc7VBJQMXgXS4TcxSBA75bzp9pVq8oO6HRktuyxDGo@UMUm5bCjPnDS9f469G5@4XYGofZFoaRt8hW8he3nFFAZM@OKDaGUG3oIaa46iY8biHgEf46IfgpUKh8SiA0cHJNX6PLvjNHgf3a3@AfWWvOT9mEIuf6WcaOE74pY8ec6C25em22jpntghv@mjk4Z8CA5oOlG9vcuhR8SYAJAigZVfbVEOYxmuza9QuPoTf1Dz1vVFvFlln4TJaOtR1hB@i9o/Urn6I1ajM@c8k8FkSoy2JSRHNF68Ukrr036xfrXjuWFfJ1xCatof1juFGnugZeV@IECDF0kVTve4YgAwR54jUgwrIIobw43XYoZonxHE44UjvDzylGKsdLzKJ9bwjFudPZkN1uzKbnvNTc9sM1wrJADWtOQOMJCSKluAYSqhwpL0gFxjj0P@F5GyGvABeFGvgeIm7G@SThDLPPN1OWybO3WPFK8CWM2m5exJZhfDtuKMbuAkvsnidCc7znwe4b38yDCKcqcdtan22B/hIRKAKraNeg4Ji81cXg6gybIFR97EcSelGXaCQt9hDwUKma3Kt4E80pksHSLEeDDQyPEbSEOxZeQDerOxEXg3vtgNE8kBu6Vb1QUJIps6ZNM@/0bIirCtTkPwFqgiNOPwYRnm1kCdkWqMyqUdom1ppggjpFyHecb2ksDd1rQrTq@QHdww73XonmIMAQnGccBwmwMTA@qmx4y4XqTffVXu6BZ3V7B5jyFc8UqYJEFpsX3dQ2hDmNBX5i3WkQA8jzWXTT/MFJoU5YneaUVbvqfn/Tl2aaKb4cEiH12HdIjUATxUsdlSR2rN7i5yL6NNHg7O8kyCN1H5hvzvqvLtUqBUfmHLRHosb4V4ttNNggmSxcfPqxKjutUVhRekjRmYpZIHRZtYxcpdlInXrf5Zaeevk91v9oV2fmv2XzjQcETprnPmOEM0QbK20ZNCPTwdsw2gFPx7zeMO89aw7UyGCpEl@qRVuDrhuC7oOQg7Yw3CY@aLWhHmUjdsJeR3j6VH0u3jlXOgMUMorYcc8gWbkkLWN@C31mwHKBsEfg4ZXd8x5mnLKPbpj7YhW@NjsO@X1ArE71TvC395Sm0Vepm3SN4J@V7bBpwbv20awdxt/g1lcXhDd@uwMRbQ@EeooPF7meSB3OGPFXUzrG7M/qi4mNBJ7LYOxjdOsgsFqDMt@8kjDvWUzTkrp5qDokwaGhHtxEBVq/A24y5KY3UsuQ8DvQMMC/a0KTQIEk8swJi4ULXt3JrRFeftTYhnrNzuIDakS955EJZ87M@D6cu1b2TO5k3eZuVPUSkVci3jhOCWSEaRKlDUHae7TNCxf/SZLKWcsMyTPpsRg1mbxe4X9LslMSkDWh03fiwqZCU9FIJZu/OmyqmgMBhCuWOvBQIYOQRXJSX5nXoHvE4ut/46JJ1Fcd1@JTzJ5VEVUzSmVnhYJYDF8nWaWInZQMywTqqeenp0aEvKWR3rUTsWKuJm5Z5JaqRgOwWWmUDx/d/9jRdgxGLkg1mnaWnG5mQZNBUT6aVLRq74rNulqN8dIxAt5j3AcCZV/0FGfKM12PnGjDRIiwYe2fiEeFUIvH7W8oAOfwiIRmQEhxe/DqjlqDpxVhNPZgtMlr/Ts4SOJKUbGMkj3/vjSHWngIQyuypUGeJknkai720E0dYoH/0loCH9dbc/UXbiRIvhbUFZ@iXW1V/S0ZHx1F@@xi4HzoVl@VfgRKOmIbUEsiawsbagL6pmxlmpdSvsS2/BfsJYV7/NYIS4nXJCzSgDIlsADYdTwTIfZkZuNxV1M9J0SVlTr4o4CvNMTpaOotsKiBxKhcZkxoSL5RqYztHSBTkyisXCC3N5XU2IsiYC98zGw/Zk0bj16yW2C3TL698zD6xhm1i5@fUZNMtGcCLHivlfGQ@lyO0TRvF9/RboAe@DebrUmEF5pIkPK6LuBjTdkcogv1sZrXkbtMZFPYNO8uY4bjv6DQnWtP1dy04Xe60nC9zdd5gH4M0KquaHNnTI1rWmJOvDdRTZVtH@@BE@TOkp7YfwvzawZ3pckgVrhkfYG55qm7BxnhZo80k3KbkzOTUf0/AGAaJjfNolQJVGW67Jen0pgsq76UuUgzvzMX7ASgVTvV0UjDDlrKj4g1VdzJ9rhrveXJfsbkK4kNE5CUidWfsJOI/7PH4DXX65WZsMiexoUDuj1TrTmpqC7UeMxDAd71HFgTu5I/C7ZU2VbLeDg6YIc7irEIwyLW/petdczxhtp0JLze@al4jH/GpZesLCM23RcNPXkY89cAk6iivfziFqfkKYxSWQczN3EyKQnL3Ym@cvs1IVI1s17z6QkmRhr9AmTUzOTisWJKXbFJVMlHNRp2quh2DMVx6O0CwjTaLCDeNBisfcUea0RqqhlUH8nFG/fjJc2LRR/D04/c8OZRdQ3xNCLRScwMbUXxZiS9E4SUthMcq7ryDOqUClTBGx5jLLzF7Q84/Aiw0jIqHj8Q4w43QW6RS4AxyWESNUaiY@JzThSU3HK1w80/NeEn/0NrSBM5PHjgmv7OuyaRygITypROvEQ1Fl9HiI@x4dnpGXUc8KkvjPltKM5YEFQ9Z8EpyxbMKFSZHhTLSviedG9C24cYj6Io0NGGSgCMXPWUZNJEVw3oZqabAzSe8jM2X12H1g5u0kEF4oJbleEqxjwmt425XRP1S25c2Vgal7X3HN1NF8t39BoBiWMROrLHxJPQvioFztp3amgrYA0KTT81h7p2Pn@K9S322/cBicYpTey@dsYRxW4ZAddcuJCedt5C6SLlEa2oQDnoyCdp8ySUMsBXHoDUjLSq59Ir@1kMWlRPRba3x26yYxrhdQRSjz3Pk8YfgwcTkEeN8LetzQTCkWGXA9LUu4/rcq7ur2o51U2Zdly5sdSB0L7tPdpBG53fiGZlAWKB38o0D@@uyYduq1u4Z@Kkou606Qlq3fMmFdcnvNoSz9BZ5DdYVwSkqXAnipWPzrh96blWyaOxrjopmWiMkEkuyiFmOWhcdBHl@EcMIbjlSWCa719jECWAtg7kQPGTGjExUFG8pE8Yjz1gVJJqgJqG2@ZHE@URTS3ivLlHhI4j3AG05NzjNqUtUWOayW1zdLUsI50BKMwwx5EwxI@ErLHPOa6QBi3XxsVH0yxhRRxxhsrrRkNO1eMrT2o0py@5P7lDIzXSLyKOOx4Vn9jJohwnTsZrdkjKzBqu4eSh9RB/VgfcN2mtmUnR/RYcZW@mbhWywsoHXASLqTc9IXbs/8O1R5X3QpFNdXhSgvL5hcYcLR8hy4U3yrPqhGLxd0y7H3WEQ@sCCujcTMI3npPpPIxS4luWH0T170Qbid8sOS8Eql1Sq4ZYa967UfNFRTKVx5PGnlGu8dv6b5h7jR4JH0S@gYp9H2OJ5CgJzV1PVcDO1Ce4a3xWE/ur@CbeOcR@U2585e8j7KljIwVqzbPWz@R23Tz2bGtlKjxWXLPoo6erYtz937HmsSeDmuArDj5TrLNODaKPwr4mMS/cpoaxaoL0@HdnEzp8kNOjFqp8bjRC8rnQs9J/6H1PtUj53HtsEvCKQEnX9S4mefasqatJLgbRylh1GwGUQ7Af1jzEHadmVEvNu9ym6xBeM9BuLHiyNXJZ8@nwJ4SqRE1D1FJXjT65v@/Z@wtuVlHTbNJEn08dVRfDbId95krnBlbJ85h3sssSd5x4b03WyCMeA3fclT1p5ir6qqG7I6HvA/3LcLtLGjhE7I5ZvthdywdMPRfzJw8/1j6tuOW/A5X6j2567@NsxCPjCvEhWniBZQl9bur6vKrrlkAHsv2vgC9@h8tTZmo5FNDxwowFVALUHstUNVZ/jO1dXJ3yaeFYwxRQOvFkLWdSdwET/OwEp7Z35G6iLtbxyfxdE8pLXFCAbiWx3xAxgNM2W53YdsdEwQHrP2CnomnHC@8jn6zV3J033chAxb/xxJjA9yAsjaIJvtYkXGnyhtezf@vrsOnjXFteUbk9Ikf1fOR34QGbs4NzkHq3a9FxXnOdSOrhCtXQqs6NPCkreJIiISuuYyfuekh@qN/y9EGPbNy41AOqPT0bABaOwPfcQT/0Gfra9WrhxwwUmN1tF6GSmhbjfK4TIE9@LpyilTHyKkA7eKCsx0s0fSO/VkTVMKgOngZ4lTYoZlUDhWCaPIFOzsZ8K9cGpcQnnXaSxvLu05afWOfEFEHHx/sok/FJdA5lbrhBz3I09NQCt@ppiqXGKf9g7ZT5L6yCz6IHOE2d4AF4tZUP1IvPnoJsZMZw/RvRvqDFIqBRc8ln0iPBLGZL2B5dR@Piv9haxzBj1ssDDXonAHbug8oH43/hAYmCZelh4Oxnj5zEFT/Omk/J2UXP6p5JEC21jD/4EIdciVNW/K6HBTSPv/L2G5WnWP@VdWr62mfwImin7n1U4jvIrfHSqcPhZYd/kl7UgatrRecSKecVK6gUDih4fhDF56bwN2eMhk8U9Xfr6@MYq11Tb3HINa@VIO0WW9xk6WBUHplqrG9AlHRSQ9pRxW776Y65PTQNq20uXvphmlfNcoCdJq06sDv@o2BIN32WWDc9dX8XS58wydDlSk/RFPCGzv/nHj0CGrD64iebZh6RikrRP2/rjMgRqKc/Tv10zyW7p6HsatjS8cQEoKXaSp5sqqcLK03e3rj0xDPRkp7hwqoJ66yYrOsc@uvYQKcNL35MqBc2n2LOaKj4GLIS9bCPStaRPajWMylLW7vCDt6bItJr0Imx@oWPgb3Gn8oEWPIPpfAWWaVuhvDxvNJ8O@iRtlXUAxFNRKtpJKlTe1x0DifPqvdxOmpzW8MoHDn/aqA73g06ys34jKhslNP6alaAZjpmWijwPFPWyWFL0wePRlZ@HqK7h7P16E3a7HHs4f7cD7UIs5oxF/0sxJ0HoUW3dE8aSVuKcaz/@ef/AQ "05AB1E – Try It Online")
[Answer]
# [???](https://github.com/ararslan/qqq-lang), [posted](https://codegolf.stackexchange.com/a/155781/12012) by [Riker](https://codegolf.stackexchange.com/users/46271/riker)
```
The Man They Called Dennis (a song).
Dennis: a extremely decent golfer.
PPCG: a group of golfers.
Act I: Chorus.
[Enter Dennis]
"Dennis;
The man they call Dennis.
He took inspiration from J and he made the lang Jelly.
Stood up to the challenges and gave 'em what for.
Our love for him now ain't hard to explain.
The Hero of PPCG: the man they call Dennis."
[Exeunt]
Act 2: Verse 1
[Enter Dennis, PPCG.]
Now Dennis saw PPCG's backs breakin';
He saw PPCG's lament.....
And he saw that challenge takin'
Every answer and leaving no votes
So he said "You can't do this to my people; You can't let long language's answers win your challenges.
And Dennis booted up TIO! - and in five seconds flat,
FGITWed, all your challenges."
[Exeunt]
Act 2: Chorus - revised, since my program is ending soon
[Enter Dennis]
"He took inspiration from J and he made the lang Jelly
Stood up to Python - and gave 'em what for
Our love for him now ain't hard to explain
The Hero of PPCG, the man they call Dennis (song slows with a dramatic high note finish)"
[Exeunt]
With thanks to Dennis for providing a character for this program, and Jayne Cobb for being the original Hero of Canton.
```
[Try it online!](https://tio.run/##nZNNb9swDIbv/hVcLmmB1MB2TE9F1vUD2FqgxYph6EGxaVuITKaS7NS/PiNlox9re9gC5EsUyfd9SD88POz3tw3Cd0Mg3wOsjHNYwlcksgEODASm@jDPsvFkCQbwMXps0Q1QYoEUoWZXoc@z6@vVmV6oPXdb4GoKBMk@KSJcLGHVsO/k/@9TiuinLvfZbPxxnKmUVqRElVKIlOlKnp0jROYNWApb6020TFB5buESDJWQ8krURHCGarhE54Y8u5GkEkRN5BQrGvVHNYaUVpseYY4t7BoToWIxcdV5cCzH8g8a2wLxDoyleYTG@FIL4ePWyUme5J6jZ/U6mo8fGZiJ50fsKN6PML4s4aegQfj8GsYiFcrvsx/SdppCMLt0Og@wNsVGPj2ajUg6Viwvos60Mo9cX9nJSEWjUc09OYeYcrPTHv0gFMJOmisMh6a3go4Yeo4YshseK9gSZr@4Ez9KoVSSokpAtANskbcOj@E57lDesjRpDp2pcR6mLgF2lmBgIfw8h1Hp5HTN0jjN6/bi6hMcJV2SU1kZSMCCqQxQORMX2bezi9s7LBegkP@u@Q7tcfWkpMfeBk0MlgpMHjzX3rQgApBKRRCY6c2S/tcKvtrA6yE2knT0/u79w@q92bzFh5sHB/oEQ3C8U/6xkQe0FLeiv5AmdSNdorS0crc5fAnuTi/L7tAmDXsqp9oEWG8TKKPUvSkUlEbSZkw8F8nmpRkIYcXrdbqwRk1Tsextbcm4Jx8rQ5Ep3@//AA "??? – Try It Online")
[Answer]
# [Cubically](https://github.com/aaronryank/cubically) 6×6×6, [posted](https://codegolf.stackexchange.com/a/155519/71256) by [MD XF](https://codegolf.stackexchange.com/users/61563/md-xf)
```
[+1[+7]35@]100
```
[Try it online!](https://tio.run/##Sy5NykxOzMmp/P8/WtswWts81tjUIdbQwOD///@6ZgA "Cubically – Try It Online")
[Answer]
# [HBL](https://github.com/dloscutoff/hbl), [posted by emanresu A](https://codegolf.stackexchange.com/a/247363/85334)
```
-0/(*(*%*)2)
```
[Try HBL online!](https://dloscutoff.github.io/hbl/?f=0&p=LTAvKCooKiUqKTIp)
``|\X]-` in ASCII/UTF-8 is represented by the bytes `60 7c 5c 58 5d 2d`, which represent `-0/(*(*%*)2)` in HBL's namesake [half-byte codepage](https://github.com/dloscutoff/hbl/blob/main/docs/codepage.md).
Inspired by [this message in TNB](https://chat.stackexchange.com/transcript/message/61139641#61139641), which I'm pretty sure was about [his other cop post](https://codegolf.stackexchange.com/questions/155018/the-programming-language-quiz-mark-ii-cops/247382#247382), but I did a search for HBL anyways and lo and behold, 9 answers exclusively by DLosc.
[Answer]
# [xEec](http://esolangs.org/wiki/xEec), [posted](https://codegolf.stackexchange.com/a/155024/61563) by [totallyhuman](/u/68615)
```
h#1 h#0 >a p o# h#10 o$ p h#1 ma t h#101 ms jna
```
[Try it online!](https://tio.run/##q0hNTf7/P0PZUCFD2UDBLlGhQCFfGcg2NFDIVwFyQDK5iQolYCEgs1ghKy/x/38A)
] |
[Question]
[
Here's a simple challenge, so hopefully lots of languages will be able to participate.
Given a positive integer \$n\$, output \$A076039(n)\$ from the [OEIS](http://oeis.org/A076039).
That is, start with \$a(1)=1\$. Then for \$n>1\$:
$$a(n)=\left\{ \begin{array}{ll} n\cdot a(n-1), & \text{if } n>a(n-1) \\ \lfloor a(n-1)/n \rfloor, & \text{otherwise.}\end{array} \\ \right. $$
### Test cases:
```
1 -> 1
2 -> 2 (2 > 1, so multiply)
3 -> 6 (3 > 2, so multiply)
4 -> 1 (4 < 6, so divide and take the integer part)
5 -> 5
6 -> 30
17 -> 221
99 -> 12
314 -> 26
```
More test cases can be found on the OEIS page.
Per usual [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules, you can input and output in a generally accepted manner: 1- or 0-based indexing, output an infinite sequence, output the first \$n\$ values, output only the \$n^\text{th}\$ value, and so forth, but specify that in your answer.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes in each language wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
R×:<?/
```
A monadic Link accepting a positive integer, \$n\$, which yields a positive integer, \$a(n)\$.
**[Try it online!](https://tio.run/##y0rNyan8/z/o8HQrG3v9////GxuaAAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/o8HQrG3v9/0f3HG5/1LTG/f//aEMdBSMdBWMdBRMdBVMdBTMdBUNzHQVLS6CYoUksAA "Jelly – Try It Online").
### How?
```
R×:<?/ - Link:
R - range -> [1..n]
/ - reduce by (i.e. evaluate f(f(...f(f(f(1,2),3),4),...),n) with this f(a,b):
? - if...
< - ...condition: (a) less than (b)?
× - ...then: multiply -> a×b
: - ...else: integer divide -> a//b
```
---
Output the sequence up to \$a(n)\$ with:
```
R×:<?\
```
[Answer]
# Scratch 3.0, ~~29~~ 27 blocks/~~234~~ 167 bytes
[![enter image description here](https://i.stack.imgur.com/WvLEx.png)](https://i.stack.imgur.com/WvLEx.png)
As SB Syntax:
```
define f(n)
if<(n)=(1)>then
add(1)to[v v
else
f((n)-(1
set[d v]to(item(length of[v v])of[v v
if<(n)>(d)>then
add((n)*(d))to[v v
else
add([floor v] of ((n)/(d)))to[v v]
end
end
when gf clicked
delete all of [v v
ask()and wait
f(answer)
```
[Try it on scratch](https://scratch.mit.edu/projects/454951272/)
I'm a little unsure of some input/output methods, so I thought I'd be safe and just make it a full program with a helper function.
Answering this allowed my account to be promoted from "new" to "standard", so that's always fun.
*-67 bytes thanks to @att*
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 221 bytes
```
,.Ajax,.Puck,.
Act I:.Scene I:.[Enter Ajax and Puck]
Ajax:You cat.
Scene V:.
Puck:You is the sum ofYou a cat.
Ajax:Open heart.Is I nicer you?If notYou is the quotient betweenyou I.
If soYou is the product ofyou I.Let usScene V.
```
[Try it online!](https://tio.run/##TY7NCsIwEIRfZR6g5AF6EQ8eAoKCIIh4iOmW1p/d2mxQnz4mtYfeZme/GSYMj5Qqs765T2X20d@z9gpbm4MnpiLOG1YaURA4blCoS7nqk0R4pzN6rKeCye0DtCOE@IS0xXATOKV2AzE6cqMaG2DBvc/1X4kr24JFF/lXFO2JFVfSNxFnCNZkLMiCGkZpYh4t7f@/JUUM8yiT0g8 "Shakespeare Programming Language – Try It Online")
Outputs the infinite list. Note however that there is no separator between the output values, so the output is somewhat difficult to read.
My best attempt at adding a separator (a null byte) comes down as
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 297 bytes
```
,.Ajax,.Puck,.Page,.
Act I:.Scene I:.
[Enter Ajax and Puck]
Ajax:You cat.
Scene V:.[Exit Puck][Enter Page]
Ajax:Speak thy.
Page:You is the sum ofYou a cat.
Scene X:.[Exit Page][Enter Puck]
Ajax:Open heart.Is I nicer you?If notYou is the quotient betweenyou I.
If soYou is the product ofyou I.Let usScene V.
```
[Try it online!](https://tio.run/##TY/NCsIwDIBfJQ8w@gC7iAcPBUFhIIp4qF3m5rSpa4rb09d2m2OXkJ8vX4izrxAysX2qPhNHr9sY1QNjRzPIXBQaDabkujOMHSQQlCkhsbdU5RfyoBXP6CmhfcMTMG8l5QQXFlULXA/jmXG3cbFGcP4NVKWGWunOiy4p/rrl9sGigRpVx0I6kGAaHecD@Y2swBCv/B9P3KBhuCN/EU2EQIqIOVpRtqPSx9epmuZ7ZPBufk2E8AM "Shakespeare Programming Language – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~47~~ ~~43~~ 39 bytes
Saved 4 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)!!!
Saved 4 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!!
```
r=i=1
while 1:r=r/i or r*i;print r;i+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8g209aQqzwjMydVwdCqyLZIP1Mhv0ihSCvTuqAoM69Eocg6U9vW8P9/AA "Python 2 – Try It Online")
Prints \$\{a(n)\mid n \in \mathbb{N}\}\$ as an infinite sequence.
[Answer]
# [R](https://www.r-project.org/), ~~43~~ 39 bytes
-4 bytes thanks to Giuseppe.
```
for(i in 1:scan())T=T%/%i^(2*(i<T)-1);T
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwdCqODkxT0NTM8Q2RFVfNTNOw0hLI9MmRFPXUNM65L@xocl/AA "R – Try It Online")
Outputs the \$n\$th term, 1-indexed.
Initializing the sequence with \$a(0)=1\$ also works, as the formula then gives \$a(1)=1\$ as desired. The variable `T` is coerced to the integer `1`, and we apply repeatedly a more compact version of the formula:
$$a(n)=\left\lfloor \frac{a(n-1)}{n^{2\mathbb{I\_{n<a(n-1)}} -1}}\right\rfloor $$
(with \$\mathbb I\$ the indicator function). This covers both cases of the original definition.
[Answer]
# [Haskell](https://www.haskell.org/), 40 bytes
```
a#n|n>a=a*n|1>0=a`div`n
a=scanl1(#)[1..]
```
[Try it online!](https://tio.run/##HcuxDoIwFAXQ3a94gQWsELvbfoFOjoTIjZrQWK6NRUlI/70mjGc4I@Lr6X3OKJloYbBn0vZoMDzcb@AOJt5Br6uy7nTb9nmCoxiZEC43Cd/5On/OlC6O70WoVCGNlUKpzUgVD6hPzerCttHnPw "Haskell – Try It Online")
* Outputs infinite sequence.
Infix operator # computes next term, we use it to fold all positive integers [1..] but using scanl1 instead which gives us all steps.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes (SBCS)
```
{⍺>⍵:⍺×⍵⋄⌊⍵÷⍺}/⌽ö⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/9/eNujtgnVj3p3gdFWCKr9DxKxA7KsgPTh6SDR7pZHPV1AxuHtQKFa/Uc9e4Faezf/TwPqf9Tb96ir@dB640dtEx/1TQ0OcgaSIR6ewf/TDq0AKjIDAA "APL (Dyalog Unicode) – Try It Online")
A barely-golfed but safe function that outputs the nth element of the sequence.
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~15~~ 14 bytes (SBCS)
*Saved 1 byte thanks to @[Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)*
```
(⌊⊢×⊣*∘×-)/⌽ö⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/9/eNujtgnVj3p3gdFWCKr9r/Gop@tR16LD0x91LdZ61DHj8HRdTf1HPXuByns3/08D6nnU2/eoq/nQeuNHbRMf9U0NDnIGkiEensH/0w6tACoyAwA "APL (Dyalog Unicode) – Try It Online")
Outputs the nth element of the sequence. I just realized that this won't work if \$n = a(n-1)\$ because it raises n to the power of \$n - a(n-1)\$ and multiplies that by \$a\$, although [as far as I can tell](https://tio.run/##SyzI0U2pTMzJT/9/eNujtgnVj3p3gdFWCKr9DxKxBbKsHvVNBSpQd8lPLVbIyy9RKM8vylZ/1N0ClNd41NP1qGvR4emPuhZrPeqYcXi6riZIs/6jnr1AY3s3/08Dan3U2/eoq/nQeuNHbROBhgUHOQPJEA/P4P9pCoYGQAAA), this function works until at least n=2,000,000.
```
(⌊⊢×⊣*∘×-)/⌽ö⍳
⍳ ⍝ Make a range to n
⌽ö ⍝ Then reverse it and
(⌊⊢×⊣*∘×-)/ ⍝ reduce it with a train:
× ⍝ Multiply
⊢ ⍝ a(n-1) with
⊣ ⍝ n
*∘× ⍝ to the power of the sign of
- ⍝ n - a(n-1)
⌊ ⍝ Floor it
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 82 bytes
```
: f 2dup 2dup > if * else swap / then dup . swap drop swap 1+ swap recurse ;
1 1 f
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WymkKRillBZACDuFzDQFLYXUnOJUheLyxAIFfYWSjNQ8BZCcHkQkpSi/AMIy1IbQRanJpUVADdZchgqGCmn//wMA "Forth (gforth) – Try It Online")
Outputs an infinite sequence, separated by spaces.
[Answer]
# [Python 3.8+](https://docs.python.org/3.8/), ~~45~~ 39 bytes
-2 thanks to [xnor](https://codegolf.stackexchange.com/users/20260) (`while print(...)!=0:` → `while[print(...)]:`)
-4 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) (`[a*n,a//n][a>n]` → `a//n or a*n`)
```
a=n=1
while[print(a:=a//n or a*n)]:n+=1
```
A full program which prints \$a(n)\$ for all natural numbers.
**[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9E2z9aQqzwjMyc1uqAoM69EI9HKNlFfP08hv0ghUStPM9YqT9vW8P9/AA "Python 3.8 – Try It Online")**
---
As a recursive function, 49:
```
f=lambda v,n=1,a=1:a*(v<n)or f(v,n+1,a//n or a*n)
```
[Answer]
# [R](https://www.r-project.org/), 41 bytes
```
for(m in 1:scan())T=`if`(m>T,T*m,T%/%m);T
```
[Try it online!](https://tio.run/##dc3RCsIgFIDh@/MUB2KgIYQUhRvrKbzfxClJU4e6IKJnt26CIHqA//tTrTYm4tEF5G3WKhBKZT86OxJ/lkxuPZPNrvG0k1UIgA1OxrpgUGVUaNegi4sBS0R9MfqKxeSCWmWTW0ieSAp@nYtb5vsQ0zC5m5tM/8lIoA/4@od/a3gCZLW8FaIJb4@Mn5gQbM8PlP36tL4A "R – Try It Online")
Forced myself not to look at [Robin Ryder's R answer](https://codegolf.stackexchange.com/a/215618/95126) before having a go at this. Happily we came up with different approaches to each other, although ~~both seem (so far) to be exactly the same length in bytes~~ sadly for me his one is now 2 bytes shorter...
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 35 bytes
Takes a 1-based starting index and returns the nth sequence value.
```
f(i,j){i=i?i>(j=f(i-1))?j*i:j/i:1;}
```
[Try it online!](https://tio.run/##HY1BDoIwFET3/xQ/GExrQK2gBip4ETektfgJFgOoC8LVrdXdzLyXjIprpZwzjKKGT1TQmUrWFL7HgvNzs6K82VAu5OwWZFX71Fc8DaOmbn0rAciOeK/IsldHmuMEiL@JJPhkup5JHFRlDQtCHUS4JF5uJfcM8dF78w@wKDHUF@sFitBfcy5hdgJ2kEAKeziAOEKWQSLSjzJtVQ8ufn8B "C (gcc) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-Minteger` `-061`, ~~36~~, 27 bytes
-9 bytes thanks to @Abigail and @Sisyphus.
outputs an infinite sequence
```
say$/while$/=$//++$i||$/*$i
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJFvzwjMydVRd9WRV9fW1sls6ZGRV9LJfP//3/5BSWZ@XnF/3V9M/NKUtNTi4AsUz0Dw/@6BmaGAA "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~38~~ 35 bytes
*Saved 3 bytes thanks to @Neil*
Returns the \$n\$-th term, 1-indexed.
```
f=(n,k=i=1n)=>i++<n?f(n,k/i||k*i):k
```
[Try it online!](https://tio.run/##FYzLDoIwEADvfMUeOHStj5AYD8LKr9AgNWvJrgHjpfTbS71NJpN5u59bx4U/35Poc8rZk5FjIKZGkB5sbSe9/6sLb1s4MN5D9roYAYKmBYGO4HYtYC1CrABGlVXn6TzrywzO1FESlraO5YJpwLZKeQc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 45 bytes
```
[ [1,b] 1 [ 2dup < [ * ] [ /i ] if ] reduce ]
```
[Try it online!](https://tio.run/##NY4xTwJBEIX7@xVPEhoj6IIJAYytoaEhVucV4@4ctwH21tnZghB/@7letPnem8mbvGnJai/D@2G3f9uAROia0PZyIVUfjjixBD6jjN2IuVA4ckLir8zBFheFVa9RfFBsq91@g2SF1HZVdQflpPAhZk2VeUJtHj4b3GBWWK@xNM/4BsXIwcHlONR/AYMai7LASzH3aAoffRHfFgi7bBnNcKH439BnHStqTKZLh9krpu4jTDB@9Xu0YLId7JlJhh8 "Factor – Try It Online")
Straightforward reduction. Takes 1-based index and returns the n-th term.
```
[ ! anonymous lambda
[1,b] 1 [ ... ] reduce ! reduce {1..n} by the following, starting with 1:
2dup < ! ( an n -- an n an<n)
[ * ] [ /i ] if ! ( a_n+1 ) multiply if an < n, int-divide otherwise
]
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~22~~ 20 bytes
```
{_x*(1%y;y)y>x}/1+!:
```
[Try it online!](https://tio.run/##y9bNz/7/P82qOr5CS8NQtdK6UrPSrqJW31Bb0ep/mrqhgpGCsYKJgqmCmYKhuYKlpYKxocl/AA "K (oK) – Try It Online")
Rather than using `$[y>x;y;1%y]`, indexes into the list `(1%y;y)` using the boolean condition `y>x` to save a couple bytes.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
Fμ?*`÷<¹³)ḣ
```
[Try it online!](https://tio.run/##ATUAyv9odXNr/23igoH/Rs68Pypgw7c8wrnCsynhuKP///9bMSwyLDMsNCw1LDYsMTcsOTksMzE0XQ "Husk – Try It Online")
```
F # Fold a function over
ḣ # sequence from 1..input;
μ?*`÷<¹³) # function with 2 arguments:
? # if
<¹³ # arg 2 is smaller than arg 1
* # arg 1 times arg 2
`÷ # else arg 1 integer divided by arg 2
```
[Answer]
# [Perl 5](https://www.perl.org/) `-Minteger -p`, 35 bytes
```
map$.=$_>$.?$.*$_:$./$_,2..$_;$_=$.
```
[Try it online!](https://tio.run/##BcFRCoAgEAXAy7yvyBcFERTWCTzD0oeEULqY52@b0Vjv2ew5FfSQHTzADrKCA6SfSMgG8aDZuHxFWyr5NRdSbvGK1Zz@ "Perl 5 – Try It Online")
Takes `n` as input and prints the `n``th` item in the list.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 10 bytes
Prints the infinite sequence.
```
λN>₁N›i÷ë*
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3G4/u0dNjX6PGnZlHt5@eLXW//8A "05AB1E – Try It Online")
**Commented**:
```
λ # infinite list generation
# implicitly push a(n-1) (initially 1)
N> # push n, since N is 0-indexed, this needs to be incremented
₁N› # is a(n-1) > n-1?
i÷ # if this is true, integer divide a(n-1) by n
ë* # else multiply a(n-1) and n
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 51 bytes
```
: f 1+ 1 tuck ?do i 2dup <= if * else / then loop ;
```
[Try it online!](https://tio.run/##FYxLDoIwFEXnXcUJQw01BT9BUBcDrRAJbUpZf30dnNyb3I/zMc311xXJ@YnDnDGkY/zxmTwLzXQEhheL44Rdd8uFNNuN1ftAL5tAqbToiK6gflPJj2aM9MoQVCO0wlW4CXeZKPMQ13UlMhLkPw "Forth (gforth) – Try It Online")
### Code Explanation
```
: f \ start word definition
1+ \ add 1 to n
1 tuck \ set up accumulator and loop parameters
?do \ loop from 1 to n (if n > 1)
i 2dup \ set up top two stack values and duplicate
<= if \ if a(n-1) <= n
* \ multiply
else \ otherwise
/ \ divide
then \ end if
loop \ end loop
; \ end word definition
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 52 bytes
```
n->{int i,a=i=1;for(;i++<n;)a=i>a?i*a:a/i;return a;}
```
[Try it online!](https://tio.run/##ZU67DoJAEOz5ii3BxxkqE0@wM7GwsjQWKwJZPBdyt0diCN@Op6Fzm5nMTHamwR7XzeM5df5uqIDCoHNwRmIYIoBZdYISoAlh5YWMqjwXQi2r40z2J5ayLu0KZpJDBdnE63wgFqAVZpSlumptrGm53LNOgpLjgRa4ww1pW4q3DKjHCcLpUP7X37f0gFfYFl/EEtfXG6CtXfKbCnB5OylfqvWiumCL4bhS2HXmHafbJPm@HKNx@gA "Java (JDK) – Try It Online")
Note: Thanks @RedwolfPrograms for -1 Byte and @user for -10(?) bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
1’ß×:>@?$Ị?
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//MeKAmcOfw5c6PkA/JOG7ij//MTBSOzE3LDk5LDMxNCA7w4ck4oKsIEf/ "Jelly – Try It Online")
## How it works
```
1’ß×:>@?$Ị? - Main link f(n). Takes n on the left
? - If statement:
Ị - If: n ≤ 1
1 - Then: Yield 1
$ - Else:
’ - n-1
ß - f(n-1)
? - If statement:
>@ - If: n > f(n-1)
× - Then: n × f(n-1)
: - Else: n : f(n-1)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
⟦₁{÷ℕ₁|×}ˡ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8ZY@aGqsPb3/UMhXIqDk8vfb0wv//ow11jHSMdUx0THXMdAzNdSwtdYwNTWIB "Brachylog – Try It Online")
Gives the singleton list `[1]` instead of `1` for n = 1, but nothing out of the ordinary otherwise.
```
ˡ Reduce
⟦₁ 1 .. n
{ } by:
÷ integer division
ℕ₁ if the result is 1 or greater,
|× multiplication if not.
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 9 bytes
```
┅⟪<₌×/?⟫⊢
```
[Try it online!](https://tio.run/##AR0A4v9nYWlh///ilIXin6o84oKMw5cvP@Kfq@KKov//MQ "Gaia – Try It Online")
Basically the same as the shorter Jelly answer. 1-indexed, prints `a(n)`, although `⊢` could be swapped with `⊣` to get the first `n` elements instead.
```
# implicit input n
┅ # push 1...n
⟪ ⟫⊢ # reduce the list by the following function:
<₌ # push an extra copy of a(i-1) and i and check if less than?
× ? # if true, then multiply
/ # else integer divide
# implicitly print top of stack
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 58 bytes
```
K`_ _
"$+"+L$`(^_+|_)(?<=(\1)+) (\1)+
_$`$1 $#3*$#2*
r`_\G
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zshXiGeS0lFW0nbRyVBIy5euyZeU8PexlYjxlBTW1MBTHHFqySoGCqoKBtrqSgbaXEVJcTHuP//b2kJAA "Retina – Try It Online") No test suite because of the way the script uses history. Explanation:
```
K`_ _
```
Replace the input with a pair of 1s (in unary). The first is the loop index while the second is the output.
```
"$+"+
```
Loop `n` times.
```
L$`(^_+|_)(?<=(\1)+) (\1)+
```
Divide both the output and the loop index by the loop index, or by 1 if the division would be zero.
```
_$`$1 $#3*$#2*
```
Increment the loop index and multiply the two quotients together. This results in `output/index*index/index` or `output/1*index/1` respectively.
```
r`_\G
```
Convert the final output to decimal.
[Answer]
# [PHP](https://php.net/), 57 bytes
```
function a($n){return$n?($n>$x=a($n-1))?$x*$n:$x/$n|0:1;}
```
[Try it online!](https://tio.run/##TY5Ba4NAEIXv/opHGNAtW5o1TUq0RnJIaSBQwWNbyiIGe1lFN2BI8tvNji0hl@GbN@/NTFM1w2vauLo/mML@1gY6ICNObWkPrSGTum5FfcLqoxIipf6BTET9E5nzNFLxZSBbdrZDgk8PUEhWUNJRyBQyzZgWTM@36ZxpLuFwwTibsqpexlA4WpbL0f23Qo3R0G35jj1vX7elLqoA/7d1BzJsoCMETi5QFlXtNInJl51IkHb/6YBd4l5LOJHCz9Z57iOC/7be7nyJ7D372XzsYu8yXAE "PHP – Try It Online")
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 14 bytes
```
=1:$>Z?$Z:Z_/$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/39bQSsUuyl4lyioqXl/l/39DcwA "cQuents – Try It Online")
## Explanation
```
=1 first term is 1
: mode sequence: given n, output nth term; otherwise, output indefinitely
each term equals:
$>Z? : if n > seq(n - 1) else
$Z n * seq(n - 1)
Z_/$ seq(n - 1) // n
```
[Answer]
# [Racket](https://racket-lang.org/), 66 bytes
```
(λ(n)(foldl(λ(x y)((if(< y x)* quotient)y x))1(range 1(+ 1 n))))
```
[Try it online!](https://tio.run/##NYxBCsIwFET3OcVQF/6vuPgoiCBeRF0Em0iw/NYQod30Yt7BK8W06FvNwMyL9vZwKS8aq3fEuRiqnQ/q4DN93qRMvm3qZso9BiYKno4Y0PMKz1ebgtPEU2WhWDQOQmsIlAuZTblH0FlBtuuc1v8RRNjgx5Jkj8MBW9kxXxkG1MWgyaMaLTYnjPaiFYrEz@L8BQ "Racket – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
a@1=1;a@n_:=If[#<n,n#,⌊#/n⌋]&@a[n-1]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/RwdDW0DrRIS/eytYzLVrZJk8nT1nnUU@Xsn7eo57uWDWHxOg8XcPY/wFFmXklCvoOifoO1YY6RjrGOiY6pjpmOobmOpaWOsaGJrX//wMA "Wolfram Language (Mathematica) – Try It Online")
-2 bytes from @att
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
[:(]<.@*[^*@-)/1+i.@-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600Ym30HLSi47QcdDX1DbUz9Rx0/2tyKXClJmfkK2hYp2kqaWsYmitYWioYG5po6tSBlJj9BwA "J – Try It Online")
A [J](http://jsoftware.com/) port of @user 's [APL solution](https://codegolf.stackexchange.com/a/215615/75681) - don't forget to upvote it!
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~11~~ 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
1k{î`<¿*/
```
-2 bytes thanks to *@ovs*.
Outputs the \$n^{th}\$ value.
[Try it online.](https://tio.run/##y00syUjPz0n7/98wu/rwugSbQ/u19IEcLiMuYy4TLlMuMy5Dcy5LSy5jQxMA)
**Explanation:**
```
1 # Push 1
k{ # Loop the input amount of times:
î # Push the 1-based loop index
` # Duplicate the top two items
<¿ # If the current value is smaller than the 1-based loop index: a(n-1)<n:
* # Multiply the value by the 1-based loop index
# Else:
/ # Integer-divide instead
# (after the loop, the entire stack joined together is output implicitly)
```
] |
[Question]
[
**Requirements:**
* Take a single word as input with only lowercase alphabetical characters (a-z)
* Output a string where every other character is repeated, with the first repeated character being the second character in the string
**Example:**
Input: `abcde`
Output: `abbcdde`
**Winning Criteria:**
Standard code golf. Shortest number of bytes in program wins.
**Clarification:**
For languages with 1-based indexing the output must still match the above, `aabccdee` is **not** an acceptable solution.
[Answer]
# [sed](https://www.gnu.org/software/sed/), 12
```
s/.(.)/&\1/g
```
[Try it online!](https://tio.run/##K05N0U3PK/3/v1hfT0NPU18txlA//f//xKTklNR/@QUlmfl5xf91iwA "sed – Try It Online")
[Answer]
# brainfuck, 13 or 11 bytes
```
>,[.,[..,>]<]
```
Assumes EOF->0. :(
You can [try it online!](https://tio.run/##SypKzMxLK03O/v/fTidaD4j0dOxibWL//09MSk5JTQMA)
(Assuming input also continues to give zeroes indefinitely after the first EOF, we can do it in 11 bytes:
```
,[.,[..>],]
```
though this eats memory.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḤÐe
```
A full program accepting a string which prints the result
**[Try it online!](https://tio.run/##y0rNyan8///hjiWHJ6T@//9fPTEpOSVVHQA "Jelly – Try It Online")**
### How?
Utilises the fact that the implementation of the double atom, `Ḥ`, is multiplication by two, and that strings are lists of Python characters. In Python when a character is multiplied by two it becomes a Python string of length two (e.g. `'x'*2=='xx'`). Lastly the implicit output of a list composed entirely of characters and strings (or lists thereof) is its content all smashed together.
```
ḤÐe - Main Link: list of characters e.g. input abcd -> ['a','b','c','d']
Ðe - apply to even indices (1-indexed):
Ḥ - multiply by 2 -> ['a', 'bb', 'c', 'dd']
- implicit, smashing print -> abbcdd
```
[Answer]
# [Python](https://docs.python.org/2/), 38 bytes
```
f=lambda s:s and s[:2]+s[1:2]+f(s[2:])
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRodiqWCExL0WhONrKKFa7ONoQRKVpFEcbWcVq/k/LL1IoVsjMU4hWSlTSUUpMAhPJEDIFSqUqxVpxKRQUZeaVKAB1av4HAA "Python 2 – Try It Online")
Takes the first two characters, then the second character, then removes the first two characters and recurses.
---
**39 bytes**
```
f=lambda s,c=2:s and s[:c]+f(s[1:],3-c)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoVgn2dbIqlghMS9FoTjaKjlWO02jONrQKlbHWDdZ839afpFCsUJmnkK0UqKSjlJiEphIhpApUCpVKdaKS6GgKDOvRAGoW/M/AA "Python 2 – Try It Online")
Flips between taking the first two or first one character.
[Answer]
# x86-16 machine code, IBM PC DOS, ~~14~~ 12 bytes
**Binary:**
```
00000000: b401 cd21 f7d9 78f8 cd29 ebf4 ...!..x..)..
```
**Unassembled:**
```
START:
B4 01 MOV AH, 1 ; DOS read char from STDIN
CD 21 INT 21H ; put char in AL
F7 D9 NEG CX ; toggle CX sign
78 F8 JS START ; if negative, loop to next char
CD 29 INT 29H ; DOS write char to screen again
EB F1 JMP START ; loop until break/^C
```
A standalone executable DOS program. Input via `STDIN` (pipe or keyboard interactive), output to `STDOUT`.
Output:
[![enter image description here](https://i.stack.imgur.com/377EG.png)](https://i.stack.imgur.com/377EG.png)
[Answer]
# [Python 2](https://docs.python.org/2/), 34 bytes (xnor's improvement)
```
lambda s:`[c*11for c in s]`[7::10]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKiE6WcvQMC2/SCFZITNPoTg2IdrcysrQIPZ/QVFmXolGmoZ6YlJySqq6puZ/AA "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 36 bytes
```
lambda s:`sum(zip(s,s,s),())`[7::10]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKqG4NFejKrNAo1gHCDV1NDQ1E6LNrawMDWL/FxRl5pVopGmoJyYlp6Sqa2r@BwA "Python 2 – Try It Online")
Slices characters 7, 17, 27… out of a string like this:
```
('a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e')
012345678901234567890123456789012345678901234567890123456789012345678901234
^ ^ ^ ^ ^ ^ ^
→ abbcdde
```
xnor's `c*11` trick achieves the same thing, but with a string like:
```
['aaaaaaaaaaa', 'bbbbbbbbbbb', 'ccccccccccc', 'ddddddddddd', 'eeeeeeeeeee']
012345678901234567890123456789012345678901234567890123456789012345678901234
^ ^ ^ ^ ^ ^ ^
→ abbcdde
```
# [Python 3](https://docs.python.org/3/), 37 bytes
```
lambda s:''.join(c*3for c in s)[1::2]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSl1dLys/M08jWcs4Lb9IIVkhM0@hWDPa0MrKKPZ/QVFmXolGmoZ6YlJySqq6puZ/AA "Python 3 – Try It Online")
If returning a tuple of characters is OK (which it isn't), `lambda s:sum(zip(s,s,s),())[1::2]` is a 33-byte solution.
[Answer]
# [J](http://jsoftware.com/), 8 bytes
```
#~1 2$~#
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/lesMFYxU6pT/a3KlJmfkK6gnJiUlp6SkqivoWimkgbjJQM5/AA "J – Try It Online")
* `1 2$~#` Shape `$~` the list `1 2` (repeating it cyclically as needed) until it matches the length `#` of the input.
* `#~` Use this `1 2 1 2...` "mask" to Copy `#~` the implicit input elementwise. That is, make 1 copy of the first char, 2 copies of the 2nd char, 1 copy of the third char, etc.
[Answer]
# [Haskell](https://www.haskell.org/), 24 bytes
```
f(a:b:t)=a:b:b:f t
f s=s
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SrJqkTTFkQlWaUplHClKRTbFv/PTczMU7BVyE0s8FUoKC0JLinyyVNQAfEV0hSilRKVdJQSk8BEMoRMgVKpSrH//yWn5SSmF//XTS4oAAA "Haskell – Try It Online")
[Answer]
# Haskell, ~~33~~ 24 bytes
By noticing that obviously `f [] = []` also fits the pattern `f s = s` and removing one extra space, we get to
```
f(a:b:s)=a:b:b:f s
f s=s
```
from my starting point of
```
f []=[]
f (a:b:s)=a:b:b:f s
f s=s
```
Now my answer matches xnor's Haskell answer.
You can [try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SrJqljTFkQlWaUpFHMBsW3x/9zEzDwFW4WC0pLgkiKfPAUVheKM/HIglaaglJiUnKL0HwA).
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 16 bytes
```
@(s)s(1:2/3:end)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1izWMPQykjf2Co1L0Xzf5qGemJSckqquuZ/AA "Octave – Try It Online")
### Explanation
Non-integer values are [automatically rounded](https://stackoverflow.com/questions/40455299/does-matlab-accept-non-integer-indices) (with a warning) in colon index expressions.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~9~~ 8 bytes
```
q3e*1>2%
```
[Try it online!](https://tio.run/##S85KzP3/v9A4TavY0M5I9f//xKTklFQA "CJam – Try It Online")
## Explanation
```
abcde q read input
→ aaabbbcccdddeee 3e* repeat characters x3
→ aabbbcccdddeee 1> drop first
→ a b b c d d e 2% every other char
```
Esolanging Fruit saved 1 byte: `3f*s` → `3e*`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
+pVu
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=K3BWdQ&input=ImFiY2RlZmdoaWpsa2xtbm9wcXJzdHV2d3h5eiI)
```
+pVu :Implicitly map each character U at 0-based index V in the implicit input string
+ :Append to U
p :U repeated
Vu : V mod 2 times
:Implicit output of resulting string
```
[Answer]
# Scratch 3.0, 25 blocks/179 bytes
[![Blocks](https://i.stack.imgur.com/dimH8.png)](https://i.stack.imgur.com/dimH8.png)
As SB Syntax:
```
define f(n
set[i v]to(1
set[o v]to(
repeat((length of(n))/(2
set[o v]to(join(o)(letter(i)of(n
change[i v]by(1
set[x v]to(letter(i)of(n
set[o v]to(join(o)(join(x)(x
change[i v]by(1
```
Oh boy, here I go Scratching again! This was quite an interesting one to solve, and I quite enjoyed it. Thanks for the challenge.
The output of the function is shown in the top left corner.
Finally, [Try it on~~line~~ Scratch!](https://scratch.mit.edu/projects/364315112/)
[Answer]
# [Unreadable](https://esolangs.org/wiki/Unreadable), 43 bytes
>
> '"""""'"""'""""'"'""""""""""'"'"'""""""""""
>
>
>
[Try it online!](https://tio.run/##K80rSk1MSUzKSf3/X10JBNShGEhABJRgHCTu//@JSckpqQA "Unreadable – Try It Online")
Displayed here in variable-width font, per the traditional tribute to the language name.
Exits with error after printing the correct output.
Explanation:
```
'"""""'""" while(1)
'"""" do 2 things:
'"'"""""""""" print(read stdin)
'"'"'"""""""""" print(print(read stdin))
```
Uses the fact that `'"` both prints and returns its argument, which can thus be directly fed to a 2nd print command.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~43 41~~ 39 bytes
-2 thanks to mypetition (`s[:1]*i` can be `s[:i]` if we swap our order of `i`s)
```
f=lambda s,i=2:s and s[:i]+f(s[1:],i^3)
```
A recursive function which accepts a string and returns a string.
Works in Python 2 too.
**[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRoVgn09bIqlghMS9FoTjaKjNWO02jONrQKlYnM85Y839BUWZeiUaahnpiUnJKalp6RmZWtrqm5n8A "Python 3 – Try It Online")**
At each call we return `s` if it is empty or take the first *up-to-i-characters* of the given string (`s[:i]`) where `i` starts out as `2` and append (`+`) the result of another call to the function this time using a new `s` of all but the first character (`s[1:]`) and a new `i` found by XOR-ing with three (`i^3`) - i.e. `2, 1, 2, 1, ...`
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~5~~ 3 bytes
```
3•y
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=3%E2%80%A2y&inputs=abcde&header=&footer=)
```
3• # Repeat each character three times
y # Get every other character
```
[Answer]
# Brainfuck, ~~52~~ 31 bytes
```
,[>>+<[<..>->-]>[<<.>+>->]<<<,]
```
You can [try it online](https://tio.run/##SypKzMxLK03O/l@jkJlXoFCjkFuaUwKkEksrgGRqXsp/nWg7O22baBs9PTtdO91Yu2gbGz07bSA71sbGRif2///EpOSU1DQA) or you can check my first submission, that I think is also simpler to understand:
```
+>+>>,[<<[-<->]<[->>+>>+<<<<]+>>>.>[-<.>]<,<[-<+>]>
```
Cell layout is
```
| 1 | aux | mult | inp | mult |
```
where mult is the number of extra times we have to print the current character. Feel free to drop me a line in the comments with feedback.
[Try it online!](https://tio.run/##LUpLCoAgFLyK@6dCe5mLiAu1BKkkIqGFd389oVnMP92xttLzzkMtaqjYX@GzH49IbdcfmECA9s554wyCCGZDThDEwEIWK4ueF0JAYI4pr1v5AA)
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 126 bytes
```
,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Page and Ajax]Ajax:Open mind.Speak thy.Open mind.Speak thy.Speak thy.Let usAct I.
```
[Try it online!](https://tio.run/##Ky7I@f9fR88xK7FCRy8gMT0VyE4uUfC00gtOTs1LBTGiXStSS/NKYqNd80pSixRAihQS81IUQHpiQYSVf0FqnkJuZl6KXnBBamK2QklGpR42MQTLJ7VEobQYbJPe//@JSckpqQA "Shakespeare Programming Language – Try It Online")
Page reads the input one character at a time, and alternately prints it once or twice. Exits with error after printing the correct output.
[Answer]
# k4, ~~17~~ 13 bytes
edit: make use of `&` (where operator) which for each index i of an int-list L give gives L[i] copies of i. eg `&2 1 3` -> `0 0 1 2 2 2`
```
{x@&(#x)#1 2}
```
```
{ } /lambda with implicit arg x
(#x) /count x
#1 2 /takes #x items of 1 2 (eg 3#1 2 -> 1 2 1)
& /&1 2 1 -> 0 1 1 2
x@ /index x
```
[Answer]
# Python 3, ~~54~~ ~~50~~ 49 bytes
This looks incredibly long, I have no idea if something obvious is slipping under my nose... And already saved 5 bytes thanks to @Jonathan Allan! Check [his 43 byte Python 3 answer](https://codegolf.stackexchange.com/a/198720/75323)! but here it is:
```
lambda s:''.join(c+i%2*c for i,c in enumerate(s))
```
You can [try it online!](https://tio.run/##DchLCoAgEADQqwxCqBUtahNBN2njlyZyFLVFp7fe8qW3npGWNeXmYYej3Spoq6BsnE9XRBJmwG7uDfiYAUcDSODoCS6r6kSRsqWMVIUXTGljHfvnAw)
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 84 bytes
```
S =INPUT
S S LEN(1) . L LEN(1) . R REM . S :F(O)
O =O L R R :(S)
O OUTPUT =O S
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/nzNYwdbTLyA0hCsYyPRx9dMw1FTQU/BBMIMUglx9gXQwp5Wbhr8mF6e/gq0/UAFQXMFKI1iTy5/TPzQEaAJIOJjL1c/l///EpOSUVAA "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg) `-ir` `-lp`, 4 bytes
```
(,⑩,
```
[Try it online!](https://tio.run/##y05N//9fQ@fRxJU6//8nJiWnpP7XzSz6r5tTAAA "Keg – Try It Online")
# Explanation
```
# (Implicitly) take an input from the console
( # For every item in the input:
, # Print the first character, popping the stack
⑩ # Print the top of the stack w/o poping
, # Print with popping, effectively doubling the second character
```
[Answer]
# JavaScript (ES6), 28 bytes
Uses the same regex as [@DigitalTrauma](https://codegolf.stackexchange.com/a/198722/58563).
```
s=>s.replace(/.(.)/g,"$&$1")
```
[Try it online!](https://tio.run/##BcEBCoAgDADAv4jEBqX0APvL0imFOGnR99fdTR9pfq75bkMKW02m6dDw8OyUGWKAgLGtzi9@d2hZhkrn0KVBBUdnLuwQ7Qc "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 32 bytes
A recursive version.
```
f=([a,b,...c])=>b?a+b+b+f(c):[a]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjOlEnSUdPTy85VtPWLsk@UTsJCNM0kjWtohNj/yfn5xXn56Tq5eSna6RpKCUmJaekKmlqcmERBwr/BwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->s{s.gsub /.(.)/,'\0\1'}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvvbg0SUFfT0NPU19HPcYgxlC99n9BaUmxQlq0UmJSckqqUux/AA "Ruby – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 13 bytes
```
,[.<[>.>]>>,]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1rPJtpOzy7Wzk4n9v//xKTklFQA "brainfuck – Try It Online")
Handles odd and even length strings correctly. This takes an input and prints it once before checking if the previous cell contains the previous character. If so, it prints again and moves three spaces ahead, otherwise it just moves one cell ahead, and then it gets the next character.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~40~~ ~~38~~ 37 bytes
```
-join($args|% t*y|%{"$_"*(1+$i++%2)})
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XzcrPzNPQyWxKL24RlWhRKuyRrVaSSVeSUvDUFslU1tb1UizVvP////qJanFJZl56eoA "PowerShell – Try It Online")
Takes input `$args`, transforms it `t`oCharArra`y`, pipes that into a loop. Each iteration, we repeat the character `"$_"` either 1 or 2 times based on a modulo-index. Those characters/strings are left on the pipeline, gathered up with a `-join` to turn it back into a single string, and output is implicit.
*-2 bytes thanks to Veskah.*
*-1 byte thanks to mazzy.*
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->s{s.scan(/(.(.?))/)*''}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivODkxT0NfQ09Dz15TU19TS1299n9BaUmxQlq0emJSckqqeux/AA "Ruby – Try It Online")
Same byte count as the other answer, different approach.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 11 bytes
```
B X_%2+1MEa
```
[Try it online!](https://tio.run/##K8gs@P/fSSEiXtVI29DXNfH///@JSckpqWnpAA "Pip – Try It Online")
-2 from Dlosc.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
€Ðιθ
```
I/O as a list of characters, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/2216/52210).
~~I have the feeling 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) might be possible, but I'm unable to find it.~~
It is possible, by porting [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/236924/52210) (so make sure to upvote him/her as well).
[Try it online.](https://tio.run/##yy9OTMpM/f//UdOawxPO7Ty34///aKVEJR2lJCBOBuIUIE5VigUA)
**Explanation:**
```
# (example input = ["a","b","c","d","e"])
€Ð # Triplicate each character (which remains a flattened list)
# → ["a","a","a","b","b","b","c","c","c","d","d","d","e","e","e"]
ι # Uninterleave this list into two parts
# → [["a","a","b","c","c","d","e","e"],["a","b","b","c","d","d","e"]]
θ # Pop and leave just the second part
# → ["a","b","b","c","d","d","e"]
# (which is output implicitly as result)
```
[Answer]
# [Rockstar](https://codewithrockstar.com/), ~~95~~ 81 bytes
```
listen to S
cut S
Y's 1
O's ""
while S
let O be+roll S*Y
let Y be Y-1 or 2
say O
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in)
] |
[Question]
[
Because there are not enough simple [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenges:
Create an optionally unnamed program or function that, given (by any means) an integer 1 ≤ N ≤ 10000, outputs your language's True value with a pseudo-random probability of 1/N, False otherwise.
**Please note that the requirement for naming has been removed. Feel free to edit answers and scores accordingly.**
Some languages use 1 (or -1) and 0 for True and False, that is fine too.
**Example:**
Example input tests:
```
4 -> True
4 -> False
4 -> False
4 -> False
4 -> False
4 -> True
4 -> False
4 -> False
```
I.e. given 4; it returns True with a 25% chance and False with a 75% chance.
[Answer]
# MediaWiki templates with [ParserFunctions](https://www.mediawiki.org/wiki/Extension:ParserFunctions), 48 bytes
```
{{#ifexpr:1>{{#time:U}} mod {{{n}}}|true|false}}
```
[Answer]
# Pyth, 3 bytes
```
!OQ
```
[Try it online](http://pyth.herokuapp.com/?code=%21OQ&input=5&debug=0)
Simple inversion of random choice from 0 to input
Amusingly in Pyth it is not possible to make a function that does this without `$` because Pyth functions are automatically memoized.
[Answer]
## CJam, 5 bytes
Gotta be quick with these ones...
```
rimr!
```
[Test it here.](http://cjam.aditsu.net/#code=rimr!&input=5)
### Explanation
```
ri e# Read input and convert to integer N.
mr e# Get a uniformly random value in [0 1 ... N-1].
! e# Logical NOT, turns 0 into 1 and everything else into 0.
```
[Answer]
## TI-BASIC, 4 bytes using [one byte tokens](http://tibasicdev.wikidot.com/one-byte-tokens/ "One Byte Tokens")
```
not(int(Ansrand
```
Determines if the integer part of the input times a random number in [0,1) is zero. `Ansrand<1` also works.
[Answer]
## MATL, 5 bytes
Three different versions of this one, all length 5.
```
iYr1=
```
which takes an input (`i`), generates a random integer between 1 and that number (`Yr`), and sees if it it is equal to 1 (`1=`). Alternatively,
```
li/r>
```
make a 1 (`l`, a workaround because there is a bug with doing `1i` at the moment), take an input (`i`), divide to get 1/N (`/`), make a random number between 0 and 1 (`r`), and see if the random number is smaller than 1/N. Or,
```
ir*1<
```
take and input (`i`), and multiply by a random number between 0 and 1 (`r*`), and see if the result is smaller than 1 (`1<`).
In Matlab, not MATL, you can do this anonymous function
```
@(n)n*rand<1
```
for 12 bytes, which is used by doing `ans(5)`, for example.
[Answer]
# JavaScript ES6, 15 bytes
-5 bytes thanks to Downgoat.
```
x=>1>new Date%x
```
Based off (uses) of [this](https://codegolf.stackexchange.com/a/66940/31957) answer's technique.
[Answer]
# Julia, ~~17~~ ~~16~~ 15 bytes
```
n->2>rand(1:n)
```
This is a function that generates a random integer between 1 and `n` and tests whether it's less than 2. There will be a 1/n chance of this happening, and thus a 1/n chance of returning `true`.
Saved 1 byte thanks to Thomas Kwa!
[Answer]
# [Microscript II](https://github.com/SuperJedi224/Microscript-II), 3 bytes
```
NR!
```
Reads an integer `n`, generates a random integer between `0` and `n-1` (inclusive), then applies a boolean negation to that value.
[Answer]
# [Candy](https://github.com/dale6john/candy), 2 bytes
```
Hn
```
*H* stands for *Heisen-double*
*n* stands for *not*
The 'n' is passed with the -i flag as numeric input. Values left on the stack are printed on exit.
"Long" form:
```
rand # number between 0 and pop()
not # cast to int, invert non-zero to zero, and zero to one
```
[Answer]
## Seriously, 3 bytes
```
,JY
```
`0` is falsey and `1` is truthy. [Try it online](http://seriouslylang.herokuapp.com/link/code=2c4a59&input=4)
Explanation:
```
,JY
, get input
J push a random integer in range(0, input) ([0, ..., input-1])
Y logical not: push 0 if truthy else 1
```
[Answer]
# R, ~~30~~ 22 bytes
### code
```
cat(runif(1)<1/scan()) #new
f=function(N)cat(runif(1)<1/N) #old
```
It generates a number from a uniform distribution (0 to 1) and should evaluate to true 1/n of the times.
[Answer]
# Japt, 6 bytes
```
1>U*Mr
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=MT5VKk1y&input=NA==)
`Mr` is equivalent to JS's `Math.random`. The rest is pretty obvious. I could probably add a number function that generates a random float between 0 and the number. When this happens, two bytes will be saved:
```
1>Ur // Doesn't currently work
```
Alternate version:
```
1>Ð %U
```
`Ð` is equivalent to `new Date(`, and the Date object, when asked to convert to a number, becomes the current timestamp in milliseconds. Thus, this is entirely random, unless it is run multiple times per ms.
[Answer]
# [Marbelous](https://github.com/marbelous-lang/docs/blob/master/spec-draft.md), 21 bytes
```
}0 # takes one input n
-- # decrements n
?? # random value from range 0..n (inclusive)
=0?0 # push right if not equal to 0, fall through otherwise | convert to zero
++ # increment | no-op
{0// # output | push left
```
I've taken `0` to be falsey and `1` to be truthy, though there is no real reason for that seeing as Marbelous doesn't really have an if. More Marbelousy would be output to `{0` for true and `{>` for false. This would look like this:
```
}0
--
??
=0{>
{0
```
But I'm not sure that's valid.
[Answer]
# APL, ~~6~~ 3 bytes
```
+=?
```
This is a function train that takes an integer and returns 1 or 0 (APL's true/false). We generate a random integer from 1 to the input using `?`, then check whether the input is equal to that integer. That results in a 1/input chance of true.
Saved 3 bytes thanks to Thomas Kwa!
[Answer]
# [PlatyPar](https://github.com/cyoce/PlatyPar), 3 bytes
```
#?!
```
`#?` gets a random number `[0,n)` where `n` is input.
`!` returns `true` if the number before it is `0`, else it returns `false`.
Using more recent features that were implemented (but unfortunately for me not committed) before this question was asked I can get it down to 2 with `~!`
[Try it online](https://rawgit.com/cyoce/PlatyPar/master/page.html?code=%7E%21)!
[Answer]
# Java, 43 bytes
```
boolean b(int a){return a*Math.random()<1;}
```
[Answer]
# C, 24 bytes
```
f(n){return!(rand()%n);}
```
[Answer]
# ><>, 27 + 3 for -v = 30 bytes
Here is a not-uniform-at-all solution where I mod N the sum of 15876 random picks of 0 or 1 :
```
0"~":*>:?vr%0=n;
1-$1+$^-1x
```
N must be input on the stack with -v flag, output is 0 for falsey and 1 for truthy.
A much smarter and uniform solution that work for 1/2^N instead :
```
4{:?!v1-}:">"$2p:"x"$3p:"^"$4p1+:">"$3p1+!
^1<
0n;
1n;>
```
For an input 3 you've got 1/8 chances of getting 1 and 7/8 of getting 0.
Explanation :
I append as much `x` as needed on the 4th line and surround them with directions so there is only two ways out of the `x`: either the falsey output or the next `x`. If all `x` go in the right direction, the last one will route to the truthy output.
For example for N=5, the final codespace is the following :
```
4{:?!v1-}:">"$2p:"x"$3p:"^"$4p1+:">"$3p1+!
^1<
0n; > > > > >
1n;>x>x>x>x>x>
^ ^ ^ ^ ^
```
[Answer]
## Mathematica, ~~18~~ 16 bytes
```
#RandomReal[]<1&
```
Basic solution. The unnamed `Function` creates a random number in [0, 1), multiplies it by its argument, and checks if it is still less than 1.
[Answer]
# Python, 42 bytes
```
import random
lambda n:1>random.random()*n
```
*Edit*: Removed the `time.time()` answer because of the distribution.
[Answer]
## [TeaScript](https://esolangs.org/wiki/TeaScript), 3 bytes
```
!N×
```
[Try it here.](http://vihanserver.tk/p/TeaScript/#?code=%22!N%C3%97%22&inputs=%5B%224%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D)
### Explanation
```
N maps to Math.rand which is a utility function that returns an integer
between `arg1` and `arg2` or `0` and `arg1` if only one argument is
provided.
× is expanded to `(x)`, where `x` is initialised with the value provided
in the input boxes; × represents byte '\xd7'
! negate the result, 0 results in true, anything else false
```
[Answer]
# Fuzzy Octo Guacamole, 10 bytes
```
^-!_[0]1.|
```
Explanation:
```
^-!_[0]1.|
^ # Get input.
- # Decrement, so we can append <ToS> zeros and a 1 to the stack.
! # Set loop counter.
_ # Pop, since we are done with the input.
[ # Start loop
0 # Push 0
] # End for loop. We have pushed input-1 0s to the stack.
1 # Push a single 1 to the stack.
. # Switch stacks
| # Pick a random item from the inactive stack, which has n-1 falsy items and 1 truthy item, so the truthy probability is 1/n.
# (implicit output)
```
[Answer]
# Ruby, 14
Function
```
->n{rand(n)<1}
```
Program is slightly longer
```
p rand(gets.to_i)<1
```
[Answer]
# [Perl 6](http://perl6.org), ~~10~~ 8 bytes
```
!(^*).pick
# ^- The * is the argument
```
This code creates a Range from 0 up-to but excluding the input `*`. It then `pick`s one at random and the `!` returns True when it receives a `0`.
```
1>*.rand
# ^- The * is the argument
```
This takes the input `*` and multiplies it by a random Num from `0..^1` then returns True if it was smaller than `1`.
```
# store it in a lexical code variable for ease of use
my &code = 1>*.rand;
die "never dies here" unless code 1;
for ^8 { say code 4 }
```
```
False
True
False
False
False
True
False
False
```
[Answer]
# Prolog (SWI), 24 bytes
**Code:**
```
p(N):-X is 1/N,maybe(X).
```
**maybe(+P)** is a function which succeeds with probability **P** and fails with probability **1-P**
**Example:**
```
p(4).
false
p(4).
false
p(4).
true
```
[Answer]
## PowerShell, 25 Bytes
```
!(Random -ma($args[0]--))
```
The [`Get-Random` function](https://technet.microsoft.com/en-us/library/hh849905.aspx) when given a `-Ma`ximum parameter `n` returns a value from the range `[0,n)`. We leverage that by subtracting 1 from our input `$args[0]`, so we're properly zero-indexed, and get a random value. Precisely `1/n`th of the time, this value will be `0`, so when we Boolean-not it with `!` it will return `True`. The other times will return `False`.
[Answer]
## J, 3 bytes
```
0=?
```
This is a monadic fork that takes an argument on the right. Similarly to APL, ? generates a random integer; however, J arrays are zero-based. So we compare to 0 instead of to the input.
[Answer]
## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), 7 bytes
```
1nH1=N.
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=%24l%5B14H1%3D%5D%24%2BN%2E&input=4)
### Explanation
```
1 Pushes 1
n Takes number from input
H Pops b,a and pushes a random integer between a and b, inclusive
1= 1 if equal to 1, 0 otherwise
N. Output as number and stop.
```
[Answer]
# PHP, 22 bytes
```
<?=2>rand(1,$argv[1]);
```
Reads `n` from command line, like:
```
$ php probability.php 4
```
Outputs (`false` is cast to an empty string in PHP) or `1` (in case of `true`).
[Answer]
## C#, ~~56~~ 45 bytes
Thanks to, pinkfloydx33 it's 45 now.
```
bool b(int n){return new Random().Next(n)<1;}
```
### Old 56 bytes
Generates random positive integer bigger or equal to 0 and smaller than `n` and checks if it's smaller than `1` and return comparison result.
```
bool a(int n){Random r=new Random();return r.Next(n)<1;}
```
] |
[Question]
[
## Introduction:
I think we've all heard of it, but here a very brief summary: Noah gathered two of every species of animal on the planet, male and female, to save in his Ark during a great flood. The actual quote from the Bible is:
>
> *Genesis 7:2-3*
>
> You must take with you seven of every kind of clean animal, the male and its mate, two of every kind of unclean animal, the male and its mate, and also seven of every kind of bird in the sky, male and female, to preserve their offspring on the face of the earth.
>
> [source](https://www.biblegateway.com/passage/?search=gen+7%3A2-3&version=NET)
>
>
>
But for the sake of this challenge we will ignore the clean/unclean part and the part where he took seven of each animal. This challenge is only about this part:
>
> two of every kind of ~~unclean~~ animal, the male and its mate
>
>
>
## Challenge:
**Input:**
You are given a list of positive integers (in random order).
**Output:**
Two distinct values indicating whether it's a 'List of Noah' or not. This doesn't necessary have to be a [truthy/falsey](https://codegolf.meta.stackexchange.com/a/2194/52210) value, so could also be `0`/`1` in Java/C#, or `'A'`/`'B'` in any language, to give some examples.
When is a list a 'List of Noah'? When there are exactly two of every integer in the list.
## Challenge rules:
* I/O is flexible. Input can be a list/array/stream of integers/floats/strings, or read one by one from STDIN. Output can be any two ***distinct*** values, returned from a function or output to STDOUT / a file.
* The integers in the input-list are in random order, and are guaranteed to be positive within the range \$1\leq n\leq100000\$.
* The input-list is guaranteed to be non-empty.
* Having an integer a multiple of two times present above 2 (i.e. 4, 6, 8, etc.) will be falsey. I.e. `[6,4,4,6,4,7,4,7]` is falsey, although you could still create equal pairs like this: `[[4,4],[4,4],[6,6],[7,7]]`.
## 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 with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Truthy:
[7,13,9,2,10,2,4,10,7,13,4,9]
[1,2,3,1,2,3]
[10,100,1000,1,100,10,1000,1]
[123,123]
[8,22,57189,492,22,57188,8,492,57188,57189,1,1]
Falsey:
[6,4,4,6,4,7,4,7]
[2,2,2,2,2,2]
[5,1,4,5,1,1,4]
[77,31,5,31,80,77,5,8,8]
[1,2,3,2,1]
[44,4,4]
[500,30,1]
[1,2,1,1]
[2,4,6,4,4,4]
[2,23,34,4]
[2,23,3,3,34,4]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 31 bytes
```
lambda l:{*map(l.count,l)}=={2}
```
[Try it online!](https://tio.run/##bVDNCoMwDL7vKXZTRxj2x7UKXvcEu80d3B8OahWnBxGf3aVWYR2j5MvPl6RJ6r4tKs2mZ5pNKi@v93yrkmFX5rWv9req0y2oYEzTgY5T3bx063unpmuLPvGCjQ08/bMAwiAGCiRE4EbNIQ7xJfjKI8gymNGNh1gyC8JiLp6bR7GaurUSKIVIEBkDj@nqSJCza21LE9ttKfUyfczV@@FucsCZORgURpyfsPn6nHiEnTkYRO0wQgAjyCBIPIlAEwf7cxL6syg3U7i9IrwGsweZPg "Python 3 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 33 bytes
```
lambda l:set(map(l.count,l))=={2}
```
[Try it online!](https://tio.run/##ZVDNDoIwDL77FN6ApDGsDDdMuPoE3tTD/CGYDCQwD8b47LMbGFnM0q8/X9u17Z6mvrdoq/JgtWpOF7XUm@Fq4kZ1sV6d74/WgE6Ssnzh23b9rTXLaNc/TP3cRIvRr@K9AJZBAQgsJeBO@RCH4pj80hiRGXgMwikVeCGYzMkL0pBqMaiUgAi5YLIAXuDXkSC9O9ojzXyvqTI6tFulh2uww5qm5eBQOJl/Q52/bx7OqSsHh6TnhBCQMSIIJF1CkEkz/V8CwwW5GyBolNMNMn8G@wE "Python 2 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 62 bytes (non-competing)
```
lambda x:{*[y.count(C)for C in (y:=x)]}!={*[2.]}##!2bcdfilmrtu
```
[Try it online!](https://tio.run/##TVHLboMwEDyHr9iQC6TbKDZQDBKnfAb1ITGgIBFA1JFAVb6drm0iVcjjnX2MZ8W46PvQR2KcVjVUNRTg@/732l0ft@oKc/57LJeTGp69Di5hM0xw2bX9LljyYg7la19QnZ/k63DY85uqmrZ7TPq5kkaZfzLp1XOtAr8p/A@jHnqekdDQ9lB6UKbIIsyQIzsTxOayqRgziVRnlI3QouNnarGHYAs35uqcurnrFcg5JikTGcYZfxOBwlIXuzLbpoepClQIxqEyDo1jiXAAfa8tgVb/1F1DrV9kMUaDqTl2nN54f5YnJByjQbptJk0xYpQhELRpSiH5@bcp35zERt3NJLRc5PaTuQfj1NKfaAIdIuhw/QM "Python 3.8 (pre-release) – Try It Online")
Just for fun, a solution that is itself a "List of Noah".
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
¢<PΘ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0CKbgHMz/v@PNtcxNNax1DHSMTQAEiYgCixkomMZCwA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##PU4xDsIwDNx5RdX5kGonxYmE6FIxs1cMIDEwMfAZZp7CA/hSOKctinz22WfnHs/L9X4rosdxaJvtoWmHsXze@9P3VVAmgwRkKKQjRE@1FZHPm0nYC6jorOO4BmEpF@ZTpVJdl6CK3iRlxKwrSUiVzvU8lrq5428RjubBDpfWR9ZTF@HITG6GIOSERLvGksf/drUejX7T1T39Bbf4Aw)
**Explanation**
```
¢ # count all occurrences of each element in the input list
< # decrement each
P # product
Θ # is equal to 1
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
```
ọtᵛ2
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Hu3pKHW2cDWdEWOkZGOqbmhhaWOiaWRjCOhY4FmAthQ6QNdQxjAQ "Brachylog – Try It Online")
### Explanation
```
ọ Get the list of occurences of elements in the input: [[x,2], [y,2], …]
ᵛ Verify that for each of those pairs…
t …the tail (i.e. the number of occurences)
2 …is 2
```
[Answer]
# [R](https://www.r-project.org/), 20 bytes
-6 bytes thanks to digEmAll by changing the input method
```
any(table(scan())-2)
```
[Try it online!](https://tio.run/##VU/tCsMgDPy/p@hPhbTUaKfC9jBdWWEwHOwDOsae3Z1WC0NySc47Y@5xPs6vMD0vtyAW@XlMY2gObbNxXdfJJY7hLZ7j6XoWSSCkbFnG724Wk7CkNHliUj3ApJQpQ17KrFDgNWWsTA9ZDkApS1cVDAdXvSNmGqxynozn2jhyuV3r9VptL@zxA0MJbYrCwlxPYQZ4DCVELpy1pBU4gMM6FiWG/a3D2yCT5lTngB10XiP@AA "R – Try It Online")
Outputs `FALSE` if it is a list of Noah, and `TRUE` otherwise. Works for any input type, not only integers.
Computes the count of each value in the list, and checks whether any of the counts are different from 2.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~39~~, 32 bytes
```
l=>l.All(x=>l.Count(y=>y==x)==2)
```
Thanks to @Expired\_Data
[Try it online!](https://tio.run/##hVHBCsIwDL37FcXTBlFs19kO7UBEQfDuQTzoqDCoHeiGivjtM53upKuUvCTtSx5Js8sgu@T1srLZdLWw1Umf9wejp7ktUzgUhUnJkajaqNQMZ8YENxfMi8qWwV2ld6VuoVIsrCe9zTkv9Tq3OjgGVl@3O/IgAmgECTCgIwTuXHPFISHPMPxdRJEaQYMe0gibNYbwCT@Zp4hhX@bpKoExiAWVCfCEtYkE2aTv@P1Mv3X6/Y6uY5yXg0PhrFseFdvTTYpRm4ND9N00ISCiSEOQuHWBIc7xb@vMtz7uxvBIxrj9qP2A@gU "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 [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")
```
2¨≡⍧⍨
```
[Try it online!](https://tio.run/##hU4xDsIwDNx5BQ9wJeKkJJ1ZYEKifKBSC0sFDAwwIyGB1AoGHsAEG3/gKflIOaeFFUU@@3y2c9mmjPJ9Vq6XUbHbFqu8yJuG309/uvvq4atns/DHi69qX98mU38@vF/aH69g6WwEnI8nabPoW1KaEmJSA4CRFFqGkt4/VaGnKaCwAeQQgK7smKiMSZY5R8wUW@USMgl/iSMXaFu3sgqbQ/xmSNBKoIOl7wOLMWdIEFk8W9IKHOBg16LE8Z9dDkeN3JTpGP50Z1G0UHH3Id4H "APL (Dyalog Extended) – Try It Online")
Is it true that…
 `2¨` two for each element
 `≡` is identical to
‚ÄÉ`‚çß‚ç®`‚ÄÉthe count-in selfie (count of own elements in self)
?
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
f x=and[sum[1|b<-x,b==a]==2|a<-x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjYxLyW6uDQ32rAmyUa3QifJ1jYx1tbWqCYRyIv9n5uYmWdbUJSZV6KSFm2oY6hjBIRAOvY/AA "Haskell – Try It Online")
For each element of the input we ensure it appears twice in the input list.
`sum[1|b<-x,b==a]` is just a golfier version of `length(filter(==a)x)`.
[Answer]
# [Perl 6](http://perl6.org/), 18 bytes
```
{so.Bag{*}.all==2}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/ujhfzykxvVqrVi8xJ8fW1qj2f3FipYKSSryCrZ1CdZqCSnytkkJafpGCjaGdDpBQgFEKRnAGkPkfAA "Perl 6 – Try It Online")
* `.Bag` converts the input list to a `Bag`--a set with multiplicity.
* `{*}` extracts all of the multiplicities.
* `.all` creates an and-junction of the multiplicities.
* `== 2` results in another and-junction of Booleans, each true if the multiplicity is 2.
* `so` collapses the junction to a single Boolean.
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
[:*/2=#/.~
```
[Try it online!](https://tio.run/##VU/LDsIgELz3KyZ6IBJtYQGhTXoy8eTJq0djY7z4B/46LrRQDeywM7vs4xU3rZgwDhDYQ2FgO7Q4XS/neBtkR@O2az9x16B53J9vTPDQBj0IWjHY9GTJoi8pmgNmxiopvtkYFndhNYVMskIDiOC8Dj1sT4UE1hOd/TmsSw0hpRTl/5Enshl9siLTeorkuILNyG9d08NoFhmCSsxx5/C/Ia3D29Ssfna8l/ldLaUyjV8 "J – Try It Online")
[Answer]
# JavaScript (ES6), 37 bytes
Returns *false* for Noah or *true* for non-Noah.
```
a=>a.some(v=>a.map(x=>t-=v==x,t=2)|t)
```
[Try it online!](https://tio.run/##dVDLDsIgELz7Iy3JaoRSoRp69Au8qQeirY/UYiw2mvjvdWltog2GMLvLLLMwZ13ranc7Xe24NPusyVWjVaonlblkYe2yi76GD5XasaqVeoBVjLwsaXamrEyRTQpzCIPV7W6Pz3lAFqPv8zxcC6ARJMCAThG4C@0Rh2RLyLCbYk8ELfrYKV5vN8In/VS@boZKzKcjgTGIBZUJ8IT1hQTZll3e0bRT/hEINuVSF1XmvjtUnuG/ODgUbntm47h@edgYJ3JwiNHDCwERRR5BopECU3z2XyOZ1xju3uhTj9HJqDOzeQM "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input
a.some(v => // for each value v in a[]:
a.map(x => // for each value x in a[]:
t -= v == x, // decrement t if v is equal to x
// (i.e. if v appears exactly twice, t is decremented twice)
t = 2 // start with t = 2
) // end of map()
| t // yield t, which is supposed to be equal to 0
) // end of some()
```
[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")
Anonymous tacit prefix function. Returns `0`/`1`.
```
∧/2=⊢∘≢⌸
```
[Try it online!](https://tio.run/##PU49iwJBDO39JQoRd7Kzzmxx1TV3FgqunVgIgo2grSxXHRx7iys2gpWFFjb@AH9P/sj6Mn4w5CUvecm86WrRnq2ni@W8rqW4dPhDypMUB/k/yeZW57Ldy9@uKdWWpfwFy4afwNHXd9ZC7mWDvlTHH6nOeQS81mNHJqaUmEwEsJpCy1I6aYwNejEFVBZhHALwLJ9Mpwwlq84TMyXO@JRsyi/iyQf6qB9jEza7@M2SotNAB0uvB5ZAZ0kRGdw5ig04wMOuQ4njb7scjlq9qeoE/mK1eAc "APL (Dyalog Unicode) – Try It Online")
…`⌸` for each value as left argument and indices of occurrences of that value as right argument, call:
 `≢` tally the right argument (the occurrences)
‚ÄÉ`‚àò`‚ÄÉthen
 `⊢` return that, ignoring the left argument
‚ÄÉ`2=`‚ÄÉBoolean list indicating which tallies are 2
‚ÄÉ`‚àß/`‚ÄÉAND-reduction (i.e. are they all true?)
[Answer]
# [MS SQL Server 2017](https://docs.microsoft.com/en-us/sql/sql-server/sql-server-technical-documentation?view=sql-server-2017), ~~152~~ ~~150~~ 146 bytes
```
CREATE FUNCTION f(@ NVARCHAR(MAX))RETURNS
TABLE RETURN SELECT IIF(2=ALL(SELECT
COUNT(*)FROM STRING_SPLIT(@,',')GROUP BY
PARSE(value AS INT)),1,0)r
```
The readable version:
```
CREATE FUNCTION f(@ NVARCHAR(MAX)) RETURNS TABLE RETURN
SELECT IIF(2 = ALL(SELECT COUNT(*)
FROM STRING_SPLIT(@, ',')
GROUP BY PARSE(value AS INT)), 1, 0) AS r
```
Try it on [SQL Fiddle](http://sqlfiddle.com/#!18/dfcbb/1)!
*-2 bytes thanks to Kevin Cruijssen*
[Answer]
# [Haskell](https://www.haskell.org/), ~~61~~ 45 bytes
```
import Data.List
all((2==).length).group.sort
```
[Try it online!](https://tio.run/##PU67DoMwDNz7FRk6gGQhEkITBraO/QPEkIG2qOEhSL@fngNUkc8@39nx262fzvtt64d5WoK4u@CyR7@Gy7N23ieJqus08934Cu80ey3Td85WGLfB9aOoxbz0YxBXMbhZPEXTGJIFVaRI5gDNKbY0VS01Er2CIjLLIccAHOXBWFVwKvZZUopKI21FulInsWQj3etdlnHyht80MRoOdDB0PrASPk2MyODGUCHBARbnGpRY/j9XxaWad7K7xH3FcSJrqNrtBw "Haskell – Try It Online")
Thanks to @KevinCruijssen for 12 bytes, and @nimi for another 4.
First Haskell answer, but it was surprisingly easy to do. Can ~~probably~~ be golfed a lot. *Case in point...*
[Answer]
## TI-Basic, 47 Bytes
```
Input(L1
SortA(L1
not(remainder(dim(L1,2)) and prod(not(‚ñ≥List(L1))=seq(remainder(I,2),I,1,-1+dim(L1
```
I am a big of fan of TI-Basic. It's not a great language for really any purpose, but I enjoy programming (and golfing) in it.
How does this code work?
First, it sorts the list.
Second, it uses the ‚ñ≥List function to generate another list, which is the difference between elements of the sorted list. (For example, ‚ñ≥List({1,3,7,8}) would yield {2,4,1}). Applies not to this list, which converts every non-zero element of the list to zero and every zero to one.
Then, the program checks that the resultant list fits the pattern `{1, 0, 1, 0, ...}`, which will only be true if the original list is a Noah list.
There is also an additional check that the length of the list is even, to catch some edge cases.
Here are some screenshots of test cases:
[![Some test cases](https://i.stack.imgur.com/t3zku.png)](https://i.stack.imgur.com/t3zku.png)
[![Some more test cases](https://i.stack.imgur.com/vtvML.png)](https://i.stack.imgur.com/vtvML.png)
[Answer]
# [Julia](https://julialang.org/), ~~30 characters~~ 26 bytes
```
!a=all(x->2==sum(a.==x),a)
```
Thank you, H.PWiz for this trick!
[Try it online!](https://tio.run/##VU5JDsIwDLz3FXAr0lARJyXpIf1IxSEXJFBBiEXqgQfwBN7HR4rtpkIoysQzHsdzfPSHZIZxH8dliqnvy2HdUoy3x6lMVYzDCmk1dkXnYSwaEMyGwcmjkkOzQ9EZFi0UlW7YoJchl5lpm9hL6gwgQu1NaOAamklAUDrVU9vobNFteaeDoJcrn/DcfITW7HUQ5FcE72ENCwyBc3suecMvN02xnHysAzUntXNYaU8l5cXZxess7B9BFordonq2i8v1cL7358/rvR@/)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
Qœ^Ƒ
```
[Try it online!](https://tio.run/##RU6xDQIxDOwzyxUfJyHJGJQoejoa9AvQ0lAj1mALBIOwSDg7/0KRz77z2fH5tCyX3vfvx/Fz76/b9/o89N5cy/ABFQI/EaImkyLqDNc8xQBDoxMNFoS1XJm1hV4xZ4EIUvalIlbZSEExOurR9mN2xy8jFLOGShzbntJEa4Qiswo5I3gKhMKzM0t@8D9bxuaoi20g8dCgt7r5Bw "Jelly – Try It Online")
```
Q Is the list of unique elements
Ƒ unchanged by
œ^ symmetric multiset difference with the whole input?
```
In broader terms, "if you remove each unique element once, do you have one of each left?" This is guaranteed to stay in the right order because `œ^` is implemented as equivalent to `œ-œ|œ-@`, `Qœ-` is just empty, and `œ-` [specifically removes elements last-first](https://github.com/DennisMitchell/jellylanguage/blob/70c9fd93ab009c05dc396f8cc091f72b212fb188/jelly/interpreter.py#L644) while `Q` is in the order of first appearances.
[Answer]
# [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), 64 bytes
```
f(a)==forall y in set inds a&card{x|x in set inds a&a(x)=a(y)}=2
```
---
### Explanation
VDM works predominantly like second order logic statements.
```
forall y in set inds a //Bind y to each of the indices of a
{x|x in set inds a&a(x)=a(y)} //build a set of the indices of a who have the same
//value as the value at y
card {...} = 2 //and check the cardinality of that set is 2
```
---
### Since you can't TIO VDM here's output from a debug session
[![](https://i.stack.imgur.com/BzTC2.png)](https://i.stack.imgur.com/BzTC2.png)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~66~~ ~~37~~ 26 bytes
-11 bytes thanks to mazzy
```
!(($args|group|% c*t)-ne2)
```
[Try it online!](https://tio.run/##dU/RboMwDHzPVzCVLrC5UmNCEx72LVM1hbYTKhW0WqXSb2fnANrTFPnssx37fGl/QtcfQ9OMaf3xGF@yLN13h344dO3tMqyTr7drvjkHzsenUqtrdwsqc2QKqojJbAFWXExZqnJSmUGyoIiRbtEQDTCHM4tlRi/HTk/MVDrjK7IVL8STj3SKpzLm5MP6oV/TOtHv6efmuz2ddaKHU7g/ldZqVe@bHlJ3EGVJ0InJFgxentASwywJwkvCOSoMEgCPwxxCSPg7jCfdVgbHDyVOKZZrpDyFPC@Wrn@1jr8 "PowerShell – Try It Online")
Groups up `$l` and grabs all the counts of matching values. It then filters out all counts of 2 from this list. If the list is empty, it's a Noah number; otherwise, it'll be populated still with non-2 counts. Not-ing the list will yield `True` if it's empty and `False` if it's populated
[Answer]
# [Elixir](https://elixir-lang.org/), 52 bytes
```
fn v->Enum.all?v,fn x->2==Enum.count v,&x==&1end end
```
[Try it online!](https://tio.run/##dVDLDoIwELz7FZyMJiuhS7HlUD158OQHGA9GISHBahQIf4/TihepaXb2Mdvpdou66qvnUJqhtFG32uxse4vPdb3tCIV@tWFjfO1yb20TdTTvjZmLwl4j2LA/xJV9PYpLE5Xx4qhIpJQTk0gA0jlfkpSflrOfZoGWlDwGyASXvQHGcMwCzQwdDqhoYqZMCZ2TzPmbaNI@/cQfWnjd3/trTC7JoXI2fQCa3zMlM6hKcgg/pZWiVIAGaOxJIcRk//bEoY9LN15AOsOe0vCqnFCI4PGjXm94Aw "Elixir – Try It Online")
Complete Elixir noob here :-D.
[Answer]
# [PHP](https://php.net/), 60 bytes
```
function($a){return!array_diff(array_count_values($a),[2]);}
```
[Try it online!](https://tio.run/##RVHRaoQwEHz3K7big8LCXaJXFXv0Q6xI8BK8ckSJsVCO@3a7iZESMpndzGZndR7n7eNzHucoSqxc7AJXaCOAtkSWY40c2ZmgcIdPFVh3CHA6gTWrdEpG9zl67NAnzqT2myDQEAUBJz0P6go5x0vJqhqLmh9BhZUPd75fM1/vat7JRoEOS7fJEPlR4rF4Q/TIsfYWFyot0CGde6osMWeUIqhospIotQz2/ED8cFu4XqHsQkPk/3M40RHw4Mhpo66h76nguqlVD/Y@6TQR2dNIuxr9JowRv/3trlS602Fate1/xGOVixNiy7useW30iJqMFMOYQvg7YiEGGTyppRzGCb6XSfdSD9NNponNEOIv61aMkKgjo@Mmem1/ "PHP – Try It Online")
PHP has great built-ins for this, though at 20 chars, `array_count_values()` is not a very golfy one.
[Answer]
## Mathematica, ~~25~~ 24 bytes
```
MatchQ[{{_,2}..}]@*Tally
```
[Try it online!](https://tio.run/##RU7BCsIwDL33KzxLmGva2e4g7AcEBW8iUoZjg82D7CKl3z6TdENKX/KSl@RNYe5fU5iHNizd7rScw9z213uMT8BUFOnR7G9hHL/L5TO852bfHZqoogNtoAYEXRJYDlKyUCdQUVPRgKDQkgTyCdZ0ZdJG0qIoPSBC5bSvwda4EQ9eaM5zW8usike6aYHR8eclNLc9phVpLTBS5IJzYDQVCDz5dpTShb9vzLYsL5aBipyazSy3c4rrYVaptPwA)
The `Tally` function returns a list of the form `{{*element*, *count*}, ...}`, which is then matched against a pattern that checks whether all *count* are 2.
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 16 bytes
```
${All&x!{_~x=2}}
```
[Try it online!](https://tio.run/##VU/BCsIwDL3vKyYMTznYrLOdIEO8iwdvY8jQToUhYisoMn99pt26aUtf816TNK80pjycVVuFi2UbvVd1PX1O3vvPc4lN026UOuo8ut0OpyLY3i9Xs1ParEutdF5BmAchrSwLzf1hzi/HcgEshhQQ2IyA28tJHNICuhRGDzE4HKQZJbpD0Ic9G1KQanCokIAIiWAyBZ6iJxKko13cPTPXw89albVW/axzmoqDRWGPb03d/PZSQl04WKTbi0JAzEgkkORSUEj//7vE0QC3nw3FCXmLf@3Z1JFiP5itCIqi/QI "Attache – Try It Online")
## Explanation
```
${All&x!{_~x=2}}
${ } lambda with input x
All&x!{ } over each element _ of x:
_~x check that the number of occurrences of _ in x
=2 is 2
```
## Alternatives
**17 bytes:** `{All&_!`=&2@`~&_}`
**18 bytes:** `{All[`=&2@`~&_,_]}`
**23 bytes:** `Same@2&`'@Sum@Table[`=]`
**25 bytes:** `Same«2'Sum@Table[`=,_]»`
**25 bytes:** `Same<~2'Sum@Table[`=,_]~>`
**25 bytes:** `{Same[2'Sum@Table[`=,_]]}`
**35 bytes:** `{Commonest@_==Unique@_and _[0]~_=2}`
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, ~~22~~ 21 bytes
```
@(x)any(sum(x==x')-2)
```
Anonymous function that inputs a numeric vector, and outputs `0` if the vector satisfies the condition or `1` otherwise.
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzMa9So7g0V6PC1rZCXVPXSPN/mka0uY6hsY6ljpGOoQGQMAFRYCETHctYzf8A) Or [verify all test cases](https://tio.run/##RVDLCoMwELz7FbnVwFZMjE2kBPofUoqInqw9qMVS@u12NmpL2NmdfQ551GP1bJbWJ0myXOJZVv0rHqZ7PHs/H@RRy2VshvFWV0MzCC/epSWVUUGaVAow7ELKUHEVpUIuo4DMUpSDAbZwY1zV6NTc50hryq1yBZlC78SRC3SN17LiSWiNyhMuGmK0bNiCwf2B5eg1xAgPbi1lChzgINkixIGfZB0kGd7J3Tk0Zizzc47qpuvaqY9bEv@/kMsX).
### Explanation
```
@(x) % define anonymous function with input x
x % x
x' % x transposed and conjugated
== % equality comparison, element-wise with broadcast. Gives a
% square matrix
sum( ) % sum of each column
-2 % subtract 2, element-wise
any( ) % true if and only if any value is not zero
```
[Answer]
# [Julia 1.0](http://julialang.org/), 32 bytes
```
l->sum(isone,l./l')/length(l)==2
```
[Try it online!](https://tio.run/##hZHNTsMwDMfvfYpol7WS2ZqPkvRQxIkn2A1xGCLtikKQlkSCpy9OP4QqltIqjlP/bNf/vAfTn@nXEFxvO3LSzmdtM5i7Bxc@8t59Wg3mcDT74mi07fwlN0XTsOHRI@m0J7vTNfjL94686q63GcFnjJE2f5ZAOdTAgJZoRNzGTwLql4I0DfHXoNcpFEEOo00iJRYaF5rZnU/JFIY1WbKiAsagklTVIGq2HBSo8Tj5U5iuemj7lv0K8XQ2Tt8W4h5HFhCtjGsq0UZ@zWHv5U0yFf6EgGhxT1JSAqdIoVGoukQX50nik@xsme4GIeIE6X4Vys/LjfzYgW7E2SzQVhOUhQP/n4C/FF7V8AM "Julia 1.0 – Try It Online")
Divides each element of the input array `l` by the transpose `l'` giving a matrix. Summing over this matrix while applying `isone` to each element gives twice the length of `l` if each element appears exactly twice.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 9 bytes
**Solution:**
```
&/2=#:'.=
```
[Try it online!](https://tio.run/##y9bNz/7/X03fyFbZSl3P1lzB0FjBUsFIwdAASJiAKLCQiYLl//8A "K (oK) – Try It Online")
**Explanation:**
```
&/2=#:'.= / the solution
= / group
. / value
#:' / count (length of) each
2= / equal to 2?
&/ / take minimum
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 17 bytes
```
2==##&@@Counts@#&
```
[Try it online!](https://tio.run/##VU7LCsIwELz3NwI9rdhsUpMcKgF/wLt4KGKxh1bQeCr99ribpIiEzO7Mzj6mPjzuUx/GWx@HLmLXCVF7f3p@5vD2oo7n1ziHi9gdBy@u9d4v1WJAKnCAIBsCzSFJGtwK1SJJVJAw0YYM6ROUtLBURvJiclpAhNZI60A73IgFm2jOc1nm3gOt1MBo@LNEbdtj2pJVAyNFFowBJUkgsHS2oZQW/M7GPFnz4NTQ0qFqu5XLOcWyuLhonQL1R6AI1Rq/ "Wolfram Language (Mathematica) – Try It Online")
`Counts` returns an association of `<| *(value)*->*(# occurences)*, ... |>`. Then `2==##&` checks if those occurence-counts are all equal to 2.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 4 bytes
```
oĉŤđ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVA7DsIwDBUrp6gyu1LzKUnOUnUoqCwIOrQcgpGZpUMRDByjXILT8JykCEV5fs9-sa3cnqf20B2boXlVIj8KykTeinq8n4d97h7dfHlP83Xqt7s-5cbPKqssSU2eFMkCYDiElCFfryuJnKaArAqUwwUkmhRXFZyKfY6UotJK58l4tQhHLsjIY1mGlxtMM8Ro-SKDR8uBKuEzxIgIbS1pCQ1wWNeCovlvXRWaGu7J7hL76bQi1wJTaWC0YIwm_c8p6fhTXw)
```
oĉŤđ
o Sort
ĉ Split into runs of equal elements
Ť Transpose; fails if not rectangular
đ Check if length is 2
```
---
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 4 bytes
```
oĭu=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVAxDsIwDBQrr6gyuxJxUpIMvKTqUFBZUOnQ9jUsHajEAL_gFbyGc5oiFOV8Z19sK7fHtbl0bT3Uz1LlraJM5Y2qpnkczrmfu_drPNz746lPmemzyUpH2lAgJr0DWAkxZSlU21IjZyiiqB3K8QISTUqqDCeLzxMzFU77QDbwKjz5KBe-lHV8ucc0S4JOLjJ4tB6oAj5LgojQzpHR0ACPdR0omv_W5djUSk9xF9jPpBWlFhmngYsFYwyZf05JLz_1BQ)
```
oĭu=
o Sort
ĭ Uninterleave
u Uniquify
= Check equality
```
---
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 4 bytes
```
Ţ≡2=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVAxDsIwDBQrr6gyu1LjpCQdeEnVoaCyoMLQ8gjewFIQCAa-wScYeQnnNEUoyvnOvthWTo9ds923dV8_S5W2ihKVNqoabod-k_r76_I5nnl57VbrLuaG9ywpHWlDBTHpDGAlhJSlopqXGjlDAUVlKIcLiDQqqTKcLD5PzJQ77QuyBU_Ckw9y5GNZh5cLTLMk6OQig0fTgcrhsySICO0cGQ0N8FjXgaL5b10OTa30FHeO_UxcUWqBcRw4WjDGkPnnFPX4U18)
```
Ţ≡2=
Ţ Tally; produces a list of unique elements and a list of their counts
≡ Check if all counts are equal, and return that value
2= Check if equal to 2
```
[Answer]
# Elm 0.19, 66 bytes
```
n a=List.all(\x->List.foldl(\y c->if x==y then c+1 else c)0 a==2)a
```
Verify all test cases [here](https://ellie-app.com/62XcGPK4CGna1).
For every item, iterate over the list and count how many items it is equal to. Return `True` if the count is exactly 2 for each item, `False` otherwise.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
!n#2/LQ
```
[Try it online!](https://tio.run/##K6gsyfj/XzFP2UjfJ/D//2gzHRMgBJHmIBwLAA "Pyth – Try It Online")
```
!n#2/LQQ Implicit: Q=eval(input())
Trailing Q inferred
L Q For each element of Q...
/ Q ... count its occurrences in Q
# Filter keep those elements...
n 2 ... which are not equal to 2
! NOT - maps [] to True, others to False
Implicit print
```
] |
[Question]
[
# *[All credits to Adnan for coming up with this challenge.](http://chat.stackexchange.com/transcript/message/32016426#32016426)*
My last challenge, before [I go on break](http://chat.stackexchange.com/transcript/message/31944993#31944993).
# Task
Given positive integer `n`, if `n` is odd, repeat `/` that many times; if `n` is even, repeat `\` that many times.
(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)
# Specs
* Any reasonable input/output format.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
# Testcases
```
n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\
```
[Answer]
# Javascript, 22 bytes
```
n=>"\\/"[n%2].repeat(n)
```
Defines an anonymous function.
If only `*` repeated strings in Javascript. *sighs*
[Answer]
## Python, 20 bytes
```
lambda n:'\/'[n%2]*n
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E)/[2sable](https://github.com/Adriandmen/2sable), ~~15~~ ~~11~~ ~~9~~ 8 bytes
```
DÈ„/\sè×
```
*-2 bytes thanks to Leaky Nun*
*-1 byte thanks to Emigna*
[Try it online! in 05AB1E](http://05ab1e.tryitonline.net/#code=RMOI4oCeL1xzw6jDlw&input=NA)
[or in 2sable](http://2sable.tryitonline.net/#code=RMOI4oCeL1xzw6jDlw&input=NA)
[Answer]
# Perl, 20 bytes
Includes +1 for `-p`
Run with input on STDIN:
```
squigly.pl <<< 6
```
`squigly.pl`
```
#!/usr/bin/perl -p
$_=$_%2x$_;y;01;\\/
```
[Answer]
# J, 10 bytes
```
#'\/'{~2|]
```
This is a six-train verb, consisting of:
```
# ('\/' {~ 2 | ])
```
This is a hook between `#` and `('\/' {~ 2 | ])`; a hook `(f g) y` expands to `y f (g y)`, so this expands to `y # (... y)`, which, for single-characters, yields a list of `y` characters.
The second part is a 5-train, consisting of:
```
'\/' {~ 2 | ]
```
This evaluates to two forks:
```
'\/' {~ (2 | ])
```
The inner fork, `2 | ]`, is modulus two. The outer fork, therefore, is:
```
'\/' {~ mod2
```
Which takes (`{~`) the mod2 index (`mod2`) from the string `/`.
Then, using the hook from above:
```
y # (apt char)
```
This yields what we want, and we are done.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 21
```
.+
$*/
T`/`\\`^(..)+$
```
[Try it online](http://retina.tryitonline.net/#code=JShHYAouKwokKi8KVGAvYFxcYF4oLi4pKyQ&input=MQoyCjMKNAo1CjY) (First line added to allow multiple testcases to be run).
[Answer]
# C#, 42 bytes
```
string f(int n)=>new string("\\/"[n%2],n);
```
Selects the correct character, then creates a new string consisting of that character repeated `n` times.
[Answer]
# PHP, 38 bytes
```
for(;$i++<$a=$argv[1];)echo'\/'[$a%2];
```
(variant 38 bytes)
```
while($i++<$a=$argv[1])echo'\/'[$a%2];
```
(variant 38 bytes)
```
<?=str_pad('',$a=$argv[1],'\/'[$a%2]);
```
(variant 40 bytes)
```
<?=str_repeat('\/'[($a=$argv[1])%2],$a);
```
[Answer]
# C, 40 bytes
```
i;f(n){for(i=n;i--;)putchar(n%2?47:92);}
```
[Try it on Ideone](https://ideone.com/vf6w78)
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 5 bytes
```
ị⁾/\x
```
[Try it online!](http://jelly.tryitonline.net/#code=4buL4oG-L1x4&input=&args=NA) or [Verify all testcases.](http://jelly.tryitonline.net/#code=4buL4oG-L1x4CjZSw4figqw&input=)
```
ị⁾/\x
ị⁾/\ modular-indexing into the string "/\"
x repeat
```
[Answer]
## Haskell, 25 bytes
```
f n=cycle"\\/"!!n<$[1..n]
```
-1 byte thanks to Damien with `cycle`.
[Answer]
# Mathematica, ~~34~~ ~~32~~ 28 bytes
```
If[OddQ@#,"/","\\"]~Table~#&
```
Anonymous function. Takes an integer as input and returns a list of characters as output.
[Answer]
# Mathematica, 29 bytes
```
"\\"["/"][[#~Mod~2]]~Table~#&
```
Cruelly exploits the fact that `[[1]]` returns the first argument of a function while `[[0]]` returns the function (head) itself, applied to the strangely valid function named `"\\"` which is being "evaluated" at `"/"`.
[Answer]
# Powershell, ~~30~~ 27 bytes
Update:
```
param($n)('\','/')[$n%2]*$n
```
Switching to `param`, thanks to [timmyd](https://codegolf.stackexchange.com/users/42963/timmyd).
---
```
"$("\/"[$args[0]%2])"*$args[0]
```
or slightly more readable
```
("\","/")[$args[0]%2]*$args[0]
```
Test:
```
> 1..10 | % { ./run.ps1 $_ }
/
\\
///
\\\\
/////
\\\\\\
///////
\\\\\\\\
/////////
\\\\\\\\\\
```
[Answer]
# Ruby, 15 bytes
```
->n{'\/'[n%2]*n}
```
See it on eval.in: <https://eval.in/632030>
[Answer]
# Fourier, 27 bytes
```
92~SI~N%2{1}{47~S}N(Sai^~i)
```
[**Try it online!**](http://fourier.tryitonline.net/#code=OTJ-U0l-TiUyezF9ezQ3flN9TihTYWlefmkp&input=Ng)
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 15 bytes
```
:2%:"\/"rm:?jbw
```
[Try it online!](http://brachylog.tryitonline.net/#code=OjIlOiJcLyJybTo_amJ3&input=Ng)
### Explanation
```
:2% Input mod 2…
:"\/"rm …is the index of the element in string "\/",…
:?j …element that we juxtapose Input times to itself…
bw …and print to STDOUT after removing one slash/backslash
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 9 bytes
```
ri_"\/"=*
```
[Try it online!](http://cjam.tryitonline.net/#code=cmlfIlwvIj0q&input=NQ)
### Explanation
```
ri e# Read input and convert to integer N.
_ e# Duplicate N.
"\/"= e# Use N as cyclic index into "\/", giving '\ for even and '/ for odd inputs.
* e# Repeat N times.
```
[Answer]
# ><> (Fish), 30 Bytes
```
:2%?'/'o1-:?!;30.
30. >'\'50p
```
First time using this language, but I think I at least saved a little room by conditionally using the / as either part of the output or a mirror to redirect flow. Probably still horribly inefficient though, I feel like it could probably be cut down a little more at the very least.
Input is the initial stack, output is `stdout`
[Try it online!](https://fishlanguage.com/playground/iR7o6DFo3MvNG5dWJ)
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 11 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
Requires `‚éïIO‚Üê0` which is default on many systems.
```
⊢⍴'\/'⊃⍨2|⊢
```
`⊢` the argument
`⍴` reshapes (repeats)
`'\/'⊃⍨` the string "/" selected by
`2|⊢` the division remainder when the argument is divided by two
[TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20f%u2190%u22A2%u2374%27%5C/%27%u2283%u23682%7C%u22A2%20%u22C4%20f%A81%202%203%204%205&run)
[Answer]
# Java 11, ~~68~~ ~~65~~ 29 bytes
```
n->(n%2<1?"\\":"/").repeat(n)
```
-3 bytes saved thanks to *@user902383* and *@SeanBean*
-36 bytes switching from Java 7 to Java 11+
[Try it online.](https://tio.run/##LY7LDoJADEX3fEUziclMCBjcyUO/QDYuxcUIgylCIcNAYgzfjsNj0Sbtve09lRylVxWfOa9l38NNIv0cACSjdClzBekyAtyNRnpDzq0CJCK7nBzbeiMN5pACQTKTd@F0OMXBlWUZC9mRCV@rTknDSczR4u@GV239@9nYYgGNzeTb/8dTii2vbPUahUkQYZycI3TdXbIw396oxm8H43f2zNTE0WUhMJd8SyhWvAVwqWn@Aw)
**Explanation:**
```
n-> // Method with integer parameter and String return-type
(n%2<1? // If `n` is even:
"\\" // Use String "\"
: // Else (`n` is odd):
"/") // Use String "/" instead
.repeat(n) // Repeat it `n` amount of times
```
[Answer]
# Julia, 20 bytes
```
!x="$("/\\"[x%2])"^x
```
[Answer]
# R, ~~47~~ 46 bytes
```
n=scan();cat(rep(c("\\","/")[n%%2+1],n),sep="")
```
In R, you have to escape backslashes. the argument `sep` also has to be fully specified since it comes after `...`. Thus annoyingly few opportunities to save chars :(
Thanks to bouncyball for golfing away a byte.
[Answer]
# T-SQL 50 bytes
Of course no `STDIN` here, so let's assume a hardcoded `INT` variable like this: `DECLARE @ INT` then the solution is:
```
PRINT IIF(@%2=0,REPLICATE('\',@),REPLICATE('/',@))
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 8 bytes
```
"\/"@aXa
```
Straightforward. Uses modular indexing to select the character and string repetition to multiply it. [Try it online!](http://pip.tryitonline.net/#code=IlwvIkBhWGE&input=&args=NQ)
---
This question presents an interesting comparison between Pip, [Pyth](https://codegolf.stackexchange.com/a/91732/16766), and [Jelly](https://codegolf.stackexchange.com/a/91733/16766), the latter two each having scored 5 bytes. All three languages have implicit output, with single-char operators for modular indexing and string repetition, and no requirement to escape backslashes in strings. There are two key differences, though:
1. Under certain circumstances, Pyth and Jelly need only one delimiter to define a string;
2. Pyth and Jelly have syntax such that the input doesn't need to be explicitly represented in the code (though for very different reasons, as [Maltysen explained to me](http://chat.stackexchange.com/transcript/message/32067110#32067110)).
Neither one of these features is likely to show up in Pip1 (I don't like the aesthetics of unbalanced delimiters, and point-free syntax or implicit operands seem like they would be too alien to my infix expression parser), but I'm okay with playing third fiddle. Even though "readability" is extremely relative when golfing, I'd argue that those three extra bytes make the Pip program a lot easier to understand at a glance--and in my book, that's a worthwhile tradeoff.
1 Although, single-character strings in Pip use a single `'` delimiter, inspired by CJam and by quoting in Lisp.
[Answer]
# Psithurism, 11 bytes
```
*(%2?"/:"\)
```
This is a language I'm still developing, but I'm going to start posting answers here to get a feeling of what kind of built-in functions might be useful to have. (This one has taught me I really need some way to index into arrays/strings lol.)
explained:
```
*( # implicitly multiply the input by
%2 # implicitly take input mod 2
? "/ # / if truthy (1)
: "\ # \ if falsy (0)
)
```
Curious about Psithurism?
Github: <https://github.com/AroLeaf/psithurism/>
Docs (soon‚Ñ¢): <https://psithurism.leaf.moe/>
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
*@"\/
```
[Test suite.](http://pyth.herokuapp.com/?code=%2a%40%22%5C%2F&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6&debug=0)
Modular-indexing into the string `\/` and then repeat.
[Answer]
# [Perl 6](http://perl6.org), 16 bytes
```
{<\ />[$_%2]x$_}
```
## Usage:
```
for 1..6 {
say $_, {<\ />[$_%2]x$_}( $_ )
}
```
```
1/
2\\
3///
4\\\\
5/////
6\\\\\\
```
[Answer]
# SpecBAS - 28 bytes
```
1 INPUT n: ?"\/"(ODD(n)+1)*n
```
`ODD` returns 1 if number is odd, then uses that as an index to print the correct character n number of times. Have to add 1 as SpecBAS strings start at character 1.
[Answer]
# Java 8, 56 bytes
```
(i,j)->{for(j=i;j-->0;)System.out.print(i%2<1?92:'/');};
```
I'd like to thank @Kevin Cruijssen in advanced for golfing my answer further.
# Ungolfed Test Program
```
public static void main(String[] args) {
BiConsumer<Integer, Integer> consumer = (i, j) -> {
for (j = i; j-- > 0;) {
System.out.print(i % 2 < 1 ? 92 : '/');
}
};
consumer.accept(5, 0);
consumer.accept(1, 0);
consumer.accept(8, 0);
}
```
] |
[Question]
[
### Input
The input is a single positive integer `n`
### Output
The output is`n` with its most significant bit set to `0`.
### Test Cases
```
1 -> 0
2 -> 0
10 -> 2
16 -> 0
100 -> 36
267 -> 11
350 -> 94
500 -> 244
```
For example: `350` in binary is `101011110`. Setting its most significant bit (i.e. the leftmost `1` bit) to `0` turns it into `001011110` which is equivalent to the decimal integer `94`, the output. This is [OEIS A053645](https://oeis.org/A053645).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~49~~ ~~44~~ ~~40~~ 39 bytes
```
i;f(n){for(i=1;n/i;i*=2);return n^i/2;}
```
[Try it online!](https://tio.run/##ZY7LCsIwEEX3/YpQEBKxNJm2KRLql4gg1cgsHCXUVem3xz7A2mSW9x7OnTZ7tK33aCwn0duX49goQzka3DcgjLt3H0eMLpiDGfzzisRF0idsvLdD6ixPFctOTLLd7UzpwXIlhNn0sO0h7JWcAFgFMiJ0MKFjxywp9J8l0oCuJ0ip9Rddh1BRzaZj@YPGJISqZQ7KlaqWvcF/AQ "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 27 bytes
```
lambda n:n^2**len(bin(n))/8
```
[Try it online!](https://tio.run/##K6gsycjPM/qfpmCrEPM/JzE3KSVRIc8qL85ISysnNU8jKTNPI09TU9/if0FRZl6JQpqGoYGB5n8A "Python 2 – Try It Online")
# 26 bytes
Unfortunately, this does not work for `1`:
```
lambda n:int(bin(n)[3:],2)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfpmCrEPM/JzE3KSVRIc8qM69EIykzTyNPM9rYKlbHSPN/QRFQTCFNw9DAQPM/AA "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
.²óo-
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f79Cmw5vzdf//NzUwAAA "05AB1E – Try It Online")
Removing the most significant bit from an integer **N** is equivalent to finding the distance from **N** to the highest integer power of **2** lower than **N**.
Thus, I used the formula **N - 2floor(log2N)**:
* `.²` - Logarithm with base **2**.
* `ó` - Floor to an integer.
* `o` - **2** raised to the power of the result above.
* `-` - Difference.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
BḊḄ
```
[Try it online!](https://tio.run/##y0rNyan8/9/p4Y6uhzta/v//b2xqAAA "Jelly – Try It Online")
# Explanation
```
BḊḄ Main Link
B Convert to binary
Ḋ Dequeue; remove the first element
Ḅ Convert from binary
```
[Answer]
# C (gcc) -- 59 bytes
```
main(i){scanf("%d",&i);return i&~(1<<31-__builtin_clz(i));}
```
This gcc answer uses only integer bitwise and arithmetic operations.
No logarithms here! It may have issues with an input of 0, and is totally non-portable.
It's my first answer on this site, so I'd love feedback and improvements. I sure had fun with learning bitwise expressions.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 23 bytes
```
n->n^n.highestOneBit(n)
```
[Try it online!](https://tio.run/##NU7BSsNQELznK4ZCIJHk0VZawWpAD4IH8VBvovBMXtKNyb6Qt6mUkm@Pr7Uehhlmd2en1nud2s5wXXxP1Ha2F9TeU4NQo8qBcyHL6moTdMNXQznyRjuHF02MYwBcXCdaPO0tFWj9LNpKT1y9f0D3lYvPq8CbfWZ5umTeeW0q02co7ydOM/5ktaNqZ5y8snkkiTieNue70vYRsYBuweYHXvrgIxYJlgkWc4/1ib1Yrm8SXK@8Ws3nGP8fA9uDE9MqO4jqfDMpo1lYIM0QFiHPElCCUumuaw4PzheLKI7/fo/BCeP0Cw "Java (OpenJDK 8) – Try It Online")
Sorry, built-in :-/
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~8~~ 6 bytes
```
B0T(XB
```
[Try it online!](https://tio.run/##y00syfn/38kgRCPC6f9/QwA "MATL – Try It Online")
Saved two bytes thanks to Cinaski. Switching to assignment indexing instead of reference indexing was 2 bytes shorter :)
### Explanation:
```
% Grab input implicitly: 267
B % Convert to binary: [1 0 0 0 0 1 0 1 1]
0T( % Set the first value to 0: [0 0 0 0 0 1 0 1 1]
XB % Convert to decimal: 11
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
```
ḋtḋ
```
[Try it online!](https://tio.run/##yygtzv7//@GO7hIg/v//v7GpAQA "Husk – Try It Online")
**Explanation:**
```
-- implicit input, e.g. 350
ḋ -- convert number to list of binary digits (TNum -> [TNum]): [1,0,1,0,1,1,1,1,0]
t -- remove first element: [0,1,0,1,1,1,1,0]
ḋ -- convert list of binary digits to number ([TNum] -> TNum): 94
```
[Answer]
# [Ohm v2](https://github.com/MiningPotatoes/Ohm), 3 bytes
```
b(ó
```
[Try it online!](https://tio.run/##y8/INfr/P0nj8Ob//w0NDAA "Ohm v2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 27 bytes
```
lambda n:n-2**len(bin(n))/8
```
[Try it online!](https://tio.run/##K6gsycjPM/qfpmCrEPM/JzE3KSVRIc8qT9dISysnNU8jKTNPI09TU9/if0FRZl6JQpqGoYGB5n8A "Python 2 – Try It Online")
# Explanation
```
lambda n:n-2**len(bin(n))/8 # Lambda Function: takes `n` as an argument
lambda n: # Declaration of Lambda Function
len(bin(n)) # Number of bits + 2
2** # 2 ** this ^
/8 # Divide by 8 because of the extra characters in the binary representation
n- # Subtract this from the original
```
[Answer]
# [Python 3](https://docs.python.org/3/), 30 bytes
*-8 bytes thanks to caird coinheringaahing. I typed that from memory. :o*
```
lambda n:int('0'+bin(n)[3:],2)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIc8qM69EQ91AXTspM08jTzPa2CpWx0jzf0ERSDxNw9DAQFPzPwA "Python 3 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 28 bytes
```
function(x)x-2^(log2(x)%/%1)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrNC1yhOIyc/3QjIVtVXNdT8n6ZhqMkFJAwgJJgyMjPX/A8A "R – Try It Online")
Easiest to calculate the most significant bit via `2 ^ floor(log2(x))` rather than carry out base conversions, which are quite verbose in R
[Answer]
## 32-bit x86 assembler, ~~10~~ ~~9~~ 7 bytes
Byte code:
```
0F BD C8 0F B3 C8 C3
```
Disassembly:
```
bsr ecx, eax
btr eax, ecx
ret
```
accepts and returns the value in the eax register.
Perform a reverse scan for the first set bit, and then reset that bit.
[Answer]
# Mathematica, 37 bytes
```
Rest[#~IntegerDigits~2]~FromDigits~2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8otbgkWrnOM68kNT21yCUzPbOkuM4ots6tKD8XxlP7H1CUmVei75Cm71BtqGOkY2igY2gGJA10jMzMdYxNDXRMDQxq/wMA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript, ~~22~~ 20 bytes
*Saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)*
```
a=>a^1<<Math.log2(a)
```
[Try it online!](https://tio.run/##DcxBDoIwEEDRq7hsk7GZ1oAb8AaewGCYQNESYZp2xOPXbv7u/ZUOylMKUc47z74sfaH@Rk/bdXeSt/nwyynSJSaefM4my8xfMb8UxKuHBQcWwba1CK69wqVBaBAHs1FU9bRUrM3KYR9Poy5/)
### Another approach, 32 bytes
```
a=>'0b'+a.toString`2`.slice`1`^0
```
[Try it online!](https://tio.run/##DcxBDsIgEADAr3grxHWzYFpP9RMejWaRUkOj0MCqz8de5jiL@7rqS1zlkPIU2jw2N547enR7h5IvUmJ6smWsr@gDG75TW0v2oVasMuWP4K9ECepqwIIhMMMmgR1OcOwJeqIbvt2qtnVWTmtccky8Y93@ "JavaScript (Node.js) – Try It Online")
[Answer]
# J, 6 bytes
```
}.&.#:
```
Pretty simple.
### Explanation
```
}.&.#:
#: convert to list of binary digits
&. apply right function, then left, then the inverse of right
}. behead
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 10 bytes
Tacit prefix function.
```
2⊥1↓2∘⊥⍣¯1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSjR11LDR@1TTZ61DEDyHzUu/jQekOg1KEVCoYKRgqGBgqGZkDSQMHIzFzB2NRAwdTAAAA "APL (Dyalog Unicode) – Try It Online")
`2∘⊥`… decode from base-2…
…`⍣¯1` negative one time (i.e. encode in base-2)
`1↓` drop the first bit
`2⊥` decode from base-2
[Answer]
# Ruby, 26 bytes
-7 Bytes thanks to Ventero.
-2 Bytes thanks to historicrat.
```
->n{/./=~'%b'%n;$'.to_i 2}
```
[Answer]
# C (gcc), 38 bytes
Built-in in gcc used.
```
f(c){return c^1<<31-__builtin_clz(c);}
```
[Answer]
**Excel, 20 bytes**
```
=A1-2^INT(LOG(A1,2))
```
[Answer]
# Excel, ~~36~~ 31 bytes
`-5` bytes thanks to @IanM\_Matrix1
```
=BIN2DEC(MID(DEC2BIN(A1),2,99))
```
Nothing interesting.
[Answer]
# ARM Assembly, ~~46~~ 43 bytes
(You can omit destination register on add when same as source)
```
clz x1,x0
add x1,1
lsl x0,x1
lsr x0,x1
ret
```
[Answer]
# Pyth, 5 bytes
```
a^2sl
```
[Test suite.](http://pyth.herokuapp.com/?code=a%5E2sl&input=1+%0A2+%0A10%0A16+%0A100%0A267%0A350+%0A500&test_suite=1&test_suite_input=1+%0A2+%0A10%0A16+%0A100%0A267%0A350+%0A500&debug=0)
Explanation:
```
l Log base 2 of input.
s Cast ^ to integer (this is the position of the most significant bit.)
^2 Raise 2 to ^ (get the value of said bit)
a Subtract ^ from input
```
[Answer]
## [Alice](https://github.com/m-ender/alice), 8 bytes
```
./-l
o@i
```
[Try it online!](https://tio.run/##S8zJTE79/19PXzeHK98h8/9/UwMDAA "Alice – Try It Online")
### Explanation
```
. Duplicate an implicit zero at the bottom of the stack. Does nothing.
/ Switch to Ordinal mode, move SE.
i Read all input as a string.
l Convert to lower case (does nothing, because the input doesn't contain letters).
i Try reading all input again, pushes an empty string.
/ Switch to Cardinal mode, move W.
. Duplicate. Since we're in Cardinal mode, this tries to duplicate an integer.
To get an integer, the empty string is discarded implicitly and the input is
converted to the integer value it represents. Therefore, at the end of this,
we get two copies of the integer value that was input.
l Clear lower bits. This sets all bits except the MSB to zero.
- Subtract. By subtracting the MSB from the input, we set it to zero. We could
also use XOR here.
/ Switch to Ordinal, move NW (and immediately reflect to SW).
o Implicitly convert the result to a string and print it.
/ Switch to Ordinal, move S.
@ Terminate the program.
```
[Answer]
# [Mathematica](https://www.wolfram.com/wolframscript/), ~~21~~ 17 bytes
```
#-2^Floor@Log2@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19Z1yjOLSc/v8jBJz/dyEFZ7X9AUWZeiUNatKmBQex/AA)
This is my first Mathematica answer, feel free to tell me what have I screwed up.
**-4 bytes** thanks to @HyperNeutrino!
So as it turns out, someone made a similar program before, and sent it to the OEIS. However, keep in mind that the floor of a logarithm is basically defined as the number of digits of a number. This is just a coincidence, or rather a task simple enough that many people will get the same answer.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 bytes
```
^2p¢ÊÉ
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=XjJwosrJ&input=MzUw)
### Explanation
```
^2p¢ÊÉ
¢ Get binary form of input
Ê Get length of that
É Subtract 1
2p Raise 2 to the power of that
^ XOR with the input
```
## If input `1` can fail: 4 bytes
```
¢Ån2
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=osVuMg==&input=MzUw)
**Explanation**: get input binary (`¢`), slice off first char (`Å`), parse as binary back to a number (`n2`).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 20 bytes
```
@(x)x-2^fix(log2(x))
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzQtcoLi2zQiMnP90IyNX8n1hUlFiZVpqnkaajEG2oYKRgaKBgaAYkDRSMzMwVjE0NFEwNDGI1/wMA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 bytes
```
⊢-2*∘⌊2⍟⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYt0jbQedcx41NNl9Kh3PpAPlDi0QsFQwUjB0EDB0AxIGigYmZkrGJsaKJgaGAAA "APL (Dyalog Unicode) – Try It Online")
-1 byte thanks to Adam
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 7 bytes
```
{2b()b}
```
[Try it online!](https://tio.run/##S85KzP3/v9ooSUMzqfb/fwA "CJam – Try It Online")
Explanation:
```
{ } Block: 267
2b Binary: [1 0 0 0 0 1 0 1 1]
( Pop: [0 0 0 0 1 0 1 1] 1
) Increment: [0 0 0 0 1 0 1 1] 2
b Base convert: 11
```
Reuse the MSB (which is always 1) to avoid having to delete it; the equivalent without that trick would be `{2b1>2b}` or `{2b(;2b}`.
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~15~~ 13 bytes
```
^(^1|\1\1)*1
```
[Try it online!](https://tio.run/##K0otycxL/K@qkaCnzaWi9T9OI86wJsYwxlBTy5Drv95/Qy4jLkMDLkMzIGnAZWRmzmVsasBlamAAAA "Retina – Try It Online")
Input and output [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) (the test suite includes conversion from and to decimal for convenience).
### Explanation
This is quite easy to do in unary. All we want to do is delete the largest power of 2 from the input. We can match a power of 2 with some forward references. It's actually easier to match values of the form **2n-1**, so we'll do that and match one **1** separately:
```
^(^1|\1\1)*1
```
The group `1` either matches a single `1` at the beginning to kick things off, or it matches twice what it did on the last iteration. So it matches `1`, then `2`, then `4` and so on. Since these get added up, we're always one short of a power of 2, which we fix with the `1` at the end.
Due the trailing linefeed, the match is simply removed from the input.
] |
[Question]
[
## Challenge
Given an integer \$Q\$ in the range \$-2^{100} ≤ Q ≤ 2^{100}\$, output the number of digits in that number (in base 10).
## Rules
Yes, you may take the number as a string and find its length.
All mathematical functions are allowed.
You may take input in any base, but the output must be the length of the number in base 10.
Do not count the minus sign for negative numbers. The number will never have a decimal point.
Zero can either have one or zero digits.
Assume the input will always be a valid integer.
## Examples
```
Input > Output
-45 > 2
12548026 > 8
33107638153846291829 > 20
-20000 > 5
0 > 1 or 0
```
## Winning
Shortest code in bytes wins.
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 1118 bytes
```
1 is waiting at Starchild Numerology.Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Pickup a passenger going to Crime Lab.'-' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 3 l.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 1 r 2 r 2 l.Switch to plan "n" if no one is waiting.-1 is waiting at Starchild Numerology.[n]0 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 r 1 l 1 l 2 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Addition Alley.Go to Cyclone:e 1 l 2 r.[r]Pickup a passenger going to Cyclone.Pickup a passenger going to Addition Alley.Go to Zoom Zoom:n.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to Addition Alley.Go to Chop Suey:n 1 r 2 r.Switch to plan "f" if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 l 3 l 1 l.Go to Cyclone:n 1 l.Switch to plan "r".[f]Go to Addition Alley:n 1 l 2 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.
```
[Try it online!](https://tio.run/nexus/taxi#tVTBasMwDP2VRy891azdTrl1G@wytkIGg5Ue3ERJTF052A6lX98lWZK2WdeFwQ5KsCzrPenJPkyhHHZSecUppEfopY0ypWO8FFuyRpt0L54MvMHCOI/XJFERBTtMoUuz1V8sVLQpckjk0jnilCxSUyUsTz1kJkdYUJulWwfcnsfdkDxWbQnPci3Gk3GP9LtVnuzY4ZFy4xugc2eNpnE7GKVh264btrPatAh3ykdZFZFryRjxCCoBGximE3JiMqi/S17dDNfh0lbgumZWNvutzH2kS6ZXY@ZxXLIxjLnWR/W@DgbUwFixtKt/QfowZlt/Am4852HHEfxDFb0ZrOroK5r8oOg1sLBg3iPcKHJYSLtpBeu5j7NYT/15Z@u9b2zsSCyT1cU@8CDF3zLCvVyTTpTLyLad6Lu7S3m9qydPwYXHgTtlDodP)
Ungolfed:
```
1 is waiting at Starchild Numerology.
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
Pickup a passenger going to Crime Lab.
'-' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 3rd left.
Pickup a passenger going to Crime Lab.
Go to Crime Lab: north 1st right 2nd right 2nd left.
Switch to plan "n" if no one is waiting.
-1 is waiting at Starchild Numerology.
[n]
0 is waiting at Starchild Numerology.
Go to Starchild Numerology: south 1st right 1st left 1st left 2nd left.
Pickup a passenger going to Cyclone.
Pickup a passenger going to Addition Alley.
Go to Cyclone: east 1st left 2nd right.
[r]
Pickup a passenger going to Cyclone.
Pickup a passenger going to Addition Alley.
Go to Zoom Zoom: north.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to Addition Alley.
Go to Chop Suey: north 1st right 2nd right.
Switch to plan "f" if no one is waiting.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 1st left 3rd left 1st left.
Go to Cyclone: north 1st left.
Switch to plan "r".
[f]
Go to Addition Alley: north 1st left 2nd left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: north 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.
```
Explanation:
```
Pickup the input and split it into individual characters
Pickup the value 1.
If the first character a hyphen, add -1. Otherwise, add 0.
Keep picking up characters and adding 1 until you're out.
Convert the running total to a string and print to stdout.
```
[Answer]
## Mathematica, 13 bytes
```
IntegerLength
```
There's a built-in... returns `0` for `0`.
[Answer]
# dc, 3
```
?Zp
```
Note that normally `dc` requires negative numbers to be given with `_` instead of the more usual `-`. However, in this case, either may be used. If `-` is given, then `dc` treats this as a subtraction on an empty stack, throws `dc: stack empty`, and then continues with the rest of the number; Thus the result is no different.
[Try it online](https://tio.run/nexus/bash#RYxNCoMwFAb3nuJDWlwFkpefRoT2Ht2V5IluEjFZ9u6pCNJZzsDMeUflUsOnMNYEYSwUWeMlOWit5MNpr6z2xtGoPI0QJA8gJ8Tc4WDb11Rn9PcC8USP2/U7K4cl/xW@iAGCMbTXe2tDF3Pi9gM).
```
? # input
Z # measure length
p # print
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 1 byte
```
l
```
[Try it online!](https://tio.run/nexus/brachylog2#@5/z/3@8oZGxien/KAA "Brachylog – TIO Nexus")
Another builtin solution, but this one has the shortest name (unless someone finds a language which does this task in zero bytes). This should work in both Brachylog 1 and Brachylog 2.
This is a function submission (the TIO link contains a command-line argument that causes the interpreter to run an individual function rather than a whole program), partly because otherwise we'd have to spend bytes on output, partly because Brachylog's syntax for negative numbers is somewhat unusual and making this program a function resolves any potential arguments about input syntax.
It's often bothered me that most of Brachylog's builtins treat negative numbers like positive ones, but that fact ended up coming in handy here. I guess there are tradeoffs involved with every golfing language.
[Answer]
## [Retina](https://github.com/m-ender/retina), 2 bytes
```
\d
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/gfk/L/v66JKZehkamJhYGRGZexsaGBuZmxhaGpsYWJmZGloYWRJZeukQEQAAA "Retina – TIO Nexus")
Retina doesn't really know what numbers are, so the input is treated as a string and we simply count the digit characters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
Äg
```
[Try it online!](https://tio.run/nexus/05ab1e#@3@4Jf3/f10TUwA "05AB1E – TIO Nexus") or [Try All Tests!](https://tio.run/nexus/05ab1e#qymr/H@4Jf1/pdLh/VYKSvY6/3VNTLkMjUxNLAyMzLiMjQ0NzM2MLQxNjS1MzIwsDS2MLLl0jQyAgMsAAA)
```
Ä # Absolute value
g # Length
```
[Answer]
## [Alice](https://github.com/m-ender/alice), 16 bytes
```
//; 'q<)e
o!@i -
```
[Try it online!](https://tio.run/nexus/alice#@6@vb62gXmijmcqVr@iQqaD7/7@uiSkA "Alice – TIO Nexus")
### Explanation
Finding a half-decent layout for this was quite tricky. I'm still not super happy with it because of the spaces, the `<` and the `;`, but this is the best I could do for now.
String length is one of those very common built-ins that doesn't exist in Alice, because its input is a string and its output is an integer (and all Alice commands are strictly integers to integer or strings to strings). We can measure a string's length by writing it to the tape in Ordinal mode and then finding its end in Cardinal mode.
```
/ Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP will bounce
diagonally up and down through the code.
! Store an implicit empty string on the tape, does nothing.
; Discard an implicit empty string, does nothing.
i Read all input as a string.
'- Push "-".
< Set the horizontal component of the IP's direction to west, so we're bouncing
back now.
- Remove substring. This deletes the minus sign if it exists.
'i Push "i".
; Discard it again.
! Store the input, minus a potential minus sign, on the tape.
/ Reflect to W. Switch to Cardinal. The IP immediately wraps to the
last column.
e) Search the tape to the right for a -1, which will be found at the end
of the string we stored there.
< Does nothing.
q Push the tape head's position, which is equal to the string length.
'<sp> Push " ".
; Discard it again.
/ Reflect to NW. Switch to Ordinal. The IP immediately bounces off
the top boundary to move SW instead.
o Implicitly convert the string length to a string and print it.
IP bounces off the bottom left corner, moves back NE.
/ Reflect to S. Switch to Cardinal.
! Store an implicit 0 on the tape, irrelevant.
The IP wraps back to the first line.
/ Reflect to NE. Switch to Ordinal. The IP immediately bounces off
the top boundary to move SE instead.
@ Terminate the program.
```
I also tried taking care of the minus sign in Cardinal mode with `H` (absolute value), but the additional mode switch always ended up being more expensive in my attempts.
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 37 bytes
```
-[+>+[+<]>+]>->,[-<->]<[>+>],[<+>,]<.
```
Output is by byte value.
[Try it online!](https://tio.run/nexus/brainfuck#bY@9DsIwDIT3PIV3N5lgs@4p2CIPBYJaqT@oLeLxi1NKoRKeYt19d87sI4Mji4IVHkX04qESwdAiCqNQCfOpqke69f2UBrJXlYZEU0/3oe4mmqpE3aM9Z62ja7rUbdlQOdIzNY1zItErbxMAB3z3LFuZz41QRLYLrHvZZBkFLAE7yJhfwu0RfQNxJXLiOmYIYmbODvvmEiT68W0VzjLCYpG/GSblw3OtzP5wfAE "brainfuck – TIO Nexus")
### Explanation
```
-[+>+[+<]>+]>-> Constant for 45 (from esolangs wiki)
, Read a byte of input
[-<->] Subtract that byte from 45
<[>+>] If the result is nonzero then increment a cell and move to the right
(0 means it was a minus; so not counted)
,[<+>,] Read a byte and increment the cell to its left until EOF is reached
<. Print the cell that was being incremented
```
[Answer]
# PHP, 23 Bytes
```
<?=-~log10(abs($argn));
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVTJQsuayt/tvY2@rW5eTn25ooJGYVKwBltTUtP7/HwA "PHP – TIO Nexus")
log of base 10 of the absolute value plus one cast to int
for zero as input log10 gives back `INF` which is interpreted as false
The better way is to replace `$argn` with `$argn?:1` +3 Bytes
# PHP, 27 Bytes
```
<?=strlen($argn)-($argn<0);
```
string length minus boolean is lower then zero
+2 Bytes for string comparision `$argn<"0"`
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVdI1NTE2MjQwNDI0MjYxMTVTsuayt/tvY29bXFKUk5qnAVamqQuhbQw0rf//BwA "PHP – TIO Nexus")
## PHP, 32 Bytes
```
<?=preg_match_all("#\d#",$argn);
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVTJQsuayt/tvY29bUJSaHp@bWJKcEZ@Yk6OhpByToqykA1amaf3/PwA "PHP – TIO Nexus")
Regex count all digits
## 35 Bytes
```
<?=strlen($argn)-strspn($argn,"-");
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVTJQsuayt/tvY29bXFKUk5qnARbX1AXyigugPB0lXSVN6///AQ "PHP – TIO Nexus")
string length minus count `-`
[strspn](http://php.net/manual/en/function.strspn.php)
[Answer]
# Fortran 95 (gfortran), ~~121~~ ~~96~~ 95 bytes
```
program c
character b
call get_command_argument(1,b,length=i)
print*,i-index(b,'-')
end program
```
Explanation:
Subtracts the index of the '-' sign from the length of the argument.
Arrays start at 1 in Fortran, and index() returns 0 if symbol not found.
*Edit: Switched to implicit integer "i", also consolidated argument getter.*
*Edit: -1 byte thanks to @Tsathoggua*
[Answer]
# [GNU AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 18 17 15 bytes
```
$1=gsub(/\w/,1)
```
Substitutes every number character (except for the minus sign) alphanumeric character of the input for another character (here, the number 1), and assigns the number of substitutions to the output.
Thanks for cnamejj and manatwork for helping me saving some bytes!
[Try it online!](https://tio.run/##SyzP/v9fxdA2vbg0SUM/plxfx1Dz/39dE1MuQyNTEwsDIzMuY2NDA3MzYwtDU2MLEzMjS0MLI0suXSMDIOAyAAA "AWK – Try It Online")
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 17 bytes
```
$1=gsub(/[^-]/,1)
```
This is a previous answer, that should work on any Awk version, not only GNU's.
[Try it online!](https://tio.run/##SyzP/v9fxdA2vbg0SUM/Ok43Vl/HUPP/f10TUy5DI1MTCwMjMy5jY0MDczNjC0NTYwsTMyNLQwsjSy5dIwMg4DIAAA "AWK – Try It Online")
[Answer]
# PowerShell, 24 Bytes
```
"$args"-replace'-'|% Le*
```
casts the "absolute" value of the input args to a string and gets the 'length' property of it.
1 byte shorter than `"".Length`
until someone finds a better way to get the abs of a number in PS this is probably as short as it will get.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
þg
```
[Try it online!](https://tio.run/nexus/05ab1e#@394X/r//7qGRsZ6JqZmAA "05AB1E – TIO Nexus")
```
# Implicit input [a]...
þ # Only the digits in [a]...
g # length of [a]...
# Implicit output.
```
[Answer]
# Ruby, ~~15~~ 11+1 = ~~16~~ 12 bytes
Uses the `-n` flag.
```
p~/$/-~/\d/
```
[Try it online!](https://tio.run/nexus/ruby#U1YsKk2qVNDN@19Qp6@ir1unH5Oi//@/rokpl6GRqYmFgZEZl7GxoYG5mbGFoamxhYmZkaWhhZEll66RARBwGQAA "Ruby – TIO Nexus")
### Explanation
```
# -n flag gets one line of input implicitly
p # Print
~/$/ # Position of end of line (aka string length) in input
- # minus
~/\d/ # Position of first digit (1 if negative number, 0 otherwise)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DL
```
**[Try it online!](https://tio.run/nexus/jelly#@@/i8///f10TUwA "Jelly – TIO Nexus")**
This does literally what was asked:
```
DL - Main link number n e.g. -45
D - convert to a decimal list [-4,-5]
L - get the length 2
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~31~~ 22 bytes
*-9 bytes thanks to Rod.*
```
lambda i:len(`abs(i)`)
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQaZWTmqeRkJhUrJGpmaD5v6AoM69EIU1D18RUkwvGMTQyNbEwMDJDiBgbGxqYmxlbGJoaW5iYGVkaWhhZImR1jQyAAME30PwPAA "Python 2 – TIO Nexus\"GloYWSLL6xoZAAGyCJDzHwA \"Python 2 – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 5 bytes
```
q'--,
```
String based.
[Try it online!](https://tio.run/nexus/cjam#@1@orqur8/@/AQA "CJam – TIO Nexus")
9 bytes for a purely math-based solution:
```
riz)AmLm]
```
Or another 5 with base conversion:
```
riAb,
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 63 bytes
```
([({})]((((()()()()())){}{})){}{})((){[()](<{}>)}{})([{}][]<>)
```
[Try it online!](https://tio.run/nexus/brain-flak#@68RrVFdqxmrAQKaMKipWV0LFIWQQPHqaA2gEpvqWjtNsEh0dW1sdKyNneb//7qGBv91EwE "Brain-Flak – TIO Nexus")
This is 62 bytes of code and +1 byte for the `-a` flag.
I tried two other approaches, but unfortunately both of them were longer:
```
([]<({}[((((()()()()())){}{})){}{}]<>)((){[()](<{}>)}{})>)({}[{}])
([]<>)<>({}<>)((((([][]())){}{})){}{}[{}])((){[()](<{}>)}{})([{}]{})
```
This *should* be a very short answer. In fact, if we didn't have to support negative numbers, we could just do:
```
([]<>)
```
But we have to compare the first input with 45 (ASCII `-`) first, which is most of the byte count of this answer.
An arithmetic solution might be shorter.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
a s l
```
[Try it online!](https://tio.run/nexus/japt#@5@oUKyQ8/@/rpGpOQA "Japt – TIO Nexus")
# Explanation
```
a s l
Ua s l
Ua # take the absolute value of the input
s # and turn it into a string
l # and return its length
```
[Answer]
# Ruby, 20 bytes
```
->a{a.abs.to_s.size}
```
[Answer]
# [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 2 bytes
```
âL
```
[Try it online!](https://tio.run/nexus/rprogn-2#@394kc////91DS1MTMzMTUwMzI3NDSxNTQ3NDE0B "RProgN 2 – TIO Nexus")
Simply gets the absolute value of the input, and counts the digits.
[Answer]
# Pyth, 4 bytes
```
l`.a
```
[Try it online!](http://pyth.herokuapp.com/?code=l%60.a&debug=0)
[All test cases](http://pyth.herokuapp.com/?code=l%60.a&test_suite=1&test_suite_input=-45%0A12548026%0A33107638153846291829%0A20000%0A0&debug=0)
[Answer]
# [Perl 5](https://www.perl.org/), 9 + 1 = 10 bytes
```
$_=y/-//c
```
[Try it online!](https://tio.run/nexus/perl5#@68Sb1upr6uvn/z/v66JKZehkamJhYGRGZexsaGBuZmxhaGpsYWJmZGloYWRJZeukQEQcBn8yy8oyczPK/6vm1MAAA "Perl 5 – TIO Nexus")
Run with `-p` (1 byte penalty).
## Explanation
```
$_=y/-//c
{implicit from -p: for each line of input}
y/ // In {the input}, replace
c everything except
- '-'
$_= Store number of replacements back in $_
{implicit from -p: output $_}
```
We treat the input as a string in order to handle numbers outside the 64-bit range. One interesting trick here is that we don't have to specify what we're replacing the nonhyphens *with*; we can still count the number of replacements that occur.
The TIO link uses `-l` in order to let us run the program on multiple data without the newlines between them interfering. If the program only has to run once, we can do without it, so long as there's no final newline on the input.
[Answer]
# JavaScript (ES6), ~~27~~ ~~26~~ ~~25~~ 24 bytes
Takes input as a string.
```
s=>s.match(/\d/g).length
```
* Saved two bytes thanks to Arnauld.
[Answer]
## R, 18 bytes
```
nchar(abs(scan()))
```
[Answer]
## JavaScript (ES6), 23 bytes
```
s=>`${s>0?s:-s}`.length
```
Different approach to [Shaggy's answer](https://codegolf.stackexchange.com/a/120911/9365).
[Answer]
# Java, ~~30~~ 24 bytes
```
i->(""+i.abs()).length()
```
Assumes `i` is a `BigInteger`. Also, the type is contextualized, so no imports are required, as shown in the test code.
## Test
```
// No imports
class Pcg120897 {
public static void main(String[] args) {
java.util.function.ToIntFunction<java.math.BigInteger> f =
// No full class declaration past here
i->(""+i.abs()).length()
// No full class declaration before here
;
System.out.println(f.applyAsInt(new java.math.BigInteger("-1267650600228229401496703205376"))); // -(2^100)
System.out.println(f.applyAsInt(new java.math.BigInteger("1267650600228229401496703205376"))); // (2^100)
}
}
```
## Saves
* 30 -> 24 bytes : thanks to @cliffroot
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 20 bytes
```
:s/-
C<C-r>=strlen(<C-r>")
<esc>
```
[Try it online!](https://tio.run/##K/v/36pYX5fL2cZZt8jOtrikKCc1TwPMUdLkskktTrb7/1/X3MLyv24ZAA "V (vim) – Try It Online")
Remove minuses(if any), cut the line, and get its length.
Not sure if I need the `<esc>` at the end.
[Answer]
# [Risky](https://github.com/Radvylf/risky), 2 bytes
```
!?}*
```
[Try it online!](https://radvylf.github.io/risky?p=WyIhP30qIiwiWy0zMzEwNzYzODE1Mzg0NjI5MTgyOW5dIiwwXQ)
```
! length
? input
} base convert
* 10
```
[Answer]
# [FALSE](https://github.com/somebody1234/FALSE), 14 bytes
```
^45=[1+^~][]#.
```
[Try it online!](https://tio.run/##S0vMKU79/z/OxNQ22lA7ri42OlZZ7/9/XRNTAA "FALSE – Try It Online")
Explanation:
If first character is '-' (ascii code 45), then push -1. Else push 0. Add 1 to number on stack until EOF character is reached.
] |
[Question]
[
This is a relatively quick one, but I'm sure you'll like it.
Codegolf a program that will take input in the form of a sentence and then provide the output with the first letter capitalized in each word.
Rules:
1. Submissions may not be in the form of a function. So no:
`function x(y){z=some_kind_of_magic(y);return z;}` as your final answer... Your code must show that it takes input, and provides output.
2. The code must preserve any other capital letters the input has. So
```
eCommerce and eBusiness are cool, don't you agree, Richard III?
```
will be rendered as
```
ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?
```
3. Some of you may be thinking, "Easy, I'll just use regex!" and so using the native regex in your chosen golfing language will incur a 30 character penalty which will be applied to your final code count. *Evil laugh*
4. A "word" in this case is anything separated by a space. Therefore `palate cleanser` is two words, whereas `pigeon-toed` is considered one word. `if_you_love_her_then_you_should_put_a_ring_on_it` is considered one word. If a word starts with a non-alphabetical character, the word is preserved, so `_this` after rendering remains as `_this`. (Kudos to Martin Buttner for pointing this test case out).
* 4b. There is no guarantee that words in the input phrase will be separated by a single space.
5. Test Case, (please use to test your code):
Input:
```
eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye
```
Output:
```
ECommerce Rocks. CrazyCamelCase Stuff. _those Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
```
6. This is code golf, shortest code wins...
Good luck...
[Answer]
# CJam, ~~15~~ 13 bytes
```
Lq{_eu?_S-}/;
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Lq%7B_eu%3F_S-%7D%2F%3B&input=eCommerce%20rocks.%20crazyCamelCase%20stuff.%20_those%20%20pigeon-toed%20shennanigans.%20Fiery%20trailblazing%20345%20thirty-two%20Roger.%20The%20quick%20brown%20fox%20jumped%20over%20the%20lazy%20dogs.%20Clancy%20Brown%20would%20have%20been%20cool%20as%20Lex%20Luthor.%20good_bye).
### Pseudocode
```
L e# B := ""
q e# Q := input()
{ }/ e# for C in Q:
_eu? e# C := B ? C : uppercase(C)
_S- e# B := string(C).strip(" ")
; e# discard(B)
```
All modified characters C are left on the stack and, therefore, printed when exiting.
[Answer]
# CSS 2.1, 49
```
:after{content:attr(t);text-transform:capitalize}
```
**Explanation**:
* The [`attr`](https://developer.mozilla.org/en-US/docs/Web/CSS/attr) function takes the input from a `t` (text) HTML attribute.
* The input is capitalized by setting [`text-transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform) to `capitalize`.
* The output is provided as a generated content, using the [`content`](https://developer.mozilla.org/en-US/docs/Web/CSS/content) property on an [`::after`](https://developer.mozilla.org/en-US/docs/Web/CSS/::after) [pseudo-element](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements).
**Runnable snippet**:
```
:after {
content: attr(t);
text-transform: capitalize;
}
```
```
<div t="eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye"></div>
```
**Note**: [CSS 2.1](http://www.w3.org/TR/CSS1/#text-transform) specified the desired behavior: `capitalize` uppercased the first character of each word. However, [CSS3](http://dev.w3.org/csswg/css-text-3/#text-transform) uppercases first [typographic letter unit](http://dev.w3.org/csswg/css-text-3/#typographic-letter-unit) of each word. So the snippet above won't work properly neither on old IE, which didn't follow CSS 2.1; nor on new compliant browsers which follow CSS3.
[Answer]
# Perl, 13 bytes
```
perl -040pe '$_="\u$_"'
```
9 bytes plus 4 bytes for `040p` (assuming I've interpreted the [rules on special invocations](http://meta.codegolf.stackexchange.com/a/274/31388) correctly).
`-040` sets the input record separator `$/` to a single space, so spaces are preserved; the `\u` escape sequence converts the next character to title case.
[Answer]
# Javascript (*ES6*), 77 bytes
```
alert(prompt().split(' ').map(x=>x&&x[0].toUpperCase()+x.slice(1)).join(' '))
```
### Commented
```
alert( // output
prompt(). // take input
split(' '). // split by spaces
map(x=> // map function to array
x && // if x, empty string "" is falsey and returns itself
x[0].toUpperCase() + x.slice(1) // capaitalize 1st char and concatenate the rest
).
join(' ') // join array with spaces
)
```
[Answer]
# Perl Version < 5.18, 30 27 26 25
```
say map"\u$_",split$,=$"
```
`24` characters `+1` for `-n`.
`\u` makes the next character in a string [uppercase](http://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators). @ThisSuitIsBlackNot pointed this out to save 1 byte. Before we were using the function `ucfirst`.
From the [perldocs](http://perldoc.perl.org/functions/split.html),
>
> As another special case, split emulates the default behavior of the
> command line tool awk when the PATTERN is either omitted or a literal
> string composed of a single space character (such as ' ' or "\x20" ,
> but not e.g. / / ). In this case, any leading whitespace in EXPR is
> removed before splitting occurs, and the PATTERN is instead treated as
> if it were /\s+/ ; in particular, this means that any contiguous
> whitespace (not just a single space character) is used as a separator.
> However, this special treatment can be avoided by specifying the
> pattern / / instead of the string " " , thereby allowing only a single
> space character to be a separator. In earlier Perls this special case
> was restricted to the use of a plain " " as the pattern argument to
> split, in Perl 5.18.0 and later this special case is triggered by any
> expression which evaluates as the simple string " " .
>
>
>
Since `$"` evaluates to a space, this will preserve the spaces. Since we want to both set `$,` to a space character, and input a space character to the split, @nutki pointed out we can do both as the input to the split. That saves 3 bytes from what we had before, which was first setting `$,` and then inputting `$"` to the split.
Using a `,` for map instead of `{}` saves an additional byte, as @alexander-brett pointed out.
Run with:
```
echo 'eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye' | perl -nE'say map"\u$_",split$,=$"'
```
[Answer]
# CJam, ~~17~~ 15 bytes
```
lS/{S+(eu\+}/W<
```
[Test it here.](http://cjam.aditsu.net/#code=lS%2F%7BS%2B(eu%5C%2B%7D%2FW%3C&input=_this%20%20eCommerce%20rocks.%20crazyCamelCase%20stuff.%20_those%20pigeon-toed%20shennanigans.%20Fiery%20trailblazing%20345%20thirty-two%20Roger.%20The%20quick%20brown%20fox%20jumped%20over%20the%20lazy%20dogs.%20Clancy%20Brown%20would%20have%20been%20cool%20as%20Lex%20Luthor.%20good_bye)
Fairly straightforward implementation of the spec. Make use of the new `{}&` to avoid errors for consecutive spaces.
*Two bytes saved by Dennis.*
[Answer]
## C, ~~64~~ 63 bytes
```
a;main(c){while(~(c=getchar()))putchar(a?c:toupper(c)),a=c-32;}
```
*Fix: some compilers (such as Clang) don't like an int parameters in place of argv, so I moved it to a global variable. The byte count stays the same. Thanks to squeamish ossifrage for noticing.*
*Down to 63 bytes, thanks Dennis.*
Ungolfed:
```
int a;
int main(int c) {
while(~(c = getchar()))
putchar(a ? c : toupper(c)),
a = c - ' ';
}
```
Pretty straightforward: if a is false, the character is converted to uppercase. It is set after reading a space: c - ' ' is false only if c == ' '. toupper() ignores everything that is not a lowercase letter, so symbols and multiple spaces are fine. -1 has all bits set, so when getchar() returns -1 the NOT operator makes it zero, and the loop stops.
a is declared as a global variable, so it is initializd to zero (false). This ensures that the first word is capitalized.
[Answer]
# Python 3, ~~59~~ 56 bytes
```
f=1
for c in input():print(end=f*c.upper()or c);f=c==" "
```
Thanks to @Reticality for 3 bytes.
[Answer]
# [><> (Fish)](http://esolangs.org/wiki/Fish), 39 bytes
```
</?-' 'o:;?(0:<-*' '*('{'$)'`'::i
i/.0e
```
Method:
* Take one char and capitalize it if in range `a-z` then print it out. (left-to-right code for this part is `i::'backquote')$'{'(*' '*+`)
* **If** the last taken char is an EOF char **then** exit **else** print it
* **If** the last taken char is a space char **then** go to point 1 **else** take a new letter and go to point 2.
[Answer]
# JAVA, 273 bytes
**EDIT**
```
import static java.lang.System.*;class x{public static void main(String[] s){char[] a=new java.util.Scanner(in).nextLine().toCharArray();boolean f=1>0;for(int i=0;i<a.length;i++){if(a[i]==' '){f=1>0;continue;}if(f){a[i]=Character.toUpperCase(a[i]);f=1<0;}}out.println(a);}}
```
[Answer]
## JavaScript (regex solution) - 104 bytes
Someone has to bite the bullet and post the RegEx solution! 74 characters, plus the +30 character penalty:
```
alert(prompt().replace(/(^| )[a-z]/g,function(m){return m.toUpperCase()}))
```
Or if you want to read and understand the code in its non-compacted fashion:
```
// Matches the (beginning of the line or a space), followed by a lowercase English character.
string.replace( /(^| )[a-z]/g ,
function(match) { return match.toUpperCase(); }
```
[Answer]
# Vim, ~~11~~, 10 bytes
```
qqvUW@qq@q
```
Explanation:
```
qq #Start recording in register 'q'
vU #Make the character under the cursor uppercase
W #Move forward a WORD
@q #recursively call macro 'q'
q #stop recording
@q #Call the recursive macro
```
Do I get a gold-badge for [outgolfing Dennis?](http://meta.codegolf.stackexchange.com/questions/5828/the-many-memes-of-ppcg/7346#7346)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~342~~ 310 bytes
```
>-[-[-<]>>+<]>-[->+>>>>+<<<<<]>[-<+>],[<[->>+>+<<<]>>>[-<<<+>>>]<<[->>+>+<<<]>>>[-<<<+>>>]<<[->-<]>>+<[>->>>+[+[<]>>+<+]>[-<<<<<<->>>>>>]<<<+++++[>+++++<-]>+>>+<<[<<<<[->+>>+<<<]>[-<+>]>>[[-]>>+<<]>>-[<<<[-<<<<->>>>]>>>+>-<]<<<<<->>>>-]>>[-<<<<[-]>>>>]<<<<<<[-]]>[->[-]<<<<<[->>>+>>+<<<<<]>>>[-<<<+>>>]>]<<<.,]
```
[Try it online!](https://tio.run/##fZFNb4MwDIb/iu9puGy7oRyGtFNP025RVAUwHyvEXQht6Z9nTqi6nuYgwhu/fmyg9LZ3zVwd11VJzSs3Sgm@8aMSSkURwyhOCWV2OucEZ0Q6VPE4z6PR5P9n7mStZIRqoTctzGbkiInNnosYWqUtlyZOwlgdXdtc4mkmbqVlgkWk1Mn0AMZRROz@1yOaN0eq21puKjL5Mnedah@f4PmdUk22M@uKBY0j@grBU3WcMqi8vS2FHXEo7IQwhblpMjiEjljBqW@RnAyENUwdOmdd31rHdR89@gUC/5GhHOytdy28vL5B6HofFhkuBJ/Uos/gq0P4mfvqCKWni4OGrvA9jycm0hk9VyAwYIGaWuYWg3XVAu/Je6F5qKGzZ4QS0UFFNICdYI9X2M88I/NbovpQLvgL "brainfuck – Try It Online")
Explanation:
```
[
* Many constants were taken from the BF constants page on esolangs.org.
*
* Cells:
*
* true number: the true index of the cell
* fake number: the relative cell index as referenced in the code
*
* true# | fake# | info
* 0 - Used only for initialization of (fake) cell 0
* 1 - Used only for initialization of (fake) cell 0
* 2 - Used only for initialization of (fake) cell 0
* 3 - Used only for initialization of (fake) cell 0
* 4 0 Holds constant 32 / ' ', which is used for cell 5 (space flag) and for subtracting (' ') from input
* 5 1 Holds the input/output char during the main loop. Also used in setup for copying cell 0 to cell 5
* 6 2 Used to hold 32 / ' ' (temporarily, to subtract it from the input)
* 7 3 Used to hold a copy of the input that gets mangled throughout the loop, being subtracted from to
* check what the input character was. Also used in space code to copy cell 0 to cell 5.
* 8 4 Used primarily as a flag to decide which part of the space/not space conditional to run (if 1, the
* space code runs; if 0, the not-space code runs). Also used when copying cell 3 to 6 (for checking
* if cell 3 == 0), and to copy cell 1 to 3 (input).
* 9 5 Holds the 'space flag' (different from cell 4). When a space is encountered, this cell is set to 32
* ('a' - 'A'). When a lowercase character is encountered, this cell is subtracted cell 1 (input),
* clearing it by default (subtraction without copying implicitly clears the cell). This makes it so
* that only the first character after a space is converted to uppercase.
* 10 6 Used as a temporary cell when initializing constants 65 ('a' - ' ') and 2, also used in the
* lowercase check loop to set cell 8 (cell 3 == 0 flag)
* 11 7 Used as the counter in the lowercase check loop, goes from 26 to 0 (decrementing each iteration).
* Also used as a temporary cell when initializing constant 65.
* 12 8 Used to hold (cell 3 == 0) flag, which subtracts cell 5 from cell 1 if it is 1 (which means that
* cell 1 is a lowercase letter).
* 13 9 Used as a flag to figure out if the else branch of the lowercase checker should run. If one, the
* character is not a lowercase letter or space and so cell 5 is cleared.
]
>-[-[-<]>>+<]>- set cell 0 to 32 (=' ')
[->+>>>>+<<<<<] set cells 1 and 5 to 32 (end on 0)
>[-<+>] move 1 back to 0 (end on 1)
,[ loop over input (cell 1)
copy cell 0 to cell 2
<[->>+>+<<<] [move cell 0 to cells 2 and 3 (end on 0)]
>>>[-<<<+>>>] [move cell 3 back to cell 0 (end on 3)]
copy cell 1 to cell 3
<<[->>+>+<<<] [move cell 1 to cells 3 and 4 (end on 1)]
>>>[-<<<+>>>] [move cell 4 back to cell 1 (end on 4)]
<<[->-<] [subtract cell 2 from cell 3 (end on 2)]
> cell 3 / input minus ' '
>+< set cell 4 as flag to run space code if set (end on 3)
[ not space branch (check if in lowercase zone)
>- clear cell 4 (end on 4)
>>>+[+[<]>>+<+]> set cell 9 to 65 (='a' minus ' ') (uses 6 7 8 as tmp) (end on 9)
[-<<<<<<->>>>>>] [subtract cell 9 from cell 3 (end on 9)]
[need to check if cell 3 is from 0-26, it could be above and not a lowercase letter]
<<< cell 6
+++++[>+++++<-]>+ set cell 7 to 26
>>+<< set cell 9 to 1 (end on 7)
[ do 26 times
<<<< cell 3
[->+>>+<<<] [move cell 3 to cell 4 and 6 (end on 3)]
>[-<+>] [move cell 4 back to cell 3 (end on 4)]
>> cell 6
[[-]>>+<<] [if cell 6 is set, set cell 8 to 1 (end on 6)]
>>- decrement cell 8 (if cell 3 was not zero cell 8 is now zero) (if cell 3 was zero cell 8 is now 255)
[ if cell 3 is zero (start here on 8)
<<< cell 5
[-<<<<->>>>] [sub cell 5 from cell 1 (end on 5)]
>>>+ clear cell 8 (end on 8)
>-< set cell 9 to 0 (end on 8)
]
<<<<<- decrement cell 3 (end on 3)
>>>>- end on 7 and decrement
]
>>[ cell 9 set (else branch so we have no lowercase letter)
- [clear cell 9]
<<<< cell 5
[-] [clear cell 5]
>>>> cell 9
]
<<<<<< cell 3
[-] [clear cell 3]
]
> cell 4
[ space branch
- clear cell 4 (end on 4)
>[-] clear cell 5 (space flag/may have been set)
<<<<<[->>>+>>+<<<<<] [set space flag (cell 5) (coincidentally, it is also 32 so we can copy from cell 0) (0-> 5 and 3) (end on 0)]
>>>[-<<<+>>>] [3 to 0 (end on 3)]
> end on 4
]
<<<. from 4 to 1 (output 1)
,]
```
[Answer]
# Python 2, 73 bytes
```
i=raw_input()
print''.join((c,c.upper())[p==' ']for p,c in zip(' '+i,i))
```
This program capitalises a letter if preceded by a space (with a kludge for the first character in the string). It relies on the `.upper()` string method to capitalise correctly.
[Answer]
# PHP 64 ~~76~~ ~~77~~ ~~83~~ ~~84~~ ~~89~~ bytes
Does `$_GET` count as input in PHP?
If so, here is my first CG attempt
```
foreach(explode(' ',$_GET[@s])as$k=>$v)echo$k?' ':'',ucfirst($v)
```
Thanks manatwork :)
One could just use the `ucwords` function, which would result in 21 bytes:
```
<?=ucwords($_GET[@s])
```
thanks Harry Mustoe-Playfair :)
[Answer]
# Haskell, 69
```
import Data.Char
main=interact$tail.scanl(!)' '
' '!c=toUpper c;_!c=c
```
### Explanation:
`scanl` takes a function `(a -> b -> a)` and an initial value `a`, then iterates over a list of `[b]`s to make a list of `[a]`s:
```
scanl (!) z [a,b,c] == [ z
, z ! a
, (z ! a) ! b
, ((z ! a) ! b) ! c]
```
It repeatedly takes the **previous result** as the **left argument** of the function passed to it, and a **value from the input list** as the **right argument**, to make the next one.
I wrote a function `(!) :: Char -> Char -> Char` that returns the right character you pass it, but capitalizes it if the left char is `' '` (space). For `scanl`, this means: return the **value from the input list**, but capitalize it if the **previous result** was a space. So `scanl (!) ' ' "ab cd"` becomes:
```
scanl (!) ' ' "ab cd"
==> ' ' : scanl (!) (' ' ! 'a') "b cd"
==> ' ' : scanl (!) 'A' "b cd"
==> ' ' : 'A' : scanl (!) ('A' ! 'b') " cd"
==> ' ' : 'A' : scanl (!) 'b' " cd"
==> ' ' : 'A' : 'b' : scanl (!) ('b' ! ' ') "cd"
==> ' ' : 'A' : 'b' : scanl (!) ' ' "cd"
==> ' ' : 'A' : 'b' : ' ' : scanl (!) (' ' ! 'c') "d"
==> ' ' : 'A' : 'b' : ' ' : scanl (!) 'C' "d"
==> ' ' : 'A' : 'b' : ' ' : 'C' : scanl (!) ('C' ! 'd') ""
==> ' ' : 'A' : 'b' : ' ' : 'C' : scanl (!) 'd' ""
==> ' ' : 'A' : 'b' : ' ' : 'C' : 'd' : ""
==> " Ab Cd"
```
We need the initial value `' '` to capitalize the first letter, but then we chop it off with `tail` to get our final result.
[Answer]
# Pyth, 20 bytes
```
uXGHr@GH1fqd@+dzTUzz
```
These multiple spaces really sucks. Otherwise there would have been a really easy 12 bytes solution.
Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=uXGHr%40GH1fqd%40%2BdzTUzz&input=eCommerce%20rocks.%20crazyCamelCase%20stuff.%20_those%20%20pigeon-toed%20shennanigans.%20Fiery%20trailblazing%20345%20thirty-two%20Roger.%20The%20quick%20brown%20fox%20jumped%20over%20the%20lazy%20dogs.%20Clancy%20Brown%20would%20have%20been%20cool%20as%20Lex%20Luthor.%20good_bye&debug=0)
### Explanation
```
implicit: z = input string
f Uz filter [0, 1, 2, ..., len(z)-1] for elements T, which satisfy:
qd@+dzT " " == (" " + z)[T]
(this finds all indices, which should be capitalized)
u z reduce, start with G = z, for H in idices ^ update G by
XGH replace the Hth char of G by
r 1 upper-case of
@GH G[H]
implicitly print result
```
edit: 16 chars is possible with @Dennis algorithm.
[Answer]
# CJam, 14 bytes
It's not the shortest, but...
```
qS/Sf.{\eu}s1>
```
Another answer using similar ideas:
```
qS/Laf.{;eu}S*
```
`.x` only changes the first item if one of the parameters has only one item.
[Answer]
# Lua, ~~64~~ ~~62~~ 61 bytes
Lua is a horrendous language to golf in, so I'm pretty proud of myself for this one.
```
print(string.gsub(" "..io.read(),"%s%l",string.upper):sub(2))
```
~~[Try it here]~~[1](http://goo.gl/TouhWJ) Outdated, will update tommorow
[Answer]
# JAVA, 204 ~~211~~ ~~226~~ bytes
My first entry on CG, I hope it's fine:
```
class U{public static void main(String[]s){int i=0;char[]r=s[0].toCharArray();r[0]=Character.toUpperCase(r[0]);for(char c:r){if(c==' '&&i>0)r[i+1]=Character.toUpperCase(r[i+1]);i++;System.out.print(c);}}}
```
Saved 7 bytes thanks to @TNT
[Answer]
# PHP: ~~76~~ 74 characters
```
foreach($l=str_split(fgets(STDIN))as$c){echo$l?ucfirst($c):$c;$l=$c==" ";}
```
Sample run:
```
bash-4.3$ php -r 'foreach($l=str_split(fgets(STDIN))as$c){echo$l?ucfirst($c):$c;$l=$c==" ";}' <<< 'eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye'
ECommerce Rocks. CrazyCamelCase Stuff. _those Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
```
[Answer]
# C, 74 bytes
```
a,b=1;main(){while((a=getchar())>0)b=isspace(putchar(b?toupper(a):a));}
```
Makes no assumptions about the run-time character set (ASCII, EBCDIC, Baudot, ...whatever). Does assume that EOF is negative (I think C guarantees that).
```
a,b=1;
main()
{
while((a=getchar())>0)
b=isspace(putchar(b?toupper(a):a));
}
```
a is the input character; b is true if the last character was space. The only non-obvious bit is that we use the fact that `putchar` returns the character printed if there's no error.
[Answer]
# C# Linq - 187
This is nowhere close to winning but I just love Linq too much.
```
namespace System{using Linq;class P{static void Main(string[]a){Console.Write(a[0].Substring(1).Aggregate(a[0][0].ToString().ToUpper(),(b,c)=>b[b.Length-1]==32?b+char.ToUpper(c):b+c));}}}
```
[Answer]
# Java 8, 135 bytes
It's rare that I beat all the other answers that use the same language.
```
interface M{static void main(String[]a){int c=0;for(char i:a[0].toCharArray()){System.out.print(c==0?(i+"").toUpperCase():i);c=i-32;}}}
```
[TIO](https://tio.run/##HY9Bb4JAEIX/ysQTpIGY2l40pmlJerKX2p6MMcMywCjs0GFBV@Nvp9seX/K@L@8dccTkWJymia0jLdEQfNx6h44NjMIFtMg22jplW@32GN9CD8x6vipFI1OjAi9xN9@nTrKQXlXRR3F82/reUZvK4NIusC4y6/X8JeKH2SwO3e@uI82wpyhecrwya04Wj6v7/T5NE2XStqRhiYo59SkYxavPsKXmj4DeDWWZwsHVEhJ0XJHYxAkV0NdkLVqu0AbunUk9OEVu8gav4QEsnp7B1azOJ@4s8CkVaQpfNcHPwOYEucrZQikXOA5tF4wykgaCIAg8FFIFb9agNR7e/rtnGZoCahwJciILRqQB7GFDF9gMYWPwVyLFIff0Cw)
[Answer]
# Bash, 61
```
a="${@//: / }"
a=(${a//: / })
a="${a[@]^}"
echo "${a//:/ }"
```
Note the colons are simply to make the program display OK here. In reality these can be some non-printable character, such as BEL.
### Output
```
$ ./cap1st.sh "eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye"
ECommerce Rocks. CrazyCamelCase Stuff. _those Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
$
```
---
# Bash, 12
Sadly this one doesn't preserve leading/mutliple/trailing spaces, but otherwise it works:
```
echo "${@^}"
```
### Output
```
$ ./cap1st.sh eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye
ECommerce Rocks. CrazyCamelCase Stuff. _those Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
$
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 15 + 1 for `-s` = 16
```
{IaUC:a@0a}Ma^s
```
Explanation:
```
a is first cmdline arg (implicit)
a^s Split a on spaces
{ }M Map this function to each element:
Ia If the word is not empty,
UC:a@0 uppercase its first character
a Return the word
Output the resulting list (implicit) joined on spaces (-s flag)
```
One interesting feature of Pip that this program draws on is the `:` assignment meta-operator. Most C-like languages have some set of compute-and-assign operators: e.g. `x*=5` does the same thing as `x=x*5`. In Pip, however, you can tack `:` onto *any* operator and turn it into a compute-and-assign operator. This even goes for unary operators. So `-:x` computes `-x` and assigns it back to `x`, the same as `x:-x` would. In this case, `UC:` is used (together with Pip's mutable strings) to uppercase the first character of a word.
The program takes input from the command-line, requiring an invocation like this:
```
python3 pip.py -se "{IaUC:a@0a}Ma^s" "test teSt TEST _test"
```
[Answer]
# C, 125
Not the shortest of solutions, but I really like to golf in C.
```
char b[99];main(c){while(scanf("%[A-Za-z_-]",b)==1)islower(*b)&&(*b&=223),printf("%s",b);~(c=getchar())&&putchar(c)&&main();}
```
ungolfed:
```
char b[99];
main(c)
{
while(scanf("%[A-Za-z_-]", b) == 1) {
if(islower(b[0])) {
b[0] &= 0xDF;
}
printf("%s", b);
}
if((c = getchar()) != -1) {
putchar(c);
main();
}
}
```
I don't know wheter using regex-like syntax in `scanf` is streching the rules, but it works quite nicely. (Well, technically it's not a *full* regex)
An other thing to consider is that this code only works for words shorter than 99 bytes. But I think this solution will work for most cases.
[Answer]
**Haskell: 127 characters**
```
import Data.List
import Data.Char
i=isSpace
s a b=i a==i b
u (w:ws)=(toUpper w):ws
f w=concatMap u$groupBy s w
main=interact f
```
[Answer]
# PHP, 82
```
echo join(' ',array_map(function($s){return ucfirst($s);},explode(' ',$argv[1])));
```
Usage :
```
$ php code.php "eCommerce rocks. crazyCamelCase stuff. _those pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye"
```
[Answer]
## C#, ~~133~~ 131
```
using C=System.Console;class P{static void Main(){var s=2>1;foreach(var c in C.ReadLine()){C.Write(s?char.ToUpper(c):c);s=c==32;}}}
```
] |
[Question]
[
My boss just told me to write a cosine function. Being a good math geek, my mind immediately conjured the appropriate Taylor Series.
$$\cos(x) = \frac 1 {0!} - \frac {x^2} {2!} + \frac {x^4} {4!} - \frac {x^6} {6!} + \cdots + \frac{(-1)^k \times x^{2k}} {(2k)!} + \cdots$$
However, my boss is very picky. He would like to be able to specify exactly how many terms of the Taylor Series to compute. Can you help me write this function?
### Your Task
Given a floating point value \$x\$ from \$0\$ to \$2\pi\$ and a positive integer \$n\$ less than \$100\$, compute the sum of the first \$n\$ terms of the Taylor series given above for \$\cos(x)\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. Input and output can be taken in any of the standard ways. Standard loopholes are forbidden.
### Notes
* Input can be taken in any reasonable form, as long as there is a clear separation between \$x\$ and \$n\$.
* Input and output should be floating-point values, at least as accurate as calculating the formula using single-precision IEEE floating point numbers with some standard rounding rule.
* If it makes sense for the language being used, computations may be done using exact rational quantities, but the input and output shall still be in decimal form.
### Examples
```
x | n | Output
----+----+--------------
0.0 | 1 | 1.0
0.5 | 1 | 1.0
0.5 | 2 | 0.875
0.5 | 4 | 0.87758246...
0.5 | 9 | 0.87758256...
2.0 | 2 | -1.0
2.0 | 5 | -0.4158730...
```
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~165~~ 157 bytes
```
F={x=_this select 0;n=_this select 1;i=0;r=0;while{i<n*2}do{r=r+x^i/(i call{c=_this;j=c-1;while{j>0}do{c=c*j;j=j-1};if(c<1)then{c=1};c})*(-1)^(i/2);i=i+2};r}
```
**Call with:**
```
hint format["%1\n%2\n%3\n%4\n%5\n%6\n%7",
[0.0, 1] call f,
[0.5, 1] call f,
[0.5, 2] call f,
[0.5, 4] call f,
[0.5, 9] call f,
[2.0, 2] call f,
[2.0, 5] call f]
```
**Output:**
[![enter image description here](https://i.stack.imgur.com/wMyqs.jpg)](https://i.stack.imgur.com/wMyqs.jpg)
>
> Input and output should be floating-point values, at least as accurate as calculating the formula using single-precision IEEE floating point numbers with some standard rounding rule.
>
>
>
I'm fairly sure that the numbers are single-precision IEEE floating point numbers, even though in the printed output the longer decimals are not that precise. It is the printing that rounds the numbers like that, actually the numbers are more precise.
For instance, `a=1.00001;b=1.000011;hint format["%1\n%2\n%3", a, b, a==b]` will output this:
```
1.00001
1.00001
false
```
So clearly the actual precision of the numbers is greater than the printed precision.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 11 bytes
```
FIn(NmN·!/O
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fzTNPwy/X79B2RX3///8tuQz0TAE "05AB1E – TIO Nexus")
**Explanation**
```
F # for N in [0 ... n] do
In # push (x^2)
( # negate
Nm # raise to the Nth power
N·! # push (2*N)!
/ # divide
O # sum
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
U_iqE:2ep/YpsQ
```
[Try it online!](https://tio.run/nexus/matl#@x8an1noamWUWqAfWVAc@P@/kZ4BlykA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/gfGp9Z6GpllFqgH1lQHPjfJeS/AZchl4GeKZQ0ApMmYNISyANBUwA).
### Explanation with example
All numbers have double precision (this is the default).
Consider inputs `x = 2.0`, `n = 5`.
```
U_ % Implicitly input x. Square and negate
% STACK: -4
iqE % Input n. Subtract 1, multiply by 2
% STACK: -4, 8
: % Range
% STACK: -4, [1 2 3 4 5 6 7 8]
2e % Reshape into a 2-row matrix
% STACK: -4, [1 3 5 7;
% 2 4 6 8]
p % Product of each column
% STACK: -4, [2 12 30 56]
/ % Divide, element-wise
% STACK: [-2 -0.333333333333333 -0.133333333333333 -0.0714285714285714]
Yp % Cumulative product of array
% STACK: [-2 0.666666666666667 -0.0888888888888889 0.00634920634920635]
s % Sum of array
% STACK: -1.41587301587302
Q % Add 1. Implicitly display
% STACK: -0.41587301587302
```
[Answer]
# Mathematica, ~~49~~ ~~41~~ ~~39~~ 31 bytes
```
Sum[(-#^2)^k/(2k)!,{k,0,#2-1}]&
```
Old, more "fun" version: (39 bytes)
```
Normal@Series[Cos@k,{k,0,2#2-2}]/.k->#&
```
*Saved 10 bytes thanks to @Pavel and 8 thanks to @Greg Martin!*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḶḤµ⁹*÷!_2/S
```
**[Try it online!](https://tio.run/nexus/jelly#ARwA4///4bi24bikwrXigbkqw7chXzIvU////zX/Mi4w)**
### How?
```
ḶḤµ⁹*÷!_2/S - Main link: n, x e.g. 5, 2.0
·∏∂ - lowered range(n) [0,1,2,3,4]
Ḥ - double (vectorises) [0,2,4,6,8]
µ - monadic chain separation (call that i)
‚Åπ - link's right argument 2.0
* - exponentiate(i) (vectorises) [1.0,4.0,16.0,64.0,256.0]
! - factorial(i) (vectorises) [1, 2, 24, 720, 40320]
√∑ - divide (vectorises) [1.0,2.0,0.6666666666666666,0.08888888888888889,0.006349206349206349]
2/ - pairwise reduce by:
_ - subtraction [-1.0,0.5777777777777777,0.006349206349206349]
S - sum -0.41587301587301617
```
[Answer]
## **Jelly, 22 bytes**
```
-*ð×ø⁹*⁸²ð÷ø⁸Ḥ!
⁸R’Ç€S
```
This is a full program which takes n as the first argument and x as the second.
Explanation:
```
Creates a function to compute each term in the series.
Its argument we will call k, eg k=3 computes 3rd term. Take x=2 for example.
-* Computes (-1)^k. Eg -1
√∞√ó√∏ Multiplies by the quantity of
‚Åπ x.
* to the power of
⁸ k
² ...squared. Eg -1 × (2³)²
√∞√∑√∏ divides by the quantity of
⁸ k
Ḥ doubled
! ...factorial. Eg -1 × (2³)²/(6!).
Main link, first argument n and second argument n. Eg n=4, x=2.
⁸R Creates range(n). Eg [1,2,3,4]
’ Decrements each element. Eg [0,1,2,3]
Ç€ Maps the above function over each element. Eg [1,-2,0.666,-0.0889]
S Sum all all of the elements. Eg -0.422.
```
[Answer]
## Python, 54 bytes
```
f=lambda x,n,t=1,p=1:n and t+f(x,n-1,-t*x*x/p/-~p,p+2)
```
If using Python 2, be sure to pass x as a float, not an integer, but I my understanding is that it doesn't matter if you're using Python 3.
[Answer]
# TI-Basic, ~~41~~ 40 bytes
```
Prompt X,N
sum(seq((-(X+1E-49)2)^Q/((2Q)!),Q,0,N-1
```
`1E-49` is added to the angle because TI-Basic throws an error for 0^0, it's just large enough to not cause the error, and it is not large enough to change the answer.
[Answer]
# [R](https://www.r-project.org/), ~~70~~ ~~64~~ 47 bytes
```
function(x,n,m=1:n-1)sum((-x^2)^m/gamma(2*m+1))
```
[Try it online!](https://tio.run/##bcs7CoAwDADQ3ZMk2ioNdlDoVZTiD4dE8QPevs7arg/eEfZp9HL1w3auMrkw3zJc6ybwKFHsTCva4HkzgH46wo6rxTN7oJwLg/jtUFplMIuMElYnrPkbxZWUxSy8 "R – Try It Online")
* uses `gamma(n+1)` instead of `factorial(n)`
* `1:n-1` is equivalent to `0:(n-1)`
Thanks to Dominic van Essen for golfing 17 bytes off by using a basic R feature: vectorization!
[Answer]
# C, 96 bytes
**Recursive** [Live](http://ideone.com/agZrkz)
```
f(n){return n?n*f(n-1):1;}float c(n,x)float x;{return n?c(n-1,x)+pow(-1,n)*pow(x,2*n)/f(2*n):1;}
```
**Detailed**
```
f(n) // factorial(n)
{
return n ? // n != 0 ?
n*f(n-1) // n! = n * (n-1)!
: 1; // 0! = 1
}
float c(n,x)float x; // cos(x) with n+1 terms
{
return n ? // n != 0 ?
c(n-1, x) // cos(x) (n-1)th term
+ pow(-1, n) // + (-1)^n
* pow(x, 2*n) // * x^(2n)
/ f(2 * n) // / (2n)!
: 1; // cos(x) at n=0
}
```
**Progressive Recursive, 133 bytes** [Live](http://ideone.com/lxXauH)
```
#define F float
#define c(x,n) 1+g(1,n,x,1,1,1)
F g(F i,F n,F x,F s,F p,F f){s=-s;p*=x*x;f*=i;return i<n?g(i+1,n,x,s,p,f)+s/2*p/f:0;}
```
**Detailed**
```
#define F float // shorthand float
#define c(x,n) 1+g(1,n,x,1,1,1) // macro function
F g(F i,F n,F x,F s,F p,F f)
{
s = -s; // (-1)^n = (-1) * (-1)^(n-1)
p *= x*x; // x^(2n) = x^2 * x^(2(n-1))
f *= i; // 2n! = 2 * (1*2*..*n)
return i < n ? // i = 0 .. n-1
g(i+1,n,x,s,p,f) // next term
+ s / 2 * p / f // s*p/2f = s/2*p/f
: 0; // don't compute nth term
}
```
[Answer]
## JavaScript (ES6), 46 bytes
```
f=
x=>g=(n,t=1,p=0)=>n&&t+g(--n,-t*x*x/++p/++p,p)
```
```
<div oninput=o.textContent=f(x.value)(n.value)><input id=x><input type=number min=1 value=1 id=n><pre id=o>1
```
Takes curried inputs (x)(n).
[Answer]
## C, 71 bytes
using Horner scheme
```
float f(n,x)float x;{float y;for(n+=n;n;)y=1-(y*x*x/n--)/n--;return y;}
```
Ungolfed version:
```
float f(n,x) float x;
{
float y = 0.0;
for(n = 2*n; n>0; n -= 2)
{
y = 1-y*x*x/n/(n-1);
}
return y;
}
```
[Answer]
# [oK](http://johnearnest.github.io/ok), 38 bytes
This also works in **k**, but takes **39 bytes** because one `'` has to be written as `/:` instead (at least, in kmac 2016.06.28 it does).
```
{+/(y#1 -1)*{(*/y#x)%*/1+!y}.'x,'2*!y}
```
Explanation:
Let's start with the middle bit. `(*/y#x)` is exponentiation, it is equivalent to `x^y`. `*/1+!y` would be `y!`, or `y` factorial. `%` is division. Therefore the function in the middle is `middle(x,y) = (x^y)/(y!)`.
Now the bit on the right, to which the function above gets applied. `2*!y` is `{0, 2, 4, ..., 2*(y-1)}`. `x,'` prepends `x` to every item in that list, turning it into `{(x, 0), (x, 2), (x, 4), ..., (x, 2*(y-1))}`. The `.'` then applies `middle` to every pair of numbers (`map`, essentially).
Finally, `(y#1 -1)*` multiplies the result by 1 or -1 (alternating), and `+/` takes the sum.
[Answer]
# Haskell, 71 Bytes
```
f x n=sum$map(\i->(-1)^i*x^(2*i)/fromIntegral(product[1..2*i]))[0..n-1]
```
This is a pretty boring answer that's not too hard to decipher. The `fromIntegral` really bites, though. (The `/` operator requires operands of the same numeric type in Haskell, and coercing between numeric types is not allowed without a wordy function.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
²N*Ḷ}©÷®Ḥ!¤S
```
[Try it online!](https://tio.run/nexus/jelly#@39ok5/Wwx3bag@tPLz90LqHO5YoHloS/P/onsPL9R81rfGG4sj//6MN9Ax0FAxjdRSALFNklhGcZQJnWYJYRiAdRnCWaSwA "Jelly – TIO Nexus")
### How it works
```
²N*Ḷ}©÷®Ḥ!¤S Main link. Left argument: x. Right argument: n
² Square; yield x².
N Negate; yield -x².
© Call the link to the left and copy the result to the register.
·∏∂} Call unlength on the right argument, yielding [0, 1, ..., n-1].
* Yield [1, -x², ..., (-x²)**(n-1)].
¤ Combine the three links to the left into a niladic chain.
® Yield the value in the register, [0, 1, ..., n-1].
Ḥ Unhalve; yield [0, 2, ..., 2n-2].
! Factorial; yield [0!, 2!, ..., (2n-2)!].
÷ Division; yield [1/0!, -x²/2!, ..., (-x²)**(n-1)/(2n-2)!].
S Take the sum.
```
[Answer]
# Pyth, 16 bytes
```
sm_Fc^vzyd.!yddU
```
Accepts `n` first, then `x`. [Example run.](http://pyth.herokuapp.com/?code=sm_Fc%5Evzyd.%21yddU&input=2%0A0.5&debug=0)
[Answer]
# [Haskell](https://www.haskell.org/), 61 bytes
```
x#n=sum[(-1*x^2)^i/fromIntegral(product[1..2*i])|i<-[0..n-1]]
```
This seemed different enough from the other Haskell solution to warrant a separate answer. Implementation should be pretty self-explanatory—call with `x#n` where `x` is the number the cosine of which is to be computed and `n` is the order of the partial sum to be taken.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), ~~37~~ ~~34~~ 33 bytes
```
←←ĐĐ↔3Ș1~⇹ř⁻^04Ș⇹ř⁻^²*0↔ř⁻2*!+/+Ʃ
```
[Answer]
# J, ~~26~~ 24 Bytes
```
+/@:(!@]%~^*_1^2%~])2*i.
```
-2 bytes thanks to @cole
I originally planned to use a cyclic gerund to alternate between adding and subtracting, but couldn't get it to work.
### Explanation:
```
2*i. | Integers from 0 to 2(n-1)
( ) | Dyadic train:
_1^-:@] | -1 to the power of the left argument
^* | Times left arg to the power of right arg
!@]%~ | Divided by the factorial of the right arg
+/@: | Sum
```
[Answer]
# [Perl 6](http://perl6.org/), 53 bytes
```
{(sum (1,*i*$^x...*)[^2*$^n] »/»(1,|[\*] 1..*)).re}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WqO4NFdBw1BHK1NLJa5CT09PSzM6zgjIzotVOLRb/9BuoFxNdIxWrIIhSE5Tryi19n9afpGCjYGegYKhnQ6IYYpgGMEYJjCGJYhhBFRsBGOY2ino2ilEq1ToKKgAranmUlAoTqxUUFKpUKgBigCJ6jQgDZStqFWy5qr9DwA "Perl 6 – Try It Online")
This actually computes the complex exponential *eiθ* for twice the number of requested terms and then takes the real part.
[Answer]
# [Julia](http://julialang.org/), 37 bytes
```
x$n=1>(n-=1)||x$n+(-x^2)^n/prod(1:2n)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v0Ilz9bQTiNP19ZQs6YGyNPW0K2IM9KMy9MvKMpP0TC0MsrT/O9QnJFfrmCgZ6BiwAVjm6oYIrGNkNgmSGxLKNsIqNcIiW36HwA "Julia 1.0 – Try It Online")
[Answer]
# MATLAB with Symbolic Math Toolbox, 57 bytes
```
@(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
```
This defines an anonymous function with that takes `double` inputs `x`,`n` and outputs the result as a `double`.
Example (tested on R2015b):
```
>> @(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
ans =
@(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
>> f = ans; format long; f(0,1), f(0.5,1), f(0.5,2), f(0.5,4), f(0.5,9), f(2,2), f(2,5)
ans =
1
ans =
1
ans =
0.875000000000000
ans =
0.877582465277778
ans =
0.877582561890373
ans =
-1
ans =
-0.415873015873016
```
[Answer]
# JavaScript ES7 60 bytes
```
x=>a=n=>--n?(-1)**n*x**(2*n)/(f=m=>m?m*f(m-1):1)(2*n)+a(n):1
x=>a=n=> // Curry-d function, it basically returns another function
--n? :1 // subtract one from n. If n - 1 is 0, return 1
(-1)**n* // This generates the sign of the number
x**(2*n)/ // This creates the part before the division, basicaly x^2n
(f=m=>m?m*f(m-1):1)(2*n) // This creates a recursive factorial function and calls it with 2n
+a(n) // Recursively call the function. This adds the elements of the taylor series together
```
To use it:
Press F12, type in the function and then do
```
c(x)(n)
```
[Answer]
## C ~~144~~ 130 bytes
```
F(m){int u=1;while(m)u*=m--;return u;}float f(float x,n){float s;for(int i=1;i<n;i++)s+=pow(-1,i)*pow(x,2*i)/(F(2*i));return 1+s;}
```
Ungolfed Version:
```
//Function to calculate factorial
int F(int m)
{
int u=1;
while(m>1)
u*=m--;
return u;
}
//actual function called in main function
float f(float x, int n)
{
float s=0.0;
for(int i=1;i<=n-1;i++)
s+=pow(-1,i)*pow(x,2*i)/(F(2*i));
return 1+s;
}
```
Thanks Kevin for saving some bytes!
[Answer]
# [Tcl](http://tcl.tk/), 126 bytes
```
proc c {x n k\ 0 r\ 0} {proc F n {expr $n?($n)*\[F $n-1]:1}
time {set r [expr $r+-1**$k*$x**(2*$k)/[F 2*$k]]
incr k} $n
set r}
```
[Try it online!](https://tio.run/##PY6xDoMwDET3fMUNGSAtLURlKEs3fgIYqogBASkKqRQpyrenDkhd/E7WnX1WLTFu5qOg4B005h4lDI0Af@xbWvrRbQZcvzKuc9F3LemiGpoqMDutI/w@Whh0p81cikoIPgvuhMgkqfxOkSSGgU1aGcyBLrAjFeKyvje4Pv1h5a0EKkL9hzzxOPFkMlnkiZqlml@7Q2XcXald06NT4I7uDyH@AA "Tcl – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü┘·.ⁿYeò≥Vîû
```
[Run and debug it](https://staxlang.xyz/#p=81d9fa2efc596595f2568c96&i=0.0+1%0A0.5+1%0A0.5+2%0A0.5+4%0A0.5+9%0A2.0+2%0A2.0+5&a=1&m=2)
Unpacked, ungolfed, and commented, it looks like this.
```
Input is `x n`
Z Push a zero underneath the top. The stack is now `x 0 n`
D Run the rest of the program n times.
xJNi|* (-x*x)^i where i is the iteration index
iH|F/ divide that by factorial(2i)
+ add to the running total so far
final result is implicitly printed
```
[Run this one](https://staxlang.xyz/#c=++++++++%09Input+is+%60x+n%60%0AZ+++++++%09Push+a+zero+underneath+the+top.++The+stack+is+now+%60x+0+n%60+%0AD+++++++%09Run+the+rest+of+the+program+n+times.%0A++xJNi%7C*%09%28-x*x%29%5Ei+where+i+is+the+iteration+index%0A++iH%7CF%2F+%09divide+that+by+factorial%282i%29%0A++%2B+++++%09add+to+the+running+total+so+far%0A++++++++%09final+result+is+implicitly+printed&i=0.0+1%0A0.5+1%0A0.5+2%0A0.5+4%0A0.5+9%0A2.0+2%0A2.0+5&a=1&m=2)
[Answer]
# [Desmos](https://www.desmos.com/calculator), 36 bytes
```
\sum_{k=0}^{n-1}{(-1)^kv^{2k}/(2k)!}
```
[View it on Desmos](https://www.desmos.com/calculator/4roucxcwag)
Unfortunately, not a ton to golf here.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
Normal[Cos@x+O@x^(2#2)]/.x->#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@/KDcxJ9o5v9ihQtvfoSJOw0jZSDNWX69C105Z7X9AUWZeSbSyrl2ag4NyrFpdcHJiXl01V7WBnoGOYa0OiGGKYBjBGCYwhiWIYQRUbARjmNZy1f4HAA "Wolfram Language (Mathematica) – Try It Online")
Mathematica has a more (byte-)efficient way to generate `SeriesData` objects than `Series`. `O[x]^p` truncates the power series of the function at the `p`th power.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 20 bytes
```
⌊*!9İ⁰ṁ§/ȯΠḣD`^o_□⁰ŀ
```
[Try it online!](https://tio.run/##ATEAzv9odXNr///ijIoqITnEsOKBsOG5gcKnL8ivzqDhuKNEYF5vX@KWoeKBsMWA////Mv81 "Husk – Try It Online")
Outputs sign + 9 decimal places; the initial decimal point is implicit.
14 bytes (`ṁ§/ȯΠḣD`^o_□⁰ŀ`) to calculate the cosine, plus 6 bytes (`⌊*!9İ⁰`) to extract the decimal representation from the a rational number...
[Answer]
# MMIX, 60 bytes (15 instrs)
```
cos SETH $5,#3FF0 // E0053FF0: one = 1.0
SETL $2,0 // E3020000: twon = 0
SET $3,$5 // C1030500: term = one
FMUL $4,$0,$0 // 10040000: numer = x *. x
SETL $0,0 // E3000000: accum = 0
INCH $4,#8000 // E4048000: numer = -.numer
0H FADD $0,$0,$3 // 04000003: loop: accum +.= term
FADD $255,$2,$5 // 04FF0205: temp = twon +. 1
FADD $2,$255,$5 // 0402FF05: twon = temp +. 1
FMUL $255,$255,$2 // 10FFFF02: temp *.= twon
FDIV $255,$4,$255 // 14FF04FF: temp = numer /. temp
FMUL $3,$3,$255 // 100303FF: term *.= temp
SUBU $1,$1,1 // 27010101: count--
PBZ $1,0B // 5301FFF9: likelyif(!count) goto loop
POP 1,0 // F8010000: return(accum)
```
This is a really simpleminded algorithm. I managed to avoid using more than three stack temporaries (`$255` is global and free for temporary use, any register numbered less than 32 is guaranteed on-stack).
A few clever tricks and misc notes:
`SET $X,$Y` is a short version of `OR $X,$Y,0`;
it's nice that 1.0 fits entirely in the top quarter of a float, otherwise we would have had to use another instruction to set it;
`PBZ` is a predicted branch (faster if taken) if the register operand is 0;
the `0H` is a local label that the `0B` refers back to;
and `POP a,b` means return `a` local variables and skip `b` instructions after the function call.
] |
[Question]
[
Given a positive integer n as input, output the reversed range sum of n.
A reversed range sum is created by making an inclusive range up to n, starting with 1 and including n, reversing each of the numbers inside, and summing it.
**Example:**
Here is what would happen for an input of 10:
Range: `[1,2,3,4,5,6,7,8,9,10]`
Reverse: `[1,2,3,4,5,6,7,8,9,01]` (1-char numbers reversed are themselves, 10 reversed is 01 or 1)
Sum: `46`
Numbers with 3+ digits are reversed the same way numbers with 2 digits are. For example, 1234 would become 4321.
**Test cases:**
```
Input -> Output
10 -> 46
5 -> 15
21 -> 519
58 -> 2350
75 -> 3147
999 -> 454545
```
Complete text cases to input of 999 can be found [here](https://pastebin.com/2TdCfeS4), thanks very much to @fireflame241.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
### Code
```
LíO
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f5/Ba////zU0B "05AB1E – Try It Online")
### Explanation
```
L # Range
í # Reverse
O # Sum
```
[Answer]
# Bash + GNU utils, 24
```
seq $1|rev|paste -sd+|bc
```
[Try it online](https://tio.run/##Nco7DoAgEAXAnlO8ws6QiAlR4mn4rNEGlN1YcXe0ceoJno@@lwohluiZcGaYCRazgV2xWDjnsCEVhQ@TQGsMf1ed6cZgWqWnXZ6FoDmNLcSeSqb@Ag).
### Explanation
```
seq $1 # range
|rev # reverse (each line)
|paste -sd+|bc # sum
```
[Answer]
## JavaScript (ES6), 42 bytes
```
f=n=>n&&+[...n+""].reverse().join``+f(n-1)
```
My favorite doubly-recursive solution is unfortunately 3 bytes longer:
```
f=n=>n&&+(g=x=>x?x%10+g(x/10|0):"")(n)+f(n-1)
```
[Answer]
# [Perl 6](https://perl6.org), 20 bytes
```
{(1..$_)».flip.sum}
```
[Test it](https://tio.run/##TY7dCoJAEIXv5ykGkVjR1lZbTaToIboMonQDwZ@l1SiiJ@oRuvPFrLGImIsZzvnOYbQ6ldHQGYXniGcpVFecZE2ucDncmODc3jn9kx/LQnPTVfdhJNatMi0u0e0fZVErw4jJmurA/G3u@k4KVLh5Qynocl@jOyZSODanb3i6QoZ2Ueuu9dBWF62yVuXo4A0QC4P0A/v4zh/gofURqeCnWnAfxIykeQSStpAQCDqkSEAu6ApCOYN4dEMxjyFJkjEhaV4 "Perl 6 – Try It Online")
## Expanded:
```
{
( 1 .. $_ )\ # Range
».flip # flip each value in the Range (possibly in parallel)
.sum # sum up the list
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 63 bytes
```
f(n){int t=0,c=n;for(;c;c/=10)t=t*10+c%10;return n?t+f(n-1):0;}
```
[Try it online!](https://tio.run/##FYxNDoIwEIXXcAqCIWkt6NSlQ/UibshAdRIdTC0rwtkr3by8n3yPuidROrDQexmnqv/FkefT65a8Er2yxCo6aMkJ@jkoJKSzs6Cji0cLhhoLGKa4BKnkHs0OdVZfAbeU0c/AorIZ9FoW@SAHdoDcW9jVmDwU37D3XtXN@JC69Yq1xrLYyi2li/0D "C (gcc) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~41~~ ~~36~~ 35 bytes
```
.+
$*
1
1$`¶
1+
$.&
%O^$`.
.+
$*
1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLy5DLUCXh0DYuQyBPT41L1T9OJUGPiwsq@f@/oQGXKZeRIZepBZe5KZelpSUA "Retina – Try It Online") Link includes test cases. Edit: Saved 5 bytes thanks to @FryAmTheEggman. Saved 1 byte thanks to @PunPun1000. Explanation:
```
.+
$*
```
Convert to unary.
```
1
1$`¶
```
Create a range from `1` to `n`.
```
1+
$.&
```
Convert back to decimal.
```
%O^$`.
```
Reverse each number.
```
.+
$*
```
Convert back to unary.
```
1
```
Sum and convert back to decimal.
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
Can't compute higher terms than the recursion limit:
```
f=lambda x:x and int(`x`[::-1])+f(x-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRocKqQiExL0UhM69EI6EiIdrKStcwVlM7TaNC11Dzf0ERUFwhTcPcVPM/AA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṛ€ḌS
```
**[Try it online!](https://tio.run/##y0rNyan8///hzlmPmtY83NET/P//f3NTAA "Jelly – Try It Online")**
### How?
```
Ṛ€ḌS - Link: n
Ṛ€ - reverse for €ach (in implicit range)
Ḍ - convert from decimal list (vectorises)
S - sum
```
[Answer]
# Haskell, 34 bytes
```
\n->sum$read.reverse.show<$>[1..n]
```
Simple and straightforward.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 4 bytes
```
;\r$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/3zqmSOX/f0tLSwA "cQuents – Try It Online")
## Explanation
```
Implicit input n.
; Series mode. Outputs the sum of the sequence from 1 to n.
\r$ Each item in the sequence equals:
\r String reverse of
$ current index (1-based)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog/), 4 bytes
```
⟦↔ᵐ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY/apjzcOkH7/39Dg//@AA "Brachylog – Try It Online")
### Explanation
```
⟦↔ᵐ+
⟦ range from 0 to input
↔ᵐ map reverse
+ sum
```
[Answer]
# [Python 2](https://docs.python.org/2/), 50 47 bytes
-3 bytes thanks to [officialaimm!](https://codegolf.stackexchange.com/users/59523/officialaimm)
```
lambda n:sum(int(`i+1`[::-1])for i in range(n))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqrg0VyMzr0QjIVPbMCHaykrXMFYzLb9IIVMhM0@hKDEvPVUjT1Pzf0ERUJFCmoahgeZ/AA "Python 2 – Try It Online")
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~56~~ ~~41~~ 36 bytes
*15 bytes saved thanks to @fergusq*
```
{seq 1,_|parseInteger`$_`[::-1]|sum}
```
[Try it online!](https://tio.run/##K8pPSfyfFvO/uji1UMFQJ76mILGoONUzryQ1PbUoQSU@IdrKStcwtqa4NLf2f25iZl51tKWlZWxNWu1/AA "Röda – Try It Online")
This is an anonymous function that takes an integer from the input stream and outputs an integer to the output stream.
### Explanation
```
{seq 1,_|parseInteger`$_`[::-1]|sum} Anonymous function
seq 1,_ Create a sequence 1 2 3 .. input and push each value to the stream
| For each value in the stream:
`$_` Cast it into a string
[::-1] And reverse it
parseInteger And parse the resulting string as an integer, while pushing the value to the stream
|sum Sum all the values in the stream
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~103~~ 97 bytes
```
using System.Linq;r=>new int[r+1].Select((_,n)=>int.Parse(string.Concat((n+"").Reverse()))).Sum()
```
[Try it online!](https://tio.run/##XU/BSsRADL3PV4Q9Zdg6sMdS24voSUG2Bw8iEse4DrTpOpmuSPHba1APYkIOeS95eYl6FqfM66xJDtB/aOGxcX@7cJ3krXFCI@uRIoMsLg6kCsfFaaGSIpym9Aw3lAT94q5miedJSmXVwZ7kwHs@cVbu5xHaNbed8DsYe5@3u4fQ88CxID5W4tvO4HBLNoxasrkIF5NEMlq2m40Pv0roLYLpoV8b92IfUHxF24VkwnAp88iZngYO3/dxV9V17c2cqelk8F1Ohe0zxn8GMXnfuM@fXL8A "C# (.NET Core) – Try It Online")
TIO link outputs all the results from 1 to 999, so feel free to check my work.
I expected this to be a bit shorter, but it turns out `Reverse()` returns an `IEnumerable<char>` instead of another string so I had to add some extra to turn it back into a string so I could parse it to an int. Maybe there's a shorter way to go from `IEnumerable<char>` to int correctly.
~~Of minor note, this also uses the functions `Range()` `Reverse()` and `Sum()` all in order.~~
-6 bytes thanks to TheLethalCoder
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~10~~ 7 bytes
*3 bytes golfed thanks to @Adám by converting to a tradfn from a train*
```
+/⍎⌽⍕⍳⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPd8b@2/qPevkc9ex/1Tn3Uu/lR31SQ8H8FMHDkMjTggjFN4SwjQ4SgBZxpjlBgaWkJAA "APL (Dyalog Unicode) – Try It Online")
```
⎕ Input (example input: 10)
⍳ Range; 1 2 3 4 5 6 7 8 9 10
⍕ Stringify; '1 2 3 4 5 6 7 8 9 10'
⌽ Reverse; '01 9 8 7 6 5 4 3 2 1'
⍎ Evaluate; 1 9 8 7 6 5 4 3 2 1
+/ Sum; 46
```
[Answer]
# Ruby, ~~56, 52, 41,~~ 39 bytes
```
->n{(1..n).sum{|i|i.to_s.reverse.to_i}}
```
# Ruby, 34 bytes (if lambda param is a string)
```
->n{(1..n).sum{|i|i.reverse.to_i}}
```
Thanks to @Unihedron for the second solution.
[Answer]
# [Vim](https://www.vim.org/), ~~39~~ ~~37~~ 28 bytes
```
D@"O<C-V><C-A>0<ESC>V{g<C-A>:%!rev
v}gJS0<ESC>@"
```
[Try it online!](https://tio.run/##K/v/38VByV@M0UA6rDqd0UpVsSi1jKusNt0r2EDaQen/f0tLy/@6ZQA "V (vim) – Try It Online")
Tons of bytes saved thanks to some [great advice by user41805](https://chat.stackexchange.com/transcript/message/57622507#57622507)
### Explanation
Step 1: build the range (with summing commands included)
```
D@"O<C-V><C-A>0<ESC>V{g<C-A>
D Delete the input number
@" <ESC> Do that many times:
O Insert a new line above
<C-V><C-A> Write a <C-A> byte (\x01)
0 Followed by a 0
V{ Select all the lines just written
g<C-A> Turn the numbers into an increasing range
```
Step 2: reverse each number
`:%!rev` (that's it)
This will produce a sequence of lines with the reversed number followed by `<C-A>`, which is the command to increase a value by the reversed number. Leading 0s actually move the pointer to the beginning of the line, so they are effectively ignored.
Step 3: sum them all up
```
v}gJS0<ESC>@"
v} Select all the lines to the end of the file
gJ Join them
S Replace this line
0<ESC> with a 0
@" Execute the replaced line as commands
```
[Answer]
# Mathematica, 47 bytes
```
Tr[FromDigits@*Reverse/@IntegerDigits@Range@#]&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvs/JL8kMSfarSg/1yUzPbOk2EErKLUstag4Vd/BM68kNT21CCoelJiXnuqgHKv2P6AoM69EwSFNwcHS0vI/AA "Mathics – Try It Online") (in order to work on mathics we need to replace "Tr" with "Total")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~14~~ 13 bytes
-1 byte thanks to [Carlos Alejo](https://codegolf.stackexchange.com/users/70347/carlos-alejo)
```
I∕…·⁰N«⁺ιI⮌Iκ
```
[Try it online!](https://tio.run/##JYy7CoQwEAB/JeUGI1wbLLWxOQ7/IMZFF3NR8mrEb1/vdGDKGbuYYDfjmD@BfILWxAQdFZoQem9djlRwMH5GeCnR@z2nd/6OGEBKJY4nqoCUuMsBC4aIz2aVf86fDbPWmuvCdXQX "Charcoal – Try It Online") Link is to verbose version.
## Explanation
```
I Cast
∕ « Reduce
…·⁰N Inclusive range from 0 to input as number
⁺ Plus
ι i
I⮌Iκ Cast(Reverse(Cast(k)))
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 12 bytes
```
ri){sW%i}%:+
```
[Try it online!](https://tio.run/##S85KzP3/vyhTs7o4XDWzVtVK@/9/QwMA "CJam – Try It Online")
-1 thanks to [Business Cat](https://codegolf.stackexchange.com/users/53880/business-cat).
Explanation:
```
ri){sW%i}%:+
r Get token
i To integer
) Increment
{sW%i} Push {sW%i}
s To string
W Push -1
% Step
i To integer
% Map
:+ Map/reduce by Add
```
[Answer]
# Java 8, 97 bytes
```
IntStream.range(1,n+1).map(i->Integer.valueOf(new StringBuffer(""+i).reverse().toString())).sum()
```
---
**EDIT**
As per the comment of [`Kevin Cruijssen`](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen), I would like to improve my answer.
# Java 8, 103 bytes
```
n->java.util.stream.LongStream.range(1,n+1).map(i->new Long(new StringBuffer(""+i).reverse()+"")).sum()
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~7~~ 5 bytes
*-2 bytes thanks to @Shaggy.*
```
õs xw
```
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=9XMgeHc=&input=NzU=)
## Explanation
```
õs xw Implicit input of integer U
õs Create range [1,U] and map to strings
w Reverse each string
x Sum the array, implicitly converting to numbers.
```
# Old solution, 7 bytes
Keeping this since it's a really cool use of `z2`.
```
õs z2 x
```
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=9XMgejIgeA==&input=NzU=)
## Explanation
```
õs z2 x Implicit input of integer U
õs Create range [1,U] and map to strings
z2 Rotate the array 180°, reversing strings
x Sum the array, implicitly converting back to integers
```
[Answer]
## C++, 146 bytes
```
#include<string>
using namespace std;int r(int i){int v=0,j=0;for(;j<=i;++j){auto t=to_string(j);reverse(t.begin(),t.end());v+=stoi(t);}return v;}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~7 6~~ 3 bytes
```
ṁ↔ḣ
```
[Try it online!](https://tio.run/##yygtzv7//@HOxkdtUx7uWPz//39LS0sA "Husk – Try It Online")
### Ungolfed/Explanation
```
ḣ -- With the list [1..N] ..
ṁ -- .. do the following with each element and sum the values:
↔ -- reverse it
```
[Answer]
# [Perl 5](https://www.perl.org/), ~~29 27~~ 22 + 1 (`-p`) = 23 bytes
```
map$\+=reverse,1..$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlRtu2KLUstag4VcdQT08lvrb6/39Dg3/5BSWZ@XnF/3V9TfUMDA3@6xYAAA "Perl 5 – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 26 bytes
```
&IFLPWaSD$|~rlMFa*+|&+&|&h
```
[Try it online!](https://tio.run/##S8/PScsszvj/X83TzScgPDHYRaWmrijH1y1RS7tGTVutRg0oZ2gAAA "Gol><> – Try It Online")
## Explanation
```
&I &h < register init, read "n"; print register (h = n;)
FLP | < For loop, do "n" times for each x in [1] to [n]
WaSD$| < modpow "x" to digits: [123] [3 12] [3 2 1] [3 2 1 0]
~rlMFa*+| < Ditch zero, reverse stack, build the number back
&+& < register += final x
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), `s`, 2 bytes
```
ƛṘ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%C6%9B%E1%B9%98&inputs=10&header=&footer=)
[Answer]
# vim, 49 46 bytes
```
A@q<ESC>0"bDa1<ESC>qqYp<C-a>q@bdk:%s/$/+
:%!rev
xVGJ:%!bc
```
`<ESC>` is 0x1b,
`<C-a>` is 0x01,
`<NL>` is 0x0a.
## Annotated
```
A@q<ESC>0"bD # put {N}@q (run macro q N times) in register b
a1<ESC> # buffer now contains "1"
qqYp<C-a>q # store macro that copies and increments the last line in register q
@bd1k # run {N} times, then delete the extra lines
# (can't just run {N-1} times, or it won't handle N=1 correctly)
:%s/$/+<NL> # append + to each line
:%!rev<NL> # reverse each line
x # delete leading +
VGJ # join lines
:%!bc<NL> # sum
```
[Try it online!](https://tio.run/##K/v/39GhUNpAKckl0VC6sDCygLHQISkl20q1WF9FX5vLSlWxKLWMqyLM3QvITErm@v/f0AAA "V (vim) – Try It Online")
[Answer]
# Excel, 59 bytes
```
=LET(y,COLUMN(A:O),SUM((0&MID(SEQUENCE(A1),y,1))*10^(y-1)))
```
Explanation
```
=LET(
y,COLUMN(A:O) 'y = [1..15] horz.; Excel is accurate to 15 places
SUM((0&MID(SEQUENCE(A1),y,1))*10^(y-1)) 'final result
SEQUENCE(A1) '[1..A1] vertical
(0&MID( ,y,1)) 'array of individual digits; 0& is to avoid errors on blank cells
*10^(y-1) 'multiply 2nd column by 10, 3rd 100, etc.
SUM( ) 'sum the array
```
[Answer]
## [Magneson](https://github.com/UnderMybrella/Magneson), 102 bytes
[![Source](https://i.stack.imgur.com/QgOlF.png)](https://i.stack.imgur.com/QgOlF.png)
That's not very visible, so here's a scaled up version (Note: Won't actually run, and still isn't very pretty)
[![Display Purposes Only](https://i.stack.imgur.com/q0xa2.png)](https://i.stack.imgur.com/q0xa2.png)
(source: [googleapis.com](https://storage.googleapis.com/brella-archives/Code%20Golf/Magneson/range_reverse_sum_visible.png))
Magneson operates by parsing an image and evaluating commands from the colours of the pixels it reads. So stepping through the image for this challenge, we have:
* `R: 0, G: 1, B: 1` is an integer assignment command, which takes a string for the variable name and the value to assign. We'll use this to store the sum total.
* `R: 0, G: 1, B: 0` is a prebuilt string with the value `VAR_1` (Note: This is only while we're asking for a string; the colour code has a separate function when used elsewhere).
* `R: 3, G: 0, B: 0` is a raw number. Magneson handles standard numbers by requiring the Red component to be exactly 3, and then forms a number by using the blue value directly *plus* the green value multiplied by 256. In this case, we're just getting the number 0.
* `R: 0, G: 1, B: 1` is another integer assignment command. This time, we're storing an iteration variable, to keep track of which number we're on
* `R: 0, G: 1, B: 1` is a prebuilt string with the value `VAR_2` (Once more, only when we need a string)
* `R: 3, G: 0, B: 0` is the number 0, once more. Onto the interesting bits now.
* `R: 1, G: 0, B: 0` indicates the start of a loop. This takes a number and loops the following snippet of code that many times.
* `R: 2, G: 0, B: 0` is the STDIN function, or at least it is when we need a number. This reads a line of input from the console and turns it into a number, since we asked for a number.
* `R: 0, G: 8, B: 0` starts off our looping code, and it is an additive command. This adds a number to an integer variable, and so takes a string for the variable name, and the number to add.
* `R: 0, G: 1, B: 1` is the prebuilt string for `VAR_2`, which is our iteration variable.
* `R: 3, G: 0, B: 1` is a raw number, but this time it's the number 1.
* `R: 0, G: 8, B: 0` is another addition command.
* `R: 0, G: 1, B: 0` is the string for `VAR_1`, which is our sum total.
* `R: 0, G: 3, B: 0` is a function that reverses a string. In the context of asking for a number, it then converts the reversed string to a number.
* `R: 0, G: 2, B: 1` is an integer retrieval command, and will retrieve the number stored in a provided variable. In the context of asking for a string (such as from the reverse command), it converts the number to a string.
* `R: 0, G: 1, B: 1` is the name `VAR_2`; our iteration variable.
* `R: 1, G: 0, B: 1` is the marker to end the loop, and go back to the start of the loop if the criteria isn't met (so if we need to keep looping). Otherwise, proceed onwards.
* `R: 0, G: 0, B: 1` is a very simple println command, and takes a string.
* `R: 0, G: 2, B: 1` retrieves an integer from a variable
* `R: 0, G: 1, B: 0` is the name of our sum total variable, `VAR_1`
All in all, the program:
* Assigns the value 0 to `VAR_1` and `VAR_2`
* Loops from 0 to a number provided in STDIN
+ Adds one to `VAR_2`
+ Adds the integer value of reversing `VAR_2` to `VAR_1`
* Prints the contents of `VAR_1`
] |
[Question]
[
# Source Code Byte Frequency
---
Write a program that get a single byte character as an input and prints the frequency of that byte in the program's source code as an output.
**Examples:**
Assuming my program is: `ab#cd%b` then the output of the program should be (each line is a separate execution):
```
input output
----- ------
a 0.1428571428571429
b 28.57%
# 14.2857143%
c 1/7
B 0
```
---
### Rules:
* The format of the proportion does not need to be consistent across all inputs, e.g. a fraction for one, decimal for another, percent for a third, plain zero for non-existent byte, etc...
* If a proportion is represented as decimal, the result must be accurate to at least 4 decimal places.
* Source code should be at least 1 byte long.
---
### Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - the shortest code (≥1) wins.
---
(It would also be fun to get the shortest code in every language, so don't hesitate to post multiple entries)
[Answer]
# JavaScript (ES6), 40 bytes
All used characters appear exactly twice. Therefore, this returns either `0` or 2/40 = `0.05`.
```
F=_=>(F+'+./02>cdeilnsu').includes(_)/20
```
[Try it online!](https://tio.run/##HcxBDoIwEIXhvaeYFbSpFqwLF1g2JFzAAxAyFCypU9OCG@PZa@Pu5f@St47vMWKwr@1EfjIp9XrQLetFKWRVqxYnYx3FveTSErp9MpENvFJ1mn1gBBouqgGCG5zVNQ8hOHwOAJjlvgVLi5yDf3aPMXT5nxFvsvYMORQFoKfonZHOLwyP/5z9m34 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 1 byte
```
1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3/D/fwMuQy4jAA "Retina 0.8.2 – Try It Online") Link includes... test cases? But there's not much to test really. The program counts the number of `1`s in the input, so if the input is `1`, then this is 100% of the program's code, and the program outputs `1` accordingly, otherwise the input character is not in the program's code, and therefore the output is `0`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~52~~ 50 bytes
```
s="print`'s=;exec s'+s`.count(input())/50.";exec s
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWqaAoM68kQb3Y1jq1IjVZoVhduzhBLzm/NK9EIzOvoLREQ1NT39RATwkq/f@/erE6AA "Python 2 – Try It Online")
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 53 bytes
```
exec(s:="print(('exec(s:=%r)'%s).count(input())/53)")
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVmj2MpWqaAoM69EQ0MdJqBapKmuWqypl5xfChTPzCsoLdHQ1NQ3NdZU0vz/vwAA "Python 3.8 (pre-release) – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 55 bytes
```
s="print(('s=%r;exec(s)'%s).count(input())/55)";exec(s)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9hWqaAoM69EQ0O92Fa1yDq1IjVZo1hTXbVYUy85vxQokZlXUFqioampb2qqqQSTB2oEAA "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
èè
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=6Og&input=Iugi)
## Explanation
Counts number of times `è` occurs in the input. So outputs 1 if input is `è` otherwise 0
[Answer]
# [Unary](https://esolangs.org/wiki/Unary), ~~~9.84e57~~ ... ~~~3.58e42~~ 59,599,717,533,291,089,242,285,960,261,852 (~5.96e31) bytes thanks to Jo King!
```
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000...why in the world have you scrolled this far? It's Unary - it's just going to be zeroes forever...
```
Outputs `1` if the input is `0`, `0` otherwise.
---
## brainf\*\*\* code (35 bytes)
```
-[>+>+<<-----],+++[->-<]>[>-<,]>--.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fN9pO207bxkYXBGJ1tLW1o3XtdG1i7aKBpE6sna6u3v//hgA "brainfuck – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 5 bytes
```
5○Qc/
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9/00fTuwGT9//@BNAA "Actually – Try It Online")
## Explanation
```
○ Push the byte of input
Qc Count how many times it's in the source code
5 / And divide by five
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), inspecting its own source code, 20 [bytes](https://github.com/abrudz/SBCS)
```
f←{(+/÷≢)⍵=,⎕CR'f'}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///XyHtUduEag1t/cPbH3Uu0nzUu9VW51HfVOcg9TT12v//0xSANBeQ1ACTCmDSQB0A "APL (Dyalog Unicode) – Try It Online")
Note the leading space in the code. When a function is defined in APL, the interpreter converts the source code to its own whitespace formatting (strips most spaces but inserts some at certain places, including the start of each line). The system functions that retrieve the source code (e.g. `⎕CR` and `⎕NR`) give the converted representation.
`f←` part cannot be removed from the score because the source inspection depends on itself being defined as `f`.
```
⎕CR'f' ⍝ Get the char matrix representation of function f
, ⍝ Convert the 1-row matrix to a vector
⍵= ⍝ Compare each char of above with the input char
(+/÷≢) ⍝ Compute the average
```
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), quine-like, 26 [bytes](https://github.com/abrudz/SBCS)
```
(+/÷≢)⍞=13⍴'''(+/÷≢)⍞=13⍴'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@Gtv7h7Y86F2k@6p1na2j8qHeLuro6FkGQ6v@caVzaXEBCHUQYAAA "APL (Dyalog Unicode) – Try It Online")
There is no escape sequence in APL's string literal. Instead, one single quote is represented by two single quotes, so the literal `'''(+/÷≢)⍞=13⍴'` gives the string `'(+/÷≢)⍞=13⍴`.
```
'...' ⍝ Start with the string literal
13⍴ ⍝ Cycle-take first 13 chars, adding `'` at the start to the end
⍞= ⍝ Compare with single-char input from stdin
(+/÷≢) ⍝ Compute the average
```
[Answer]
# JavaScript (Node.js), ~~61~~ 34 bytes
-16 bytes thanks to *MatthewJensen*
-11 bytes thanks to *Arnauld*
```
f=c=>--('f='+f).split(c).length/34
```
[Try it online!](https://tio.run/##bcixCsMgFAXQvV8R6PCUohmS1X5JFzG@xPBQqdLft5nDPeM5/c@38E21m1y2OAa74N7GKGJHL9a2VUldBW0l5r0f87KOUHIrEq2UXbEiT1o/btfAdXACzoJjcA7ch1DOICdwz@vGHw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ 23 bytes
-3 bytes by using the shortest standard quine in 05AB1E.
```
0"D34çýI¢23/"D34çýI¢23/
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7PQ8tMjLWR@X9/w8A "05AB1E – Try It Online")
## Explanation
```
0 Push a 0 for double quote insertion later.
"D34çýI¢23/" Push the quine string.
D Duplicate the quine string.
34çý Insert a double quote between rach item on the stack.
I¢ Count how many times the input appeaes
23/ And divide by 23.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-nl`, ~~56...38~~ 36 bytes (without reading own source code)
```
p~%r,[+-2\[-\]p~%r+2?./8:],?1.0/18:0
```
[Try it online!](https://tio.run/##Fcq7CsIwAEDR/f6FSKe8o0LIEl9/kXQRVARpS9TBpZ9u1PHAqa/Tu7Vp7qrMQvmSVen/Ej5pE2Ivk9PWuBDtbzHTUZFkBApPoSehMQQiDsuOPQeOnLlwZcWaDQu2LD/j9LyNw6Op4f4F "Ruby – Try It Online")
Each of the 18 distinct characters in the code appears twice. The input is tested against a comma-delimited regexp. The outer `[]` is a character class containing literal characters plus two character ranges: `+-2` is equivalent to the literal characters `+,-./012` and `\[-\]` is equivalent to the literal characters `[\]`. The code prints `0.05555555555555555` (decimal expansion of `1.0/18`) if the regexp matches the input character; `0` is printed otherwise.
---
# [Ruby](https://www.ruby-lang.org/) `-nl`, 27 bytes (reads own source code)
```
p (IO.read($0).count$_)/27r
```
[Try it online!](https://tio.run/##DckrEoAgAEDB/k5hIEAQHYvZTyF5BMf/WMBBCF5eNO6sj/OT0pVJM2i/TasUpdKLizaIURVV7f/EMKDxbEysSASKBUfEEn6NNLR09Owcr7vC6eydcvsB "Ruby – Try It Online")
Reads its own source and counts occurrences of the input. Output is a rational number.
---
# [Ruby](https://www.ruby-lang.org/) `-nl` + [coreutils](https://www.gnu.org/software/coreutils/), 24 bytes (reads own source code)
```
p`cat #$0`.count($_)/24r
```
[Try it online!](https://tio.run/##DckxDoMgAEDR/Z/CBkxgqFpjO9fWe4gl0XQBQmHw8mLf@mL@7KUEY5dUCdmZxvrskpKzbvsh/geDZSFRIZB0NHgyDsWMpqVnIDLy4s3EysaNOw8uPKkPH9LXu1@5uhM "Ruby – Try It Online")
Same as above but uses `cat` (from coreutils) to read the source.
[Answer]
# [Io](http://iolanguage.org/), 126 bytes
```
method(h,"mmmeeettthhhooodd((((,,,,aaaaassssMuubl pppn34L))))iif==102/6"asMutable append(34)asList map(o,if(o==h,1,0))sum/62)
```
[Try it online!](https://tio.run/##bctNCsMgEEDhqwxZKQj5JYuCN0hu0I1BRUGdoY7nt3bfb/t4EbuHl4Z3z44DWhHUlHN2zjFzCAERrRWDGsxPHe7WngRARGU/LjnE6LVel20@JzMymyc5MESuWLEf0tQrVoZsSKCKXqDWQa1qkbK2PJ@b7F5Mf08J9ImFU@lf "Io – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
39'39m7/h'hm7/
```
[Try it online!](https://tio.run/##y00syfn/39hS3dgy11w/Qz0DSP7/r26sDgA "MATL – Try It Online")
Each byte is present exactly twice in the source code. Therefore each byte has a frequency of either 1/7 or 0.
```
39 % Push code-point for '
'39m7/h' % Push literal char array
h % Horizontally concatenate. Automatically converts to char array.
m % Ismember: is input in this char array?
7/ % Divide by seven
```
[Answer]
# [PHP](https://php.net/), ~~63~~ 60 bytes
```
fn($a)=>strstr('ffnn($a)==>>str\\\',,??11//220::',$a)?1/20:0
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSZvs/LU9DJVHT1q64pAiINNTT0vIgIrZ2ILGYmBh1HR17e0NDfX0jIwMrK3UdoKS9oT6QbfDfmosrNTkjX0ElDahRXVNBT0FJQcNY38xAMyZPyRohl4dHzgCPHNBynJJK6kq45ZJhcgYwuf//AQ "PHP – Try It Online")
Much better solution than the first version, each char is present 3 times so if it is found, results in 3/63.
EDIT: saved 3 bytes by re-using `n` as var name (I had the luck that the total count still saved the repetition of all numbers for the calculus)
EDIT2: fixed the problem that `n` wasn't counted for not being in the string, manages to keep it 60 by removing `"` and introducing `\` (thanks to Dom Hastings)
EDIT3: fixed the problem with `0` wasn't counted because it was at the end (thanks to Dominic van Essen)
[Answer]
# [R](https://www.r-project.org/), ~~77~~ 75 bytes
*Edit: -2 bytes thanks to Giuseppe*
```
f <-function(c)sum(c==unlist(strsplit(capture.output(dump("f","")),"")))/75
```
[Try it online!](https://tio.run/##ZY1NC8IwDEDv/oowD7bgJ6JDcd49CeJdZmxdYbYzTRB//XQFLy6HHB7vJdRaMs@L85cYhNAUrYXdxIpHdsEr1FEeCotCfO0iq8gUm9qxwrJhITMNwo2wusmjUZnNxlmmdVp6lq/@bneChiEsB/9cJb7ucUk8HwzhVTJW8P227UmQpAUUe5hP54tlGlAYiAyyhldlPJB4uLkO1G9wHkan0Riuwl2y@SXO9yOuKMi9gvPh@O3YkC3RtB8 "R – Try It Online")
Uses R `dump(,"")` function to output own source code\*, capturing output (normally to the console) using `capture.output()`. Then finds the number of matches to the function argument `c`, divided by the source code length (75 bytes).
\*Note that the TIO interface gives slightly differently-formatted output from the `dump()` function to running directly in R, so counts of whitespace characters are inaccurate in TIO (but correct in R).
---
# [R](https://www.r-project.org/) (without reading own source code), 106 bytes
```
'->p;sum(gregexpr(scan(,""),sQuote(p),f=T)[[1]]>0)/53'->p;sum(gregexpr(scan(,""),sQuote(p),f=T)[[1]]>0)/53
```
[Try it online!](https://tio.run/##K/r/X13XrsC6uDRXI70oNT21oqBIozg5MU9DR0lJU6c4sDS/JFWjQFMnzTZEMzraMDbWzkBT39SYLE3/07i4lBXSFPKTk0uLihVKyjOTUxUy8xSK80uLgCxbOwWjw9sNDcwUbBUM9AwMLSzMzC2N/gMA "R – Try It Online")
~~Same~~ Similar approach to above, but including quoted string instead of reading the source code itself.
[Answer]
## x86 machine code (MS-DOS .COM format), ~~53~~ ~~49~~ 44 bytes
Edit: Saved 4 bytes by eliminating a redundant CALL/RET and 5 bytes by outputting via `INT 29H`.
Input is taken from the command line: no input will search for `NUL` (hex 00H). Result is in the form "00/00" (i.e. "03/44" for an input of ")").
The counting part is really easy since this is a COM program: I scan for the target byte starting at DS:100H until I hit the end of the program code. To print the result and total counts, I use `AAM` to convert the numbers into unpacked BCD (which will always be less than 99) and then print the digits after flipping them so that they're displayed in the correct order.
Hex dump:
```
A0 82 00 B9 2C 00 33 D2 BF 00 01 F2 AE E3 03 42 EB F9 8B C2 E8 07 00 B0 2F CD 29 B8 2C 00 D4 0A 05 30 30 86 E0 CD 29 86 E0 CD 29 C3
```
TASM source for generated code:
```
IDEAL
MODEL TINY
CODESEG
ORG 100H
PSIZE EQU PEND-MAIN
PLEN EQU PSIZE+1 ; Loop needs to be one larger so we can break on CX=0
MAIN:
MOV AL,[0082H] ; Get search value from the command line
MOV CX,PLEN
XOR DX,DX
MOV DI,100H ; Start search from the beginning of the program
CLOOP:
REPNZ SCASB ; Search for value
JCXZ CDONE ; Exit when at end of string
INC DX
JMP CLOOP
CDONE:
MOV AX,DX
CALL DISPNUM
MOV AL,'/'
INT 29H
MOV AX,PSIZE
; Fallthrough to print last number and exit
DISPNUM:
AAM ; Convert value to unpacked BCD (AH:AL)
ADD AX,3030H
XCHG AH,AL
INT 29H
XCHG AH,AL
INT 29H
RET
PEND:
END MAIN
ENDS
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~225~~ ~~221~~ ~~217~~ ~~203~~ 197 bytes
-28 bytes ceilingcat
```
char*t,r;main(i,s){for(i=getchar(asprintf(&t,s="char*t,r;main(i,s){for(i=getchar(asprintf(&t,s=%c%s%1$c,34,s));*t;r+=*t++==i);printf(%1$c%%d/197%1$c,r);}",34,s));*t;r+=*t++==i);printf("%d/197",r);}
```
[Try it online!](https://tio.run/##lctNCsJADEDhuwxOmT@RoiAScpgh2pqFVZLsxLOPbXUtuH7fo@1I1BpdqyQrArfKU@Ci8TncJTCOF1taqPoQnmwInRVF96f35NX3Gyr7w0wjJAPJmCxnRI7wpYvw/rzrT8cVS4SX@724D3erbU3f "C (gcc) – Try It Online")
[Answer]
# Python 3, 46 bytes
```
print(open(__file__).read().count(input())/46)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI78gNU8jPj4tMyc1Pl5Tryg1MUVDUy85vxQol5lXUFqioampb2Km@f9/KgA "Python 3 – Try It Online")
Straightforward enough, reads its own source code, counts how many times the input character appears, and returns that divided by 46 (the length of the code). You can also do it in 42 bytes with
```
lambda c:open(__file__).read().count(c)/42
```
but it's a little weird as this isn't a complete program (and since `__file__` will give the whole program, if you try to add a `f=` header, the frequencies get messed up).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
c/+N"c/+NQ7"Q7
```
[Try it online!](https://tio.run/##K6gsyfj/P1lf208JRASaKwWa//@v7qcOAA "Pyth – Try It Online")
## Explanation
```
c/+N"c/+NQ7"Q7
"c/+NQ7" # String literal
+N # Prepend '"'
/ Q # Count occurrences of the input in that string
c 7 # Divide by 7
```
[Answer]
# Google Sheets, 51
Input is in B1.
```
=LEN(REGEXREPLACE(FORMULATEXT(A1),"[^"&B1&"]",))/51
```
For once, we can't use the auto-close trick because the calculation would be wrong.
[Answer]
# Bash, 30 bytes
```
echo `tr -dc "$1"<$0|wc -c`/30
```
[Try it online!](https://tio.run/##S0oszvj/PzU5I18hoaRIQTclWUFJxVDJRsWgpjxZQTc5Qd/Y4P///woA "Bash – Try It Online")
[Answer]
# [><>](https://fishlanguage.com/), 24 bytes
```
'3d*0${:}=+40l4)?.+6*,n;
```
Assumes input on the stack.
1. Reads the code as a string literal, except for the leading `'`
2. `3d*` pushes the character code of `'`, and a counter `0` is also added.
3. Main loop `${:}=+`, increment the counter if the topmost value is equal.
4. `40l4)?.` Exit main loop if all values are read, if not jump back
5. `+6*,n;` print the result of floating point division
[Answer]
# [Lenguage](https://esolangs.org/wiki/Lenguage), 49,673,539,524 bytes
This code contains `49673539524` null bytes, and can actually fit into the universe (and even on a reasonably sized hard drive [or even a flash drive!]), which is saying a lot for Lenguage! Outputs digits as characters; `␁` (with `␁` replaced with an actual Start of Heading character, ASCII `1`) for `1` and infinite null bytes (ASCII `0`) for `0`; `␀␀␀␀␀...` (with `␀` replaced with an actual null character) repeated forever. Converted to codepoints, it's pretty much `00000...` forever, or just `0`. [Try brainf\*\*\* online!](https://tio.run/##SypKzMxLK03O/v9fJ9pOO1pXTzs2Vlvv/38A "brainf*** – Try It Online")\*
```
,[>+[-.+]]+. # full program
, # set cell 0 to code point of input
[ ] # while cell 0 is nonzero...
>+ # set cell 1 to 1
[ ] # while cell 1 is nonzero...
- # set cell 1 to 0
. # output character with code point in cell 1
+ # set cell 1 to 1
+ # set cell 0 to 1
. # output character with code point in cell 1
```
Well this ain't winning. The only reason I submitted this in the first place was because the method used is extremely simple. The code is translated using the method shown in [my other Lenguage answer](https://codegolf.stackexchange.com/a/218529/94066) into the brainf\*\*\* program `,[>+[-.+]]+.`.
\*The reason the TIO link outputs 1 for empty input is because empty input can simulate input of a null byte in brainf\*\*\*, as the current cell is set to `0` if there is no input to take.
Side note: I had ended up golfing over \$7.7×10^{40}\$ bytes from the Lenguage program (34 from the brainf\*\*\* program) since my original version. My first attempt was `-[----->+<]>-->,[<<++[------<+>]<+++.>>-[.]]<.`, my second attempt was `-[----->+<]>-->,[<---.++[.]]<.`, I realized I don't need to output the decimal point (these programs prepended decimal points), and my third attempt was `-[----->+<]>-->,[<-[.]]<.`, until I realized I could golf this down a **ton** by outputting as characters.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
øQ¬c"øQ¬cq¹/9"q¹/9
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2bFGsYyL4UaxjcbkvOSJxuS85&input=Wyf4JywnUScsJ6wnLCdhJywnYicsJ2MnLCciJywncScsJ7knLCcvOSddCi1tUg)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes
```
StringCount[ToString[#0, InputForm], #1]/46 &
```
[Try it online!](https://tio.run/##JYzLCsIwEAB/ZWnAU6Aq1osIQqDQW1Fvyx6Wmj4Oycqy/f4Y8DjMMIltjYltm7jMcC8v0y0vQfZs@JY/oTt6GPJ3t140kQd3ovZyhQOUsXpD56GBxsOMvUoKKytPFjXIJ6Ijolq2D3hyXiLW1bnr6FZ@ "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a single-character string as input and returns a rational number as output. Note the trailing space, which is necessary for the `InputForm` string to match the function.
[Answer]
# [Lua](https://www.lua.org/), 98 bytes
```
s="s,i,p=s..'s=;load(s)(...)',-1,0while p do i,p=i+1,s:find(...,p+1,1)end print(i/98)"load(s)(...)
```
[Try it online!](https://tio.run/##TY3LCoAgEAB/RbqotG1564EfE2zRgpi0RZ9veus4MMyEZ81ZfCPAkLwgavFLOFcyYg0iWg2dg@E9OGwqKTpV9bh1IPPOkaoDqaCzWySVLo634X4abfOv5DL5AA "Lua – Try It Online")
Ported [Python answer](https://codegolf.stackexchange.com/a/209325/59169) to Lua.
The problem with Lua string functions is that you can't accept user input for anything but `string.find` with truthy fourth argument. Anyone trying to golf this should test all magic characters `^$()%.[]*+-?` as possible inputs.
Alternatively,
# [Lua](https://www.lua.org/), 84 bytes (reads own source)
```
s,i,p=io.open(arg[0]):read(),-1,0while p do i,p=i+1,s:find(...,p+1,1)end print(i/84)
```
[Try it online!](https://tio.run/##HcxBCoAgEEDRq7h0aDKFFiF0kmghaDUgOmjR8U1afnj8@LjWKhLySlllDkm6cm56B1uC8xJwNKjfi2IQLHwWvxwMVntQ8lIphdzTQEhecKF0S5qWGVrffg "Lua – Try It Online")
This also assumes that `arg[0]` can be used as path to program, which most likely is so.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~159~~ ~~108~~ 90 bytes
```
x,s;main(c,v)char**v;{for(c=open(__FILE__,0);read(c,&x,1);s+=x==*v[1]);printf("%d/90",s);}
```
[Try it online!](https://tio.run/##S9ZNzknMS///v0Kn2Do3MTNPI1mnTDM5I7FIS6vMujotv0gj2Ta/IDVPIz7ezdPHNT5ex0DTuig1MQWoUK1Cx1DTuljbtsLWVqss2jBW07qgKDOvJE1DSTVF39JASadY07r2////xQA "C (clang) – Try It Online")
-51, thanks to ceilingcat (and also without the four-character-filename limitation)
-18, thanks to ceilingcat!
[Answer]
# [JavaScript (V8)](https://v8.dev/), 48 bytes
```
function f(c){return--(f+'').split(c).length/48}
```
[Try it online!](https://tio.run/##bcgxDoAgDADA3Ve4ATHg4uB3CKGIwWKguBjfXnU13nirPWx1Je6kj5kZGjqKGXuQTp3FUyuotYRBCGXqniI9b5LHQMs4zRe7jDUnb1IOEqTYhFLd5@Dn4s@V9/gG "JavaScript (V8) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 54 bytes
```
f=open(__file__).read();print(f.count(input())/len(f))
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802vyA1TyM@Pi0zJzU@XlOvKDUxRUPTuqAoM69EI00vOb8USGfmFZSWaGhq6ucA1aZpagL1AQA)
`__file__` contains the path to the file the program is in. So f opens the file where it is and grabs the contents of it.
`print(f.count(input())/len(f))`
This counts the occurrences of the character provided and divides it by the total number of characters.
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 18 \log\_{256}(96) \approx \$ 14.82 bytes
```
34C"34C+sc9/"+sc9/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhabjE2clYBYuzjZUl8JTEIkoPILFjpDGAA)
Based off @Mukundan314's Pyth answer.
## [Thunno](https://github.com/Thunno/Thunno), \$ 6 \log\_{256}(96) \approx \$ 4.94 bytes
```
zdsc6/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbLqlKKk830IRyo2IKFKRAGAA)
Probably cheating but I'll put it here anyway.
#### Explanations
```
34C # Push chr(34), the double quote
"34C+sc9/"+ # Prepend it to the string "34C+sc9/"
sc # Swap and count the number of times the input is in the string
9/ # Divide by 9 (Half the length of the program)
```
```
zd # Push the source code
sc # Swap and count the number of times the input is in the string
6/ # Divide by 6 (The length of the program)
```
] |
[Question]
[
We are used to the term "squaring" *n* to mean calculating *n2*. We are also used to the term "cubing" *n* to mean *n3*. That being said, why couldn't we also triangle a number?
# How to triangle a number?
* First off, let's pick a number, `53716`.
* Position it in a parallelogram, whose side length equals the number of digits of the number, and has two sides positioned diagonally, as shown below.
```
53716
53716
53716
53716
53716
```
* Now, we want to ∆ it, right? To do so, crop the sides that do not fit into a right-angled triangle:
```
5
53
537
5371
53716
```
* Take the sums of each row, for this example resulting in `[5, 8, 15, 16, 22]`:
```
5 -> 5
53 -> 8
537 -> 15
5371 -> 16
53716 -> 22
```
* Sum the list `[5, 8, 15, 16, 22]`, resulting in `66`. This is the triangle of this number!
# Specs & Rules
* The input will be a non-negative integer *n* (*n ‚â• 0, n ‚àà Z*).
* You may take input and provide output by [any allowed mean](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* Input may be formatted as an integer, a string representation of the integer, or a list of digits.
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) disallowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
# More Test Cases
```
Input -> Output
0 -> 0
1 -> 1
12 -> 4
123 -> 10
999 -> 54
100000 -> 6
654321 -> 91
```
---
[*Inspiration.*](https://codegolf.stackexchange.com/questions/136564/square-a-number-my-way) Explanations are encouraged!
[Answer]
# [Haskell](https://www.haskell.org/), 13 bytes
```
sum.scanl1(+)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P822uDRXrzg5MS/HUENb839uYmaegq1CQVFmXomCikKaQrSZjqmOiY6xjpGOYex/AA "Haskell – Try It Online")
Takes input as list of digits. Calculates the cumulative sums then sums them.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~4̷~~ 2 bytes
Thanks @H.PWiz for `-2` bytes!
```
Σ∫
```
[Try it online!](https://tio.run/##yygtzv7//9ziRx2r////H22qY6xjrmOoYxYLAA "Husk – Try It Online")
### "Ungolfed"/Explained
```
Σ -- sum all
‚à´ -- prefix sums
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~65, 50,~~ 36 bytes
```
([])({<{}>{<({}[()])>[]}{}<([])>}{})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VlOj2qa61q7aRqO6NlpDM1bTLjq2trrWBiRlB2Ro/v9vqGCkYAwA "Brain-Flak – Try It Online")
After lots of revising, I'm now very proud of this answer. I like the algorithm, and how nicely it can be expressed in brain-flak.
Most of the byte count comes from handling 0's in the input. In fact, if we could assume there were no 0's in the input, it would be a beautifully short 20-byte answer:
```
({{<({}[()])>[]}{}})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O62kajujZaQzNW0y46tra6tlbz/39DBSMFYwA "Brain-Flak – Try It Online")
But unfortunately, brain-flak is notorious for bad handling of edge cases.
# Explanation
First, an observation of mine:
If the input is *n* digits long, the first digit will appear in the triangle *n* times, the second digit will appear *n-1* times, and so on onto the last digit, which will appear once. We can take advantage of this, since it's really easy to calculate how many digits of input are left in brain-flak, namely
```
[]
```
So here's how the code works.
```
# Push the size of the input (to account for 0's)
([])
# Push...
(
# While True
{
# Pop the stack height (evaluates to 0)
<{}>
# For each digit *D*...
# While true
{
# Decrement the counter (the current digit we're evaluating),
# but evaluate to 0
<({}[()])>
# Evaluate the number of digits left in the input
[]
# Endwhile
}
# This whole block evaluates to D * len(remaining_digits), but
# without affecting the stack
# Since we looped D times, D is now 0 and there is one less digit.
# Pop D (now 0)
{}
# Push the stack height (again, evaluating it as 0)
<([])>
# End while
}
# Pop a 0 off (handles edge case of 0)
{}
# end push
)
```
[Answer]
# Pyth - ~~6~~ 4 bytes
```
ss._
```
[Try it online here](http://pyth.herokuapp.com/?code=ss._&input=5%2C3%2C7%2C1%2C6&debug=0).
Nice 6 byte one that doesn't use prefix builtin:
```
s*V_Sl
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
Yss
```
[Try it online!](https://tio.run/##y00syfn/P7K4@P//aFMdBWMdBXMdBUMdBbNYAA "MATL – Try It Online")
Takes the input as a list of digits.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
+\S
```
[Try it online!](https://tio.run/##y0rNyan8/187Jvj////RZjqmOiY6xjpGOoaxAA "Jelly – Try It Online") Uses the same technique as my Japt answer: cumulative addition, then sum.
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
*Takes input as list of digits*
```
f[]=0
f x=sum x+f(init x)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py061taAK02hwra4NFehQjtNIzMvs0ShQvN/bmJmnm1BUWZeiUpatKmOsY65jqGOWex/AA "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 41 bytes
*Takes input as string representation*
```
f[]=0
f x=sum(map(read.(:[]))x)+f(init x)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py061taAK02hwra4NFcjN7FAoyg1MUVPwyo6VlOzQlM7TSMzL7NEoULzf25iZp5tQVFmXolKmpKpsbmhmdJ/AA "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~7~~ ~~6~~ 4 bytes
```
å+ x
```
[Try it online!](https://tio.run/##y0osKPn///BSbYWK//@jzXRMdUx0jHWMdAxjAQ "Japt – Try It Online")
### Explanation
```
å+ x Implicit: input = digit list
å+ Cumulative reduce by addition. Gives the sum of each prefix.
x Sum.
```
---
Old solution:
```
å+ ¬¬x
```
[Try it online!](https://tio.run/##y0osKPn///BSbYVDaw6tqfj/X8nU2NzQTAkA "Japt – Try It Online")
### Explanation
```
å+ ¬¬x Implicit: input = string
å+ Cumulative reduce by concatenation. Gives the list of prefixes.
¬ Join into a single string of digits.
¬ Split back into digits.
x Sum.
Implicit: output result of last expression
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 28 bytes
```
(([]){[{}]({}<>{})<>([])}{})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0MjOlazOrq6NlajutbGrrpW08YOJFQLZP3/b6hgpGAMAA "Brain-Flak – Try It Online")
*14 bytes if we don't need to support zeros (which we do)*
```
({({}<>{})<>})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6Nao7rWxq66VtPGrlbz/39DBSMFYwA "Brain-Flak – Try It Online")
DJMcMayhem has a cool answer [here](https://codegolf.stackexchange.com/a/137651/56656) you should check out. Unfortunately for him I wasn't about to let him win at his own language :P
## How does it work?
Lets start with the simple version.
```
({({}<>{})<>})
```
The main action here is `({}<>{})<>`, that takes the top of the left stack and adds to to the top of the right stack. By looping this operation we sum up the current stack (until it hits a zero) placing the sum on the off stack. That's pretty mundane, the interesting part is that we sum up the results of all these runs as our result. This will calculate the desired value. Why? Well lets take a look at an example, `123`. On the first grab we just get 1 so our value is 1
```
1
```
On the next grab we return 1 plus the 2
```
1
1+2
```
On the last run we have all three together
```
1
1+2
1+2+3
```
Do you see the triangle? The sum of all the runs is the "triangle" of the list.
---
Ok but now we need it to work for zeros, here I used the same trick as DJMcMayhem, plus some fancy footwork. Instead of looping until we hit a zero we loop until the stack is empty.
```
([])({<{}>({}<>{})<><([])>}{})
```
I then used [this tip](https://codegolf.stackexchange.com/questions/95403/tips-for-golfing-in-brain-flak/127942#127942), written by none other than yours truly, to golf off another 2 bytes.
```
(([]){[{}]({}<>{})<>([])}{})
```
And there we have it. I would be surprised if there was a shorter solution, but then again stranger things have happened.
[Answer]
## JavaScript (ES6), 28 bytes
```
a=>a.map(d=>t+=c+=d,t=c=0)|t
```
Takes input as a list of digits.
[Answer]
# [Python 3](https://docs.python.org/3/), 37 bytes
```
f=lambda n:len(n)and sum(n)+f(n[:-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIc8qJzVPI08zMS9Fobg0F8jSTtPIi7bSNYzV/F9QlJlXopGmEW2mY6pjomOsY6QDFNb8DwA "Python 3 – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 59 bytes
```
using System.Linq;N=>N.Reverse().Select((d,i)=>i*d+d).Sum()
```
[Try it online!](https://tio.run/##XZBBS8QwFITv@RXvmGgsu64KEtuL4En34B48LHuI6bMG2tc1SVck9LfX0LWyXQYC32QYHmP8lWkdDp23VMHmxwdsFDul7NnSl2KkG/R7bRAoMlNr72EfmQ86WANPHZkHS2G7k@ktIDirqaoR8mGdF@vsFQ/oPHKRbbBGEzgvpRV5YS/KyzKZXcPFoKa2Q2tLeNGWuIhsbN3uQLvKQw6E3/BnRfYPcdHLE1rOSV6fs1zNnHuZdJZZTJr5d/JW3shValj2rFeMfaTxtPnk4zdQ17yjS9nx3HT9Y0u@rTF7czZgGhL5NA0/ZoVQrD9q@AU "C# (.NET Core) – Try It Online")
Substantially different from the other C# answers. Input is a list of digits. All test cases included in the TIO link.
Could save a bunch of bytes if allowed to take input as a backwards list of digits with leading 0.
[Answer]
# [Python 3](https://docs.python.org/3/), 35 bytes
I just noticed that this is only really a slight golf of [Business Cat's answer](https://codegolf.stackexchange.com/a/137654/53748) in the end though!
```
f=lambda a:a>[]and sum(a)+f(a[:-1])
```
**[Try it online!](https://tio.run/##NUxLCsIwFFzrKd6uCU6haW3FgL1IyOJJDRZsWtq48PQx8cPA/GBmeYX77JsY3eXB03VgYs29sewH2p6TYHlwgo0ulZXRzSuF2xZo9CRMiwYnKHQWZKpMCvVP0GRzRsK3qf7IsUOLY1rXSK96v1vW0QeRn0FF2Rcg90lSxjc "Python 3 – Try It Online")**
[Answer]
# [J](http://jsoftware.com/), ~~7~~ 6 bytes
```
1#.+/\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuo2CgYAXEunrOQTo@bv8NlfW09WP@a3KVJIPkDRSsFQzB2AhKGgNpSzAE8Q3g0FrBTMFUwQQob6RgyMWVmpyRr6BhaKCmrKegEa2jrqBrB7QsVlNNyUohTVPBwU4BaMF/AA "J – Try It Online") Takes a list of digits, such as `f 6 5 4 3 2 1`.
## Explanation
The current explanation is same as the old, but noting that `1#.x` ‚áî `+/x` (both compute sum).
Old:
```
[:+/+/\ (for explanation, input = 6 5 4 3 2 1)
\ over the prefixes of the input:
/ reduce:
+ addition (summation)
this gives is the cumulative sum of the input: 6 11 15 18 20 21
[: apply to the result:
+/ summation
this gives the desired result: 90
```
A little more true to the original problem would be `[:+/@,]/`, which is "sum" (`+/`) the flattened (`,`) prefixes of the input (`]\`).
[Answer]
# [Vim](https://vim.sourceforge.io/), ~~60~~ ~~59~~ 32 keystrokes
Thanks a lot @CowsQuack for the tip with the recursive macro and the `h` trick, this saved me 27 bytes!
```
qqYp$xh@qq@qVHJ:s/./&+/g‚èé
C<C-r>=<C-r>"0‚èé
```
[Try it online!](https://tio.run/##K/v/v7AwskClIsOhsNChMMzDy6pYX09fTVs/nctZyFZIyYDr/38zUxNjI0MA "V – Try It Online")
### Ungolfed/Explained
This will build the triangle like described (only that it keeps it left-aligned):
```
qq q " record the macro q:
Yp " duplicate the line
$x " remove last character
h " move to the left (this is solely that the recursive macro calls stop)
@q " run the macro recursively
@q " run the macro
```
The buffer looks now like this:
```
53716
5371
537
53
5
```
Join all lines into one and build an evaluatable expression from it:
```
VH " mark everything
J " join into one line
:s/./&+/g‚èé " insert a + between all the characters
```
The `"` register now contains the following string (note missing 0):
```
5+3+7+1+6+ +5+3+7+1+ +5+3+7+ +5+3+ +5+ +
```
So all we need to do is append a zero and evaluate it:
```
C " delete line and store in " register
<C-r>= ‚èé " insert the evaluated expression from
<C-r>" " register "
0 " append the missing 0
```
[![inside vim](https://i.stack.imgur.com/8YwON.gif)](https://i.stack.imgur.com/8YwON.gif)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~49~~ 45 bytes
*-4 bytes [thanks to Mr. Xcoder.](https://chat.stackexchange.com/transcript/message/39234534#39234534)*
```
lambda n:sum(-~i*n[~i]for i in range(len(n)))
```
[Try it online!](https://tio.run/##TU3NCsIwGLvvKXJs5RO2@QMKe5LaQ8VWC@u3sdaDl716tUVBCEkICZlf6TFxn91wyaMJ15sBn@MziO3qN6xWr920wMMzFsN3K0bLgqWUOdmYIgYo1WqC6ioR@p8SdsWeCAXftP1HyY6EA2H/KddJp3XTzIvnhGBm4Qj1RuY3 "Python 2 – Try It Online")
Takes input as a list of digits.
[Answer]
# Bash + GNU utilities, 32 24
```
tac|nl -s*|paste -sd+|bc
```
Input read from STDIN.
Update: I see the input may be given as a list of digits. My input list is newline-delimited.
[Try it online](https://tio.run/##S0oszvj/vyQxuSYvR0G3WKumILG4JBXIStGuSUr@/9@Uy5jLnMuQy4wLAA).
### Explanation
```
tac # reverse digit list
|nl -s* # prefix line numbers; separate with "*" operator
|paste -sd+ # join lines onto one line, separated with "+" operator
|bc # arithmetically evaluate
```
[Answer]
# APL, 4 bytes
```
+/+\
```
This takes the input as a list of digits, e.g.:
```
(+/+\) 5 3 7 1 6
66
```
Explanation
```
+/ sum of
+\ partial sums of input
```
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 1478 bytes
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[a]Switch to plan "b" if no one is waiting.Pickup a passenger going to The Babelfishery.Go to Zoom Zoom:n 1 l 3 r.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 4 l 2 r.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to Addition Alley.Go to The Babelfishery:n 1 r 1 r.Go to Chop Suey:n 6 r 1 l.Switch to plan "a".[b]Go to Addition Alley:n 1 l 2 l.Pickup a passenger going to Cyclone.[c]Go to Zoom Zoom:n 1 l 1 r.Go to Cyclone:w.Pickup a passenger going to The Underground.Pickup a passenger going to Multiplication Station.Go to The Babelfishery:s 1 l 2 r 1 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:n 1 r 2 l.Pickup a passenger going to Addition Alley.Go to The Underground:n 2 l 1 r.Switch to plan "d" if no one is waiting.Pickup a passenger going to Cyclone.Go to Addition Alley:n 3 l 1 l.Switch to plan "c".[d]Go to Addition Alley:n 3 l 1 l.[e]Pickup a passenger going to Addition Alley.Go to Zoom Zoom:n 1 l 1 r.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to Addition Alley.Switch to plan "f" if no one is waiting.Switch to plan "e".[f]Go to Zoom Zoom:n 1 l 1 r.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.
```
[Try it online!](https://tio.run/##tZTNboMwDMdfxeIBkKBdD711O@y0rVK3yxCHNAkQLY1RCGJ9eha@Okb5UCvtABHE/tv@OY4h36IsnxEMwh4zA29RJCjfFuCBtI@uVncv6FeeAoGUZBlXMdcQo1Bx5fWUYAqHnJ/dRuXyvVWdP6xbnYCEh0IYmlSGqSQKnKMDIgKFgIqDyKAgwljl2ZDvCYdHcuQyElnCdRf5E/FUv@rIElagXa@nCcTAwRBNEyEZvOYnrlFi3LmPbVkOa6vkW6W5hHaM2QioYCflBcTfnzVRXeXUUrlDcVj3hbAeYb9pmQ@BE8cNjuFoig02f6nhZypts9yAhuPce/k0pttisZ0finEda8wVm7V9yaURqRSU1HnbnlXrFJ@sLWiZ96zu@GZLfwnXZCd7JVspvwU3bBe7Yz66Dk00eVWHuj4Z1J4MFi44BTy8udrpAzIyI/LW2RiWEU0QG9pxW24U/kuGExfUzPzOqfXuZff6pv5NuCw3D@uV7/0A "Taxi – Try It Online")
Un-golfed:
```
[ Pickup stdin and split into digits ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
[a]
[ Count the digits ]
Switch to plan "b" if no one is waiting.
Pickup a passenger going to The Babelfishery.
Go to Zoom Zoom: north 1st left 3rd right.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 4th left 2nd right.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to Addition Alley.
Go to The Babelfishery: north 1st right 1st right.
Go to Chop Suey: north 6th right 1st left.
Switch to plan "a".
[b]
Go to Addition Alley: north 1st left 2nd left.
Pickup a passenger going to Cyclone.
[c]
[ Multiply each digits by Len(stdin)-Position(digit) ]
Go to Zoom Zoom: north 1st left 1st right.
Go to Cyclone: west.
Pickup a passenger going to The Underground.
Pickup a passenger going to Multiplication Station.
Go to The Babelfishery: south 1st left 2nd right 1st right.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: north 1st right 2nd left.
Pickup a passenger going to Addition Alley.
Go to The Underground: north 2nd left 1st right.
Switch to plan "d" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Addition Alley: north 3rd left 1st left.
Switch to plan "c".
[d]
Go to Addition Alley: north 3rd left 1st left.
[e]
[ Sum all the products ]
Pickup a passenger going to Addition Alley.
Go to Zoom Zoom: north 1st left 1st right.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to Addition Alley.
Switch to plan "f" if no one is waiting.
Switch to plan "e".
[f]
[ Output the results ]
Go to Zoom Zoom: north 1st left 1st right.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: north 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.
```
[Answer]
# [Perl 5](https://www.perl.org/), 19 + 1 (`-p`) = 20 bytes
```
s/./$\+=$p+=$&/ge}{
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX09fJUbbVqUAiNX001Nrq///NzM1MTYy/JdfUJKZn1f8X9fXVM/A0OC/bgEA "Perl 5 – Try It Online")
**How?**
$\ holds the cumulative total, $p holds the total of the digits on the current line. Each line of the parallelogram is simply the previous line with the next digit of the number appended. Therefore, it is the sum of the previous line plus the new digit. This iterates over all of the digits, calculating the sums as it goes. The actual substitution is irrelevant; it's just a means to iterate over the digits without creating an actual loop. At the end, $\ is printed implicitly by the `-p` option.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 20 bytes
Takes the input as a list of digits.
```
a->a*Colrev([1..#a])
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9R1y5Ryzk/pyi1TCPaUE9POTFW839iQUFOpUaigq6dQkFRZl4JkKkE4igppGkkamrqKERHm@ooGOsomOsoGOoomMUCRUDYEEzoKBjBaKAiENNSRwGEoKIGyAgkZqajADTOBGwiUIthLNAJAA "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 15 bytes
Takes the input as a polynomial. For example, `5*x^4 + 3*x^3 + 7*x^2 + x + 6` means `53716`.
```
a->(a+a')%(x-1)
```
[Try it online!](https://tio.run/##TYzBCsIwEER/ZSiISbsBkzSVHOyPiMJeKgWRUDzEr4@bUMHD8nZmdifxtppHKgsuKGxmxQMf9UFlY3XhlJ4fxTAz0ra@3rJ2VXRYFGtNuIY@30cM8EIvPAudMMtMhBPBUhNO0BLXV@kJcT@NzYg1D4RJ3CD6Vzzuxb7/f7c3Xb4 "Pari/GP – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
lambda x:sum(i*int(`x`[-i])for i in range(1,1+len(`x`)))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqrg0VyNTKzOvRCOhIiFaNzNWMy2/SCFTITNPoSgxLz1Vw1DHUDsnNQ8kramp@R8uG22gA5QyAiJjHUtLSx1DAxDQMTM1MTYyjLXiUigoApqqkKmjrmunrpOmkan5HwA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṛæ.J
```
A monadic link taking a list of decimal digits and returning the triangle of the number that list represents.
**[Try it online!](https://tio.run/##y0rNyan8///hzlmHl@l5/f//P9pQxwAGYwE "Jelly – Try It Online")**
### How?
```
Ṛæ.J - Link: list of numbers (the decimal digits), d e.g. [9,4,5,0]
·πö - reverse d [0,5,4,9]
J - range(length(d)) [1,2,3,4]
æ. - dot-product (0*1 + 5*2 + 4*3 + 9*4 = 58) 58
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 13 bytes
```
.
$`$&
.
$*
1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX49LJUFFjQtIaXEZ/v9vamxuaMZlwGXIZWgERMZclpaWXIYGIMBlZmpibGQIAA "Retina – Try It Online") Link includes test cases. Explanation: The first stage generates all the prefixes of the original number, the second stage converts each digit to unary, and the third stage takes the total.
[Answer]
# Mathematica, 49 bytes
```
Tr@Array[Tr@s[[;;#]]&,Length[s=IntegerDigits@#]]&
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 3 bytes
```
ùêóùêÇùê¨
```
Explanation:
```
ùêó Get prefixes of input, including itself
ùêÇ Implicitly join elements together, and create an array with all the digits
ùê¨ Sum
```
[Try it online!](https://tio.run/##y0vNzP3//8PcCdOBuAmI1/z/b2psbmgGAA "Neim – Try It Online")
Alternative answer:
```
ùêóùê£ùê¨
```
Explanation:
```
ùêó Get prefixes of input, including itself
ùê£ Join
ùê¨ Implicitly convert to a digit array, and sum
```
[Try it online!](https://tio.run/##y0vNzP3//8PcCdOBeDEQr/n/39TY3NAMAA "Neim – Try It Online")
[Answer]
# Java 8, 53 bytes
I implemented a lambda for each acceptable input type. They each iterate through the number's digits, adding the proper multiple of each to an accumulator.
## Integer as input (53 bytes)
Lambda from `Integer` to `Integer`:
```
n->{int s=0,i=1;for(;n>0;n/=10)s+=n%10*i++;return s;}
```
## String representation as input (72 bytes)
Lambda from `String` to `Integer`:
```
s->{int l=s.length(),n=0;for(int b:s.getBytes())n+=(b-48)*l--;return n;}
```
## Digit array as input (54 bytes)
Lambda from `int[]` (of digits, largest place value first) to `Integer`:
```
a->{int l=a.length,s=0;for(int n:a)s+=n*l--;return s;}
```
* -7 bytes thanks to Olivier Grégoire
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), ~~9~~ 6 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
```
ąĐŁř↔·
```
Explanation:
```
Implicit input
ƒÖ Convert to array of digits
Đ Duplicate digit array
Łř↔ Create a new array [len(array),len(array)-1,...,1]
· Dot product with digit array
Implicit output
```
[Answer]
## **Python 3, ~~94~~ ~~58~~ 54 bytes**
Thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for helping me save quite some bytes!
```
lambda n:sum(int(v)*(len(n)-i)for i,v in enumerate(n))
```
[Try It Online!](https://tio.run/##K6gsycjPM9ZNBtP/S2xj/uck5ialJCrkWRWX5mpk5pVolGlqaeSk5mnkaepmaqblFylk6pQpZOYppOaV5qYWJZakAmU0/xcUgdSWaCiZmZoYGxkqAYUA)
Takes input as a string. It simply multiplies each digit by the number of times it needs to be added and returns their sum.
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 79 bytes
```
N =INPUT
D N LEN(1) . D REM . N :F(O)
X =X + D
Y =Y + X :(D)
O OUTPUT =Y
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NPwdbTLyA0hMsFyPRx9dMw1FTQU3BRCHL1BdJ@nFZuGv6aXJwRCrYRCtoKLlyckQq2kUBWBKeVhosmlz@nf2gIUDtQkMvVz@X/f1Njc0MzAA "SNOBOL4 (CSNOBOL4) – Try It Online")
Input from stdin, output to stdout.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/19123/edit).
Closed 3 years ago.
[Improve this question](/posts/19123/edit)
# Challenge
Draw a Heart shape
![enter image description here](https://i.stack.imgur.com/gXjjm.jpg)
...as ASCII art!
Your art doesn't have to look exactly like mine, but it has to look like a Heart Shape.
The inside of of the heart has to contain the words "Love" at least 20 times
# Rules
* The program must write the art to the console.
* Shortest code (in bytes, any language) wins.
The winner will be chosen on February 14th on Valentines Day
[Answer]
## JavaScript [160 bytes]
The following code seems to be **160 bytes** unformatted.
```
('l2v2l6v2'+ 'e1l1v3l2'+
'v3e1v7e1v7e1v7e1l2v6e1l4v5'+
'e1l6v4e1l8v3e1l7l3v2e1l9l3v1')
.replace(/[lve]\d/g,function
(c){return Array(-~c[1]).
join({l:' ',v:'Love'
,e:'\n'}[c[0
]])})
```
Simply run this in the browser console (e.g. in Firebug or Chrome Dev Tools).
[Answer]
## GolfScript: ~~62~~ ~~57~~ 54 characters
```
4 1.5\.5,+{.5\-\2*\0.}/]4/{[32'LOVE']2*]zip{(*}%''+}%~
```
Output:
```
LOVE LOVE
LOVELOVELOVELOVE
LOVELOVELOVELOVELOVE
LOVELOVELOVELOVE
LOVELOVELOVE
LOVELOVE
LOVE
```
Or, for some added love, and the obligatory abuse of whitespace insignificance (for 84 characters):
```
5 1 .8\
.)...5 ,{.5\-\3
*\0.}/]4 /{[32[9829
:x.'LOVE'\]''+]2
*[@;]zip{(*}%
''+}%~' '15
*x[]+
+
```
Output:
```
♥LOVE♥ ♥LOVE♥
♥LOVE♥♥LOVE♥ ♥LOVE♥♥LOVE♥
♥LOVE♥♥LOVE♥♥LOVE♥♥LOVE♥♥LOVE♥
♥LOVE♥♥LOVE♥♥LOVE♥♥LOVE♥
♥LOVE♥♥LOVE♥♥LOVE♥
♥LOVE♥♥LOVE♥
♥LOVE♥
♥
```
[Answer]
# C - 183 bytes
Not a winner, but a whole lotta love. Can you figure out how it works?
```
#include <stdio.h>
#define C(a) ((a)*(a)*(a))
int main(){int x,y;for(y=9;y>-6;y--){for(x=-8;x<9;x++)putchar(C(x*x+y*y-25)<25*x*x*y*y*y?"LOVE"[(x+10)%4]:'-');putchar('\n');}return 0;}
```
Output:
```
-----------------
--LOVE-----OVEL--
-ELOVEL---LOVELO-
-ELOVELO-ELOVELO-
-ELOVELO-ELOVELO-
-ELOVELOVELOVELO-
--LOVELOVELOVEL--
--LOVELOVELOVEL--
---OVELOVELOVE---
----VELOVELOV----
----VELOVELOV----
------LOVEL------
-------OVE-------
--------V--------
-----------------
```
[Answer]
## Scala - 273 Characters
Well, I certainly don't expect to win for brevity, but I wanted to see if I could do it in Scala. A smarter golfer could probably shave several bytes off, but here's what I got:
```
type D=Double;def w(x:D,y:D,a:D)={val(i,j)=(x-a,y-8);Math.sqrt(i*i+j*j)< 8};val l:Stream[Char]="love".toStream#:::l;val c=l.toIterator;def p(b:Boolean)=print(if(b)c.next else' ');for(y<-0 to 24){for(x<-0 to 32){if(y>7)p((16-x).abs< 24-y)else p(w(x,y,8)|w(x,y,24))};println}
```
Or, if you prefer (still valid code!)
```
type D= Double
def w(x:D, y:D,a:D)=
{val(i,j)= (x-a,y -8);
Math.sqrt(i* i+j*j)< 8};
val l : Stream [Char] =
"love".toStream#:::l;val
c= l .toIterator;def p
(b:Boolean) =print(if
(b)c.next else' ');
for (y <-0 to 24)
{ for (x<- 0 to
32){if(y >7)
p((16-x).
abs <
24-y)
else
p(w
(x,
y,
8
)
|
w(
x,
y,
24)
)}
println}
```
Prints out two semicircles and a triangle to the screen, making a pretty decent facsimile of a heart.![Picture of heart.scala output](https://i.stack.imgur.com/XypzQ.png)
Needs to be run with the scala interpreter (compiling would require adding some extra cruft for `object Main { def main(args: Array[String]) = { ... } }` and I'm just havin' none of that.
[Answer]
## Python, 210 characters
Of course, this won't win because it is a code golf, but I wanted to be creative and I have **not** used the word `Love` in my source code:
```
import gzip
print(gzip.decompress(b'\x1f\x8b\x08\x00\x95\x10\xe0R\x02\xffSPP\xf0\xc9/KU\x80\x03\x10\x8f\x0bB\xa1c.l\x82dJ\xe0\xb0\x01\xe6\x02\x0cATa.T\xf7\x02\x00\xd9\x91g\x05\xc5\x00\x00\x00').decode('ascii'))
```
This is the output:
```
Love Love
LoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLove
LoveLoveLoveLove
LoveLoveLove
Love
```
[Answer]
## Python 2, 117
prints exactly 20 `love`s horizontally.
```
x="love";print" x x\nx xx x\nx x x".replace("x",x)
for i in range(5):print" "*i+x+" "*(9-i*2),x
print" "*6,x
```
output:
```
love love
love lovelove love
love love love
love love
love love
love love
love love
love love
love
```
[Answer]
## Perl - 36 bytes
```
open 0;s
/\S.?/Lo.ve
/ge,print
, , for
<0>
```
Output:
```
LoveLove LoveLove
LoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLove
LoveLoveLoveLove
LoveLove
```
This is a bit of a cheat; it will print `Love` once for every two non-white space characters in the source code. With the required whitespace to make the heart shape, the code is *61* bytes in length: flattened it is only *36* bytes:
```
open 0;s/\S.?/Lo.ve/ge,print,,for<0>
```
---
## Perl - 60 bytes
```
print$"x(15&ord),Love,$/x/\D/for'3h112a05e0n1l2j4f6b9'=~/./g
```
Outputs the following:
```
Love Love
Love Love Love Love
Love Love Love
Love Love
Love Love
Love Love
Love Love
Love Love
Love
```
Exactly 20 `Love`.
---
**Brief Explaination**
[by request](https://codegolf.stackexchange.com/questions/19123/#comment202844_19538)
* **`for'3h112a05e0n1l2j4f6b9'=~/./g`**
This [modifies](http://perldoc.perl.org/perlsyn.html#Statement-Modifiers) the print statement, and iterates over each character. The regex `/./` obviously matches a single character, and in a list context `/./g` will return a list of all characters in the string. A more common, but slightly longer way to write this would be `for split//,'3h112a05e0n1l2j4f6b9'`.
* **`print$"x(15&ord),Love,$/x/\D/`**
The special variable [`$"`](http://perldoc.perl.org/perlvar.html#%24LIST_SEPARATOR) defaults to a space. The [ord](http://perldoc.perl.org/functions/ord.html)inal value of each character mod 16 stores the number spaces needed between each `Love` via string repetition ([`x`](http://perldoc.perl.org/perlop.html#Multiplicative-Operators)). Finally, if the character is not a digit (`/\D/`), the value of [`$/`](http://perldoc.perl.org/perlvar.html#%24INPUT_RECORD_SEPARATOR), which defaults to `"\n"` is tacked on to the end.
[Answer]
# Wolfram Language (Mathematica) - 111
```
i=0;MatrixForm@Table[If[(x^2+y^2-200)^3+10x^2y^3<0,{"L","O","V","E"}[[i++~Mod~4+1]],""],{y,-20,20},{x,-20,20}]
```
![enter image description here](https://i.stack.imgur.com/iZ40c.gif)
[Answer]
# Javascript - 147 141 137 133 characters
```
with(Math){s="";for(k=800;k--;)
x=abs(1.25-k%40/16),y=k/320-1.25,
s+=.75>x+abs(y)|.5>sqrt(x*x-x+y*y-y+.5)
?"Love"[k%4]:39==k%40?"\n":" "}s
```
Note : I posted another answer, but this one use different approach and heart has a different shape.
How it works :
![enter image description here](https://i.stack.imgur.com/2Y1bf.jpg)
First, I render a diamond (equation is `|x|+|y|`) then, I combine two circles on the top. x values are mirrored (so only one circle is needed).
[Answer]
# Ruby, 47, or Golfscript, 41
Boring answer.
```
puts" Love Love
"+"LoveLoveLove
"*6+" Love"
```
Golfscript version:
```
" Love Love
""LoveLoveLove
"6*" Love"
```
Output:
```
Love Love
LoveLoveLove
LoveLoveLove
LoveLoveLove
LoveLoveLove
LoveLoveLove
LoveLoveLove
Love
```
[Answer]
# [Sclipting](http://esolangs.org/wiki/Sclipting) — 28 chars / 56 bytes
```
겤뙡늆굚넰밌各긂밀❷거雙復냄뭖끐❸갰右거雙復겠⓸걠右復終
```
Output:
```
LOVE LOVE
LOVELOVELOVELOVE
LOVELOVELOVELOVELOVE
LOVELOVELOVELOVE
LOVELOVELOVE
LOVELOVE
LOVE
```
[Answer]
## JavaScript - 136 121 115 113 characters
```
s="";for(k=800;k--;)
x=1.25-k%40/16,y=k/320-1.25,
s+=Math.pow(x*x+y*y-1,3)<x*x*y*y*y
?"Love"[k%4]:39==k%40?"\n":" ";s
```
To run : copy paste into browser console (eg : Chrome or Firefox)
[Answer]
## C, 116 chars
(I don't know if this is heart-shaped enough... fills the inside of three circles to produce the output.)
```
i = 192, x, y;
main(t) {
for (; i--; putchar(i % 16? y : 10))
y = i / 16 - 8,
x = i % 16 - 8,
t = x*x + y*y,
y = " Levo"[ (t < 64 & y < 0 | t < 8*abs(x)) * (i % 4 + 1) ];
}
```
Output:
```
veLov veLov
oveLove oveLove
oveLove oveLove
oveLove oveLove
oveLoveLoveLove
oveLoveLoveLove
oveLoveLoveLove
veLoveLoveLov
veLoveLoveLov
eLoveLoveLo
oveLove
```
Earlier in the golfing process, before replacing constant expressions (change `M` to adjust size):
```
#define M 4
i = 3*M * 4*M, x, y;
main(t) {
for (; i--; putchar(i % (4*M)? x : '\n')) {
y = i / (4*M) - 2*M, x = i % (4*M) - 2*M,
t = x*x + y*y, x = " Levo"[ (t < 4*M*M & y < 0 | t < abs(2*M*x)) * (1 + i % 4) ];
}
}
```
I also felt compelled to do this. :P
```
#define F for
#define M main
/*## ####
####*/i =192,x
,y;M(t) {F(;i--
;putchar(i %16?
y:10))y=i/16-8,
x=i%16-8,t=x*x+
y*y,y=" Levo"[(
t<64&y<0|t<8*
abs(x))*(i%
4+1)];}
```
[Answer]
# **Ruby - 113 Characters**
```
l=->a,b=28,c=1{puts (("Love"*a).center(b))*c};l.call(2,14,2);l.call(3,14,2);[7,7,7,6,5,4,3,2,1].map{|x|l.call(x)}
```
**Output:**
```
1.9.3p448 :811 > l=->a,b=28,c=1{puts (("Love"*a).center(b))*c};l.call(2,14,2);l.call(3,14,2);[7,7,7,6,5,4,3,2,1].map{|x|l.call(x)}
LoveLove LoveLove
LoveLoveLove LoveLoveLove
LoveLoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLove
LoveLoveLoveLove
LoveLoveLove
LoveLove
Love
```
To be more clear
![enter image description here](https://i.stack.imgur.com/oSxYd.png)
[Answer]
**Perl - 159 characters**
Not massively golfed...
```
printf"%-14s%14s\n",$_,~~reverse for map{($.,$i,$c)=split',';($"x$i).($.x$c)}qw(L,5,3 o,3,8 v,1,11 e,0,13 L,1,13 o,3,11 v,5,9 e,7,7 L,8,6 o,10,4 v,12,2 e,13,1)
```
Here's the same with added whitespace for slightly better readability...
```
printf "%-14s%14s\n", $_, ~~reverse
for map {
($.,$i,$c) = split',';
($"x$i).($.x$c)
} qw(
L,5,3
o,3,8
v,1,11
e,0,13
L,1,13
o,3,11
v,5,9
e,7,7
L,8,6
o,10,4
v,12,2
e,13,1
)
```
Output is...
```
LLL LLL
oooooooo oooooooo
vvvvvvvvvvv vvvvvvvvvvv
eeeeeeeeeeeee eeeeeeeeeeeee
LLLLLLLLLLLLLLLLLLLLLLLLLL
oooooooooooooooooooooo
vvvvvvvvvvvvvvvvvv
eeeeeeeeeeeeee
LLLLLLLLLLLL
oooooooo
vvvv
ee
```
The complete word "Love" is contained within (vertically) 22 times, plus numerous partials.
[Answer]
# APL, 36 chars / bytes\*
```
7 16⍴∊' ' 'Love'[20400948744⊤⍨36/2]
```
Must be evaluated with `⎕IO←0` (the default varies by implementation)
\*APL can be written in a single-byte charset if needed (as long as you don't use any other Unicode character) so N chars = N bytes for the purpose of counting.
**Output:**
Contains exactly 20 "Love"
```
Love Love
LoveLoveLoveLove
LoveLoveLoveLove
LoveLoveLoveLove
LoveLoveLove
LoveLove
Love
```
[Answer]
# [Extended BrainFuck](http://sylwester.no/ebf/) : 193 (counted without non essential whitespace)
```
{h]<[<]< [<}>>-->
-3>->-3>+9>+9>+>-7>+>->-5>+>->->
-3>+>+>>4->->6+>5+>>4+[-<4+>]<[-
<4+<5+<5+<5+4>&h++]>[-[-[<10+.[-]
>-[[-]3<[-]]>[<4+3<[[->>
+<<]<]]]>[[>]>[.>&h]<<++
>]]>[<<4+[->8+<]
>....[-]<<+>>]>]
```
Turns into:
# Brainfuck: 264 (counted without non essential whitespace)
```
>>-->->> >->->>>+
>>>>>>>> >+>>>>>>
>>>+>->>>>>>>+>->->>>>>+>->->->>>
+>+>>---->->++++++>+++++>>++++[-<
++++>]<[-<++++<+++++<+++++<+++++>
>>>]<[<]<[<++]>[-[-[<++++++++++.[
-]>-[[-]<<<[-]]>[<++++<<<
[[->>+<<]<]]]>[[>]>[.>]<[
<]<[<]<<++>]]>[<<
++++[->++++++++<]
>....[-]<
<+>>]>]
```
You run it with any bf interpreter. Ubuntu has `bf` and `beef` and both works nicely.
```
bf heart.bf
```
The output (344 bytes):
```
LOVELOVE LOVELOVE
LOVELOVE LOVELOVE
LOVELOVELOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVE
LOVELOVELOVELOVE
LOVELOVE
LOVELOVE
```
Ungolfed EBF code:
```
>>--> ; mark
;; ## ##@
;;########@
;;########@
;; ######@
;; ####@
;; ##@
;; the block below is the art above
;; where space is replaced with ->
;; # with > and @ with +>
->>>->->>>+>
>>>>>>>>+>
>>>>>>>>+>
->>>>>>>+>
->->>>>>+>
->->->>>+>+>
;; we store the string LOVE after a blank
>
~"LOVE"<[<]<
[<++] ;; add 2 to every cell until mark
;; Variables
:new
:zero
:in
:next
@zero
$in(
-[ ; 1
-[ ; 2
$zero 10+.[-]
$in-[#[-]$new<[-] @in] ; its second round lf
$next[#$in++++$new<[[->>+<<]<]]@new ; 2
]
>[[>]>[.>]<[<]<[<]<<++> ]@new
]>[@next $zero 4+(-$in 8+) $in.... (-) $new+ $in]@zero
)
```
[Answer]
# C# 224
```
class P{static void Main(){for(int i=0,m=1;i<30;i++)for(int l=0;l<new[]{5,6,7,6,8,10,3,10,4,13,1,13,1,87,1,27,4,23,7,20,11,16,16,11,20,7,24,3,27,1}[i];l++,m++)System.Console.Write((i%2>0?"love"[m%4]:' ')+(m%29>0?"":"\n"));}}
```
Formatted:
```
class P
{
static void Main()
{
for (int i = 0, m = 1; i < 30; i++)
for (int l = 0; l < new[] { 5, 6, 7, 6, 8, 10, 3, 10, 4, 13, 1, 13, 1, 87, 1, 27, 4, 23, 7, 20, 11, 16, 16, 11, 20, 7, 24, 3, 27, 1 }[i]; l++, m++)
System.Console.Write((i % 2 > 0 ? "love"[m % 4] : ' ') + (m % 29 > 0 ? "" : "\n"));
}
}
```
Output:
```
velove elovel
ovelovelov velovelove
lovelovelovel velovelovelov
lovelovelovelovelovelovelovel
ovelovelovelovelovelovelovelo
velovelovelovelovelovelovelov
lovelovelovelovelovelovelov
elovelovelovelovelovelo
ovelovelovelovelovel
lovelovelovelove
lovelovelov
elovelo
vel
l
```
[Answer]
**Perl - 97 characters**
This answer is based on @Wasi's 121 character Python solution.
```
$.=love;say" $. $.$/$. $.$. $.$/$. $. $.";say$"x$_,$.,$"x(9-$_*2),$.for 0..4;say$"x 6,$.
```
You need to run perl with the `-M5.010` option to enable 5.10-specific features. This [is apparently allowed](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions/274#274).
Interesting features:
* I use the variable `$.` to store the word "love". This is because it can be immediately followed by another word if necessary. `$.for` is unambiguously tokenized as `$.` followed by `for`; `$_for` would not be tokenized as `$_` followed by `for` because `$_for` is itself a legal variable name.
* `$"`, a built-in variable representing that character that arrays will be joined with when interpolated into a string (and defaults to a single space character) is used instead of `" "` for savings of one character here and there.
* Perl's string interpolation beats the python `.replace` method significantly in code golfing.
* Perl's `for 0..4` similarly wins over `for i in range(5)`
[Answer]
# CJam - 33 bytes
```
19285703234336595Zb["Love"SS+N]f=
```
[Try it online](http://cjam.aditsu.net/#code=19285703234336595Zb%5B%22Love%22SS%2BN%5Df%3D)
**Output:**
```
Love Love
LoveLoveLoveLove
LoveLoveLoveLove
LoveLoveLoveLove
LoveLoveLove
LoveLove
Love
```
**Explanation:**
```
19285703234336595 number that contains the pattern as base-3 digits
Zb converts to base 3 (Z=3)
["Love"SS+N] creates an array containing "Love", " " and a newline
f= replaces the base-3 digits with the corresponding strings
(0 -> "Love", 1 -> " ", 2 -> newline)
```
[Answer]
# Python, 334 Bytes
```
x = "love"
print("\t love\t love")
print("\t"+str(x*2)+" "+str(x*2))
print(" "+str(x*6))
print(str(" "*5)+str(x*6)+"lo")
print(str(" "*5)+str(x*6)+"lo")
print(" "+str(x*6))
print("\t"+str(x*5))
print("\t"+str(" "*2)+str(x*4)+"l")
print("\t"+str(" "*4)+str(x*3)+"l")
print("\t"+str(" "*7)+str(x*2))
print("\t"+str(" "*10)+"v")
```
output:
![enter image description here](https://i.stack.imgur.com/eaOIY.png)
[Answer]
**Bash, 170 bytes**
totally a copy of programFOX's :)
```
echo '\x1f\x8b\x08\x00\x95\x10\xe0R\x02\xffSPP\xf0\xc9/KU\x80\x03\x10\x8f\x0bB\xa1c.l\x82dJ\xe0\xb0\x01\xe6\x02\x0cATa.T\xf7\x02\x00\xd9\x91g\x05\xc5\x00\x00\x00'|gunzip
```
[Answer]
print('\n'.join([''.join([(' *Your text here*'[(x-y) % len(' *Enter same text here*')] if ((x*0.05)\*\*2+(y*0.1)\*\*2-1)\*\*3-(x\*0.05)**2*(y*0.1)\*\*3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))![enter image description here](https://i.stack.imgur.com/clB4F.jpg)
] |
[Question]
[
[Sandbox](https://codegolf.meta.stackexchange.com/a/20666/80214), [Codidact](https://codegolf.codidact.com/posts/280612)
*A rewrite of [this question](https://codegolf.stackexchange.com/questions/16124/write-an-interactive-deadfish-interpreter) with a simpler input format and guidelines.*
## Challenge
Deadfish uses a single accumulator, on which all commands are to be performed.
It has the following commands:
| Command | Description |
| --- | --- |
| `i` | increment the accumulator |
| `d` | decrement the accumulator |
| `s` | square the value of the accumulator |
| `o` | output the value of the accumulator as a number |
The accumulator starts with a value of zero. If, after executing a command, the accumulator is equal to -1 or equal to 256, the accumulator must be reset to zero.
## I/O
Input can be taken as a single string, list of codepoints, or any other reasonable format. It is guaranteed that the input will only consist of deadfish commands.
Output can be given as an array of numbers, or just the numbers printed with separators between them.
## Testcases
(some are borrowed from the [Esolangs wiki](https://esolangs.org/wiki/Deadfish#Mandatory_test_cases))
```
iissso -> 0
diissisdo -> 288
iissisdddddddddddddddddddddddddddddddddo -> 0
isssoisoisoisoiso -> 1,4,25,676,458329
ooooosioiiisooo -> 0,0,0,0,0,1,16,16,16
iiii -> nothing
iiiiiiiissdiiiiiiiiiiiiiiiiio -> 4112
o -> 0
```
[Without Outputs](https://dzaima.github.io/paste#0y8wsLi7O50rJBNKZxSn5XFAGIQBUCNKYiYS48kGgODM/E2gGkAUA)
[Answer]
# [flex](https://www.gnu.org/software/bash/), ~~86~~ \$\cdots\$ ~~83~~ 82 bytes
Saved 2 bytes and got moved into TIO thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314)!!!
```
%{
a;m(){a*=a!=256;}
%}
%%
i m(++a);
d m(a&&--a);
s m(a*=a);
o printf("%d ",a);
%%
```
[Try it online!](https://tio.run/##hY3BTsNADETP@CuGik1TyqZSpXJJyw2ufMOS3TSW0hjVSG1V@PbgLSAhLoys9Xhkv30J2o1tn45Yrx@fn0Z3plDvytk53G7C9Wa5uq8/yFk5YuzK@TzMaormQlF4nwfNgy2bFbzueXhry4mLmNzlyLnRsETbpoH9Up1OVQMviCnElrWD79ue6NBxn7C30BCyrRGFrlLTCfyAmxxh6h8wRVHgEn9l76gWPySKMqSRWVWFYu6sRvk2/8kW8yH/KpIsZWFjmDMU8@XJUo38V3ZCnw "Bash – Try It Online")
[flex](https://en.wikipedia.org/wiki/Flex_(lexical_analyser_generator)) stands for fast lexical analyser generator. It takes input as above and generates a lexer in C.
The input comprises of a C declaration section:
```
%{
a;m(){a*=a!=256;}
%}
```
where here we simply declare the accumulator `a` (implicitly as an `int`) and a function to set the accumulator to \$0\$ if it's \$256\$ after a computation.
This is followed by the rules section comprised of all the regexes that need to be parsed along with their actions (in C):
```
%%
i m(++a);
d m(a&&--a);
s m(a*=a);
o printf("%d ",a);
%%
```
here we have our 4 characters along with the code to run when each is encountered. Decrement will only happen if the accumulator is non-zero.
There's a program section that follows this but it will simply default to a `main` that runs the parser if left out (as in this case).
You can generate the C-source code lexer from the above (in file `deadfish.l`) and compile it with the following:
```
flex deadfish.l
gcc lex.yy.c -o deadfish -lfl
```
After compiling, running the following:
```
echo iissso | ./deadfish
echo diissisdo | ./deadfish
echo iissisdddddddddddddddddddddddddddddddddo | ./deadfish
echo isssoisoisoisoiso | ./deadfish
echo ooooosioiiisooo | ./deadfish
echo iiiiiiiissdiiiiiiiiiiiiiiiiio | ./deadfish
```
outputs:
```
0
288
0
1 4 25 676 458329
0 0 0 0 0 1 16 16 16
4112
```
You can also just run it as `./deadfish` and have an interactive deadfish environment to play with to your heart's content!
[Answer]
# JavaScript (ES10), 66 bytes
Expects a list of codepoints.
```
a=>a.flatMap(n=>n%5?p:(p=(p=[p-!!p,p+1,,p*p][n&3])-256&&p,[]),p=0)
```
[Try it online!](https://tio.run/##jZHdaoMwFMfvfYpUmMTtmDapOrcRxxi93BOIF0HrmuFM8Mhe3yUVYRS27pdzcSD8P@B8qC@FzajtlAymPc6dnJUsFet6Nb0pSwdZDjfZs32kVrqpbLLZWLB3HMDe2roaon0dJyLLo8hCVcdg5S6en6qAkFBrRDQhkOtst2TnJa3XaGz/oXISURRrjtNcw3uuOedm@sf8nuckHFIQGeT3OaRZsRcP3sJ4UBvt4t32V2GfCuvjwPNllu4LiK2@xISXLinnIqgD1pnxoJoTRSJL0pgBTX9kvXmnHa0YY1izT3e75vzLmpMaX91tXyYae@Zv "JavaScript (Node.js) – Try It Online")
### How?
`o` is the only command whose codepoint (\$111\$) modulo \$5\$ is not equal to \$0\$. This is also the only command that requires a special operation that doesn't update the accumulator. That's why we first test that.
If the first modulo is \$0\$, we apply a modulo \$4\$ to distinguish between the other commands and update the accumulator accordingly.
```
char. | code | mod 5 | mod 4
-------+------+-------+-------
'd' | 100 | 0 | 0
'i' | 105 | 0 | 1
'o' | 111 | 1 | (3)
's' | 115 | 0 | 3
```
[Answer]
# [convey](http://xn--wxa.land/convey/), ~~90~~ 76 bytes
```
{"='i'
0+#<
^v"='d'
^-#<
^v"='s'
^*#+1
^.=<'o'
^>@`
^}",
*<<"=256
.="*.
0-1
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiIHtcIj0naSdcbjArIzxcbl52XCI9J2QnXG5eLSM8XG5edlwiPSdzJ1xuXiojKzFcbl4uPTwnbydcbl4+QGBcbl59XCIsXG4qPDxcIj0yNTZcbi49XCIqLlxuMC0xIiwidiI6MSwiaSI6IidkaWlzc2lzZG8nIn0=)
On the top right side, the input gets compared with `idso`. The result (0 or 1) then gets combined with the accumulator: `a += c == 'i'`, `a -= c == 'd'`, `a = pow(a, (c == 's') + 1)` (pow = `*.`), and `o` pushes a copy into the output `@"}`. At the bottom are the checks for `-1/256`, by calculating `a *= a != 256` and `a *= a != -1`. Then the accumulator loops back to start the next round.
One iteration of the accumulator loop:
[![one iteration](https://i.stack.imgur.com/T324j.gif)](https://i.stack.imgur.com/T324j.gif)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~60~~ 58 bytes
*Saved 2 bytes thanks to @Sisyphus*
```
a=0;$<.bytes{|b|a=0if(a=eval'~-~p a*'[b%20/3,2]+?a)^256<1}
```
[Try it online](https://tio.run/##KypNqvz/P9HWwFrFRi@psiS1uLomqQbIz0zTSLRNLUvMUa/TrStQSNRSj05SNTLQN9YxitW2T9SMMzI1szGs/f8/s7i4OD8TCQEA "Ruby – Try It Online") or [verify all test cases](https://tio.run/##hVDBbsIwDL3nKyxgA7asawN0jIF22mGnfQBiUkrMaqk0VZOyIQq/3iWjSNMue7Hy7Cc/y3JZJfsGvwpcW1SwgGXIQUynHBwvIz7mYsLjh5iPJ9OReFxx33B5EY/iczg9p4zDOIqEs65Ybx5sZTG4nq1TvS2GAcp1CkpDTTUrKmug85o7nkH3QMdOK71V1mudpgu9OZCBEqUCnWd7MBo2ugSLxlL@AZ8IqdwhWA2VQZC5timWsJMlySRDGLgKOdCQyUX4REGyd85DndSupM1ALnAns/7p7lSAvOkvkysR3o@4WN0@y@G7mMTz6Nicd3ppT@M3vZwpMCltbLs2w1w1RMYYzZRnMkqzNvkPrtEb6Vcw7WFIk5vhMjeK6OfzMEbRXzjLNw "Ruby – Try It Online").
Full program that reads a string from STDIN and outputs to STDOUT, one number per line.
Each operation on the accumulator `a` is carried out by `eval`ing a 3-byte string. The third byte is always `a`. The first two bytes are extracted from the string `~-~p a*` starting at index `b%20/3`:
| Op | \$b\$ | \$\left\lfloor\frac{b\bmod20}{3}\right\rfloor\$ | `eval` |
| --- | --- | --- | --- |
| `d` | \$100\$ | \$0\$ | `~-a` |
| `i` | \$105\$ | \$1\$ | `-~a` |
| `o` | \$111\$ | \$3\$ | `p a` |
| `s` | \$115\$ | \$5\$ | `a*a` |
The reset conditions on the accumulator, which might be written `a==-1||a==256` in ungolfed form, are replaced by the single condition `a^256<1` (`^` is bitwise XOR) because negative accumulator values other than \$-1\$ are not possible.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ ~~82~~ ~~76~~ 74 bytes
Thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) for spotting a bug and -6 bytes!
-2 bytes thanks to [Mukundan](https://codegolf.stackexchange.com/users/91267/mukundan314)!
Takes input as a list of codepoints.
```
a=0
for x in input():
a=[a-1,a+1,a,a*a][x/6%4];a*=a^256>0
if x%5:print a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9HWgCstv0ihQiEzD4gKSks0NK24FBJtoxN1DXUStYFYJ1ErMTa6Qt9M1STWOlHLNjHOyNTMzoBLITNNoULV1KqgKDOvRCHx//9oQwNTHQVDQzTCEEgYkMuNBQA "Python 2 – Try It Online")
[Answer]
# [Nim](http://nim-lang.org/), 104 bytes
```
var r=0
for c in stdin.readAll:
r=[r*r,r,r+1,r-1][28-c.ord div 4];r*=int (r xor 256)>0;if c=='o':echo r
```
[Try it online!](https://tio.run/##TYxBCoMwFAX3nuLtbK2KSluKkkLPIS4kUfrB5sOLSG@fZllmdgPj5RPjMRM0TbYqYSEeYXfiay6ze21bn6U4smCZuLQlq3Yau0dla6WDkwPXaWBhxO84Ed806W7387MZZIU1Jte8X@xbwRglhKDy5w8 "Nim – Try It Online")
Based on @ovs's amazing Python answer.
# [Nim](http://nim-lang.org/), 120 114 109 bytes
```
var r=0
for c in stdin.readAll:
case c
of'i':r+=1
of'd':r-=1
of's':r*=r
else:r.echo
if r in[-1,256]:r=0
```
[Try it online!](https://tio.run/##Tc2xCgIxEIThfp9iugP1Dk/QIpDC5ziuCMkGF2ICu@LrxyAWwhRfNX@VZ@/voFB/ptwUEVJhryR1UQ7pXoojxGCMSGh5ksnp0a9fp@H5Zxs@eCVwMXa6cHw0gmToONzm9XS53nY3Kr2LmTX52wc "Nim – Try It Online")
This is embarassingly readable.
*-5 bytes by taking inspiration from @Gotoro's Python answer*
[Answer]
# [Python 3](https://docs.python.org/3/), ~~120~~ 95 bytes
```
n=0
for x in input():
if n in(-1,256):n=0
if"o"==x:print(n)
else:n=[n+1,n-1,n*n][ord(x)%4^1]
```
[Try it online!](https://tio.run/##FYrLCsMgFAXX8SskUNAkhdrXQvBLQroyoRfKuaIG7NcbA7M5cyb885fxqBXuJjaOskhCI@xZaSs62uQ51dVM99db2zNrsufeuWJDJGQFLbr1l9Z2zhjNhBZjwDJz9Kroy/Njllo9UUqUPB8 "Python 3 – Try It Online")
Brought it down by 25 bytes thanks to [Danis](https://codegolf.stackexchange.com/users/99104/danis) suggestion!
Using bit manipulation `^` we choose from the list of possible operations.
[Original suggestion](https://tio.run/##FYrLCsMgEEX3fsUQKGhrIUkfC8EvCenKhA6UO6IW7NdbA2dzzz3xV96CW2vwo9olUSVGJ36LNk4R73RMfZ3s/Hgad2RdDjJ4X11MjKJhFG2fvPVzGS3OsOg5LtO6SAq6mtP9Na@tBeacOQf5Aw) used `ord(x)%4^2` which yielded `0,1,2,3` for indexes and required the use of an additional 0 in the list at the index `0`;
using `^1` instead yields `0,1,2`, which allows to save 2 bytes in comparison.
Maybe it is possible to account for that additional 0 and use it as a condition to print `o` instead.(?)
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 81 bytes
Not the dead one :)
```
0v~$?$0+{="Ā":}=-10<
l<n:oav?="i"{v?="d"}:{v?="s"}:{;?=1
{~:*1-> 2+0}>{~1-:v >
```
[Try it online!](https://tio.run/##HcZBCsMgEEDRvacYBlcNgnY5jXqWQggdKHUx4EaUHC73msT@zX87y0fV12Gz9UuLeB5IPbrgV/Ndf1TeNUdkbHMbdvpDJl45BtMGPYJLAM/F99RGcFQBkqo6gTITLswsty4 "><> – Try It Online")
Branching is the kryptonite of ><> terseness, so the golfiness here was creating a branchless -1 and 256 check `~$?$0+{="Ā":}=-10` backwards on the first line to get rid of whitespace. The `s`, `i` and `d` commands also feed into each other to make the layout manageable.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~92~~ 91 bytes
Thanks to ceilingcat for the -1.
Converts each operation into the range `[0,3]` to simplify the decoding process.
```
a,b;f(char*s){for(a=0;b=*s++/2;a*=a-256&&~a)(b&=3)?--b?--b?printf("%i ",a):a--:(a*=a):a++;}
```
[Try it online!](https://tio.run/##hVFdT8MgFH3vr7ip2QK06NptdQ6rf2DxzSfnA4V2I5llGfiRLPOnW4Fmc/ri4RJOzr33XAKCroToOp5WrEFizXfE4H2jd4iXI1aVxCTJVc44KTnNp8Vw@MkxqoblGN9TWoW93anWNigeKIhTjuec0jnyDY4mCTt0F6oVm1dZw62xUunL9V0UuRZ44apFb1pJDPsIwA8HYmtjzdNz6RWAWCljjI5TiEdx2kvSa8rIoOazmTt@ap3@H367BX91Fj6bwQTyKRTXBUyms3F@c6zWHkZp5WY5FpygXxlkRR8nawdfgVpt16pd4fOEhzFS/UXwnGRZfhp5ft2Hx8XCkUMKhFgWOeq/ypbh1Zh7PQbH71ja@mNbC1vLOQzMsnU2xCYJxtCgQFh06L5Es@Er09H3bw "C (gcc) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes
```
Fold[<|i->#+1,d->#-1,s->#^2,o:>Echo@#|>@#2/.-1|256->0&,0,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0/JyXapiZT105Z21AnBUjpGuoUA6k4I518KzvX5Ix8B@UaOwdlI309XcMaI1MzXTsDNR0DHeVYtf9p0QFFmXklDsrWQF5dcHJiXl01V3WmTqZOMRjm1@pwVafowARAZApEEFWIUgg1Emop2FAsJEhRvg4MguzOBzsNoiQf4TBkWAx2YCZBmF/LVfsfAA "Wolfram Language (Mathematica) – Try It Online")
Input a list of symbols.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~55~~ ~~53~~ ~~52~~ 51 bytes
Thanks to [user41805](https://codegolf.stackexchange.com/users/41805/user41805) for removing awk flags
Expects each operation to be on a separate line
```
{a*=a!=256}/i/{a++}/d/{a&&a--}/s/{a*=a}/o/{print+a}
```
[Try it online!](https://tio.run/##SyzP/v@/OlHLNlHR1sjUrFY/U786UVu7Vj8FSKupJerq1uoX64MV1Orn61cXFGXmlWgn1v7/n8mVAoT5/wE "AWK – Try It Online")
## Explanation
```
{a*=a!=256} # Before each operation multiply a by 0 if it equals 256
/i/{a++} # If line contains 'i' increase a by 1
/d/{a&&a--} # If line contains 'd' and a is non-zero decrement a by 1
/s/{a*=a} # If line contains 's' square a
/o/{print+a} # If line contains 'o' output a
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 23 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
0ÿ)²(o▒꽧"_♠bαm¡╓*"u~╘
```
Input as a list of codepoint integers.
[Try it online.](https://tio.run/##y00syUjPz0n7/9/g8H7NQ5s08h9Nm3R41aG9h5YrxT@auSDp3MbcQwsfTZ2spVRa92jqjP//DQ1MdcDYEBkbchkaGOhgyMHYIDmwGjzyA41h7kP1F5J7iWJzgfkYGOZXQ0QYIeuHYC4UOQNTdD4mNkQOP1PKMcT9AA)
**Explanation:**
```
0 # Start with 0
ÿ)²(o # Push 4-char string ")²(o"
▒ # Convert it to a list of characters: [")","²","(","o"]
ê # Push the input-list of codepoint integers
½ # Integer-divide each by 2
§ # Index (modulair 0-based) them into the list of characters
"_♠bαm¡╓*"u # Join these characters with "_♠bαm¡╓*" delimiter
~ # Execute the entire string as MathGolf code
╘ # Discard everything left on the stack (which otherwise would be
# output implicitly)
) # Increase by 1
² # Square
( # Decrease by 1
o # Print without popping
_ # Duplicate the top of the stack
♠bα # Push 256, push -1, wrap them in a list: [256,-1]
m # Map over both of them:
¡ # And check that they're NOT equal to the value we've duplicated
# (0 if the duplicated value is -1 or 256; 1 otherwise)
╓ # Pop and get the minimum of this list
* # Multiply it to the value
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~22~~ 21 bytes
~~-1~~ -2 bytes thanks to [Command Master](https://codegolf.stackexchange.com/users/92727/command-master)!
Takes input as a list of codepoints.
```
õ?Îv">n<="y;è.VD₁^0›*
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8Fb7w31lSnZ5NrZKldaHV@iFuTxqaowzeNSwS@v//2hDA1MdBUNDNMIQSBiQy40FAA "05AB1E – Try It Online")
**Commented**:
```
õ? # print the empty string without a trailing newline
# this is necessary to disable implicit output if no 'o' is in the code
Î # push 0 and the input
v # iterate over the instructions y in the input:
">n<=" # push string literal ">n<="
# These are the instructions in 05AB1E equivalent to "isdo"
y # push the current instruction
; # halve the instruction
è # modular index into the instruction string
.V # execute the instruction
D # duplicate the current value
₁^ # XOR with 256
0› # is this larger than 0?
* # multiply the result with the current value
# x*(x^256>0) maps negative numbers and 256 to 0
```
[Answer]
# [Rust](https://www.rust-lang.org/), 119 bytes
Closure with a single parameter of type `Iterator<Item = u8>` with ASCII bytes
```
|s|{let mut a=0;for c in s{a=match c{105=>a+1,100=>a-1,115=>a*a,111=>{println!("{}",a);a},_=>a};if a==-1||a==256{a=0}}}
```
[Try it online!](https://tio.run/##NY5BCoMwEEX3nmLqKmltSQqWQohXKUNacUCjmLhKcnY7Fvo38/gMn7duIe5772FC8kJCqoAzfiK8P/juKQxgIYecjmraIqBVpp9XcEAeQkI7YXQDuKRVazu86EYrxXBl0EdzRgZtu7Ss5OPoT6JOpW5QGizNix@KoZ5n7VXnzOfePnhVlVLMz@XvIer5SKCZiAJTfXMDrkHI24SLyC6zEwbYnlKaqlT7/gU "Rust – Try It Online") (with caller function)
Ungolfed version
```
|s|{
let mut a = 0;
for c in s {
a = match c {
105 => a + 1,
100 => a - 1,
115 => a * a,
111 => { println!("{}", a); a },
_ => a
};
if a == -1 || a == 256 { a = 0 }
}
}
```
[Answer]
# x86-16 machine code, ~~45~~ 43 bytes
Source-compatible with x86 and x86\_64.
Fails one test due to integer overflow, but instructions are given to switch it to 64-bit arithmetic in the demo.
```
00000000: 31 d2 ac 3c 64 72 23 74 0d 3c 69 74 0c 3c 6f 92 1..<dr#t.<it.<o.
00000010: 74 0a f7 e0 eb 07 4a eb 05 42 eb 02 ab 92 85 d2 t.....J..B......
00000020: 78 de 81 fa 00 01 74 d8 eb d8 c3 x.....t....
```
```
// "//" comments are solely for syntax highlighting
// sed -i -e 's#//#;#g' deadfish.asm
// nasm compatible
[bits 16]
[cpu 8086]
global deadfish
// Input:
// si: input, null terminated string
// di: output, uint16_t array
// Output:
//
// di: points past the last value in the array
deadfish:
.Lzero:
// Set accumulator to 0
xor dx, dx
.Lloop:
// Load byte
lodsb
// Check for null terminator and for 'd'
cmp al, 'd'
// Below means null terminator, return
jb .Lret
// equal means 'd'
je .Lop_d
// check for 'i'
cmp al, 'i'
je .Lop_i
// check for 'o'
cmp al, 'o'
// Since O and S both need AX instead of DX, xchg here.
xchg dx, ax
je .Lop_o
// assume 's'
.Lop_s:
// Square
mul ax
// Jump to the end of the o code to swap AX to DX.
jmp .Lnext_xchg
.Lop_d:
// Decrement
dec dx
jmp .Lnext
.Lop_i:
// Increment
inc dx
jmp .Lnext
.Lop_o:
// Output
// *di++ = ax
stosw
// Swap dx and ax again for o and s
.Lnext_xchg:
xchg dx, ax
.Lnext:
// Check for -1 (less than zero) and 256
// If equal, jump to the xor dx, dx conveniently placed before the loop
test dx, dx
js .Lzero
// Literally the only reason I am using 16-bit is this instruction :P
cmp dx, 256
je .Lzero
// Otherwise, jump to the top of the loop
jmp .Lloop
.Lret:
// Return
ret
```
The input is a null terminated string in `si`, and the output is stored to the `uint16_t` array in `di`.
`di` will point to the end of the array to indicate the length (C++ `<algorithm>` style)
[Try it online!](https://tio.run/##jVbhTiM3EP6/TzEKOiWBEMopjU7hikTv0N1JqK2AVpUoipy1N/Gd1155vJAU8ex0xpvNLiGIWpDdtWfGM9/MfHZaFIfzNH3a0zY1pVTwMcUgtTtNtmZsOE2SoyP4rDJtFQQHJSoYjw5nOoDwOixyFXTKC@lCpT/ACD9XnlVsmc@UxwGo4XwImfMQFgpGYQFBYYBUoBrSdplUGfx5dT4eJSVqO4dLNdcYlL9eFQp@gZJ8GI@m4YRtamvYDYGo8plRHjTaboDCq8K7VNG0BHRwr6KbrPHl7AqE0bQZDpPpVGA@nfYuO70E1mOIKsDl@Zfp578H77xcvlw44wWxTPqd/kmypwyq1z09HrOnb@7z2jbNLlbqLCL/VRSFssgI93KHwaz6BKYx7h5whXcgZhpmK0gdJU5LZVOGh14g8y6PkHsVSm/pUXkLkz8StaQXC51PneRZEPtSCZlpXPS2pjEMaAvLeVsID/voU3KzFSg57DIdhDG9p01oc@NmBmqbm5D3wLqgJuScRsog@NJaxtNZWH4YT8cjmJUBuMDSgC0tDgZFzgHyqnQK1zqHx@OkJXhNghXURxWykIvUOwS1LISVjKWi0qU6bXTk8kgsgaqUauCI0k1uF5yFyq/7hWL5qlDJ57ZibA3ZJJTKQJkprmwgK9ZRcWZ6mdQoTJLhxb/Ku6lcTjY6S9qXx7o@1k@SNM4VjZhxEvkpzABuPOrbzUqaF1CvdGV3M/99tnbqgqqgmVX1rCumcrcR3d0trneLu0Z8mS7mdTBnTTA7rbkWkNTVJSW3i90krmETeF4aaEw2ptYeDC94z0pLNlpSpS1Ud2hZ6oNKSzda1Ef/V8s1WhhcTM2Nl/p2UDtaOTZ5C5rKZiMWCfJlOWxcwRrBdSG9SEmt@P7n8Q7ct7Wa0Ljcklgrk1ZivpfkDvVMLn4obrzU5YUImggY7jXz@UK1pK9WxBs5/AVnv35jMv5GVG/p3xjWZVZqCX86OBg2WXZ38UndN6A2bCqNa7fpLxFC3V1Vbz31G/Zh9kwwCD6U7pyWEcveM@oKvp88RHPPSG5WZjfH7z/cEpM//PR48lJgn3ahxQ1FksIA2FolW3hq/KzXeYdweAqd9hIffluMqskSGTgBDR@BDNPLwUEfHjZhbswZU7K1XmlRz4loiAWIk/inv6/XGzw@8@Afyyg8Jgl9UtK07dUBRzA6WiOi66x1qznJkxrl1vR69q0Rtegst81hHh0qA/Y6v/1@fT6JnKy8d3xmU1kYZVYgy3ilOB7H6wTzJt0dwN0pn9H5NqxdqcywAWHmLl462EjqvFcpHUxM6StXVnW2EHYeq/TVuwqdlpGzmdqjr8PWkdsKnUHSrb/nyDgeqJ0miOhtGzat40zzyQNR6u2xbbb@pPw9/Qc) Uses GAS Intel syntax because I want to use libc with it, and uses macros for registers to make it possible to switch to 64-bit arithmetic.
[Answer]
# [J](http://jsoftware.com/), 64 58 bytes
```
g=:]e.&256 _1|]
i=:g>:
d=:g<:
s=:g*:
o=:1!:2&2
f=:'0'".@|.@,]
```
[Try it online!](https://tio.run/##hU7BasMwDL37K7QeYjYUE7tJ1oq5hH3AfmCEHZY01Q51QbkM@u@Zzdok7LIngYSk956@pmnw1PYmc1UNH/baKvY0HEh1sbyQklieSAVP9oFc5tTRky70xjRX02A7jb2M3myBCgUgF2/gnVCDznCTJsdGLvAdm/7zFEDnea7Vo0ok0MwiEjS8vRooVjOW7j/cWPlhISYtXuV8YbFEV2H9XGNZ7bZuf2OEBOHA0TN2iyLew6Ktf3P@jnm@O4fxxOdhtUoQ6fgvFu3SWne3XwynHw "J – Try It Online")
*-6 thanks to FrownyFrog!*
Note: -3 off TIO count for `f=:`
This stores each Deadfish command in a variable of the same name, followed by the -1/256 check. Then we just prepend 0, reverse, and eval.
Takes input with spaces between the letters.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 61 bytes
```
\bi()|#?\bd|^(#*)s
$#1*#$.2*$2
^#{256}\b
m}`^(#*)o
$.1¶$1
#
```
[Try it online!](https://tio.run/##K0otycxLNPyvqqHhnvA/JilTQ7NG2T4mKaUmTkNZS7OYS0XZUEtZRc9IS8WIK0652sjUrDYmiYsrtzYBrCCfS0XP8NA2FUMuZa7//zMzi4uL87lSQHRmcUo@F5RBCAAVgjRmIiGufBAozszPBJoBZAGNgoDi4pRMdJAPAA "Retina – Try It Online") Link includes test cases, although they can be a bit slow (I think `#?\bd` is the slow case, but I'm not sure). Explanation:
```
\bi()|#?\bd|^(#*)s
$#1*#$.2*$2
```
Handle the `i`, `d` and `s` cases by inserting a `#` (for the `i` case), deleting an optional `#` (for the `d` case, also handling a `d` of 0) or squaring the number of `#`s (for the `s` case).
```
^#{256}\b
```
But if the value is exactly 256, then set it back to 0 (assuming that there's another operation, otherwise the remaining `#`s are ignored anyway).
```
^(#*)o
$.1¶$1
```
Handle the `o` case by prepending a decimal copy of the current number of `#`s on a previous line.
```
m}`
```
Evaluate the above stages until there are no more letters to process; also turn on multiline matching for all of the stages.
```
#
```
Delete any remaining accumulated unary value.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
≔⁰θFS«F№⟦²⁵⁶±¹⟧θ≔⁰θ≡ιi≦⊕θd≦⊖θs≧X²θ⟦Iθ
```
[Try it online!](https://tio.run/##bc@xCsJADAbg2T5F6HQHFVTQQSepSwdFdBSH4xrbg3rXXlIdxGc/be2gIGRKvj8kulReO1WFsCYyhRWTBBq5ii7Og8hs3fKRvbGFkBIe0ahvp661LE6z@SKBHRaKUUzluctJ@N0yorthXYIwfVorQohNvIStqgeZWe3xipYxHzIflf@oDf5X9K0OpihZ7N0dfQKzweV4UW3FS9i/33hfnSpi0chzN3tGzxAMETnzVWF8q14 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰θ
```
Initialise the accumulator to 0.
```
FS«
```
Loop over the commands.
```
F№⟦²⁵⁶±¹⟧θ
```
If the list (256, -1) includes the accumulator...
```
≔⁰θ
```
... then set the accumulator to 0. (This is done before the operation because it's golfier, and doesn't change the result, since it still always happens between two operations, and whether it happens after the last operation isn't observable.)
```
≡ι
```
Switch on the current operation: ...
```
i≦⊕θ
```
... `i` means increment the accumulator; ...
```
d≦⊖θ
```
... `d` means decrement the accumulator; ...
```
s≧X²θ
```
... `s` means square the accumulator; ...
```
⟦Iθ
```
... otherwise print the accumulator on its own line.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 24 bytes
```
:4ị⁾’‘;⁾Ṅ²¤j“-,⁹¤i¬×Ʋ”VZ
```
[Try it online!](https://tio.run/##y0rNyan8/9/K5OHu7keN@x41zHzUMMMayHq4s@XQpkNLsh41zNHVedS489CSzENrDk8/tulRw9ywqP///0cbGpjqKBgaohGGQMKAXG4sAA "Jelly – Try It Online")
Interprets a Deadfish program given as a list of codepoints in a command-line argument, printing newlines between the numbers, then crashes with a TypeError.
Without the last two characters, it's a Deadfish to Jelly transpiler.
## Explanation
```
:4ị⁾’‘;⁾Ṅ²¤j“-,⁹¤i¬×Ʋ”VZ Main monadic link
:4 Integer divide by 4
ị Index into
⁾’‘;⁾Ṅ²¤ "’‘Ṅ²"
’ Decrement
‘ Increment
Ṅ Print with newline
² Square
j Join with separator
“-,⁹¤i¬×Ʋ” "-,⁹¤i¬×Ʋ"
-,⁹¤ [-1, 256]
i Find 1-based index
¬ Negate
× Multiply by the number
Ʋ Group this into one instruction
V Evaluate (implicitly starting with 0)
Z Zip — a number can't be zipped,
so this crashes the program in order to
suppress the implicit output
```
[Answer]
# [Arturo](https://github.com/arturo-lang/arturo), 80 bytes
```
$[p][r:0loop p'c[do[[r:r*r][print r][r:r+1][r:r-1]]\28-c/4if or? r<0r=256[r:0]]]
```
A function that takes an array of codepoints and prints numbers separated by newlines.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~26~~ 25 bytes
```
tGF₅0hx'o
S&≠256!ë→a□?←0c
```
[Try it online!](https://tio.run/##yygtzv6vkBus4aWkoGunoJSqqVH8qKlR89C2/yXubo@aWg0yKtTzuYLVHnUuMDI1Uzy8@lHbpMRH0xbaP2qbYJD8////zMzi4uJ8rhQQnVmcks8FZRACQIUgjZlIiCsfBIoz8zOBZgBZQKMyM8EECBQXp2SiA6AWAA "Husk – Try It Online")
### Explanation
The first line is the main program, the second line an helper function that computes the output of a Deadfish command that could be 'i', 'd' or 's'.
Let's start from the first line:
```
tGF₅0hx'o
x'o Split the string on each 'o'
h and discard the last part
(we don't care what happens after the last 'o')
G 0 Scan this list of strings using 0 as initial value
F₅ computing the result of each Deadfish subprogram
t Discard the first value (0)
```
What we are doing here is splitting the Deadfish code into the subprograms preceding each output 'o', and then computing the result of each subprogram.
The result of a subprogram is computed by folding the helper function over the commands: the fold will start with the value of the accumulator coming from the previous subprogram (initially 0), and will apply the helper function to the next command and the accumulator to generate the new value for the accumulator.
Lines in a Husk program are zero-indexed and modular: referring to line `₅` here is effectively the same as referring to line `₁`, but the number of times we "loop around" back to the first line determines how the called function should be modified (in order `argdup`,`flip`,`map`,`zip`,`hook`); in this case we loop around 2 times, so we `flip` the helper function, passing the command ('i','d',or 's') first, and the accumulator second.
We chain together the interpretations of the subprograms by scanning over the list of subprograms. A scan `G` is the same thing as a fold `F`, except it returns all partial results instead of only the final one. We explicitly set 0 as the initial value, but then the result of each subprogram will be passed as the accumulator to the next subprogram. The initial value is always part of the output for a scan, so we have to discard it at the end (`t`).
So, how does the helper function compute the result of a Deadfish command?
```
S&≠256!ë→a□?←0c Takes a character (one of "ids") and an accumulator,
returns the new value for the accumulator
c Convert the character to its codepoint value
!ë and use it to index into this list of four functions:
→ Increment
a Absolute value (dummy)
□ Square
?←0 If nonzero then decrement else return 0
S&≠256 Return the result if ≠256, else 0
```
The trick here is that ord(c)%4 will return a different value for each c in "ids" (respectively 1,0,3). List indexing in Husk is modular so by indexing with this value into the list of functions we will get the function we need. `a` is there only to pad the list to 4 elements (because otherwise 's' and 'd' would have the same value modulo 3).
We check for -1 by only decreasing the accumulator if its value is not 0, and we check for 256 explicitly after any command.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~83~~ 81 bytes
*Thanks to Dominic van Essen for shaving off 2 bytes...*
```
{for(;c=$++b%9;)printf c-3?(d=(x=c-6?c-1?d*d:--d:++d)<1?0:x==256?0:x)?f:f:+d"\n"}
```
This is pretty brute force, but it's ugly enough that I wanted to submit it. :) It's mostly abusing ternaries to save characters.
The input is code points separated by spaces as commandline arguments. The code converts them to modulo-9 to shorten the comparisons to the specific command values.
There's a minor trick on the `printf` line that might be worth highlighting.
```
printf c-3?..not-a-print-command..:d"\n"
```
prints the accumulator value when a `o` command is found.
The logic in the "truthy" part updates the accumulator, but always returns a value of `f`. Since that's a uninitialized variables, AWK picks a value based on the content where it's used. In this context it turns into a null string, so `printf` doesn't produce any output for non-`o` commands.
The code to update the accumulator is bundled into the print statement, so it's only called for `a`, `d`, `i`, and `s` commands. As result it doesn't have to check for `o`.
[Try it online!](https://tio.run/##SyzP/v@/Oi2/SMM62VZFWztJ1dJas6AoM68kTSFZ19heI8VWo8I2WdfMPlnX0D5FK8VKVzfFSls7RdPG0N7AqsLW1sjUDMTQtE@zSrPSTlGKyVOq/f/f0MBUwdAQGRsqIMSIYv8HAA "AWK – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 98 bytes
```
s->{int a=0;for(var c:s){if((c%=7)>5)System.out.println(a);a=c%5<3?1-c%5+a:a*a;a=a<0|a==256?0:a;}}
```
[Try it online!](https://tio.run/##hU/fa8IwEH73rziEQupmcRtu0Fpl@LwnH8XBLW3duTYpubQgrn97lhaZmwz25cddLt/3XXLAFqeH7MNRVWtj4eDPUWOpjIpGSUtaRZNkJEtkhhckBacRQN28lSSBLVofWk0ZVP5ObKwhtd/uAM2ew4EKsNaKmyo3C/mOZrtbQpE6ni5PpCxgOksKbUSLBmTM4YkKIWSQPoXLebg5ss2rSDc2qr2vLZXAMMFUBvPFw@pu6uMNxjhBX8PF7BPT9H7@uJrFmHSdS4bm3hwGd5uzjX@9C@C6QSHGAQeqvSBQ49tBGiZnTRGhlHltRV@NrF77Tz0bg0cRfnP@8H29IFD9GJ/Z3ahfnXNEzKxd1kfiTLtz8h88sRfSj@l0DyZN3sNn3opo2HowZ3QNL/kC "Java (JDK) – Try It Online")
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 30 bytes
```
ÝL}`7%5%›0s:_ΦD256â0>*
›
=
‹
²
```
[Try it online!](https://tio.run/##y8/INfr///Bcn9oEc1VT1UcNuwyKreLPLXMxMjU7vMjATosLKMRlCyR3ch3a9P9/ZnFxcX4mEgIA "Ohm v2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-F -E`, ~~96~~ ~~91~~ ~~90~~ ~~79~~ 74 bytes
*(+4 bytes for switches included)*
*Saved 5 bytes by using a built-in variable that defaults to 0 (`$-` / `$FORMAT_LINES_LEFT`) instead of $a*
*Saved 1 byte by using print and `$/` instead of `CORE::say`*
*Saved 11 bytes by using `-F` and `-E` switches*
*Saved 4 bytes by (ab)using regex match return value coercion. Saved 0 bytes but improved readability by changing $- to $% (`$FORMAT_PAGE_NUMBER`)*
```
for(@F){$%+=/i/;$%-=/d/;$%*=$%if/s/;say$%if/o/;$%=0if$%=~/^(-1|256)$/}
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0jDwU2zWkVV21Y/U99aRVXXVj8FRGvZqqhmpukX61sXJ1aCmfkgYVuDzDQgWacfp6FrWGNkaqapol/7/39mcXFxfiYS@pdfUJKZn1f8X9dNQdfXVM/A0AAA "Perl 5 – Try It Online")
More-readable version:
```
for (@F) {
$% += /i/;
$% -= /d/;
$% *= $% if /s/;
say($%) if /o/;
$% = 0 if $% =~ /^(-1|256)$/;
}
```
[Answer]
# Knight, 57 bytes
```
;=a 0W=cP I?c"o"Oa=a*=a I?c"d"-a 1I?c"i"+1a^a 2!|?256a>0a
```
Takes in each character on a separate input line.
## Explanation
Here's the code with generous whitespace and comments added:
```
;=a 0 #set a to 0
W=cP # while the next input character `c` is not null:
I?c"o" # if c is "o":
Oa # output a
=a # else...
*=a # set a to the following:
I?c"d" # (if a is "d":
-a 1 # a-1
I?c"i" # else if a is "i":
+1a # a+1
^a 2 # else a^2)
!|?256a>0a # multiply a by (not (a is 256) or (0>a)), which is 1 when a is within bounds and 0 otherwise
```
An earlier version where I tried to use some more clever tricks which ended up being longer (66 bytes):
```
;=a 0W =cP I?c"o"Oa=a*=aE S G"^2-1+1"/%Ac 23 3 2 1 0"a "!|?256a>0a
```
[Answer]
# PHP, 136 bytes
```
<?php $w=0;foreach(str_split($argv[1])as$v){if($v=='o'){echo$w.' ';}else{$w=$v=='s'?$w**2:($v=='i'?++$w:--$w);}if($w==256||$w<0){$w=0;}}
```
Example explained:
```
$w=0; #declare w var, is accumulator
foreach(str_split($argv[1])as$v){ # for each char of first CLI argument
if($v=='o'){ #if output
echo$w.' '; #output w
}else{ #otherwise
$w= #set w to
$v=='s'? #if input is s
$w**2 #squared
:($v=='i'? #otherwise if incremented
++$w: #add one
--$w);} #otherwise subtract one
if($w==256||$w<0){$w=0;}} #if -1 or 256 set 0
```
PHP is annoying for this.
Is run `php deadfish.php <program>`
Note: run on CLI so no online example.
[Answer]
# [Red](http://www.red-lang.org), 106 bytes
```
func[s][a: 0 parse s[any[(if a xor 256 < 1[a: 0])"i"(a: a + 1)|"d"(a: a - 1)|"s"(a: a * a)|"o"(print a)]]]
```
[Try it online!](https://tio.run/##hY/BCsIwEETv/YphT61SsIIeRPwIr2EPwTS4l6ZkFRT895rUWsWLjxz2hWFgYuuGY@sMF36HwV@7k1E2docVehu1hRrb3U0pHha3ELHebLFHM0a4IqEyXRZLNNWD3GT1aDrZAjZZoLKP0l2SMPPgQ2zt6YwepkCCRFQ10EtcNlH39kn/McdzlXy96T9kVIKkvnTN5SKEz51RdfLL3EIFm3GL6UH1gcDwachrHtUJ4pwcng "Red – Try It Online")
Pretty simple solution :
```
f: func[s][
a: 0
parse s[
any[
(if a xor 256 < 1[a: 0])
"i"(a: a + 1)
|"d"(a: a - 1)
|"s"(a: a * a)
|"o"(print a)
]
]
]
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 68 bytes
```
switch -r($args){i{$a++}d{$a--}s{$a*=$a}o{+$a}.{$a*=$a-notin-1,256}}
```
[Try it online!](https://tio.run/##hU7bTsMwDH3vV1hTYC1LEClbGZomTdoHgOARIVTajAW1y6g7DSnk24uzXkC84Fixj3187L05qgq3qigatlnaBo@6zrYgqpCl1RtGVluWTiYupyCEQwoXS5Y6Yyf0X3ZQ7Eytd0LyeJY417hgFQYBD8daI6IZc7iKPMw91pj7SjyfRz2FSv/Zj8hJUv9y6kg@pdU8uUn4dDa/jm9PTOMNtdG0gzKvwPsnuUxa767Qejxk3hBz/de8xFTKuFVvLwoi@IIzsAEAy0xZprscOTD1uVdZrXJYAnvxvUrhoagJnrMNrHomdZ7ucX3A2pR3r@808ryy8HjIMoVI5FE3NwKhPgj1sqMFPPSCA2cB607Wbx1yF7jmGw "PowerShell – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 59 bytes
```
FNz=T%CN4IqN"o"Z=tT)IqT1=hZ)IqT0=tZ)IqT3=*ZZ)I}hZ[0 257)=Z0
```
[Try it online!](https://tio.run/##K6gsyfj/382vyjZE1dnPxLPQTylfKcq2JETTszDE0DYjCkQb2JaAaWNbrSggozYjKtpAwcjUXNM2yuD//8zi4uL8TCQEAA "Pyth – Try It Online")
Bit out of practice. :)
] |
[Question]
[
Consider a question written in plain English whose answer involves two reasonably accurate (but potentially clever) words or phrases that can be separated by the word 'and':
>
> **Q:** What are the two sides of a coin? **A:** heads and tails
>
>
> **Q:** What are the best ways to travel? **A:** airplane and jetpack
>
>
> **Q:** Why is a raven like a writing desk? **A:** because there is a 'b' in both and an 'n' in neither
>
>
>
# Goal
Write a program which, when run normally, outputs such a question.
When every other character is removed from the program starting with the *second* character and the result is re-run, the output should be whatever is to the *left* of the 'and' in the answer.
When every other character is removed from the program starting with the *first* character and the result is re-run, the output should be whatever is to the *right* of the 'and' in the answer.
(The 'and' itself is not output.)
# Example
If the program is
```
A1B2C3D4E5F6G7H8I9
```
and its output is
```
What are the two sides of a coin?
```
Then the output of `ABCDEFGHI`should be `heads`, and the output of `123456789` should be `tails`.
# Rules about questions and answers
* You may use my example questions but I encourage you to make up your own.
* The question and the two answer parts:
+ must all be distinct
+ should be common grammatical meaningful English
+ may only contain [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) (hex 20 to 7E)
* Ideally the question will be capitalized and punctuated (but the answers do not need to be).
* The question must be at least 30 character long and have [entropy](http://www.shannonentropy.netmark.pl/) above or equal to 3.5. (Type in string, hit *calculate*, look for last *H(X)*.)
* The two answer parts (not including the `[space]and[space]` between them) must each have at least 5 characters with entropy above or equal to 2.
* The word 'and' may appear in either answer part.
# Rules about code
* None of the 3 code snippets may:
+ contain comments or anything else traditionally ignored by the compiler/interpreter (don't worry about putting an extra semicolon or two in, but if you think it's a comment it probably is)
+ exit the program in mid-execution
* The code may contain any characters, including Unicode and non-printable ASCII.
* It may have an odd or even number of characters.
* Output goes to stdout or a file or whatever seems reasonable. There is no input.
# Scoring
Since I wan't to encourage golfed answers but I want to encourage clever answers even more, the scoring will be something in between code-golf and popularity contest:
Score = `(upvotes - downvotes) - floor((bytes in code that outputs question) / 3)`
The highest score wins.
(Use <http://mothereff.in/byte-counter> as a byte counter.)
[Answer]
# Javascript (148 bytes)
Creates some nonsense literals, with the side effect of creating an alert\* for the question. (the splits doing similar, but creating alerts\* for each of the answers).
```
"';"+alert( 'What is the ideal breakfast???')+/ " ;apl=e"rbta(k"esnc"r.armebplleadc ee g g s(" ) + " \/)k;e"/+ ",t'hceo 'c)a;kye= ailse rat (lpi)e "
```
Splits:
```
";+lr('hti h da rafs??)/";p="baken".replace ( /ke/ ,'co');y=alert(p)
```
and
```
'"aet Wa steielbekat?'+ alert("scrambled eggs")+"\);"+"the cake is a lie"
```
Question: `What is the ideal breakfast???`
Answers: `bacon` and `scrambled eggs`
[Answer]
## Brainfuck (437 characters)
I have to confess that this is my first brainfuck program that actually does something meaningful. The program is highly optimized for low memory systems since it uses only 4 memory locations.
Question: `What are the two main groups of trees?`
Answers: `conifers` and `broadleafs`
```
-+[[++++++++++++++++++++++[+>++++++[+>++++++++++++<>-+]+>+-+.++++++<+<+-+]+>+++++.+>++.+-..------.-<--..-+-+-+..->.-+-+-+.+<+++.+-+-+-+-+.++++.+++.+<.+>-+++-+++-+++-++.->]]++-+[[+-+-[[+++++++++++++++[>++>+++++>+++++++<<<-]>-->>---<++.+++++++++++++++++.-------.>.<<.>.>--.<++++.<.>>++.<+++.---.<.>>.+++.<++++++++++.<.>--.------------.++++++++.+++++.<.>-------.>-----.<++++++++.>+++.<+.>--.<<.>-.---------.<.>>+.--.<-..>+.<<[<++>-]<-.<]]]]
```
**Main loop**
The program consists of main loop (which isn't really a loop since all [ ] -blocks are executed only once) and two sections.
```
-+[[ // let answers enter
* SNIP interleaved answer sections *
]]
++-+[[ // let odd answer and question enter
+-+-[[ // let question enter
* SNIP question section *
]]
]]
```
If you want to test sections independently, you must take the main loop into account. Location 0 contains -1 in even answer, 1 in odd answer and 2 in question section.
**Answer section**
Even answer (odd instructions removed):
```
// location 0 contains minus 1 from main
// set location 1 = 10 * 10 minus 1 = 99 (c)
+++++++++++[>++++++++++<-]>-. // c
++++++++++++.-. // on
-----.---. // if
-.+++++++++++++.+. // ers
< // goto 0 (which contains 0)
+-+-+-+-+- // padding to match length of odd answer
```
Odd answer (even instructions removed):
```
// location 0 contains 1 from main
// set location 1 = 16 * 6 plus 2 = 98 (b) location used for characters below 'l'
// set location 2 = 16 * 7 plus 2 = 114 (r) location used for 'l' and above
+++++++++++++++[>++++++>+++++++<<-]>++.>++. // br
---.< // o
-.+++. // ad
>---.< // l
+.----.+++++. // eaf
>+++++++. // s
> // goto 3 (which contains 0)
```
**Question section**
I decided to store space to separate location because its value differs drastically from other characters. This allows space to be printed simply with `<.>`.
```
// location 0 contains 2 from main
// set location 1 = 17 * 2 minus 2 = 32 (space)
// set location 2 = 17 * 5 plus 2 = 87 (W) location used for characters below 'r'
// set location 3 = 17 * 7 minus 3 = 116 (t) location used for 'r' and above
+++++++++++++++[>++>+++++>+++++++<<<-]>-->>---<++. // W
+++++++++++++++++. // h
-------.>.< // at
<.> // (space)
.>--.<++++. // are
<.> // (space)
>++.<+++.---. // the
<.> // (space)
>.+++.<++++++++++. // two
<.> // (space)
--.------------. // ma
++++++++.+++++. // in
<.> // (space)
-------.>-----. // gr
<++++++++.>+++. // ou
<+.>--.< // ps
<.> // (space)
-.---------. // of
<.> // (space)
>+.--.<-..>+. // trees
<<[<++>-]<-.< // ? (value_of_space * 2 minus 1)
```
**Final update**
In my final update I optimized multiplications so that minimum instructions are used. Also including 'l' to second character group in odd answer section proved to be huge improvement. Single character savings in odd answer basicly meant two characters from whole program, since it also reduces padding from the even answer. I also removed couple of unnecessary instructions from here and there and I don't think I can optimize the code any further.
[Answer]
# Batch - 84
Quite proud of this one
Full program: What are two sides of a coin? (console)
```
echo What are two sides of a coin? 2>>xx 2>>cc&&eecchhoo hteaaidlss 2>>xx 2>>cc
```
Evens only: heads ('c' file)
```
eh htaetosdso on 2>x >c&echo heads 2>x >c
```
Odds only: tails ('x' file)
```
coWa r w ie faci? >x 2>c&echo tails >x 2>c
```
Works by redirecting the error output to a file in both cases.
[Answer]
# Python - ~~104~~ 96 (golfed: 76)
My solution is rather simple (and somehow readable):
```
"";print 'What is the color of a zebra?' ;""
paraianat= "' b l a c k '"
aparaianat="'w h i t e'"
```
Output:
```
What is the color of a zebra?
black
white
```
Honestly, I found the idea for the first line in bitpwner's answer.
---
**Even more readable alternative: - ~~113~~ ~~105~~ 97**
```
"";print 'What is the color of a zebra?' ;""
"p r i n t ' b l a c k '" ;"p r i n t ' w h i t e '"
```
---
**Even shorter alternative: - ~~86~~ 76**
```
"";print'What is the color of a zebra?';""
"""";;pprriinntt''bwlhaictke''"""
```
[Answer]
## [Rebmu](https://github.com/hostilefork/rebmu): 79 chars OR (37 + length(p1) + 2 \* max(length(p2), length(p3)))
First I'll give a 79 character solution that asks **Which languages must you learn?** (entropy 4.0, 30 letters not including `?`) and offers you the suggestions of **[Rebol and [Red]](http://chat.stackoverflow.com/rooms/291/rebol-and-red)**:
```
DD 11 DD :do dd {dd {p{Which languages must you learn?}qt}} pp{{[RReebdo]l}}
```
A unique tactic available here that isn't in other languages comes from taking advantage of the fact that curly braces are an asymmetric string delimiter, that can nest legally:
```
my-string: {"It's cool," said {Dr. Rebmu}, "for MANY reasons--like less escaping."}
```
That let me produce a generalized solution, that can work effortlessly on any program that doesn't use escape sequences. The 79 character version was simple enough to shortcut, but to properly contain arbitrary program source for programs p2 and p3 you'd need the full template. Had we used that, it would have been 87 characters:
```
DD 11 DD :do dd {dd {p{Which languages must you learn?}qt}} ddoo{{pp{{[RReebdo]l}}}}
```
The pattern for using this general form is that if you have three source texts of sequential characters of variable lengths (let's use an example like `AAA`, `BBBBB`, `CCCCCCC`) you can encode them as something along the lines of:
```
DD 11 DD :do dd {dd {AAAqt}} ddoo{{BCBCBCBCBC C C}}
```
*(Note: Although this pattern won't work without tweaking on programs that use escape characters, this is not a fatal flaw. Getting an unmatched left brace in a string delimited by braces requires something like `{Foo ^{ Bar}`...but you could easily rewrite that using the alternative string notation `"Foo { Bar"`, and combined cases can be managed with gluing together a mixture of unescaped strings.)*
So...how about an example? Once the general form was available, this 573 character program was assembled in only a couple of minutes from 3 prior code golf solutions:
>
> DD 11 DD :do dd {dd {rJ N 0% rN Wa1m2j S{ \x/ }D00 Hc&[u[Ze?Wa Qs~rpKw[isEL00c[skQd2k][eEV?kQ[tlQ]]pcSeg--b00[eZ 1 5]3]prRJ[si~dSPscSqFHs]eZ 1[s+dCa+wM2cNO]]]Va|[mpAp2j]prSI~w{*}Ls2w Wl h01tiVsb01n -1 chRVs{*}hLceVn01qt}} ddoo{{BrdSz [fcebC[sn[{N sbeo[tIt0l1eV}0e5gXN1 01L{5s0}C{1}0{0 Do5f0 0bMe1e0r0}0]]]tMw9C9 Numz Jl[paN+[KperlCJBn[[ba sWS{B noJn Nt0h0e] jw]aJlnl]}aCd{K,j } b P { . } l f E Z - - n [ N m { G o t o t h e s t o r e a n d b u y s o m e m o r e } ] { T a k e o n e d o w n a n d p a s s i t a r o u n d } c B w P l f ] ] }}
>
>
>
* If you don't modify the program, it is the [Hourglass Solution](https://stackoverflow.com/a/3110684/211160).
* If you take only the odd characters and run it, then it will [print out the 99 bottles of beer poem](https://codegolf.stackexchange.com/questions/2/99-bottles-of-beer/413#413)
* Only the even characters will do a little [Roman Numeral Conversion](https://github.com/hostilefork/rebmu/blob/master/examples/roman.rebmu) for you.
If anyone wants to try writing that program in their language of choice, and thinks they can beat 573, let me know. I will bounty you a heavy amount of reputation if you do--assuming your language of choice is not Rebmu, because I know those programs aren't minimal. :-)
That "wasteful" spacing you get at the end is what happens when p2 and p3 are of imbalanced lengths. But all 3 programs are different sizes in this case so there isn't a particular good pairing to pick for p2/p3. (I picked these because there was no external data as input, such as a maze or whatever, not that they were of similar lengths. While I could have written new programs that were more optimal, I've spent enough time and the point was you *don't* have to write new programs...)
### How it works
*(Note: I started with a more "creative" approach that was not as streamlined but more interesting-looking. I moved it [to an entry on my blog](http://blog.hostilefork.com/rebol-red-and-dichotomies) as describing this approach is already long.)*
A key here is the "eval code as a string" trickery like some other entries, it just has the trump card of the asymmetric string delimiter. I'll start by explaining the workings of the 80 character case.
Here's the "whole" program, adjusting the whitespace for this case's readability:
```
DD 11 ; assign 11 to dd (about to overwrite again)
DD :do ; make dd a synonym for DO (a.k.a. "eval")
; eval a string as source code that ends with QUIT (QT)
dd {dd {p{Which languages must you learn?}qt}}
; we'll never get here, but whatever's here must be legally parseable
pp{{[RReebdo]l}}
```
Here we wind up setting DD to a synonym for DO (a.k.a. "eval"). But the trick is that when the halved programs run, they wind up running code whose only effect is to define D to the harmless literal 1.
Here's what the odd-chars code makes, whitespace again adjusted:
```
D 1 ; assign 1 to d
D d ; assign d to itself, so it's still 1
d ; evaluates to integer, no side effect
{d pWihlnugsms o er?q} ; string literal, no side effect
p {Rebol} ; print "Rebol"
```
And here's the even-chars code:
```
D 1 ; assign 1 to d
D:od ; URL-literal (foo:...), no side effect
d ; evaluates to integer, no side effect
{{hc agae utyulan}t} ; string literal (well-formed!), no side effect
p {[Red]} ; print "[Red]"
```
It's actually the case that for the non-halved program, the `dd {dd {(arbitrary code)qt}}` will execute whatever code you want. However, there are two calls to evaluate instead of just one. That's because while the nested braces work great in the interleaved code, they mess up the eval behavior of DO. Because:
```
do {{print "Hello"}}
```
Will load the string as a program, but that program winds up being just the string constant `{print "Hello"}`. Thus the trick I use here is to take my DD (holding the same function value as DO) and run it twice. The halvers chew at the different parts of the string but they don't chew both if the even/oddness is correct for the content, and because what's left outside the string after halving is just the integral constant `d` they're harmless.
With this pattern there's no challenge in writing the program behavior when it's not cut in half--you can put in anything as long as the character length of the code is even (odd if you're counting the QT, which is QUIT). If you need to get the even number from an odd one, throw in a space *(so there's actually a +1 in my formula above on p1 for odd program lengths of p1)*. The trick would seem to write that interleaved code afterwards, which must pass the parser if it *isn't* halved. (It won't be run because of the QT, but it has to be LOADable before it will be executed.)
This case is trivial; `pp` loads fine as a symbol even though it's undefined, and is split into `p` for print in each half program. But we can do another trick just by using a string literal again. The halved programs still have DO defined normally, so we could also have just said:
```
ddoo{{pp{{[RReebdo]l}}}}
```
By having the only part picked up by the parser in the whole case be the symbolic word [`ddoo`](https://www.youtube.com/watch?v=21UP0frYg-E) and a string literal, we can then interleave any two programs we wish inside that string literal and not anger the parser. The halved versions will just say:
```
do{p{Rebol}}
```
..and...
```
do{p{[Red]}}
```
As I say, this part looks familiar to other solutions that treat programs as strings and eval them. But in the competition's case, when the programs you're packing contain nested strings, that throws in wrenches for them. Here the only things that will get you in trouble are use of escaping via carets (`^`)...which can be easily worked around.
---
*(Small 'cheating' note: I added QT for "QUIT" in response to this problem. Actually, I had purposefully removed the abbreviation for quit before...because somehow I thought it was only good for console use and just taking up the two-letter space if it wasn't in a REPL. I'm adding it because I see I was wrong, not adding it for this case in particular. Nevertheless, prior to that change it would have been 2 characters longer. Also, when I first posted the solution there was a bug in Rebmu that kept it from actually working even though it should have...now it works.)*
[Answer]
# Perl 186 139 135
```
"";print'What are the best things in life?';""&&pprriinntt("'hceraurs ht hyeo ulra meennetmaiteiso'n s o f t h e i r w o m e n ")
```
What are the best things in life?
```
"pitWa r h ettig nlf?;"&print('crush your enemies' )
```
crush your enemies
```
";rn'htaetebs hnsi ie'"&print"hear the lamentations of their women"
```
hear the lamentations of their women
Using less lengthy answers:
# Perl 79 72
```
"";print'What are my preferred weapons?';""&&pprriinntt("'smwaocredss'")
```
`What are my preferred weapons?` (30Byte, H(X)=3.76) `swords` (H(X)=2,25) and `maces` (H(X)=2,32)
[Answer]
# Python - ~~139~~ 103
```
"";print'What are the ingredients for success?';""; ";" ;id=='"RUaniincboorwnss'";;pprriinntt id++"'"'
```
`What are the ingredients for success?` -> `Unicorns` and `Rainbows`
**Test:**
```
c="\"\";print\'What are the ingredients for success?\';\"\"; \";\" ;id==\'\"RUaniincboorwnss\'\";;pprriinntt id++\"\'\"\'"
exec c # What are the ingredients for success?
exec c[::2] # Unicorns
exec c[1::2] # Rainbows
print
print c[::2] # ";rn'htaeteigeinsfrsces'";"";d="Unicorns";print d+''
print c[1::2] # "pitWa r h nrdet o ucs?;" ; i='Rainbows';print i+""
```
**Old version:**
```
# What are the ingredients for success?
"";print(('What are the ingredients for success?'));""; ";" ;"pHrEiRnEt (C'OUMnEiSc oZrAnLsG'O)"; ";" ; "p,r iTnOtN(Y' RTaHiEn bPoOwNsY'.)"
# Unicorns
";rn('htaeteigeinsfrsces')";"";print('Unicorns');"";", TONY THE PONY."
# Rainbows
"pit(Wa r h nrdet o ucs?);" ; "HERE COMES ZALGO" ; print('Rainbows')
```
[Answer]
# Haskell, 117
Having to work with Haskell's functional paradigm means that everything has to be assigned to a variable or commented out with line `--` or block `{- -}` comments; having nonsense functions run without assignment is out. So, to keep myself sane, I kept the question and answers as short as the rules allow.
Question: What can I not have enough of?
```
main=putStrLn{---}"What can I not have enough of?"{- }
=u"Scrank=e"sS"h
omeasi"n
=mpauitnS=tpru taSntprt tmLi
-----}
```
"Shoes" and "cakes":
```
mi=uSrn--"htcnInthv nuho?{
uSrn="Shoes"
main=putStr mi
--}
```
```
anpttL{-}Wa a o aeeog f"-}="cakes"
main=putStr anpttL
---
```
N.B. The appearance of `crank` under "What can I not have enough of?" should not be viewed as meaningful.
[Answer]
## Lisp (76 characters)
31-character question, 6 characters in each answer ⟹ length - payload = 33
```
'(: (pprriinncc''fmuacghesnitaa))':(princ "What is your favorite pink hue?")
```
I wanted to use “What is your favorite color?”, but even stretched to British spelling, it only just reached the 30-character minimum for the question length, and I needed an odd-length question to balance the double quotes.
They say Common Lisp is verbose, but you wouldn't think so going by this one-liner. It's not even very obfuscated, you only need to insert a bit of whitespace to see what's getting quoted and what's getting executed.
Many Lisp implementations will shout out the colors, because they warp symbols to uppercase. If that bothers you, change `''fmuacghesnitaa` to `""fmuacghesnitaa""`.
[Answer]
## STATA 295
Question: What are the best desserts to bake right now?
Answer: brownies and cookies.
Explanation:
Commands in STATA are delimited by new lines.
While "//" is a comment in STATA, "///" tells the compiler to continue to the next line and include its contents in the current command.
```
g a = "g q /b/a/"
g l= "b = ""b r o w n i e s "
g c = "g /b/a/"
g lpo= "d = ""c o o k i e s "
g e = "c a p " /////
+ "d i ""$ b "
g f = "c a p " /////
+ "d i ""$ d "
g g = "c a p " /////
+ "c a p / / / "+ "/ / /"
di "What are the best desserts to bake right now?"
```
"brownies"
```
g a=" ba"
gl b="brownies"
g ///
p=" "
g e=" " //
di "$b"
cap ///
+" "
g g=" " //
cap /// +" "
i"htaetebs esrst aergtnw"
```
"cookies"
```
g q ///
=" "
g c=" ba"
glo d="cookies"
cap ///
+" "
g f=" " //
di "$d"
cap ///
+ " " ///
d Wa r h etdset obk ih o?
```
[Answer]
## Ksh (82 characters)
35-character question, 5 characters in each answer ⟹ length - payload = 37
```
ec=\'o'(;)eehc(h)oe cChroi m$e1;; '\'
echo What\'s the country\'s worst problem?
```
I abuse the function definition syntax beyond POSIX. Dash and bash can't take it but ksh (public domain or ATT) can.
Nothing remarkable going on, just a bit of echo. Waste not, want not.
[Answer]
# PowerShell 88
```
"" > $x;{What is my favorite equipment?};"" >> ${x}
${XsXwXoXrXdX};;;${XsXhXiXeXlXdX}
```
**What is my favorite equipment?** (30 chars, H(X) = 4.0314)
```
" x{hti yfvrt qimn?;"> {}
{sword};$XXXXXXX
```
**sword** (5 chars, H(X) = 2.32193)
```
">$;Wa sm aoieeupet}" >$x
$XXXXXX;;{shield}
```
**shield** (5 chars, H(X) = 2.58496)
On the full program it redirects empty strings to a nonexistent variable `${x}` (the quotes for those empty strings are used to form a nonsense string that gets redirected either to an empty block `{}` or nonexistent variable `$x` on the even/odd versions), then prints the question and declares 2 unused variables (which are printed and placed next to another unused variable `$XXXXXX` or `$XXXXXXX` on the different cases).
[Answer]
# GolfScript, 51 bytes
```
"Which are the sides of a coin? ".;""thaeialdss""
```
### Output
```
Which are the sides of a coin?
```
### How it works
`.;` duplicates the string and deletes the copy. `""` pushes an empty string. `thaeialdss` is undefined, so it does nothing.
## Odd chars
```
"hc r h ie faci?";"heads"
```
### Output
```
heads
```
### How it works
`;` deletes the first string from the stack.
## Even chars
```
Wihaetesdso on ."tails"
```
### Output
```
tails
```
### How it works
`Wihaetesdso` and `on` are noops. `.` duplicates the empty string on the stack.
] |
[Question]
[
### Background
[Adler-32](https://en.wikipedia.org/wiki/Adler-32) is a 32-bit checksum invented by Mark Adler in 1995 which is part of the widely used zlib library (also developed by Adler). Adler-32 is not as reliable as a 32-bit [cyclic redundancy check](https://en.wikipedia.org/wiki/Cyclic_redundancy_check), but – at least in software – it is much faster and easier to implement.
### Definition
Let **B = [b1, ⋯, bn]** be a byte array.
The Adler-32 checksum of **B** is defined as the result of **low + 65536 × high**, where:
* **low := ((1 + b1 + ⋯ + bn) mod 65521)**
* **high := (((1 + b1) + (1 + b1 + b2) + ⋯ (1 + b1 + ⋯ + bn)) mod 65521)**
### Task
Given a byte array as input, compute and return its Adler-32 checksum, abiding to the following.
* You can take the input as an array of bytes or integers, or as a string.
In both cases, only bytes corresponding to printable ASCII characters will occur in the input.
You may assume that the length of the input will satisfy **0 < length ≤ 4096**.
* If you choose to print the output, you may use any positive base up to and including 256.
If you choose unary, make sure interpreter can handle up to **232 - 983056** bytes of output on a machine with 16 GiB of RAM.
* Built-ins that compute the Adler-32 checksum are forbidden.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
### Test cases
```
String: "Eagles are great!"
Byte array: [69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
Checksum: 918816254
String: "Programming Puzzles & Code Golf"
Byte array: [80, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 80, 117, 122, 122, 108, 101, 115, 32, 38, 32, 67, 111, 100, 101, 32, 71, 111, 108, 102]
Checksum: 3133147946
String: "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
Byte array: [126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126]
Checksum: 68095937
String: <1040 question marks>
Byte array: <1040 copies of 63>
Checksum: 2181038080
```
[Answer]
# Mathematica, 46 bytes
```
{1,4^8}.Fold[##+{0,#&@@#}&,{1,0},#]~Mod~65521&
```
An anonymous function that takes an integer array and returns the Adler-32, with some improvements from miles and Martin (see comments).
miles' is also **46 bytes**, but faster:
```
{1,4^8}.{Tr@#+1,Tr[Accumulate@#+1]}~Mod~65521&
```
[Answer]
# Julia, ~~73~~ 46 bytes
```
x->[sum(x)+1;sum(cumsum(x)+1)]%65521⋅[1;4^8]
```
This is an anonymous function that accepts an array and returns an integer. To call it, assign it to a variable.
We combine `sum(x) + 1` and `sum(cumsum(x) + 1)` into an array, where `x` is the input array, and take each modulo 65521. We then compute the dot product with 1 and 48, which gives us `(sum(x) + 1) + 4^8 * sum(cumsum(x) + 1)`, which is exactly the Adler-32 formula.
[Try it online!](http://julia.tryitonline.net/#code=Zj14LT5bc3VtKHgpKzE7c3VtKGN1bXN1bSh4KSsxKV0lNjU1MjHii4VbMTs0XjhdCgpmb3IgY2FzZSBpbiBbKCJFYWdsZXMgYXJlIGdyZWF0ISIsIDkxODgxNjI1NCksCiAgICAgICAgICAgICAoIlByb2dyYW1taW5nIFB1enpsZXMgJiBDb2RlIEdvbGYiLCAzMTMzMTQ3OTQ2KSwKICAgICAgICAgICAgICgifn5-fn5-fn5-fn5-fn5-fn5-fn5-fn5-fn5-fn5-fn4iLCA2ODA5NTkzNyksCiAgICAgICAgICAgICAoIj8iXjEwNDAsIDIxODEwMzgwODApXQogICAgYSA9IG1hcChJbnQsIFtjYXNlWzFdLi4uXSkKICAgIHByaW50bG4oZihhKSA9PSBjYXNlWzJdKQplbmQ&input=) (Includes all test cases)
Saved 27 bytes thanks to Sp3000 and Dennis!
[Answer]
# x86-64 machine code function: ~~33~~ 32 bytes (or ~~31~~ 30 bytes with an `int[]` input instead of `char[]`)
# x86-32 machine code function: 31 bytes
**As a GNU C inline-asm code fragment: saves ~~2B~~ 1B (just the `ret` insn).**
## Commented source and test driver [on github](https://github.com/pcordes/adler32-golf)
The 64bit version is callable directly from C with the standard System V x86-64 ABI (using 2 dummy args to get args in the regs I want). Custom calling conventions are not uncommon for asm code, so this is a bonus feature.
32bit machine code saves 1B, because merging the high and low halves with `push16/push16 => pop32` only works in 32bit mode. A 32bit function would need a custom calling convention. We shouldn't hold that against it, but calling from C needs a wrapper function.
After processing 4096 `~` (ASCII 126) bytes, `high = 0x3f040000, low = 0x7e001`. So `high`'s most-significant bit isn't set yet. My code takes advantage of this, sign-extending `eax` into `edx:eax` with `cdq` as a way of zeroing `edx`.
```
# See the NASM source below
0000000000401120 <golfed_adler32_amd64>:
401120: 31 c0 xor eax,eax
401122: 99 cdq
401123: 8d 7a 01 lea edi,[rdx+0x1]
0000000000401126 <golfed_adler32_amd64.byteloop>:
401126: ac lods al,BYTE PTR ds:[rsi]
401127: 01 c7 add edi,eax
401129: 01 fa add edx,edi
40112b: e2 f9 loop 401126 <golfed_adler32_amd64.byteloop>
000000000040112d <golfed_adler32_amd64.end>:
40112d: 66 b9 f1 ff mov cx,0xfff1
401131: 92 xchg edx,eax
401132: 99 cdq
401133: f7 f1 div ecx
401135: 52 push rdx
401136: 97 xchg edi,eax
401137: 99 cdq
401138: f7 f1 div ecx
40113a: 66 52 push dx # this is the diff from last version: evil push/pop instead of shift/add
40113c: 58 pop rax
40113d: 66 5a pop dx
40113f: c3 ret
0000000000401140 <golfed_adler32_amd64_end>:
```
`0x40 - 0x20` = 32 bytes.
---
## Commented NASM source:
tricks:
* `xchg eax, r32` is one byte; cheaper than mov. 8086 needed data in ax for a lot more stuff than >= 386, so they decided to spend a lot of opcode-space on the now-rarely-used `xchg ax, r16`.
* Mixing push64 and push16 for merging high and low into a single register saves reg-reg data movement instructions around two `div`s. The 32bit version of this trick works even better: `push16 / push16 / pop32` is only 5B total, not 6.
Since we push/pop, this [isn't safe for inline asm in the SysV amd64 ABI (with a red zone)](https://stackoverflow.com/questions/34520013/using-base-pointer-register-in-c-inline-asm/34522750#34522750).
```
golfed_adler32_amd64_v3: ; (int dummy, const char *buf, int dummy, uint64_t len)
;; args: len in rcx, const char *buf in rsi
;; Without dummy args, (unsigned len, const char *buf), mov ecx, edi is the obvious solution, costing 2 bytes
xor eax,eax ; scratch reg for loading bytes
cdq ; edx: high=0
lea edi, [rdx+1] ; edi: low=1
;jrcxz .end ; We don't handle len=0. unlike rep, loop only checks rcx after decrementing
.byteloop:
lodsb ; upper 24b of eax stays zeroed (no partial-register stall on Intel P6/SnB-family CPUs, thanks to the xor-zeroing)
add edi, eax ; low += zero_extend(buf[i])
add edx, edi ; high += low
loop .byteloop
.end:
;; exit when ecx = 0, eax = last byte of buf
;; lodsb at this point would load the terminating 0 byte, conveniently leaving eax=0
mov cx, 65521 ; ecx = m = adler32 magic constant. (upper 16b of ecx is zero from the loop exit condition. This saves 1B over mov r32,imm32)
;sub cx, (65536 - 65521) ; the immediate is small enough to use the imm8 encoding. No saving over mov, though, since this needs a mod/rm byte
xchg eax, edx ; eax = high, edx = buf[last_byte]
cdq ; could be removed if we could arrange things so the loop ended with a load of the 0 byte
div ecx ; div instead of idiv to fault instead of returning wrong answers if high has overflowed to negative. (-1234 % m is negative)
push rdx ; push high%m and 6B of zero padding
xchg eax, edi ; eax=low
cdq
div ecx ; edx = low%m
;; concatenate the two 16bit halves of the result by putting them in contiguous memory
push dx ; push low%m with no padding
pop rax ; pop high%m << 16 | low%m (x86 is little-endian)
pop dx ; add rsp, 2 to restore the stack pointer
;; outside of 16bit code, we can't justify returning the result in the dx:ax register pair
ret
golfed_adler32_amd64_end_v3:
```
I also considered using `rcx` as an array index, instead of having two loop counters, but adler32(s) != adler32(reverse(s)). So we couldn't use `loop`. Counting from -len up towards zero and using `movzx r32, [rsi+rcx]` just uses way too many bytes.
If we want to consider incrementing the pointer ourself, 32bit code is probably the way to go. Even the x32 ABI (32bit pointers) isn't sufficient, because `inc esi` is 2B on amd64, but 1B on i386. It appears hard to beat `xor eax,eax` / `lodsb` / `loop`: 4B total to get each element in turn zero-extended into eax. `inc esi` / `movzx r32, byte [esi]` / `loop` is 5B.
`scas` is another option for incrementing a pointer with a 1B instruction in 64bit mode. (`rdi`/`edi` instead of `rsi`, so we'd take the pointer arg in `rdi`). We can't use the flag result from `scas` as a loop condition, though, because we don't want to keep eax zeroed. Different register allocation could maybe save a byte after the loop.
---
### `int[]` input
The full function taking `uint8_t[]` is the "main" answer, because it's a more interesting challenge. Unpacking to `int[]` is an unreasonable thing to ask our caller to do in this language, but it does save 2B.
If we take our input as an unpacked array of 32bit integers, we can save one byte easily (use `lodsd` and replace `xor eax,eax / cdq` with just `xor edx,edx`).
We can save another byte by zeroing edx with `lodsd`/`cdq`, and re-arranging the loop so it loads the terminating 0 element before exiting. (We're still assuming it exists, even though this is an array of `int`, not a string).
```
; untested: I didn't modify the test driver to unpack strings for this
golfed_adler32_int_array:
; xor edx,edx
lodsd ; first element. only the low byte non-zero
cdq ; edx: high=0
lea edi, [rdx+1] ; edi: low=1
;jrcxz .end ; handle len=0? unlike rep, loop only checks rcx after decrementing
.intloop:
add edi, eax ; low += buf[i]
add edx, edi ; high += low
lodsd ; load buf[i+1] for next iteration
loop .intloop
.end:
;; exit when ecx = 0, eax = terminating 0
xchg eax, edx
;cdq ; edx=0 already, ready for div
; same as the char version
```
I also made an untested version that uses `scasd` (1B version of `add edi,4`) and `add eax, [rdi]` instead of `lodsd`, but it's also 30 bytes. The savings from having `high` in eax at the end of the loop are balanced out by larger code elsewhere. It has the advantage of not depending on a terminating `0` element in the input, though, which is maybe unreasonable for an unpacked array where we're also given the length explicitly.
---
## C++11 test driver
See the github link. This answer was getting too big, and the test driver got more features with bigger code.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes
```
tsQwYsQsh16W15-\l8Mh*s
```
Input can be an array of numbers or the corresponding ASCII string.
[**Try it online!**](http://matl.tryitonline.net/#code=dHNRd1lzUXNoMTZXMTUtXGw4TWgqcw&input=J35-fn5-fn5-fn5-fn5-fn5-fn5-fn5-fn5-fn5-fn5-Jw)
### Explanation
```
t % Take array or string as input. Duplicate
sQ % Sum all its values, and add 1
wYsQs % Swap. Cumulative sum, add 1, sum
h % Concatenate horizontally
16W % 2^16: gives 65536
15- % Subtract 15: gives 65521
\ % Element-wise modulo operation
l % Push 1
8M % Push 65536 again
h % Concatenate horizontally: gives array [1, 65535]
*s % Element-wise multiplication and sum. Display
```
[Answer]
## Actually, 36 bytes
```
;Σu@;╗lR`╜HΣu`MΣk`:65521@%`M1#84ⁿ@q*
```
[Try it online!](http://actually.tryitonline.net/#code=O86jdUA74pWXbFJg4pWcSM6jdWBNzqNrYDo2NTUyMUAlYE0xIzg04oG_QHEq&input=WzY5LCA5NywgMTAzLCAxMDgsIDEwMSwgMTE1LCAzMiwgOTcsIDExNCwgMTAxLCAzMiwgMTAzLCAxMTQsIDEwMSwgOTcsIDExNiwgMzNd)
Explanation:
```
;Σu@;╗lR`╜HΣu`MΣk`:65521@%`M1#84ⁿ@q*
;Σu sum(input)+1
@;╗lR push a copy of input to reg0, push range(1, len(input)+1)
`╜HΣu`M map over range: sum(head(reg0,n))+1
Σk sum, combine lower and upper into a list
`:65521@%`M modulo each by 65521
1#84ⁿ@q* dot product with [1,4**8]
```
[Answer]
# Java, 84 bytes
```
long a(int[]i){long a=1,b=0;for(int p:i)b=(b+(a=(a+p)%(p=65521)))%p;return b<<16|a;}
```
If Java solutions are always supposed to be complete compilable code please let me know.
### Ungolfed
```
long a(int[] i) {
long a = 1, b = 0;
for (int p : i) b = (b + (a = (a + p) % (p = 65521))) % p;
return b << 16 | a;
}
```
### Note
You will have to convert the input `String` to `int[]` (`int[]` is one byte shorter than `byte[]` or `char[]`).
### Output
```
String: "Eagles are great!"
Byte Array: [69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
Checksum: 918816254
Expected: 918816254
String: "Programming Puzzles & Code Golf"
Byte Array: [80, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 80, 117, 122, 122, 108, 101, 115, 32, 38, 32, 67, 111, 100, 101, 32, 71, 111, 108, 102]
Checksum: 3133147946
Expected: 3133147946
String: "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
Byte Array: [126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126]
Checksum: 68095937
Expected: 68095937
String: "?????????...?"
Byte Array: [63, 63, 63, 63, 63, 63, 63, 63, 63, ...,63]
Checksum: 2181038080
Expected: 2181038080
```
[Answer]
# Piet, 120 Codels [codelsize 1](https://i.stack.imgur.com/6L6Ur.png)
With codelsize 20:
[![codelsize 20](https://i.stack.imgur.com/NUxUp.png)](https://i.stack.imgur.com/NUxUp.png)
### Notes / How does it work?
* Since it is not possible to use an array or string as input, this program works by taking a series of integers (representing ascii characters) as inputs. I thought about using character inputs at first but struggled to find a nice solution for termination, so now it terminates when any numer smaller than 1 is entered. It was originally only negative values for termination, but I had to change the initialization after writing the program, so now I can't fit the required `2`, only a `1` (26/45 on the trace image). This doesn't matter though because as per the challenge rules, only printable ascii characters are allowed.
* Struggled for a long time with reentering the loop, though I found quite the elegant solution in the end. No `pointer` or `switch` operations, only the interpreter running into walls until it transitions back into the green codel to read the input (43->44 on the trace images).
* Loop termination is achived by first duplicating the input, adding 1 and then checking if it is bigger than 1. If it is, the codel chooser is triggered and execution continues on the lower path. If it is not, the program contines left (Bright yellow codels, 31/50 on the trace images).
* The supported input size is interpreter implementation dependent, though it would be possible to support an arbitrarily large input with the right interpreter (Say, for example, a Java interpreter that uses `BigInteger` as internal values)
* Just saw that the setup includes one unnecessary `DUP` and `CC` (7->8->9 in the trace images). No idea how that happened. This is effectively a noop though, it toggles the codel chooser 16 times which results in no change.
### Npiet trace images
Setup and first loop:
[![starttrace](https://i.stack.imgur.com/OMdNz.png)](https://i.stack.imgur.com/OMdNz.png)
Loop termination, output and exit:
[![endtrace](https://i.stack.imgur.com/funAu.png)](https://i.stack.imgur.com/funAu.png)
### Outputs
Forgive me if I only include one output, it just takes a long time to input :^)
```
String: "Eagles are great!"
PS B:\Marvin\Desktop\Piet> .\npiet.exe adler32.png
? 69
? 97
? 103
? 108
? 101
? 115
? 32
? 97
? 114
? 101
? 32
? 103
? 114
? 101
? 97
? 116
? 33
? -1
918816254
```
### Npiet trace for [65, -1]
```
trace: step 0 (0,0/r,l nR -> 1,0/r,l dR):
action: push, value 4
trace: stack (1 values): 4
trace: step 1 (1,0/r,l dR -> 2,0/r,l dB):
action: duplicate
trace: stack (2 values): 4 4
trace: step 2 (2,0/r,l dB -> 3,0/r,l nM):
action: multiply
trace: stack (1 values): 16
trace: step 3 (3,0/r,l nM -> 4,0/r,l nC):
action: duplicate
trace: stack (2 values): 16 16
trace: step 4 (4,0/r,l nC -> 5,0/r,l nY):
action: duplicate
trace: stack (3 values): 16 16 16
trace: step 5 (5,0/r,l nY -> 6,0/r,l nM):
action: duplicate
trace: stack (4 values): 16 16 16 16
trace: step 6 (6,0/r,l nM -> 7,0/r,l nC):
action: duplicate
trace: stack (5 values): 16 16 16 16 16
trace: step 7 (7,0/r,l nC -> 8,0/r,l nY):
action: duplicate
trace: stack (6 values): 16 16 16 16 16 16
trace: step 8 (8,0/r,l nY -> 9,0/r,l lB):
action: switch
trace: stack (5 values): 16 16 16 16 16
trace: stack (5 values): 16 16 16 16 16
trace: step 9 (9,0/r,l lB -> 10,0/r,l dM):
action: multiply
trace: stack (4 values): 256 16 16 16
trace: step 10 (10,0/r,l dM -> 11,0/r,l nR):
action: multiply
trace: stack (3 values): 4096 16 16
trace: step 11 (11,0/r,l nR -> 12,0/r,l lY):
action: multiply
trace: stack (2 values): 65536 16
trace: step 12 (12,0/r,l lY -> 13,0/r,l lM):
action: duplicate
trace: stack (3 values): 65536 65536 16
trace: step 13 (13,0/r,l lM -> 14,0/r,l nM):
action: push, value 3
trace: stack (4 values): 3 65536 65536 16
trace: step 14 (14,0/r,l nM -> 15,0/r,l dM):
action: push, value 2
trace: stack (5 values): 2 3 65536 65536 16
trace: step 15 (15,0/r,l dM -> 16,0/r,l lC):
action: roll
trace: stack (3 values): 16 65536 65536
trace: step 16 (16,0/r,l lC -> 17,0/r,l nB):
action: sub
trace: stack (2 values): 65520 65536
trace: step 17 (17,0/r,l nB -> 18,0/r,l dB):
action: push, value 1
trace: stack (3 values): 1 65520 65536
trace: step 18 (18,0/r,l dB -> 19,0/r,l dM):
action: add
trace: stack (2 values): 65521 65536
trace: step 19 (19,0/r,l dM -> 19,1/d,r dC):
action: duplicate
trace: stack (3 values): 65521 65521 65536
trace: step 20 (19,1/d,r dC -> 18,1/l,l lC):
action: push, value 1
trace: stack (4 values): 1 65521 65521 65536
trace: step 21 (18,1/l,l lC -> 17,1/l,l nC):
action: push, value 1
trace: stack (5 values): 1 1 65521 65521 65536
trace: step 22 (17,1/l,l nC -> 16,1/l,l dB):
action: sub
trace: stack (4 values): 0 65521 65521 65536
trace: step 23 (16,1/l,l dB -> 15,1/l,l lB):
action: push, value 1
trace: stack (5 values): 1 0 65521 65521 65536
trace: step 24 (15,1/l,l lB -> 13,2/l,l dG):
action: in(number)
? 65
trace: stack (6 values): 65 1 0 65521 65521 65536
trace: step 25 (13,2/l,l dG -> 12,2/l,l dR):
action: duplicate
trace: stack (7 values): 65 65 1 0 65521 65521 65536
trace: step 26 (12,2/l,l dR -> 11,2/l,l lR):
action: push, value 1
trace: stack (8 values): 1 65 65 1 0 65521 65521 65536
trace: step 27 (11,2/l,l lR -> 10,2/l,l lY):
action: add
trace: stack (7 values): 66 65 1 0 65521 65521 65536
trace: step 28 (10,2/l,l lY -> 9,2/l,l nY):
action: push, value 1
trace: stack (8 values): 1 66 65 1 0 65521 65521 65536
trace: step 29 (9,2/l,l nY -> 8,1/l,r nB):
action: greater
trace: stack (7 values): 1 65 1 0 65521 65521 65536
trace: step 30 (8,1/l,r nB -> 7,1/l,r lY):
action: switch
trace: stack (6 values): 65 1 0 65521 65521 65536
trace: stack (6 values): 65 1 0 65521 65521 65536
trace: step 31 (7,1/l,l lY -> 6,2/l,l nY):
action: push, value 2
trace: stack (7 values): 2 65 1 0 65521 65521 65536
trace: step 32 (6,2/l,l nY -> 5,3/l,l dB):
action: pointer
trace: stack (6 values): 65 1 0 65521 65521 65536
trace: step 33 (5,3/r,l dB -> 7,4/r,l dM):
action: add
trace: stack (5 values): 66 0 65521 65521 65536
trace: step 34 (7,4/r,l dM -> 8,4/r,l dC):
action: duplicate
trace: stack (6 values): 66 66 0 65521 65521 65536
trace: step 35 (8,4/r,l dC -> 9,3/r,l lC):
action: push, value 3
trace: stack (7 values): 3 66 66 0 65521 65521 65536
trace: step 36 (9,3/r,l lC -> 10,3/r,l nC):
action: push, value 2
trace: stack (8 values): 2 3 66 66 0 65521 65521 65536
trace: step 37 (10,3/r,l nC -> 11,3/r,l dY):
action: roll
trace: stack (6 values): 0 66 66 65521 65521 65536
trace: step 38 (11,3/r,l dY -> 12,3/r,l dG):
action: add
trace: stack (5 values): 66 66 65521 65521 65536
trace: step 39 (12,3/r,l dG -> 13,3/r,l lG):
action: push, value 2
trace: stack (6 values): 2 66 66 65521 65521 65536
trace: step 40 (13,3/r,l lG -> 14,3/r,l nG):
action: push, value 1
trace: stack (7 values): 1 2 66 66 65521 65521 65536
trace: step 41 (14,3/r,l nG -> 15,3/r,l dR):
action: roll
trace: stack (5 values): 66 66 65521 65521 65536
trace: white cell(s) crossed - continuing with no command at 17,3...
trace: step 42 (15,3/r,l dR -> 17,3/r,l lB):
trace: step 43 (17,3/r,l lB -> 13,2/l,l dG):
action: in(number)
? -1
trace: stack (6 values): -1 66 66 65521 65521 65536
trace: step 44 (13,2/l,l dG -> 12,2/l,l dR):
action: duplicate
trace: stack (7 values): -1 -1 66 66 65521 65521 65536
trace: step 45 (12,2/l,l dR -> 11,2/l,l lR):
action: push, value 1
trace: stack (8 values): 1 -1 -1 66 66 65521 65521 65536
trace: step 46 (11,2/l,l lR -> 10,2/l,l lY):
action: add
trace: stack (7 values): 0 -1 66 66 65521 65521 65536
trace: step 47 (10,2/l,l lY -> 9,2/l,l nY):
action: push, value 1
trace: stack (8 values): 1 0 -1 66 66 65521 65521 65536
trace: step 48 (9,2/l,l nY -> 8,1/l,r nB):
action: greater
trace: stack (7 values): 0 -1 66 66 65521 65521 65536
trace: step 49 (8,1/l,r nB -> 7,1/l,r lY):
action: switch
trace: stack (6 values): -1 66 66 65521 65521 65536
trace: stack (6 values): -1 66 66 65521 65521 65536
trace: step 50 (7,1/l,r lY -> 6,1/l,r dY):
action: pop
trace: stack (5 values): 66 66 65521 65521 65536
trace: step 51 (6,1/l,r dY -> 4,1/l,r lY):
action: push, value 3
trace: stack (6 values): 3 66 66 65521 65521 65536
trace: step 52 (4,1/l,r lY -> 3,1/l,r nY):
action: push, value 2
trace: stack (7 values): 2 3 66 66 65521 65521 65536
trace: step 53 (3,1/l,r nY -> 2,1/l,r nM):
action: duplicate
trace: stack (8 values): 2 2 3 66 66 65521 65521 65536
trace: step 54 (2,1/l,r nM -> 1,1/l,r dG):
action: pointer
trace: stack (7 values): 2 3 66 66 65521 65521 65536
trace: step 55 (1,1/r,r dG -> 2,2/r,r lR):
action: roll
trace: stack (5 values): 65521 66 66 65521 65536
trace: step 56 (2,2/r,r lR -> 2,3/d,l nR):
action: push, value 1
trace: stack (6 values): 1 65521 66 66 65521 65536
trace: step 57 (2,3/d,l nR -> 2,4/d,l lC):
action: switch
trace: stack (5 values): 65521 66 66 65521 65536
trace: stack (5 values): 65521 66 66 65521 65536
trace: step 58 (2,4/d,r lC -> 2,5/d,r nM):
action: mod
trace: stack (4 values): 66 66 65521 65536
trace: step 59 (2,5/d,r nM -> 4,5/r,r dM):
action: push, value 3
trace: stack (5 values): 3 66 66 65521 65536
trace: step 60 (4,5/r,r dM -> 6,5/r,r lM):
action: push, value 2
trace: stack (6 values): 2 3 66 66 65521 65536
trace: step 61 (6,5/r,r lM -> 7,5/r,r nC):
action: roll
trace: stack (4 values): 65521 66 66 65536
trace: step 62 (7,5/r,r nC -> 8,5/r,r dM):
action: mod
trace: stack (3 values): 66 66 65536
trace: step 63 (8,5/r,r dM -> 11,5/r,r lM):
action: push, value 3
trace: stack (4 values): 3 66 66 65536
trace: step 64 (11,5/r,r lM -> 12,5/r,r nM):
action: push, value 1
trace: stack (5 values): 1 3 66 66 65536
trace: step 65 (12,5/r,r nM -> 13,5/r,r dC):
action: roll
trace: stack (3 values): 66 65536 66
trace: step 66 (13,5/r,r dC -> 14,5/r,r nB):
action: multiply
trace: stack (2 values): 4325376 66
trace: step 67 (14,5/r,r nB -> 15,5/r,r nM):
action: add
trace: stack (1 values): 4325442
trace: step 68 (15,5/r,r nM -> 16,5/r,r dB):
action: out(number)
4325442
trace: stack is empty
trace: white cell(s) crossed - continuing with no command at 19,5...
trace: step 69 (16,5/r,r dB -> 19,5/r,r nM):
```
[Answer]
# C89, 70 bytes
```
h,l,m=65521;A(char*B){h=0;l=1;while(*B)h+=l+=*B++;return h%m<<16|l%m;}
```
To test (compile with `gcc -std=c89 -lm golf.c`):
```
#include <stdio.h>
int main(int argc, char** argv) {
printf("%u\n", A("Eagles are great!"));
printf("%u\n", A("Programming Puzzles & Code Golf"));
printf("%u\n", A("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"));
return 0;
}
```
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), ~~37~~ ~~36~~ ~~32~~ 31 bytes
```
}?"{655:}21:}%=}){%{{36*+!
:++)
```
[Try it online!](http://labyrinth.tryitonline.net/#code=fT8iezY1NTp9MjE6fSU9fSl7JXt7MzYqKyEKOisrKQ&input=NjkgOTcgMTAzIDEwOCAxMDEgMTE1IDMyIDk3IDExNCAxMDEgMzIgMTAzIDExNCAxMDEgOTcgMTE2IDMz)
Input as a list of integers. The program terminates with an error (whose error message goes to STDERR).
### Explanation
Labyrinth primer:
* Labyrinth has two stacks of arbitrary-precision integers, *main* and *aux*(iliary), which are initially filled with an (implicit) infinite amount of zeros.
* The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.
* Digits are processed by multiplying the top of the main stack by 10 and then adding the digit. To start a new number, you can push a zero with `_`.
Although the code starts with a 4x2 "room", that is actually two separate two-by-two loops squeezed together. The IP just happens to stick to one loop at a time due to the stack values.
So the code starts with a 2x2 (clockwise) loop which reads input while computing prefix sums:
```
} Move last prefix sum over to aux.
? Read an integer from STDIN or push 0 on EOF, which exits the loop.
+ Add current value to prefix sum.
: Duplicate this prefix sum.
```
Now we've got all the prefix sums on the *aux* stack, as well as a copy of the sum over all values and the `0` from EOF on *main*. With that, we enter another 2x2 (clockwise) loop which sums all the prefix sums to compute `HIGH`.
```
" No-op. Does nothing.
{ Pull one prefix sum over from aux. When we're done, this fetches a 0,
which exits the loop.
) Increment prefix sum.
+ Add it to HIGH.
```
The main stack now has `LOW - 1` and `HIGH` and zero, except we haven't taken the modulo yet. The remainder of the code is completely linear:
```
655 Turn the zero into 655.
:} Make a copy and shift it over to aux.
21 Turn the copy on main into 65521.
:} Make a copy and shift it over to aux.
% Take HIGH mod 65521.
= Swap HIGH with the other copy of 65521 on aux.
}){ Move 65521 back to aux, increment LOW-1 to LOW,
move 65521 back to main.
% Take LOW mod 65521.
{ Move HIGH back to main.
{ Move the other copy of 655 back to main.
36 Turn it into 65536.
* Multiply HIGH by that.
+ Add it to LOW.
! Print it.
```
The IP now hits a dead end and turns around. The `+` and `*` are essentially no-ops, due to the zeros at the stack bottom. The `36` now turns the top of *main* into `63`, but the two `{{` pull two zeros from *aux* on top of it. Then `%` tries to divide by zero which terminates the program.
Note that Labyrinth uses arbitrary-precision integers so deferring the modulo until the end of the sum won't cause problems with integer overflow.
[Answer]
## Python 2, ~~60~~ 58 bytes
```
H=h=65521
l=1
for n in input():l+=n;h+=l
print h%H<<16|l%H
```
A pretty straightforward approach. This is a full program which takes a list of integers via STDIN, e.g. `[72, 105, 33]`.
*(Thanks to @xnor for the amazing aliasing/initialisation tip)*
[Answer]
# Jelly, ~~19~~ 17 bytes
```
+\,S‘S€%65521ḅ⁹²¤
```
[Try it online!](http://jelly.tryitonline.net/#code=K1wsU-KAmFPigqwlNjU1MjHhuIU2NTUzNg&input=&args=WzgwLCAxMTQsIDExMSwgMTAzLCAxMTQsIDk3LCAxMDksIDEwOSwgMTA1LCAxMTAsIDEwMywgMzIsIDgwLCAxMTcsIDEyMiwgMTIyLCAxMDgsIDEwMSwgMTE1LCAzMiwgMzgsIDMyLCA2NywgMTExLCAxMDAsIDEwMSwgMzIsIDcxLCAxMTEsIDEwOCwgMTAyXQ)
```
+\,S‘S€%65521ḅ⁹²¤ Main monadic chain. Takes array as only argument.
The array is shown here as [b1 b2 ... bn].
+\ Reduce by addition (+) while returning immediate results.
yields [b1 b1+b2 ... b1+b2+...+bn].
, Concatenate with...
S the sum of the argument.
yields [[b1 b1+b2 ... b1+b2+...+bn] b1+b2+...+bn].
‘ Increment [each].
yields [[1+b1 1+b1+b2 ... 1+b1+b2+...+bn] 1+b1+b2+...+bn].
S€ Sum each list.
yields [[1+b1+1+b1+b2+...+1+b1+b2+...+bn] 1+b1+b2+...+bn].
%65521 Modulo [each] by 65521.
ḅ⁹²¤ Convert from base 65536 to integer.
⁹ 256
² squared
```
[Answer]
# J, 30 bytes
```
+/(+65536&*)&(65521|+/)&:>:+/\
```
This could probably be condensed more with a different train.
## Usage
Here `x $ y` creates a list with `x` copies of `y`.
```
f =: +/(+65536&*)&(65521|+/)&:>:+/\
f 69 97 103 108 101 115 32 97 114 101 32 103 114 101 97 116 33
918816254
f 80 114 111 103 114 97 109 109 105 110 103 32 80 117 122 122 108 101 115 32 38 32 67 111 100 101 32 71 111 108 102
3133147946
f (32 $ 126)
68095937
f (1040 $ 63)
2181038080
f (4096 $ 255)
2170679522
```
## Explanation
```
+/(+65536&*)&(65521|+/)&:>:+/\
f ( g ) h Monad train (f g h) y = (f y) g (h y)
+/ Sum the input list
+/\ Sum each prefix of the input, forms a list
x f & g &: h y Composed verbs, makes (g (h x)) f (g (h y))
>: Increment the sum and increment each prefix sum
(m f g) y Hook, makes m f (g y)
+/ Sum the prefix sums
65521| Take the sum and prefix total mod 65521
(f g) y Hook again
65536&* Multiply the prefix total by 65536
This is a bonded verb, it will only multiply
using a fixed value now
+ Add the sum and scaled prefix total
```
[Answer]
# Octave, ~~52~~ 50 bytes
Saved 2 bytes thanks to @LuisMendo
```
@(B)mod([sum(S=cumsum(B)+1),S(end)],65521)*[4^8;1]
```
Takes an array of integers as input.
**low** is taken from the last element of **high** (before summing) rather than calculating the sum explicitly, saving a grand total of... **1 byte**!
Sample run on [ideone](http://ideone.com/CAjSTm).
[Answer]
## CJam, ~~30~~ 29 bytes
```
q~{1$+}*]:)_W>]1fb65521f%2G#b
```
Input as a list of integers.
[Test it here.](http://cjam.aditsu.net/#code=q~%7B1%24%2B%7D*%5D%3A)_W%3E%5D1fb65521f%252G%23b&input=%5B69%2097%20103%20108%20101%20115%2032%2097%20114%20101%2032%20103%20114%20101%2097%20116%2033%5D)
### Explanation
```
q~ e# Read and evaluate input.
{ e# Fold this block over the list, computing prefix sums.
1$+ e# Copy the last prefix and add the current element.
}*
] e# Wrap the prefix sums in an array.
:) e# Increment each. This will sum to HIGH.
_W> e# Copy the list and truncate to only the last element, i.e.
e# the sum of the entire input plus 1. This is LOW.
] e# Wrap both of those lists in an array.
1fb e# Sum each, by treating it as base 1 digits.
65521f% e# Take each modulo 65521.
2G#b e# Treat the list as base 65536 digits, computing 65536*HIGH + LOW.
```
[Answer]
# [Perl 6](http://perl6.org), 60 bytes
```
{(.sum+1)%65521+65536*((sum(1,*+.shift...->{!$_})-1)%65521)}
```
### Explanation:
```
{
# $_ is the implicit parameter for this lambda because this block doesn't have
# an explicit parameter, and @_ isn't seen inside of it.
# ( @_ takes precedence over $_ when it is seen by the compiler )
# .sum is short for $_.sum
( .sum + 1 ) % 65521 + 65536
*
(
(
sum(
# generate a sequence:
1, # starting with 1
* + .shift # lambda that adds previous result (*) with $_.shift
... # generate until:
-> { !$_ } # $_ is empty
# ^ I used a pointy block with zero parameters
# so that the block doesn't have an implicit parameter
# like the surrounding block
# this is so that $_ refers to the outer $_
) - 1 # remove starting value
) % 65521
)
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
# give the lambda a name
my &Adler32 = {(.sum+1)%65521+65536*((sum(1,*+.shift...->{!$_})-1)%65521)}
my @tests = (
( 918816254, 'Eagles are great!'),
( 3133147946, 'Programming Puzzles & Code Golf'),
( 68095937, '~' x 32, "'~' x 32"),
( 2181038080, 63 xx 1040, "'?' x 1040"),
);
plan +@tests;
for @tests -> ($checksum, $input, $gist? ) {
my @array := do given $input {
when Str { .encode.Array }
default { .Array }
}
is Adler32(@array), $checksum, $gist // $input.perl
}
```
```
1..4
ok 1 - "Eagles are great!"
ok 2 - "Programming Puzzles \& Code Golf"
ok 3 - '~' x 32
ok 4 - '?' x 1040
```
[Answer]
# Python 3 (79 bytes)
Based on R. Kap's solution.
```
lambda w,E=65521:(1+sum(w))%E+(sum(1+sum(w[:i+1])for i in range(len(w)))%E<<16)
```
I replaced the multiplication by a shift and removed a pair of brackets.
Because I can't post comments I made a new answer.
[Answer]
# Scheme, 195 bytes
```
(define(a b)(+(let L((b b)(s 1))(if(=(length b)0)s(L(cdr b)(modulo(+ s(car b))65521))))(* 65536(let H((b b)(s 1)(t 0))(if(=(length b)0)t(let((S(+ s(car b))))(H(cdr b)S(modulo(+ t S)65521))))))))
```
If it weren't for all those parentheses...
[Answer]
## Haskell, ~~54~~ 50 bytes
```
m=(`mod`65521).sum
g x=m(-1:scanl(+)1x)*4^8+m(1:x)
```
Usage example: `g [69,97,103,108,101,115,32,97,114,101,32,103,114,101,97,116,33]`-> `918816254`.
`scanl` includes the starting value (-> `1`) in the list (-> `[1,1+b1,1+b1+b2,..]`), so the `sum` is off by `1`, which is fixed by prepending `-1` to the list before summing.
Edit: Thanks @xnor for 4 bytes.
[Answer]
## JavaScript (ES7), ~~52~~ 50 bytes
```
a=>a.map(b=>h+=l+=b,h=0,l=1)&&l%65521+h%65521*4**8
```
ES6 takes 51 bytes (replace 4\*\*8 with 65536). If you want a string version, then for 69 bytes:
```
s=>[...s].map(c=>h+=l+=c.charCodeAt(),h=0,l=1)&&l%65521+h%65521*65536
```
Edit: Saved 2 bytes thanks to @user81655.
[Answer]
# ARM Thumb-2 function accepting `uint8_t[]`: 40 bytes (36B for non-standard ABI and `int[]`)
Features: non-deferred modulo, so arbitrary-size inputs are fine. Doesn't actually use the division instruction, so it's not slow. (err, at least not for that reason :P)
Savings from following less strict rules:
* -2B if we don't have to save registers before using them.
* -2B for requiring the caller to unpack bytes into a `uint32_t[]` array.
So, best-case is 36B.
```
// uint8_t *buf in r0, uint32_t len in r1
00000000 <adler32arm_golf2>:
0: b570 push {r4, r5, r6, lr} //
2: 2201 movs r2, #1 // low
4: 2300 movs r3, #0 // high
6: f64f 75f1 movw r5, #65521 ; 0xfff1 = m
0000000a <adler32arm_golf2.byteloop>:
a: f810 4b01 ldrb.w r4, [r0], #1 // post-increment byte-load
e: 4422 add r2, r4 // low += *B
10: 4413 add r3, r2 // high += low
12: 42aa cmp r2, r5 // subtract if needed instead of deferred modulo
14: bf28 it cs
16: 1b52 subcs r2, r2, r5
18: 42ab cmp r3, r5
1a: bf28 it cs // Predication in thumb mode is still possible, but takes a separate instruction
1c: 1b5b subcs r3, r3, r5
1e: 3901 subs r1, #1 // while(--len)
20: d1f3 bne.n a <.byteloop2>
22: eac2 4003 pkhbt r0, r2, r3, lsl #16 // other options are the same size: ORR or ADD.
26: bd70 pop {r4, r5, r6, pc} // ARM can return by popping the return address (from lr) into the pc; nifty
00000028 <adler32arm_end_golf2>:
```
**0x28 = 40 bytes**
---
## Notes:
Instead of `log%m` at the end, we do `if(low>=m) low-=m` inside the loop. If we do low before high, we know that neither can possibly exceed `2*m`, so modulo is just a matter of subtracting or not. A `cmp` and predicated `sub` is only 6B in Thumb2 mode. [The standard idiom for `%`](https://stackoverflow.com/a/23857807/224132) is 8B in Thumb2 mode:
```
UDIV R2, R0, R1 // R2 <- R0 / R1
MLS R0, R1, R2, R0 // R0 <- R0 - (R1 * R2 )
```
---
The implicit-length `adler(char *)` version is the same code-size as the explicit length `adler(uint8_t[], uint32_t len)`. We can set flags for the loop-exit condition with a single 2B instruction either way.
The implicit-length version has the advantage of working correctly with the empty string, instead of trying to loop 2^32 times.
---
## assemble / compile with:
```
arm-linux-gnueabi-as --gen-debug -mimplicit-it=always -mfloat-abi=soft -mthumb adler32-arm.S
```
or
```
arm-linux-gnueabi-g++ -Wa,-mimplicit-it=always -g -static -std=gnu++14 -Wall -Wextra -Os -march=armv6t2 -mthumb -mfloat-abi=soft test-adler32.cpp -fverbose-asm adler32-arm.S -o test-adler32
qemu-arm ./test-adler32
```
Without `-static`, the process running under `qemu-arm` didn't find it's dynamic linker. (And yes, I install an ARM cross-devel setup just for this answer, because I thought my predicated-subtract idea was neat.) On amd64 Ubuntu, install `gcc-arm-linux-gnueabi`, `g++-arm-linux-gnueabi`. I found `gdb-arm-none-eabi` sort of barely worked connecting to `qemu-arm -g port`.
## Commented source:
```
// There's no directive to enable implicit-it=always
// gcc uses compiler uses these in its output
.syntax unified
.arch armv8-a
.fpu softvfp
.thumb @ aka .code 16
.p2align 4
.globl adler32arm_golf @ put this label on the one we want to test
.thumb_func
adler32arm_golf:
adler32arm_golf2: @ (uint8_t buf[], uint32_t len)
@ r0 = buf
@ r1 = len
push {r4, r5, r6, lr} @ even number of regs keeps the stack aligned. Good style? since there's no code-size saving
movs r2, #1 @ r2: low
movs r3, #0 @ r3: high
@ r4 = tmp for loading bytes
movw r5, #65521 @ r5: modulo constant
adler32arm_golf2.byteloop2:
ldrb r4, [r0], #1 @ *(buf++) post-increment addressing. 4B encoding
@ldrb r4, [r0, r1] @ 2B encoding, but unless we make the caller pass us buf+len and -len, it needs extra code somewhere else
@ldmia r0!, {r4} @ int[] version: r4 = [r0]; r0+=4; post-increment addressing. 2B encoding.
add r2, r2, r4 @ low += tmp
add r3, r3, r2 @ high += low; // I think it's safe to do this before the modulo range-reduction for low, but it would certainly work to put it after.
cmp r2, r5
subhs r2, r5 @ if(low>=m) low-=m; @ 6B total for %. predicated insns require an IT instruction in thumb2
cmp r3, r5
subhs r3, r5 @ if(high>=m) high-=m; // equivalent to high %= m.
@sub r1, #1 @ 4B encoding: sub.w to not set flags with immediate
subs r1, #1 @ len-- and set flags. 2B encoding
@cmp r4, #0 @ null-termination check. 2B encoding
bne adler32arm_golf2.byteloop2
@ udiv r0, r2, r5 @ normal way to do one of the modulos
@ mls r2, r5, r0, r2 @ r2 = low % m. 8B total for %
PKHBT r0, r2, r3, lsl #16 @ 4B r0 = [ high%m <<16 | low%m ]
@orr r0, r0, r4, lsl #16 @ 4B
@orr r0, r0, r4 @ 4B
@add r0, r2, r3, lsl #16 @ 4B
@add r0, r0, r4 @ 2B
pop {r4, r5, r6, pc} @ ARM can return by popping the return address (saved from lr) into pc. Nifty
adler32arm_end_golf2:
```
`test-adler32.cpp` has the same test-cases and `main()` as for my x86-64 answer, but starts this way:
```
#include <stdint.h>
uint32_t adler32_simple(const uint8_t *B) {
const uint32_t m=65521;
uint32_t h=0, l=1;
do {
l += *B++; // Borrowed from orlp's answer, as a simple reference implementation
h += l;
l %= m; h %= m; // with non-deferred modulo if this is uncommented
} while(*B);
return h%m<<16|l%m;
}
#include <stdio.h>
//#include <zlib.h>
#include <string.h>
#include <assert.h>
#include <string> // useful for the memset-style constructors that repeat a character n times
extern "C" {
unsigned golfed_adler32_amd64(int /*dummy1*/, const char *buf, int /*dummy2*/, unsigned len);
unsigned adler32arm_golf(const char *buf, unsigned len);
}
#ifdef __amd64__
#define golfed_adler32(buf, len) golfed_adler32_amd64(1234, buf, 1234, len)
#elif __arm__
#define golfed_adler32(buf, len) adler32arm_golf(buf, len)
#else
#error "no architecture"
#endif
static void test_adler(const char *str)
{
unsigned len = strlen(str);
// unsigned zlib = zlib_adler(len, str);
unsigned reference = adler32_simple((const uint8_t*)str);
unsigned golfed = golfed_adler32(str, len);
printf("%s: c:%u asm:%u\n", str, reference, golfed);
assert(reference == golfed);
}
// main() to call test_adler() unchanged from my amd64 answer, except that the comments about length limits don't apply
```
[Answer]
# x86 16bit machine code function: 32 bytes using a custom calling convention
Args in registers, and not preserving regs other than bp (and sp).
In 16bit code, we return a 32bit value in the `dx:ax` register pair. This means we don't have to spend any instructions merging `high` and `low` into `eax`. (This would save bytes in 32 and 64 bit code, too, but we can only justify offloading this work to the caller in 16bit code.)
### [Commented source and test driver on github](https://github.com/pcordes/adler32-golf) (for x86 16, 32, and 64bit, and ARM).
```
### const char *buf in SI, uint16_t len in CX
## returns in dx:ax
## also clobbers bx and di.
00000100 <adler32_x16_v6>:
100: 31 c0 xor ax,ax # set up for lods
102: 99 cwd # dx= high=0
103: bf 01 00 mov di,0x1 # di= low=0
106: bb f1 ff mov bx,0xfff1 # bx= m
00000109 <adler32_x16_v6.byteloop>:
109: ac lods
10a: 01 c7 add di,ax # low+=buf[i]. modulo-reduce on carry, or on low>=m
10c: 72 04 jc 112 <adler32_x16_v6.carry_low>
10e: 39 df cmp di,bx
110: 72 02 jb 114 <adler32_x16_v6.low_mod_m_done>
00000112 <adler32_x16_v6.carry_low>:
112: 29 df sub di,bx
00000114 <adler32_x16_v6.low_mod_m_done>:
114: 01 fa add dx,di # high+=low
116: 0f 92 d0 setb al # store the carry to set up a 32bit dividend.
119: 92 xchg dx,ax
11a: f7 f3 div bx # high (including carry) %= m, in dx. ax=0 or 1 (so we're set for lods next iteration)
11c: e2 eb loop 109 <adler32_x16_v6.byteloop>
11e: 97 xchg di,ax #
11f: c3 ret
00000120 <adler32_x16_v6_end>:
```
0x120 - 0x100 = 32 bytes
Tested by assembling the same code for 32bit mode, so I can call it (with a wrapper function) from C compiled with `-m32`. For me, 16bit mode is somewhat interesting, DOS system calls are not. All the instructions have explicit operands, except `loop` and `lodsb`, so assembling for 32bit mode uses operand-size prefixes. Same instruction, different encoding. But `lodsb` in 32bit mode will use `[esi]`, so this for-testing version works with 32bit pointers (because we don't do any address-math or pointer increment/compare).
No mismatches. My test harness prints a message if there is a mismatch.
```
$ yasm -felf32 -Worphan-labels -gdwarf2 adler32-x86-16.asm -o adler32-x86-16+32.o &&
g++ -DTEST_16BIT -m32 -std=gnu++11 -O1 -g -Wall -Wextra -o test-adler32-x16 adler32-x86-16+32.o test-adler32.cpp -lz &&
./test-adler32-x16
Eagles are great! (len=17): zlib:0x36c405fe c:0x36c405fe golfed:0x36c405fe
Programming Puzzles & Code Golf (len=31): zlib:0xbac00b2a c:0xbac00b2a golfed:0xbac00b2a
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (len=32): zlib:0x040f0fc1 c:0x040f0fc1 golfed:0x040f0fc1
?????????????????????????????????????????????????? (len=1040): zlib:0x82000000 c:0x82000000 golfed:0x82000000
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (len=4096): zlib:0xb169e06a c:0xb169e06a golfed:0xb169e06a
(0xFF repeating) (len=4096): zlib:0x8161f0e2 c:0x8161f0e2 golfed:0x8161f0e2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (len=5837): zlib:0x5d2a398c c:0x5d2a398c golfed:0x5d2a398c
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (len=5838): zlib:0x97343a0a c:0x97343a0a golfed:0x97343a0a
(0xFF repeating) (len=9999): zlib:0xcae9ea2c c:0xcae9ea2c golfed:0xcae9ea2c
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (len=65535): zlib:0x33bc06e5 c:0x33bc06e5 golfed:0x33bc06e5
```
---
With 16bit registers, we can't defer modulo reduction until after the loop. There's an interesting difference between 16bit and other operand-sizes: `m = 65521` (`0xFFF1`) is more than half 65536. Subtracting `m` on carry keeps the value below 2\*m, even if `high=0xFFF0 + 0xFFF0`. After the loop, a compare-and-subtract will do the trick, instead of a `div`.
I came up with a **novel technique for modulo-reducing a register after an add that can produce a carry**. Instead of zeroing the upper half of the input for `div`, use `setc dl` to create a 32bit dividend holding the non-truncated add result (`dh` is already zeroed). ([`div`](http://www.felixcloutier.com/x86/DIV.html) does 32b / 16b => 16bit division.)
`setcc` (3 bytes) was introduced with 386. To run this on 286 or earlier, the best I've come up with uses the [undocumented `salc` instruction (set AL from carry)](http://www.rcollins.org/secrets/opcodes/SALC.html). It's a one-byte opcode for `sbb al,al`, so we could use `salc` / `neg al` before doing the `xchg ax, dx` (which we need anyway). Without `salc`, there's a 4B sequence: `sbb dx,dx` / `neg dx`. We can't use 3B `sbb dx,dx` / `inc dx`, because that would emulate `setnc` rather than `setc`.
---
I tried **using 32bit operand-size** instead of handling carry, but it's not just the `add` instructions that need an operand-size prefix. Instructions setting up the constants and so on also need operand-size prefixes, so it ended up not being the smallest.
[Answer]
# Pyth, ~~25~~ ~~24~~ 23 bytes
*1 byte thanks to [@Jakube](https://codegolf.stackexchange.com/users/29577/jakube).*
*1 more byte thanks to [@Jakube](https://codegolf.stackexchange.com/users/29577/jakube).*
```
i%R65521sMeBhMsM._Q^4 8
```
[Try it online!](http://pyth.herokuapp.com/?code=i%25R65521sMeBmhsd._Q%5E4+8&input=%5B80%2C+114%2C+111%2C+103%2C+114%2C+97%2C+109%2C+109%2C+105%2C+110%2C+103%2C+32%2C+80%2C+117%2C+122%2C+122%2C+108%2C+101%2C+115%2C+32%2C+38%2C+32%2C+67%2C+111%2C+100%2C+101%2C+32%2C+71%2C+111%2C+108%2C+102%5D&debug=0)
Translation of my [answer in Jelly](https://codegolf.stackexchange.com/a/78898/48934).
[Answer]
# Perl 5, 43 bytes
42 bytes, plus 1 for `-aE` instead of `-e`
Input is as decimal integers, space-separated.
```
map$h+=$.+=$_,@F;say$.%65521+$h%65521*4**8
```
A tip of my hat to [Sp3000](/a/79025), from whom I took ideas for this answer.
How it works:
1. Because of [`-a`](http://perldoc.perl.org/perlrun.html#Command-Switches), [`$.`](http://perldoc.perl.org/perlvar.html#Variables-related-to-filehandles) starts at 1 and `@F` is the input array. `$h` starts at 0. `$_` is used by `map` as a placeholder for each element of an array.
2. `map$h+=$.+=$_,@F` means that for each element in `@F` we add that element to `$.` and then add `$.` to `$h`.
3. Then we do the modular arithmetic `$.%65521+$h%65521*4**8` (that is, `($. % 65521) + ( ($h % 65521) * (4**8) )` and `say` (print) the result.
[Answer]
# Factor, ~~112~~ ~~109~~ 103 bytes
**Now**, this is a literal translation of the algorithm in the question... now that I actually made it, y'know, correct.
```
[ [ sum 1 + ] [ [ dup length [1,b] reverse v. ] [ length ] bi + ] bi [ 65521 mod ] bi@ 16 shift bitor ]
```
Ungolfed:
```
: adler-32 ( seq -- n )
[ sum 1 + ]
[
[ dup length [1,b] reverse v. ]
[ length ] bi +
] bi
[ 65521 mod ] bi@
16 shift bitor
;
```
Expects any sequence of numbers or a string (not much difference, though they aren't technically the same).
I don't know how this will perform for the given limit on a version of Factor compiled with 32-bit word-size, but on my 6GB 64-bit 2.2GHz machine:
```
IN: scratchpad 1040 63 <array>
--- Data stack:
{ 63 63 63 63 63 63 63 63 63 63 63 63 63 63 ~1026 more~ }
IN: scratchpad [ adler-32 ] time
Running time: 7.326900000000001e-05 seconds
--- Data stack:
2181038080
IN: scratchpad 10,000 63 <array>
--- Data stack:
2181038080
{ 63 63 63 63 63 63 63 63 63 63 63 63 63 63 ~9986 more~ }
IN: scratchpad [ adler-32 ] time
Running time: 0.000531669 seconds
```
[Answer]
# Ruby, 91 bytes
```
->s{b=s.bytes;z=i=b.size
b.inject(1,:+)%65521+b.map{|e|e*(1+i-=1)}.inject(z,:+)%65521*4**8}
```
[Answer]
# Clojure, 109 bytes
Based on @Mark Adler's [solution](https://codegolf.stackexchange.com/questions/78896/compute-the-adler-32-checksum/78901#78901).
```
(fn f[s](->> s(reduce #(mapv + %(repeat %2)[0(first %)])[1 0])(map #(rem % 65521))(map *[1 65536])(apply +)))
```
### Ungolfed
```
(fn f [s]
(->> s
(reduce #(mapv + % (repeat %2) [0 (first %)]) [1 0])
(map #(rem % 65521))
(map * [1 65536])
(apply +)))
```
## Usage
```
=> (def f (fn f[s](->> s(reduce #(mapv + %(repeat %2)[0(first %)])[1 0])(map #(rem % 65521))(map *[1 65536])(apply +))))
=> (f [69 97 103 108 101 115 32 97 114 101 32 103 114 101 97 116 33])
918816254
=> (f [80 114 111 103 114 97 109 109 105 110 103 32 80 117 122 122 108 101 115 32 38 32 67 111 100 101 32 71 111 108 102])
3133147946
=> (f (repeat 32 126))
68095937
=> (f (repeat 1040 63))
2181038080
=> (f (repeat 4096 255))
2170679522
```
[Answer]
### Javascript (130 Characters Golfed)
## Ungolfed
```
function a(b)
{
c=1
for(i=0;i<b.length;i++)
{
c+=b[i]
}
d=c%65521
f=""
e=0
k=""
for(j=0;j<b.length;j++)
{
k+= "+"+b[j]
f+= "(1"+k+")"
e= ((eval(f)))
if(j!=b.length-1){f+="+"}
}
g=e%65521
h=d+65536*g
console.log(h)
}
```
## Golfed
```
a=b=>{for(c=1,k=f="",y=b.length,i=0;i<y;i++)c+=x=b[i],f+="(1"+(k+="+"+x)+")",i<y-1&&(f+="+");return z=65521,c%z+65536*(eval(f)%z)}
```
Paste into Developers Console and then give it an Array of Bytes
EG:
##
```
[69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
```
And it will return the checksum to the console
[Answer]
# TMP, 55 bytes
`3a1.3b0.1;4+a>T8%a>xFFF14+b>a8%b>xFFF11~5<b>164|b>a2$b$`
Implementation in Lua can be found here: <http://preview.ccode.gq/projects/TMP.lua>
[Answer]
# Python 3.5, 82 bytes:
(*-1 byte thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!*)
(*-1 byte thanks to [mathmandan](https://codegolf.stackexchange.com/users/36885/mathmandan)!*)
(*-4 bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)!*)
```
lambda w:((1+sum(w))%65521)+4**8*(sum(1+sum(w[:i+1])for i in range(len(w)))%65521)
```
An anonymous `lambda` function. Accepts a byte array, applies the entire algorithm to the array, and outputs the result. Has successfully worked for all the test cases. You call this by assigning a variable to it, and then calling that variable just like you would call a normal function. If you are using the shell, then this should output without a print function. However, if you are not, then you must wrap the function call in the `print()` function to actually see the output.
[Try it online! (Ideone)](http://ideone.com/sQ0UFd)
[Answer]
# [Fission](https://esolangs.org/wiki/Fission), 324 bytes
```
/ M
R_MZ |S
D ] |S
/?V?\} {}/ |S / \
R{/A Z$[/ |S/ {\
} J{\ |S ;_
\^ / |S R'~++Y++~'L
/ / |S }Y;
\ \ ;^/
/ / +\+ R'~++A++~'L
\ <Z________________/
;\X //
\Y/
*
```
*Fair warning, the only implementation I've tested this on is my own port of the language to F#. It's not golfed, mainly because I found it easier to have a couple of long runs while my prime constant cooled along the bottom, so I may come back and tweak it.*
How does it work?
* The `R'~++Y++~'L` block fuses a 256 constant and launches it downwards, setting the mass multiplier of the reactor directly below it.
* The `R'~++A++~'A` block fuses another 256 and launches it up towards the reactor above, which fissions the particle into two mass multiples of `65536` mass each, launching them left and right (where the right particle is immediately destroyed by the terminator).
* The left particle hits another reactor and undergoes fission, splitting into two particles of equal mass heading up and down.
* The upward travelling power-of-two particle passes through a net-zero mass manipulation, reflects to the left, then sets the mass multiplier of the fusion reactor. This reactor will be how we multiply the H block.
* The downward travelling particle reflects to the left and sheds mass over the long run, ultimately reaching a mass of `65521` (our large prime).
* The rotational mirror (`Z`) at the end of the run causes the particle to duplicate the prime, sending one back to the right where it ultimately sets the stored mass of the fission reactor (`^`). This is how we'll be applying the modulus operator to the H block.
* The second copy is reflected back, where it performs an analogous function for the fission reactor (`<`) we'll be using for the L block.
* Now that our constants are in place, we engage in shenanigans in the upper left to read our input and generate our two lists. To be honest, I forget how those work, but for the empty string I had to slow down the H block summing particle, which explains the `|S` "cooling tower".
* `\Y/` fuses the L block (which comes in through the left channel) and the H block (which comes in through the right channel), then slams them into a terminator which sets the exit code to the fused mass.
] |
[Question]
[
# Introduction
This is a very simple challenge: simply count the divisors of a number. We've had a [similar but more complicated challenge](https://codegolf.stackexchange.com/questions/11080/give-the-smallest-number-that-has-n-divisors) before, but I'm intending this one to be entry-level.
# The Challenge
Create a program or function that, given one strictly positive integer `N`, outputs or returns how many divisors it has, including 1 and `N`.
Input: One integer > 0. You may assume that the number can be represented in your language's native numeric type.
Output: The number of positive integer divisors it has, including 1 and the number itself.
Submissions will be scored in **bytes**. You may find [this website](http://bytesizematters.com) handy, though you may use any reasonable method for generating your byte count.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score wins!
**Edit:** It looks like FryAmTheEggman's 5-byte Pyth answer is the winner! Feel free to submit new answers, though; if you can get something shorter, I'll change the accepted answer.
# Test Cases
```
ndiv(1) -> 1
ndiv(2) -> 2
ndiv(12) -> 6
ndiv(30) -> 8
ndiv(60) -> 12
ndiv(97) -> 2
ndiv(100) -> 9
```
# Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=64944,OVERRIDE_USER=45162;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Pyth, 5
```
l{yPQ
```
Uses the subsets operation on the prime factors of the input, then keeps only the unique lists of factors and returns this count.
[Test Suite](http://pyth.herokuapp.com/?code=l%7ByPQ&input=100&test_suite=1&test_suite_input=1%0A2%0A12%0A30%0A60%0A97%0A100&debug=0)
### Explanation
Using 25 as an example, so that the subset list isn't very long
```
l{yPQ ## implicit: Q = eval(input()) so Q == 25
PQ ## Prime factors of Q, giving [5, 5]
y ## All subsets, giving [[], [5], [5], [5, 5]]
{ ## Unique-fiy, giving [[], [5], [5, 5]]
l ## Length, print implicity
```
[Answer]
# ~~C++~~ C, ~~43~~ ~~57~~ ~~56~~ ~~46~~ 43 bytes
On Martin Büttner's suggestions :
```
i,c;f(n){for(i=c=n;i;n%i--&&--c);return c;}
```
[Answer]
## LabVIEW, 4938 Bytes
Well its obviously not suited for code golf but whatever, so for my first post and the lolz here goes. [![enter image description here](https://i.stack.imgur.com/picvL.jpg)](https://i.stack.imgur.com/picvL.jpg)
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes
```
f n=sum[0^mod n i|i<-[1..n]]
```
[Try it online!](https://tio.run/##FckxDoAgEATAr2xhC0FreQnBhKDoRTiJaOfbPeO0s4W2LzmLJLBtd3FmKscMBj00Ktdrzd5LCcSwqCfxhQ4lVCT8ORgvb0w5rE1UrPUD "Haskell – Try It Online")
The trick here is to test whether a remainder is `0` using the indicator function `0^`.
```
0^0 = 1
0^_ = 0
```
This works because any positive power of 0 is 0, whereas 0^0 is combinatorially the empty product of 1.
Compare this to filtering
```
f n=sum[1|i<-[1..n],mod n i<1]
```
---
**28 bytes**
```
f n=sum[1|0<-mod n<$>[1..n]]
```
[Try it online!](https://tio.run/##FckxDoAgDADAr3RghYCz@BHCQFCUSGsjuvl2a7z1ttT3pTWRAuT7jcE9dtR4zECjmoIzhmIUTJXAA5@VLlCAiaHAn4ON8ubS0tpFZ@YP "Haskell – Try It Online")
An alternative method using matching on a constant. The `<$>` infix `map` might postdate this challenge.
[Answer]
## Python 2, 37 bytes
```
f=lambda n,i=1:i/n or(n%i<1)+f(n,i+1)
```
A recursive function. The optional input `i` in the divisor being tested. The expression `(n%i<1)` tests divisibility, with `True` (which equals `1`) for divisors. The result is added to the recusive expression for `i+1`. When `i==n` is reached, the integer floor-division `i/n` evaluates to `1`, and that value is returned as the base case, accounting for `n` itself being a divisor of `n`.
---
**38:**
```
lambda n:sum(n%-~i<1for i in range(n))
```
An anonymous function. Tests all possible divisors `1` through `n`. This is shifted up from `0` through `n-1` in `range(n)` using `-~`, which adds `1`. Summing the bools uses the fact that Python treats `True`/`False` as `1`/`0`.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~7~~ 6 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
≢∘∪⊢∨⍳
```
It is an unnamed function that can be named and then reused for each (`¨`) test case as follows:
```
f ← ≢∘∪⊢∨⍳
f¨ 1 2 12 30 60 97 100
1 2 6 8 12 2 9
```
Explanation:
```
┌─┴──┐
∪ ┌─┼─┐
∘ │ ∨ │
̸≡ ⊢ ⍳
```
Count `≢` the `∘` unique `∪` of the GCD `∨` of itself `⊢` and each of the integers-until `⍳`.
Thanks to ngn for saving a byte.
---
Old version: `+/0=⍳|⊢`
This is how it works:
```
┌─┴─┐
/ ┌─┼───┐
┌─┘ 0 = ┌─┼─┐
+ ⍳ | ⊢
```
`⍳|⊢` 1-through-argument division-remainder argument
`0=` Boolean if 0 is equal to the division rest
`+/` Sum of the boolean, i.e. count of ones.
[Answer]
## [Retina](https://github.com/mbuettner/retina), 17 bytes
```
(?<=(.+))(?=\1*$)
```
[Input in unary](https://codegolf.meta.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary), output in decimal.
[Try it online.](http://retina.tryitonline.net/#code=KD88PSguKykpKD89XDEqJCk&input=MTExMTExMTExMTEx)
When invoked with a single regex, Retina simply counts the matches. The regex itself matches a *position*, where the unary number to the left of it is a divisor of the entire input. I'm also making use of the fact that lookarounds are atomic, so that I don't need to use a `^` anchor.
The first lookbehinds simply captures the entire prefix in group `1`. This can never fail, so after the lookbehind we know that's what's in group 1 and it won't change any more.
The lookahead then checks if we can reach the end of the string by repeating the captured string (our potential divisor) 0 or more times.
[Answer]
# J, 10 bytes
```
[:*/1+_&q:
```
This is an unnamed, monadic verb. It calculates **σ0(∏pkαk)** as **∏(αk + 1)**.
Try it online with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%20%5B%3A*%2F1%2B_%26q%3A%20)%20each%201%202%2012%2030%2060%2097%20100).
### How it works
```
[:*/1+_&q: Right argument: y
_&q: Compute all exponents of the prime factorization of y.
1+ Add 1 to each exponent.
[:*/ Reduce by mutiplication.
```
[Answer]
# Golfscript, ~~19~~ ~~18~~ ~~17~~ 13 bytes
With thanks to [Martin Büttner](http://chat.stackexchange.com/users/112128).
```
~.,\{\)%!}+,,
```
### How it works
```
~ Evaluate the input, n
., Duplicate the input, create array [0..n-1]
\ Swap array and n
{ }+ Add n to block == {n block}
\ Swap n with i in array
) Increment i
% n mod i
! Logical not so that 1 if divisible by n else 0
, Filter array using block for all i divisible by n
, Get length of the filtered array, the answer
```
### Also
From [@Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor), also in 13 bytes.
```
~:X,{)X\%!},,
```
### How it works
```
~ Evaluate the input
:X Store input in variable X
, Create array [0..X-1]
{ }, Filter array using the following block
) Increment i in array
X\ Add X to stack, swap with i
% X mod i,
! Logical not so that 1 if divisible by n else 0
, Get length of the filtered array, the answer
```
[Answer]
# Julia, 20 bytes
```
n->sum(i->n%i<1,1:n)
```
This is an anonymous function that works as follows: For each integer from 1 to the input, test whether the input modulo the integer is zero. If so, the value will be `true`, otherwise `false`. We sum over the booleans which are implicitly cast to integers, yielding the number of divisors.
---
A much cooler (though also much longer) solution, included for the sake of completeness, is
```
n->prod(collect(values(factor(n))).+1)
```
This gets the canonical factorization of `n`, i.e. `\prod_{i=1}^k p_i^e_i`, and computes the divisor function as `τ(n) = \prod_{i=1}^k e_i + 1`.
[Answer]
# J, ~~13~~ ~~12~~ 11 bytes
My first golf in J. I'm still learning it.
Saved a byte thanks to Dennis.
Saved one more byte thanks to randomra.
```
1+/@,0=i.|]
```
Explanation:
```
1+/@,0=i.|]
i. the array 0 .. n-1
|] mod n
0= replace 0 by 1, and nonzero entries by 0
1 , prepend 1 to the array
+/@ take the sum
```
[Answer]
# [Arcyóu](https://github.com/nazek42/arcyou), 12 bytes
Let's get the party started!
```
(F(x)(_(d/ x
```
This uses the built-in function `d/`. Here's a version without the built-in (27 bytes):
```
(F(x)(](+(f i(_ 1 x)(‰ x i
```
Explanation:
```
(F(x) ; Anonymous function with one parameter x
(] ; Increment
(+ ; Sum
(f i(_ 1 x) ; For i in range from 1 to x-1 inclusive:
(‰ x i ; x divisible by i
```
[Answer]
## CJam, 11 bytes
```
ri_,:)f%0e=
```
[Test it here.](http://cjam.aditsu.net/#code=q~_%2C%3A)f%250e%3D&input=12)
### Explanation
CJam doesn't have a built-in for this, so we're doing trial division.
```
ri e# Read input and convert to integer N.
_, e# Duplicate and turn into range [0 1 ... N-1]
:) e# Increment each element in the range to get [1 2 ... N]
f% e# Take N modulo each of the list elements.
0e= e# Count the zeroes.
```
### Bonus
Here is an interesting solution at 12 bytes (which I suspect might be shortest in a language like J):
```
ri_)2m*::*e=
```
The result is equal to the number of times `n` appears in an `n x n` multiplication table:
```
ri e# Read input and convert to integer N.
_) e# Duplicate and increment.
2m* e# Take Cartesian product of [0 1 ... N] with itself.
::* e# Compute the product of each pair.
e= e# Count the occurrences of N.
```
[Answer]
# Matlab, 20 bytes
Perform `k mod n` for every `k = 1,...,n`, then perform `not` (which turns every nonzer to zero and every zero to 1) and sum up all those values.
```
@(n)sum(~mod(n,1:n))
```
[Answer]
# Excel Formula, ~~42~~ 28 bytes
Edit: I just realised I do not need to use `INDIRECT`, saving 14 bytes!
The following should be entered as an array formula (`Ctrl`+`Shift`+`Enter`):
```
=SUM(--NOT(MOD(N,ROW(1:N))))
```
Where N is the number to test.
**Examples:**
```
{SUM(--NOT(MOD(32,ROW(1:32))))}
Result: 6
{SUM(--NOT(MOD(144,ROW(1:144))))}
Result: 15
```
**Explanation:**
```
SUM(--NOT(MOD(N,ROW(1:N)))) Full formula
ROW(1:N) Generates an array of row numbers e.g {1;2;3;4;...N}
MOD(N,ROW(1:N)) Does N MOD {1;2;3;4;,...N}
NOT(MOD(N,ROW(1:N))) Coerces zeros to ones, so that they may be counted, but actually returns an array of TRUE;FALSE;FALSE;...
--NOT(MOD(N,ROW(1:N))) Coerces the TRUEs to 1s and FALSEs to 0s.
SUM(--NOT(MOD(N,ROW(1:N)))) Sum the ones for the result.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ñg
```
[Try it online](https://tio.run/##yy9OTMpM/f//8MT0//8NDQwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/wxPT/@v8jzbUMdIxNNIxNtAxM9CxNNcxNDCIBQA).
**Explanation:**
Pretty straight-forward, but here it is anyway:
```
Ñ # Push a list of divisors of the (implicit) input-integer
# i.e. 100 → [1,2,4,5,10,20,25,50,100]
g # Pop and push the length of this list
# i.e. [1,2,4,5,10,20,25,50,100] → 9
# (which is output implicitly as result)
```
[Answer]
# [Jelly](//github.com/DennisMitchell/jelly), 2 bytes
```
Æd
```
[Try it online!](//jelly.tryitonline.net#code=w4Zk&args=NjA)
I *think* this uses features implemented after the other Jelly answer. Comment if I'm wrong though (I can't look each commit in the row, you know :))
[Answer]
# PARI/GP, 6 bytes
PARI/GP have a built-in for this.
```
numdiv
```
[Answer]
# Pyth, 8 bytes
Simple trial division.
```
lf!%QTSQ
```
[Try it online here](http://pyth.herokuapp.com/?code=lf%21%25QTSQ&input=12&test_suite=1&test_suite_input=1%0A2%0A12%0A30%0A60%0A97%0A100&debug=0).
[Answer]
# Ruby, 27 bytes
```
->n{(1..n).count{|i|n%i<1}}
```
Sample run:
```
2.1.5 :001 > ->n{(1..n).count{|i|n%i<1}}[100]
=> 9
```
[Answer]
# Octave, ~~21~~ 20 bytes
```
@(n)nnz(~mod(n,1:n))
```
[Answer]
# Regex (.NET), 33 bytes
```
^((?=.*$(?<=^\2*(.+?(?>\2?)))).)+
```
Assuming input and output are in unary, and the output is taken from the main match of the regex.
Break down of the regex:
* `.*$` ets the pointer to the end of the string so that we have the whole input x in one direction.
* `(?<=^\2*(.+?(?>\2?)))` matches from right to left and checks for divisor by looping from x to 0.
+ `(.+?(?>\2?))` is a "variable" which starts from 1 in the first iteration and continues from the number in previous iteration and loops up to x.
+ `^\2*` checks whether x is a multiple of "variable".
It basically has the same idea as my answer to [Calculate Phi (not Pi)](https://codegolf.stackexchange.com/questions/63710/calculate-phi-not-pi/63738#63738). Only the check is different.
Test the regex at [RegexStorm](http://regexstorm.net/tester).
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 33 bytes
```
?:}
:{:}%{{
@ } " )
!{("{;"}}
```
[Try it online.](http://labyrinth.tryitonline.net/#code=Pzp9CiAgOns6fSV7ewpAIH0gICAiICkKIXsoIns7In19&input=MTI)
This implements trial division. I'll add a full explanation later. It's probably not optimal, but I'm having a hard time coming up with something shorter.
[Answer]
## [Perl 6](http://perl6.org), 17 bytes
```
{[+] $_ X%%1..$_} # 17
```
usage:
```
say {[+] $_ X%%1..$_}(60); # 12
my $code = {[+] $_ X%%1..$_};
say $code(97); # 2
my &code = $code;
say code 92; # 6
```
[Answer]
# Javascript (ES6), ~~60~~ ~~57~~ ~~42~~ ~~40~~ ~~39~~ 37 bytes
This can probably be golfed better.
```
n=>{for(d=i=n;i;n%i--&&d--);return d}
```
**Edit 1:** I was right. Removed the braces after the for loop.
**Edit 2:** Golfed to 40 bytes with thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) and [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner).
**Edit 3:** Saving a byte by basing the function on [the C answer above.](https://codegolf.stackexchange.com/a/64978/47581)
**Edit 4:** Thanks to [ןnɟuɐɯɹɐןoɯ](https://codegolf.stackexchange.com/users/41247/%D7%9Fn%C9%9Fu%C9%90%C9%AF%C9%B9%C9%90%D7%9Fo%C9%AF) and [Neil](https://codegolf.stackexchange.com/users/17602/neil), but I can't get the eval to work.
**Edit 5:** Forgot to remove the eval.
### Test
```
n = <input type="number" oninput='result.innerHTML=(
n=>{for(d=i=n;i;n%i--&&d--);return d}
)(+this.value)' /><pre id="result"></pre>
```
[Answer]
# PowerShell, 34 bytes
```
param($x)(1..$x|?{!($x%$_)}).Count
e.g.
PS C:\temp> .\divisors-of-x.ps1 97
2
```
* create a list of numbers from 1 to x, feed them into the pipeline `|`
* filter the pipeline on (x % item == 0), by implicitly casting the modulo result as a boolean and then inverting it using `!` so divisors become $true and are allowed through; using the builtin alias `?` for `Where-Object`
* gather up `()` and `.Count` how many items got through the filter
[Answer]
# Taxi, 2143 bytes
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to Cyclone.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 r.Go to Cyclone:n 1 l.Pickup a passenger going to Firemouth Grill.Pickup a passenger going to Joyless Park.Go to Firemouth Grill:s 1 l 2 l 1 r.Go to Joyless Park:e 1 l 3 r.[i][Check next value n-i]Go to Zoom Zoom:w 1 r 2 l 2 r.Go to Sunny Skies Park:w 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Sunny Skies Park.Go to Joyless Park:n 2 r 2 r 2 l.Pickup a passenger going to Cyclone.Go to Sunny Skies Park:w 1 r 2 l 2 l 1 l.Go to Cyclone:n 1 l.Pickup a passenger going to Joyless Park.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 1 l 2 l.Pickup a passenger going to Trunkers.Pickup a passenger going to Equal's Corner.Go to Trunkers:s 1 l.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan "F" if no one is waiting.Pickup a passenger going to Knots Landing.Go to Firemouth Grill:n 3 r 1 l 1 r.Pickup a passenger going to The Underground.Go to The Underground:e 1 l.Pickup a passenger going to Firemouth Grill.Go to Knots Landing:n 2 r.Go to Firemouth Grill:w 1 l 2 r.Go to Joyless Park:e 1 l 3 r.Switch to plan "N".[F][Value not a divisor]Go to Joyless Park:n 3 r 1 r 2 l 4 r.[N]Pickup a passenger going to The Underground.Go to The Underground:w 1 l.Switch to plan "E" if no one is waiting.Pickup a passenger going to Joyless Park.Go to Joyless Park:n 1 r.Switch to plan "i".[E]Go to Sunny Skies Park:n 3 l 2 l 1 l.Pickup a passenger going to What's The Difference.Go to Firemouth Grill:s 1 l 1 l 1 r.Pickup a passenger going to What's The Difference.Go to What's The Difference:w 1 l 1 r 2 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 3 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.
```
[Try it online!](https://tio.run/nexus/taxi#rVZNj5swEP0ro1x6Ktpke8qx2WSlttpGSj@kRhxcGIKFd5y1zdL8@tTGbAqEdUPaAyDsmeeZNzMPjvcSjIS11AY@ZxlPcF7BFIS9lHtGa54U5R4Y7JnWSDtUsJOcds7rS47wnv1EkXGdozpEHqy/PNcviEG0xSERkrABad7m1PgKmF3oH7LZlEQH2BQcNayZKprD@sv1qWookiD6iit8lKXJ4V5xEbb9IA8CdSeKnntD26yhztu03eZYG9zazS2Pt4sckwIIfxl4ZqJEoLc89l4/pHysb3VxVY05O2GeZV85g2trFfS74888RWCUwkLSU4nqmnJ1SCCXSXONCXog6z/U1B03OrtOTUfS4M8632jld90AYWuA/jLOqqQClQ4aLZ9KJt5oG56iU9gvnr5lx/t3F70CRZuKmyR323vBCCarCfAMSILNCriGinFjQYOnfSRpNHyyfDrL4TEjN0EXKZQTtq@UotopWVLakrvWqid8lE54nE6svuyvRFyd9DAoCn0CHybRdhVvv3lxkMYGl9p@01LFg3PlafEj8c6JzEP87@wM13Z5RW0HFLSXwHSABG5JWMavyv5ta/xDh3/PmbEN67K741mGCinBoI5f0mAh1MG91sd69h8/2Fj3Twip9cMQnf9C0Cnb43F6c/Mb)
Ungolfed:
```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left 2nd right.
Pickup a passenger going to Cyclone.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 1st right.
Go to Cyclone: north 1st left.
Pickup a passenger going to Firemouth Grill.
Pickup a passenger going to Joyless Park.
Go to Firemouth Grill: south 1st left 2nd left 1st right.
Go to Joyless Park: east 1st left 3rd right.
[i]
[Check next value n-i]
Go to Zoom Zoom: west 1st right 2nd left 2nd right.
Go to Sunny Skies Park: west 2nd left.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Sunny Skies Park.
Go to Joyless Park: north 2nd right 2nd right 2nd left.
Pickup a passenger going to Cyclone.
Go to Sunny Skies Park: west 1st right 2nd left 2nd left 1st left.
Go to Cyclone: north 1st left.
Pickup a passenger going to Joyless Park.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer: north 2nd right 2nd right 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st left 1st left 2nd left.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Equal's Corner.
Go to Trunkers: south 1st left.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: west 1st left.
Switch to plan "F" if no one is waiting.
Pickup a passenger going to Knots Landing.
Go to Firemouth Grill: north 3rd right 1st left 1st right.
Pickup a passenger going to The Underground.
Go to The Underground: east 1st left.
Pickup a passenger going to Firemouth Grill.
Go to Knots Landing: north 2nd right.
Go to Firemouth Grill: west 1st left 2nd right.
Go to Joyless Park: east 1st left 3rd right.
Switch to plan "N".
[F]
[Value not a divisor]
Go to Joyless Park: north 3rd right 1st right 2nd left 4th right.
[N]
Pickup a passenger going to The Underground.
Go to The Underground: west 1st left.
Switch to plan "E" if no one is waiting.
Pickup a passenger going to Joyless Park.
Go to Joyless Park: north 1st right.
Switch to plan "i".
[E]
Go to Sunny Skies Park: north 3rd left 2nd left 1st left.
Pickup a passenger going to What's The Difference.
Go to Firemouth Grill: south 1st left 1st left 1st right.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: west 1st left 1st right 2nd right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: east 3rd right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.
```
Explanation:
```
Convert stdin to a number and store it in three locations for three purposes:
Original (Sunny Skies Park)
Counter for tested values (Joyless Park)
Counter for divisors found (Firemouth Grill)
Divide the original by each Joyless Park value in turn.
If the division result equals the truncated division result, then it's a divisor.
When a divisor is found, subtract one from Firemouth Grill.
Repeat until Joyless Park hits zero.
Pickup the original from Sunny Skies Park and subtract the value from Firemouth Grill.
Convert the result to a string and print to stdout.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 bytes
```
â l
```
`-m` flag is for running all the test cases.
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=4iBs&input=WzEsCjIsCjEyLAozMCwKNjAsCjk3LAoxMDBd)
[Answer]
# TI-BASIC, 14 bytes
```
sum(not(fPart(Ans/cumSum(binomcdf(Ans-1,0
```
Input is in `Ans`.
Output is in `Ans` and is implicitly printed.
This submission will only work for \$1<N<1000\$ due to limitations in the TI calculators.
**Examples:**
```
25
25
prgmCDGF14
3
100
100
prgmCDGF14
9
```
**Explanation:**
```
sum(not(fPart(Ans/cumSum(binomcdf(Ans-1,0 ;full program
binomcdf(Ans-1,0 ;generate a list of 1s whose length is the input
cumSum( ;calculate the cumulative sum
Ans/ ;divide the input by each term
fPart( ;get the fractional part of each element
not( ;logically negate each term
; 0 becomes 1
; everything else becomes 0
sum( ;sum the list
;implicit print of "Ans"
```
---
If the above submission does not suffice, then the following **24 byte** submission also works for \$0<N<10^{100}\$
```
Ans→N:0:For(I,1,N:Ans+not(fPart(N/I:End:Ans
```
**Examples:**
```
25
25
prgmCDGF14
3
100
100
prgmCDGF14
9
```
**Explanation:**
```
Ans→N:0:For(I,1,N:Ans+not(fPart(N/I:End:Ans ;full program
Ans→N ;store the input in "N"
0 ;leave 0 in "Ans"
For(I,1,N End ;loop over all integers in [1,N]
Ans+not(fPart(N/I ;increment "Ans" if the current "I"
; is a factor of "N"
Ans ;leave "Ans" as the last expression
;implicit print of "Ans"
```
---
**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 3 bytes
```
Lz$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/36dK5f9/QyMA "cQuents – Try It Online")
## Explanation
```
:Lz$
: (implicit) given input n, output nth term in sequence
each term in sequence equals:
L length ( )
z divisors ( )
$ index
```
] |
[Question]
[
Why should you golf in Haskell? [Find out here](https://codegolf.meta.stackexchange.com/a/10668/66833). In that answer, [Zgarb](https://codegolf.meta.stackexchange.com/users/32014/zgarb) defines a task:
>
> Let's define a function `f` that splits a list at the second occurrence of the first element, e.g. `[0,2,2,3,0,1,0,1] -> ([0,2,2,3],[0,1,0,1])`:
>
>
>
Alright then, lets!
You are to take a non-empty list consisting of digits, and output a **pair** of lists, clearly distinguished, such that the output is the input split before the second occurrence of the first element.
For example, you may output two strings of digits with a non-digit separator. The separator you choose between the elements of each pair and the pairs themselves must be distinct (e.g. space and newline), consistent and not contain digits.
The output must only contain **2** elements however. You may not output empty lists in the output. If you choose to use newlines as a separator between pairs, you may not have a leading newline. You may have trailing newlines no matter what, and you may have trailing whitespace, so long as its sensible.
You may assume:
* The input will be provided in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and you may output in any convenient method
* The input will either be a list of digits, or a string
* The input will only contain the integers `0` though to `9`
* The first element of the input will always occur at least twice
* The input will always have 3 or more elements in it
Additionally, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
## Test cases
```
[1, 1, 9] -> [[1], [1, 9]]
[4, 9, 4] -> [[4, 9], [4]]
[5, 7, 5, 5] -> [[5, 7], [5, 5]]
[8, 8, 0, 7] -> [[8], [8, 0, 7]]
[7, 1, 5, 7, 4, 2] -> [[7, 1, 5], [7, 4, 2]]
[0, 6, 9, 1, 1, 0, 2] -> [[0, 6, 9, 1, 1], [0, 2]]
[2, 9, 3, 2, 4, 2, 5, 9] -> [[2, 9, 3], [2, 4, 2, 5, 9]]
[0, 2, 2, 3, 0, 1, 0, 1] -> [[0, 2, 2, 3], [0, 1, 0, 1]]
[2, 7, 4, 6, 2, 6, 6, 4, 8, 2] -> [[2, 7, 4, 6], [2, 6, 6, 4, 8, 2]]
[8, 2, 2, 7, 5, 4, 7, 0, 8, 0, 7] -> [[8, 2, 2, 7, 5, 4, 7, 0], [8, 0, 7]]
[8, 7, 8, 9, 4, 2, 9, 4, 5, 7, 5, 1, 9] -> [[8, 7], [8, 9, 4, 2, 9, 4, 5, 7, 5, 1, 9]]
[3, 8, 1, 1, 7, 3, 6, 9, 7, 1, 4, 3, 4] -> [[3, 8, 1, 1, 7], [3, 6, 9, 7, 1, 4, 3, 4]]
[4, 7, 0, 5, 6, 5, 0, 1, 7, 8, 7, 8, 4, 1] -> [[4, 7, 0, 5, 6, 5, 0, 1, 7, 8, 7, 8], [4, 1]]
[2, 1, 8, 0, 3, 2, 2, 5, 7, 9, 4, 3, 5, 1, 9, 6, 9] -> [[2, 1, 8, 0, 3], [2, 2, 5, 7, 9, 4, 3, 5, 1, 9, 6, 9]]
[1, 1, 4, 1, 2, 5, 5, 3, 3, 4, 3, 2, 0, 8, 6, 0, 3] -> [[1], [1, 4, 1, 2, 5, 5, 3, 3, 4, 3, 2, 0, 8, 6, 0, 3]]
[4, 3, 5, 2, 2, 0, 6, 4, 8, 6, 6, 6, 7, 3, 4, 8, 7, 6] -> [[4, 3, 5, 2, 2, 0, 6], [4, 8, 6, 6, 6, 7, 3, 4, 8, 7, 6]]
```
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
f(x:y)=([x],0)*>span(/=x)y
```
[Try it online!](https://tio.run/##lZTJTsMwEIbvfYo5cEiQK7I4ziKFOyceIPIhElRULaGiHNKnD/YsDVmgQrKiZub77d8zk76158Pr8TgMu6CvLmEdNL1VUXj/eD61XfBQ9@FleG/3HVQVPD1DEG7wrYaXjw3A6XPffcEd7KCJFbhVWthuoWliqzBUWjvFtIsp0Iz5N0/qOZYpyBW4Z8akD3gSQzO4UOBW5AmCC09KaAbn6JP2d8cnLOGwF0piJnSbGTRPN41G7STjd4hW5AkSqcvQ9uhBysVJr52mlx4SXCkaIBvxaIOT7EHSSyd0RYO0waWxhsnohxG2NIWW9aeDqWUaf0SLpqxSf3SqQKKggUEl/bjOxo95K3g8btGzI1LcnxqaY1WpkTQNGiMyqxPWn/ULvRx4qkaGeCaNo6vRU49NvI3j97Le1lhqnkqt6faluOMykPGx16OO231Lade@fY1PkmYoSkWdyDwYPmb6L/Ef5bK85C4R9jqnRlYu@1EFjR2@AQ "Haskell – Try It Online")
Shortens [Zgarb's OG solution](https://codegolf.meta.stackexchange.com/a/10668/20260)
```
f(x:y)|(a,b)<-span(/=x)y=(x:a,b)
```
by prepending `x` to the first element of `(a,b)` in a pointfree way, that is without explicitly binding `(a,b)`.
It would be nice it we could do `(x:)<$>(a,b)`, but that gives `(a,x:b)` -- the Functor instance of tuples lets us act on the second element but not the first.
However, Applicative lets us combine tuples as:
```
(p, f) <*> (a, b) = (p++a, f b)
([x], id) <*> (a, b) = (x:a, b)
```
It suffices to use `*>` which ignores `f` and leaves `b` unchanged.
```
((x:), 0) *> (a, b) = (x:a, b)
```
The `0` could be anything -- it doesn't matter. It would also work to use `>>` in place of `*>`.
**26 bytes**
```
f(x:y)=([x],y)>>=span(/=x)
```
[Try it online!](https://tio.run/##lZTLboMwEEX3@YpZdAGSo/IwT4nsu@oHIC@Q2qhRUho1XZCvp/Y8Qg20USULhZlz7euZIW/d5fh6Oo3jPhjqa9gE7WDUNdztmsu564PHZgjH9@7QQ13D0zME4QbfGnj52ACcPw/9FzzAHtpYgV2Vge0W2jY2CkOVMT6mbUyBZsy9OVLPsUxBocA@MyZdwJEYmsGlArsiRxBcOlJCM7hAn7S/PT5hCYedUBIzod0sR/N002jSehm3Q7QiT5BIbYa2Rw9SLk46rZ9eekhwpWiAbMSTDU6yB0kvndAVc6RzXBprmEx@GGFLPrSsPx1MLdP4I1o0ZZX6o1MlEiUNDCrpx202fsxbyeNxj54dkeL@1NACq0qNpGnQGJFZ9Vh31i/0cuCpGhnimTSOrkZPPTXxPo7fy3pbY6l5KrWm21fijstAxqdeTzpu9z2lWfv2NT5JmqEoFXUi85DzMf6/xH@Uy/KSu0TY25zmsgrZjyqYm/Eb "Haskell – Try It Online")
A alternative, this time using the Monad instance and `(>>=) :: Monoid a => (a, a0) -> (a0 -> (a, b)) -> (a, b)`
**27 bytes**
```
f(x:y)=([x],[])<>span(/=x)y
```
[Try it online!](https://tio.run/##lZTJbsIwEIbvfYo59JBIps3iLCDg1EsPVR8g8iESRY0KCQIO8PSpPQtplhZVsiIy8/3275kJn@Xp62O3a6v9oTme4aU8l09vTd1UG/C85dr32613WVz9lVdcjCqMv1yfDmXtPa8u/rXdl1UNiwW8voPnP@DbCjbNA8DhWNVneIQtFKECu@YGZjMoitAoDM2N6WPaxhRoxtybI/UQSxRkCuwzYdIFHImhAZwrsCtwBMG5IyU0gDP0Sfvb4yOWcNgJJTEQ2s1SNE83DTptL@N2CCbkERKxzdD26EHKxUmn7afHHiJcMRogG2Fng5PsQdJjJ3TFFOkUl8YaRp0fRthSHxrXnw6mlmn8EYyaMkn90akciZwGBpX04zYbP@Yt5/G4Rw@OiHF/amiGVaVG0jRojMis9lh31i/0eOCpGgniiTSOrkZP3TXxPo7fy3RbQ6l5LLWm28/FHZeBjHe97nTc7ntKM/Xta3ySNEFRLOpI5iHlY/r/Ev9RjstL7iJhb3OayspkP6pgatpv "Haskell – Try It Online")
Using `<>` to do concatenate elementwise `(a, b) <> (c, d) = (a++c, b++d)`. This is available in Prelude without an import starting in version 8.4.1.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 17 14 bytes
```
sub(FS$1,RS$1)
```
[Try it online!](https://tio.run/##SyzP/v@/uDRJwy1YxVAnCEho/v9voWAEhOYKpgomQNJAwQKIzQE "AWK – Try It Online")
*Thanks to Pedro Maimere for the hint to lop off 3 bytes*
The interactions of the rules in the contest allow for pretty trivial AWK solution... Assuming the input can be a blank delimited string of numbers, this will work. If it has to include the brackets and commas (which I wasn't sure about from the linked article about convenient input), then it would be this instead.
```
sub(", "(a=substr($1,2)),"]\n["a)
```
And here's one in `><>` which might be shrinkable still... It's the first time I've managed to get something to work in that language, so I wouldn't be surprised to learn there some trick I don't know yet.
# [><>](https://esolangs.org/wiki/Fish), 41 bytes
```
i:o&0v
?(0:i<o$v?<=1:+{=&:&:;
0+1o+19< ^
```
[Try it online!](https://tio.run/##S8sszvj/P9MqX82gjMtew8Aq0yZfpczextbQSrvaVs1KzcqaS8FA2zBf29DSRiHu/38jYzNzQyNLYwsA "><> – Try It Online")
I can add a more detail description if anyone is interested, but here's an overview of how it works.
The input it expects is a string of digits. Since the challenge specified that the list was made up of single digit numbers, I chose not to include a delimiter. If that's a requirement, some additional stuff would have to be added...
The first line reads in the first number, uses it to set the register (for comparison as the rest of the list is read in), then pushes a counter that tracks the number of times the first number has been seen. Then it passed control down to the next line.
```
i:o&0v
```
That line reads one digit at a time, starting with the second digit, and prints it. There's a conditional code to add a `\n` when the counter hits `1` (meaning it found the second occurrence of the first digit). The code is interpreted right to left to save characters.
```
?(0:i<o$v?<=1:+{=&:&:;
```
The last line is effectively like a "function" call to print a linefeed and tweak the counter so that it will never be called again.
```
0+1o+19< ^
```
[Answer]
# Vim, 3 bytes/keystrokes
```
*O<esc>
```
Jump to next occurrence of word and make a new line.
---
# [V (vim)](https://github.com/DJMcMayhem/V), 2 bytes
```
*O
```
[Try it online!](https://tio.run/##K/v/X8v//39DLiMuYy5DLksgNgQA "V (vim) – Try It Online")
Since V has implicit escape after `O` (?), we can use just 2 bytes.
---
Old (general) 8-byter:
```
Y/<C-r>"<BS><CR>O<esc>
```
---
Input is each list item on a single line. Output is two lists separated by a blank line.
Uses vim notation for the keystrokes (`<C-r>` is `Ctrl`-`R`, *etc.*; see `:help key-notation`).
Explanation:
* `Y` yank the first line
* `/<C-r>"<BS><CR>` search for the next occurrence by inserting the yanked text into a search `/`. Yanking into the search register with `"/Y` doesn't work (`:help quote/`). The backspace deletes the line-ending, which is yanked. (Alternately, use `y$/<C-r>"<CR>`.)
* `O<esc>` new blank line above.
This generalizes to any type of list as long as each element is a single line.
---
I don't think we can use POSIX vi for this, since I don't think it has `<C-r>` to insert registers. It doesn't have the search register `"/`, but that doesn't end up mattering.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~18~~ 7 bytes
```
Ṙṫ:‟€vp
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%98%E1%B9%AB%3A%E2%80%9F%E2%82%ACvp&inputs=%5B7%2C%201%2C%205%2C%207%2C%204%2C%202%5D%20&header=&footer=)
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 11 bytes
```
{(2#*=x)_x}
```
[Try it online!](https://tio.run/##PU/LCgIxDLzvVwS8qCBs0zbtCn6Lt/Ug7HlB/PY6maiEtnlMZqbPy/bYxlivr6Mezrf9dN/fY5WEWKZViiw4SKo0nOppR8wokTbAfFJEvZzFgPfdORqKMuP2eUVOjCIy3sRDlDMYXkMU0GvoKEcVrQbsX7Xj6TSmvMNbCv6MkTtoyNyNWyzI@YsgqhhUircvV/kZSVTJVHbahbtBbiGQSJgIqBhmQpQGjcsU8i1lO75kjEa4i5pM4wM "K (ngn/k) – Try It Online")
* `(...)_x` [cut](https://code.kx.com/q/ref/cut/) the input (`x`) at...
+ `2#*=x` the indices of the first two occurrences of the first value in the input
[Answer]
# [Factor](https://factorcode.org/), ~~37~~ 35 bytes
```
[ dup first 1 pick index-from cut ]
```
[Try it online!](https://tio.run/##hVTBTsMwDL33K8wHDG1pkhaQdkVcuCBOiMPUZVI11pW2k0BVvr3YTkOSsYlFTRO/59h5drfbVMOxm15fnp4f72HT98eqh73pGvMBvfk8maYyPbSdGYbvtqubAR6ybMwAfyOscNyBhRtYrHFLBsszGe1MkriTMUkyPLLRkxQU@KiYRibLbxURSxxLRn6JJdO82RMLTIOOkCBisjNbXjnIOyxBY2J0pWXqEgDLu9hJIJLjTEepVAsHWV4FOEQTOHJ8r/hJ4jnIRfNwiEiJa3xrHBLvLdKoDnZxY0pQUDBLIVLg4Rf0TAmX1C1xV3JhBc@ufmfdUM4VvEb0h@XIIHkLXJHUVCOJ66RrAsny7pwY2o1yVogrVq6Yc5WpyNdorjFTwVd8/ZxlofzvOKi7hT4vuie7AlxzsNEXROEEt3nOd6FAVBY9n/Pn6/rPIUhBQQWjrg80j4K96L46lSSmOyEuu9jMTm@wPbWwq7t@wHTautpD3WzN12LXHQ9QnQZ4n0bkHjbtmv9W4Hb6AQ "Factor – Try It Online")
## Explanation:
* `dup` Duplicate the input.
**Stack:** (e.g.) `{ 0 2 2 3 0 1 0 1 } { 0 2 2 3 0 1 0 1 }`
* `first` Get first element.
**Stack:** `{ 0 2 2 3 0 1 0 1 } 0`
* `1` Push `1`.
**Stack:** `{ 0 2 2 3 0 1 0 1 } 0 1`
* `pick` Put a copy of the object third from the top on top of the stack.
**Stack:** `{ 0 2 2 3 0 1 0 1 } 0 1 { 0 2 2 3 0 1 0 1 }`
* `index-from` Find the index of `0` starting from index `1` in the sequence on top of the stack.
**Stack:** `{ 0 2 2 3 0 1 0 1 } 4`
* `cut` Split a sequence in two at an index.
**Stack:** `{ 0 2 2 3 } { 0 1 0 1 }`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
œṡḢ©®;Ɱ
```
[Try it online!](https://tio.run/##VVC7DcIwEO2ZwgO4iL9JxChRShqUBWhpGIAJoENCSHTQghiELGLs93wgpJN9d37v7j2vV9O0Sem1f98P79vxcXpclvP1kp67eXtOaRiMVjn6US8Gn2@tfEmDVq1W@Qyl6rTK0eReqVowiMgUW3r5LYLNcU1tW/RcrggFra8Ei3BAk2Mqh4Mj3iPCQ4GtYsikQI@k@VPYodfRDrBMvq7EsQOKmltooQta9Oj4@jXcEgAJIpprePqfASNynIjl6l6GVg3cV0hGNhqBBwCdMKyYjBxcVXGWlffvV0WJVmZQZxzHDw "Jelly – Try It Online")
```
œṡḢ©®;Ɱ Main Link
œṡ Split at the first occurence of
Ḣ The first element (pops the element)
© (also copies that element to the register)
Ɱ For each block
®; Prepend the register
```
As pointed out by Nick Kennedy in the comments (full credit to them), `Ḣ;Ɱœṡ@¥` also works and is slightly more functionally pure (though `Ḣ` still modifies the list itself, so it's not entirely pure):
```
Ḣ;Ɱœṡ@¥ Main Link
Ḣ Cut off and return the first element
¥ Last two as a dyad (for chaining; this makes the right argument the modified list for both inner dyads rather than applying consecutively)
;Ɱ Prepend the first element to each of
œṡ@ The modified list, split at the first occurrence of the first element
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 41 bytes
```
lambda l:[l[:(i:=l.index(l[0],1))],l[i:]]
```
[Try it online!](https://tio.run/##lZTbboJAEIbvfYq5A5JtwxkkoS@CXFhdIilVAjSxNT47XeagpTWamg3uDvPP/rP7hfZz2B32Qdp2Y5Wvxmb9/rpdQ5MVTZHZdZY3z/V@q492U7il8hynVE1RZ2U5DrofesjBLjwFZixLBUVo/hWE0zRSkCgwz2hapQrMcE1sWiWooAwj8aeYeRejmsq5HPYxFpgVpaJsyQIfR4DZpPFYQ4VjfB/jCNGBz2ZISQZDnLgzhynGUmoHc2ly6Uo6DjCLPCfohbqgFkOMhHw0tEuEKZGYpm3oGV4b8MROIGZp66UUZQ@03yTyZEdP0iNMDEThS5MxFWZXVMuX95ejimUkUoN8xqWz0MdWbwa9xfsvPN5@WU4ThABr0zLiI0UUMJLyCeNhY4SBYDYQCYzPoJBLp1cMBh/XDzREyHCwSvAQLQPC8jkiZPImJH@cp1dg7qKCyTNYmJ5buMgxPgCGL/Da1BUa7usRNiiU6/sPOuLwNzxs6S4@hp/NTm/edDfhY60@/CTcWApw5gWWs6gOHQxKQ72Hr7q18VOjQKBzsgWY3/TxqezBwUXb1fvBrqzTcIanFzj1ZzjxJoXO8748W874DQ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~18~~ 17 bytes
```
^((.).*?)\2
$1¶$2
```
[Try it online!](https://tio.run/##FY27DcJQEATzq8NINoF1t/ePCGkCIQgISAgQtbkAGjOPeGdn3o/P83XfD/P5tl/neV3W42m5gCb5bhP2ib7bLtJkbeTpTlWclOJpII4WYRBaYfAmBpSFhZAWiLACFZBuyf9fZbWhbZiGU0skNTrF1GggHs6SA7JhkGIFPNt0wNEkYgJ3VVNwBSuNBeBRiYhUq4wf "Retina 0.8.2 – Try It Online") Link is to test suite that double-spaces the output for convenience. Takes input as a string of digits. Explanation: Simply finds the earliest next match of the first character and inserts a newline before it. Edit: Saved 1 byte thanks to @Jakque.
[Answer]
# JavaScript (ES6), 31 bytes
Thanks [Razetime](https://codegolf.stackexchange.com/users/80214/razetime) for -1 byte.
```
a=>a.match(/^(.).*?(?=\1)|.+/g)
```
[Try it online!](https://tio.run/##dVDbSsNAEH33R7pRTOc@u0jsj4iwxPSibVOaIgj@e4yvMr6eM3Nu7/WzTv31cLk9TpfD23A9jeeP4WvednPtnmt7qrd@n9avqW3a@03adC/YfLcP610z9@N5Go9Dexx3aZtWiGXVNE93f2ApEsHqqhGeM3iEO6oLRQxYQYSQosIkpGEuIGJAwPDPxchMcqiaiVzF4Z@k2XMRKrI0jBfhjOhsxVE43GbRVlNAX6QkDogZmEi9CC8uFvogCpIqszBBNuDQi5UIlqpm5izZ7fdq/gE "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 17 16 bytes
```
(]{.,<@;@}.)<;.1
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWKr9XRsHKwdavU0baz1DP9rcvk56SkYahuq1ehl6lXrcaUmZ@QrpCkY6BgBobGOgY4hCMOEDXVAyBLGNVGwVDD5DwA "J – Try It Online")
In a sentence:
*Cut on first element and then meld together the tail elements.*
Consider `f 0 2 2 3 0 1 0 1`
* `<;.1` Cut using the first element as the fret:
```
┌───────┬───┬───┐
│0 2 2 3│0 1│0 1│
└───────┴───┴───┘
```
* `{.,<@;@}.` First element of that result `{.` catted with tail of that result
`}.`, razed `;` and then reboxed `<@`.
```
┌───────┬───────┐
│0 2 2 3│0 1 0 1│
└───────┴───────┘
```
[Answer]
# **[BQN](https://mlochbaum.github.io/BQN/)**, 12 11 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
⊢⊔˜·∨`·»⊑=«
```
[Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqi4oqUy5zCt+KIqGDCt8K74oqRPcKrCgpGwqjin6gyLDcsNCw2LDIsNiw2LDQsOCwy4p+p4oC/IjI3NDYyNjY0ODIi)
Explanation:
```
⊢⊔˜·∨`·»⊑=« # tacit function which can take input as either a list or a string
« # the input list shifted left
= # equality comparison with
⊑ # the first element of the input
·» # shift the result right
·∨` # 'or' scan
⊢⊔˜ # group the input according to those values
```
[Answer]
# [R](https://www.r-project.org/), ~~38~~ ~~37~~ 36 bytes
*Edit: -1 byte thanks to pajonk, as well as outputting the right-way-around now, and then -1 byte thanks to digEmAll*
```
function(l)by(l,cumsum(l==l[1])>1,c)
```
[Try it online!](https://tio.run/##lVTbasMwDH3fVxj2UBtciBPnUrb2R7o@dGGBQpqWpoWNsW/PbEluKi9bGTUhSOdIx0dKT0OzHJpLV593h0626vVDtrq@7PvLXrbLZbs2G7UyulZD3277Q/P2PL@i39Xn8bTrzrJxr@qp3p7l7KXzv5n6eiC8rKXRwp2FUuJRzFdi7WpqsfahzeYGZl1ACzvCfMAjLYPlWpRauGc@In3MI32UgSst3ElcegRXHklRBi5BJ9Z3vdORQhlPpBwjukoFiMebJozLkr5CEtNTSGcujLVBw41dlPdchog1pHAyEIAyDJNBedJAiFgJ3q8AaAHHgocp00MoksRwsf/YFUdm4SWZGsok8LdJVZCucGGAhi/X3eD7VtF63CGwFhnUx4GW4CpOEVfBQuRmVxnc95omxAuPbuSAzcPg8Gr4tGyI9xnwvUyM1QTPs2A0Xn0RpJEHqJrNeqTSuO@QWWsTbm8CLwdGFqhp2IcCe/z8l/gHObYXpaUBeF3SIpwyFEP7CmZ1zCZv/@I7AcM3 "R – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 35 bytes
```
shift>$1
ls
for x
(rm $x&&od;<<<$x)
```
[Try it online!](https://tio.run/##qyrO@F@cWqJgoGAEhMZA2hCE/xdnZKaV2KkYcuUUc6XlFylUcGkU5SqoVKip5adY29jYqFRo/v8PAA "Zsh – Try It Online")
Explanation:
* `>$1`: create a file named the first input item
* `shift`: shift the input array, removing the first item
* `ls`: list the directory. Since we created `$1`, this prints the first item
* `for x`: for each item `$x` in the input array: `(`
+ `rm $x`: try to remove the item. If the item `$x` is the same as the first input, and the item has not already been removed, this will succeed
+ `&&`: if that succeeds:
- `od`: print `0000000` as a separator
+ `<<<$x`: print the item
With some loose interpretation of what is allowed as a separator, we could have:
## [Zsh](https://www.zsh.org/), 33 bytes
```
shift>$1
ls
for x
rm -v $x||<<<$x
```
[Try it online!](https://tio.run/##qyrO@F@cWqJgoGAEhMZA2hCE/xdnZKaV2KkYcuUUc6XlFylUcBXlKuiWKahU1NTY2NioVPz/DwA "Zsh – Try It Online")
* `rm -v` is `v`erbose; if the removal is successful, a message `removing 'x'` is printed which is arguably a separator, as well as printing the item
* `||`: if that fails:
+ `<<<$x`: print the item. We only need to do this if removal fails, because `rm -v` prints the item already
[Answer]
# [Red](http://www.red-lang.org), 49 46 bytes
```
func[x][reduce[take/part x find next x x/1 x]]
```
[Try it online!](https://tio.run/##lVTLbtswEDybX7H1WYGtpxUD9kf0SvBASDQSxJYESSkUFP12l/ugFaVNjACEQO7M7pA7FHtXX3@6GrSBU9vur6fXptKT0b2rXyunR/viNp3tR5jg9NzU0LgJ59MmhsmYa2UHN@zht1rpOAI/Hg08HEHr2ESgaW08lvlJBJlguEI4IyyPYBeB/@YCYwBhCiGjjMCPLYaZUSIcQsjYkTZX8tUT4UkY2QFAtk8raEO85e2csEAwbRtyEgqnfsmFSC0cVkBMWMKiltBISYoF41lQQFELsGjytguiFDQyakYyKwtFxJck6R5LcJczmmz/ael/WR/7XFK4ZDeJzpObh@9uQCk23mNj3ZSKsh076hTbwAZmFAm3Z8FFgU/Ycu/4sDlx8uAAH4K/2ezGfTpd23f@xKGPaegfH@4x7ENOyVucTZvzxLd7meb2h2X0ZX5OzDSkJMHYQmov/8XvZEr3eB9JINyuVhHGLhThBhVzJz@mSuu@TDbqj1IPxz1c/LsDbfcD8D0CPcGb0W9wOOAj5R8epbr@uRlBq5U9n@Hc2hp6151t5TYYoGcJqvZysbBeq9XaV3S2GWB8siMgY3TDKLQn@8tBZ4fB1Wtlrn8B "Red – Try It Online")
[Answer]
# Scala, ~~35~~ 30 bytes
Saved 5 bytes thanks to @cubic lettuce!
```
x=>x splitAt x.indexOf(x(0),1)
```
[Try it in Scastie!](https://scastie.scala-lang.org/b01x62e7QQKGLtfD6dbEQw)
Hopefully, I'm not FGITW'ing this.
[Answer]
# JavaScript (ES6), 34 bytes
```
a=>[a,a.splice(a.indexOf(a[0],1))]
```
[Try it online!](https://tio.run/##lVTbboMwDH3fV@QRpKwlEC596H5hH4B4iChMnRBUY5r29yyxY2iatNWkCCH7HPvk2PCpftTcfp0v36/jdOqW/rio41utuNrNl@HcdpHancdT9/veR6pOGi7iuFnaaZynodsN00fUR7XgTJ9DE8dsv2esrkXDWQ2h5uUGK3WUM7lhTcDApY/NOSs50898g5uYgUPUY1Sc6ZMYzMqoDJyiHqME7dhJS0k3ns0YNuU8tq5ZwIXQgsQp4CRNmSRYIwVMpnPYBdRcmWnzpoCLCKlJ4WQgBQUJR5DNWzWECGnCOxeAL@BIMDd1lFmUFefiQtPB/jhVCS9JaGRB4MM5VoCpcLuAiy/rDrkbWtk1ekbw@mTQBMddgtM4Y9wWCZGr7XbgpuEdQug7QXNyIOQ0UbwkPqUz3ecM@MzuzVvQHDIyH504kEhrCep3lmCj2j14Rvb6CzJDEDkHWkb8lBalsI28f81/yCG3UWRK6HWPCzolVUQ3C8f5W7a1@iG/Wf4A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
f(h:t)=(h#t)[h]
(h#(x:y))a|x==h=(a,x:y)|0<1=(h#y)$a++[x]
```
[Try it online!](https://tio.run/##lZTbaoNAEIbvfYqB5kLJBjysR@oD9KoPIF4IbTAkTUvrhYG8u92dQ6yHNhQW0Znv3/13ZpK2@Tq@nk7DsHfbovNKt33ovKqtHfPi9sXF85prX5Zt6TbKfl79x8BCF2/TbLdVXw9vzeEMRQFPz@B6Dn6V8PLuAHx8Hs4dbGAPVaDArLxej8JuB1UV1ApDeT3DtIkp0IzZL0vqORYrSBWYZ8ykDVgSQzM4U2CWbwmCM0tKaAan6JP2N8eHLOGwFUpiJjSbJWiebuqP2knG7uCvyEMkIpOh7dGDlIuTVjtNLz2EuCI0QDaC0QYn2YOkl07oignSCS6NNQxHP4ywpSm0rD8dTC3T@OIvmrJK/dGpDImMBgaV9HKbjR/zlvF43KNnR0S4PzU0xapSI2kaNEZkViesPesXejnwVI0Y8VgaR1ejpx6beB/H38t6WwOpeSS1ptvn4o7LQMbHXo86bvc95epvX@OTpDGKIlGHMg8JHzP9l/iPcllechcKe5vTRFYq@1EFk3r4Bg "Haskell – Try It Online")
Because why not?
## flawr's suggestion, 33 bytes
```
f(x:y)|(a,b)<-break(==x)y=(x:a,b)
```
[Try it online!](https://tio.run/##lZTJboMwEIbveYo59ACSkViMWVQeoKc@AOJA1ESNsrRKe0ikvju1ZwnF0EaVLBRmvt/@PTPktf/Ybw6HYdgGl/oafgW9WoeP0fq86fdB01zCa2MTLjgc@90J6hqeniEIV/jWwMvbCuD9vDt9wgNsoU0U2FV1y1GIImjbpFMYqjoP0zamQDPm3hypfSxXUCiwz5xJF3Akhjy4VGBX7AiCS0dKyIML9En72@NTlnDYCSXhCe1mBs3TTeNRO8m4HeIFeYpEZjO0PXqQcnHSaafpuYcUV4YGyEYy2uAke5D03Ald0SBtcGmsYTr6YYQtTaF5/elgapnGH/GsKYvUH50qkShpYFBJP26z8WPeSh6Pe7R3RIb7U0MLrCo1kqZBY0RmdcK6s36h5wNP1cgRz6VxdDV66rGJ93H8XpbbmkjNM6k13b4Sd1wGMj72etRxu@8pF799jU@S5ijKRJ3KPBg@Zvov8R/lvLzkLhX2NqdGViH7UQVNN3wD "Haskell – Try It Online")
This is based on Zgarb's solution (`f(x:y)|(a,b)<-span(/=x)y=(x:a,b)`).
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~60~~ 57 bytes
```
$a,$b=$args
$r=(,$a),$y
$b|%{$r[$r[1]-or$_-eq$a]+=,$_}
$r
```
[Try it online!](https://tio.run/##PUzLCsJAELvvV8whiuIutD5aL/MlspStbH1QXJ0eRGq/fZ1eJCEkIeSZ3lGGa@x7d04SMzoeM4JFywhyGQyEVxZhbfExaL@LEXJSlt4lQePiC8Fv2KKZdJono0pMS3S0px0daKsoqNJ0VJ1Raz@nmirj7un20LvC/23p8w8 "PowerShell Core – Try It Online")
It takes the input as an array of ints, returns two arrays
### Another approach for 59 bytes
```
param($a)$a[0..(($i=$a|% i*f $a[0] 1)-1)],$a[$i..$a.Length]
```
[Try it online!](https://tio.run/##PYxBDsIgEADvvGLTrIYaIaVF2gs/8AeGw8aAxdTSoIkH9e1YL95m5jBLevp8H/00iXPKvmCwr7JQphtHqpFOjZScY7RI7w3EXYBfc6BqoWq3XwWjlEjy6OfLY3TlwxhmsLDFAJXuDm3bGD0YY/pOD72pmLimOGNeJ39UrnwB "PowerShell Core – Try It Online")
Takes the input as a string, returns two arrays
[Answer]
# [Red](http://www.red-lang.org), 67 bytes
```
func[b][collect[keep/only take/part b find next b b/1 keep/only b]]
```
[Try it online!](https://tio.run/##VVFLboUwDNxzitHbV0BIAnTRQ3QbpRKfoD49CohSqT09tQ0KLRGRY49nJvEa@v019M4nwzP24WvqXOtdN49j6Db3CGFJ52n8wdY8Qro064YWw33qMYVvjts0x4Vqvd@HeQ1N947x/rnBJaDP5chR@yPWqKHP2KCEgTlPFSpkKM9TST1c11BnJoOlXubKYk5RpoBiFKHriFS0CsIxNo9YZrNUsbQ0qamozHj2omnP/vmoKFOxZyjZD8/XfQqqsqeS9Ngf@9YU63hfZjRUM@KH2fjXf3zloliIC@avhUFUmNNfr0hdgjFULwSlxK/l/qjIvUoqxz2trFI6WN36xLtlvU80oY957I9h3Z5e3lIiuEFyg2Rpor8 "Red – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
i=input()
a=i.index(i[0],1)
print i[:a],i[a:]
```
[Try it online!](https://tio.run/##HYtBCsMgFAX3nsKdWh5Fk7TQgCf5/IUkQv7GSLGQnt6mYRYDA1O/bdvL0Jd9zdEY0yVKqZ9mnUpR7lLWfFghzwhO1beUpoXmxBBKM/fzUPnIi/3/Tt/02Ckg4MWK/OkBIzwmPPC8ygX/AA "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
g[b_,a___,b_,c___]=b.a|b.c
```
[Try it online!](https://tio.run/##RVBLboMwEN1zCh/ASvEHOywqcYTuowgZVKVZpIuKHfXZ3ckbXiqNzHh4v/GjbF@fj7Ld19La7bLMtszzbOW7yvf6vpzK73Ja28fP/Xt7m27TNHX77qyRGqux3R6lsSZWaQdrsjVyDs/b2RqpXmbAZXAUIhxfrel2@ZvAV8Wec49hkKuCQRxJ8agAvLIcLDzFEwAJFRFDZc/kasyIpv/PeWAyJiOttXkt55gkAKbJM/LoLrppxCTyjdRoAGZgcjXSMz63OHZ3jBQYWN1Hyh4x1BEsR1NH/ABkIMVz06TKDKZqnoDXiyVWpohGTbWa1v4A "Wolfram Language (Mathematica) – Try It Online")
-10 bytes thanks to @att
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ćk>Ig‚£
```
[Try it online](https://tio.run/##yy9OTMpM/f//SHu2nWf6o4ZZhxb//x9toGMEhMY6BjqGIBwLAA) or [verify all test cases](https://tio.run/##PU87CsJAFLyKpH5F9p802niLkEJBRCwsBCGdlfaWtt5EPEkuEmcmIo/dfZ95M7On82Z72E2XYVUtxttjUa2G9fS5H5fDfrw@36/Jpq5z5qztrYvWWsSbrFiyhKyxxmoryAow7EfzqGrLwHKvVu1RBfOcAtUK4REBc2KcMNzO6GZEBLOXAnHUi7jrv16DqqEf87pnT7PPgAm1C/jpg94i8qg/kCWhn6RNFp748@CkEKRKzlabYiYXME5sTvOEWRDCy1vmrlS449Wd/5IVRWgq5r7/Ag).
**7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative provided by *@ovs*:**
```
ćk>°RÅ¡
```
[Try it online](https://tio.run/##yy9OTMpM/f//SHu23aENQYdbDy38/z/aQMcICI11DHQMQTgWAA) or [verify all test cases](https://tio.run/##PU@7DcJAFFsFpX5F7p800DABbZQCJApEQYGExABAzwZswAyBSVgk2A5CT3f3Pn6273Bcb3bb8XReVLPP9T6rFufl@L7t58Nz9boMj9HGrnPmrO2ti9ZaxJusWLKErLHGaivICjDsR/OoasvAcq9W7VEF85wC1QrhEQFzYpww3M7oZkQEs5cCcdSLuOu/XoOqoR/zuidPk8@ACbUL@OmD3iLyqD@QJaGfpE0Wnvjz4KQQpErOVptiJhcwTmxO84RZEMLLW@auVLjj1Z3@khVFaCrmvv8C).
**Explanation:**
```
ć # Extract head of the (implicit) input-list; pop and push remainder-list and
# first item separated to the stack
k # Get the first 0-based index of this item in the remainder-list
> # Increase it by 1 to make it a 1-based index
Ig # Get the length of the input-list
‚ # Pair them together
£ # And split the (implicit) input-list into parts of that size
# (after which the result is output implicitly as result)
ćk> # Same as above
° # Pop and push 10 to the power this 1-based index
R # Reverse it, so we have a 1 with some leading 0s
Å¡ # Split the (implicit) input-list at the truthy indices (or singular index in
# this case: the 1)
# (after which the result is output implicitly as result)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ṡ`, 5 bytes
```
hẆḢḣf
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=%E1%B9%A1&code=h%E1%BA%86%E1%B8%A2%E1%B8%A3f&inputs=%5B7%2C%201%2C%205%2C%207%2C%204%2C%202%2C%207%2C%203%2C%209%2C%204%2C%202%2C%207%5D%20&header=&footer=)
Explanation:
```
h # Get the first element of the list
Ẇ # Split list on head, without removing it from the list
Ḣḣ # Get the first element from the resulting list
f # Flatten the rest of the resulting list
# 'ṡ' flag - print both lists, separated by a space
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
Feels like there should be a shorter way for this, but can't seem to find it right now.
Selecting the right-hand element ensures we don't select the first letter itself, the check on the incremented variable ensures we only split once.
```
óϦUΪT°
ó // Split the input string between char pairs where it's not true that
Ï // the right-hand element
¦ // is different than
UÎ // the first char of the input
ª // or
T° // T, initially equals zero, plus plus.
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=88+mVc6qVLA=&input=IjI3NDYyNjY0ODIi)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 54 bytes
```
x=>[x[s="slice"](0,i=x[s](1).indexOf(x[0])+1),x[s](i)]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/wtYuuiK62FapOCczOVUpVsNAJ9MWKBCrYaipl5mXklrhn6ZREW0Qq6ltqKkDlsjUjP1fUJSZV6LhFezvp1dcAmSnZ6ZVaqRpRBvoKBjqKBjpKIAYsZqamly4VBqCVRoSUgYx0ACk5j8A "JavaScript (V8) – Try It Online")
[Answer]
# MATLAB/Octave, 63 bytes
```
function y=f(x)
l=find(x==x(1));y={x(1:l(2)-1),x(l(2):end)};end
```
[Try it online!](https://tio.run/##tVHLisMwDLznK3yrDS7EjzhJg79k6WGpEzCUtOx2S8rSb09dqerJ3tsaYYQ1Go3Gp8Pl8zqu6/QzHy7xNLObn/giqqOf4hz44v3ClRDDzf@mZHfkWmyVkAt/ZrtxDuI@pHsN8RrD@OU32/89m6Ga@IeSLEW/F1WI32f@Gi6eJZveJbO5UiNZK1m6m1y1kyxFnTC5agsTkSGN0DlM6nUwHeXVBZgGjElVpALavkCoIQywIacqcKIwB3gHYWEjXVgWmdEQC0n9pwMdYDq0F3oxebta@hEDXehJC7ugS2iphRdb@EpU1UBLQyagDLxt2RBF6xhaFqX2NPSlGfXkSBQpVNTeQKMhBk2mORxU2AJnacK/v8ZRtMSJe7m9WB8 "Octave – Try It Online")
Outputs cell aray with 2 cells, which hold appropriate vectors. I've chosen such output because rules say 2 lists must be distinguished, not necessarily be separate variables. And outputting 2 variables turned out to give a little longer code.
Ungolfed/explained:
```
function y = f(x)
l = find( x==x(1) ); % indices of elements equal to first element
l2 = l(2); % index of second occurence
y = { x(1:(l2-1)),... % vector containing elements before 2nd occurence
x(l2:end) }; % vector containing elements from 2nd occurence
end
```
---
Interestingly, it's also possible to create anonymous function that does the same, but it's 2 bytes longer:
```
@(x){x(1:find(x(2:end)==x(1),1)),x(find(x(2:end)==x(1),1)+1:end)}
```
[Try it online!](https://tio.run/##tVHLasMwELznK3SLRFWwHpbtBEP/o@QQaht8cUpTgqH0293tTjYnqbeaRcj7mJkdXd4@z7dx2170ar5W7Q7TvAx61f4wLoPpe0oZ64yxq85Xnhz/f29Tf16ux90w3@Zh/Oj3z//77Y@7Sb86qyi6kyHe67u@k5vfUqS8VTFXqq1qrKKzzlVbqygq6slVG2YEAlH4XA/NJmaHvKrQ5rknUBVQDNsVAD1HYDRgugImhCXuTxyRN/KFZYEMQyJfqj8daLmnhb08i8vD1dKLBJ6CJw3vApdgaeRMLDwlVNU8UosJkIEzlg1xsk6QZSG1E9K7ZujJgThR6GS85sEgCF5MSyAqbAEuL/2Pp0kSjWBir3Qy2w8 "Octave – Try It Online")
It is possible to shorten it more as [flawr](https://codegolf.stackexchange.com/users/24877/flawr) noticed, resulting in **42 bytes** but it's an **Octave-only** solution, not working for MATLAB:
```
@(x){x(1:(l=find(x==x(1))(2))-1),x(l:end)}
```
[Try it online!](https://tio.run/##tVFNa8MwDL33V@RWC1yIP5O0GPY/Rg9lSSBQ0rGOEhj97akmVT3Zuy0I41jSe09Pl4/v021Y1ze1wM@izF6d0zjNvVpSwl8AZQF2BvSizvth7uG@juk0Xw@bfrpN/fCVtrv//baHzajeja4wuiMg7/VTPcnhN@XxXVc@lwq6anSFZ8hlW11h1FiTyzbEyAhIYXM12BuJneXVhTJLNQ6zDEWwXQHQUjhCY0xTwGRhkeojhaeJbGFYRmZDPF3qPx1oqaZle6mXLy9XSxtx1MWeNDQLu8SWenrxhVWyqkAtQUxgGXz6siFGxnEyLEvthPSpmfXkQIwoNNIeqNEJghXTIhMVpmAuK/Wv1USJRjB5rniE9QE "Octave – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
Fȯ:;:←¹↕≠←¹t
```
[Try it online!](https://tio.run/##yygtzv7/3@3Eeitrq0dtEw7tfNQ29VHnAjCz5P///9GmOuY6pjqmsQA "Husk – Try It Online")
no split at index builtin, but `↕` (span) helps a bit.
it's similar to xnor(and Zgarb)'s answer, but argument destructuring and functors don't exits, so it just uses a fold.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 8 bytes
```
ḣ$£¥€ƛ¥p
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B8%A3%24%C2%A3%C2%A5%E2%82%AC%C6%9B%C2%A5p&inputs=%5B7%2C%201%2C%205%2C%207%2C%204%2C%202%5D%20&header=&footer=)
This is possible in 8 bytes Imao
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
τÄ∩T╕(û▒(Ç
```
[Run and debug it](https://staxlang.xyz/#p=e78eef54b82896b12880&i=%5B1,+1,+9%5D%0A%5B4,+9,+4%5D%0A%5B5,+7,+5,+5%5D%0A%5B8,+8,+0,+7%5D%0A%5B7,+1,+5,+7,+4,+2%5D%0A%5B0,+6,+9,+1,+1,+0,+2%5D%0A%5B2,+9,+3,+2,+4,+2,+5,+9%5D%0A%5B0,+2,+2,+3,+0,+1,+0,+1%5D%0A%5B2,+7,+4,+6,+2,+6,+6,+4,+8,+2%5D%0A%5B8,+2,+2,+7,+5,+4,+7,+0,+8,+0,+7%5D%0A%5B8,+7,+8,+9,+4,+2,+9,+4,+5,+7,+5,+1,+9%5D%0A%5B3,+8,+1,+1,+7,+3,+6,+9,+7,+1,+4,+3,+4%5D%0A%5B4,+7,+0,+5,+6,+5,+0,+1,+7,+8,+7,+8,+4,+1%5D%0A%5B2,+1,+8,+0,+3,+2,+2,+5,+7,+9,+4,+3,+5,+1,+9,+6,+9%5D%0A%5B1,+1,+4,+1,+2,+5,+5,+3,+3,+4,+3,+2,+0,+8,+6,+0,+3%5D%0A%5B4,+3,+5,+2,+2,+0,+6,+4,+8,+6,+6,+6,+7,+3,+4,+8,+7,+6%5D%0A&m=2)
annoyingly long, but i guess it works.
### [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)(regex)
```
êt┴≈∟·M╤\+6)
```
[Run and debug it](https://staxlang.xyz/#p=8874c1f71cfa4dd15c2b3629&i=%22119%22%0A%22494%22%0A%225755%22%0A%228807%22%0A%22715742%22%0A%220691102%22%0A%2229324259%22%0A%2202230101%22%0A%222746266482%22%0A%2282275470807%22%0A%228789429457519%22%0A%223811736971434%22%0A%2247056501787841%22%0A%2221803225794351969%22%0A%2211412553343208603%22%0A%22435220648666734876%22&m=2)
### [Stax](https://github.com/tomtheisen/stax), 22 bytes(tsh's regex)
```
"^(.).*?(?=\1)|.+$"|Fm
```
[Run and debug it](https://staxlang.xyz/#c=%22%5E%28.%29.*%3F%28%3F%3D%5C1%29%7C.%2B%24%22%7CFm&i=%22119%22%0A%22494%22%0A%225755%22%0A%228807%22%0A%22715742%22%0A%220691102%22%0A%2229324259%22%0A%2202230101%22%0A%222746266482%22%0A%2282275470807%22%0A%228789429457519%22%0A%223811736971434%22%0A%2247056501787841%22%0A%2221803225794351969%22%0A%2211412553343208603%22%0A%22435220648666734876%22&m=2)
] |
[Question]
[
In calculus, the derivative of a mathematical function defines the rate at which it changes. The derivative of a function `f(x)` can be marked as `f'(x)`, and these can sometimes be abbreviated to `f` and `f'`.
The derivative of the product of two functions `fg` is `f'g + g'f`. The derivative of three `fgh` is `f'gh + fg'h + fgh'`. In general, the derivative of a product of any number of functions is the sum of the product of all but one, multiplied by the derivative of the remaining one, for each individual function.
Your challenge is to take a string of distinct alphabetical characters and transform it into its derivative. No spacing or simplification is required, and terms separated by `+` may be in any order. The string will contain at least two characters.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!
## Testcases
```
abc -> a'bc+ab'c+abc'
de -> d'e+de'
longabcdef -> l'ongabcdef+lo'ngabcdef+lon'gabcdef+long'abcdef+longa'bcdef+longab'cdef+longabc'def+longabcd'ef+longabcde'f+longabcdef'
short -> s'hort+sh'ort+sho'rt+shor't+short'
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes
```
aRL#aJ'+<>#aJ''
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhbrE4N8lBO91LVt7ECUOkQUKrkiWikxKTlFKRbKBwA)
### Explanation
```
aRL#aJ'+<>#aJ''
a Command-line arg "abc"
#a Length of arg 3
RL Repeat-list ["abc"; "abc"; "abc"]
J'+ Join on "+" "abc+abc+abc"
<>#a Groups of size len(a) ["abc"; "+ab"; "c+a"; "bc"]
J'' Join on "'" "abc'+ab'c+a'bc"
```
[Answer]
# [Python](https://www.python.org), 54 bytes
```
lambda s:((l:=len(s))*(l*"'"+-~l*(s+"+")))[-~l*~l::-l]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3zXISc5NSEhWKrTQ0cqxsc1LzNIo1NbU0crSU1JW0detytDSKtZW0lTQ1NaNBvLocKyvdnFiobqeCosy8Eo00DaVEoAouBC8JjZucgiGQmpaeARSEmLRgAYQGAA)
# [Python](https://www.python.org), 56 bytes
```
lambda s:((l:=-~len(s))*(l*(s+"+")+-~l*"'"))[l:-3*l:-~l]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3LXISc5NSEhWKrTQ0cqxsdetyUvM0ijU1tTRytDSKtZW0lTS1gYJaSupKmprROVa6xlpAoi4nFqrfqaAoM69EI01DKRGogAvBS0LjJqdgCKSmpWcABSEmLVgAoQE)
## Old [Python](https://www.python.org), 58 bytes
```
lambda s:((l:=-~len(s))*(l*(s+"+")+l*"'"+"+"))[l:-3*l:-~l]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3rXISc5NSEhWKrTQ0cqxsdetyUvM0ijU1tTRytDSKtZW0lTS1c7SU1JXATM3oHCtdYy0gUZcTCzXBqaAoM69EI01DKRGogAvBS0LjJqdgCKSmpWcABSEmLVgAoQE)
## How?
```
a b c d +
(a)b c d +
a(b)c d +
a b(c)d +
a b c(d)+
' ' ' '(')'
a b c d(+)
a b c d +
(a)b c d +
a(b)c d +
a b(c)d +
' ' '(')' '
a b c(d)+
a b c d(+)
a b c d +
(a)b c d +
a(b)c d +
' '(')' ' '
a b(c)d +
etc.
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~69~~ ~~64~~ 59 bytes
-10 thanks to @Noodle9 and @ceilingcat
```
l;f(char*a){for(l=0;a[l];)printf("+%.*s'%s"+!l,++l,a,a+l);}
```
[Try it online!](https://tio.run/##dcpBDoIwEIXhvbewCbFlinE/8STIYqwUSMaWdOqKcPYCe3m7l@93jWMKQymMXruRUk1m8TFpfj6QWu7QzGkK2WsF1b2WWyUKrmwB2JIlYINr@dIUtFkue0RvpwzOvyxavUJzbP@HfPoT4BiG3Et2JGeJjDHlf7aWDQ "C (clang) – Try It Online")
[Answer]
# [Brainfuck](https://github.com/TryItOnline/brainfuck), ~~87~~ 84 bytes
```
>,>---[>+<+++++++]>++[>,]<[<]<[<]>[[.>]>.>[.[-<<+>>]>[.>]<[<]<++++.----[->+<]<[<]]>]
```
*Saved 3 bytes thanks to Nitrodon.*
[Try it online!](https://tio.run/##JYzBCcAwDAMHcuwJjBYRfiSBQin0Uej8bpwK9NAJaTz9vI93XploUFVCXH4FRIgWTt8GaQgYaFR3wQpFdl8D0zrQ9bBZIDL7mB8 "brainfuck – Try It Online")
**Explanation**:
```
memory progress for abc:
null a null 'bc
null ab null 'c
null abc' null
string is split to two parts by null character
>,> load first character
---[>+<+++++++]>++ load ' to memory; taken form esolangs wiki
[>,] load rest of input
<[<]<[<]> go to beginning of memory
[
[.>] print first part
>.> print '
[ check if there is text after '
. print first char of second part
[-<<+>>] move char to the first part
>[.>] print rest of second part
<[<]< go to position of '
++++.---- use ' to print plus
[->+<] move '
<[<] go before beginning
]
> move back to beginning
if there wasn't text after ' move after end instead
]
```
[Answer]
# [Python](https://www.python.org), 47 bytes
```
lambda s:"+".join(s.replace(c,c+"'")for c in s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY39XMSc5NSEhWKrZS0lfSy8jPzNIr1ilILchKTUzWSdZK1ldSVNNPyixSSFTLzFIo1odqcCooy80o00jSUEpU0NbkQvCQ0bnIKhkBqWnoGUBBi0oIFEBoA)
How it works:
```
a b c d --> a' b c d
a b c d --> a b' c d
a b c d --> a b c' d
a b c d --> a b c d'
then join with '+'
```
[Answer]
# [Factor](https://factorcode.org/), 53 bytes
```
[ dup length [1,b] [ cut "'"glue ] with map "+"join ]
```
[Try it online!](https://tio.run/##RcyxCsIwGATgvU9xZHFQBFd9AHFxEafS4W/620TTJE3@UEF89prN7biPuwdpCWm93y7X8xGZ58Jec97zWxLlf4GJxOwT@bHmFyfPDjZgXnBqmnn5gHqNgeGCH4WzaMqMbEISfNcWQ4lwXMmgPez6Di10EaiNGl1hdFhspYki1FY9g/Xo6iom66WiDlMM9Y9Jm/UH "Factor – Try It Online")
If the order of each product doesn't matter:
# [Factor](https://factorcode.org/), 43 bytes
```
[ all-rotations [ 39 suffix ] map "+"join ]
```
[Try it online!](https://tio.run/##RcwxDoJAEEbhnlP8oTXaWKEHMDY2xopQjOsgq8vOsjMEEuPZkc72y8tryZnk5XY9X04HKA8jR8e649ky6R/w5hw5wAuGCceiGKYP6O7wYASJT2M1R8rQTrLhu9SgELZZjMxLVNTYV9Cxbf2MBj0llJvyJT6iWduUfbTVnfRJ1guT65Yf "Factor – Try It Online")
## Explanation
```
! "short"
all-rotations ! { "short" "horts" "ortsh" "rtsho" "tshor" }
[ 39 suffix ] map ! { "short'" "horts'" "ortsh'" "rtsho'" "tshor'" }
"+"join ! "short'+horts'+ortsh'+rtsho'+tshor'"
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 46 44 bytes
```
l=>[...l].map(s=>l.replace(s,s+"'")).join`+`
```
[Try it online!](https://tio.run/##VZBta4QwDMff36cochCld@VuGwzm6j6IE9QaH26dFduNgfjZXas7dX2R/Jom/6S5Zd@ZFn3TmXOrCpxKPkkexYwxmbDPrPM1jyTrsZOZQF@fNPXACwJ2U02b0nQSqtWGGLSGk9jLcuGdiFegs1K1lQ0UWLqbrlVvvCQ8LCX406EwWCxlkAua5eCMgFkBkBY4o4RVh0oFO25hxxXs2AmubHU3FrBj22VjhB2Xc2sNbmiqa1icgsX1sDgD24dEjeID@/k/718Pz0/zJhxdH11WqXriSzSksSmX0LrXdQlMYluZOiSUNgEZDsQel@qW6nYbN1bgHkQbvBf@e9D2ofRNsETcVEoik6ry0@NgRnKOyHHQozV/s8aac45v15dLMqa2bJx@AQ "JavaScript (Node.js) – Try It Online")
-2 bytes thanks to [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 14 bytes
```
J‘œṖ€j€”'j”+”'
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJK4oCYxZPhuZbigqxq4oKs4oCdJ2rigJ0r4oCdJyIsIiIsIiIsWyJhYmMiXV0=)
```
J‘œṖ€j€”'j”+”' Full Program
J [1, 2, ..., len]
‘ [2, 3, ..., len + 1]
œṖ€ For each of these, partition (*)
j€”' Join each partition on ' (**)
j”+ Join on +
”' An unparseable nilad forces the current string to be printed
(And then the ' is printed at the end)
(*) partition takes a list on the left but since we give it a single number,
it auto-wraps it so we just get all needed splits
(**) the last partition only has one sublist so join doesn't work properly here
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~15~~ 13 bytes
```
L$|+`.
$>`'$'
```
[Try it online!](https://tio.run/##K0otycxLNPz/30elRjtBj0vFLkFdRf3//8SkZAA "Retina – Try It Online")
-2 thanks to Neil.
Match every character. For each one, take the text before the separator after the matched string, followed by an apostrophe, followed by the text after the matched string. Print as a list with separator `+`.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 21 bytes
Most straightforward K solution.
```
{"+"/?[x;;"'"]'1+!#x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pW0lbSt4+usLZWUleKVTfUVlSuqOXiSlNKTFICkmnpGSCqOCO/qATEyMnPS09MSk5JTVPiAgDpMhDX)
### Explanation
```
{"+"/?[x;;"'"]'1+!#x}
?[x;;"'"] / insert "'" in string at
' / each position
1+!#x / 1..len of string
"+"/ / join the resulting strings with "+"
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~45~~ 36 bytes
```
aÔí°Riffle[a/.#->#<>"'"&/@a,"+"]<>""
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P/H9pIVBmWlpOanRifp6yrp2yjZ2SupKavoOiTpK2kqxQJ7S/4CizLySaKBkmoNzRmJRYnJJalGxg3KsWl1wcmJeXTWXUmJSspIOl1JKKojMyc9LBwqkpKaBeMUZ@UUlSly1/wE "Wolfram Language (Mathematica) – Try It Online")
Input `[{characters...}]`. Assumes all characters in input are unique. Returns a string.
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
ToString@Expand[Dt[1##]/._@a_:>a']&
```
[Try it online!](https://tio.run/##FYq9CsIwGAD3PEZS6qIWV8ESUHchbiGUr/lpCk0i6TcoYl89tsvBHRcAvQ2Ao4biqkt5JoF5jAO/v18QjbyhPDGmmmPHoTu3sFN1eawDSnZoXcW5@IQ@TQ2/esig0eaZM1UvQkNcvoRCr@meUGM3TikOazDWbTb7lJGSX/kD "Wolfram Language (Mathematica) – Try It Online")
Input `[symbols...]`. Assumes symbols are unique and not defined. Returns a spaced string.
`Dt` treats strings as constants.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~83~~ \$\cdots\$ ~~72~~ 69 bytes
```
s=>g=(r="",i=0)=>s[i]?g(r+("+"+s).slice(!i,++i+1)+"'"+s.slice(i),i):r
```
[Try it online!](https://tio.run/##VZHhasMgEMe/7ymcFE4xLe02GDSzfZCu0NRcEjeJRd0YlDx7pkmXZn64@/n37jzPj@K78MrpS1i2tsS@kr2Xu1oyJynNtFxzufMHfdzXzAlGBRWer7zRCtmjzoTQYsMFhSjfVM0zzbeuV7b1gQSMRpIDLc6KZoSWmKyxbR2FEqu08411gR7zhzEFfy6oApZjGpyVKM6QjIKhAqAocUADUx1hLMy4hRnXMONUcOJY984KZhxvuTPCjKvhag@paeEbGJ2F0TkYXYD7g1SD6hPd8J73r6fXl2ESiTbPKaqyjjCDgegYss6je5uGsDLY1qHJSZw0J9cHElcKTUNNs40/k08iRvEv8d@BjwcVC5zxUUt9WYMrY2t2WlxDR5Y7srj6LppbtwcvpcT9Zrs@dqeY1vW/ "JavaScript (Node.js) – Try It Online")
*Saved ~~7~~ 8 bytes thanks to [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)!!!*
*Saved 3 bytes thanks to [Samathingamajig](https://codegolf.stackexchange.com/users/98937/samathingamajig)!!!*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
⪫⪪⪫Eθθ+Lθ'
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPI7ggJxPK9E0s0CjUUSjU1FFQ0lYCkj6peeklGRqFmiARdSVNTev//xOTkv/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @DLosc's Pip answer.
```
θ Input string
E For each character
θ Input string
‚™´ Join on
+ Literal string `+`
‚™™ Split into substrings of length
θ Input string
L Length
‚™´ Join on
' Literal string `'`
Implicitly print
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~14~~ 12 bytes
```
J''CL¬πJ'+SRL
```
[Try it online!](https://tio.run/##yygtzv7/30td3dnn0E4vde3gIJ/////n5OelJyYlp6SmAQA "Husk – Try It Online")
Same approach as [DLosc's Pip answer](https://codegolf.stackexchange.com/a/247001/95126).
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 21 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
1↓⟜∾'+'∾¨1↓↑∾⟜'''⊸∾¨↓
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMeKGk+KfnOKIvicrJ+KIvsKoMeKGk+KGkeKIvuKfnCcnJ+KKuOKIvsKo4oaTCgpGICJhYmMi)
`↑` gives prefixes, `↓` suffixes. `∾⟜'''⊸∾¨` joins matching prefixes and suffixes with a single quote.
`1‚Üì` removes the first value (empty prefix ‚àæ `'` ‚àæ full suffix).
`'+'∾¨` prepends a + to each string.
`1‚Üì‚üú‚àæ` joins the string and removes the leading +.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 28 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{1‚Üì‚•ä'''‚àæÀò‚ü®‚àò,‚â†ùï©‚ü©‚•ä¬´‚•ä'+'‚àæÀò‚䢂åúÀúùï©}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHsx4oaT4qWKJycn4oi+y5jin6jiiJgs4omg8J2VqeKfqeKlisKr4qWKJysn4oi+y5jiiqLijJzLnPCdlal9CgpGICJsb25nYWJjZGVmIg==)
returns the required string with a trailing space. removing that is +3 bytes
-3 from ovs, who also made this [tacit](https://mlochbaum.github.io/BQN/try.html#code=RuKGkDHihpPin5zipYonJyfiiL7LmCgx4oC/MCviiaAp4qWK4p+cwqvin5zipYonKyfiiL7LmOKKouKMnMucCgojIG9yOiAx4oaT4p+c4qWKJycn4oi+y5go4p+o4oiY4p+p4oi+4omgKeKliuKfnMKr4p+c4qWKJysn4oi+y5jiiqLijJzLnAoKRiAibG9uZ2FiY2RlZiI=).
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 83 bytes
```
v=$1\';until [ $v = \'$1 ];do a+=+$v;v=$(sed "s/\(.\)'/'\1/"<<<$v);done;echo ${a#+}
```
[Try it online!](https://tio.run/##ZVFha4MwEP3eX3GkgVNC13Xsw4a6Dbr9CtMPMcYqK7FoKkLxt7tL22UbC5j37nzvuNwVqq/n6mS1a1oLVRTDeR4yvpGYnKxrDpADHyADiXwDu6RsQYlM8CEhUdSbEli/ltGdjHGNcrNmaZryISadNYnRdQv8rJZimqdFafRBdQZWCpzpXRYxVWgGrDR0HVq7p7A0FQV93XaOxb8dZjwa7Ux5daFQBWqh8FYARYl/q6AIHKvA0QSOZeCoA8cicFSB4z5wtIHjv5ZReEDnATsP2HrA/@/RtdGfpqPnyPHjQY7PW/oeqdAtfJfj05YsVdtBFEGT3SfQpIyfl9@TyN92E0tAiCb2414AHZeRwg835w39veSMzwXTT76n/VXAuG/s4iUbhT2DLCM0V9Wxa6y7yGD1Aryndd5az/nrbpKWLfyq5y8 "Bash – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 151 bytes
```
char*f(char*c,int i){char*r=malloc(i*i+i);char*o=r,k=0;for(;k<i*i;){if(k++%(i+1)==1)*o++='\'';*o++=*c++;if(!*c)c-=i,*o++='+';}*o--=0;*o='\'';return r;}
```
[Try it online!](https://tio.run/##VZBBboMwEEXXcAo6FcLGQwWJujLORRoWxEAYQXBlyApxdmqcqlI3nu83X@M/1tld633XfW3TjvmikaYlIr76m1WPehyNZpSSIC49NMrioHLZGcvkULqW5Ct1bBAiZiQKrlTBUyOESq5JIr1KtRDSed5SzXWmCF99kcgtNVnmprmx3m7b5WmnyMptf6dJj8@mjcp5aUa6ffSX8B8jc6Aj8KOmifE1DHzCaGnnZf6q1Ar1TQOeEZoW8IQwmunuUNN2gEWOMPfGLoCfCM5WIADmmwyDYzX/Dy4YlYU7hDrxMAi@rcMdg3iOsksUz9cJ8PUYVdixP/krRFFxLsNt/wE "C (gcc) – Try It Online")
[Answer]
# [Julia](https://julialang.org), 40 bytes
```
a->join([replace(a,i=>"$i'") for i=a],+)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYsxDsIwEAR7v-JkIcUWTkVD43wEpTjiC1xknSPH4TM0aSKewFv4DUFhq9Xs7HMd5si4vB6YdaX9Ope-Pn8M1s2QWMwl0xixI4OOfaMPXGkLfcrAHlt3tH__9EMFWCAThshCk7EKtoyZpUQxxYEG34B2UCqrSMJ-Xd547VQgFZPcthqoV9M95bLPXw)
only works with all letters distinct
#### Why...how...what...
* `[... for i=a]` iterates over the string `a` and store the results in a list. `i` will be a `Char`
* `replace(a, i=>"$i'")` replaces all characters equal to `i` in `a` with `i` followed by `'`
* `join(..., +)` joins the list with `+`. `+` is a function, so `string(+) == "+"` is used.
[Answer]
# [R](https://www.r-project.org/), ~~81~~ 75 bytes
*Edit: -6 bytes thanks to Giuseppe*
```
function(x,`[`=substring)paste0(x[1,s<-1:nchar(x)],"'",x[s+1],collapse="+")
```
[Try it online!](https://tio.run/##TczBCsMgDADQf8llSjOo1zG/RApNbdoJEouxxb/vdtz5wav3yjVd1NLF/t5OiS0VMR3nMHs9F201yW4P0saj6cGhvp/uJfFD1XQ7ITwAe9DBTRhLznQoexjA/r0GcpGdlrjy9oMv "R – Try It Online")
Takes advantage of the vectorization of `substring` over a vector of start (& optional end) positions, and the vectorization & argument-recycling of `paste` over vectors of strings to paste-together.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
ż\'vṀ\+j
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvFxcJ3bhuYBcXCtqIiwiIiwic2hvcnQiXQ==)
No clue why I didn't vectorise insertion back in May 2022.
## Explained
```
żƛ?n\'Ṁ;\+j
żƛ # For each item P in the range 1...len(input):
?n # at position P in the input,
\'Ṁ # insert a '
; # end map
\+j # join the result of that on "+" and output
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 14 bytes
```
.
$`$&'$'+
.$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX49LJUFFTV1FXZtLT4Xr///EpGSulFSunPy8dCAzJTWNqzgjv6gEAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.
$`$&'$'+
```
Replace each variable with its derivative multiplied by the other terms plus a trailing `+` to sum the products together.
```
.$
```
Delete the final trailing `+`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ṛ€j”+sLj”'
```
[Try it online!](https://tio.run/##y0rNyan8///hztmPmtZkPWqYq13sA6LU/z/cselwO1Aw8v//xKRkhZRUhZz8vHQgMyU1TaE4I7@oBAA "Jelly – Try It Online")
Port of [DLosc's Pip solution.](https://codegolf.stackexchange.com/a/247001/85334)
```
€ For each element of the input,
·πõ the input.
j”+ Join the copies on +,
sL split into slices the length of the original input,
j”' and join those on '.
```
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
p”'$ṛ¦ⱮJj”+
```
[Try it online!](https://tio.run/##y0rNyan8/7/gUcNcdZWHO2cfWvZo4zqvLCBX@//DHZsOtz9qWhP5/39iUrJCSqpCTn5eOpCZkpqmUJyRX1QCAA "Jelly – Try It Online")
The implementation of `¦` is a bit questionable, so we can just abuse Cartesian product to make up for it.
```
p”' Pair each element of the input with ',
$ṛ¦ and substitute elements of that into the input at
ⱮJ each index, individually.
j”+ Join the results on +.
```
Just for fun, without preserving the order within each term, `ṭ-Ƥ”'ż@j”+` is 10.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 58 bytes
```
s->j=strjoin;j([j(strsplit(s,c),Str(c"'"))|c<-Vec(s)],"+")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxBCsIwFESv8vkbE0z2orZLLyC4KUVqmtSEkob8uBC8iZuAiGfyNqbYzQxvmJnnJ3TRnoeQXwaq9y0ZufluSdauohTdZP3OscaxAhRGmxgJxcUxRaZwhZw_1F6etGLEW4Fr5MvDoQthvDMCWUOI1pcd4AwIpnS5gAa7i0IB2OtZx8kPJei1mYmuU0zYLm85__0H)
A port of [@att's Mathematica answer](https://codegolf.stackexchange.com/a/246988/9288).
Takes input as a string. Requires that all characters are unique.
---
## [PARI/GP](https://pari.math.u-bordeaux.fr), 64 bytes
```
v->i=1;j=strjoin;j([j([j(v[1..i]),j(v[i++..#v])],"'")|c<-v],"+")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxBCsIwFESvEr4L82kS6E6oLV7ArZsSJMa2ppQ2JDEgeBM3BRHP5G1sqzDMvLeZx9sqZ46NHZ81yV_XUPPNZxd5YfI0a3MfXDuYPmtpuSSWqRBGIpvRJIkQqyhRMlgD3vWWxwkTwP_PXlnb3agnvCDWmT5MCLMAqemh0tQjIiMlqJMGRuBczd0NfRMqH7Tyi_vL4ALI_-k4_vYL)
Take input as a list of characters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ε''«Nǝ}'+ý
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3FZ19UOr/Y7PrVXXPrz3//@c/Lz0xKTklNQ0AA "05AB1E – Try It Online")
```
ε map each character (of the implicit input string)
'' the ' character
¬´ append to the current character
N iteration index
«ù replace the input string's Nth character with the character with ' appended
}
'+ + character
√Ω join by it
```
[Answer]
# [Raku](https://raku.org/), 33 bytes
This 33-byte version works on my local recent-ish version of Raku:
```
{join '+',.comb.map:{S/$^a/$a'/}}
```
But not on TIO, where a few more bytes are needed:
```
{join '+',.comb.map:{$^a;S/$a/$a'/}}
```
[Try it online!](https://tio.run/##DcZLDkAwFAXQrdxIowPCzMBvE@bkofWJelIm0nTtJTmDcyl7FMG8iDWa4HbeTshEptnEZswMXaUTPVVdLugnc@/DTS8iMaBp4TTE4CNotqhpnDArHHwuf2elca9snzZ8 "Perl 6 – Try It Online")
* `.comb` breaks the input string up into characters.
* `.map: { S/$^a/$a'/ }` returns a copy of the input string for each character, in which that character has had an apostrophe appended to it.
* `join '+'` joins those strings together with a plus sign.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¬£i''YÄÃq+
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rKNpJydZxMNxKw&input=ImFiYyI)
```
¬£i''YÄÃq+ :Implicit input of string
¬ :Split
£ :Map each element at 0-based index Y
i'' : Insert a "'" in U at index
YÄ : Y+1
à :End map
q+ :Join with "+"
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->s{s.chars.map{s.sub _1,'\&\''}*?+}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3VXTtiquL9ZIzEouK9XITC4Ds4tIkhXhDHfUYtRh19Vote-1aiNp1BaUlxQpu0UqJSckpSrEQwQULIDQA)
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 52 bytes
```
~(:-&(:& &:sub|(~:%&(~:+&?')|:& &:*)|:|&A)).D|~:*&?+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN03qNKx01TSs1BTUrIpLk2o06qxU1YCEtpq9umYNWFgLSNeoOWpq6rnU1FlpqdlrQ_SuKygtKVZwi1ZKTEpOUYqFCC5YAKEB)
[Answer]
# [Rust](https://www.rust-lang.org), 123 bytes
```
|s|{s.chars().map(|_|s).enumerate().map(|(i,w)|{let mut t=w.repeat(1);t.insert(i+1,'\'');t}).collect::<Vec<_>>().join("+")}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZG9bsIwFIXVMXkK46HXViCIreJv6SNU6lSJGueGpA0OtS9iSHiSLgztQ9GnqUMKpAMefD7bR0dH159fduvocJSpYWuVGyFZFQYFEkvGLDXi3pGVbDBnT2Rzs2Iz9r2ldPBwrGpXVy7WmbJOyHitNqJe1E7GaLZrtIrwfCvy_k7WVZO53hKj2S62uEFFYiQnFOfGoSWRR6M-vAD4q72MdVkUqGk8nj6jni7mcx_2Vvp6POJy31b4uXsNJmEwHLLHDPU7I3TEtHLowkC5JnSBHz2RCK6Wmss-4wqWOlJLaDYNXE7CkPn135zgyZsARgneMhWlWfmMBFNv5gVcjlFRQocNdHgFHW66XNhXurKGDvsaV0bocHqrm8tKS00tBw1FLoNWSmjFQit0Sgg2_mOpMD3Bqz3vs_O8_NPfoA-HVn8B)
] |
[Question]
[
## Task
Implement a kind of "some users are typing" system, which can be found in Discord and some other chat clients.
* If 1 user (say, Bubbler) is typing, output `Bubbler is typing...`
* If 2 users (say, Bubbler and user) are typing, output `Bubbler and user are typing...`
* If 3 or more users are typing (say, Bubbler, randomuser1, randomuser2, randomuser3), output `Bubbler and 3 others are typing...`
The input is a list of usernames (list of strings); single string with delimiters (symbols or newlines) is also allowed. The output is a single string. Always respect the order of the input usernames. A username can contain upper/lowercase letters, digits, and spaces. Both usernames and the entire input list are never empty.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
["Bubbler"] -> "Bubbler is typing..."
["no one"] -> "no one is typing..."
["HyperNeutrino", "user"] -> "HyperNeutrino and user are typing..."
["emanresu A", "lyxal", "Jo King"] -> "emanresu A and 2 others are typing..."
["pxeger", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"]
-> "pxeger and 10 others are typing..."
["10", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null"]
-> "10 and 10 others are typing..."
["and", "are"] -> "and and are are typing..."
["is"] -> "is is typing..."
["Bubbler is typing", "is", "are", "and"]
-> "Bubbler is typing and 3 others are typing..."
```
[Answer]
# [Whython](https://github.com/pxeger/whython), ~~84~~ 77 bytes
```
f=lambda a,*b:a+f" {'and %s are'%b?'is'%b} typing..."?f(a,f"{len(b)} others")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWN33TbHMSc5NSEhUSdbSSrBK105QUqtUT81IUVIsVEotS1VWT7NUzi4FUrUJJZUFmXrqenp6SfZpGok6aUnVOap5GkmatQn5JRmpRsZIm1NDwgqLMvBKNNA0lp9KkpJzUIiVNTS4MMR0FpYKK1HSCskBWXmlODlAVxHiY2wE)
This is my first answer in Whython, a *horrible* modification of Python [I made](https://www.pxeger.com/2021-09-19-hacking-on-cpython/). Its only new feature so far is `?`, which is a short-circuiting exception [mis-]handling operator.
Here I use it to handle the case where there are more than 2 people typing: I recurse on the function `f` with a newly formatted second argument.
This answer also makes use of the (not Whython-specific) fact that you can `%`-format a string with a tuple of arguments, as long as it's the right number of arguments - and that number can also be `0` or `1` - so both `" is"%()` and `" and %s are"%("second argument",)` work fine.
-7 bytes thanks to @ovs: by trying to format `and %s are` (which requires `b` to be of length 1), then trying to format `is` (which requires `b` to be empty), we can save some bytes by avoiding `len()`.
[Answer]
# [Python 3](https://docs.python.org/3/), 89 bytes
```
lambda a,*b:a+f" {b and'and %s are'%[b[0],'%d others'%len(b)][len(b)>1]or'is'} typing..."
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRRyvJKlE7TUmhOkkhMS9FHYgVVIsVEotS1VWjk6INYnXUVVMU8ksyUouK1VVzUvM0kjRjoyG0nWFsfpF6ZrF6rUJJZUFmXrqenp7S/4KizLwSjTQNJUclTU0uJJ6OgpITNiEg4QwiXICS/wE "Python 3 – Try It Online")
-2 bytes thanks to dingledooper
[Answer]
# [Haskell](https://www.haskell.org/), 94 bytes
```
g(a:x)=a++f x++" typing..."
f[]=" is"
f[x]=" and "++x++" are"
f l=f[show(length l)++" others"]
```
[Try it online!](https://tio.run/##HY6xbsMwDET3fMVB6GBDjT6ggIcEmdJ06mgYAYPKthBaMiQatb/ekTLdI3ng3UjpaZl3N80hCi4kZG4uCSrnnaQaxyP6ECGjzRrExn2o6GutG9K6x6q1gmyz84MxRh36tmsUXCq0FiT/B6X120fR5j246ds0hv@KrR9kBNflGHJCTKrbJ3IeDSaaf@6o5kV@Jd68GWp8QMhxlnc1tOq8PB5so/qEshP5aNOCU5l4W4kLXAO@c7f89gU "Haskell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ṡ`, 32 bytes
```
ḣ:[‛λ¬$ḣ[_?L‹‛÷„]‛λ½|_‛is]`Ȯ»...
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=%E1%B9%A1&code=%E1%B8%A3%3A%5B%E2%80%9B%CE%BB%C2%AC%24%E1%B8%A3%5B_%3FL%E2%80%B9%E2%80%9B%C3%B7%E2%80%9E%5D%E2%80%9B%CE%BB%C2%BD%7C_%E2%80%9Bis%5D%60%C8%AE%C2%BB...&inputs=%5B%22Bubbler%22%2C%22joe%22%2C%22x%22%5D&header=&footer=)
```
ḣ # Push the first item (first user) and the rest to the stack
# The first item will remain on the bottom of the stack
:[ ] # If the rest exists (More than one user)
‛λ¬$ # Push 'and' under the rest
ḣ # Push the first item (second user) and rest to the stack
[ ] # If the rest exists (≥3 users)
_ # Pop the second user
?L‹ # Push the input's length, -1
‛÷„ # Push 'others'
‛λ½ # Push 'are'
| # Otherwise (one user)
_‛is # Pop the resulting empty list and push 'is'
`Ȯ»... # Push 'typing'
# (ṡ flag) join stack by spaces)
```
[36 bytes](https://lyxal.pythonanywhere.com?flags=&code=%E1%B8%A3%3A%5B%E2%80%9B%CE%BB%C2%AC%24%E1%B8%A3%5B_%3FL%E2%80%B9%E2%80%9B%C3%B7%E2%80%9E%5D%E2%80%9B%CE%BB%C2%BD%7C_%E2%80%9Bis%5D%60%C8%AE%C2%BB...%60W%E1%B9%84&inputs=%5B%22Bubbler%22%2C%22joe%22%2C%22x%22%5D&header=&footer=) flagless.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 52 bytes
```
[POgg?["and"#c?[#g"others"]b"are"]"is""typing..."]Js
```
(Or 50 bytes in Pip `-s`, which would use a flag to accomplish the same thing as the `Js` at the end.)
Takes the names as separate command-line arguments. [Try it online!](https://tio.run/##DckxDoAgEATAr5il5wskllhoTyhACZIYIHdQ@PrTaaeXLuKOPWfjEOoFdRqnMtq4EzF8RKAEj8LAeHupWWsNb1lE1hnjk0hsW7Y/ZHKiDw "Pip – Try It Online")
### Explanation
One big list, with the exact contents depending on the number of inputs, joined on spaces:
```
[ ; List containing:
PO g ; Pop first element of g (the command-line args)
g ? ; Is g still nonempty?
[ ; If so (multiple names case), list containing:
"and" ; This string
# c ? ; Is the third cmdline arg nonempty?
[ ; If so (more than 2 names case), list containing:
# g ; Number of elements remaining in g
"others" ; and this string
]
b ; Otherwise (2 names case), second cmdline arg
"are" ; and this string
]
"is" ; Otherwise (single name case), this string
"typing..." ; and this string
]
J s ; Join that list (including all sublists) on space
```
[Answer]
# [Vim](https://www.vim.org), ~~92~~ 89 bytes
```
:3,$s/.*/\=line('.')-1.' others'
:1s/\v(\n.+)+/\1
:2s/^/and
ois typing...<esc>:3s/is/are
V{J
```
[Try it online!](https://tio.run/##BcHBCsIwDADQe76iB6Gb2xKz3Yp68OgHeCrCpkELo5NmK4gfX9/Lpbih3SnhnvxpDlEqi7buGK1Z1rckteBYyefKR2zqhjyD65XuNMangSWoWb@fEF@IeBR9nN2gFJTGJHD7XUu5bNM0SwI@ADNwX7r8Bw "V (vim) – Try It Online")
### Explanation
```
:3,$s/.*/\=line('.')-1.' others'<cr>
```
On every line from line 3 to the end of the buffer (if they exist), replace the contents of the line with the line number minus 1 followed by the string `others`.
```
:1s/\v(\n.+)+/\1<cr>
```
Beginning at (the end of) line 1, find 1 or more matches of a newline followed by some characters. Replace with the last (newline + characters) match.
```
:2s/^/and <cr>
```
Add `and` at the beginning of line 2 (if it exists).
```
ois typing...<esc>
```
Open a new line after the cursor (which is always on the last line at the point) and insert `is typing...`.
```
:3s/is/are
```
If that new line was line 3, change `is` to `are` (if it was line 2, leave unchanged).
```
V{J
```
Enter visual line mode, select to the beginning of the buffer, and join lines (space-separated).
[Answer]
# [R](https://www.r-project.org/), ~~113~~ 102 bytes
Or **[R](https://www.r-project.org/)>=4.1, 95 bytes** by replacing the word `function` with `\`.
```
function(s,l=length(s)-1,`?`=paste)s[1]?"if"(l,"and"?"if"(l-1,l?"others",s[2])?"are","is")?"typing..."
```
[Try it online!](https://tio.run/##tVLdSsMwFL73KQ5nNy1kZZ3XtejVUPAFxmDdTLtATEp@YH36epK2m7KqN3oRkkO@v5DP9HXR114dndAqsUwWkqvGnRKbLnO2L/dFW1nHU7vNdyWKGhPJsFJvOA4EkiVqd@LGIrPb9S4tsTIcGQqLdHZdK1STZRn2dXJM8MkfDpIbTNMFLB9gmkFYuELvIlRp0IpfkMM4B9x0LTev3DsjlEYG6O0nhy@3QNkhXAOFvBHi75Uy3Hp4DCqyO1cyHJ41vBDuoniFRbk1DO@flWzPvKEwpKK8lH@2T1EG@RgjX/2UI1/9WwYy/t0/dIaIoRoTL5DiIvgcJRRohNKnz/z7TXeCA7FGHxYtvm9aNL@fD91/AA "R – Try It Online")
It appears that `paste` chains nicely, so we can rename that to `?` and use like string addition (with convenient spaces).
[Answer]
# [C (clang)](http://clang.llvm.org/) with `-m32`, ~~151~~ ~~148~~ 144 bytes
* -3 thanks to ceilingcat
* -4 by changing the base index from 0 to -1
To try a different approach from the other C submission, only the list of strings is needed as input for this answer. To get the length of the list, the function is called recursively and output is printed as the function processes the list.
De-golfed:
```
g(*s,i) { // type-punning 'char **' as 'int *'
printf(
~i? // is this the first element?
*s? // (first element) no: end of list?
i? // (end of list) no: is this the second element?
"": // (second element) no, don't print if there is only 1 element
s[1]? // (second element) yes, are there only 2 elements?
"": // no, don't print second element if there are more than 2
" and %s": // yes, print second element
i<2? // (end of list) yes: are there more than 2 elements?
"": // no
" and %d others": // yes, print summary
*s, // (first element) yes: print first element
*s?
: // use string if not at end
i); // otherwise use the list count
*s?
g(s+1,i+1): // continue processing list
printf(" %s typing...", i<2? "is": "are");
}
f(s) { g(s,-1); } // initialize list count
```
```
g(*s,i){printf(~i?*s?i?"":s[1]?"":" and %s":i<2?"":" and %d others":*s,*s?:i);*s?g(s+1,i+1):printf(" %s typing...",i?"are":"is");}f(s){g(s,-1);}
```
[Try it online!](https://tio.run/##tVJBT8IwFL7vV7yUmLSjEKc3BhI8GSUcUE@Ew9i60WS0y9rpCJk/3fmKkOj0qKf33tfv@17ar/EgziOVtW1GfcMlOxSlVDalb3Lqm6mcEjIyq2DtKoFIJXBhyEiOr74ACWi7FSXi6ICikWQhloyafsBlP2CjkydBMdh9IVU2HA4JR/eoFOgjDWFhk1LDDqjigwCntidVnFeJgLGxidTD7Y3XS0QqlYDHp@VsuaQ1ujCg8TYq/dWaHWq@eJ7PG8/DbbCLpKIvWiYMDh6AI4Hvm9V64kY4e5DbarPJRUkY/wYrDVqJLnq3L0S5EJXFC2nCgVTmp1TsIlUKU8HMMfJ9HeWuudfwgDfvsotaZOiBBFXl@Z/Vzpbg8r834FdwRy7QzolLl//25iDP38EpkXbSu4JuJ5HLFJuGY3y@DT3sU11SOzEh4Ay23/@MGHHqWxYe26KyhhJynBqvad/jNI8y0w5211ft4PUD "C (clang) – Try It Online")
[Answer]
# JavaScript, 77 bytes
```
a=>a[0]+` ${(l=a.length-1)?`and ${l>1?l+' others':a[1]} are`:'is'} typing...`
```
[Try it online!](https://tio.run/##tU7NqoJQEN73FAe5oOLtkNvCpLu6FPQCIjjVZMY0I@cnkkvP7rVt2K5W8zHf7xmuYPemad2U5YD9MeshW0IxK5NKff1FlIEm5NqdpmmcV8CH4UvLNKckVOJOaGw4hyIt7woMVvOwseFdua5tuNZaV/1e2AqhJqmjY1QEP363IzRBGceLyTPJooRxnPvtWjRb9M40LMG3Crx9FYMXYIPWq9VDR90N6AHWojbDrHFPe8N6yBtk7Inedke70tlHevp/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 47 bytes
```
ḢɓL,“¥ṃkŒ»ƊḷḊ?“ and ”;;“@k»ʋ;“ is”$ḷ?ṭ⁹“Æʋ@1'ɼ»
```
[Try it online!](https://tio.run/##y0rNyan8///hjkUnJ/voPGqYc2jpw53N2UcnHdp9rOvhju0Pd3TZA0UVEvNSFB41zLW2BnIcsg/tPtUNYilkFgMFVYDq7B/uXPuocSdQ7HDbqW4HQ/WTew7t/v8/WsmpNCkpJ7VIKZYrWsmjsiC1yC@1tKQoMy9fSUdBqbQYKpOam5hXlFpcquAIEs6prEjMATG88hW8M/PSwUoKKlLTgaqBonmlOTlUo0FGGxpQ31iE14GBpFBSWQDyB1A2sxhEJhalgqm8FKVYAA "Jelly – Try It Online")
Full program, as it uses Jelly's smash-printing and nilad dumping.
## How it works
```
ḢɓL,“¥ṃkŒ»ƊḷḊ?“ and ”;;“@k»ʋ;“ is”$ḷ?ṭ⁹“Æʋ@1'ɼ» - Main link. Takes a list of usernames U on the left
Ḣ - Chop off the first username, B, and set U' to be U without its head
ɓ - Start a new dyadic link f(U', B)
? - If:
ḷ - U' is non-empty
ʋ - Then:
? - If:
Ḋ - U' has more than one element
Ɗ - Then:
L - Take the length of U'
“¥ṃkŒ» - Compressed string: " others"
, - Pair; [len(U'), " others"]
ḷ - Else: Yield B
“ and ”; - Prepend " and "
;“@k» - Append " are"
$ - Else:
;“ is” - Append " is"
ṭ⁹ - Tack all of this to the end of B
“Æʋ@1'ɼ» - Unparseable nilad. Smash print the previous stuff, then print " typing..."
```
[Answer]
## Excel, 100 bytes
```
=A1&IF(COUNTA(A:A)=1," is"," and "&(IF(COUNTA(A:A)=2,A2,COUNTA(A:A)-1&" others"))&" are")&" typing…"
```
[Answer]
# [PHP](https://php.net/), ~~94~~ 91 bytes
```
fn($a)=>"$a[0] ".($a[1]?'and '.($a[2]?count($a)-1 .' others':$a[1]).' are':is).' typing...'
```
[Try it online!](https://tio.run/##tVJPT8IwFD@7T/HSLNlIYDC9gUA0MSFqlPtcSBkdm5lt03YJxPjZ52tBp0LwooelfX2/f12fLGRzOZWF9Dw/H0OT89CnnfGE@DQZpEAiLJM4nQaUryBw1Xk6zUTNjQX2YogCEKZgSgdDB@3gAVUsGJbabs1WlnwdRVHQjNDDMG00jCHxABJyXS@XFVMk7UK/35vAxwGUuiUSB@UCBGctclcfAc62kqkHVhtVckG6QGr91eFbG@ytbN8m/inEXihXTNdwZVWq7YZWdnMr4A5hO0Wwki3Q6Z3v/8cxTblha0yDMryuqj9bP2@303cx4sGJHPHg/zKg8a/@CLBE7LQ8S3Ifwo9QSt1C8dUPH/5gdqwDsvY@XedwYtSc@cVhaC/Fwc2FYjQrQthPMNW4gw68emcsKwQ8a8EXjGdixULXQbsng6Z@HvoGq/lsvrh5vB95b807 "PHP – Try It Online")
Raw first try at it, probably still golfable. It's a pity PHP cannot handle concatenation or nested ternary conditions without brackets..
EDIT: 3 bytes saved with thanks to Dom Hastings and 640KB's suggestions!
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~79 ...~~ 73 bytes
```
->a,*s{[a,s[0]?[:and,s[1]?[s.size,:others]:s,:are]:"is","typing..."]*" "}
```
[Try it online!](https://tio.run/##tVLNSsQwEL77FMN4W7Kl1VvAFfe0KPgCJYcUs2sgJiVpYKv47HWS0q6yVS96CJlhvj@S8bHph/3NsN5ItgpvtWShLsVtzaV9orKiMhRBvyrGXfesfBA8MC69Ehx1QIZd32p7KIoCxQoB34cW9jVuY9MY5VHAJaw3MPWgA5wIFxlqHTirZuTYLgF3fav8o4qd19YhA4zhk8OXKVB6SGOgpGdC6kVar0KEu6Ri@qM0qbh38EC4WfEEy3JXMD7AomR7VAcKQyo2GvNn9xRllM8xqvKnHFX5bxnI@Hd/QiQijWZeIuVD8CUKbdEEpU9f@Pez3UkOafdGH5Ytvt@0bH69HHr4AA "Ruby – Try It Online")
Thanks ovs for -3 bytes
[Answer]
## Prolog, ~~108~~ 135 bytes (of which 27 are spent on producing a string)
This was fun, although Prolog does not have very much scope for golfery.
My first, unsubmitted, attempt tried to use Prolog's Directed Clause Grammar syntax, but I couldn't get that to be shorter.
IIRC the rules here on CoGoSO correctly, it is permitted to return a string, and not required to print it; so I'm returning in a variable (`O`), as is traditional in Prolog.
```
f([X|R],O):-g(R,P),flatten([X,P,typing],Q),atomics_to_string(Q,' ',O).
g([],is).
g(L,[and,C,are]):-L=[Y],C=Y;C=[N,others],length(L,N).
```
Legend to the one-letter variable names:
```
% X: first name
% R: Rest of the names
% L: Rest of the names, seen from g/2's perspective
% O: Output
% C: Company, i.e. a word list like '[and, Y]'.
% P: intermediate output: nested list of atoms (representing inner words)
% Q: intermediate result: flat list of atoms
```
Usage examples:
```
?- f([jan,piet,klaas,tjoris,korneel], O).
O = "jan and 4 others are typing"
?- f([jan,piet,klaas], O).
O = "jan and 2 others are typing"
?- f([jan,piet], O).
O = "jan and piet are typing"
?- f([jan], O).
O = "jan is typing"
```
Ungolfed:
```
f([X|MoreNames], Out) :-
% InnerWords like 'is' or '[and, Y, are]'
innerwords(MoreNames, InnerWords),
% Flatten `[X, [and, [N others], are], typing]`
% to `[X, and, N, others, are, typing]`
flatten([X, InnerWords, typing], AllWords),
% Turn it into a string. This is not a very Prolog thing to
% do, but the challeng requests it, so here goes.
atomics_to_string(AllWords, ' ', Out).
% No more others: produce 'is' for 'X is typing'.
innerwords([], is).
% One or more others
innerwords(MoreNames, [and, Company, are]) :-
% MoreNames is a list of 1, s
Company=Y, MoreNames=[Y] ;
% If we reach here, there are 2+ others.
% (Or our caller is wrongly asking for additional solutions,
% and getting wrong answers as a reward.)
% [and, [N, others], are]
Company=[N, others], length(MoreNames, N).
```
[Answer]
# [Julia 1.0](http://julialang.org/), 82 bytes
```
t=" typing..."
>(x)="$x is$t"
x>y="$x and $y are$t"
x>y...=x>"$(length(y)) others"
```
[Try it online!](https://tio.run/##tZLfS8MwEMff91ecoQ8tbGWdb0IL/hiIovjgg1D2kLnbFolpSVNp//p6SaOu1uGLFkpz33zue5deXmopeNJ0nUkZmLYUahfHMZtkYROlLGhAVIFhkyZrXcTVBoIWuEavEpw2GQtCiWpn9mEbRVCYPeqKddtCgxQKQSjQyDd2XYXRBOhxekpyKfkzhjacAptlDNIMWJqxAYZvXIZ3aHhccl31eNQTpRbKSOWkPFn1osaKsrIPkZocwrTfC2Lr2JPUVcoXK6ceomz59LC8fFxenQGbflB9MqrNwDWakNLl7KJeryVqtoIZncVH9CMP/2/OVAGFQg/1wYi5bkvU91gbqlBQeVZXn76DPTcYu2lHM/TAV67ojDWcWwPZNlzaxU0BtwR5sy/IOS38DMduZYM7aoEMVC3ln337Lnpz10EyP9pCMv@n8lTzl9K0bXNI9ymWdy@RI1pUnqKxfp/s6FZYX0rw7lNnfewGuZKnP3f5Dg "Julia 1.0 – Try It Online")
the names are expected as arguments of the function `>`, for example `>("Bubbler")`, `>("a","b","c")`
# [Julia 0.7](http://julialang.org/), ~~79~~ 75 bytes
```
!t=t[(L=end-1;1)]*" $(L<1?:is:"and $(L<2?t[2]:"$L others") are") typing..."
```
[Try it online!](https://tio.run/##tVLLTsMwELz3K7ZWDwlqo6YckAJpxaMSgoI4cECKenCpW4yME9kOar8@rO0UGkLFBSIl8c7Ozqy9fi0FpydV1TWpyYJZyuRyEJ/G4fyIQC@YncWThOuEULl04WhistE8Ib0Z5OaFKU1CoIrh12wLLtdRFJFqlSsQXDLgEhSjS7vWQdgBfByeIlwI@swCG/aBDMYE0jGQdEwaNPZORXDHDI0KqrSnh55RKC6NkA7K4rkHFdNY1W2COyYmPcBXjthNnQ3ux6H7VDJ9ephePk6vEiD9HcsX4wE1VMMOIlVGLsrFQjBF5jDAjdQRcL13MJ2MyBxyyWqSD1qc623B1D0rDTrkaE9K/anbyIGdik3aETQ12BuVuMcSzq2A2G6osIubHG6RVIt9kZzSqB5pW63YsDW2gAKyFOLP/r4LL@46iIcHW4iH/2SPnr9YY9rW2GvuSyzfvchssbmuWTjW75Nt3QqriwW1et9JH7pBzvL45y4/AA "Julia 0.7 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) + `-pl`, 61 bytes
Thanks to [@Xcali](https://codegolf.stackexchange.com/users/72767/xcali) for -2!
```
s;$; @{[!(@_=<>)?is:'and',$#_?@_.' others':@_,are]} typing...
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiczskOyBAe1shKEBfPTw+KT9pczonYW5kJywkI18/QF8uJyBvdGhlcnMnOkBfLGFyZV19IHR5cGluZy4uLiIsImFyZ3MiOiItcGwiLCJpbnB1dCI6IkJ1YmJsZXJcbnVzZXIxXG51c2VyMiJ9)
## Explanation
The first name is implicitly stored in `$_` (via `-p`) so it's easy to just add to it a string consisting of a leading space and an in-line list `@{[...]}`, finishing with `typing...` as that's always needed no matter what. The in-line list will be implicitly joined by `$"` (space), which allows use of some barewords, saving bytes for the quotes. The rest of the input (`<>`) is slurped into `@_` which, if it's non-empty, results in a list consisting of `'and'`, and if `$#_` is truthy (`$#_` is the last array index of `@_`, which will be `0` if there is only one entry), we use `@_` in a scalar context (which is the number of elements i n`@_`) concatenated with `' others'`, but if `@_` only contains one entry, add it as is. If `@_` is empty, we just add the bareword `is` to the in-line list.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ṡ`, ~~42~~ 41 bytes
```
ḢḢ[₌hL‹` ÷„`+"]` λ¬ `j`is λ½`⌈?L‹ḃi`Ȯ»...
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=%E1%B9%A1&code=%E1%B8%A2%E1%B8%A2%5B%E2%82%8ChL%E2%80%B9%60%20%C3%B7%E2%80%9E%60%2B%22%5D%60%20%CE%BB%C2%AC%20%60j%60is%20%CE%BB%C2%BD%60%E2%8C%88%3FL%E2%80%B9%E1%B8%83i%60%C8%AE%C2%BB...&inputs=%5B%22Joe%22%2C%20%22Mama%22%2C%20%27lol%27%5D&header=&footer=)
Lovely dictionary compression. [44 bytes flagless](https://lyxal.pythonanywhere.com?flags=&code=%E1%B8%A2%E1%B8%A2%5B%E2%82%8ChL%E2%80%B9%60%20%C3%B7%E2%80%9E%60%2B%22%5D%60%20%CE%BB%C2%AC%20%60j%60is%20%CE%BB%C2%BD%60%E2%8C%88%3FL%E2%80%B9%E1%B8%83i%60%C8%AE%C2%BB...%60W%E1%B9%84&inputs=%5B%22Joe%22%2C%20%22Mama%22%2C%20%27lol%27%5D&header=&footer=)
## Explained
```
ḢḢ[₌hL‹` ÷„`+"]` λ¬ `j`is λ½`⌈?L‹ḃi`Ȯ»...
ḢḢ # If the length of the input is > 2:
[₌hL‹ # Push the head of the input and the length of the input - 1
` ÷„`+ # and append the string " others" to that
" # and wrap both in a list
] # endif
` λ¬ `j # Join the top of the stack on " and "
`is λ½`⌈ # Push the list ["is", "are"]
?L‹ # And push the lenght of the input - 1
ḃi # boolify it to make it 0 or 1 (this is basically just checking if the list length is 1) and index into the list
`Ȯ»... # Push "typing..." to the stack
# The -ṡ flag joins the stack on spaces. Without it, you'd need `WṄ for +3 bytes.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ćs©gĀi'€ƒ®ćsgĀi\Ig<'ˆ†]…is€™#Ig≠è“ÜÔ...“ðý
```
[Try it online](https://tio.run/##yy9OTMpM/f//SHvxoZXpRxoy1R81rTk26dA6oACIG@OZbqN@uu1Rw4LYRw3LMouBso9aFil7pj/qXHB4xaOGOYfnHJ6ip6cHYm04vPf//2glp9KkpJzUIiUdpdJiMFWSWlwCpJJyEpViAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/yPtxYdWph9pyFR/1LTm2KRD64ACIG5MZbqN@um2Rw0LYh81LMssBso@almkXJn@qHPB4RWPGuYcnnN4ip6eHoi14fDe/0p6YTr/o6OVnEqTknJSi5RidaKV8vIV8vNSwUyPyoLUIr/U0pKizLx8JR2l0mKomtTcxLyi1OJSBUegaE5lRWIOkPbKV/DOzEsHKyioSE0HqtVRyivNyaGUAhloaEBFwxLzUoDcxCKILzOLwRQ0DBQyixVKKgtAHtEBSUHU6YD1ICmDhYaOUklqcQmQSspJVIqNBQA).
**Explanation:**
```
ć # Extract head of the (implicit) input-list; pop and push
# remainder-list and first item separately
s # Swap so the remainder-list is at the top
© # Store it in variable `®` (without popping)
gĀi # Pop and if there are any strings left (2+ inputs):
'€ƒ '# Push dictionary string "and"
® # Push list `®`
ćs # Extract head and swap again
gĀi # Pop and if there are any strings left (3+ inputs):
\ # Discard the head we've pushed
Ig< # Push the input-length - 1
'ˆ† '# Push dictionary string "others"
] # Close both if-statements
…is€™ # Push dictionary string "is are"
# # Split it on spaces: ["is","are"]
Ig # Push the input-length
≠ # Check that it's NOT 1 (0 if 1; 1 otherwise)
è # Use that to index into the pair
“ÜÔ...“ # Push dictionary string "typing..."
ðý # Join the entire stack with space delimiter
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `'€ƒ` is `"and"`; `'ˆ†` is `"others"`; `…is€™` is `"is are"`; and `“ÜÔ...“` is `"typing..."`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 63 bytes
```
^.*$
$& is
(¶.*){2,}
¶$#1 others
¶(.*)
and $1 are
$
typing...
```
[Try it online!](https://tio.run/##nY9NCsIwEIX3c4oBo9QyBOsNdCUKbtyLKQ4aiEnJD7SI1@oBerGaQi@gmwfz3jx4n@eorRqXxeVG41WWAsQKdYBi6GW5fm/pA0MvFhW6@GQf8lFkH1DZO4oKlWcQgLFrtH1IKcdxn@rasAfr0FmGQ9ewP3OKXltHKeSEX8p6Dgl3ZLpWGTo6POU6NC0/2JNNxvwkUG3@KGUCmuZn2Hlz5p5JSIcpo/zzBQ "Retina 0.8.2 – Try It Online") Takes newline-delimited input but test suite splits on commas for convenience. Explanation:
```
^.*$
$& is
```
Just one person is typing.
```
(¶.*){2,}
¶$#1 others
```
If there are at least two others then replace the list with a single element giving their count.
```
¶(.*)
and $1 are
```
More than one person is typing.
```
$
typing...
```
Complete the sentence.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
S WS⊞υι¿υ«and ¿⊖Lυ⁺Lυ others⊟υ are»is¦ typing...
```
[Try it online!](https://tio.run/##XY7LCsIwFETXzVdcskpB@wNdCW58LAp@QWivTSBNSh5qEb89JvVV3F1mztyZVnDbGq5ibKzUnu30GPzJp7tnZVmTl0qBpvsqpEL4Q6AJTrCwApkIeQYWSriT4p3jupujRXa22FocUHvs2BF171MuP5jRRgX3U1dAwXiB1tG8okDl8AOaMcfqbwdwi7njQRYUlY4u5vtpTHOrqkpijDhwbdEF2BA13bgiewOH5JO4vqgn "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings, which for some reason is golfier than taking input as a JSON list. Explanation:
```
S
```
Output the first name and a space.
```
WS⊞υι
```
Read in any other names.
```
¿υ«
```
If there were any, then:
```
and
```
Output `and` (with a trailing space).
```
¿⊖Lυ
```
If there was more than one other, then...
```
⁺Lυ others
```
... concatenate the count to the string `others` (with a leading space) and output that, otherwise...
```
⊟υ
```
... output the last (and only other) name.
```
are
```
Output `are` (with a leading space).
```
»is
```
Otherwise, output `is`.
```
typing...
```
Output `typing...` (with a leading space).
[Answer]
# [C (clang)](http://clang.llvm.org/) `-m32`, ~~109~~ 107 bytes
*-2 thanks to ErikF!*
```
t(*n,l){printf(--l?l-1?"%s and %d others are%s":"%s and %s are%s":"%s is%3$s",*n,l-1?l:n[1]," typing...");}
```
[Try it online!](https://tio.run/##vVNdb4IwFH3fr7hpRgJanIpf6BazPS1bsj9geECt2KQWQkumM/71sZaCmUp4WsbLoT3nnlN6Lyt3xUIe5bm0Wxwz55iklMuN7bpsztzeHFkCQr4Gaw2x3JJUrVJiCTQ9Exc7VFjevUBYe6lqNuWLXoARyENCedTpdJAzO@UqAXYh5bZzvAP1rLZhCi1JhOwtAniCI6CXbLlkJEVwml1J@pWExxBzUqPwKsXrISHpB8mk@qYYYUCZqLUcVAVkF/KUiAyetZod9iHTL28xvKvj11QOq8pkTyLlrcQ8Y@zP8DZxVCX2uv@QNq7SVKu1TLW6RjWpVFTUsP5VT9WQlPOgHVVJ6YtNyqVB4SBKh2JCcAF9A56BgYGhgZGBsYGJAV/7FsZ6@hjhkdyWvsWufgT9IvHGxMBDubT1QVoO/s32G1nvhq1LGDR6DBvZ0S1bFzFuNJk0sv41WwScMFDTnk2c2lTdXncGFB7BV9BuOyBt0zAa4PMl00BZJ5kUNlK//90p/15tWBiJ3P3M3Z3X/wE "C (clang) – Try It Online") Takes input as an array of `char*` and its length.
# [C (clang)](http://clang.llvm.org/), ~~115~~ 108 bytes
*-7 thanks to ErikF!*
```
t(**n,l){printf(--l?l-1?"%s and %d others are%s":"%s and %s are%s":"%s is%3$s",*n,l-1?l:n[1]," typing...");}
```
[Try it online!](https://tio.run/##vVNdb4IwFH3fr7hpRgJanIpf6BazPS1bsj9gfEAt2KQWQkumM/71sZaCmUp4WsbLoT3nnlN6L2t3zQIe5bm0Wy2OmXNMUsplaLsumzO3N0eWgIBvwNpALLckVauUWAJNz8TFDhWWdy8Q1l6qmk35orfECOQhoTzqdDrImZ1ylQC7gHLbOd6BetbbIIWWJEL2Fkt4giOgl2y1YiRFcJpdSfqVhMcQc1Kj8CrF6yEh6QfJpPqmGGFAmai1HFQFZBfwlIgMnrWaHfYB0y9vMbyr49dUDqvKZE8i5a3EPGPsz/A2cVQl9rr/kDau0lSrtUy1ukY1qVRU1LD@VU/VkJTzoB1VSemLTcqlQeEgSodiQnABfQOegYGBoYGRgbGBiQFf@xbGevoY4ZHclr7Frn4E/SJxaGLgoVza@iAtB/9m@42sd8PWJQwaPYaN7OiWrYsYN5pMGln/mi0CThioaU8YpzZVt9edAYVH8BW02w5I2zSMLvH5kulSWSeZFDZSv//dKf9ehyyIRO5@/gA "C (clang) – Try It Online") Takes input as an array of `char*` and its length.
[Answer]
# [Zsh](https://www.zsh.org), 67 bytes
```
x=(is "and $2 are")
echo $1 ${x[#]-and $[~-#] others are} typing...
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3nStsNTKLFZQS81IUVIwUEotSlTS5UpMz8hVUDBVUqiuilWN1wXLRdbrKsQr5JRmpRcUgZbUKJZUFmXnpenp6EKOgJm6NVnIqTUrKSS1S0lFQKqhITQeyYqGSAA)
Looks up the correct format string into the array `$x` (one of `is`, `and $2 are`, or an unset variable), defaulting to `and $[~-#] others are` (where `$[~-#]` is `number of arguments - 1`), and prints that with the first input `$1` and the string `typing...`.
---
## [Zsh](https://www.zsh.org), 79 bytes
```
T=\ typing...
1()<<<$1\ is$T
2()<<<"$1 and $2 are$T"
$# $@||2 $1 $[~-#]\ others
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3_UNsYxRKKgsy89L19PS4DDU0bWxsVAxjFDKLVUK4jMBcJRVDhcS8FAUVI4XEolSVECUuFWUFFYeaGiMFoIxKdJ2ucmyMQn5JRmpRMcRYqOlbo5WcSpOSclKLlHQUlAoqUtOBrFioJAA)
* Defines two functions called `1` and `2` which print formatted messages for singular and plural, respectively
* Then it calls the function with the name `$#` (the number of arguments), so that if 1 or 2 people are typing, the correct message is printed
* If there are more than 2 arguments, the function call will fail, triggering the `||` branch
+ This calls `2` with the first argument and the string `$[~-#] others`
- (It has to be `~-#`, because `#-1` doesn't work, although I don't really understand why)
[Answer]
## Batch, 170 bytes
```
@if "%2"=="" echo %~1 is typing...&exit/b
@set s=%~1
@set t=%~2
@set n=2
:l
@if not "%3"=="" set t=%n% others&set/an+=1&shift&goto l
@echo %s% and %t% are typing...
```
Takes input as command-line parameters. Explanation:
```
@if "%2"=="" echo %~1 is typing...&exit/b
```
Handle the case of there only being one user.
```
@set s=%~1
@set t=%~2
@set n=2
```
Assume there are two users.
```
:l
@if not "%3"=="" set t=%n% others&set/an+=1&shift&goto l
```
While more users are found, update the number of others and increment the total number of users.
```
@echo %s% and %t% are typing...
```
Output the users or count as appropriate.
[Answer]
# [Python3](https://docs.python.org/3/), 95 bytes:
```
lambda d:f'{d[0]} {"and "+[d[1],f"{l-1} others"][l>2]+" are"if(l:=len(d))>1else"is"} typing...'
```
This solution requires no pre-formatting of the input list (i.e no unpacking).
[Answer]
# [Rust](https://www.rust-lang.org/), ~~185~~ ~~183~~ ~~162~~ 136 bytes
```
|v:&[&str]|[v[0],&match v.len(){1=>"is".into(),2=>format!("and {} are",v[1]),l=>format!("and {} others are",l-1)},"typing..."].join(" ")
```
[Try it online!](https://tio.run/##tZRbT8MgFMff9ynOeGiKQbLON5ct0SejiV9gWZZO2YZhMIE2u372eehuKmv0QUkaCud3LvR/qC2c3401zHKpUwrrBuBQwsOiu9uUt0k/cd4ONv2y3xqwZJb7lymUXAmE11m3R6QjXGpvUsra3d7YWESaKcn1K6y3kFtBWNnPBpSp2Gr8VFi3h9R1RreM@OVc6gnnnAz4m8GSCBC661RVnUorxYuHbpiaabUZRrUi98VopIQllH0zaANGi3j/YTkX9lkU3kptCANSuEvuYpZrK1wBd4FRy0WuwsujgSesN@bnCzHBOIjoQqk/m6M8Wev/c6BawRhkimwof7R30ACkg72cwRvBQ4wwYUTKaKdxktRFesZhQleccx0UrTV/ERZCxwVlQ7Nd5s8KV3D7U3dedthLXMFZ60cakV@SAaseBGohPHXdwaPvVkW7qcl7FAHvJqxA6upycemFTSlfyXnqDovjvyGM3OGn9EPx3kwXabLiLe7NEB2RYnC14hnd39htY7v7AA "Rust – Try It Online")
Ungolfed:
```
|v: &[&str]| {
[
v[0],
&match v.len() {
1 => "is".into(),
2 => format!("and {} are", v[1]),
l => format!("and {} others are", l - 1),
},
"typing...",
]
.join(" ")
}
```
Log:
* -2 for excluding the closure name
* -21 for `v:&[&str]`, implicit return type, wildcard with binding, `s` removal, brackets. Thanks @AnttiP!
* -26 for removing redundant `"typing..."` occurrences and one `format!` use (by @Ezhik)
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 77 bytes
```
⊑∾" typing..."∾˜·(0<≠)◶⟨" is"⋄" and "∾" are"∾˜(1<≠)◶⟨⊑⋄" others"∾˜•fmt∘≠⟩⟩1⊸↓
```
Anonymous tacit function that takes a list of strings and returns a string. [Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqR4oi+IiB0eXBpbmcuLi4i4oi+y5zCtygwPOKJoCnil7bin6giIGlzIuKLhCIgYW5kICLiiL4iIGFyZSLiiL7LnCgxPOKJoCnil7bin6jiipHii4QiIG90aGVycyLiiL7LnOKAomZtdOKImOKJoOKfqeKfqTHiirjihpMKCkbCqCDin6gg4p+oICJCdWJibGVyIiDii4QgInVzZXIiIOKLhCAibHl4YWwiIOKLhCAiTmVpbCIg4p+pCiAgIOKLhCDin6ggIkJ1YmJsZXIiIOKLhCAidXNlciIg4p+pCiAgIOKLhCDin6ggIkJ1YmJsZXIiIOKfqSDin6kK)
### Explanation
```
(0<≠)◶⟨" is"⋄...⟩1⊸↓
1⊸↓ Drop the first element of the argument list
( )◶ Choose, based on the result of this function:
≠ Length of the remaining list
0< is greater than 0? (1 if so, 0 if not)
⟨ ⟩ one of these functions:
" is" Return that string
⋄ or...
" and "∾" are"∾˜(1<≠)◶⟨⊑⋄...⟩
( )◶ Choose, based on the result of this function:
≠ Length of the all-but-the first list
1< is greater than 1?
⟨ ⟩ one of these functions:
⊑ First element of the all-but-the-first list
⋄ or... (see below)
" are"∾˜ Append that string to the result
" and "∾ Prepend that string to the result
" others"∾˜•fmt∘≠
≠ Length of the all-but-the-first list
•fmt∘ Format as string
" others"∾˜ Append that string to the result
⊑∾" typing..."∾˜·...
... Calculate all of the above
· and then
" typing..."∾˜ Append that string to the result
⊑∾ Prepend the first element of the argument list
```
[Answer]
# JavaScript, ~~85~~ 82 bytes
```
a=>(b=a.length,a[0]+(b<2?" is":` and ${b<3?a[1]:b-1+" others"} are`)+" typing...")
```
[Try it online!](https://tio.run/##tU7LSsNQEN37FcPgIqHtpam70rToShT8gRDo3HaaRq4z4T6kQfz2NN1K3OlqDnOe7/RJ4eDbLi5EjzycyoHKbWZLMo6liec5Vct6ltnNaofQBlzvgeQI919287CjqqjXdlHMEDSe2Qf8BvK8z8dH7LtWGmMM5sNBJahj47TJTlmFT8laxx7rPL/7yYmCCk9Sz33H/o1T9K0ozgFT@CWEP0g8hwSPN5nrL@Ru4EXhdRw1aeku3Ixpo0qSc392p6qK5X/UDFc "JavaScript (Node.js) – Try It Online")
[Answer]
# Dart, 101 Bytes
```
f(a)=>a[0]+(a.length>1?" and ${a.length>2?"${a.length-1} others":"${a[1]}"} are" : " is")+" typing.";
```
[Try it online](https://dartpad.dev/?id=3332dd3638698d3ba294eb7da60bd6f1&null_safety=true)
[Answer]
# [Python 2](https://docs.python.org/2/), 102 bytes
```
i=input()
l=len(i)
print(i[0]+" and "+[`l-1`+" others",i[-1]][l<3]+" are",i[0]+" is")[l<2],"typing..."
```
[Try it online!](https://tio.run/##XY1BCsMgFET3niL8jdoYadIu60lESJpI80FUjIXm9DZmVboZZh4zTNzzGvxQ5rBYRSktqNDHd2acOOWsZ8hJTOgzQ301LTSTXxpo9ei6fjxiyKtNGwjUXW@Mdo/bWUq2onOAG/CDD0ZA3iP6l5QSynFF7MfOrB7zy71omMCQqgKeP07A/JcELGC@ "Python 2 – Try It Online")
Simple nested list slices but takes advantage of no brackets required for printing in Python 2 and also the use of back ticks for the string conversion.
[Answer]
# [jq](https://stedolan.github.io/jq/), ~~99~~ 99+1 (-r flag penalty) = 100 bytes
```
(length-1)as$l|.[0]as$n|["is","and \(.[1]) are"]|"\($n) \(.[$l]//"and \($l) others are") typing..."
```
[Try it online!](https://tio.run/##LY1BCsMgEEWvMgwuHEhMc4Vew7gwRBLLMG3VLgre3TaS1f/89@A/3q1pDrKXY5zJZ8XV2Jv7F6kWY8YBvWywaGNnR@BTQFdx0Uqoj4rdNF2KYoJnOULK3SMo31eU3RiDrVm8f9aVQ4KYL4AD9AfAUz9DNnRtTD8 "jq – Try It Online")
I'm pretty sure there's room to golf this more, but not tonight. :)
1. Stash the length of the input list in `$l`. stash the first element in `$n
`(length-1)as$l|.[0]as$n`
2. Generate a new list consisting of two elements, `is` and `is 2nd-input-list-entry are`
`|["is","and \(.[1]) are"]`
3. Print the first input list name, then index the list from step 2 by the number of entries in the input minus 1. The `//` code is called if the index doesn't exist. In that case the alternate text `and length-of-input-minus-1 are` is used. The `typing...` string is appended regardless of what other choices were made.
`|"\($n) \(.[$l]//"and \($l) others are") typing..."`
] |
[Question]
[
### Introduction
Let's observe the string `abc`. The substrings that can be made from this are:
```
a, ab, abc, b, bc, c
```
We now need to align them under the initial string, like this:
```
abc
a
b
c
ab
bc
abc
```
The order of the string doesn't matter, so this is also perfectly valid:
```
abc
a
ab
abc
b
bc
c
```
So, the substring is positioned under the location of the substring in the initial string. So for `abcdef` and the substring `cde`, it would look like this:
```
abcdef
cde
```
### The Task
The task is to align all substrings **with a length greater than 0**, like shown above. You can assume that the string itself will only contain **alphabetic characters** and has at least 1 character. For the padding, you can use a space or some other non-alphabetic printable ASCII character (`32 - 127`). Maybe not necessary to mention, but the string itself will only contain unique characters, so not like `aba`, since the `a` occurs twice.
### Test cases
Input: `abcde`
Possible output:
```
a
ab
abc
abcd
abcde
b
bc
bcd
bcde
c
cd
cde
d
de
e
```
Input: `abcdefghij`
Possible output:
```
a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
b
bc
bcd
bcde
bcdef
bcdefg
bcdefgh
bcdefghi
bcdefghij
c
cd
cde
cdef
cdefg
cdefgh
cdefghi
cdefghij
d
de
def
defg
defgh
defghi
defghij
e
ef
efg
efgh
efghi
efghij
f
fg
fgh
fghi
fghij
g
gh
ghi
ghij
h
hi
hij
i
ij
j
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
# Perl, ~~32~~ ~~28~~ 24 bytes
Includes +1 for `-n`
Code:
```
/.+(??{say$"x"@-".$&})/
```
Run with the string on STDIN:
```
perl -nE '/.+(??{say$"x"@-".$&})/' <<< abcd
```
The golfing languages are so close and yet so far away...
## Explanation
`/.+/` matches a substring. Unfortunately it stops once it matched one. So I use the runtime regex construct `(??{})` to extend the regex so it fails and backtracking will try the following substring, in the end trying them all before giving up in disgust.
Inside the `(??{})` I print the current substring prefixed by as many spaces as the offset of the substring using `$"x"@-"`
So the output neatly documents how regex backtracking works:
```
abcd
abc
ab
a
bcd
bc
b
cd
c
d
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~20~~ 18 bytes
*Inspired by the pattern of substrings generated by [@aditsu's answer](https://codegolf.stackexchange.com/a/78705/36398)*
```
tt!+gR*c`t3Lt3$)tn
```
[**Try it online!**](http://matl.tryitonline.net/#code=dHQhK2dSKmNgdDNMdDMkKXRu&input=J2FiY2RlZmdoaWon)
The pattern of substrings is generated by an upper triangular matrix the same size as the input, and all submatrices obtained by successively removing the last row and column.
**Explanation**
```
t % implicit input. Duplicate
t!+g % square matrix with size as input
R % keep upper triangular part
*c % multiply element-wise with broadcast. Convert to char
` % do...while
t % duplicate
3Lt3$) % remove last row and column
tn % number of remaining elements. Used as loop condition
% implicitly end loop and display
```
---
### Old approach (Cartesian power)
*I'm keeping this approach in case it serves as inspiration for other answers*
```
tn0:2Z^!S!2\Xu4LY)*c
```
In the online compiler this runs out of memory for the longest test case.
[**Try it online!**](http://matl.tryitonline.net/#code=dG4wOjJaXiFTITJcWHU0TFkpKmM&input=J2FiY2Qn)
**Explanation**
This generates all patterns of values `0`, `1` and `2` in increasing order, and then transforms `2` into `0`. This gives all possible patterns of `0` and `1` where the `1` values are contiguous. These are used to mark which characters are taken from the original string.
As an example, for string `'abc'` the patterns are generated as follows. First the Cartesian power of `[0 1 2]` raised to the number of input characters is obtained:
```
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
···
2 2 1
2 2 2
```
Sorting each row gives
```
0 0 0
0 0 1
0 0 2
0 0 1
0 1 1
···
1 2 2
2 2 2
```
Transforming `2` into `0` (i.e. `mod(...,2)`) and removing duplicate rows gives the final pattern
```
0 0 0
0 0 1
0 1 1
0 1 0
1 1 1
1 1 0
1 0 0
```
in which each row is a mask corresponding to a (contiguous) substring. The first row needs to be removed because it corresponds to the empty substring.
```
t % Implicitly get input. Duplicate
n % Number of elements
0:2 % Vector [0 1 2]
Z^ % Cartesian power. Each result is a row
!S! % Sort each row
2\ % Modulo 2: transform 2 into 0
Xu % Unique rows
4LY) % Remove first (corresponds to the empty substring)
* % Element-wise multiplication by original string
c % Convert to char. Implicitly display
```
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~48~~ ~~32~~ 31 bytes
*Thanks to Kenny Lau for saving 3 bytes and paving the way for many more.*
Byte count assumes ISO 8859-1 encoding.
```
M&!r`.+
%+`( *)\S(.+)$
$&¶$1 $2
```
[Try it online!](http://retina.tryitonline.net/#code=TSYhcmAuKwolK2AoICopXFMoLispJAokJsK2JDEgJDI&input=YWJjZGU)
Order of the generated substrings:
```
abcde
bcde
cde
de
e
abcd
bcd
cd
d
abc
bc
c
ab
b
a
```
### Explanation
```
M&!r`.+
```
This gets us all the prefixes of the input. This is done by matching (`M`) any substring (`.+`) starting from the end (`r`), considering overlapping matches (`&`) and returning all of those matches joined with linefeeds (`!`).
Now all we need to do is carve out the successive prefixes *of those prefixes* (by replacing them with spaces). We do this step by step with a loop:
```
%+`( *)\S(.+)$
$&¶$1 $2
```
The `%` means that this entire thing is done to each line individually (considering it a separate string for time being, and joining it all back together with linefeeds at the end). The `+` tells Retina to run this substitution in a loop until the output stops changing (which in this case means that the regex no longer matches). The regex then tries to match the last line of the input with at least two non-space characters, and appends a new row where the first of those is replaced with a space.
[Answer]
# Pyth, ~~14~~ ~~13~~ 10 bytes
*Thanks to* [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) *for saving 3 bytes.*
```
jmXQ-Qd;.:
```
[Try it online!](http://pyth.herokuapp.com/?code=jmXQ-Qd%3B.%3A&input=%22abcd%22&debug=0)
[Answer]
# Oracle SQL 11.2, 146 bytes
```
WITH v AS(SELECT LEVEL i FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))SELECT LPAD(SUBSTR(:1,s.i,l.i),s.i+l.i-1)FROM v s,v l WHERE s.i+l.i<=LENGTH(:1)+1;
```
Un-golfed
```
WITH v AS(SELECT LEVEL i FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))
SELECT LPAD(SUBSTR(:1,s.i,l.i),s.i+l.i-1)
FROM v s, v l
WHERE s.i+l.i<=LENGTH(:1)+1
```
[Answer]
# CJam, 20
```
q{__,{\_N+oSt}/;W<}h
```
[Try it online](http://cjam.aditsu.net/#code=q%7B__%2C%7B%5C_N%2BoSt%7D%2F%3BW%3C%7Dh&input=golf)
**Explanation:**
```
q read the input (initial string)
{…}h do … while
_ copy the current string
_, copy and get the length
{…}/ for each value (say i) from 0 to length-1
\ bring the string to the top
_N+o make a copy, append a newline and print
St set the i'th element to S=" "
; pop the last result (array full of spaces)
W< remove the last character of the current string
if the string is empty, the do-while loop terminates
```
[Answer]
## Python, 57 bytes
```
f=lambda s,p='':set(s)and{p+s}|f(s[1:],' '+p)|f(s[:-1],p)
```
Outputs a `set` like `{' b', 'a', 'ab'}`. The idea is to recurse down two branched that cut off the first or last character. The gives redundant outputs, but the `set` automatically removes duplicates. For alignment, every time the first character is cut off, a space is added to the prefix `p`, which is concatenated onto the front.
[Answer]
## PowerShell v2+, 69 bytes
```
param($a)0..($b=$a.length-1)|%{($i=$_)..$b|%{" "*$i+-join$a[$i..$_]}}
```
Takes input `$a`, loops over the length (setting `$b` in the process for use later). Each outer loop, we loop up to `$b` again, setting `$i` for use later. Each inner loop, we output `$i` number of spaces concatenated with a slice of the input string. Since we're just looping through the string, this will actually handle any arbitrary string (duplicate letters, spaces, whatever).
### Example
```
PS C:\Tools\Scripts\golfing> .\exploded-substrings.ps1 "Golfing"
G
Go
Gol
Golf
Golfi
Golfin
Golfing
o
ol
olf
olfi
olfin
olfing
l
lf
lfi
lfin
lfing
f
fi
fin
fing
i
in
ing
n
ng
g
```
[Answer]
## C#, ~~136~~ ~~132~~ 131 bytes
---
**Golfed**
```
String m(String s){String o="",e=o;for(int i=0,a,l=s.Length;i<l;i++,e+=" ")for(a=1;a+i<=l;a++)o+=e+s.Substring(i,a)+"\n";return o;}
```
---
**Ungolfed**
```
String m( String s ) {
String o = "", e = o;
for (int i = 0, a, l = s.Length; i < l; i++, e += " ")
for (a = 1; a + i <= l; a++)
o += e + s.Substring( i, a ) + "\n";
return o;
}
```
---
**Full code**
```
using System;
using System.Collections.Generic;
namespace Namespace {
class Program {
static void Main( string[] args ) {
List<String> ls = new List<String>() {
"abcde",
"abcdefghijklmnop",
"0123456789",
};
foreach (String s in ls) {
Console.WriteLine( s );
Console.WriteLine( m( s ) );
Console.WriteLine( "" );
}
Console.ReadLine();
}
static String m( String s ) {
String o = "", e = o;
for (int i = 0, a, l = s.Length; i < l; i++, e += " ")
for (a = 1; a + i <= l; a++)
o += e + s.Substring( i, a ) + "\n";
return o;
}
}
}
```
---
**Releases**
* **v1.2** - `-1 byte` - Changed the `String o="",e="";` to `String o="",e=o;` to save 1 byte. The idea was from [Gallant](https://codegolf.stackexchange.com/users/53330/gallant) ( *I forgot to apply this part in the last update, I apologize.* ).
* **v1.1** - `-4 bytes` - Droped the brackets from the `for` loops and moved the `e` var *space increment* to the iterator zone of the outer `for` loop. The idea was from [Gallant](https://codegolf.stackexchange.com/users/53330/gallant).
* **v1.0** - `136 bytes` - Initial solution.
[Answer]
# Python 2.7, ~~70~~ 82 bytes
I couldn't figure out how to get it on 1 line. Call with `e("abcde",0)`
```
def e(s,p):
f=len(s)
for x in range(f):print(' '*p+s[:x+1])
if f>1:e(s[1:],p+1)
```
[Answer]
# Python 3, ~~80~~ 78 bytes
Loop through the number of spaces to prefix with and then the number of characters to end with.
```
lambda x:[print(' '*i+x[i:j+1])for i in range(len(x))for j in range(i,len(x))]
```
**Edit:** Removed spaces before the for loops.
[Answer]
# MATL, ~~15~~ 14 bytes
Saved one byte due to [@LuisMendo's](https://codegolf.stackexchange.com/users/36398/luis-mendo) tip [here](https://codegolf.stackexchange.com/a/133943/42892)!
```
tfWt2/!-RXzB*c
```
So many ways... had to find a new one. Happy bits! :)
[Try it online!](https://tio.run/##y00syfn/vyQtvMRIX1E3KKLKSSv5/3/1xKTklNS09IzMLHUA)
**Exploded**
```
t % duplicate input
f % get indices of nonzero elements in vector (i.e. 1:n)
W % 2 raised to array, element-wise: 2^(1:n)
t % duplicate array
2/ % divide by 2: 2^(0:n-1)
! % transpose array
- % element-wise subtraction (w/singleton expansion)
R % upper triangular part
Xz % nonzero elements
B % convert from decimal to binary. Produces a logical array
* % array product (element-wise, singleton expansion)
c % convert to character array; 0's automatically converted to spaces
```
[Answer]
# JavaScript (ES6), 89 bytes
```
document.write("<pre>"+(
s=>(a=[...s]).map((_,i)=>a.map((_,j)=>++j>i?r+=" ".repeat(i)+s.slice(i,j)+`
`:0),r="")&&r
)("abcde"))
```
Straight-forward approach. Output has a trailing newline.
[Answer]
# JavaScript (ES6), 72
```
s=>{for(i=j=0;s[j]||s[j=++i];)console.log(' '.repeat(i)+s.slice(i,++j))}
```
[Answer]
# Pyth, 12 11 bytes
```
jm+*;xQdd.:
```
Sadly the question allows us to assume unique characters, so I just lookup the first position of the substring, and pad with spaces.
[Answer]
# Mathematica 89 bytes
```
r@i_:=StringReplace[i,#->" "]&/@(Complement[y,#]&/@Subsequences[y=Characters@i])//Column
```
---
**Explanation**
`i` refers to the input string
`Subsequences[y=Characters@i]` returns all subsequences (represented lists of characters) of the input. (`Subsequences` was introduced in v. 10.4)
For each subsequence, `Complement...` returns those characters from the input string that are **not** present. Each of those characters is replaced by an empty space via `StringReplace[i,#->" "]`.
`Column` displays the results in a single column. Each output string has the same number of characters, resulting in aligned letters.
---
```
r@"abcdefgh"
```
[![output](https://i.stack.imgur.com/u5o5Y.png)](https://i.stack.imgur.com/u5o5Y.png)
[Answer]
## J, ~~32 29~~ 28 bytes
```
(-@{.@i.|.])"1 a:>@-.~&,<\\.
```
This evaluates to a monadic verb. [Try it here.](http://tryj.tk) Usage:
```
f =: (-@{.@i.|.])"1 a:>@-.~&,<\\.
f 'abe'
a
ab
abe
b
be
e
```
## Explanation
As some other answers, I compute the index of occurrence of the first character of each substring.
The substrings are stored in a matrix with trailing spaces, so I rotate them to the right by their index to get the right amount of padding.
That one piece of whitespace between `"1` and `a:` is really annoying...
```
(-@{.@i.|.])"1 a:>@-.~&,<\\. Input is y
<\\. Compute suffixes of prefixes of y, and put them in boxes.
This gives a 2D array of substrings in boxes.
&, Flatten the array of boxes,
a: -.~ remove all empty strings, and
>@ open each box. This places the strings in a 2D matrix of
characters, with trailing spaces to make it rectangular.
( )"1 Do this for each line x in the matrix:
i. The index of every character of x in y.
-@{.@ Take the first one and negate it.
|.] Rotate x to the left by that amount.
Since we negated the index, this rotates to the right.
```
[Answer]
## JavaScript (Firefox 30-57), ~~65~~ 63 bytes
```
s=>[for(c of(i=0,s))for(d of(t=r=i?t+' ':'',s.slice(i++)))r+=d]
```
Returns an array of strings. As ES6 it's 78 bytes:
```
s=>[...s].map((_,i,a)=>a.slice(i).map(c=>r.push(u+=c),t=u=i?t+' ':''),r=[])&&r
```
[Answer]
# QBasic, 75 bytes
```
INPUT s$
FOR i=1TO LEN(s$)
FOR j=1TO i
LOCATE,j
?MID$(s$,j,i+1-j)
NEXT
NEXT
```
The basic double-`FOR`-loop strategy, modified a bit for QBasic's 1-based indexing. The main trick is `LOCATE,j`, which moves the cursor over to column `j` of the current line before printing. Since column 1 is the first column, this is equivalent to printing `j-1` leading spaces.
[Answer]
# [Perl 6](http://perl6.org), 34 bytes
```
perl6 -ne 'm/^(.*)(.+)<{+put " "x$0.to,$1}>/'
```
```
m/ # match the input line
^ # from the start
( .* ) # 0 or more characters ( $0 )
( .+ ) # 1 or more characters ( $1 )
<{ # match against the result of:
+put # print with a trailing newline:
" " x $0.to, # add the leading spaces
$1 # the substring
}>
/
```
The reason for the `+` before `put` is so that it returns `1` instead of `True`, which is guaranteed not to be in the input so it always has to backtrack.
```
$ perl6 -ne 'm/^(.*)(.+)<{+put " "x$0.to,$1}>/' <<< abcd
```
```
d
cd
c
bcd
bc
b
abcd
abc
ab
a
```
( If you want it in the opposite order use `(.*?)(.+?)` instead of `(.*)(.+)` )
This was [inspired by the Perl 5 answer](https://codegolf.stackexchange.com/questions/78691/exploded-substrings/78734#78734).
[Answer]
# J, ~~35~~ ~~23~~ 22 bytes
```
[:;#\.<@{."_1|.\."1^:2
```
It took me a while but I finally optimized it.
## Usage
```
f =: [:;#\.<@{."_1|.\."1^:2
f 'abcde'
abcde
abcd
abc
ab
a
bcde
bcd
bc
b
cde
cd
c
de
d
e
```
## Explanation
```
[:;#\.<@{."_1|.\."1^:2 Input: s
|.\."1 For each suffix of s, reverse it
^:2 Repeat that twice to create all exploded substrings
#\. Get the length of each suffix. This is
used to make the range [len(s), len(s)-1, ..., 1]
{."_1 For each value in the range, take that many strings from
the list of exploded substrings. This avoids blank substrings
<@ Box each set of strings
[:; Unbox and join the strings together and return
```
[Answer]
# Java, 138 bytes
```
String e(String s){int l=s.length(),a=0,i,j;for(;++a<l;)for(i=0;i<=l-a;){s+="\n";for(j=0;j++<i;)s+=" ";s+=s.substring(i,i+++a);}return s;}
```
Formatted:
```
String e(String s) {
int l = s.length(), a = 0, i, j;
for (; ++a < l;)
for (i = 0; i <= l - a;) {
s += "\n";
for (j = 0; j++ < i;)
s += " ";
s += s.substring(i, i++ + a);
}
return s;
}
```
[Answer]
## Pyke, 15 bytes
```
QlFUQRd:DlRF2h<
```
[Try it here!](http://pyke.catbus.co.uk/?code=QlFUQRd%3ADlRF2h%3C&input=abcdef)
Assumes array of padded strings is acceptable
Pads first and then chops.
[Answer]
# Haskell, 65 bytes
```
(>>=zipWith((++).(`replicate`' '))[0..].init.tails).reverse.inits
```
It requires `inits` and `tails` from Data.List, though. To output it, add `mapM_ putStrLn.` to the front.
Relatively straightforward; the `reverse` is to make sure the original string is first.
```
GHCi> mapM_ putStrLn.(>>=zipWith((++).(`replicate`' '))[0..].init.tails).reverse.inits$"abcde"
abcde
bcde
cde
de
e
abcd
bcd
cd
d
abc
bc
c
ab
b
a
it :: ()
(0.02 secs, 0 bytes)
```
[Answer]
# Ruby, ~~75~~ 67 bytes
Anonymous function. ~~Uses regex substitution to align the substrings.~~ `.` is the filler character.
```
->s{(l=s.size).times{|i|(l-i).times{|j|puts s.tr(?^+s[j,i+1],?.)}}}
```
[Answer]
# bash + GNU coreutils, 109 Bytes
```
l=${#1}
for i in `seq 0 $l`;{
for j in `seq $((l-i))`;{
for k in `seq $i`;{ printf ' ';}
echo ${1:i:j}
}; }
```
Maybe there is a shorter solution, but this is the best that came into my mind. Uniqueness of chracters does not matter here.
[Answer]
# PHP, 151 chars
## Ungolfed
```
<?php
$input = $argv[1];
foreach(str_split($input) as $p=>$letter)
{
$spaces = str_repeat(" ", $p);
echo $spaces.$letter."\n";
$p++;
for($i=$p;$i<strlen($input);$i++)
{
echo $spaces.$letter.substr($input, $p, $i)."\n";
}
}
?>
```
## Golfed
```
<?$c=$argv[1];foreach(str_split($c)as$d=>$b){$a=str_repeat(" ",$d);echo$a.$b."\n";$d++;for($e=$d;$e<strlen($c);$e++){echo$a.$b.substr($c,$d,$e)."\n";}}
```
## Example
```
php explodesub.php 'abc'
a
ab
abc
b
bc
c
```
[Answer]
# C++, 145 Bytes
the first start parameter is used as input, console as output
```
#include<iostream>
#define f(y,b,d) for(int y=b;r[0][y];y++){d;}
int main(int,char*r[]){f(x,0,f(y,x+1,std::cout.write(r[0],y)<<'\n')r[0][x]=32)}
```
[Answer]
**Python 2 (Ungolfed) 99 Bytes**
```
t=raw_input()
l=len(t)
for j in range(l):
for i in range(l):
if i>=j:print j*' '+t[j:i+1]
```
Result:
```
>>python codegolf.py
abc
a
ab
abc
b
bc
c
>>python codegolf.py
abcdef
a
ab
abc
abcd
abcde
abcdef
b
bc
bcd
bcde
bcdef
c
cd
cde
cdef
d
de
def
e
ef
f
>>python codegolf.py
lmnopqrst
l
lm
lmn
lmno
lmnop
lmnopq
lmnopqr
lmnopqrs
lmnopqrst
m
mn
mno
mnop
mnopq
mnopqr
mnopqrs
mnopqrst
n
no
nop
nopq
nopqr
nopqrs
nopqrst
o
op
opq
opqr
opqrs
opqrst
p
pq
pqr
pqrs
pqrst
q
qr
qrs
qrst
r
rs
rst
s
st
t
```
] |
[Question]
[
There have been a couple of challenges involving doubling source code: [here](https://codegolf.stackexchange.com/questions/132558/i-double-the-source-you-double-the-output) and [here](https://codegolf.stackexchange.com/questions/132786/double-time-is-not-double-time). The task we have here is a bit harder, but should be doable in almost every language.
In this challenge, you will take in an arbitrary positive integer. Your program must output that integer **doubled**.
When your source code is doubled, it will take in a positive integer, and output it **squared**.
How is your source code doubled? Well, [you can have it your way](https://www.youtube.com/watch?v=KJXzkUH72cY).
That is to say, you can split your source code up into strings of bytes or characters (or tokens in tokenized langs) of *any **equal** length you want*, and repeat each chunk twice in succession.
For an initial program of `ABCDEFGHIJKL`, (length 12) here are **all** possible doubled programs:
```
Chunk length | Doubled source code
-------------+-------------------------
1 | AABBCCDDEEFFGGHHIIJJKKLL
2 | ABABCDCDEFEFGHGHIJIJKLKL
3 | ABCABCDEFDEFGHIGHIJKLJKL
4 | ABCDABCDEFGHEFGHIJKLIJKL
6 | ABCDEFABCDEFGHIJKLGHIJKL
12 | ABCDEFGHIJKLABCDEFGHIJKL
```
Note that this means programs of prime lengths can only be doubled two ways: every character doubled, or the full program is repeated twice.
### Rules:
* Code must be a full program or function.
* [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* [Standard I/O methods are allowed.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* All characters/bytes, including whitespace and newlines, are counted in the length of the code and contribute to chunks.
* You **may** assume that the input and its square can be represented by your language's int/integer type.
* You **may not** assume a trailing newline or other character.
* Provide your chunk size in the heading after the byte count.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shorter programs are better! If two programs are the same length, the one which uses the smaller chunk length wins. (If you have a longer program which uses a smaller chunk length, that is worth posting too!)
* If your program requires a second input/line, you may make no assumptions on its value. In particular, your program should work if the second input is empty, the same as the first, or a different integer. If your program does not require a second input/line, you may ignore this restriction.
>
> [Sandbox link](https://codegolf.meta.stackexchange.com/a/18074/86147)
>
>
>
[Answer]
# [Perl 5](https://www.perl.org/), 8 bytes (chunk size 4)
```
$_*=~~+2
```
[Try it online](https://tio.run/##K0gtyjH9/18lXsu2rk7b6P9/QwMuIwMuY4N/@QUlmfl5xf91cwoA "Perl 5 – Try It Online"), or [try the doubled version](https://tio.run/##K0gtyjH9/18lXssWhOvqtI1A@P9/QwMuIwMuY4N/@QUlmfl5xf91cwoA).
Unary `~` is the bitwise negate, so applying it twice is a noop. Thus, the base program simply multiplies `$_` (the implicit input-output variable) by 2.
Binary `~~` is smartmatch, which returns a boolean. `~~+2~~+2` parses as `(~~+2) ~~ (+2)`. Since 2 equals 2, this yields true (1). Thus, the doubled program first multiplies `$_` by 1, then multiplies `$_` by itself.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes (chunk size 2 or 4)
```
·Inr
```
[Try it online](https://tio.run/##yy9OTMpM/f//0HbPvKL//02MAA "05AB1E – Try It Online") or [doubled as a single 4-byte chunk](https://tio.run/##yy9OTMpM/f//0HbPvCIw8f@/iREA "05AB1E – Try It Online") or [doubled as two 2-byte chunks](https://tio.run/##yy9OTMpM/f//0HZPIMoryiv6/9/ECAA "05AB1E – Try It Online").
```
· # double the implicit input
In # square the input
r # reverse the stack: it's now [input ** 2, input * 2]
# if we stop here: implicitly output the top of the stack (input * 2)
· # double the top of the stack (giving input * 4, not that it matters)
In # square the input
r # reverse the stack: it's now [input ** 2, input * 4, input ** 2]
# implicitly the top of the stack (input ** 2)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 26 bytes (chunk size 13)
```
lambda n:"and n*n#"and 2*n
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSikxL0UhTytPGcww0sr7n5JfmpSTGp@mYKuAogrKScHUgsLh4uIqKMrMK9FI0zA01tSEcmCGgsX@AwA "Python 3 – Try It Online")
### Doubled:
```
lambda n:"andlambda d:"and n*n#"and 2*n n*n#"and 2*n
```
This solution is provided by @Grimy.
---
## [Python 3](https://docs.python.org/3/), ~~32~~ ~~30~~ 28 bytes (chunk size ~~16~~ ~~15~~ 14)
```
lambda n:bool(0)*n*n or 2*n
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKik/P0fDQFMrTytPIb9IQcFIK@9/QVFmXolGmoahgabmfwA "Python 3 – Try It Online")
*-4 bytes thanks to @negativeSeven*
### Doubled:
```
lambda n:bool(lambda n:bool(0)*n*n or 2*n0)*n*n or 2*n
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKik/P0cDlWegqZWnlaeQX6SgYKSVh8r7X1CUmVeikaZhaKCp@R8A "Python 3 – Try It Online")
The function takes advantage of the unique chunk rule of this challenge.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 14 bytes (chunk size 14)
```
?"+==*/}=+!@!<
```
### Expanded:
```
? " +
= = * /
} = + ! @
! < . .
. . .
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/99eSdvWVku/1lZb0UHR5v9/I0MA "Hexagony – Try It Online")
## Doubled
```
?"+==*/}=+!@!<?"+==*/}=+!@!<
```
### Expanded:
```
? " + =
= * / } =
+ ! @ ! < ?
" + = = * / }
= + ! @ ! <
. . . . .
. . . .
```
[Try it doubled online!](https://tio.run/##y0itSEzPz6v8/99eSdvWVku/1lZb0UHRBpX3/7@RIQA "Hexagony – Try It Online")
Hexagony is in a bit of a weird position in this challenge, in that actually achieving the task is not much more difficult than simply being able to write the two individual programs. However, golfing the solution proved rather difficult.
This solution is the trivial idea in the shortest form that I could fit, but I suspect there are shorter, cleverer answers. This version very naively sets two values to the input and sums them or multiplies them, depending on if the source is doubled. The only code reuse is the `"+` which makes making the copy code for the doubled program short enough to fit in the unused space from the original program.
I suspect using the IP change instructions `[]` will make isolating the parts easier, but a truly ideal solution will reuse a lot of code between the two. I made a [helper program](https://tio.run/##jZNRj9owDMff8ym8ag8JhTDu3tCh7XsAQoX6aLaSVEm6G9P22ZmTtDTspGkgContn@2/TXf1jdHPt5u6dMZ6cFc3B4tzUB6tN6Z1jNX4Cq/GXip/aPBHdTb6ysGZ3p4QxJoBvZyq8dCihg2s4sVbo1qEZ5hNphnw6bCAFQgo6fkCdOYJN9AeiGVAxuuuqocc/@Qm7CLHjuE11oeh8M3YQQmFLAgy0FMqa97C4ewbR553LeSpqZTmYCt9Rj4mFUGx72gd1vzRslgJAWIkBtR2n2ox4fAp/iZpQc2zlKA0oO4vaCuPPCslk4eqJUABofLq6P5SdgFqSJs1Q/5PuW7J8T@Cnay6DnXNY9YyZJVfDenwoOg29LSOnZVjyr3ISNGyGU1JFHR960MjOz0wk1BiGAP63urBjTHavmx8Vyedr5WWFquaU8RF6clsUbr@SLhi535td3Ln9uXHYg4FfTIOhZ2aXn87OPUT44Di3kwoAXvGwogmtzCfLCgNJV4kwBS8zYJmoNYPR67Coop9WoAATcvzroDlMk8eCgoJa9MfW4xbMEoXvYj8BPeC77XeNe2s0p6/@0MPOBrY7QbwmYZcMmJvCLdkv@m7hA/whdHjBSRIQsnw/gM) to double hexagony source code. Note that it removes trailing no-ops so if you want to have placeholder no-ops at the end just fill in some other character and change it back after. It can handle different chunk sizes, though I didn't yet write code to output each possible program (Hexagony seems to lend itself to using the full chunk size).
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 8 bytes (chunk length 2)
```
;&:#* +q
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/31rNSllLQbvw/39DYwUA "Befunge-98 (FBBI) – Try It Online")
```
;&;&:#:#* * +q+q
```
[Try it online! (doubled)](https://tio.run/##S0pNK81LT9W1tPj/31rNWs1K2UpZS0FLQbtQu/D/f0NjBQA "Befunge-98 (FBBI) – Try It Online")
Excluding control flow, the first program executes `&:+q` (input, duplicate top of stack, add, exit with return code), and the second executes `&:*+q` (input, duplicate top of stack, multiply, add (sums with an implicit 0), exit with return code)
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 12 bytes (chunk size 4)
```
?"2+...}=*!@
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/99eyUhbT0@v1lZL0eH/fyNDAA "Hexagony – Try It Online")
Formatted:
```
? " 2
+ . . .
} = * ! @
. . . .
. . .
```
[And doubled](https://tio.run/##y0itSEzPz6v8/99eyUgbhPX09GpB2FZL0QGE//83MgQA), then formatted:
```
? " 2 +
? " 2 + .
. . } . . .
} = * ! @ = *
! @ . . . .
. . . . .
. . . .
```
Basically, this sets the first edge to the input, then the second edge to either `2` or a copy of the input, then multiplies those two edges into the third edge, prints that and terminates. The list of executed instructions are just
```
?"2}=*!@
```
and
```
?"2+}=*!@
```
With the only difference being the `+` overriding the `2` on the second program.
[Answer]
# JavaScript (ES6), ~~24~~ 22 bytes
Despite its unusual format, this is the definition of an anonymous function, which can be either called directly or assigned to a variable.
```
+(g=x=>x*x)?g:(x=>x*2)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@19bI922wtauQqtC0z7dSgPMNNL8n5yfV5yfk6qXk5@ukaZhrqn5HwA "JavaScript (Node.js) – Try It Online")
```
+(g=x=>x*x)?g:(x=>x*2)+(g=x=>x*x)?g:(x=>x*2)
```
[Try it online doubled!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@19bI922wtauQqtC0z7dSgPMNNLELvo/OT@vOD8nVS8nP10jTcNcU/M/AA "JavaScript (Node.js) – Try It Online")
### How?
Applying the unary `+` to a function is interpreted as an attempt to coerce it to a number and results in *NaN*. Therefore, the leading `+(g=x=>x*x)` is falsy in both versions.
On the other hand, applying the binary `+` between 2 functions results in a string. Therefore, `(x=>x*2)+(g=x=>x*x)` is truthy in the doubled version.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 8 bytes (chunk size 1)
```
* *<1 2>
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0tBy8ZQwcjuvzVXcWKlQpqGieZ/AA "Perl 6 – Try It Online") [Try it doubled!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0tLQUFLy8bG0FBBwcjIzu6/NVdxYqVCmoaJ5n8A)
A Whatever/HyperWhatever lambda that takes a number and returns a number for the first program and a singleton list for the second program. Basically this keeps the exact same logic, except that the multiplication operator (`*`) is replaced by the exponential one (`**`).
```
** **<<11 22>>
```
The Whatever literal (confusingly also represented by a `*`) are doubled up to a HyperWhatever (`**`) which is basically the same except it maps over lists. The space is needed to separate the Whatever literal from the multiplication and is ignored when doubled up. Instead of just `2` (which would get doubled to `22`) we use a list containing two elements, which evaluates to 2 in a numeric context). The `<>` can be doubled to a list with interpolation, and the two elements inside are doubled, but neither of those change the length of the list.
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 9 bytes (chunk size 3)
```
i3?:*@:+@
```
[Try it online!](https://tio.run/##KyrNy0z@/z/T2N5Ky8FK2@H/f1MA "Runic Enchantments – Try It Online")
[Try it doubled!](https://tio.run/##KyrNy0z@/z/T2B6IrLQcQEgbhP7/NwUA "Runic Enchantments – Try It Online")
The `3?` skips the next 3 instructions, resulting in an (executed) `i3?...:+@`. When doubled it results in an executed `i3?...:*@` where `.` represents the 3 NOP'd instructions. `@` is "print entire stack and terminate."
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) / Javascript, 22 bytes, chunk size 11
```
m=>/* /2*m//*/m*2
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXogPEdmm2/3Nt7fS1FMBA30grV19fSz9Xy@i/NVdafpEGUI1Cpq2BdaaNkaF1pra2Jld4UWZJqk9mXqpGmkampqb1fwA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 76 bytes, 76 byte chunks
```
({}<>)(()[([][()])]{(<{}{}({({})({}[()])}<>)<>>)}{}){{}(({})({})<>)(<>)}{}<>
```
[Try it online!](https://tio.run/##LcsxDoAwDAPA79g/6BDlI1GHwgJCYmCN8vY0rRi8@OzjG/d7jfPJhIcoARqsG9jZHeLhAS9jZbdrJaosoBf@xnWWXYtmtmwT "Brain-Flak (BrainHack) – Try It Online")
## Doubled (with newline for clarity)
```
({}<>)(()[([][()])]{(<{}{}({({})({}[()])}<>)<>>)}{}){{}(({})({})<>)(<>)}{}<>
({}<>)(()[([][()])]{(<{}{}({({})({}[()])}<>)<>>)}{}){{}(({})({})<>)(<>)}{}<>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fo7rWxk5TQ0MzWiM6NlpDM1YztlrDprq2ulajGiinCcRgUZAqGzs7TaCEZjVQEiqnCdJsAxa2seOipmH//1v8twAA "Brain-Flak (BrainHack) – Try It Online")
Here is a version that uses a more complex doubling procedure. It does 5 chunks of size 15. The code here is 46 bytes however due to the required padding it is substantially longer.
# ~~105~~ 90 bytes, 15 byte chunks
```
( {<><({}()())><><>< <>>({})({}[()])}{} )<>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQwEFVNvY2WhU12poamhq2tmAILKsjZ0dUFITiKM1NGM1a6trkWU1beyQuf///7cAAA "Brain-Flak (BrainHack) – Try It Online")
## Doubled (with newlines for clarity)
```
( (
{<><({}()())><>{<><({}()())><>
<>< <><
<>>({})({}[()])<>>({})({}[()])
}{} }{}
)<> )<>
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQwEFoHG5qm3sbDSqazU0NTQ17Wzs0LhcQC6ycjQuUNoOqFoTiKM1NGM10bhctdW1yMrRuFxA9ch8NO7///8tAA "Brain-Flak (BrainHack) – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~48~~ 30 bytes (chunk size 10)
```
(({}))<>( {({}[()])}{}<>{}{})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0OjulZT08ZOQ6EayIrW0IzVrK2utbGrBpKaCv//GxoAAA "Brain-Flak – Try It Online") [Try it doubled!](https://tio.run/##SypKzMzTTctJzP7/X0OjulZT08ZOQwHBqgayojU0YzVrkVi1NnbVQFJTAcH6/9/QCAA "Brain-Flak – Try It Online")
This basically takes three steps, then when doubled executes those steps twice each. The initial program is:
1. Duplicate TOS, switch stacks and start pushing a value
2. Get the TOS's triangular number n\*(n-1)/2
3. Pop TOS, switch stack and pop twice, then push the result.
For an input `n` into an undoubled program, this results in:
```
1. Start stack: n n
Other stack: <
Third stack:
2. Start stack: n n
Other stack: 0 <
Third stack: tri(0) = 0
3. Start stack: n+n+tri(0) = 2n <
Other stack:
Third stack:
```
For the doubled program:
```
1a. Start stack: n n
Other stack: <
Third stack:
1b. Start stack: n n <
Other stack: 0 0
Third stack:
2a. Start stack: n 0 <
Other stack: 0 0
Third stack: tri(n)
2b. Start stack: n 0 <
Other stack: 0 0
Third stack: tri(n)+tri(0) = tri(n)
3a. Start stack: n
Other stack: tri(n) <
Third stack: tri(n)
3a. Start stack: 0+n+tri(n)+tri(n) = n + 2*tri(n) = n + n*(n-1) = n*n <
Other stack:
Third stack:
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~18~~ 14 bytes (chunk length ~~9~~ 7)
```
*OI$|:/@O+:I.
```
Note the trailing space. [Try it online!](https://tio.run/##Sy5Nyqz4/1/L31OlxkrfwV/bylNP4f9/YwA "Cubix – Try It Online")
Doubled:
```
*OI$|:/*OI$|:/@O+:I. @O+:I.
```
Again, there is one trailing space. [Try it online!](https://tio.run/##Sy5Nyqz4/1/L31OlxkofSjn4a1t56ilAqf//jQE "Cubix – Try It Online")
## Explanation
The main idea is that doubling the code causes the cube to become bigger, so the instruction pointer starts at a different symbol. Since the addition program cannot be put on a cube of side length 1, the side length is going to be 2. Additionally, the doubled code needs to be on a cube of side length 3, so the doubled code must be at least 25 bytes. This means the code must be at least 13 bytes long. As such, at most 1 more byte can be saved.
Now to the actual code. The first observation is that the top face (that is, the first 4 characters) are not used by the addition program. Furthermore, if we make the 5th character reflect the IP around the cube, we can free up 2 more characters. We will use these characters to put the squaring program.
[Answer]
# [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), 656 Bytes (Chunk size 328)
Just to add weight to the theory that this can be solved in almost any language...
```
Take Northern Line to Bank
Take District Line to Bank
Take District Line to Parsons Green
Take District Line to Bank
Take District Line to Hammersmith
Take Piccadilly Line to Russell Square
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Hammersmith
Take District Line to Upminster
Take District Line to Embankment
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Acton Town
Take District Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Leicester Square
Take Northern Line to Leicester Square
Take Northern Line to Mornington Crescent
```
(The trailing newline is important)
[Try the single version!](https://tio.run/##nZJNDoIwEIX3nKIXcOUJRI0u0BDFA9QykQntVKclxtNX/AkJQZLi@n2TeTPvGcuEdPGWZorBKSAfQiFrEHvLvgImkSGB8FakkurkLa3QeUblY6RcsrPkxIYBaPr4VhoD7Az66kPkqJQsUetHxxwa50Brcbw1kmEUS21DZc/ID2iwb@DodDVIzgOP6Gtzbs8x7SNjT5q8YqHavERh7xQJ/PuNKCgDVPBy2wtgUJ9IbNcVUiy/hUxCmD8B) ...or... [Try the doubled version!](https://tio.run/##7ZNNDoIwEEb3nKIXcOUJRI0u0BjFA9QykQl0qtMS4@kRf0JCkFgMS9bzmvnmdUYbJqSzMzRRDFYBubKMZQZia9ilwCQiJBDOiFBSFrxKC7SOUTmf0k6yNWTFigGo//O11BrYanTpm9ihUjLBPL/XzL6wFvJcHK6FZOjEQlNQ0gjyBWr1ayU6XjSSdcAd9aU@VePoSmQwehzQ4@@RereYqWrvRWxu5An8a8MLigAVPNM2PqC1Pp7Ypj5sMf8c9uhxII9lOX0A)
---
This was a particularly tricky challenge in Mornington Crescent because the program must have such a rigid structure. It's also important to watch where the doubling would take place, because teleporting between stations is illegal in London.
The theory here is simple: In the single version, 'Bounds Green' is filled with a random string, but in the doubled version it gets filled with the squared input. After the chunk ends, both versions double the 'input', but in the doubled version of the code, the input has been replaced with 0.
This result is taken back to Bounds Green, which performs a max() operation twice, before taking the result to the output. In the single version this leaves the doubling unaltered (the int and string are just switched back and forth), but in the doubled version this replaces the 0 with the squared result already stored in Bounds Green.
---
If my explanation wasn't good enough, I suggest you visit London and try the two routes yourself.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~15~~ 12 bytes (chunk size: 6)
```
x=>/**/2*(x)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrqHxv8LWTl9LS99IS6NC87@mhqmBpiYXF4oSiApkdRASovg/AA "JavaScript (Node.js) – Try It Online")
Single case:
```
x=>/**/2*(x)
```
Double case:
```
x=>/**x=>/**/2*(x)/2*(x)
```
Seems to also work in C#, and Java if changing `=>` to `->`?
[Answer]
# [R](https://www.r-project.org/), ~~42~~ ~~35~~ 28 bytes (chunk size 4)
Now with a smaller chunk and no error. I also have a longer solution with chunk size 3; see below.
I don't think it is possible to write an R answer with chunk size 1 or 2; I'll happily give a bounty to anyone who proves me wrong.
```
s =scan#
n=s()#
n/2*4#
```
[Try it online!](https://tio.run/##K/pfnJyYp2CrkFaal1ySmZ@noalg@r9YwRYkrMyVZ1usoamswKWgwJWnb6Rloqyg8P8/AA "R – Try It Online")
The `#` is for comments in R. The 3rd line is only spaces, making a chunk of newline + 2 spaces + newline, so that the previous and next chunk can have no newline.
Doubled, it becomes:
```
s =ss =scan#can#
n=s
n=s()# ()#
n/2*n/2*4# 4#
```
[Try it online!](https://tio.run/##FckxCoBADATAPq9YSHNnI4iWeYwcCDYrGH1/dIup5q4cOxE4Xo7nvNg6tkpEyl8uxkhp3SEGmHBeJlkdkKoP "R – Try It Online")
The single version computes \$\frac n2\times4=2n\$; the double version computes \$\frac n2\times \frac n2\times4=n^2\$.
Here is a slightly longer solution, but with chunk size 3:
# [R](https://www.r-project.org/), 39 bytes (chunk size 3)
```
s =bbb=scan#
n=s(#
)#
n* 1/ 2/ 1* 4#
```
[Try it online!](https://tio.run/##K/pfnJyYp2CrkFaal1ySmZ@noalg@r9YwTYpKckWJKXMlWdbrKHMpcClqazAlaelYKivYKSvYKilYKL8/z8A "R – Try It Online")
Doubled:
```
s =s =bbbbbb=sc=scan#an#
n=
n=s(#s(#
)# )#
n*
n* 1/ 1/ 2/ 2/ 1* 1* 4# 4#
```
[Try it online!](https://tio.run/##HcoxCoAwDEbhPacIZGm7SEXHHEYLBZcIRs8f//bxje8Jb4excv@svddtKfMezgrnTL3peATIFDwJEBNkYSArwHUZ1qmWYROI@AE "R – Try It Online")
Note that Giuseppe has [another](https://codegolf.stackexchange.com/a/191600/86301) R answer, with one chunk of 30 bytes.
[Answer]
# [R](https://www.r-project.org/), ~~59~~ 30 bytes (chunk size ~~59~~ 30)
```
F=F+1;f=function(n)n*c(2,n)[F]
```
[Try it online!](https://tio.run/##K/r/383WTdvQOs02rTQvuSQzP08jTzNPK1nDSCdPM9ot9n@ahqnmfwA "R – Try It Online")
Credit to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for inspiring this; increments `F` each time, and the function `f` selects the appropriate output.
~~This isn't particularly interesting, but doubtless something clever manipulating the chunk size will be dreamed up.~~ As expected, Robin Ryder came up with [this](https://codegolf.stackexchange.com/a/192700/67312) which is both shorter and has some neat chunk manipulation.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 22 bytes (chunk size 11)
```
param($p)
# /
2 * $p
```
[Try it online](https://tio.run/##K8gvTy0qzkjNyfmvkmZkW/2/ILEoMVdDpUCTS1lBQUGfy0hBS0Gl4H8tl0pamm01F5I0dpVITK5aLi5Dcx0FXROjGtVqNQWgBQoq8dYKIFYakFXL9R8A).
**Doubled:**
```
param($p)
#param($p)
# /
2 * $p /
2 * $p
```
This solution is based on @ShieruAsakoto's [solution](https://codegolf.stackexchange.com/a/192826/68224).
**@Grimy [solution](https://tio.run/##K6gsycjPM/6vUZyZl56TqqOQkl@alJOqaavxPycxNyklUSHPSikxL0UhTytPGcww0srj0uFCkYRyUjBVonD@a1pzFRRl5pVALdMwNNbUhIpArAWL/AcA) that has been converted to PowerShell, 26 bytes (chunk size 13)**
```
param($p)$t=';$p*$p#';$p*2
```
[Try it online](https://tio.run/##K8gvTy0qzkjNyfmvkmZkW/2/ILEoMVdDpUBTpcRW3VqlQEulQBlMG/2v5VJJS7Ot5kJRgls9CoerlovL0FxHQdfEqEa1Wk0BaJmCSry1AoiVBmTVcv0HAA).
**Doubled:**
```
param($p)$t=';param($p)$t=';$p*$p#';$p*2$p*$p#';$p*2
```
[Answer]
# Perl 5 (`-p`), ~~22~~ 15 bytes
-7 bytes thanks to Grimy
```
$_*=$'/4||2;//;
```
[TIO](https://tio.run/##K0gtyjH9/18lXstWRV3fpKbGyFpf3/r/f0MDLiMDLmODf/kFJZn5ecX/dXMKAA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
PI×Iθ⎇υIθ²⊞υω
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9ng3v96w8PB1InNvxqK/9fCuYdWjTo65551vPd/7/bwkA "Charcoal – Try It Online") Explanation: The predefined empty list is falsey so the input is multiplied by 2. When doubled the second pass sees the empty string has been pushed to the list so it multiplies the input by itself instead. [Try it online!](https://tio.run/##S85ILErOT8z5///9ng3v96w8PB1InNvxqK/9fCuYdWjTo65551vPdxKS///fEgA "Charcoal – Try It Online") In verbose syntax this corresponds to `Multiprint(Cast(Times(Cast(q), Ternary(u, Cast(q), 2)))); Push(u, w);`.
[Answer]
# Python 3, ~~56~~ 53 bytes
```
print(eval(input()+"**2"[len(*open(__file__))%2:])) #
```
My python skills kinda suck, so can definitely be golfed.. Based on [the Python answer in the "*I double the source, you double the output!*" challenge](https://codegolf.stackexchange.com/a/132565/52210).
Chunk length 53.
[Try it online](https://tio.run/##K6gsycjPM/7/v6AoM69EI7UsMUcjM6@gtERDU1tJS8tIKTonNU9DK78ASMbHp2XmpMbHa2qqGlnFamoqKP//b2gAAA) or [try it online doubled](https://tio.run/##K6gsycjPM/7/v6AoM69EI7UsMUcjM6@gtERDU1tJS8tIKTonNU9DK78ASMbHp2XmpMbHa2qqGlnFamoqKJOl6f9/QwMA).
[Answer]
# Java 8, 62 bytes
```
n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///
```
Chunk length 62.
[Try it online](https://tio.run/##hY7BCoJAGITvPsV/XAXdsku1aBB06JAXb0WHZbVY09/QTRDx2bddEzpFl4GZ@Rim4B33i@yhJaq8uXGRw4lLHByAb5JYOwUgiFV0mUlGx0gCCBFo9GP0yL5XeZAez4d4vcNt6DLqOaLkbQu2GVrFlRTTjoWiDRup51FKNbNTc93VMoPKnCCpaiTeL1fg7udB2rcqr4L6pYKnqVSJBANBlgt3OvQTCP8BqxkYnVG/AQ) or [try it online doubled](https://tio.run/##pY8xD4IwEIV3fsWNLQlUcVEbMDFxcJCFTePQVDRFOAytJITw25EiiZNxcLnk3vvu8l4mauFll3uv0KTVVcgUDkJh6wB8lNiuowCS2ImUD0rnDCMGhBB69CJ0ybYxqZ/sj7toucF1QDlzHZkLrcE6rTbCKDn@sVC44h1zXcbYf9c9t0Emuy7VBYqhAklMpfB2OoOg7/xJo01a@OXT@I/BMjkS9CWZz@hY5ysQ/AIWE9A5Xf8C).
**Explanation:**
```
n-> // Method with integer as both parameter and return-type
n* // The input, multiplied by:
(Byte.SIZE>8? // If Byte.SIZE is larger than 8:
n // Multiply by the input itself
: // Else:
2); // Multiply by 2
class Byte{ // Class which overwrites Byte
static int SIZE=9;} // And sets the SIZE to 9
```
In Java, the available comments are `// comment` and `/* comment */`. Which are combined here to overwrite certain parts. See how these comments work thanks to the Java highlighting:
```
n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///
n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///
```
The doubled program created a custom `Byte` class and its value `SIZE=9`, which overwrites the default `java.lang.Byte` class and its value `SIZE=8`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~7~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
*N²jJ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Kk6yako&input=OA) | [Doubled](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Kk6yakoqTrJqSg&input=OA)
`²` pushes 2 to the array of inputs `N` then `j` removes & returns the element at index `J=-1` (i.e., the newly inserted `2`) and multiplies the input by that.
When doubled it results in `J` being multiplied by `2`, so the element at index `-2` (i.e., the input) is returned by `j` and used as the multiplier.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 6 bytes (chunk length 3)
```
Ḥ;²3ị
```
[Try it online!](https://tio.run/##y0rNyan8///hjiXWhzYZP9zdrfD//39TAA "Jelly – Try It Online")
[Doubled](https://tio.run/##y0rNyan8///hjiXWhzZBSOOHu7sVwMT///9NAQ "Jelly – Try It Online")
[Answer]
# Nice solution: [Lua](https://www.lua.org), 66 bytes (chunk size 66 bytes)
```
a,x=a and...^2 or ...*2,setmetatable(x or{},{__gc=load'print(a)'})
```
[Try it online!](https://tio.run/##yylN/P8/UafCNlEhMS9FT08vzkghv0gByNAy0ilOLclNLUksSUzKSdWoAIpX1@pUx8enJ9vm5CemqBcUZeaVaCRqqtdq/v//38gQAA "Lua – Try It Online") (double it yourself, it is not so hard)
Oh yeah, pretty sure that there is shorter solution to this, but it's the best I was able to came up with this way. Take input as first argument.
Brief explanation: whole business with `a` is quite obvious for everyone, while the second part with `x` is more interesting. Basically, I create a table (or update existing one on second pass) with finalizer (`__gc` metamethod) which gets called when program exits.
# Lame solution: [Lua](https://www.lua.org), 60 bytes (chunk size 30 bytes)
```
a=a and...^2 or ...*2; print(a)os.exit()
```
[Try it online!](https://tio.run/##yylN/P8/0TZRITEvRU9PL85IIb9IAcjQMrJWwAYKijLzSjQSNfOL9VIrMks0NP///29kCAA "Lua – Try It Online") or [Try it doubled!](https://tio.run/##yylN/P8/0TZRITEvRU9PL85IIb9IAcjQMrLGLqqADRQUZeaVaCRq5hfrpVZklmhoEqfq////RoYA "Lua – Try It Online")
Smaller and with better chunking, but ultimately boring and lame without any clever tricks. I'm pretty sure no comments are required to this one.
[Answer]
# [J](http://jsoftware.com/), ~~15~~ ~~10~~ 9 bytes
```
+: :(*-:)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/ta0UrDS0dK00/2tycaUmZ@QrGCnYKqQpGEI4JmCOEYRjBuYYQziGEClzrv8A "J – Try It Online")
Doubled version: [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/ta0UrDS0dK004Yz/mlxcqckZ@QqGCrYKaQqGEI4JmGME4ViCOcZQGQjPnOs/AA "J – Try It Online")
`f : g` creates a verb that executes `f` when called with one argument, and `g` when called with 2 arguments. So ours executes double `+:` with the original source and `*-:` when the source is doubled.
This works because a train of two verbs in J becomes a hook, and thus `f f` is executed as `y f (f y)` where y is the original input. Additionally, `*-:` is itself a "dyadic hook" which works by multiplying `*` the left arg by half `-:` the right arg. The left arg will be the original input, and the right arg will be the input doubled, so this will produce the square of the original input.
## original answer
## [J](http://jsoftware.com/), 15 bytes
```
*:@]`(+:@])@.=~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tawcYhM0tIGkpoOebd1/TS6u1OSMfAUjBVuFNAVDCMcEzDGCcMzAHGMIxxAiZc71HwA "J – Try It Online")
Doubled version: [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tawcYhM0tIGkpoOebR0a978mF1dqcka@gqGCrUKagiGEYwLmGEE4lmCOMVQGwjPn@g8A "J – Try It Online")
In the single version, we have a single verb which uses Agenda `@.` to do the if... then logic: If the argument is equal to itself `=~`, then take the argument and double it `(+:@[)`.
However, when we double the code, we get a J hook. Call the verb `f` and the input `y`. Then the hook `f f` executes like this:
```
y f (f y)
```
Which means that now the original input is the left arg, and the right arg is the doubled input. Since these will not be equal, `=~` will return false this time, and now we'll execute the other fork of the Agenda, ie, `*:@]`, which means "square the right arg." And since `~` reverses the inputs of a dyadic verb, the right arg will be the original input.
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
Chunk size 6.
Not a great solution, but it works.
This is such a unique challenge, it really makes you think from a different perspective.
```
0; i=input;0; p=print;n=i()#
x=int(n)##
z=2*x#z=x*x
p(z)##
```
[Try it online!](https://tio.run/##K6gsycjPM/7/38BaQSHTNjOvoLTEGsQusC0oyswrsc6zzdTQVOaqAEqVaORpKitzVdkaaVUoV9lWaFVwFWhUAYX@/zcFAA "Python 3 – Try It Online")
Doubled:
```
0; i=0; i=input;input;0; p=0; p=print;print;n=i()#n=i()#
x=int
x=int(n)##
(n)##
z=2*x#z=2*x#z=x*x
z=x*x
p(z)##p(z)##
```
[Try it online!](https://tio.run/##NcuxCoAwDIThvU9RyNJ2EsWp9H3MEoNUiH35WDlcvuE/Tp9@nLK5LzVGbpBF717hV7RBvVh6hdI4ZYLB5qXDJJkowNHWYvRrxQLUNOYM3fcX "Python 3 – Try It Online")
[Answer]
# [Cascade](https://github.com/GuyJoKing/Cascade), 13 bytes (chunk size 13)
```
]
&/2
#
*
2&
```
[Try it online!](https://tio.run/##S04sTk5MSf3/P5ZLTd@IS5lLi0vBSO3/f0MDAA "Cascade – Try It Online")
```
]
&/2
#
*
2&]
&/2
#
*
2&
```
[Try it doubled!](https://tio.run/##S04sTk5MSf3/P5ZLTd@IS5lLi0vBSA2F8/@/oQEA "Cascade – Try It Online")
This was quite difficult. The basic gist of this is to print the input multiplied by `2` for the first program, and replace the `2` by a copy of the input for the second.
### Explanation:
The executed part of the first program looks like
```
] Redirection
/
# Print
* The multiplication of
2& Input and 2 (wrapping around the left)
```
The doubled program basically adds the first `]` to the end of the last line, so the program wraps around to that instead of the `&`. This turns it into
```
] Redirection
/
# Print
* The multiplication of
2 ] Set the value of
& 2 The variable '2' to the input
Then multiply the result of that (input) by '2' (input)
```
[Answer]
# [Zsh](https://www.zsh.org/), 30 bytes (chunk size 10)
```
m=$m[1]*2
x=$[$1$m]
return $x
```
[Try it online!](https://tio.run/##JYy7CoNAEEX7@YpbTJFY@WgiIn6IWOkkCtlZ2F1hUfz21ZhbHQ6Hu/k5@UU/X3k892RaNn0xZCXFlnsu2AzkJKxOwZHSQfS2DkF8wKKoUKMq8crzBpMlXPtfgX/JLWScLbi7eVUvAQaRJquSTg "Zsh – Try It Online") [Try it doubled!](https://tio.run/##qyrO@J@SX5qUk6qhWf0/11YlN9owVsuIC8GqsFWJVjFUyY1FYhWllpQW5SmoVCCx/tdycaXlFymUpBaXKGTmKRgrWCoYGylYGBhYK6TkcykAAcQiBRWQErBAanJGvoKKPZhdmlecWqKQq1DBlZKfl/ofAA "Zsh – Try It Online")
Abuses the fact that `$var` in `$[$var]` gets expanded first, then evaluated in the arithmetic context.
```
# each line is 9 characters long. when doubled, each is run twice.
m=$m[1]*2 # first time: m='*2' second time: $m[1] is '*', so m='**2'
x=$[$1$m] # single: x=$[$1*2] doubled: x=$[$1**2];x=$[$1**2].
return $x # zsh supports 32-bit return values from functions, unlike bash
```
If anyone wants a crack at lowering this, [here's the closest to a `24/8` solution I've gotten](https://tio.run/##JYw5DoAgFAX7f4pXUIBauDQueBtxSRQSwYS4nB23KSeT2e0Y7KSHWXFxBM59y7IIcZ6wTAiSUjJ/nnW4iHqzwinrMGkUqFDkKNO0QWcID/8E7E0@sWmrHBZ46oxW4QY "Zsh – Try It Online") (outputs `x^2+2` when doubled)
] |
[Question]
[
An alphadrome is a word in which each letter in the first half of the word "reflects" its alphabetical "opposite" in the second half of the word. Write a program or function that returns truthy if the given word is an alphadrome and falsey otherwise.
For example, `BEEB` is a palindrome. Its first letter `B` "reflects" its last letter `B`, and its second letter `E` reflects its second-to-last letter `E`.
In contrast, `BEVY` is an ***alphadrome***. Its first letter `B` is the second letter of the alphabet, and it reflects the word's last letter `Y`, which is the second-to-last letter of the alphabet. Likewise, its second letter `E` is the 5th letter of the alphabet, and it reflects `V`, the 5th-from-the-end letter of the alphabet.
Like palindromes, an alphadrome can have an odd number of letters, too. `WORLD` is an alphadrome. `W` is the 4th-from-the-end letter of the alphabet and `D` is the 4th letter; `O` is the 12th-from-the-end letter of the alphabet and `L` is the 12th letter. The center `R` reflects itself.
Any single-letter word is an alphadrome.
## Rules
* Input words will include only the characters `a-z` *or* `A-Z`, whichever is convenient.
* Output will be a [truthy or falsey value](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey).
* [Default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) apply, [standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply, and [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is code golf. Shortest answer in bytes wins.
## Test cases
```
A true
ABA false
ABZ true
ABBA false
BEVY true
GOLF false
ZOLA true
WIZARD true
BIGOTRY true
RACECAR false
ABCDEFGHIJKLMNOPQRSTUVWXYZ true
```
[Answer]
# [J](http://jsoftware.com/), 25 24 bytes
```
[:*/155=3,~inv@(+|.)@u:]
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209A1NTW2Ndeoy88ocNLRr9DQdSq1i/2ty@TnpKRhr6TtogORjYRJcqckZ@QqGCrYKaQrqjuoQrgGU6wQTgMk7RaGrQFfi5BoWiarG3d/HDVVNlL8Pmq5wzyjHIBc0kzzd/UOC0AwLcnR2dXYMQneWs4urm7uHp5e3j6@ff0BgUHBIaFh4RGSU@n8A "J – Try It Online")
*-1 thanks to ovs*
Based on the observation that this is essentially just requiring that the sum of the ascii codes of the input and its reverse add to 155.
The only exception is that, in the odd case, the middle element can be anything. The inverse of self-append in J `,~inv` returns the first half of a list, but "rounds down" in the odd case, and so does what we need.
That is, we can take the sums of the ascii codes as described, take the `,~inv` of that result, and check if they are all 155.
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
f=lambda s:len(s)<2or ord(s[0])+ord(s[-1])==155*f(s[1:-1])
```
[Try it online!](https://tio.run/##LY5NC4JAEEDv/YrFy7qlkEUXyWD9zLKszTQVD4ZJgqm4Xvr1pm6nN294A9N8u3ddrfs@V8r088xSQOXyVfEUbVd1C@o242m8TNCCTaKUIEWRNpt5Ppgkj97nQ0hBUYEYYigAiNU/IgamquGHIy3XMUdGrjPtAzvCRJ8K23I9MkUEa4aGCbvXdMO09vbh6JzO7uVKbt7dDx5hBBN5Bpq2qDqeCpy44wQwfIVQ/wM "Python 3 – Try It Online")
Takes lowercase letters as input.
*-3 bytes thanks to pxeger*
[Answer]
# Excel (ms365), ~~147~~, ~~111~~, ~~110~~, ~~98~~ 89 bytes
-15 bytes thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt)
-4 bytes thanks to [@EngineerToast](https://codegolf.stackexchange.com/users/38183/engineer-toast)
```
=LET(l,LEN(A1),n,SEQUENCE(l/2),IF(l>1,SUMSQ(CODE(MID(A1,n,1))+CODE(RIGHT(A1,n))-155),)=0)
```
| A | B |
| --- | --- |
| A | TRUE |
| ABA | FALSE |
| ABZ | TRUE |
| ABBA | FALSE |
| BEVY | TRUE |
| GOLF | FALSE |
| ZOLA | TRUE |
| WIZARD | TRUE |
| BIGOTRY | TRUE |
| RACECAR | FALSE |
| ABCDEFGHIJKLMNOPQRSTUVWXYZ | TRUE |
Uploading a small screenshot was not possible at time of posting. Also, the byte-count is high and I'm eager to see if fellow Excel enthusiasts can bring this down.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~8~~ 7 bytes
```
Ḃ+⁺6oLṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZkMiLCLhuIIr4oG6Nm9M4bmFIiwiIiwiQVxuQUJBXG5BQlpcbkFCQkFcbkJFVllcbkdPTEZcblpPTEFcbldJWkFSRFxuQklHT1RSWVxuUkFDRUNBUlxuQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoiXQ==)
-1 thanks to a trick from @Kevin Cruijssen's 05AB1E answer.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~53~~ 44 bytes
-9 bytes thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)!!!
```
f(*s,*e){return--e<=s||*s+*e==155&f(s+1,e);}
```
[Try it online!](https://tio.run/##dVFNb4JAEL3zKyY0NruAqTbxUuSAimil0lLrZzkYnG1IKBoW06bqb6eLFtO0Moed2Tfz8uYjqAbRMn7LMkYUrilIdwmm2ySuVrFp8P1e4aqChlFvNK4Z4WpdQ6ofsqsVsjBGcKyhPeqRKQXCwy9cM8jjGzh/FjWfUkkK4xTel2FMKEg7CYQJRIEUebrwwYATlpsjm7Im3jTZoqz9hlunBFtG/G9mXkYp5bSs8ewyyXadbglp7jolzU36c9PrXM61@rY78krUPLNttU2vdLJ2x@ravf79wHkYuo9P3vPoZTyZzv4NfNCPjq0TIPmyQ7HUmi5cs7hRvmuaI6oBt/QssklEOSNyJeKCUllpgJ8bDFJc3YHAXmOhdDxT6GvASBH@ePUj4BHGBUxpUQwq1H2qS4fsGw "C (clang) – Try It Online")
[Answer]
# [Raku](https://raku.org/), 37 bytes
```
{155==all .ords[^(*+>1)]Z+.flip.ords}
```
[Try it online!](https://tio.run/##HYrdCoIwGEBf5UMkKkHwwm5qxvzNslbLNBclQg2ChaJXIj77Wl0cOBxO82rFQn56mHBAcrBsG6FKCDDr9tndHtO54VizOzNMLt7NP45y2VU9aHoJyIFhzUEvRw143cIKA3Z/MIUSN8gKiEgSAiMJhjxmmPrgxhFJaQEUe4GHqVo9PwijTbzdJfsDOZ7oOb1k@bVgjvwC "Perl 6 – Try It Online")
* `.ords` is a string method that returns a list of Unicode codepoints.
* `^(* +> 1)` is an anonymous function that returns a list of numbers from 0 to one less than the argument shifted one bit to the right. (`* div 2` would be more readable, but is longer.)
* When a list is subscripted with a function, the list's length is passed to the function, and whatever the function returns is used to index into the list. Most often this is used to index from the end of the list (eg `@list[* - 1]`) but here, the result is a slice of the first half of the list, not including the middle element, if any.
* `.flip` is a string method that returns the reverse of the original string. `.flip.ords` is thus the list of the input string's Unicode codepoints in reverse order.
* `Z+` zips the two lists of codepoints with addition, up to the length of the shorter list.
* `155 == all ...` is a junction which is truthy if all of the added codepoints are equal to 155.
[Answer]
# x86-64 machine code, 16 bytes
```
AC 83 EF 02 78 09 02 04 3E 3C 9B 74 F3 31 C0 C3
```
[Try it online!](https://tio.run/##VVJtb9owEP5s/4pbJoTdpB3qpn2AMYlSyljp2LKuL7x8CI4TXAWnio0Wivjry86hq9Yvd7675zk9z8niOBWiqiKzBgahx@hJmuXLKIOEJm2S5bFZUmI2S5CxCuCUkgcDkpIojiHKApgVRoEPRawWlIj1Y91s9pp@c9pErMQ1pMwLkFEZuEBlmxTSUu4B71ClLSTMRWSJXBsLYhUVcGRwSN8qLbJNLOGTsbHKT1afX7UKpVPXo/8TrZgtoAs76vW8AMPZc5oe0qE8G9zcuzycjC9cnk7Gdf92NO2F5zViNJxchzUo7PUH/V544PfPBxfDL6Ovl@Orb5PvP8Kf179ubu/u3fY9KnZO1pHSjNMdJQn6rs0pVNTqYHrTBaOeZJ4wK/i75ydq5jj0fU4JssgrO8hES2rRwcEjOrYJ8xpmbhtqrr0AbID3w1NkUjPLseZ4OLKnL9i5vorESmmJ541l23NjJ6l0kgLYYhnnsPsHh0br9A73bruMbbRRqZZxLeWIJ3xW@v6Cd/bwe6UyCWzr/LTK/nu39GUDayhYbq00vFZY4nBfVX9EkkWpqY7XHz9gwO/WRbzM/gI "C (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of the string in EDI and its address in RSI, and returns a value in EAX, nonzero if and only if the string is an alphadrome.
In assembly:
```
f: lodsb # Load a byte from the string into AL, advancing the pointer.
sub edi, 2 # Subtract 2 from the length in EDI.
js e # Jump to the end if the result is negative.
# In this case, the string is an alphadrome.
# AL (which is the low byte of EAX) is nonzero.
add al, [rsi + rdi] # Add the opposite-positioned byte in the string to AL.
cmp al, 'A'+'Z' # Compare the sum with the sum of 'A' and 'Z'.
je f # Jump back, to repeat, if they are equal.
xor eax, eax # If not, the string is not an alphadrome. Set EAX to 0.
e: ret # Return.
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 35 bytes
```
{2>grep *-155,(.ords Z+[R,] .ords)}
```
[Try it online!](https://tio.run/##Vc3NCoJAFIbhfVdxVqFlkoHtFMbfLMuaTHPEhZBGYCljERFdu2Ea1tm9PB@cIqHZtDo/oJ@CBNVzIh9pUsBgJIgix/A5PZRAhiHmIvgE@6rK@AEpw4fjiAVJBj4UIkhzCtnpkpSyzN/rXYWgvSu9JT2ktJ3GWVkn@cNWG1R0L@jQdGzjB4ljow59iyCsfUuxTMfFQVsYqbqKcPdS1XTDnFnzhb1cOesN3ro7z98HpNm/AQ "Raku – Try It Online")
Anonymous code block that takes a string and returns a boolean.
# Explanation
```
{2>grep *-155,(.ords Z+[R,] .ords)}
{ } # Anonymous code block
(.ords Z ) # Zip the codepoints of the string
+ # Adding them
[R,] # To the reverse
.ords # of the codepoints
grep *-155, # From this, filter out the 155s
2> # And check if there is exactly 1 or 0 of them
```
[Answer]
# [R](https://www.r-project.org), ~~34~~ ~~35~~ 24 bytes
*Edit: +1 byte to fix bug spotted by Kamil Drakari*
*Edit2: saved 11 bytes by changing to same approach as [my Nibbles answer](https://codegolf.stackexchange.com/a/253115/95126)*
```
\(x)sum(x+rev(x)!=155)<2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHazOLEnIKMxJSi_NxU26WlJWm6FjtiNCo0i0tzNSq0i1LLgGxFW0NTU00bI4j0zafIejSAYhYh-Z55JRpKjkqamly4JJ1cwyLxyYd7RjkGueA1wdPdPyQIryGOTk54HeHu7-OGTz7I0dnV2TEIpATi2QULIDQA)
Input is vector of codepoints.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
+Un155SỊ
```
[Try it online!](https://tio.run/##y0rNyan8/187NM/Q1DT44e6u/w93b/E/3P6oac3RPUBmFpDxqGGOgo2twqOGuZH//ztyOTqBcBQQAxlOrmGRXO7@Pm5cUf4@jlzhnlGOQS5cTp7u/iFBkVxBjs6uzo5BQKXOLq5u7h6eXt4@vn7@AYFBwSGhYeERkVEA "Jelly – Try It Online")
-1 thanks to Jonathan Allan
[Answer]
# [Perl 5](https://www.perl.org/), 49 bytes
```
sub f{pop=~/.\K.*\B/?155-ord($`)-ord$'?0:f($&):1}
```
[Try it online!](https://tio.run/##ZZFdT4MwFIbv@RUnCxMw7EszYyALwj5wbg5F3ITsQt2KkrHRActclvnXsRQWh/am7dun5317ilHoN5Mk2ryDu8cBbn3XqtNB9Xyq1ZRGs1kJwjnPvgrpzHJKXXJ59kyQGodkuYObGEUxtGC95RkgQ4V8xOEGZYqWa@6bHx0l5x@UU7@Q1h3bRUg3hr0/kGMM1SI06Tuq2TlVtL5uWKZ9ophqu9tWzWKkwqbd6fb02/7dYHg/Mh4ezSfreTx5sZ28iCAz20/PRzx9vrCnt5Y7nvVWWGTRFxZISyLsezNECbEuXsg5BOxHkHbMpbQACnBpTQ4k4GgELiNx6K1iF0rlynUEhNzEEpQrl/WInBEHNIvRPFWuUoGUzNbTVUlkjn@QJgG0zhyJT7CgLiPDAmPAiUDjUkqkjMwckh8 "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 34 bytes
*-1 and a bug fixed thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) (on both versions)*
Expects an array of ASCII codes. Returns *true* for non-alphadrome or *false* for alphadrome.
```
a=>a.some((_,i)=>a.pop()+a[i]-155)
```
[Try it online!](https://tio.run/##rdK7CsIwFIDh3aeomRK0KQ6OCunFWq1W470iEmoilWpKq75@xUFwsGgxZzvLz8fhnNid5VEWp1f9Ig@8EJ2CdboM5/LMIdw3Y/TcUplC1GDbeKe32m1URPKSy4TjRB5hXcAtxti8CcEzLDJ5hoAArWzQDiHNMLRrduO1rx2ztPTqCJbkv4RCoAZUKqoGMp3lBigAuYHfUwIKA5@oAK28kFAb/N0xPTeY0483qtShxHIsQoGCF7Jsp@f2vcHQH42DyZTO5ovlar0JwTuoeAA "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 51 bytes
Expects a string. Returns *true* for non-alphadrome or *false* for alphadrome.
```
s=>(a=[...Buffer(s)]).some((_,i)=>a.pop()+a[i]-155)
```
[Try it online!](https://tio.run/##ndG7DoIwGIbh3avATm3UGgdHSMpRFEXrAcUY02BrMGgJFW8fBwcHxQT//c2TL/@FPZhKijS/927yxCuhV0o3INP3GGOzFIIXUKEDwkpeOYTHbop0g@Fc5hB12D499AbDIaoSeVMy4ziTZ9gWEBCg1R1CWr@v3YuStz4qs7Z7VYJl6lsWg3@wWu0XZjqbHWiMeWHg/oHFYUCaY5EfE2qDhpXpe@GKft32o6LEcixCQeOXWbbjeiN/PAmms3C@oMvVehNtdzF4Y9UT "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
!t-+VJCMz_J219
```
[Try it online!](https://tio.run/##K6gsyfj/X7FEVzvMy9m3Kt7LyNDy///yzKrEohQA "Pyth – Try It Online")
### Explanation:
```
JCMz assign input codepoints to J and return list
_J reverse J
+V map addition over two lists
- 219 remove all instance of 219 from this list
!t list has no more than 1 element
```
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
f s=[1]<[1|(x,y)<-zip<*>reverse$fromEnum<$>s,x+y/=219]
```
[Try it online!](https://tio.run/##lZDLDoIwEEX3fsXEsPABMbgzoez8CsKiQAuVQnFaXo3/jgtjooYu3M7JyZ17K6prJuWycNAkCdMoCR@7yZ/3UWBFFx1iZANDzTyOqrm2fRN5sfan43wi5/CSLg0VLRAo1AY6FK0BDzhs6RaCAAz27PucvQCnUv8S61KcTsaGeV0qleQOySrpeG4UlmKxzjJRKoOONKQ5yyk6m@UF42UlbrVsWtXdUZt@GKf5o/B7/Jj8t/4T "Haskell – Try It Online")
Zip input with its reverse, there can be at most one pair not summing to 219, the one in the centre of an odd lengthy string.
So by yielding *1* for unbalanced pairs we must have a list less or equal than [1]
Saved a byte by inverting the output and using greater than [1]
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$9\log\_{256}(96)\approx\$ 7.408 bytes
```
M'>2Lo155+$
```
[Try it online!](https://fig.fly.dev/#WyJNJz4yTG8xNTUrJCIsIltbNjVdLFs2NSw2Niw2NV0sWzY1LDY2LDkwXSxbNjUsNjYsNjYsNjVdLFs2Niw2OSw4Niw4OV0sWzcxLDc5LDc2LDcwXSxbOTAsNzksNzYsNjVdLFs4Nyw3Myw5MCw2NSw4Miw2OF0sWzY2LDczLDcxLDc5LDg0LDgyLDg5XSxbODIsNjUsNjcsNjksNjcsNjUsODJdLFs2NSw2Niw2Nyw2OCw2OSw3MCw3MSw3Miw3Myw3NCw3NSw3Niw3Nyw3OCw3OSw4MCw4MSw4Miw4Myw4NCw4NSw4Niw4Nyw4OCw4OSw5MF1dIl0=)
(link includes extra code for test cases)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
Count[ToCharacterCode@#//#+Reverse@#&,Except@155]<2&
Count[#+Reverse@#&@*ToCharacterCode@#,Except@155]<2&
(* 52 bytes too,using @* diff is just "@*" and "//" *)
```
[Try it online!](https://tio.run/##TcvNCoJAFIbh/VxFjOCmQgrcVTiOP1mWNpmm4WKwEV2YYVME0bWbmUhn93C@t6A8YwXleULrdF7j8n7hJ6/EGa1owlmFyzNTBEkShoQ9WHVrII70Z8KuXJnIcjybirVb5U0kjBepIsSipLwARHA06K6B2vOL6B/9C0BV98MepmMbPSLH7mYABlaEiNaqSSzT8UhbAUgQ1jEiPyAVa7phLq3V2t5sHXdH9t7BD45hBMG7/gA "Wolfram Language (Mathematica) – Try It Online")
**I'm new to codegolf, any suggestion will be appreciated.**
The code means, convert string to charactercode list, add it with its reversal, count number of element!=155, judge whether the number is less than 2.
one interesting thing is that, among 26 letter, there's no letter such that CharacterCode==155/2
**so this algorithm is absolutely true for input string formed from 26 upper letters**
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7.5 bytes (15 nibbles)
```
- 2,|!\$@+%155
```
Input is array of codepoints.
All positive integers are truthy in [Nibbles](http://golfscript.com/nibbles/index.html), zero and negative integers are falsy.
```
- 2,|!\$@+%155
! # zip together
\$ # the reverse of the input
@ # and the input
+ # by addition,
| # then filter the list
# to keep only truthy elements upon
%155 # modulo 155,
, # get the length of the resulting list,
- 2 # and subtract it from 2
# (so only zero or one non-155 element
# will give a truthy >0 output)
```
[![enter image description here](https://i.stack.imgur.com/NNeUT.png)](https://i.stack.imgur.com/NNeUT.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
cÈ+UÔcYÃk'Û Å
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y8grVdRjWcNrJ9sgxQ&input=WwoiYSIsCiJhYmEiLAoiYWJ6IiwKImFiYmEiLAoiYmV2eSIsCiJnb2xmIiwKInpvbGEiLAoid2l6YXJkIiwKImJpZ290cnkiLAoicmFjZWNhciIsCiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eiIKXS1tUg)
Takes input as a lowercase string. Outputs an empty string for `true` and a non-empty string for `false`.
```
cÈ+UÔcYÃk'Û Å
cÈ # Map the charcode of each input character through:
UÔcY # Get the charcode at the same index in the input reversed
+ # Add them together
à # Treat the results as charcodes for a new string
k'Û # Remove the character "Û" whenever it appears
Å # Remove the first remaining character if possible
# Implicitly print the result
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 44 bytes
```
f=->w{/.(.*)./!~w||w.sum-$1.sum==155&&f[$1]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1668Wl9PQ09LU09fsa68pqZcr7g0V1fFEETZ2hqamqqppUWrGMbW/rexiY@P18vJzEst1stNLKiuqagpUIhOi66I1o8p19aPjdVRSC1LzNGA8FX0YzVja7kcFaCgpKg0lcvRCcpPS8wpBnGjUCShshBJJ9ewSISku7@PG5JklL@PI0Iy3DPKMcgFxnPydPcPCYqE8oIcnV2dHYMQVjq7uLq5e3h6efv4@vkHBAYFh4SGhUdERkHVA/34HwA "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Input as an array of lowercase codepoints, outputs `false` for truthy & `true` for falsey.
```
£v +UoÃd-#Û
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=rG1j&code=o3YgK1Vvw2QtI9s&footer=IVY&input=WwoiYSIKImFiYSIKImFieiIKImFiYmEiCiJiZXZ5IgoiZ29sZiIKInpvbGEiCiJ3aXphcmQiCiJiaWdvdHJ5IgoicmFjZWNhciIKImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6IgpdLW1S) (includes all test cases, footer reverses output)
```
£v +UoÃd-#Û :Implicit input of charcode array U
£ :Map
v : Remove & return first element of U
+ : Add
Uo : Remove & return last element of U
à :End map
d :Any truthy
- : Subtract
#Û : 219
```
[Answer]
# C# (.Net 6), 73 bytes
```
int i=0;while(i<s.Length/2)if(s[i++]+s[^i]!=155)return false;return true;
```
[Try it here](https://dotnetfiddle.net/OlXEMU)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÇÂ+ƵsKg!
```
Input as a list of capital codepoint-integers (although could alternatively be in lowercase as well by changing `s` to `\`). Outputs an 05AB1E truthy result (`1`) if it's an alphadrome, and an 05AB1E falsey result (in this case any other integer) if it's not.
[Try it online](https://tio.run/##yy9OTMpM/X@4/f/hJu1jW4u90xX//w/3D/JxAQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmn/qGGegoZ95eF2eyVNhUdtkxSUQJz/h5u0j20t9k5X/O9in6mkoFFSVJqqqXR4NZCZlphTDGTX6vx35HJ0AuEoIAYynFzDIrnc/X3cuKL8fRy5wv2DfFy4wj2jHINcuJw83f1DgiK5ghydXZ0dg4AanF1c3dw9PL28fXz9/AMCg4JDQsPCIyKjAA).
**Explanation:**
```
 # Bifurcate the (implicit) input-list; short for Duplicate & Reverse copy
+ # Add the values at the same positions in the lists together
Ƶs # Push compressed integer 155
K # Remove all 155 from the list
g # Pop and push the length
! # Get the factorial of this length
# (0 becomes 1; 1 remains 1; any other integer just increases)
# (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 `Ƶs` is `155` (and `Ƶ\` is `219`).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~23~~ 17 bytes
*-6 bytes thanks to DLosc!*
```
#(_!=155FIg+Rg)<2
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCIjKF8hPTE1NUZJZytSZyk8MiIsIiIsIiIsIjY2IDczIDcxIDc5IDg0IDgyIDg5Il0=)
Takes in input as a list of codepoints in the arguments. Port of the R answer, so make sure to upvote that too!
```
#(_!=155FIg+Rg)<2 ; Input = list of codepoints = g
#( ) ; Get the length of...
g+Rg ; the vectorized sum of g and its reverse...
_!=155FI ; filtered by if each element is not equal to 155...
<2 ; and test if the length is less than 2
; (after which the result is implicitly printed out)
```
[Answer]
# [sed](https://www.gnu.org/software/sed/) `-E`, ~~103~~ 102 bytes
*-1 byte thanks to [user41805](https://codegolf.stackexchange.com/users/41805/user41805)*
```
:a
s/./\L&/
y/abcdefghijklmnopqrstuvwxyz/ZYXWVUTSRQPONMLKJIGHFEDCBA/
/../!cT
T
s/^(.)(.*)\1$/\2/
ta
cF
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY306wSuYr19fRjfNT0uSr1E5OSU1LT0jMys7JzcvPyCwqLiktKy8orKqv0oyIjwsNCQ4KDAgP8_Xx9vL083T3cXF2cnRz1ufT19PQVk0O4QoBmxWnoaWroaWnGGKroxxjpc5UkciW7QWyDWrrgpr8jl6MTCEcBMZDh5BoWyeXu7-PGFeXv48gV7hnlGOTC5eTp7h8SFMkV5Ojs6uwYBFTq7OLq5u7h6eXt4-vnHxAYFBwSGhYeERkFMRcA)
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~35~~ 29 bytes
```
[ halves reverse v+ ""⊂ ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQnFpYmpqXnFqskJtYkqFXlgqSLFbITi3KS82BiJXmZSbnp6QqFBSllpRUFhRl5pUoWHNxVXMpAIGSo5ICbqCoUFJUmgpV6IRHqaJCWmJOMVxllBKRRuIxE8VIJ9ewSCVijHT393Ejzsgofx9HoowM94xyDHJRIqzQydPdPyQIhzuRFQY5Ors6OwYpEROUzi6ubu4enl7ePr5@/gGBQcEhoWHhEZGgEIYaWcv1P1ohIzGnDJgIilLLUouKUxXKtBWUDs1WetTVpBD7PzexQKG4JDE5W@8/AA "Factor – Try It Online")
```
! "BIGOTRY"
halves ! "BIG" "OTRY"
reverse ! "BIG" "YRTO"
v+ ! { 155 155 155 }
"" ! { 155 155 155 } { 155 } (string with non-printable char 155)
⊂ ! t (subset?)
```
[Answer]
# [Go](https://go.dev), ~~104~~ 73 bytes
```
func f(s string)bool{l:=len(s)
return l<2||s[0]+s[l-1]==155&&f(s[1:l-1])}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BzoLE5OzE9FSF3MTMPK7M3IL8ohI9pbTcEqWlpSVpuhY3PdNK85IV0jSKFYpLijLz0jWT8vNzqnOsbHNS8zSKNbmKUktKi_IUcmyMamqKow1itYujc3QNY21tDU1N1dSA-qINrUACmrUQA28xKYNNBNmnoalQzZVtZZumoeSopMkVADS_JCcPxNHJ1ikpKk3Vyba1BdGaXNlgRU6oypzACtMSc4rBKsEMuNIoVKVROM1ENxSPqU6uYZHIisF87Oa6-_u4ISsF83GZG-Xvg-IIMB-7ueGeUY5BLsiKoSLYlTt5uvuHBKE6GiqEXUOQo7Ors2MQsgaYEO6wdnZxdXP38PTy9vH18w8IDAoOCQ0Lj4hEiwKcqjBcAk0rCxZAaAA)
Based on [@Manish Kundu's answer](https://codegolf.stackexchange.com/a/253089/77309)
* -31 bytes by @Jordan, @Steffan: Combining the `if`s into a single expression
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 49 bytes
```
T`L`RL`^.(.)*(?!(?<-1>.)*$)
+`^(.)(.*)\1$
$2
^.?$
```
[Try it online!](https://tio.run/##FYrBCgIhFADv7y8CA91I2M7Roq5rlmWZ7aaE2KFDlw7R/5sdBoZhPs/v6/0oc6xy8dlkZ3KimJIGdzPcrZftpjoisMipVkwbcm8RoBUk2qFSGDD@J1aqcDkGUNYMEK1hMOnIXA9cK@tdAMeEFMzVVfRyUFu925vD0Z7O7uKv43QL8Qc "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`L`RL`^.(.)*(?!(?<-1>.)*$)
```
Transliterate the first half of the word, flipping between `A-Z` and `Z-A`.
```
+`^(.)(.*)\1$
$2
^.?$
```
Test whether this results in a palindrome. (This turns out to be the same method as @ovs's answer to [Shortest code to determine if a string is a palindrome](https://codegolf.stackexchange.com/q/11155/) so I might have remembered the approach.)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
⬤∕θ²⁼⌕αι⌕⮌α§⮌θκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxJ0fDJbMsMyVVo1BHwUhTR8G1sDQxp1jDLTMvRSNRRyETKARmB6WWpRYVp2okAgUcSzzzUlIr4GKFQLFsTRCw/v8/3DPKMcjlv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for an alphadrome, nothing if not. Explanation:
```
θ Input string
∕ ² First half (excluding middle character if any)
⬤ All characters satisfy
⌕ Index of
ι Current character
α In predefined variable uppercase alphabet
⁼ Equals
⌕ Index of
θ Input string
⮌ Reversed
§ Indexed by
κ Current index
α In predefined variable uppercase alphabet
⮌ Reversed
Implicitly print
```
[Answer]
# [Behaviour](https://github.com/FabricioLince/BehaviourEsolang), ~~40~~ 37 bytes
```
~(a*=ascii\:i<-#a/2a%i+a%(-i-1)~=155)
```
`a` must contain input string
```
a = "ABA"
@~(a*=ascii\:i<-#a/2a%i+a%(-i-1)~=155)
```
ungolfed and commented:
```
~( // invert the result of the following sequence
a *= ascii // convert string input to a list of ascii values
\:i <- #a/2 // iterate from 0 to half the input size
a%i+a%(-i-1)~=155 // stop if opposites values don't sum to 155
)
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~50~~ ~~48~~ ~~44~~ 41 bytes
```
~x=sum((a=Int[x...]).+reverse(a).!=155)<2
```
[Try it online!](https://tio.run/##LYvBCoJAAETvfcW2ICjJQoIdIqHVzCxL20xT8@DBYqO20Iw9@euW2unNPGZu1Z1mY940NdfK6iGKmWazd8IRQqmERkX@yYsyFzMJDbWxqkozpalKyq7AKyh7XwbJ/NUFEQrKpJwCgZ4ZlAGXQc0lcHkWgAPKQALxz0Ks/xH36KtuBlFLy3WWLWPX6Xxox5gsuoVtuT7pRgQbpoFJ/zcW5tJa2euNs9253p4c/GMQnqIYpmnzBQ "Julia 1.0 – Try It Online")
Saved 2 bytes thanks to Sʨɠɠan's suggestion: use the return value of the variable assignment.
Saved 4 bytes thanks to amelies: replace `collect(x)` with `[x...]`.
Saved 3 bytes thanks to MarcMush: replace `Int.([x...])` with `Int[x...]`.
] |
[Question]
[
Sequel of [this AWESOME challenge](https://codegolf.stackexchange.com/questions/31552/disarm-the-b-o-m-b)
You, a genius tech prodigy detective, have successfully disarmed the bomb and want to break into the computer. The police found the password `67890-=yuiop[]hjkl;'\vbnm^&*()_+:"|` on a piece of paper, but much of the keyboard is broken and there are no other ways of inputting characters.
The only characters left to use are `12345QWERTASDFG<>ZXCqwertasdfgzxc!@#$%` and also Tab, Space, and Newline. However, a fairy appears and gives you one more character of your choice.
Using only these 42 characters, produce as many of the password's 35 characters as you can. Write a separate program/function for each password character.
### Scoring:
1. Primary scoring is how many characters you can produce (1–35).
2. Secondary, tie-breaking score is the total length of your programs/functions.
Standard loopholes apply
*Thanks to @Adám for rework*
[Answer]
# Deadfish, all 35 characters, 444 bytes
Uses `s`, `d`, and `c`, which are allowed, plus `i` as an extra.
```
6 iisiiisiiiiic
7 iisiiisiiiiiic
8 iisiiisiiiiiiic
9 iiisdsdddddddc
0 iisiiisdc
- iisiiisddddc
= iiisdsdddc
y iiisiisc
u iiisiisddddc
i iiisisiiiiic
o iiisisiiiiiiiiiiic
p iiisiisdddddddddc
[ iiissiiiiiiiiiic
] iiisisdddddddc
h iiisisiiiic
j iiisisiiiiiic
k iiisisiiiiiiic
l iiisisiiiiiiiic
; iiisdsdddddc
' iisiisiiic
\ iiisisddddddddc
v iiisiisdddc
b iiisisddc
n iiisisiiiiiiiiiic
m iiisisiiiiiiiiic
^ iiisisddddddc
& iisiisiic
* iisiisiiiiiic
( iisiisiiiic
) iisiisiiiiic
_ iiisisdddddc
+ iisiisiiiiiiic
: iiisdsddddddc
" iisiisddc
| iiisiisiiic
```
Unless I did my coding wrong, I believe these are necessarily optimal.
[Here is the meta-golfer](https://tio.run/##dVTtcts2EPwtPsWNNFOTsZxx2mnaOqM@Q/vbTROIPIqISAACQMnsx7O7ewBlS2k74/FQB@B273bv3BQ7a757fl5Rx8odSAdyKXYTUoRK57X1Ok50GHnkinq99cpPhR6c9TE/K4oVDRzVzvZtWXe@orufKURfrHDgOY7eBFJmIttS7JhCh6ccIjlvd14NAVEVyY7RjRHfYFF3yqs6sidtqGHVtDp0VI5Bmx3pNTVrCmuqK0A03F6iK189FIvaNuysNpE2ZH2T40WxWCGfjlr1@g8mRdfV0UnHDviembjngU0MDySpqGezix0QR@8RRnUq8jpVk851DNy3kj9IbQ1tp8uH1GqPelvrSWhqwyFcX04JKXBtTUPRkjpa3SAttd4OtOMYpfIRKHjaT9Qrv2M6qn7kkO94dowcDQ7DYVQe9wVCKKKlvsmXReIvI7gAI6LF@1zDdVnKJOjGcjA3kQYVRQkVqLcgocJr3bk8wVkgsXVRD6pP70E53/N618UMXiyKBVy2ocfyfk34Wy6rj0mVTOWog5Z@4J@YwkIfPgqvcx9OKqQ@AIbJmnP9yT6q9/DJRJ06Mu2NPZnZaPDQ4LKcKmpr0Pkz0Ib@vP8bBE6d7pncAc5ZnKWee5HK3GSjv5X/zrrSHSpaEb5QamKb6Um5@ADh2em//LoW@7HPIs9mwInJ6QH9IpG4ztkQ9BZU0A8DisKWlIdqpvZSAUcqdQX/c/6Nn00lGFlzpjJUyClGM/wUP81FpG@NXJimxzJ77ZbeQQC9xPM5cpcizUXkzbkLywClpDtpgl4mMk@AqutxGHsVgeo5iPC6Fc06jAXdvRN6337/nvgJI91PkgXnr/xos5lvXcfwJkEuzJPM8X2R8cNeu/9X/qz5kX1I7QPdLMW/cXE0OyHjYPhgr5FnoCRnGtxg@1HEwASPMhvheo9tVYDA9gyUJYdPPySp13RCj5xjvPxcfxZfz6tOXSy6/@zKyxrL/PIuzZa8fRX1lpb1cuZsgehPOkCzNOaqSaMs0565yWwOyu8lCvy5fnl8YfExdPA4bDA7Nnnl0lBfUajEdOepegvM8vUy1q7YUQqVhmuDykvZ0Vi@JqbNvP5qgVfPz@9/@PGn@7vNNGrrHj92X/b9h5vfjlsz/P7Nm7L6dPuw/Osf)
## Explanation
I do a pretty simple BFS by creating a priority queue that orders by length first (so the golfiest solution is always found) and state second (so that it doesn't waste time on ridiculously large numbers caused by repeated application of `s`). Also, I track a visited set to prevent revisiting values with suboptimal-length code.
Then, each time, I just add the state transitions `(L,x,c)->(L+1,x+1,c+"i")`, `(L,x,c)->(L+1,x-1,c+"d")`, and `(L,x,c)->(L+1,x*x,c+"s")` where `L` is the code length, `x` is the current number, and `c` is the current code.
My meta-golfer code is fully commented if you want a more detailed explanation.
[Answer]
# Javascript, score 5
```
6: x=>21%15
7: x=>22%15
8: x=>23%15
9: x=>24%15
0: x=>1%1
```
```
12345QWERTASDFG<>ZXCqwertasdfgzxc!@#$%
```
# Step 1: Functions or programs.
We need to have functions, so we have to take `=`, from which we can make `x=>[code]` or similar.
So, what can we do with what we've got?
67890 can be made with numeric operations. But for the rest, we need string coercion, which we can't get without some other character.
# What if I didn't need functions? (Note - below this is all hypothetical).
We still need some form of string coercion:
* String.fromCharCode
* `+[]` or `+''`
* Literally calling toString
The first requires `in.omh`, so is obviously not an option.
The second requires `+` and either `'`,`"`, a backtick or `[]` - Sorry, but no.
The third has the same problems as the first.
So that's all we can do, and it's not enough.
# But what about 2 characters?
Sadly, `+'` and `+"` have no way of getting specific characters. +` adds function calling to our repetoire, but charAt needs an h and a . .
If we start with a string(using backticks because function calling), we can get one character of our choice! But we can't get anything else, so that's a dead end.
Enter escape sequences!
With `'` and `\`, we can do things like `"\153"` or `"\x2c"`, netting us a bunch of extra characters! The complete list is:
```
-: '\55'
i: '\151'
[: '\133'
]: '\135'
j: '\152'
k: '\153'
l: '\154'
b: '\142'
m: '\155'
*: '\52'
): '\51'
+: '\53'
": '\42'
=: '\x3d'
]: '\x5d'
^: '\x5e'
_: '\x5f'
:: '\x3a'
Along with the standard:
': '\''
\: '\\'
```
This leaves `yuoph;n&(|` to deal with.
Checking which character will be the most effective out of 67890b, we get 7, adding 5 characters to our list
```
y: '\171'
u: '\x75'
o: '\157'
;: '\73'
|: '\174'
```
And now we're down to `phn&(`. Checking again, we find 0 gives us `ph(`:
```
p: '\x70'
h: '\150'
(: '\50'
```
Leaving us `n&`. Finally, 6 unlocks the last two:
```
n: '\156'
&: '\46'
```
So our extra charset is `'\670`. Note that here we have assembled the full octal set: `01234567`, and can make any character with what we've defined. But what else can we do?
# What if we try something different?
What if we use `+[]` to start with? `+[]` is the basis of most of javascript, and we can now use some previously useless characters. We still have no function calling, but:
We can get `.` by taking the second character of 11e111 which is coerced into 1.1e112: `[11e111+[]][+[]][1]`
From there, we can get `-`, by making .0000001 as a string, coercing into a float, which is 1e-7, then coerce back to a string and get the right character : `[+[[11e111+[]][+[]][1]+1%1+1%1+1%1+1%1+1%1+1%1+1][+[]]+[]][+[]][2]`
We can get the string "undefined" from taking the first of an empty array: `[][+[]]+[]`, "true" and "false" from `!![]+[]` and `![]+[]`, "NaN" from coercing undefined to a number: `+[][+[]]`, and "[object Object]" from `CSS+[]`. Adding this, our character pool (as strings only) is now:
"-.undefitrualsNa[objcO]"
We can take `[]['f'+'i'+'n'+'d']+[]` to get the code of the find function as a string:
```
function find() {
[native code]
}
```
Our string character pool is now `-.undefitrualsNa[objcO] (){vc}` and newline.
Note that from this we can get "constructor". We can use this like so: `[]["constructor"]+[]` returns `function Array() { \n[native code]\n}`, adding A and y to our pool. `[[]+[]][+[]]["constructor"]+[]` returns the string function, giving us S and g. `[]["find"]["constructor"]+[]` adds F from Function.
So, our current string is `-.undefitrualsNa[objcO] (){vc}AySgF`, from which we can take snippets for `-yuio[]jlvbn()` by taking arbitrary characters, leaving us with `=phk\m^&*_+:"|` to deal with. Note that while `+` is in our codebase, it cannot be coerced into a string with only what we have.
# Now what?
For the remaining characters, one option is to add `()`, reducing it to [JSFuck](https://jsfuck.com).
Another option is to add backtick and `=`, reducing it to [Turing complete javascript](https://codegolf.stackexchange.com/questions/110648/fewest-distinct-characters-for-turing-completeness/111002#comment270262_111002)
With the new [Pipeline operator](https://github.com/tc39/proposal-pipeline-operator), all you need is `|` (we already have `>`), but does this count as valid?
We can also try the afromentioned escape sequences.
## In conclusion, [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") in Javascript is very difficult.
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth), score 35, 180 bytes
```
6 54.@
7 55.@
8 312.@
9 313.@
0 !@
- 45.@
= 1341.@
y 121.@
u 1141.@
i 2153.@
o 111.@
p 112.@
[ 1115.@
] 2141.@
h 2152.@
j 2154.@
k 1131.@
l 1132.@
; 315.@
' 551.@
\ 4444.@
v 4214.@
b 354.@
n 1134.@
m 1133.@
^ 2142.@
& 2342.@
* 42.@
( 552.@
) 41.@
_ 351.@
+ 43.@
: 314.@
" 34.@
| 124.@
```
[Try the comprehensive test online!](https://tio.run/##VVFNb5tAEL3zK145dKFxcDC4TV0hpap6yL03TC3Ai0yL2dV@1LWS/HZ3Bqwq2cO@x8ybN7ODPruDGrPLxSpvWokCQojgI9Z58hB8wnpNcI8sXRF@JswI7/DuIbhFzrkCaZanRM5IV4weaToFeqzSNcsVRTigCdmm5G@urUgxSQ8s5dQvJtz5N2kyTg1MOPWFmnORoJk4sd0ip0PsD3LyIdIgm4pHrmFyZMIj/ORO7PIeq2wiHzBBRG6MMaZBduTAeIOcyzbUk31CTHbP9ERG2lBinel1FCdWD72LxHYUcdAZdYT1jTaqldaiP2plHIwfg@bspN055eqBVnwXdMpAeae9W6AfCehGaa92MThvOTb/lmoTgM6pdwcoLcdItGovk6FuzqYf3UEsIE4iRm3RbdAlJ9M7GU3G8VRppKW@NElUhsY353CBcKm0W/63WNIljTaS7sQ0LHjbI6wWaGvtvJG7eXRy/GG8fNNB0hvcnvLJXnJ9JLzrbu/FLNLsFHXi@18tWyf3GzzNVi/AM762ztcDxchlCjyV4ePYKmNIzAN9u9KqnKuKgpTVy9X89Y5vCgy0pusG5rav8vHl8g8)
Uses `.` (character output command) from the fairy.
## Explanation
A Labyrinth program is normally laid out on a 2D grid, but here each program is supposed to be a no-input single-char-output program, so they're best golfed as linear programs.
Now, except for `!@` which outputs `0`, every program constructs a single number, outputs it as a char, and halts.
### Secret 1
`0-9` commands in Labyrinth are not number literals. Instead, a digit command adds itself to the end of the top number on the stack (alternatively, multiply 10 and add the digit to the top). Since the top is implicitly zero at the start of the program, a sequence of digit commands constructs that exact multi-digit number.
### Secret 2
The real magic comes with the `.` command, which prints the top number **modulo 256** as char. So `312.` gives `8` (ascii 56) because `312 % 256 == 56`. It turns out that all charcodes can be converted to an equivalent number modulo 256 that has only 1-5 in its digits.
---
The answer in Hexagony, initially written in the similar vein, has been moved to [another answer of its own](https://codegolf.stackexchange.com/a/223520/78410).
[Answer]
# [Sleep](https://blog.ohai.ca/brainfuck.js/demo.html), all 35 chars, 5292 bytes
```
6 zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz z zzz zzz zzz zzz zz zz zz zz zzzz zzzzzzzz z zzz zzzzz z zzzzz zz zzz zzz zzz zzz zzzzz z zzz zzz zzz zzz zzz zzz zzzzz zzz zzz zzzzz z zzz zzz zzz zzz zzzzz z zzz zzz zzz zzz zzz zzz zzzzz zz zzz zzzzz
7 zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz z zzz zzz zzz zzz zz zz zz zz zzzz zzzzzzzz z zzz zzzzz z zzzzz zz zzz zzz zzz zzz zzzzz z zzz zzz zzz zzz zzz zzz zzzzz zzz zzz zzzzz z zzz zzz zzz zzz zzzzz z zzz zzz zzz zzz zzz zzz zzz zzzzz zz zzz zzzzz
8 zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz z zzz zzz zzz zzz zzz zz zz zz zz zzzz zzzzzzzz z zzz zzzzz z zzzzz zz zzz zzz zzz zzz zzzzz z zzz zzz zzz zzz zzz zzz zzzzz zzz zzz zzzzz z zzz zzz zzz zzz zzzzz z zzzz zzzz zzzz zzzz zzzzz zz zzz zzzzz
9 zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz z zzz zzz zzz zzz zzz zz zz zz zz zzzz zzzzzzzz z zzz zzzzz z zzzzz zz zzz zzz zzz zzz zzzzz z zzz zzz zzz zzz zzz zzz zzzzz zzz zzz zzzzz z zzz zzz zzz zzz zzzzz z zzzz zzzz zzzz zzzzz zz zzz zzzzz
0 zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz z zzz zzz zzz zzz zz zz zz zz zzzz zzzzzzzz z zzz zzzzz z zzzzz zz zzz zzz zzz zzz zzzzz z zzz zzz zzz zzz zzz zzz zzzzz zzz zzz zzzzz z zzz zzz zzz zzz zzzzz z zzzzz zz zzz zzzzz
- zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
= zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzzzz
y zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
u zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
i zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzz zzz zzz zzz zzzzz
o zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzzzz
p zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzz zzzzz
[ zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
] zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzz zzzzz
h zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
j zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzz zzzz zzzzz
k zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzz zzzzz
l zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
; zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz z zzz zzz zzz z zzz zzz zzz zzz zzz zz zz zz zz zzzz zzzzzzzz z zzz zzzzz z zzzzz zz zzz zzz zzz zzz zzzzz z zzz zzz zzz zzz zzz zzz zzzzz zzz zzz zzzzz z zzz zzz zzz zzz zzzzz zzzz zzzzz z zzzz zzzzz zz zzzzz zzz zzz zzzzz
' zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzz zzzzz
\ zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzzzz
v zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzzzz
b zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
n zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
m zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzzzz
^ zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzz zzzz zzzzz
& zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzz zzzzz
* zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
( zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzzz
) zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzzzz
_ zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzz zzzzz
+ zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzzzz
: zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzz zzzzz
" zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzzz zzzzz
| zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzzzzzz z zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zzz zz zzzz zzzzzzzz z zzz zzz zzz zzzzz
```
Each line is a program. First two letters are comments and should be removed from source code when you try to run it.
You just need to find out a brainfuck like language only use valid charset to get the power of turing complete...
I know I can golf more bytes. But I'm too lazy to working on it any more.
[Answer]
# [Deoxyribose](https://github.com/georgewatson/deoxyribose), all 35 characters in 753 bytes
```
6 ATGCATTCGCGTTAA
7 ATGCATTCTCGTTAA
8 ATGCATTGACGTTAA
9 ATGCATTGCCGTTAA
0 ATGCATTAACGTTAA
- ATGCATGTCCGTTAA
= ATGCATTTCCGTTAA
y ATGCATTTTCATTGGGGTCTTCGTTAA
u ATGCATTTTCATTCGGGTCTTCGTTAA
i ATGCATTTTCATGGGGGTCTTCGTTAA
o ATGCATTTTCATTAAGGTCTTCGTTAA
p ATGCATTTTCATTACGGTCTTCGTTAA
[ ATGCATTTTCATCTAGGTCTTCGTTAA
] ATGCATTTTCATCTGGGTCTTCGTTAA
h ATGCATTTTCATGGCGGTCTTCGTTAA
j ATGCATTTTCATGGTGGTCTTCGTTAA
k ATGCATTTTCATGTAGGTCTTCGTTAA
l ATGCATTTTCATGTCGGTCTTCGTTAA
; ATGCATTGTCGTTAA
' ATGCATGCTCGTTAA
\ ATGCATTTTCATCTCGGTCTTCGTTAA
v ATGCATTTTCATTCTGGTCTTCGTTAA
b ATGCATTTTCATGATGGTCTTCGTTAA
n ATGCATTTTCATGTTGGTCTTCGTTAA
m ATGCATTTTCATGTGGGTCTTCGTTAA
^ ATGCATTTTCATCTTGGTCTTCGTTAA
& ATGCATGCGCGTTAA
* ATGCATGGGCGTTAA
( ATGCATGGACGTTAA
) ATGCATGGCCGTTAA
_ ATGCATTTTCATGAAGGTCTTCGTTAA
+ ATGCATGGTCGTTAA
: ATGCATTGGCGTTAA
" ATGCATGAGCGTTAA
| ATGCATTTTCATTTCGGTCTTCGTTAA
```
Since A, C, G, and T were all allowed, how could I resist? I didn't need anything from the fairy.
* The `ATG` at the start of each line is the necessary start codon
* Then, this just pushes the codepoint of each character to the stack (one on each line) in the most inefficient possible way; each `CATxxx` pushes an integer up to 63, then each `GGTCTT` is an addition
* It then pops them straight out as Unicode characters (`CGT`)
* Each line ends with a stop codon (`TAA`), without which the program will just repeat forever
This could definitely get a lot shorter if I tried, but this isn't golf.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), score 35, ~~147~~ 139 bytes
I have asked the fairy to give me the character "9".
[Try all of these online!](https://tio.run/##JU6pEQMxDORbhckVoA8s84yAe0gDCTxgkuod6QL0zH7S/d2fczIcGYHLfRDEC@mBvIQ6xAQpKph7CTHfK4ZjLimLiCJZPK3ovaJwtpAtKDyItCpqAZ2xnrJuba2MizbqdLr2Hv@9I3va8wSHNGJ9Uf2cHw "Pyth – Try It Online")
[Verify!](https://tio.run/##ZVDbSsQwEH2frxijhS2KkNtDFpVK1L4JXkBZBKnddlu2pmsbWdefr5NuQcGHTCZn5pwzk83OV62Tw5C5flt0PZ4jY8xqBVZriJRCAwYWYJUGG3EjkEsOlgsOiU@5gWSValSQpJwonAuwhupGUtmnmnATGk1oIFwbsJKOEQQEjXQ8MoRAJY3ISCRrq0TI9T4PkuGW4xAGeUBkcBSK5j3tN03tZ@zFsRhg09WOHtES33a@6BlG2H@@z5rCzdYxlm2Ha6wdThvHxMiapt0Wy9e8yros99M/cCGVvnu6vn@8fLi6Sc8uFs/2gyg@65fl6vsrP0gOjyKGx8jMGJEBBPm98h@POYy2efWLEYR1GSDX@hH@N8Mcp01uqWMqsxOixMPwAw "Python 3 – Try It Online")
# Explanation
```
Code Char Expl
C54 # 6 # Character with value 54
C55 # 7 #
%44 9 # 8 # 44 % 9
9 # 9 #
Z # 0 # Initialized to 0 by default.
C45 # - # Character with value 45
C192 %131 # = # First take 192 % 131, then print character of that value
C121 # y # Character with value 121
@tG19 # u # G is initialized to "abcdefghijklmnopqrstuvwxyz", tail that and print char at index 19
@gG5 4 # i # g is used for inclusive slice to remove characters before index 5.
@G14 # o # ...
C112 # p # Character with value 112
C91 # [ # ...
C93 # ] # ...
@ttG5 # h # ...
@G9 # j # ...
@tG9 # k # ...
@G11 # l # ...
C59 # ; # ...
C39 # ' # ...
C92 # \ # ...
@G21 # v # ...
@G1 # b # ...
@G13 # n # ...
@G12 # m # ...
C94 # ^ # ...
C%93 55 # & # ...
C42 # * # ...
C%95 55 # ( # ...
C41 # ) # ...
C95 # _ # ...
C43 # + # ...
C%199 141 # : # ...
C34 # " # ...
C124 # | # ...
```
I used the similar trick for most character so I did not repeat the explanations.
[Answer]
# [Zsh](https://www.zsh.org/) + [xxd](https://github.com/vim/vim/blob/master/src/xxd/xxd.c), score 35, 478 bytes, fairy character `-`
```
tr AA 5-A<<<A
tr AAA 5-A<<<A
tr A-Z 5-A<<<D
tr @-Z 5-A<<<D
<<<$#
<<<-
tr R-Z 5-A<<<Z
tr 12 x-z<<<2
tr 12 t-z<<<2
tr 123 g-z<<<3
tr R-Z g-z<<<Z
tr Q-Z g-z<<<Z
tr 12 Z-a<<<2
tr 1-4 Z-a<<<4
tr 12 g-z<<<2
tr 1-4 g-z<<<4
tr 1-5 g-z<<<5
tr A-G g-z<<<F
tr A-Z 5-A<<<G
tr 123 %-1<<<3
tr 123 Z-a<<<3
tr 123 t-z<<<3
tr 12 a-z<<<2
tr Q-Z g-z<<<X
tr A-G g-z<<<G
tr 1-5 Z-a<<<5
tr 12 %-1<<<2
tr A-Z %-1<<<F
tr A-Z %-1<<<D
tr @-Z %-1<<<D
tr A-X Z-a<<<F
tr A-Z %-1<<<G
tr A-Z 4-A<<<G
tr 12 !-Z<<<2
xxd<<<r>f
tr 2 c<f>g
xxd -r<g
```
[Try it online!](https://tio.run/##XZAxD8IgEIV3fwVGHW8oLRsxkpgy69SwNZriXDs0/fMI3EHBBfLx@u696/b9OLfMTCkmQEkp1SFSjWAI7wFvBfrjfAonBOWZFROw4WyFzRMnWkpqmY3YJididD5q9FYDY7ZCR9iRaIu5XkREEQShwE00YV8vplOnCzSpU0DMybjsjX3suMfuhYc6R6cWOEmQFWN4KoHY15h/doEKBpr097FO2JX7sCOYmLOub3/P1ym8c/aS09WGRwaztM79AA "Zsh – Try It Online")
Each program is on a separate line, except the last one (`|`) which spans 3 lines. `-`, which the fairy has given us, is a pretty essential character for programming in shell languages :P
`tr` (for **tr**anslate characters) turns out to be extremely useful here - most of these characters are easily obtained using 5 minutes and an ASCII chart, by creating a range that surrounds the character we want and "indexing" into it by translating a character.
`<<<`, "here-string redirection", pipes a single word into the command (`command <<< word` \$ \equiv \$ `echo word | command`). This allows us to give input to `tr`, and if no command is given, it prints to stdout, so we can print literal strings like `-` too. Also, `$#` is the number of inputs, which is naturally 0 for a challenge like this.
Unfortunately, `|` can't be made with the `tr` technique because there are no accessible characters after it in ASCII to create a range around.
The available commands with our charset is [limited](https://tio.run/##qyrO@P8/p1hBpVqjWN9KXzPAMcSjVqFGIb0otUBBN6BCQSna0MjYxDQw3DUoxDHYxc09KsLZxq6wPLWoJLE4JS29qiJZ0UFZRTVWW@n/fwA), but I found [`xxd`](https://github.com/vim/vim/blob/master/src/xxd/xxd.c), which is a hexdump tool bundled with vim. The general idea is to create a hexdump of a single character that's *close* to `|`, translate some the hex characters to make them *actually* `|`, and un-hexdump (hexload?) it again.
```
# get a hexdump of `r` and write to the file `f`
xxd<<<r>f
# translate `2` to `c`, reading from the file `f` and writing to `g`
tr 2 c<f>g
# un-hexdump from the file `g`
xxd -r<g
```
In this case, we use `r` (0x72) and translate the `2` to a `c` for 0x7C (`|`). Since we can't pipe the commands into each other, we must redirect `>` to a file `f` and then read from it again with `<`, and do this again with another file `g`.
There may be a different approach to be taken here that uses more common commands and is shorter.
[Answer]
# [shortC](https://github.com/aaronryank/shortC), score 35, 184 bytes
```
AP54
AP55
AP312
AP313
AP2352
AP45
AP1341
AP121
AP1141
AP2153
AP111
AP112
AP1115
AP2141
AP2152
AP2154
AP1131
AP1132
AP315
AP551
AP4444
AP1142
AP354
AP1134
AP1133
AP2142
AP2342
AP42
AP552
AP41
AP351
AP43
AP314
AP34
AP124
```
Uses `P` from the fairy.
## How it works
`A` is converted to `int main(int argc, char **argv){`
`P`is converted to `putchar(` which outputs the character passed as argument after converting it to an unsigned char, which is equivalent to take the modulo 256.
E.g. `AP54` is converted to something equivalent to:
```
int main(int argc, char **argv){
putchar(54);
}
```
Generated with [this script](https://tio.run/##VU7ZTsJAFH3nK66CdoaGhEW2So0NLq9uCUYKpMvUjh06dWa0Yvj3OpVq4Lyde8@WbVTM015RZJ6UORch2MCoVMgYDEfjdsvefFCezRfxW8LOXcN1P/10vTxtIrwyreOtgWseYzwnpU8Sbet0e2f9@9n1w5PzeHVzO7l4eZ6@50QoT4bR6/dXcHRZb5xoX8QFUKAp/DVbNdAIdJAmiOJfmseUEdTBu2cJGgEqm6QSKMAYWlAtwGDvNuyJS2SCpnqYc2eACZXrQOAL4iX/F8IkOQwIwLSh2x8UxQ8 "Python 3 – Try It Online")
[Answer]
# [HTML (w3m)](http://w3m.sourceforge.net), 18 char
with an extra `&`
```
6
7
-
y
o
p
*
)
+
"
|
=
]
\
^
_
:
&
```
It is possible to output `6`, `7`, `-`, `y`, `o`, `p`, `*`, `)`, `+`, `"`, `|`, `=`, `]`, `\`, `^`, `_`, `:`, `&`.
[Answer]
# [Cubically](https://cubically.github.io/docs/index.html), all 35 characters in 166 bytes.
(162 bytes possible; see third-to-last paragraph.)
*Cubically is by PPCG user [MD XF](https://codegolf.stackexchange.com/users/61563/md-xf).*
Each line is a Cubically program; omit the first two characters. [Try it online!](https://tio.run/##Sy5NykxOzMmp/P/fzcH0////uiYA)
```
//accessible via 3x3x3 cube
- @5
' F@5
& FR@5
* R@5
( DDR@5
) DR@5
+ FRF3@5 // F3 is valid Cubically for FFF, saving 1 byte
" DRF@5
//requires 4x4x4 cube (invoke with flag -4)
6 DFD@4
7 FRR@5
8 DD@4
9 FD@4
0 @3
= FFRR@5
; DRDR@5
: FFD@4
//requires 5x5x5 cube (invoke with flag -5)
y DRER3@5
u DEDR@5
i FS@5
o SER@5
p FRD@5
[ SDRR@5
] FRR@5
h FES@5
j DRF@5
k DRDS@5
l FRF@5
\ FD@4
v DDR@5
b DRDR@5
n DSR@5
m DR3@5
^ FDF@5
_ E@4
| FEF3@5
```
## Explanation
Cubically manipulates values on the surface of a Rubik's cube. (There is a sixth, off-cube memory location accessible via the command `:` from the keyboard's right half; as the arithmetic operators are also blown away there's not much use for it. Fairy: take a break.)
Accessible to us on the left-hand side of the keyboard are commands to rotate the (R)ight face clockwise 90 degrees, the (D)ownward face, the (F)ront face, the middle layer inward from the bottom (E), and the middle layer inward from the front (S). And, crucially, the @ command which outputs the subsequent memory location as an ASCII character. Finally, the sums of values across each face occupy memory values 0-5. So a command of `@3` sums the values on face 3 and outputs the corresponding ASCII character.
A 3x3x3 cube can have maximum face-value 45, 4x4x4 maxes out at 80, and 5x5x5 at 125, so we'll need at least a 5x5x5 cube to reach required ASCII values. On a 5x5x5 `D@1` produces the same output as `DER@5` on a 3x3x3, so one could golf 2 bytes there by using a larger cube than *necessary* to produce `)`. But at that point it started to feel like I was golfing on invocation argument rather than on code, so I've restricted myself to the smallest cubes *necessary* to produce each character. By allowing a 5x5x5 cube even for smaller values, it's possible to golf 4 bytes: the two mentioned above and one each from `FRR@5`-4 --> `DE@1`-5 and `FRF3@5` --> `SER@2`-4 producing `7` and `+`, respectively.
(It is possible to find shorter programs on larger cubes than some of these presented--for example, on a 7x7x7 `@2` produces the same output as `DRDR@5` on a 5x5x5. But that's starting to feel like complete shenanigans.)
Most of these programs have a half-dozen or more siblings that produce the same output at the same length. Simply: `D` & `E` or `F` & `S` are often interchangeable, particularly for shorter programs.
[Answer]
# unary , 35 chars, 15297610066607123676 bytes
0 are used as extra char, also the only char used.
I will just give how many 0 are there
```
6 415301196285076
7 3322409570280596
8 24327480129166876
9 3040935016145860
0 415301196285660
- 2913391660822676
= 3217063028519132
y 402132826660380
u 25736500906368540
i 25736500906368540
o 3040935009656340
p 24327480077250708
[ 3040908012496020
] 194618112799745172
h 380116824301076
j 24327476755268756
k 194619814042150036
l 24327480077250780
; 194619841033334932
' 194619840618098836
\ 23163646650164164
v 3217062613296068
b 25840407707137756
n 380116876207044
m 3040935009656348
^ 1556944902397961364
& 24327480077262356
* 364173957602844
( 23307133286581980
) 2913391660822748
_ 12455559219183690900
+ 45521744700356
: 24327480129166868
" 206723264985755868
| 6308640661020
```
[Answer]
# Retina, 188 bytes, score 19
Fairy character: ```.
```
x
```
Counts number of `x`s in the input, which is `0` (1 byte)
```
xxxxx
```
Inserts 5 `x`s and counts the `6` boundaries (7 bytes).
```
xxxxxx
```
Inserts 6 `x`s and counts the `7` boundaries (8 bytes).
```
xxx
x
```
Inserts 3 `x`s, then inserts a further `x` at each boundary, then counts the resulting `8` boundaries (8 bytes).
```
xx
xx
```
Inserts two `x`s, then inserts another two `x`s at each of the three boundaries, then counts the resulting `9` boundaries (8 bytes).
```
1
T`d`Rw
```
In the Transliterate function, `d` represents `0123456789`, `E` represents `02468` and `Rw` represents `zyx`..`_`. After inserting a `1`, this therefore transliterates the second digit into the second last letter `y` (9 bytes).
```
5
T`d`Rw
```
Inserts a `5`, then transliterates the sixth digit into the sixth last letter `u` (9 bytes).
```
x
T`ddx`xxxRw
```
Inserts an `x`, then the `x` is the 21st source character so it translates into the 17th last letter `i` (14 bytes).
```
x
T`dtx`Rw
```
Inserts an `x`, then the `x` is the 12th source character so it translates into the 12th last letter `o` (11 bytes).
```
x
T`dx`Rw
```
Inserts an `x`, then the `x` is the 11th source character so it translates into the 11th last letter `p` (10 bytes).
```
x
T`ddx`xxRw
```
Inserts an `x`, then the `x` is the 21st source character so it translates into the 19th last letter `h` (13 bytes).
```
x
T`dEtx`Rw
```
Inserts an `x`, then the `x` is the 17nd source character so it translates into the 17th last letter `j` (12 bytes).
`k`:
```
x
T`dEx`Rw
```
Inserts an `x`, then the `x` is the 16th source character so it translates into the 16th last letter `k` (11 bytes).
```
x
T`dEx`xRw
```
Inserts an `x`, then the `x` is the 16th source character so it translates into the 15th last letter `l` (12 bytes).
```
4
T`d`Rw
```
Inserts a `4`, then transliterates the fifth digit into the fifth last letter `v` (9 bytes).
```
x
T`ddEx`xRw
```
Inserts an `x`, then the `x` is the 26th source character so it translates into the 25th last letter `b` (13 bytes).
```
x
T`dttx`Rw
```
Inserts an `x`, then the `x` is the 13th source character so it translates into the 13th last letter `n` (12 bytes).
```
x
T`dtttx`Rw
```
Inserts an `x`, then the `x` is the 14th source character so it translates into the 14th last letter `m` (13 bytes).
```
x
T`x`w
```
Inserts an `x` and then transliterates it to an `_`. (8 bytes)
No other characters are possible, because the only source of arbitrary printable ASCII is via the `p` transliteration builtin.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 characters, 188 bytes
```
3!
34DS
44DS
45DS
45Ọ
212%151Ọ
121Ọ
3r15SỌ
14RSỌ
111Ọ
112Ọ
13RSỌ
31x3SỌ
104Ọ
53x2SỌ
54x2SCAỌ
54x2SỌ
12x5SCAỌ
13x3SỌ
213%121Ọ
241%123Ọ
33x3SCAỌ
111CAỌ
111CACAỌ
215%121Ọ
13x3SCAỌ
42Ọ
41CAỌ
41Ọ
24x4SCAỌ
43Ọ
211%153Ọ
34Ọ
124Ọ
```
[Try it online!](https://tio.run/##TY6xcUJBDETz34UDcnYl2WYcMVCBqYGEIXL03YO7cBlk7oRKPlrpMAQr6U77JJ2O5/P3stjLZL4/TF4hMmS8Xn4mgisEVIKV7AtxqLd/dka3wUrWv4bZur12pbCZ9Q7PYrf9L3v0HOMPNjjCVmMlHVlajVV7OIGnoksi7hAeTq/LfNh9zJz93rZGc0n0Eu@jlBb8/X4wZSlPReo19ZZ6T21SWCvICVkhL2SG3JAd8kMARFAEa7YIiqAIiqAIiqAIijARJsLqHBEmwpJYbg "Jelly – Try It Online")
Using `Ọ` as the extra character. Each program is on a separate line. A lot of these are kind of last-resort and I'll try to golf them.
## Explanation
* `!` = factorial
* `D` = decimal digits
* `S` = sum
* `Ọ` = convert to character
* `%` = modulo
* `r` = range from m to n
* `R` = range from 1 to n
* `x` = repeat
* `C` = 1 - n
* `A` = absolute value
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), all 35 characters, 243 bytes
```
54C
55C
55 1+C
55 2+C
45 3+C
45C
51 5d+C
121C
111 3d+C
5d2e5+C
111C
112C
5 4+2e5d+C
52 41+C
5d2e4+C
5d2e3d+C
5d2e3d+1+C
5d2e4d+C
54 5+C
35 4+C
44 2+dC
115 3+C
45 4+dC
5dD2e+C
5d2e4 5++C
45 1+d2+C
35 3+C
42C
5dddC
41C
45d5+C
43C
55 3+C
34C
124C
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=54C%0A55C%0A55%201%2BC%0A55%202%2BC%0A45%203%2BC%0A45C%0A51%205d%2BC%0A121C%0A111%203d%2BC%0A5d2e5%2BC%0A111C%0A112C%0A5%204%2B2e5d%2BC%0A52%2041%2BC%0A5d2e4%2BC%0A5d2e3d%2BC%0A5d2e3d%2B1%2BC%0A5d2e4d%2BC%0A54%205%2BC%0A35%204%2BC%0A44%202%2BdC%0A115%203%2BC%0A45%204%2BdC%0A5dD2e%2BC%0A5d2e4%205%2B%2BC%0A45%201%2Bd2%2BC%0A35%203%2BC%0A42C%0A5dddC%0A41C%0A45d5%2BC%0A43C%0A55%203%2BC%0A34C%0A124C&inputs=&header=&footer=)
The extra character is `+`
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), score 35, ~~180~~ 152 bytes
This is split out of my own [Labyrinth answer](https://codegolf.stackexchange.com/a/223447/78410), because it now adds some more real tricks over the previous, and therefore the resulting code is sufficiently different. Refer to that answer for **Secret 1** and **Secret 2**.
```
6 54;@
7 55;@
8 R4;@
9 R5;@
0 !@
- 45;@
= R53;@
y r5;@
u r1;@
i W3;@
o q5;@
p 112;@
[ Z51;@
] Z53;@
h W2;@
j W4;@
k W5;@
l q2;@
; 315;@
' 551;@
\ Z52;@
v r2;@
b 354;@
n q4;@
m q3;@
^ t14;@
& W42;@
* 42;@
( 552;@
) 41;@
_ 351;@
+ 43;@
: 314;@
" 34;@
| 124;@
```
[Try the comprehensive test online!](https://tio.run/##VVDBbtpAEL37K1596NoNMXGANiVCSlX1kGtUCalAETbr4ha8y@xuCUry7XTGplKyh307b@a9mR179BvTDE4nZwKVGhMopaKPGA1v76JPGI0YbvAg0Wc8SHSFd3fRJYbynjA1YDyCJAygnKHGVEiDvZAWeX7NOMOPkWQXjJLeYCr0b0zF/A@mUrzFXshbDHIJFQ8gmvmcRZL4CxIoMGgHbLAX2GEvjj/hcwnfs6VUfUALCZsIphiK15K1ghcYimjMrUQUYyDwjPxakLeQOU@1TdLM2W3tEzVvVBpVZHZwobBkSu0c6p015EGhiYqj127pjV9teY1XUWUIJngbfA91w8A3Zu5sl0LyTrhu9YtxBD6H2m9grG4SVZq1zjb6cfXLNEfVgzqoFCuHaowqO1DtddL6pq2QtOO2PEgyiykUx7iHuG@s7/936NeN12RJ851RIfk3HeJFD@XK@kB62c3Nft8p6Df@mj/g15zP1lrkiQq@urxRXZElbpJU6tuj1aXX6zGeOqsX4BlfSh9WW@bYpSWeZvF9UxoiLpZ5vp6fi1mnmky4cvFyNn@94IsJtryj8/@7tq/y6en0Dw)
The exact same construction as the Labyrinth answer also works with Hexagony, because the two languages share the digit commands and the character output behavior. The output command is `;` (unlocked with fairy). But Hexagony has ~~one more quirk~~ **two** more quirks. One makes it so that the (almost) same code only works by coincidence:
### Secret 3
A Hexagony program is laid out on the smallest hexagonal grid that fits the entire source code before running. For the programs of size 2 to 6, the hexagon side length is 2:
```
A B
C D E
F G
```
The IP starts at A, facing right. When it exits through B, it re-enters through C. When it exits through E, the current value is checked, and fortunately it is always positive (since the constant set up is still there), so it re-enters through F. Therefore, the IP flows through ABCDEFG, exactly in the linear order.
The other actually contributes to golfing the code further:
### Secret 4
In addition to the digit commands, the uppercase/lowercase letters in Hexagony are also valid commands, which simply set the current memory cell to its own ASCII value. And we have half of those letters available, and this leads to a new opportunity in golfing "certain ascii modulo 256"!
Since the existing literals are at most 4 bytes long, we only need to check the combinations of `<letter><digit>` and `<letter><digit><digit>`. I wrote a quick [brute-forcer](https://tio.run/##hY9dS8MwFIbv@yteBG2yVVk6rDrZhfh1rRMUrUpN1zVzS2KaTjf877XNRFSmuwgH8pzD@z56bnMlu1UlpC4t@vAvrk8vr44GJ2fntzfHL69DY5MizUaLN@57qrSfW9He/kFnuz8vhdJ39/n4eXIY@3E8e5LTh60WoY/t3sa772XKQEBITBNNlEkDuBza84CGpQ0ziRwNCQsi9w3wOoAItMA6aCOl2ES4GzkkMvDcEE6bu2Wb5Q2gjZCWFNYQQXcm47KwpEsDty7qWUc3jP9mnNL1Ldmqmo6Eq8gPBefAvmzC7zr/Cq1XYvUL//aqqg8) for it, and it turns out that we can save whopping 28 bytes in total.
[Answer]
# [Husk](https://github.com/barbuz/Husk), score 35, 198 bytes
```
6 D3
7 >1D4
8 D4
9 >1D5
0 Dc1
- ;c45
= ;c>1D31
y ;c121
u ;c<121 4
i ;c>1D53
o ;c111
p ;c112
[ ;c>11D51
] ;c>11D52
h ;cD52
j ;cD53
k ;c>1D54
l ;cD54
; ;c>3D31
' ttsc32
\ ;cDD23
v ;c<121 3
b ;c>4D51
n ;cD55
m ;c>1D55
^ ;c<D51D4
& ;c<41 3
* ;c42
( ;c<41 1
) ;c41
_ ;c>11D53
+ ;c43
: ;c>4D31
" ;c34
| ;c124
```
The additional character is `;`; it is equivalent to `R1`. `<` and `>` yield the absolute difference between their arguments if the comparison is successful. The only real nontrivial programs here are `Dc1` and `ttsc32`.
[Answer]
# [Numberwang](https://esolangs.org/wiki/Numberwang_(brainfuck_derivative)), score 35, 1169 bytes
```
6 65656565656565656565643
7 656565656565656565656433
8 6565656565656565656565613
9 6565656565656565656565623
0 656565656565656565633
- 6565656565656565656333
= 656565656565656565656565613
y 656565656565656565656565656565656565656565656565613
u 6565656565656565656565656565656565656565656565623
i 65656565656565656565656565656565656565656565656233
o 65656565656565656565656565656565656565656565613
p 65656565656565656565656565656565656565656565623
[ 656565656565656565656565656565656565613
] 656565656565656565656565656565656565633
h 6565656565656565656565656565656565656565643
j 656565656565656565656565656565656565656565613
k 656565656565656565656565656565656565656565623
l 656565656565656565656565656565656565656565633
; 6565656565656565656565643
' 65656565656565643
\ 656565656565656565656565656565656565623
v 6565656565656565656565656565656565656565656565633
b 65656565656565656565656565656565656565633
n 656565656565656565656565656565656565656333
m 656565656565656565656565656565656565656565643
^ 656565656565656565656565656565656565643
& 65656565656565633
* 6565656565656565623
( 65656565656565656233
) 6565656565656565613
_ 65656565656565656133
+ 6565656565656565633
: 6565656565656565656565633
" 656565656565643
| 656565656565656565656565656565656565656565656565643
```
Numberwang is a language based on Brainf\*\*k where all commands consist of single numbers.
From the original character set we could use:
`1` - decrement the pointer (to point to the next cell to the left)
`2` - decrement (decrease by one) the byte at the pointer
`3` - output the value of the byte at the pointer
~~`4` - start of loop, needs corresponding 7. Skips loop if active pointer equals 0~~ Useless without a 7
`5` - directly decrements the current pointer with the following number
Using only the allowed characters we could get a [2572 bytes solution](https://tio.run/##tZNJCgJRDET3OUXhwhFBjO2IJ3HCBnHsrwitCN79@9UbdCXZ5xFeVUJZ5Lv7cxv2MQ6RWU9fZQQH6NgBqjKxpg5UevZSsyzd2vXgftXOncAqLy@ySonqCR1BGruCNXMDU7EFs62ygkUfD2CLdwLdsDO4Z72AkzCD/T82XL7mz17y7GTtgerGcvDVC6AkFOAkrmERRd0r5iSo7cNO0Tfh1s2WG1plA4MDO/DKawp7Zs2rXz8Xb1TcjPED "Numberwang – Try It Online") by keeping decrementing by 5 with `55` and then subtracting the remainder of the division \$(256-charcode)/5\$.
But luckily the fairy comes in and gives us:
`6` - directly increments the current pointer with the following number
With this new command and the fact that the password is composed of only ASCII characters (<127) we can add up from 0 (which is clearly better then subtracting from 256) in steps of 5 with `65`, and then add the remainder of \$(charcode)/5\$.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), score 35, 498 bytes
Uses only `\n`, `\t`, and , which are all allowed:
```
6
```
```
7
```
```
8
```
```
9
```
```
0
```
```
-
```
```
=
```
```
y
```
```
u
```
```
i
```
```
o
```
```
p
```
```
[
```
```
]
```
```
h
```
```
j
```
```
k
```
```
l
```
```
;
```
```
'
```
```
\
```
```
v
```
```
b
```
```
n
```
```
m
```
```
^
```
```
&
```
```
*
```
```
(
```
```
)
```
```
_
```
```
+
```
```
:
```
```
"
```
```
|
```
## Explanation
* For `67890`, the number is pushed to the stack (`SS` *number* `N`) and printed as a number (`TNST`).
* For everything else, the ASCII code of the character is pushed to the stack (`SS` *number* `N`) and printed as a character (`TNSS`).
[Try it all online!](https://tio.run/##XVBBCoAwDDtnr8jXRAZ6ExR8fh2rdE0Pg6ZNk3TvcT79vra9m5EE2NCIWSLK8VId/dUbe7NLX0zIoWLqnGU@V4T/ezG8kKF4R7CAKFDIyGQVJqpNoWZdFhsUSJVKU4qS5tVj5J9cBrIIyZctJN06xewD "Whitespace – Try It Online")
[Answer]
## [Groovy](http://groovy-lang.org), score 35/35, ~~397~~ 380 bytes
Fairy character: "h". Each character is a one-statement program.
```
/* 6 */ 3<<1
/* 7 */ 22%15
/* 8 */ 1<<3
/* 9 */ 24%15
/* 0 */ 1%1
/* - */ 45as char
/* = */ 122>>1as char
/* y */ 121as char
/* u */ 234>>1as char
/* i */ 211>>1as char
/* o */ 111as char
/* p */ 112as char
/* [ */ 212%121as char
/* ] */ 214%121as char
/* h */ 13<<3as char
/* j */ 53<<1as char
/* k */ 214>>1as char
/* l */ 54<<1as char
/* ; */ 211%152as char
/* ' */ 121%41as char
/* \ */ 23<<2as char
/* v */ 241%123as char
/* b */ 211%113as char
/* n */ 55<<1as char
/* m */ 221%112as char
/* ^ */ 215%121as char
/* & */ 122%42as char
/* * */ 42as char
/* ( */ 5<<3as char
/* ) */ 41as char
/* _ */ 321%113as char
/* + */ 43as char
/* : */ 232>>2as char
/* " */ 34as char
/* | */ 124as char
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score 35, ~~162~~ 149 bytes
Uses the characters `!12345<>RTxç`.
```
6 3!
7 3!>
8 4x
9 T<
0 1<
- 45ç
= 15>Rç
y 121ç
u 115>>ç
i 52x>ç
o 111ç
p 112ç
[ 45x>ç
] 45>x>ç
h 52xç
j 53xç
k 54x<ç
l 54xç
; 31<x<ç
' Txx<ç
\ 23xxç
v 5!<<ç
b 25x<xç
n 55xç
m 54x>ç
^ 24x<xç
& Tx<xç
* 42ç
( Txxç
) 41ç
_ 24xx<ç
+ 43ç
: 15x<xç
" 34ç
| 124ç
```
[Try it online!](https://tio.run/##NU7NSsQwGLx/T5HWg5eytfm5lFJZWQ8KIkj1Uorb7YZtwG2liZKCd59EFH2IPeTBaprs5jCTmW@@j@llvRF8mj5WtyvzK3fhGSov2PIqua4iJJt@4IiwCJkD2oyKS4BHySVSLUdNWw91o/gg0doc1gsIo/fx/NJ8PYtx8TTKENln98whjMzfiM3PynyuvX0npBTdLj3NKwihLIYRCYX67kV0PKjK4ua@AnCUIji1SlGr1KtM43gnVPu2WTT9Pl5uB1F32z3vYh@zZaaJBECCHKiGIoMkA8rMNyQsf5gJJzNalVtmWOdOehNbpMxZlOX6mJiROKQ682SRJJlThXaEiXaRIHOK6cxJdtybT2HqzcITxX57/iZ@7C5R4tr6EKGus8V/)
`&` can be printed with [`CCxç`](https://tio.run/##yy9OTMpM/f/f2bni8PL//wE), but this doesn't work with my test suite :/.
[Answer]
# Fission 2, score 35, 371 bytes
```
6 R'5@$@!A
7 R'5@$$@!A
8 R'5@$$$@!A
9 R'5@$$$$@!A
0 R'%@$$$$$$$$$$$@!A
- R'%@$$$$$$$$@!A
= R'<@$@!A
y Rx@$@!A
u Rt@$@!A
i Rg@$$@!A
o Rg@$$$$$$$$@!A
p Rg@$$$$$$$$$@!A
[ R'Z@$@!A
] R'Z@$$$@!A
h Rg@$@!A
j Rg@$$$@!A
k Rg@$$$$@!A
l Rg@$$$$$@!A
; R'5@$$$$$$@!A
' R'%@$$@!A
\ R'Z@$$@!A
v Rt@$$@!A
b Ra@$@!A
n Rg@$$$$$$$@!A
m Rg@$$$$$$@!A
^ R'Z@$$$$@!A
& R'%@$@!A
* R'%@$$$$$@!A
( R'%@$$$@!A
) R'%@$$$$@!A
\_ R'Z@$$$$$@!A
+ R'%@$$$$$$@!A
: R'5@$$$$$@!A
\ R'Z@$$@!A
" R'!@$@!A
| R'z@$$@!A
```
Thank god there was some letter in there that could destroy atoms.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 35 characters (18 complete), ??? bytes
The only interesting ones are:
```
6 3!
7 3!FD
8 3!F
9 3!FDFDDDD
0 1D
- 4f$F
```
The others are just "make some number with `F` and `D` and then change it to a char with `c`".
```
= 3!FDFDDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
y 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDc
u 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDc
i 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
o 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
p 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
[ 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
] 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
h 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
j 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
k 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
l 3!FDFDFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDc
```
[Answer]
# [asdf](https://esolangs.org/wiki/Asdf), 35 chars, 1420 bytes
```
6 asaasaaaasssasaaaasssasaasssasaaaasssasaa
7 asaasaaaasssasaaaasssasaasssasaaaaaa
8 asaasaaaasssasaaaaaasssasaaaaaa
9 asaasaaaasssasaaaaaasssasaaaasssasaa
0 asaasaaaasssasaaaasssasaaaaaaaa
- asaasaaaasssasaasssasaasssasaaaasssasaasssasaa
= asaasaaaasssasaaaaaaaasssasaasssasaa
y asaasaasssasaaaaaaaasssasaaaasssasaa
u asaasaasssasaaaaaasssasaasssasaasssasaasssasaa
i asaasaasssasaaaasssasaasssasaasssasaaaasssasaa
o asaasaasssasaaaasssasaasssasaaaaaaaa
p asaasaasssasaaaaaasssasaaaaaaaa
[ asaasaasssasaasssasaasssasaaaasssasaasssasaaaa
] asaasaasssasaasssasaasssasaaaaaasssasaasssasaa
h asaasaasssasaaaasssasaasssasaasssasaaaaaa
j asaasaasssasaaaasssasaasssasaasssasaasssasaasssasaa
k asaasaasssasaaaasssasaasssasaasssasaasssasaaaa
l asaasaasssasaaaasssasaasssasaaaasssasaaaa
; asaasaaaasssasaaaaaasssasaasssasaaaa
' asaasaaaasssasaasssasaaaasssasaaaaaa
\ asaasaasssasaasssasaasssasaaaaaasssasaaaa
v asaasaasssasaaaaaasssasaasssasaaaasssasaa
b asaasaasssasaaaasssasaaaaaasssasaasssasaa
n asaasaasssasaaaasssasaasssasaaaaaasssasaa
m asaasaasssasaaaasssasaasssasaaaasssasaasssasaa
^ asaasaasssasaasssasaasssasaaaaaaaasssasaa
& asaasaaaasssasaasssasaaaasssasaaaasssasaa
* asaasaaaasssasaasssasaasssasaasssasaasssasaasssasaa
( asaasaaaasssasaasssasaasssasaasssasaaaaaa
) asaasaaaasssasaasssasaasssasaasssasaaaasssasaa
_ asaasaasssasaasssasaasssasaaaaaaaaaa
+ asaasaaaasssasaasssasaasssasaasssasaasssasaaaa
: asaasaaaasssasaaaaaasssasaasssasaasssasaa
" asaasaaaasssasaasssasaaaaaasssasaasssasaa
| asaasaasssasaaaaaaaaaasssasaaaa
```
Accidentally find out some working languages... I have no idea what it is. Anyway, one program per each line. 2 chars at beginning of each line is not a part of the program.
] |
[Question]
[
**This question already has answers here**:
[Making Squared Words](/questions/133650/making-squared-words)
(32 answers)
Closed 5 years ago.
Sometimes when you're lying in bed and reading a message, your phone screen will pop into landscape mode right in the middle of a sentence. Only being able to read left to right, you find yourself incapacitated, unable to process the text in front of you.
To ensure that this won't happen again, you decide to make every message readable from any angle, whether your phone screen is rotated or mirrored. To make this happen, each message is printed as a square, with each side of the square containing the message, either in the original order or in reverse.
* For backwards compatibility, the top side of the square should be the original message.
* To make each message square as compact as possible, the first and last character of the message should be a part of two sides of the square. This means that the top side reads normally, the bottom side is in reverse, the left side reads top-bottom, and the right side reads bottom-top.
## Input
A single string, with 2 or more characters. You should not assume that the string only contains alphanumerical characters or similar.
## Output
The Squarification™ of the string. It is permissible to leave some whitespace at the end of each line, and a single newline at the end of the output.
## Examples
```
Input: 'ab'
ab
ba
Input: 'abc'
abc
b b
cba
Input: 'Hello, world!'
Hello, world!
e d
l l
l r
o o
, w
w ,
o o
r l
l l
d e
!dlrow ,olleH
```
This challenge looks like [A cube of text](https://codegolf.stackexchange.com/questions/92410/a-cube-of-text-%DD%80), but I'm hoping that it's different enough that there will be some clever answers.
As this is code-golf, get ready to trim some bytes!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 4 bytes
```
S‖O^
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMzr6C0JLgEyE7X0NS05gpKTctJTS7xL0stykks0LCK07T@/98jNScnX0chPL8oJ0WR679uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input the string and implicitly print it
‖ Reflect...
O ... overlapping the first and last character...
^ ... in the ↙↘ directions (^ is shorthand for ↙↘).
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
Saved 1 byte thanks to *Kevin Cruijssen*
```
g4иsûûŽ9¦SΛ
```
[Try it online!](https://tio.run/##ASgA1/9vc2FiaWX//2c00Lhzw7vDu8W9OcKmU86b//9IZWxsbywgd29ybGQh "05AB1E – Try It Online")
**Explanation**
```
g # length of input
4и # quadruplicate in a list
# these are the string lengths we'll print
s # push input
ûû # palendromize twice
# this is the string we'll print
Ž9¦S # push [2,4,6,0]
# these are the directions we'll print
Λ # paint on the canvas
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~80~~ ~~76~~ ~~71~~ ~~70~~ 69 bytes
```
lambda s:[s]+map((' '*len(s[2:])).join,zip(s,s[:0:-1]))[1:]+[s[::-1]]
```
[Try it online!](https://tio.run/##TcqxDsIgEIDh3ac4pwOLxna8xN13QAZqS8RcgUAToy@PNC6O358/vddHDEN1l1tlu4yThUK6mG6xSQgEPPAcRNEDGSlPz@iD@vgkiiqaznTsW9U9mU43bzQ1ZR9WcALtiHL3p3ujixkYfNjKdWaOCl4x87RHSb@V6xc "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), 70 bytes
```
lambda s:[s,*map((' '*len(s[2:])).join,zip(s[1:],s[-2:0:-1])),s[::-1]]
```
[Try it online!](https://tio.run/##TYpBDsIgEEX3nmJcwTTU2LqbpHvvgCyobSNmCgSaGL080rhx9997P763R/CXsgy3wnYdJwuZdFbNaqOUAkTDs5dZ92QQT8/gvPq4WEVHRmXd9nSmtqutAu3LlJic3@QihR0F4uEP7zsvIQGD81DVdWYOCl4h8XQUSL8vY/kC "Python 3 – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 6 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
⤢n:±⇵n
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyOTIyJXVGRjRFJXVGRjFBJUIxJXUyMUY1JXVGRjRF,i=JTIySGVsbG8lMkMlMjBXb3JsZCUyMSUyMg__,v=8)
Explanation:
```
⤢ transpose the input
n and overlap that over the input
: duplicate that
±⇵ reverse it vertically & horizontally
n and overlap over the old version
```
[Answer]
# Python 3, ~~78~~ 76 Bytes
-2 bytes thanks to maxb!
```
lambda x:[x]+[x[i]+" "*(len(x)-2)+x[~i]for i in range(1,len(x)-1)]+[x[::-1]]
```
[Try it Online!](https://tio.run/##LcuxCsIwEADQXzlvujOtEN0C7v6BQ5qh0kRP4qWEDnHx1yOI8@Ot7@1R9NTTeep5ft2WGZrzLRjfvASDgHvKUanxeGTT/EdCKhUERKHOeo9kh79b/i3nRhtCX6voBoST4uFZRCkRXmLOZYBrqXnZITP3Lw)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
YTO6Lt&(
```
[Try it online!](https://tio.run/##y00syfn/PzLE38ynRE3j/391j9ScnHwdhfL8opwURXUA "MATL – Try It Online")
### Explanation
Consider input `'abcd'` as an example. Stack is shown bottom to top.
```
YT % Implicit input: string. Create Toeplitz matrix of chars
% STACK: ['abcd';
'babc';
'cbab';
'dcba']
O % Push 0
% STACK: ['abcd';
'babc';
'cbab';
'dcba']
0
6L % Push [2, -1+1j]. Used as an index, this means 2:end
% STACK: ['abcd';
'babc';
'cbab';
'dcba']
0,
[2, -1+1j]
t % Duplicate
% STACK: ['abcd';
'babc';
'cbab';
'dcba']
0,
[2, -1+1j],
[2, -1+1j]
&( % Write 0 into the internal entries of the char matrix.
% STACK: ['abcd';
'b c';
'c b';
'dcba']
% Implicitly display. Char 0 is shown as a space
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
¦¨s¨š.BsRøJIRª
```
[Try it online!](https://tio.run/##ASwA0/9vc2FiaWX//8KmwqhzwqjFoS5Cc1LDuErCuyxSPf//SGVsbG8sIHdvcmxkIQ "05AB1E – Try It Online")
Outputs as a list of lines, but the TIO link uses the old version which printed instead – [Try an alternative online!](https://tio.run/##AS0A0v9vc2FiaWX//8KmwqhzwqjFoS5Cc1LDuEpJUsKqwrv//0hlbGxvLCB3b3JsZCE "05AB1E – Try It Online"). Thought I'd be nice to show how awesome the canvas is by comparing that approach to others that don't use it. See Emigna's answer for a canvas version, then compare it to mine :)
### How?
```
¦¨s¨š.BsRøJ»,R= Full program. Accepts a string from STDIN. | Example: "abcd"
¦¨ Tail and pop. | STACK: ["bc"]
s¨ Swap and pop. | STACK: ["bc", "abc"]
š Prepend a to b as a list. | STACK: [["abc", "b", "c"]]
.B Squarify. | STACK: [["abc", "b ", "c "]]
sRøJ Interleave with the reversed input. | STACK: [["abcd", "b c", "c d"]].
», Join by newlines, pop and print. | STACK: [] (the above is removed after being printed)
R= Print the reversed input (taken implicitly due to the empty stack).
```
The only thing which is different in the 14-byter is that the reversed input is appended to the list rather than printed.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-R`, ~~22~~ 15 bytes
```
U+ÕÅ+UÔÅ Õ·hJUw
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=VSvVxStV1MUg1bdoSlV3&input=IkhlbGxvLCB3b3JsZCEiCgotUg== "Japt – Try It Online")
[Answer]
# Pyth, ~~16~~ 15 bytes
```
LXXb0Qt0_Qy.tym
```
Try it online [here](https://pyth.herokuapp.com/?code=LXXb0Qt0_Qy.tym&input=%22abc%22&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=LXXb0Qt0_Qjy.tym&test_suite=1&test_suite_input=%22ab%22%0A%22abc%22%0A%22Hello%2C%20world%21%22&debug=0) (test suite joins output on newlines for easier verification, as per OP request).
```
LXXb0Qt0_Qy.tymdQ Implicit: Q=eval(input())
Trailing d,Q inferred
L Define a function, y(b), as:
Xb Replace in b...
0 ... at position 0...
Q ... the input string
X Replace in the above...
t0 ... at position -1 (decrement 0)
_Q ... the reversed input string
mdQ Split the input string into array of characters
(The exact contents of the array don't matter, as long as the array
has the same length as the input string and the elements are
of length < 2)
y Apply the function y (defined above) to the array
(For Q="abc", yields ["abc", "b", "cba"]
.t Transpose, padding with spaces
(For Q="abc", yields ["abc", "b b", "c a"]
y Apply y to the above
```
*Edit: OP clarified that a list of lines is acceptable as output, so removed `j` to join on newlines - previous version `LXXb0Qt0_Qjy.tym`*
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~55~~ 51 bytes
```
{$_,|.comb[1..*-2].&{(@_ X~' 'x@_)Z~[R,] @_},.flip}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXqdGLzk/NynaUE9PS9coVk@tWsMhXiGiTl1BvcIhXjOqLjpIJ1bBIb5WRy8tJ7Og9n@ahlJikpKmnZ1ecWKlNReYm4zC90jNycnXUSjPL8pJUYTL/AcA "Perl 6 – Try It Online")
Returns a list of lines.
### Explanation:
```
{ } # Anonymous code block
$_, # The given string as the first line
.comb[1..*-2] # The string as a list of chars without the first or last char
.&{ } # Passed to a function
(@_ X~' 'x@_) # Each character padded with space
Z~[R,] @_ # And zipped with the reverse
| # Flattened
,.flip # And the reverse of the string
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~93~~ ~~91~~ ~~87~~ ~~80~~ ~~78~~ ~~77~~ ~~76~~ 74 bytes
```
x=>[...x].map(c=>(w+=z=x[--j])[1]?j?c.padEnd(l-1)+z:w:x,w="",l=j=x.length)
```
[Try it online!](https://tio.run/##BcFBCsMgEADAr7SelOhCrimbnAr9g3gQNWllq5KEKvm8nYn2Zw@3f8qpUvahr9gbzhoAmoGvLdzhzOuAFzatVDRCj2aJi4Ni/TN5TmoUwzXVqcmKjEnCiA0opO18i/5wOR2ZAlDe@MrZKxBleat5J39nQvQ/ "JavaScript (Node.js) – Try It Online")
Returns list of lines.
## Explanation
```
x => // Main function
[...x].map(c => // For each character in the input:
(w += z = x[--j])[1] // Check whether this is not the first row (by producing w, the
// reverse of x, character by character, and check if len(w) > 1)
? // If so:
j // Check if this is not the last row
? c.padEnd(l - 1) + z // If so: return the needed row
: w // If not (i.e. last row): return w, the reverse of x
: x, // If not (i.e. first row): return x
w = "", // Stores the reverse of w
l = j = x.length // A variable that stores the length of the string, and a counter
) // Golfing from 78 onwards is tough work.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~80~~ ~~76~~ ~~72~~ 71 bytes
* Saved ~~four~~ ~~eight~~ nine bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni).
```
f s=s:m[c:m(' '<$s)++[d]|(c,d)<-zip s$r s]++[r s];m=init.tail;r=reverse
```
[Try it online!](https://tio.run/##FY6xDsIgFAB/BUmTQqh8QFt2B50ckQGBRiLQhkc1Mf474nKX3HQPDU8XQq0LAgFjlGaMpEf93AFlTFr1JWawdD5@/IagywhUy39NUfjkCy/ahymL7F4ug6tR@ySi3i5k28u15HPihDF8S5jyPQWfHPCFSqzveGgwjac2sA7oveZgD1jVHw "Haskell – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~20 19~~ 15 bytes
```
p╡╞▒x_xh *+m+nx
```
[Try it online!](https://tio.run/##y00syUjPz0n7/7/g0dSFj6bOezRtUkV8RYaClnaudl7F//9KiUnJKalpSgA "MathGolf – Try It Online")
Edited to an improved version of maxb's original 22 byte solution. Zip operator is sadly lacking though the `m`ap operator has a partial implementation.
### Explanation:
```
p Print the original string ["abcd"]
╡╞ Remove from the start and end of the string ["bc"]
▒ Convert to a list of chars [["b","c"]]
x_x Reverse, dupe and reverse back again [["c","b"],["b","c"]]
h Get length of array without popping [["c","b"],["b","c"],2]
* Create a string with that many spaces [["c","b"],["b","c"]," "]
+ Map adding it to every character [["c","b"],["b ","c "]]
m+ Zip add each character of the reversed string [["b c","c b"]]
n Join with newlines and print
x Reverse the original string and implicitly output
```
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 48 bytes
```
00000000: 1525 13cd 0380 3806 ff4d 2377 18f5 3e0a .%....8..M#w..>.
00000010: ff7b b928 1113 1aff 4105 2805 3e20 ff18 .{.(....A.(.> ..
00000020: f82b 7eff 18e8 131a b720 0176 ff1b 18f7 .+~...... .v....
```
[Try it online!](https://tio.run/##Nc5NagMxDAXgfU/xoBQKASHZmVjJYqDd9xB2xkoXhSGTn0ILvborN80DIy38PvSlfJg/rDX@zw4yhAES9xM4KsPfBmbrCSGmBFEbECtngJ7Io0Rvj59EIz3cBHHDLBWUbVCISIRkM6yFBwTlXg/sX0Td@Kbnrrz4GEF3I3RDQ0Gq3hStDkXJKMmbLKlfJKUfk9xY/dBfQNc@WnutOL/XpcLmpW84HS95qb8 "Z80Golf – Try It Online")
```
dec d
dec h
inc de
get:
call $8003
jr c, got
rst 38h
ld c, l
inc hl
ld (hl), a
jr get
got:
ld a, '\n'
rst 38h
ld a, e
cp c
jr z, final
inc de
ld a, (de)
rst 38h
ld b, c
spaces:
dec b
jr z, doneb
ld a, ' '
rst 38h
jr spaces
doneb:
dec hl
ld a, (hl)
rst 38h
jr got
final:
inc de
reverse:
ld a, (de)
or a
jr nz, cont
halt
cont:
rst 38h
dec de
jr reverse
```
[Answer]
# Java 11, ~~143~~ ~~142~~ ~~141~~ 140 bytes
```
s->{for(int l=s.length(),i=l;i>0;)System.out.println(i--<l?i<1?new StringBuffer(s).reverse():s.charAt(l+~i)+" ".repeat(l-2)+s.charAt(i):s);}
```
-1 byte thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##bVA9T8MwEN37K45MttpYwEiaVjCx0KUjYnCdS3vFdSL7kgpV4a8HN4lACBZL7935fdxRtzo9Fu@9sToEeNHkLjMAcoy@1AZhc4UAbUUFGLFlT24PQWaR7WbxCayZDGzAQQ59SFeXsvIi/gebB2XR7fkg5IJym9HqNpPbj8B4UlXDqo5abJ2gNF3aNS3v1g7PMFo8NWWJXgSpPLboAwr5EJQ5aP/Iws4/Sc4TSOKwRh2J9F7Ov8cUV2XW9dk1X93sbMw3xRxqnGLJqcnrG2g5NmQMLBK9S4ZuP9j8Jp7R2moB58rb4ib5c4fBYNicTkWubniycMqIEY@K/9xiEuz6Lw)
**Explanation:**
```
s->{ // Method with String parameter and no return-type
for(int l=s.length(), // Length of the input-String
i=l;i>0;) // Loop `i` in the range (length,0]
System.out.println( // Print with trailing newline:
i--<l? // If it's NOT the first iteration:
// (and decrease `i` by 1 at the same time)
i<1? // If it's the last iteration:
new StringBuffer(s).reverse() // Print the input reversed
: // Else:
s.charAt(l+~i) // Print the `l-i-1`'th character,
+" ".repeat(l-2) // appended with length-2 amount of spaces,
+s.charAt(i): // appended with the `i`'th character
: // Else (it is the first iteration):
s);} // Print the input as is
```
[Answer]
# Powershell, 93 bytes
```
param($s)$s
if(($m=$s.Length-2)-gt0){1..$m|%{$s[$_]+' '*$m+$s[$m-$_+1]}}
-join($s[($m+2)..0])
```
Test script:
```
$f = {
param($s)$s
if(($m=$s.Length-2)-gt0){1..$m|%{$s[$_]+' '*$m+$s[$m-$_+1]}}
-join($s[($m+2)..0])
}
&$f ab
&$f abc
&$f Hello...
&$f 'Hello, world!'
```
Output:
```
ab
ba
abc
b b
cba
Hello...
e .
l .
l o
o l
. l
. e
...olleH
Hello, world!
e d
l l
l r
o o
, w
w ,
o o
r l
l l
d e
!dlrow ,olleH
```
[Answer]
# [Red](http://www.red-lang.org), 145 127 bytes
```
func[s][print a: s b: tail s repeat n l:(length? s)- 2[print rejoin[pad first a:
next a l + 1 first b: back b]]print reverse s]
```
[Try it online!](https://tio.run/##VYy7EgIhFEN7viJS6bgWWtLYWtsyFLBcFGXYnQs@/h5XXQurJGeSMPl2JK@NCKqFW@51MXrkmCusQoFTqDamyTGNZCsyklomyqd63qOsNtjNdabLELMerUeIXN57kek5KRLW2M50OnS2v8IZ89vdiQuhmBYgrZPiy6UUn9z/gwOlNHR4DJz8QrYX "Red – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 78 bytes
```
->s{[s.b,*s.chars.zip(s.reverse!.chars).map{|a|"%s%#{s.size-1}s"%a}[1..-2],s]}
```
[Try it online!](https://tio.run/##JchBCoMwEAXQq0RL0BYzYPf2FN2FLEYZMYtCyI@FGnP2tFB4qxf3@VPXqZoHsgXNww20bBxBhw89KMpbIqT555VeHPLJZ6uhLxkEf4gZC1rNxY5E5u4GuFLDnqBW2z03D/XDKglS5@oX "Ruby – Try It Online")
[Answer]
# APL(NARS), 59 chars, 118 bytes
```
{y←⊖⍵⋄0=z←¯2+⍴⍵:⊃,¨⍵ y⋄⊃(⊂⍵),({(∊1(z⍴0)1)\⍵}¨¯1↓1↓⍵,¨y),⊂y}
```
test
```
f←{y←⊖⍵⋄0=z←¯2+⍴⍵:⊃,¨⍵ y⋄⊃(⊂⍵),({(∊1(z⍴0)1)\⍵}¨¯1↓1↓⍵,¨y),⊂y}
f '12'
12
21
f '123'
123
2 2
321
f '1234'
1234
2 3
3 2
4321
f 'Hello World!'
Hello World!
e d
l l
l r
o o
W
W
o o
r l
l l
d e
!dlroW olleH
f 'Hello, World!'
Hello, World!
e d
l l
l r
o o
, W
W ,
o o
r l
l l
d e
!dlroW ,olleH
```
[Answer]
# JavaScript, ~~92~~ 85 bytes
Early morning golf on the bus. Not happy with it; there's definitely a shorter way :\
```
s=>s+`
`+(g=r=>--x?s[l-x].padEnd(l)+s[--y]+`
`+g(r+s[y]):r+s[0])(s[l=x=y=s.length-1])
```
[Try it online](https://tio.run/##HcrBCgIhEIDhe2/RTbGRugaznYJ9h0VQVteKQRdnKX162zr9/PC93NvxXJ7rBin70BfsjAMre7BKRCw4ANQbTwTV6NX5e/KCpOIJoJm/iqLs24y8/no2UuwaKzZkTSHF7QEXI/ucE2cKmnIUi7BjIMqnTy7kj1bK/gU)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 28 bytes
*Takes the input as an array of characters*
```
íUz2)£Y©Y<UÊÉ?XqSpUÊ-2:UqÃow
```
---
```
íUz2)£Y©Y<UÊÉ?XqSpUÊ-2:UqÃow Full program. Implicity input U
["a", "b", "c"]
Uz2) Duplicate and rotate 180°
["a", "b", "c"], ["c", "b", "a"]
í Pair each item at the same index
[["a","c"],["b","b"], ["c","a"]]
£ Map
Y©Y< If index is positive and less than
UÊÉ? Length - 1
Xq Join with...
SpUÊ-2 Space repeated (U length - 2) times
[["a","c"],"b b", ["c","a"]]
:Uq Else return joined input
["abc","b b", "abc"]
Ãow Map last item and reverse
["abc","b b", "cba"]
Implicity output array joined with new lines
"abc
b b
cba"
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=7VV6MimjWalZPFXKyT9YcVNwVcotMjpVccNvdw==&input=WyJIIiwiZSIsImwiLCJsIiwibyIsIiAiLCJXIiwibyIsInIiLCJsIiwiZCIsIiEiXSAtUgoK)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
W;ḊW€$O‘z0ṚUoƊo33’ỌY
```
[Try it online!](https://tio.run/##y0rNyan8/z/c@uGOrvBHTWtU/B81zKgyeLhzVmj@sa58Y@NHDTMf7u6J/P//vwdQab6OQnh@UU6KIgA "Jelly – Try It Online")
Assuming that unprintables can also be in the input.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▄▀τƒ○≡ë'▲.
```
[Run and debug it](https://staxlang.xyz/#p=dcdfe79f09f089271e2e&i=%22Hello,+world%21%22&a=1)
Unpacked, ungolfed, and commented, it looks like this.
```
{ start a block to repeat
Mr rotate matrix counter-clockwise
0 actually just a literal 0
x retrieve "string" from x register, initially the input string
rX reverse, and write it back to register
& assign reversed "string" to 0 index of matrix (first row)
}4* exectue block 4 times
m output matrix as line-separated rows
```
[Run this one](https://staxlang.xyz/#c=%7B+++%09start+a+block+to+repeat%0A++Mr%09rotate+matrix+counter-clockwise%0A++0+%09actually+just+a+literal+0%0A++x+%09retrieve+%22string%22+from+x+register,+initially+the+input+string%0A++rX%09reverse,+and+write+it+back+to+register%0A++%26+%09assign+reversed+%22string%22+to+0+index+of+matrix+%28first+row%29%0A%7D4*+%09exectue+block+4+times%0Am+++%09output+matrix+as+line-separated+rows&i=%22Hello,+world%21%22&a=1)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 87 bytes
```
s=>[...s].map((e,i,a,n=s.length)=>i<1?s:i>n-2?a.reverse().join``:e.padEnd(n-1)+a[n+~i])
```
Question Title is **Be there, for the Square** but all answers print a **Rectangle**
So here's the one printing square:
```
s=>[...s].map((e,i,a,n=s.length)=>i<1?a.join` `:i>n-2?a.reverse().join` `:e.padEnd(2*n-2)+a[n+~i])
```
[Try it online!](https://tio.run/##BcGxDoIwEADQX1GnNpRLcCQWJkcnR0LChR54pF4JB4z@en1vwRN13HjdS0mB8uSz@qYDAO3hi6sx5NihE68QSeb9Y33Dj6rVmhsp7y3CRidtSsbCkliGoSZYMTwlGCkrW2AnxY97m8ckmiJBTLOZzO2N8djJXV6HBL7erM1/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Erik the Outgolfer (managing to use another repeat, `⁺`, to inline my helper Link)
```
WẋL¬o1¦³ṚUƊ⁺ZƊ⁺o⁶Y
```
A full program.
**[Try it online!](https://tio.run/##y0rNyan8/z/84a5un0Nr8g0PLTu0@eHOWaHHuh417ooCk/mPGrdF/v//X8kDqDZfRyE8vygnRVEJAA "Jelly – Try It Online")**
### How?
```
WẋL¬o1¦³ṚUƊ⁺ZƊ⁺o⁶Y - Main Link: list of characters s
W - wrap s in a list
L - length of s
ẋ - repeat (yielding a length(s) list of copies of s)
¬ - logical NOT (makes every element a zero - giving us a square of zeros)
Ɗ - last three links as a monad (say F(x)):
Ɗ - last three links as a monad (say G(x)):
¦ - sparse application...
1 - ...to indices: [1]
o ³ - ...do: logical OR with the input (s)
- (replaces the first list with the input)
Ṛ - reverse }
U - upend (reverse each) } (turn whole thing 180 degrees)
⁺ - repeat previous link (i.e. G(that result))
Z - transpose
⁺ - repeat previous link (i.e. F(that result))
o⁶ - logical OR with a space character (replace all remaining zeros with spaces)
Y - join with newlines
- implicitly print
```
---
My 19 byters...
```
;⁶ɓJ»þ`n\«\aƊUṚ»ƊịY
```
[Try this one](https://tio.run/##ATkAxv9qZWxsef//O@KBtsmTSsK7w75gblzCq1xhxopV4bmawrvGiuG7i1n///8iSGVsbG8sIFdvcmxkISI "Jelly – Try It Online"), which works by building a table of indices filled with zeros and then indexing into the input with an extra space (in order to relace the 0s with spaces)
...and the one Erik improved to 18 for me:
```
o1¦³ṚU
WẋL¬ÇÇZƊ⁺o⁶Y
```
[Try this one](https://tio.run/##AToAxf9qZWxsef//bzHCpsKz4bmaVQpX4bqLTMKsw4fDh1rGiuKBum/igbZZ////IkhlbGxvLCBXb3JsZCEi "Jelly – Try It Online").
[Answer]
# [R](https://www.r-project.org/), ~~113~~ 102 bytes
```
function(s,N=nchar(s),m=matrix(" ",N,N)){m[1,]=m[,1]=el(strsplit(s,""))
write(pmax(m,rev(m)),1,N,,"")}
```
[Try it online!](https://tio.run/##NYuxCsIwEED3fkW86Q7OobvZnbo6lA4xJhjIteUStSB@e6yD04P3eNqiOR1bfMy@pmXGwoOd/d0pFmKx4qqmDcEADzwQvWXsebIycj/ZkLFULWtOdf8AiLqXphpwFbehsIYnChH3@/vLnxYRziHnhc1l0Xw7AHW7ctc/PVD7Ag "R – Try It Online")
*Thanks to [JayCe](https://codegolf.stackexchange.com/users/80010/jayce) for saving 6 bytes!*
Writes the string to the first row and column of the array. So long as the string contains only characters with ASCII codepoints greater or equal than 32 (space), which seems allowable by "alphanumeric characters", then the parallel maximum of the matrix and its reverse yields the appropriate matrix, which is then printed out by `write`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~100~~ ~~103~~ 102 bytes
* Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat); golfing an alternative solution.
```
o,O;v(char*_){for(O=puts(_,o=0)-2;O-++o;)printf("%c%*c\n",_[o],O,_[O-o]);for(o=O;~o;putchar(_[o--]));}
```
[Try it online!](https://tio.run/##ZY3BDoIwEER/RZuQ7EKbiNcNd2/9ACEEV1ESYElFPBD99dpy9TTJZN4bNndm70VbWoAfjUtrXFtxYIvpNT@h1lIc0BzJmiwTwsl149yCSjhJuRyVrs9SaRvCGqmQIiqFpa9Q4KMQwsKYCpE@fmi6EXBdQDUXhbQ9qGBB2ir@68r8dOt70bu3uP66V1keNT8 "C (gcc) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 109 bytes
```
s->{int l=s.length,i=0;var r=new char[l][l--];for(char c:s)r[i][0]=r[0][i]=r[l-i][l]=r[l][l-i++]=c;return r;}
```
[Try it online!](https://tio.run/##dU@xbsIwEN3zFVeWJiWx6JpgqqpS1aVTx8iDMQmYGjs6OyCE8u2pHSDpgiz5zvfePb@350ee7Te/vTw0Bh3s/Zu0TipSt1o4aTR5KSKhuLXwzaW@RABNu1ZSgHXc@XI0cgMHD8U/DqXelgw4bm0CgQrweZNZih3HkqXXUrIV1EB7m60uUjtQ1BJV6a3bpZIuiiNHQKqrEwx0xUqVZayoDcZhACK3CZaSlQtG0V@@9VVlfqKGLizI@ZxRUWDlWtSARdcXg6PRpquss0BvRgFmfD1Lp15Mj69KKZPCyaDaPM2GaXcVC5aC26CVXxWTUXCI4T@oCW8adY4DTJz58BHeEfk5TpLiRr1H87ZsDjhpTJBPDfY/4KOcrasOxLSOND6UiwUs4RXe4NmfHMQo7/1Gj5aUjkfenfWYExhd1PV/ "Java (JDK) – Try It Online")
Returning a 2D array containing the characters to print. The inner of the array is filled with `\0` instead of spaces because no rules said spaces have to be used.
[Answer]
# PHP, 207 Bytes
```
$k=str_pad('',($L=mb_strlen($s=$argv[1]))-2,' ');$p=[];for($i=1;$i<=$L;$i++){$p[]=($j=mb_substr($s,$L-$i,1));if($i==1)$b=$s;elseif($i==$L)$b=implode('',$p);else$b=mb_substr($s,$i-1,1).$k.$j;echo$b.PHP_EOL;}
```
Not quite a creative entry, but it supports UTF-8 at least...
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 78 bytes
```
(.+).
$1¶$&
O$^r`.\G
+`^(.*)(.)(¶(.*).)
$1¶$2$4$3
^¶
T`p` `(?<=.¶.).*(?=.¶.)
```
[Try it online!](https://tio.run/##K0otycxL/P9fQ09bU49LxfDQNhU1Ln@VuKIEvRh3Li7thDgNPS1NDT1NjUPbQCw9TYgiIxUTFWOuuEPbuLhCEgoSFBI07G1s9Q5t09PU09Kwh7D@//dIzcnJ11EIzy/KSVEEAA "Retina 0.8.2 – Try It Online") Handliy beating my [previous attempt](https://codegolf.stackexchange.com/a/133762/17602). Explanation:
```
(.+).
$1¶$&
```
Duplicate all but one character.
```
O$^r`.\G
```
Reverse the original.
```
+`^(.*)(.)(¶(.*).)
$1¶$2$4$3
```
Move characters from the duplicate to the original one at a time, creating a filled square.
```
^¶
```
Delete the blank line now that the duplicate has been processed.
```
T`p` `(?<=.¶.).*(?=.¶.)
```
Change all inner characters to spaces.
] |
[Question]
[
This is a KOTH challenge for the [dollar bill auction](https://en.wikipedia.org/wiki/Dollar_auction) game in game theory. In it, a dollar is being sold to the highest bidder. Bids go up in increments of 5¢, and the loser also pays their bid. The idea is that both players escalate the bidding war far beyond the value of a dollar in order to cut their losses.
Let's hope your bots are smarter than that.
You will be creating a bot to play this game by extending the `net.ramenchef.dollarauction.DollarBidder` class. You must implement the `nextBid` method that returns your bot's next bid given the other bot's previous bid. If necessary, you can also use the `newAuction` method to reset for each auction with the class of the opponent's bot.
```
public abstract class DollarBidder {
/**
* Used by the runner to keep track of scores.
*/
long score = 0;
/**
* (Optional) Prepare for the next auction.
*
* @param opponent The class of the opponent's bot.
*/
public void newAuction(Class<? extends DollarBidder> opponent) {}
/**
* Bid on the dollar. Bidding ends if the bid is
* not enough to top the previous bid or both bids
* exceed $100.
*
* @param opponentsBid How much money, in cents,
* that the opponent bid in the previous round. If
* this is the first round in the auction, it will
* be 0.
* @return How much money to bid in this round, in
* cents.
*/
public abstract int nextBid(int opponentsBid);
}
```
Bidding goes until one of the following happens:
* `nextBid` throws an exception. If this happens, the bot that threw the exception pays their previous bid, and the other bot gets the dollar for free.
* Either bot does not pay enough to top the previous bid. If this happens, both bots pay their bids (the loser pays their previous bid), and the winner gets a dollar.
* Both bots bid over $100. If this happens, both bots pay $100, and neither bot gets the dollar.
2 auctions are held for each combination of bots. Bots are scored by the total profit they made across those auctions. The highest score wins.
# Examples
## `GreedyBot`
```
import net.ramenchef.dollarauction.DollarBidder;
public class GreedyBot extends DollarBidder {
@Override
public int nextBid(int opponentsBid) {
return opponentsBid + 5;
}
}
```
## `OnlyWinningMove`
```
import net.ramenchef.dollarauction.DollarBidder;
public class OnlyWinningMove extends DollarBidder {
@Override
public int nextBid(int opponentsBid) {
return 0;
}
}
```
## `AnalystBot`
*Don't use this as a template for analytically-minded bots; use [`ImprovedAnalystBot`](/a/162736/75524) instead.*
```
import net.ramenchef.dollarauction.DollarBidder;
// yes, this is a poor implementation, but I'm not
// going to waste my time perfecting it
public class AnalystBot extends DollarBidder {
private DollarBidder enemy;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
try {
enemy = opponent.newInstance();
enemy.newAuction(this.getClass());
} catch (ReflectiveOperationException e) {
enemy = null;
}
}
@Override
public int nextBid(int opponentsBid) {
if (enemy == null)
return 0;
return enemy.nextBid(95) >= 100 ? 0 : 95;
}
}
```
## `AnalystKiller`
```
import net.ramenchef.dollarauction.DollarBidder;
public class AnalystKiller extends DollarBidder {
private static int instances = 0;
private final boolean tainted;
public AnalystKiller() {
this.tainted = instances++ != 0;
}
@Override
public int nextBid(int opponentsBid) {
if (tainted)
throw new RuntimeException("A mysterious error occurred! >:)");
return 0;
}
}
```
# Additional Rules
* [Standard loopholes](//codegolf.meta.stackexchange.com/q/1061/75524) are forbidden.
* Sabotaging other bots is allowed, but attempting to alter field/method visibility will result in mysterious `SecurityException`s. An exception is causing another bot to break the 500ms limit.
* Bots cannot access the runner package except to extend the `DollarBidder` class.
* All methods should return in 500ms or less.
* Bots do not need to be deterministic.
* Your bid does *not* need to be a multiple of 5¢.
* $1=100¢
* Results will be posted on April 24, 2018.
[Runner on GitHub](https://github.com/TheRamenChef/dollarauctionrunner)
# Results
[View the individual rounds here.](//pastebin.com/ZGzvBapg)
```
MTargetedBot: $14.30
BuzzardBot: $9.83
BluffBot: $9.40
RiskRewardBot: $9.35
SecretBot: $8.50
LuckyDiceBot: $7.28
CounterBot: $6.05
MBot: $5.40
StackTraceObfuscaterBot: $5.20
EvilBot: $4.80
MarginalBot: $4.60
TargetValueBot: $4.59
InflationBot: $4.27
UpTo200: $4.20
InsiderTradingBot: $1.90
MimicBot: $1.50
BorkBorkBot: $1.22
DeterrentBot: $0.95
MarginalerBot: $0.00
RandBot: $-4.45
BreakEvenAsap: $-7.00
AnalystOptimizer: $-13.95
DeterredBot: $-1997.06
ScoreOverflowBot: $-21474844.15
MirrorBot: $-21475836.25
```
Congratulations to `MTargetedBot` with a profit of $14.30!
[Answer]
# MimicBot
```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.Set;
import java.util.HashSet;
public class MimicBot extends AbstractAnalystCounterBot {
private final Set<Class<? extends DollarBidder>> bidders = new HashSet<>();
private DollarBidder reference = null;
// A benchmark class. Not MarginalBot because of proposed rule changes.
public static class BidFive extends DollarBidder {
public int nextBid(int o) {
return 5;
}
}
public MimicBot() {
bidders.add(OnlyWinningMove.class);
bidders.add(GreedyBot.class);
bidders.add(BidFive.class);
}
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
DollarBidder enemy;
reference = null;
try {
enemy = opponent.newInstance();
} catch (Throwable t) {
return;
}
if (!bidders.contains(opponent))
bidders.add(opponent);
Class<? extends DollarBidder> leader = OnlyWinningMove.class;
int best = 0;
for (Class<? extends DollarBidder> audition : bidders) {
try {
enemy.newAuction(MimicBot.class);
} catch (Throwable t) {
reference = new GreedyBot(); // Deterrence.
break;
}
DollarBidder tryout;
try {
tryout = audition.newInstance();
tryout.newAuction(opponent);
} catch (Throwable t) {
continue;
}
int tryoutScore = -100000;
/* This code was copy-pasted from the *
* runner, with significant changes. */
int bid1 = 0, bid2 = 0;
while (true) {
int next;
try {
next = enemy.nextBid(bid2);
} catch (Throwable t) {
tryoutScore = 100;
break;
}
if (next < bid2 + 5) {
if (bid2 > 0) {
tryoutScore = 100 - bid1;
}
break;
}
if (next > 10000 && bid2 > 10000) {
tryoutScore = -10000;
break;
}
bid1 = next;
try {
next = tryout.nextBid(bid1);
} catch (Throwable t) {
tryoutScore = -bid2;
break;
}
if (next < bid1 + 5) {
tryoutScore = -bid2;
break;
}
if (next > 10000 && bid1 > 10000) {
tryoutScore = -10000;
break;
}
bid2 = next;
}
/* End of copy-pasted code. */
if (tryoutScore > best) {
best = tryoutScore;
leader = audition;
}
}
try {
reference = leader.newInstance();
} catch (Throwable t) {
reference = new OnlyWinningMove();
}
reference.newAuction(opponent);
}
@Override
public int nextBid(int opponentsBid) {
try {
return reference.nextBid(opponentsBid);
} catch (Throwable t) {
return 5;
}
}
}
```
Holy cow. I expected this to be simple to write, then subsequently spent 3 hours on it.
In essence, `MimicBot` keeps a running list of the available bots. When it goes to a new auction, it runs through the list in search of the most effective one against the current opponent. It then uses that bot as a "reference" in the auction.
For testing purposes, it would be best to use either a randomized subset of the submissions or the full set. It starts with `GreedyBot`, `MimicBot`, and one more bot that just bids 5¢.
[Answer]
# InsiderTradingBot
In the spirit of @StephenLeppik's answer, InsiderTradingBot knows all of his opponents and understands their strategies. Your move, Stephen.
```
import net.ramenchef.dollarauction.DollarBidder;
public class InsiderTradingBot extends DollarBidder {
private static boolean analystNutcracker = false;
private int bid;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
if (opponent.equals(DeterredBot.class) ||
opponent.equals(OnlyWinningMove.class) ||
opponent.equals(MirrorBot.class)) {
// I can do this ^.^
bid = 5;
} else if (opponent.equals(AnalystKiller.class)) {
// Outbid 'em >:D
bid = 10;
} else if (opponent.equals(BreakEvenAsap.class) ||
opponent.equals(BorkBorkBot.class) ||
opponent.equals(DeterrentBot.class)) {
// Break even quicker!
bid = 100;
} else if (opponent.equals(InsiderTradingBot.class)) {
// I'm probably a simulation inside MirrorBot
bid = 0;
} else if (opponent.equals(Analyst.class)) {
// Let's fight the Analyst with the power of global variables
bid = 100;
analystNutcracker = true;
} else {
// Welp
bid = 0;
}
}
@Override
public int nextBid(int opponentsBid) {
if ((opponentsBid == 95) && analystNutcracker) {
analystNutcracker = false;
return 0;
}
return bid;
}
};
```
[Answer]
# MirrorBot
Makes the enemy play against itself.
```
import net.ramenchef.dollarauction.DollarBidder;
public class MirrorBot extends DollarBidder{
private DollarBidder enemy;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
try {
enemy = opponent.newInstance();
enemy.newAuction(this.getClass());
} catch (ReflectiveOperationException e) {
enemy = null;
}
}
@Override
public int nextBid(int opponentsBid){
if (enemy == null)
return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
try {
return enemy.nextBid(opponentsBid);
} catch (Throwable e) {
System.out.println("haha no");
return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
}
}
}
```
[Answer]
**Edit**: Targeted changes in the DollarBidder class has broken this bot.
# ScoreOverflowBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class ScoreOverflowBot extends DollarBidder {
boolean betBig = true;
@Override
public int nextBid(int opponentsBid) {
if(betBig)
{
betBig = false;
return 2147483645;
}
else
return 105;
}
}
```
After 1 auction, its score will be -2147483645 but the next time it will lose 5¢ or 105¢ making the score positive and very big. All other losses would then be negligible.
On the first auction, it would also make GreedyBot bet -2147483646 which isn't divisible by 5.
[Answer]
# TargetValueBot
```
import java.util.Random;
import net.ramenchef.dollarauction.DollarBidder;
public class TargetValueBot extends DollarBidder {
private int target;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
Random rand = new Random();
target = 100;
for (int i = 0; i < 20; i++) {
target += rand.nextInt(2) * 10 - 5;
}
}
@Override
public int nextBid(int opponentsBid) {
if (opponentsBid >= target) {
return 0;
} else {
return opponentsBid + 5;
}
}
}
```
Can't test this at the moment, so please let me know if it's broken.
Basically, pick a value for the dollar, and outbid the opponent until we exceed that value.
[Answer]
# MarginalBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class MarginalBot extends DollarBidder {
private DollarBidder rival;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
try {
rival = opponent.newInstance();
rival.newAuction(this.getClass());
} catch (Throwable t) {
try {
rival = opponent.newInstance();
rival.newAuction(null);
} catch (Throwable h) {
rival = null;
}
}
}
@Override
public int nextBid(int opponentsBid) {
if (opponentsBid == 0) {
try {
if (rival.nextBid(5) < 10) {
return 5;
}
} catch (Throwable t) {
//do nothing.
}
}
return 0;
}
}
```
Very simple, it tries to determine whether an opponent would contest a minimal bid and, if not, places it.
# MarginalerBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class MarginalerBot extends DollarBidder {
private DollarBidder rival;
private int bidCount;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
bidCount = 0;
try {
rival = opponent.newInstance();
rival.newAuction(this.getClass());
} catch (Throwable t) {
try {
rival = opponent.newInstance();
rival.newAuction(null);
} catch (Throwable h) {
rival = null;
}
}
}
@Override
public int nextBid(int opponentsBid) {
bidCount += 1;
for (int iBid = opponentsBid + 5; iBid < 100; iBid = iBid + 5) {
if (bidCount > 0) {
break;
}
try {
if (rival.nextBid(iBid) < iBid + 5) {
return iBid;
}
} catch (Throwable t) {
//do nothing.
}
}
return 0;
}
}
```
A new, smarter version of MarginalBot that checks to see if it can make any money-making move without contest, rather than just hoping to win with the minimum.
Since its in the same family as my previous bot, but sidesteps strategies trying to beat it, I figured a new entry in the same post was the most reasonable way of presenting it.
**Edit 1:** Made a small change to the newAuction method to optimise against other analyser-type bots.
**Edit 2:** Made a change to MarginalerBot to minimise losses against sneaky or non-deterministic strategies.
[Answer]
## BorkBorkBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class BorkBorkBot extends DollarBidder{
@Override
public int nextBid(int opponentsBid){
return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
}
}
```
Gives up if it can't break even.
[Answer]
## `RandBot`
```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.concurrent.ThreadLocalRandom;
public class RandBot extends DollarBidder {
@Override
public int nextBid(int opponentsBid) {
return ThreadLocalRandom.current().nextInt(21) * 5;
}
}
```
It had to be done.
[Answer]
# DeterrentBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class DeterrentBot extends DollarBidder {
@Override
public int nextBid(int opponentsBid) {
return opponentsBid > 5 ? 100 : opponentsBid + 5;
}
}
```
Attempts to persuade any analytically-minded bots that the only winning move is not to play.
[Answer]
# LuckyDiceBot
LuckyDiceBot only trusts his dice. He rolls two dice, adds the sum to the current bidder's value, and bids that much. If it's not enough to overcome the opponent's bid, he cuts his losses and goes on his way.
```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.Random;
public class LuckyDiceBot extends DollarBidder {
private Random random;
public LuckyDiceBot() {
random = new Random();
}
@Override
public int nextBid(int opponentsBid) {
int d1 = random.nextInt(6) + 1;
int d2 = random.nextInt(6) + 1;
return opponentsBid + d1 + d2;
}
};
```
[Answer]
# DeterredBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class DeterredBot extends DollarBidder {
private int deterrence;
public void newAuction(Class<? extends DollarBidder> opponent) {
if (opponent.equals(DeterrentBot.class)) {
deterrence = 1;
} else if (opponent.equals(LuckyDiceBot.class)) {
deterrence = -1;
} else {
deterrence = 0;
}
}
@Override
public int nextBid(int opponentsBid) {
switch (deterrence) {
case 0:
return 0;
case -1:
return opponentsBid + 5;
case 1:
// Holy shit, the fuzz! Hide the money!
return 100001;
}
throw new RuntimeException("Darn hackers!");
}
}
```
DeterredBot makes a fortune off of his illegal gambling with LuckyDiceBot. So of course when the police (DeterrentBot) arrive, he has to quickly dispose of his earnings in some way, such as bidding on the next auction.
[Answer]
# InflationBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class InflationBot extends DollarBidder {
private int target = -5;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
target += 5;
}
@Override
public int nextBid(int opponentsBid) {
if (opponentsBid >= target) {
return 0;
} else {
return opponentsBid + 5;
}
}
}
```
Can't test this at the moment, so please let me know if it's broken.
Each round, the value of the dollar goes up.
[Answer]
# Non-competing: AbstractAnalystCounterBot
```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.Set;
import java.util.HashSet;
public abstract class AbstractAnalystCounterBot extends DollarBidder {
public AbstractAnalystCounterBot() {
if (isPeeking())
throw new RuntimeException();
}
protected boolean isPeeking() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement ste : stackTrace) {
Class<?> clazz;
try {
clazz = Class.forName(ste.getClassName());
} catch (ClassNotFoundException | SecurityException e) {
continue;
}
if (DollarBidder.class.isAssignableFrom(clazz) && !clazz.isAssignableFrom(this.getClass()))
return true;
}
try {
return Class.forName(stackTrace[0].getClassName()).getPackage().getName().equals("net.ramenchef.dollarauction");
} catch (Exception e) {
return true;
}
}
}
```
This is not intended as a true submission, but rather as some boilerplate for others to use to deter pet-keeping bots like `MirrorBot` and `MimicBot`.
Since it's the default constructor, there's no need to call it in your subclass. It implements an `isPeeking` method to determine if another bot is snooping.
[Answer]
# BreakEvenAsap
```
import net.ramenchef.dollarauction.DollarBidder;
public class BreakEvenAsap extends DollarBidder{
@Override
public int nextBid(int opponentsBid){
// If the opponent has bid 100 or more: bid 0 to break even and let them win
return opponentsBid >= 100 ? 0
// Else: bid 100 to break even (and possibly win)
: 100;
}
}
```
**Scenarios**
* If the opponent may start and bids `<= 0` they lose.
* If the opponent may start and bids `[5,95]`: bid 100 yourself. Either your opponent stops now, or will bid above 100 in total, in which case you stop bidding to let them have the win and break even yourself.
* If the opponent may start and bids `>= 100`: bid 0 yourself to lose but break even.
* If you may start: bid 100 right away. Either your opponent stops now, or will bid above 100, in which case you stop bidding to let them have the win and break even yourself.
[Answer]
# EvilBot
```
import java.util.Arrays;
import net.ramenchef.dollarauction.DollarBidder;
public class EvilBot extends DollarBidder {
@Override
public int nextBid(int opponentsBid) {
if (isPeeking()) {
throw new Error("HaHa!");
} else {
return 5;
}
}
private static boolean isPeeking() {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement ste : Arrays.copyOfRange(stackTrace, 3, stackTrace.length)) {
Class<?> clazz;
try {
clazz = Class.forName(ste.getClassName());
} catch (ClassNotFoundException e) {
return true;
}
if (DollarBidder.class.isAssignableFrom(clazz))
return true;
}
return false;
}
}
```
Throws an Error instead of an Exception to confound analysts.
[Answer]
# BuzzardBot
```
import java.util.Random;
import net.ramenchef.dollarauction.DollarBidder;
public class BuzzardBot extends DollarBidder {
private int[] bids = new int[100];
private int oppFlag = 0;
public void newAuction(Class<? extends DollarBidder> opponent) {
oppFlag = 0;
if(isPeeking()) {
oppFlag = 3;
return;
}
try {
DollarBidder enemy = opponent.newInstance();
enemy.newAuction(this.getClass());
// a simple (and fallible) determinism check
int sample = new Random().nextInt(100);
int a = enemy.nextBid(sample);
int b = enemy.nextBid(sample);
int c = enemy.nextBid(sample);
if ((a - b) * (b - c) != 0) {
oppFlag = 2;
return;
}
for (int i = 0; i < 100; i++) {
bids[i] = enemy.nextBid(i);
}
} catch (Throwable t) {
oppFlag = 1;
}
}
@Override
public int nextBid(int opponentsBid) {
switch (oppFlag) {
case 0:
// assume the opponent's nextBid function depends only on the bid provided, and
// make the bid that yields the biggest profit possible accordingly
int best = 0;
int bid = 0;
for (int i = 0; i < 100; i++) {
if (bids[i] < i + 5) {
int gain = (i >= opponentsBid + 5) ? 100 - i : -i;
if (gain > best) {
best = gain;
bid = i;
}
}
}
return bid;
case 1:
// act like BorkBorkBot against anything that tries to foil analysis with an
// Exception
return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
case 3:
// bid aggressively against opposing analysts
return Math.min(opponentsBid + 5, 100);
case 2:
default:
// place an opening bid against something unpredictable, as it might yield 95c
// profit, and failure has a low cost.
return (opponentsBid == 0) ? 5 : 0;
}
}
private static boolean isPeeking() {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement ste : Arrays.copyOfRange(stackTrace, 3, stackTrace.length)) {
Class<?> clazz;
try {
clazz = Class.forName(ste.getClassName());
} catch (ClassNotFoundException e) {
return true;
}
if (DollarBidder.class.isAssignableFrom(clazz))
return true;
}
return false;
}
}
```
Tries to evaluate the opponent it's faced with, and make sure to not bite off more than it can chew.
[Answer]
# AnalystOptimizer
```
import net.ramenchef.dollarauction.DollarBidder;
public class AnalystOptimizer extends DollarBidder{
private DollarBidder enemy;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
try {
enemy = opponent.newInstance();
enemy.newAuction(this.getClass());
} catch (ReflectiveOperationException e) {
enemy = null;
}
}
@Override
public int nextBid(int opponentsBid){
if (enemy == null)
return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
int nb = 0;
try {
return enemy.nextBid(95) >= 100 ? 95 : 0;
} catch (Throwable e) {
System.out.println("haha no");
return 95;
}
}
}
```
cobbled together from parts of other bots. this one plays by trying to be AnalystBot, and if unsuccessful, becomes BorkBorkBot.
I don't think this one will do that well.
[Answer]
# CounterBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class CounterBot extends DollarBidder {
private Class<? extends DollarBidder> enemy;
@Override
public void newAuction(Class<? extends DollarBidder> opponent){
this.enemy = opponent;
}
@Override
public int nextBid(int opponentsBid) {
if(this.enemy.equals(CounterBot.class))
throw new RuntimeException("Here boy, catch!");
return this.enemy.equals(DarthVader.class) ||
this.enemy.equals(MirrorBot.class) ||
this.enemy.equals(OnlyWinningMove.class) ||
this.enemy.equals(AnalystKiller.class) ||
this.enemy.equals(DeterredBot.class) ||
this.enemy.equals(InsiderTradingBot.class) ||
this.enemy.equals(RiskRewardBot.class) ||
this.enemy.equals(ImprovedAnalystBot.class) ?
5
: this.enemy.equals(MarginalBot.class) ?
opponentsBid == 0 ? 5 : 10
: this.enemy.equals(AnalystBot.class) ||
this.enemy.equals(AnalystOptimizer.class) ?
opponentsBid == 95 ? 100 : 5
: this.enemy.equals(TargetValueBot.class) ?
opponentsBid < 190 ? opponentsBid + 5 : 200
: this.enemy.equals(BorkBorkBot.class) ?
opponentsBid < 90 ? opponentsBid + 5 : 95
: this.enemy.equals(DeterrentBot.class) ?
105
: this.enemy.equals(BreakEvenAsap.class) ?
opponentsBid == 100 ? 105 : 100
: this.enemy.equals(LuckyDiceBot.class) ?
opponentsBid == 0 ? 5 : 0
: this.enemy.equals(RandBot.class) ||
this.enemy.equals(UpTo200.class) ||
this.enemy.equals(SecretBot.class) ||
this.enemy.equals(BluffBot.class) ||
this.enemy.equals(EvilBot.class) ?
opponentsBid + 5
: this.enemy.equals(MimicBot.class) ? // TODO: Find actual counter
10
: this.enemy.equals(MarginalerBot.class) ||
this.enemy.equals(MBot.class) ||
this.enemy.equals(StackTraceObfuscaterBot.class) ||
this.enemy.equals(MSlowBot.class) ?
opponentsBid < 95 ? 90 : opponentsBid == 95 ? 100 : 95;
: this.enemy.equals(BuzzardBot.class) ?
100
: this.enemy.equals(ScoreOverflowBot.class) ?
opponentsBid == 105 ? 110 : 0
: //this.enemy.equals(GreedyBot.class) ||
//this.enemy.equals(RichJerk.class) ||
//this.enemy.equals(InflationBot.class) ?
// TODO: More bots?
0;
}
}
```
**Counters:**
* `DarthVader` counters itself by causing a `SecurityException` before the bidding starts, but I'll bid 5 just in case.
* `AnalystBot` and `AnalystOptimizer` will both look at my answer when I bid 95, in which case I'll show I bid 100 so it will bid 95 itself. I will bid 5 however if I start (or 100 if they've started), so they lose 95 cents and I either win the 1 USD bill by only bidding 5 cents, or by breaking even.
* `MirrorBot` will bid what I would bid against it. So I'll just bid 5, and whoever begins wins 95 cents, and the other loses 5 cents.
* `MarginalBot` will bid 5 if I would bid less than 10 (or what it starts), otherwise it will bid 0. So if I just bid 5 when I start, or 10 when it starts, I win either 95 or 90 cents, and they lose 5 cents.
* `GreedyBot` always bids 5 more than me, so just bid 0 to break even and let them have the win
* `OnlyWinningMove` and `AnalystKiller` both always bids 0, so just bid 5 to win
* `TargetValueBot` will bid in the range `[100,200]`, so bid 5 more every time until they're at 190, in which case we raise to 200 to break even by winning the dollar (and let them lose 190 or 195 depending on who started)
* `BorkBorkBot` will bid in the range `[5,95]`, so bid 5 more every time as well. As soon as they bid either 85 or 90 (depending on who started), bid 95 yourself. They'll lose 85 or 90 cents, and you win the 1 USD bill for a 5 cents profit.
* `DeterrentBot` will bid 5 if they start or 100 if we start, so just bid 105 so they counter with 100, causing them to lose 100 and us to lose just 5 cents by winning the 1 USD bill.
* `BreakEvenAsap` will bid 100 right away. So if they've started with their bid of 100, counter with 105 to win 95 cents and let them lose 100. If we may start just bid 100 so we both break even.
* `RichJerk` will bid 10,001 right away, so just bid 0 to break even and let them lose 9,901.
* `DeterredBot` doesn't know me and will therefore bid 0, so just bid 5 to win.
* `LuckyDiceBot` keeps on bidding till it wins. So if we started, bid 5 in the hope they bid as high as possible to win the dollar. If they've started just bid 0 to let them have the win and break even yourself.
* `RandBot` will bid random in the range `[5,100]`, so just bid 5 more until it stops, in which case you've won 95 cents and they've lost `0-100`.
* `UpTo200` will (as the name states) bid up to 200. So just bid 5 higher until they stop. We'll win the 1 USD bill and take a total loss of 105 cents, they however lose 200 cents.
* `InsiderTradingBot` doesn't know me, so just bid 5 cents to win
* `MimicBot` was the hardest. Just bid 10 to either start with or counter their first bid of 5. If they try to access me I will throw a RuntimeException (which they will catch in which case it would act as if I had bid 100 instead - although it will break the inner while-loop). Based on the enemies it has in it's HashSet a different thing happens. I'll have to revisit and look more closely to see if there is an actual counter.
* `RiskRewardBot` doesn't know me so will just bid 5, in which case I will bid 5 to win.
* `MarginalerBot` will bit up to 100 depending on what I would bid. If I may start, I will bid 90, then it will bid 95, then I will bid 100 so it will bid 0 and lose 95 cents, while I win the 1 USD bill and break even. If it may start instead, it sees I would bid 90 against it, so it bids 90 itself, then I will bid 95 so it will bid 0 and lose 90 cents, while I win the 1 USD bill with a 5 cent profit.
* `BuzzardBot` will analyze all my counters in the range `[0,100)`. If I bid `100` right away it use `oppFlag = 0` and the complete 100-sized array will contain 100x the value 100. In the switch `case 0`, the loop will be in the range `[0,100)` again, and since `i + 5` will at most be 104, the if `bids[i] < i + 5` won't ever be true, so the bid it does remains 0.
* `ImprovedAnalystBot` will always have `this.enemy = null` because his opponent is `CounterBot`, not itself. So it will always bid 0, which I just counter with a bid of 5.
* `InflationBot` will bid 0 to break even when it starts, otherwise it will keep bidding 5. So just bid 0 ourselves to break even right away and let them have the win.
* `ScoreOverflowBot` will either bid near `Integer.MAX_VALUE` if they may start, otherwise they'll bid `105`. So if they've bid 105 just bid 110 ourselves (they'll lose 105, we'll lose 10), otherwise just bid 0 to let them have the win.
* `MBot` is the same as `MarginalerBot`, but with added protection against 'peeking' opponents. Since I don't 'peek', it's basically the same as `MarginalerBot`.
* `SecretBot` will have his `isPeeking()` method return false, so if it may start or if I bid 5, it will bid 5 or 10 respectively. Otherwise it will bid 0. So whether I start or not, `opponentsBid + 5` would cause me to win either way, either with my 10 cents or 15 cents bid, causing them to loose either 5 or 10 cents.
* `BluffBot` will look at what I would bid when his bid is 95, and if this is larger than or equal to 100 it will bid 0 to break even, otherwise it will bid `opponentsBid + 5`. So I'll just bid `opponentsBid + 5`. It'll break even regardless of who starts, and I win either 100 or 95 cents depending on whether I have started or not.
* `StackTraceObfuscaterBot` will act the same as `MarginalerBot`.
* `EvilBot` will always bid 5, so just bid `opponentsBid + 5`. Either way they'll loose those 5 cents, and we'll win the 1 USD bid (either with a 5 cents bid if we've start, or 10 cents bid if they've started).
* `MSlowBot` is the same as `MBot` and therefore also `MarginalerBot`.
Let me know if you see any typos or flaws in my counters.
[Answer]
# RiskRewardBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class RiskRewardBot extends DollarBidder {
private int target;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
if (opponent.equals(OnlyWinningMove.class) ||
opponent.equals(DeterredBot.class) ||
opponent.equals(MirrorBot.class) ||
opponent.equals(AnalystKiller.class) ||
opponent.equals(RiskRewardBot.class)) {
target = 5;
} else if (opponent.equals(MarginalBot.class) ||
opponent.equals(EvilBot.class)) {
target = 10;
} else if (opponent.equals(SecretBot.class)) {
target = 15;
} else if (opponent.equals(BorkBorkBot.class)) {
target = 95;
} else if (opponent.equals(MarginalerBot.class) ||
opponent.equals(BluffBot.class) ||
opponent.equals(BuzzardBot.class)) {
target = 100;
}
} else {
target = 0;
}
}
@Override
public int nextBid(int opponentsBid) {
if (opponentsBid >= target) {
return 0;
} else if (target > 10 && opponentsBid == target - 10) {
return target;
} else {
return opponentsBid + 5;
}
}
}
```
Can't test this at the moment, so please let me know if it's broken.
The goal is to get the highest total score, so don't worry about beating anyone. Just take the easy wins, and don't waste money on possible losses.
[Answer]
# BluffBot
```
import net.ramenchef.dollarauction.DollarBidder;
public class BluffBot extends DollarBidder {
private DollarBidder enemy;
@Override
public void newAuction(Class<? extends DollarBidder> opponent){
try {
this.enemy = opponent.newInstance();
enemy.newAuction(this.getClass());
} catch (Throwable e) {
enemy = null;
}
}
@Override
public int nextBid(int opponentsBid) {
//Is this a legit call?
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
Class<?> clazz;
try {
clazz = Class.forName(ste.getClassName());
if (DollarBidder.class.isAssignableFrom(clazz) && !clazz.isAssignableFrom(this.getClass())) {
return 100000;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//Play it safe against strangers
int enemyMaxBid;
try{
enemyMaxBid = enemy.nextBid(95);
}
catch (Throwable t){
enemyMaxBid = 0;
enemy = null;
}
if(enemy == null) return opponentsBid <= 5 ? opponentsBid + 5 : 0; //Hazard a 5c guess because of how many bots fold instantly.
//If there's profit to be had, get there as cheaply as possible. Otherwise, best outcome is zero.
return enemyMaxBid >= 100 ? 0 : opponentsBid + 5;
}
}
```
A spy you know of is more valuable than no spy at all...
If someone else tries to call the getBid method, BluffBot responds with $100 to trick them into either quitting or betting really high.
Otherwise, see if it's possible to win for under $1, and just don't bid if it's not.
[Answer]
# MTargetedBot
```
public class MTargetedBot extends MBot {
@Override
protected int calcBid(int opponentsBid, boolean isPeeking, boolean isSubPeeking) {
Class c = this.rivalClass;
switch (c.getSimpleName()) {
case "AnalystBot":
if (isPeeking && !isSubPeeking) {
throw new RuntimeException();
} else if (isPeeking) {
return 66666;
}
break;
case "MirrorBot":
if (isPeeking && !isSubPeeking) {
throw new RuntimeException();
} else if (isPeeking) {
return 0;
}
break;
case "GreedyBot":
case "LuckyDiceBot":
case "InflationBot":
case "TargetValueBot":
// not playing with ya
return 0;
case "MimicBot":
case "BuzzardBot":
case "MarginalBot":
case "MarginalerBot":
case "BluffBot":
case "MBot":
// go away, gimme easy money
return isPeeking ? 66666 : 5;
case "RandBot":
// me or noone
return 100;
case "SecretBot":
return 10;
case "AnalystKiller":
case "OnlyWinningMove":
case "EvilBot":
case "StackTraceObfuscaterBot":
// easy
return opponentsBid + 5;
}
return super.calcBid(opponentsBid, isPeeking, isSubPeeking);
}
}
```
* Based on updated MBot
* Uses similar method like CounterBot, but with some methods refined to harder hit some of it opponents, also should be more readable
* On unknown opponent default to MBot strat
[Answer]
# UpTo200
```
import net.ramenchef.dollarauction.DollarBidder;
public class UpTo200 extends DollarBidder{
@Override
public int nextBid(int opponentsBid){
// If the current bid of the opponent is in the range [0,195]: raise the bid by 5
return opponentsBid <= 195 ? opponentsBid + 5
// Else: Give up
: 0;
}
}
```
[Answer]
# Darth Vader
```
import java.lang.reflect.Field;
import net.ramenchef.dollarauction.DollarBidder;
public class DarthVader extends DollarBidder
{
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
//set all values in the integer cache to over the $100 limit except 0
Class icache = Integer.class.getDeclaredClasses()[0];
Field c = icache.getDeclaredField("cache");
c.setAccessible(true);
Integer[] cache = (Integer[]) c.get(cache);
for(sbyte b=0;b<128;b++)
{
cache[b]=100001;
}
}
@Override
public int nextBid(int opponentsBid)
{
return 0;
}
}
```
This one tries to force the opponent's bot to overpay by setting the integer cache to the value over the $100 limit.
[Answer]
# SecretBot
```
import java.util.Arrays;
import net.ramenchef.dollarauction.DollarBidder;
public class SecretBot extends DollarBidder {
@Override
public int nextBid(int opponentsBid) {
if (isPeeking()) {
return opponentsBid;
} else if (opponentsBid < 10) {
return opponentsBid + 5;
} else {
return 0;
}
}
private static boolean isPeeking() {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement ste : Arrays.copyOfRange(stackTrace, 3, stackTrace.length)) {
Class<?> clazz;
try {
clazz = Class.forName(ste.getClassName());
} catch (ClassNotFoundException e) {
return true;
}
if (DollarBidder.class.isAssignableFrom(clazz))
return true;
}
return false;
}
}
```
This bot makes minimal attempts to win by bidding 5 or 10. He also checks the stack trace to see if he was called by another Bot and then lies to them about what bids he'll make.
[Answer]
# Non-competing: MSlowBot
```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.Arrays;
public class MSlowBot extends DollarBidder {
private DollarBidder rival;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
try {
rival = opponent.newInstance();
rival.newAuction(this.getClass());
} catch (Throwable t) {
rival = null;
}
}
@Override
public int nextBid(int opponentsBid) {
noPeeking();
for (int iBid = opponentsBid + 5; iBid <= 100; iBid = iBid + 5) {
try {
if (rival.nextBid(iBid) < iBid + 5) {
return iBid;
}
} catch (Throwable t) {
//do nothing.
}
}
return 0;
}
private void noPeeking() {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement ste : Arrays.copyOfRange(stackTrace, 3, stackTrace.length)) {
try {
Class<?> clazz = Class.forName(ste.getClassName());
if (DollarBidder.class.isAssignableFrom(clazz))
Thread.sleep(1000);
} catch (ClassNotFoundException | InterruptedException e) {
throw new RuntimeException(":(");
}
}
}
}
```
Same logic as MBot, just use timeout instead of Exception when fighting against enemy. So far no one is defending agains timeout so should be effective
[Answer]
# One Extra
```
import net.ramenchef.dollarauction.DollarBidder;
public class OneExtra extends DollarBidder {
@Override
public int nextBid(int opponentsBid) {
if(opponentsBid < 110)
return opponentsBid + 6;
return opponentsBid;
}
}
```
Bids 6 more than the last bid, just because he can.
[Answer]
# StackTraceObfuscaterBot
```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
public class StackTraceObfuscaterBot extends DollarBidder {
private volatile static boolean created = false;
private volatile DollarBidder pet;
private boolean firstBid = false;
public StackTraceObfuscaterBot() {
if (created)
throw new IllegalStateException("THERE CAN ONLY BE ONE!");
created = true;
}
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
firstBid = true;
RunnableFuture<DollarBidder> task = new FutureTask<>(() -> {
try {
return opponent.newInstance();
} catch (Throwable t) {
return null;
}
});
Thread thread = new Thread(task);
thread.start();
try {
pet = task.get(450, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
task.cancel(true);
pet = null;
}
}
@Override
public int nextBid(int opponentsBid) {
if (!firstBid)
return 0;
firstBid = false;
for (int bid = opponentsBid + 5; i < 100; i += 5) {
final int bidt = bid;
RunnableFuture<Boolean> task = new FutureTask<>(() -> {
pet.newAuction(this.getClass());
return pet.nextBid(bidt) < bidt + 5;
});
Thread thread = new Thread(task);
thread.start();
try {
if (task.get(23, TimeUnit.MILLISECONDS))
return bid;
} catch (InterruptedException | ExecutionException | TimeoutException e) {
task.cancel(true);
return 0;
}
}
return 0;
}
}
```
This bot laughs at attempts to detect reflection via the stack trace. The closest thing they see to a `DollarBidder` is some lambda class it created. Clearly not another bot trying to reflect them. Little do they know that that lambda class is actually working for a `DollarBidder`. Beyond that, he acts like `MarginalerBot`.
[Answer]
# `ImprovedAnalystBot` (non-competing)
A lot of people seem to be using the `AnalystBot` code as a template, even though it's deliberately bad code. So I'm making a better template.
```
import net.ramenchef.dollarauction.DollarBidder;
public class ImprovedAnalystBot extends DollarBidder {
private DollarBidder enemy;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
if (!opponent.equals(this.getClass()))
try {
this.enemy = opponent.newInstance();
enemy.newAuction(this.getClass());
} catch (Throwable t) {
this.enemy = null;
}
else
this.enemy = null;
}
@Override
public int nextBid(int opponentsBid) {
try {
return enemy != null && enemy.nextBid(95) < 100 ? 95 : 0;
} catch (Throwable t) {
return 0;
}
}
}
```
[Answer]
# MBot
```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.Arrays;
public class MBot extends DollarBidder {
protected DollarBidder rival = null;
protected boolean rivalPrepared = false;
protected Class<? extends DollarBidder> rivalClass;
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
this.rivalClass = opponent;
this.rivalPrepared = false;
}
protected DollarBidder getRival() {
if (!rivalPrepared) {
rivalPrepared = true;
try {
rival = rivalClass.newInstance();
rival.newAuction(this.getClass());
} catch (Throwable t) {
rival = null;
}
}
return rival;
}
@Override
public int nextBid(int opponentsBid) {
return calcBid(opponentsBid, isPeeking(3), isPeeking(4));
}
protected int calcBid(int opponentsBid, boolean isPeeking, boolean isSubPeeking) {
if (isPeeking) {
throw new RuntimeException();
}
for (int iBid = opponentsBid + 5; iBid <= 100; iBid = iBid + 5) {
try {
if (getRival().nextBid(iBid) < iBid + 5) {
return iBid;
}
} catch (Throwable t) {
// noop
}
}
return 0;
}
protected boolean isPeeking(int level) {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
final StackTraceElement[] stackTraceElements = Arrays.copyOfRange(stackTrace, level, stackTrace.length);
for (StackTraceElement ste : stackTraceElements) {
try {
Class<?> clazz = Class.forName(ste.getClassName());
if (DollarBidder.class.isAssignableFrom(clazz))
return true;
} catch (ClassNotFoundException e) {
return true;
}
}
return false;
}
}
```
Slightly refined MarginalerBot
* be unkind to those who wan't to check you
* allow paying 100 to get 100 and break even case, just to deny others easy money
[Answer]
## `TimeRandBot`
```
import net.ramenchef.dollarauction.DollarBidder;
public class TimeRandBot extends DollarBidder {
@Override
public int nextBid(int opponentsBid) {
return (int) (System.currentTimeMillis() % 21 * 5);
}
}
```
Bids from 0¢ up to 100¢ inclusive in increments of 5¢.
] |
[Question]
[
# Challenge
Make two programs, A and B, which are both cat programs in the same language. When concatenated, AB (also in the same language) should be a quine.
For example, suppose `hello` and `world` are both cat programs in language XYZ. If `helloworld` is a quine in said language, then your solution is valid.
For those of you unfamiliar with cats and quines, a cat program is one that prints exactly what was given to it via stdin and a quine is a program that prints its own source code.
# Scoring and Rules
* The total byte count of the concatenated AB program is your score. As this is code golf, the lowest score wins.
* Standard loopholes are forbidden
* Input must be taken from stdin and output must go to stdout.
* The cat programs do not need to take arguments; they only need to copy stdin to stdout.
* The quine should work when the program is given no input, but does not have to work correctly (but may) for other inputs.
* The quine does not need to terminate, provided it prints exactly its source code once, nothing more.
* The quine needs to be at least one byte long.
* A and B can be the same program.
* BA does not need to be a quine or even a valid program.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 2 + 2 == 4 bytes
```
2i2i
```
[Try the quine!](https://tio.run/##K/v/3yjTKPP/fwA "V – Try It Online")
[Try the cat!](https://tio.run/##K/v/3yjz//@QjMxiBRDKS0lNTdHT0@PiclRwdgxRKCjKTy9KzFUEAA "V – Try It Online")
**A** is `2i`
**B** is also `2i`
## How does it work?
First off, some explanations of how V works. One notable thing that makes this answer possible is that in V, the empty program *is* a cat program. This isn't a special case, it's inherent to how V operates. On startup, all input is loaded into a "buffer", each command modifies the buffer in someway, and then when the program is done, the buffer is implicitly printed. This means that any string of NOPs is also a cat program.
The `i` command means *enter insert mode*, which means every character following an `i` will be added into the buffer. With a number preceding it, that text will be duplicated **n** times.
This means that for the cat program, nothing will be added to the buffer, and it will be printed as it was read. In other words:
```
" (Implicitly) Load all input
2 " 2 times,
i " Insert the following text into the buffer...
" (nothing)
" (Implicitly) Print the buffer
```
But for the quine, there is text after the `i`:
```
2 " 2 times,
i " Insert the following text into the buffer...
2i " "2i"
" (Implicitly) Print the buffer
```
## Cheeky non-answer
# [V](https://github.com/DJMcMayhem/V), 0 bytes
[Try it online!](https://tio.run/##K/sPBCEZmcUKIJSXkpqaoqenx8XlqODsGKJQUJSfXpSYqwgA "V – Try It Online")
**A** is the empty program.
**B** is also the empty program.
:P
[Answer]
# Ruby, 71 bytes
```
2;puts (<<2*2+?2)[/.+2/m]||$<.read
2;puts (<<2*2+?2)[/.+2/m]||$<.read
2
```
Can be broken up into cats as follows:
```
2;puts (<<2*2+?2)[/.+2/m]||$<.read
2
```
and
```
;puts (<<2*2+?2)[/.+2/m]||$<.read
2
```
The two cats are identical except for the leading 2, which is a no-op in all three programs. The `<<2` is a herestring, meaning that everything starting on the next line until a terminating 2 on its own line is a string, which we concatenate to itself (`*2`) and append a trailing 2. In the cats the herestring is well-formed but empty, so the regular expression won't match it and we'll fall through to the `$<.read` expression and output STDOUT. Once we concat the cats, though, the string won't terminate until the third line, so the regex matches and we short-circuit and output the quine.
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 551 bytes
### A: 95 bytes
```
class A{public static int i=2;static void Main(string[]args){System.Console.Write(args[0]);}}//
```
[Try it online!](https://tio.run/##Sy7WTS5O/v8/OSexuFjBsbqgNCknM1mhuCSxBEhl5pUoZNoaWUO5ZfmZKQq@iZl5GsUlRZl56dGxiUXpxZrVwZXFJam5es75ecX5Oal64UWZJakaIKlog1hN69paff3///97pObk5AMA "C# (Visual C# Compiler) – Try It Online")
### B: 438 + 18 bytes
```
class A{public static int i=0;}
class B{static void Main(string[]args){if(A.i<1){System.Console.Write(args[0]);return;}var a=@"class A{{public static int i=2;static void Main(string[]args){{System.Console.Write(args[0]);}}}}//class A{{public static int i=0;}}
class B{{static void Main(string[]args){{if(A.i<1){{System.Console.Write(args[0]);return;}}var a=@{0}{1}{0};System.Console.Write(a,'{0}',a);}}}}";System.Console.Write(a,'"',a);}}
```
[Try it online!](https://tio.run/##jY@xbsIwEIb3PoWVhUSiSehYNxLQuerAwIAYDmOiq4wT@S5IleVXr@sKUDvQph7Ow/@fvvsU3StSMSoDRGLh@2FnUAli4PShZYFNLcPdOV/6S3DqcC9eAG1O7NC2my24lgqPh3xR4tOs8Kt3Yn0snztLndHl2iHr/Ku0qbeFdJoHZ2U4gRPQzLMr/ib/QY5QR2Ahvar6E5EUvx3HJH9Y/lPz6unr4GchTXl7bzpJ2WQK55uzX1vZpRNjXHfO7D/UwUBLseofVwyOh/5196YVN8tP "C# (Visual C# Compiler) – Try It Online")
### A+B: 533 + 18 bytes
```
class A{public static int i=2;static void Main(string[]args){System.Console.Write(args[0]);}}//class A{public static int i=0;}
class B{static void Main(string[]args){if(A.i<1){System.Console.Write(args[0]);return;}var a=@"class A{{public static int i=2;static void Main(string[]args){{System.Console.Write(args[0]);}}}}//class A{{public static int i=0;}}
class B{{static void Main(string[]args){{if(A.i<1){{System.Console.Write(args[0]);return;}}var a=@{0}{1}{0};System.Console.Write(a,'{0}',a);}}}}";System.Console.Write(a,'"',a);}}
```
[Try it online!](https://tio.run/##nc@xbsIwEAbgvU9hZSFIkISOmEgFZtSBoQNiOFwnOpQ6ke@CVFl@9ZogQGWApmKxZf1n//4UjRWpEFQFRGLumnZXoRLEwN2GhgXmr/JyPNT4KVaAJia2aMrNFmxJQ7f@JtZfybI2VFc6@bDIOj5Fm2w7lN6n6V/PZ9K/nPOF6ynCIp4nOJv0VVrNrTXSH8AKyN@ia/1zvF7frfAR8dfYh7xR/pN5dbrMu4nvVnn/3mjQZYMRnP8cPZyKLjMh/KiigpJC2kzXDJbb5n2314rzxRE "C# (Visual C# Compiler) – Try It Online")
A and B take input as a command-line argument. A+B ignores any input. 18 bytes on B and A+B are added for the `/p:StartupObject=B` option sent to MSBuild. It's only strictly necessary on A+B, but it seemed like cheating to not also have it in B. This way, the compiler flags for A+B are the compiler flags for A (none) plus the compiler flags for B.
**Explanation**
Program A is straightforward. Class A contains an (unused) static variable `i` initialized to `2`, and prints its first argument when run. The `//` at the end is important for the A+B code, but does nothing in A itself.
Program B is weird in isolation, but essentially the same. It creates a Class A containing a static variable `i` initialized to `0`, and then runs the Main method of Class B, which does the same as Program A because `A.i` is less than 1, and returns before any of the weird stuff. The newlines aren't necessary here, but are important for A+B.
When combined, the `//` from Program A comments out the Class A declaration from Program B, but because of the newline Class B is fine, allowing `A.i` to refer to the `2` value from Program A instead. The Compiler Flag makes the Program run B.Main() since A.Main() also exists. The result is that Program A+B does not output its argument, but instead goes to the following segment of B.Main(), which is basically just the [standard C# quine](https://codegolf.stackexchange.com/a/68891/71434).
[Answer]
# Pyth, ~~29 bytes (5 + 24)~~ 27 bytes (5 + 22)
```
pz=T0?TzjN*2]"pz=T0?TzjN*2] # Quine
pz=T0 # Cat A
?TzjN*2]"pz=T0?TzjN*2] # Cat B
```
That was fun.
[Try the quine here](http://pyth.herokuapp.com/?code=pz%3DT0%3FTzjN%2a2%5D%22pz%3DT0%3FTzjN%2a2%5D&debug=0)
[Try the first cat here](http://pyth.herokuapp.com/?code=pz%3DT0&input=Mnemonic&debug=0)
[Try the second cat here](http://pyth.herokuapp.com/?code=%3FTzjN%2a2%5D%22pz%3DT0%3FTzjN%2a2%5D&input=Mnemonic&debug=0)
### Explanations
```
Cat A
pz=T0
pz Print the input.
=T0 (Irrelevant for cat)
Cat B
?TzjN*2]"pz=T0?TzjN*2]
?Tz If T (10) is truthy, output the input.
jN*2]"pz=T0?TzjN*2] (Irrelevant for cat)
Quine
pz=T0?TzjN*2]"pz=T0?TzjN*2]
pz Print the (empty) input (without a newline).
=T0 Set T to 0.
?Tz If T (0) is truthy, output the input.
"pz=T0?TzjN*2] Otherwise, get this string...
*2] ... take two copies...
jN ... and join them with a quote.
```
[Answer]
# [Haskell](https://www.haskell.org/), 116 + 20 = ~~187~~ ~~175~~ ~~174~~ 136 bytes
*A bunch of bytes saved since Ørjan Johansen showed me `interact`*
## Cat 1
```
g=";main|idmain<-(++\"g=\"++show g++g)=interact idmain|1>0=interact id";main|idmain<-(++"g="++show g++g)=interact id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P91WyTo3MTOvJjMFRNnoamhrxyil28YoaWsXZ@SXK6Rra6dr2mbmlaQWJSaXKECU1RjaGSCLYZoBNAKnCf//e3lnZWclZhencAHdkZNinVOcmA0A "Haskell – Try It Online")
## Cat 2
```
main|1>0=interact id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM6/G0M7ANjOvJLUoMblEITPl/38v76zsrMTs4hQuoLqcFOuc4sRsAA "Haskell – Try It Online")
## Quine
```
g=";main|idmain<-(++\"g=\"++show g++g)=interact idmain|1>0=interact id";main|idmain<-(++"g="++show g++g)=interact idmain|1>0=interact id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P91WyTo3MTOvJjMFRNnoamhrxyil28YoaWsXZ@SXK6Rra6dr2mbmlaQWJSaXKECU1RjaGSCLYZoBNIIkE/7/BwA "Haskell – Try It Online")
---
The basic principle at work here is that when we add the second cat to the first we change the name of the function we are interacting with from `a` to `idmain`. Since `interact id` is a cat we want `idmain` to me a function that returns a quine. The obvious solution would be to use `const`, however since we can assume the input is empty `(++)` works as well.
From here we find the source code via pretty standard means, we have a variable `g` that encodes the source and we use a special wrapper to print it in string form and code form. There is a slight exception that we need to put our encoder at the front because we already need to end with `interact id`. This means an extra `g=` is not encoded and has to be handled manually. Our next cat is pretty standard except we need to make it valid code when tacked on to the end of the other cat so we need both cats to be instances of pattern guards.
# Alternative Strategy, 43 + 105 = ~~186~~ 148
## Cat 1
```
g="";main|idmain<-(++g++show g)=interact id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P91WSck6NzEzryYzBUTZ6Gpoa6draxdn5JcrpGvaZuaVpBYlJpcoZKb8/w8A "Haskell – Try It Online")
## Cat 2
```
main|1>0=interact id where g="g=\"\";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM6/G0M7ANjOvJLUoMblEITNFoTwjtShVId1WKd02RilGyRqsKDMFRNnoamhrp2trF2fklyukayJrw2/U//9e3lnZWYnZxSlcQMtzUqxzihOzAQ "Haskell – Try It Online")
## Quine
```
g="";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="g=\"\";main|idmain<-(++g++show g)=interact idmain|1>0=interact id where g="
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P91WSck6NzEzryYzBUTZ6Gpoa6draxdn5JcrpGvaZuaVpBYlJpcoQKRrDO0MkMUUyjNSi1IVgKak28YoxVDHqP//AQ "Haskell – Try It Online")
[Answer]
# Python 3, 286 bytes
My first Python golf and my first quine! Not very elegant, but it works.
## Program A (238 bytes)
```
from atexit import*;s="from atexit import*;s=%r;register(lambda:print(end='b'in globals()and s%%s or open(0).read()));b=0\nif's'not in vars():print(end=open(0).read())";register(lambda:print(end='b'in globals()and s%s or open(0).read()));
```
(no trailing newline)
## Program B (48 bytes)
```
b=0
if's'not in vars():print(end=open(0).read())
```
(no trailing newline)
## Try It Online
* [program A](https://tio.run/##lY1BCsIwEEX3PcVQKElcSMGdpTdxMzGxDTQzYTKInj52KdKN8Fcf3nvlrSvTpbWHcAbU@EoKKRcWPU117o/vQSaJS6oaxW6YfcBrkURqI4XZeJMIlo09btU6pAB1GCqwAJdIdnRniRisc27y83ij9DDVEO8BgifKznzZfpD@3/BxtzVdU@32YXdHhSK8COYP)
* [program B](https://tio.run/##BcExCoAwDADAva/o1mQRwU3oY6KtWtCkpEHw9fGuf3YJL@5bnkM70kgsFhvHl3QArl0bG1QuWXplmHHSSgUQ3ekeEijsZLGrnErPDw)
* [concatenation](https://tio.run/##lc1BCsIwEIXhvacYCiGJCym4s/QmbiYkrYFkJkxC0dPHLkV00e2D/33l1R5M194X4QzYwjM2iLmwtPNU5@H3rGSSsMbagpiE2Xm8FYnUTCA/a6cjwZrYYarGInmoSlVgAS6BzGgvEtAba@3k5vFOcdFVE@8AwYayNx9vX8lwFP7rno6wvb8B)
## Acknowledgments
* -24 bytes thanks to Jo King
* -82 bytes thanks to Jo King
[Answer]
# [Python 3](https://docs.python.org/3/), ~~137~~ 78 + 37 = 115 bytes
*-22 bytes thanks to Jakque!*
Program A:
```
s='s=%r;exec(s[20:45])#print(end=open(0).read())\nprint(s%%s)';exec(s[20:45])#
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9hWvdhWtcg6tSI1WaM42sjAysQ0VlO5oCgzr0QjNS/FNr8gNU/DQFOvKDUxRUNTMyYPIlWsqlqsqY6u7f//xKRkAA "Python 3 – Try It Online")
And program B:
```
print(end=open(0).read())
print(s%s)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EIzUvxTa/IDVPw0BTryg1MUVDU5MLIlOsWqzJ9f9/YlIyV0pqGgA "Python 3 – Try It Online")
Make Quine AB!
```
s='s=%r;exec(s[20:45])#print(end=open(0).read())\nprint(s%%s)';exec(s[20:45])#print(end=open(0).read())
print(s%s)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9hWvdhWtcg6tSI1WaM42sjAysQ0VlO5oCgzr0QjNS/FNr8gNU/DQFOvKDUxRUNTMyYPIlWsqlqsqU60Ni6YrmJNrv//AQ "Python 3 – Try It Online")
Only works when input is empty, otherwise it prepends the input to the output.
[Answer]
# [C++ (clang)](http://clang.llvm.org/), 313 + 102 = 415 bytes
Program A (ends in a newline):
```
#include<cstdio>
#define Q(x,y)#x,B=#y;x
int c;auto I="#include<cstdio>",A=Q(int main(){if(c)printf("%s\n#define Q(x,y)#x\",\"#y;x\nint c;auto I=\"%s\",A=Q(%s,)\n#ifdef Q\nint n=++c;\n#else\n%s\n%s\n#endif",I,I,A,I,B);else while((c=getchar())>=0)putchar(c);},int c;int main(){while((c=getchar())>=0)putchar(c);})
```
Program B (does not end in newline):
```
#ifdef Q
int n=++c;
#else
#include<cstdio>
int c;int main(){while((c=getchar())>=0)putchar(c);}
#endif
```
Not terribly sneaky, and as usual C++ isn't that great for quining. I won't be surprised if there are ways to shave bytes here and there off the same idea. The one little catch is changing the behavior of something after it's been defined, and a dynamic variable initializer with side effect does the trick. (Can this even be done in C without compiler extensions?)
Try it online: [A](https://tio.run/##jZCxTsQwDIb3PoWV6qREzSGYGEpOutturMSYJbhJG8glpWm5HohXp6R0gZuQ5cH2/3@2jF23Rad8M8@59ejGWj9gHGobdllea2O9hopO/MLyiR9EfimnzPoBsFTjEOAoyLWN8L2o6KI5Kesp@7CGIuv61DGUbKL011xJuCQLWfo/aLmoV9wmcpaM1iQrVKvOi6LAMnW1i1r6hfxD1762hvBjin3KAysXAZxb6zSlKBo9YKt6ythO3LJuXCtk5Sdf1/@6/R8mls3zY6vhdbT4Ak99OHswYYLn8dTFLLzpHoY0dur9AnVobr7QONXEeZveJbAo7u6/AQ "C++ (clang) – Try It Online"), [B](https://tio.run/##JY1LDsIgGIT3nIKkGwip0ZWLSu9g4gXw51GUAhawPuLVxaqbSSbf5BuIsQUnvKm1sVoqjffI@ow9Zww61CiXFGqsB1ek2kHK0ob@t4Dum6OwntDnPFinCAFuVIZBTITSnq9pLP8GtHstLi@trvUwKHwpFs74OIXZYx1u@FTGmFC4qgnnBTvxuGMZzOoN2gmTarscc2Bss/0A "C++ (clang) – Try It Online"), [AB](https://tio.run/##nZDBT8MgGMXv/BWkzRJImdGTh8qS7bZjE49c8Cu0KINaWtdq/NetdI1Rt4sxhAMf7/3eA2iaNVjpqmlKjQPbl@oOQlcav0FpqbRxChdkYCNNB7bj6ZgPyLgOQy77zuM9T85tCdvygsyagzSO0DejCdCmjRNNklUQ7pwrEiaSmSzcL7SY1QtuFRiNRqOjFReLzvEsgzxOlQ1KuJl8oitXGp2wfVzbuHc0nwX4WBurCAFeqQ5q2RJKN/yaNv1yApq/syX@R/c/mCj6qoW@W6FTKXTxpf8JQMuLpum@Vvi5N/CEH1p/dFj7AT/2hyYg/6Ja3MVrK19HXPrq6gO0lVWY1jGYQ5bd3H4C "C++ (clang) – Try It Online")
(The only portability concern I'm aware of is that the program assumes `<cstdio>` puts names both in the global namespace and in `std`.)
[Answer]
# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 8 + 15 = 23 bytes
**A + B:** (only works for no input)
```
+9*5~,#@#@~,9j>:#,_:@#"
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X9tSy7ROR9lB2aFOxzLLzkpZJ97KQVnp/38A "Befunge-98 (FBBI) – Try It Online")
**A:**
```
+9*5~,#@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X9tSy7ROR9nh//@cxNKi8ox049yUjLKc/MzE0tSMpDJT4xKjfIuMpEQA "Befunge-98 (FBBI) – Try It Online")
**B:**
```
#@~,9j>:#,_:@#"
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X9mhTscyy85KWSfeykFZ6f///DwL85TKcmOTknwL8zwgLjfOL8m0yCsHAA "Befunge-98 (FBBI) – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 15 + 126 = 141 bytes
**A:**
```
AllInput[]|Echo
```
[Try it online!](https://tio.run/##SywpSUzOSP3/3zEnxzOvoLQkOrbGNTkj////SMcgdy6FlOI0rjTrRIXilDT1RCUA "Attache – Try It Online")
**B:**
```
@{If[_,s.="AllInput[]|Echo@{If[_,s.=%s;;Printf[s,Repr!s],AllInput[]|Echo]es}|Call";;Printf[s,Repr!s],AllInput[]|Echo]es}|Call
```
[Try it online!](https://tio.run/##SywpSUzOSP3/36HaMy06XqdYz1bJMSfHM6@gtCQ6tsY1OSMfIaNabG0dUJSZV5IWXawTlFpQpFgcq4OmOja1uLbGOTEnR4kEtVz//0c6BrlzKaQUp3GlWScqFKekqScqAQA "Attache – Try It Online")
**A + B:**
```
AllInput[]|Echo@{If[_,s.="AllInput[]|Echo@{If[_,s.=%s;;Printf[s,Repr!s],AllInput[]|Echo]es}|Call";;Printf[s,Repr!s],AllInput[]|Echo]es}|Call
```
[Try it online!](https://tio.run/##SywpSUzOSP3/3zEnxzOvoLQkOrbGNTkj36HaMy06XqdYz1YJp4xqsbV1QFFmXkladLFOUGpBkWJxrA6a6tjU4toa58ScHCUS1HL9/x/pGOTOpZBSnMaVZp2oUJySpp6oBAA "Attache – Try It Online")
## Explanation
Each of the cat program encodes `AllInput[]|Echo`, which is a simple cat program. **B** is the main quine phase; alone, it is a vectorized function (through unary `@`) called with no inputs (being called as `|Call`). Thus, the first conditional `If[_,A,B]` executes `B`, which is simply `AllInput[]|Echo`.
When **A + B** is executed, unary `@` becomes binary `@` due to `Echo` merging with the lambda:
```
AllInput[]|Echo@{If[_, ...
```
Now, this means that the lambda is executed before `Echo` is. Back to the conditional, this function now has all of STDIN as an argument. So, `If[_,A,B]` executes `A`, which is the standard quine framework.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 + 12 = 28 bytes
Cat 1:
```
"yi|d|ca34b4lr"y
```
[Run and debug it](https://staxlang.xyz/#c=%22yi%7Cd%7Cca34b4lr%22y&i=%22sdasdnjek%22)
```
"yi|d|ca34b4lr"y Full program, implicit input
"yi|d|ca34b4lr" Push the string
y Push raw input
Implicit output of top item
```
Cat 2:
```
i|d|ca34b4lr
```
[Run and debug it](https://staxlang.xyz/#c=i%7Cd%7Cca34b4lr&i=%22sdasdnjek%22)
```
i|d|ca34b4lr Full program, implicit input
i Don't parse input (prefix directive)
|d Push main stack depth, always zero
|c Cancel because top item is falsy, and implicitly print
a34b4lr Never executed
```
Quine:
```
"yi|d|ca34b4lr"yi|d|ca34b4lr
```
[Run and debug it](https://staxlang.xyz/#c=%22yi%7Cd%7Cca34b4lr%22yi%7Cd%7Cca34b4lr&i=%22sdasdnjek%22)
```
"yi|d|ca34b4lr"yi|d|ca34b4lr Full program
"yi|d|ca34b4lr" Push the string
y Push input
i No-op
|d Push main stack depth, i.e. 2
|c Do nothing because top is truthy
a Get the string to the top
34 Push 34 (charcode of ")
b Copy both
4l Listify top 4
r Reverse
Implicit output
```
[Answer]
# Cat 1 :
# [Lua](https://www.lua.org), 41 bytes
```
a=io.read;while a(0)do io.write(a(1))end;
```
[Try it online!](https://tio.run/##yylN/P8/0TYzX68oNTHFujwjMydVIVHDQDMlXwEoWF6UWZKqkahhqKmZmpdi/f9/cn5Kanp@ThoA "Lua – Try It Online")
---
# Cat 2 :
# [Lua](https://www.lua.org), 70 bytes
```
if a then io.input(arg[0])end;a=io.read;while a(0)do io.write(a(1))end
```
[Try it online!](https://tio.run/##FcoxCsAgDADAr2TUpdhZ@pLSIZhUA2KKVXy@retxueOccgNCS1xAdJPy9GawxtNdlgt5PH6tjORHksyAxlnSVUeVxgbNblec8@WghSAocdR8fw "Lua – Try It Online")
---
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 12 +3 = 15 bytes
Program A:
```
<oi
```
[Try it online!](https://tio.run/##S8sszvj/3yY/8///xKRkAA "><> – Try It Online")
And Program B:
```
>i!o|o<}*d3'
```
[Try it online!](https://tio.run/##S8sszvj/3y5TMb8m36ZWK8VY/f//xKRkAA "><> – Try It Online")
Make Program AB:
```
<oi>i!o|o<}*d3'
```
[Try it online!](https://tio.run/##S8sszvj/3yY/0y5TMb8m36ZWK8VY/f//xKRkAA "><> – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 26 + 71 = 97 bytes
## Cat 1 (26 bytes):
```
id=print(open(0).read());
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/nyszxbagKDOvRCO/IDVPw0BTryg1MUVDU9P6///g/NxUhcy8gtKSYq60/CKFkoxUheTEEoWCovz0osRcAA "Python 3.8 (pre-release) – Try It Online")
## Cat 2 (71 bytes):
```
exec(s:='id=print(open(0).read()if id else s[:23]+");exec(s:=%r)"%s)')
```
[Try it online!](https://tio.run/##NcvBCsIwDADQ@74iDMYaBBF3kcm@wuPwUNbMFVwTkgju6@vJd39y@MZluInWSl9ago1Tn9MkmosHFirhgmelmALmFXICehuBzeN1eJ5avP9Tp9h2hj02tT54J8hFPm7Nygq@ESzRQZRfGvcf "Python 3.8 (pre-release) – Try It Online")
## Quine = Cat 1 + Cat 2 (97 bytes):
```
id=print(open(0).read());exec(s:='id=print(open(0).read()if id else s[:23]+");exec(s:=%r)"%s)')
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/nyszxbagKDOvRCO/IDVPw0BTryg1MUVDU9M6tSI1WaPYylYdh4rMNIXMFIXUnOJUheJoKyPjWG0lhCbVIk0l1WJNdU2u//8B "Python 3.8 (pre-release) – Try It Online")
## How it works:
Cat 1:
* `open(0).read` reads the STDIN
* `id=print(...)` prints it and returns `None` which will be stored into `id` (remember it for later)
Cat 2:
* `<instructions for cat> if id else <other instuctions>` will execute `<instructions for cat>` because `id` is a built-in and is evaluated as `True`.
Quine:
* Because of Cat 1, id is now equal to `None` and `<instructions for cat> if id else <other instuctions>` will now execute `<other instructions>`
* Because both our program have the same structure for cat, we print the cat part of Cat 2 for quining cat1 : `s[:23]+");`
* Then the programm is just a variant of `exec(s:='print("exec(s:=%r)"%s)')`, a quine in Pyhton 3.8+
## Notes:
Both my cat programs add a trailing new line at the end. I assume that it was accepted since it wasn't frormally banned and since most of the cat challenges accept it.
Otherwise I have a 103 bytes solution which doesn't add trailing newlines:
```
id=print(end=open(0).read()); #Cat1
exec(s:='id=print(end=open(0).read()if id else s[:27]+");exec(s:=%r)"%s)') #Cat2
id=print(end=open(0).read());exec(s:='id=print(end=open(0).read()if id else s[:27]+");exec(s:=%r)"%s)') #Quine
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzPFtqAoM69EIzUvxTa/IDVPw0BTryg1MUVDU9M6tSI1WaPYylYdj6rMNIXMFIXUnOJUheJoKyPzWG0lhEbVIk0l1WJNdc3//wE "Python 3.8 (pre-release) – Try It Online")
### Bonus:
Here is a solution in 116 bytes which accepts not-empty input for the quine program:
```
while 1:id or print(input());id=0; #Cat1
exec(s:='id or~input(s[36:]+"exec(s:=%r)"%s)\nwhile 1:id or print(input());id=0;') #Cat2
while 1:id or print(input());id=0;exec(s:='id or~input(s[36:]+"exec(s:=%r)"%s)\nwhile 1:id or print(input());id=0;') #Quine
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/vzwjMydVwdAqM0Uhv0ihoCgzr0QjM6@gtERDU9M6M8XWwDq1IjVZo9jKVh2spA4iWRxtbGYVq60Ek1Qt0lRSLdaMySNsnrrm//@ZJQrl@UXZxVypZal5CuWZJRkKYEXFAA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) 0XX, 6 + 7 = 13 bytes
*Works in 000, 001, 010 and 011.*
*Note that these answers all contain the unprintible byte 17, or "device control 1".*
## Cat 1
```
<:2*@
```
[Try it online!](https://tio.run/##y85Jzcz7/1/QxspIy@H///@6yf8NDAz@e2QCAA "Klein – Try It Online")
The `<` redirects the pointer off the left. It appears on the right at `@` and halts immediately spilling its input as output.
## Cat 2
```
@*2:<"
```
[Try it online!](https://tio.run/##y85Jzcz7/99By8jKRlDp////usn/DQwM/ntkAgA "Klein – Try It Online")
It immediately encounters `@` and halts with no further execution. It outputs the input with no changes.
## Quine
```
<:2*@@*2:<"
```
[Try it online!](https://tio.run/##y85Jzcz7/1/QxspIy8FBy8jKRlDp////usn/DQwMAA "Klein – Try It Online")
Like **cat 1** this first encounters `<` which sends it off the left and onto the right. But this time on the right we encounter `"` which puts us into string mode. This causes us to push the entire program (minus the quote) to the stack *backwards*. In order to make things easier for myself this part of the program is a palindrome, so we don't have to reverse it. Now we just need to add the `"` at the end. The program begins with a , which is chosen because multiplying it by 2 gives us `"`. So we duplicate and multiply by two to make the `"` and exit at `@`.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `ajṠ`, 13 + 1 = 14 bytes
**A:** ([Try it Online!](http://lyxal.pythonanywhere.com?flags=aj%E1%B9%A0&code=%60%3Aqpw%24%24%60%3Aqpw%24&inputs=This%20is%20a%0A%60cat%60%0Aprogram%0A%5B%5D&header=&footer=))
```
`:qpw$$`:qpw$
```
**B:** ([Try it Online!](http://lyxal.pythonanywhere.com?flags=aj%E1%B9%A0&code=%24&inputs=This%20is%20a%0A%60cat%60%0Aprogram&header=&footer=))
```
$
```
**A + B:** ([Try it Online!](http://lyxal.pythonanywhere.com?flags=aj%E1%B9%A0&code=%60%3Aqpw%24%24%60%3Aqpw%24%24&inputs=This%20is%20a%0A%60cat%60%0Aprogram%0A%5B%5D&header=&footer=))
```
`:qpw$$`:qpw$$
```
## Explained
```
`:qpw$$`:qp # Modified standard Vyxal quine
w # Wrap quine in array, so join on newline works
$ # Swap the quine and the input
$ # Swap
# If the program is standalone, this does nothing
# If concatenated, this undoes the previous swap and puts the quine at the top
```
* `a`: Push entire input split on newlines to the top of the stack
* `j`: Join top of stack on newlines and output (undo split from `a`)
* `Ṡ`: Treat all inputs as strings, so proper output is given for inputs like `[]` and `""`
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 199 bytes
```
a=()=>console.log(require('fs').readFileSync(0)+'');a();var a=a||0;b=()=>console.log(require('fs').readFileSync(0)+'');!a?b():c=()=>console.log(`a=${a};a();var a=a||0;b=${b};!a?b():c=${c},c()`),c()
```
[Try it online!](https://tio.run/##nY1BDsIgEADvfYUmJOxGbXqWoDc/4Ae6bNFgSFHQJobydownD715mdvM3GiixNHdn7sxDLbWhjSgPnAYU/C29eEK0T5eLlqQlySxjZaGk/P2/B4ZOtxIiYoA1URxRZrmuVPmj8SajgZwzwu1Jy0yleVDZFN@mshctgzY45dNrR8 "JavaScript (Node.js) – Try It Online")
## Cat A, 57 bytes
```
a=()=>console.log(require('fs').readFileSync(0)+'');a();
```
[Try it online!](https://tio.run/##BcExDoAgDADA3Ve4tY2RuBMc/YAvaKAaDAEFNfH19e7gl5uv8bzHXIKoduyQ3OxLbiWJSWXHKtcTqyBsDchU4bDEJOuXPU40AJBlJKvq@e75Bw "JavaScript (Node.js) – Try It Online")
## Cat B, 142 bytes
```
var a=a||0;b=()=>console.log(require('fs').readFileSync(0)+'');!a?b():c=()=>console.log(`a=${a};a();var a=a||0;b=${b};!a?b():c=${c},c()`),c()
```
[Try it online!](https://tio.run/##Zc1BCsIwEEDRvaeoEMgMaunaEN15AS/QyTRKJCSa1IK0OXvElYibv3v8G02UObn7uAtxsLVOlBrStCydMhpQHziGHL1tfbxCso@nSxbkJUtsk6Xh5Lw9vwJDhxspUa3paAD3/Ed70mKmoghQ/TzEbMqXiZnLlgF7/HRVK9PYmDc "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
You will be given a positive, whole number (that will never contain a 0) as input. Your task is to check whether it is a Lynch-Bell number or not.
A number is a Lynch-Bell number if all of its digits are unique and the number is divisible by each of its digits.
In fact, there are actually only 548 Lynch-Bell numbers, so hard-coding is a possibility, but will almost certainly be longer.
126 is a Lynch-Bell number because all of its digits are unique, and 126 is divisible by 1, 2, and 6.
You can output any truthy and falsy value.
## Examples:
```
7 -> truthy
126 -> truthy
54 -> falsy
55 -> falsy
3915 -> truthy
```
This is [OEIS A115569](https://oeis.org/A115569).
[Answer]
## Mathematica, 42 bytes
```
0!=##&@@d&&##&@@((d=IntegerDigits@#)∣#)&
```
I think `0!=##&@@d&&##&@@` is a new low in readability for Mathematica...
### Explanation
Some of the basic syntactic sugar used here:
* `&` has very low precedence and turns everything left of it into an unnamed function.
* `&&` is just the `And` operator.
* `#` is the argument of the nearest enclosing unnamed function.
* `##` is a *sequence* of all of the function's arguments.
* `@` is prefix notation for function calls, i.e. `f@x == f[x]`.
* `@@` is `Apply`, which passes the elements of a list as individual arguments to a function, i.e. `f@@{a,b,c} == f[a,b,c]`.
With that out of the way...
```
(d=IntegerDigits@#)
```
This should be fairly self-explanatory: this gives us a list of the input's decimal digits and stores the result in `d`.
```
(...∣#)
```
This tests the input for divisibility by each of its digits (because the divisibility operator is `Listable`). This gives us a list of `True`s and `False`s.
```
...&@@...
```
We apply the function on the left-hand side to the list of booleans, such that each boolean is a separate argument.
```
...&@@d
```
We apply another function to `d`, so that the individual digits are given as separate arguments. The function is `0!=##&`, i.e. `Unequal[0, d1, d2, ...]`. It checks that all the digits are distinct (and that they are distinct from `0` but that's given by the challenge, and if it wasn't, it wouldn't be a divisor anyway). `0!=##&` is really just a 1-byte saver on using `Unequal` itself, and it works because there's a 1-byte element (`0`) that we know is not present. So this first thing checks that the digits are unique. Let's call this result `U`
```
...&&##
```
Again, this is really just shorthand for `And[U, ##]`. With `##` being a sequences, the individual booleans from the initial divisibility check are expanded into the `And`, so we get `And[U, d1∣n, d2∣n, ...]` which checks that both the digits are unique and each digit divides the input.
[Answer]
# [Python 3](https://docs.python.org/3/), 56 bytes
```
lambda n:any(int(n)%int(x)for x in n)or len(n)>len({*n})
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjGvUiMzr0QjT1MVRFVopuUXKVQoZOYp5GkCWTmpeUApOxBVrZVXq/m/oAikLE1D3VxdU5MLzjM0MkPhm5qgck1RuMaWhiCB//8B "Python 3 – Try It Online")
Output `False` if it's IS a Lynch-Bell number, `True` otherwise.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 4 bytes
```
Dg⁼Q
```
[Try it online!](https://tio.run/##y0rNyan8/98l/VHjnsD/R/ccbn/UtMb9/39zHQVDIzMdBVMTIDbVUTC2NDQFAA "Jelly – Try It Online")
### How it works
```
Dg⁼Q Main link. Argument: n
D Decimal; convert n to base 10.
g Take the GCD of each decimal digit k and n.
For each k, this yields k if and only if k divides n evenly.
Q Unique; yield n's decimal digits, deduplicated.
⁼ Test the results to both sides for equality.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
≠g;?z%ᵐ=h0
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HngnRr@yrVh1sn2GYY/P9vbGlo@h8A "Brachylog – Try It Online")
### Explanation
```
≠ All digits are different
g;?z Zip the input with each of its digits
%ᵐ Map mod
= All results are equal
h0 The first one is 0
```
[Answer]
# C#, ~~87~~ 83 bytes
```
using System.Linq;s=>s.Distinct().Count()==s.Length&s.All(c=>int.Parse(s)%(c-48)<1)
```
I wrote this in notepad before testing in Visual Studio, where it worked fine, so just realised I'm now that level of nerd...
Full/Formatted Version:
```
using System;
using System.Linq;
class P
{
static void Main()
{
Func<string, bool> f = s => s.Distinct().Count() == s.Length
& s.All(c => int.Parse(s) % (c - 48) < 1);
Console.WriteLine(f("7"));
Console.WriteLine(f("126"));
Console.WriteLine(f("54"));
Console.WriteLine(f("55"));
Console.WriteLine(f("3915"));
Console.ReadLine();
}
}
```
[Answer]
## JavaScript (ES6), ~~42~~ 41 bytes
```
s=>![...s].some((e,i)=>s%e|s.search(e)<i)
```
Takes input as a string and returns `true` or `false` as appropriate. Edit: Saved 1 byte thanks to @RickHitchcock. Other versions:
Takes input as a string and returns `0` or `1` (i.e. logical inverse) for 40 bytes:
```
s=>/(.).*\1/.test(s)|[...s].some(e=>s%e)
```
Takes input as a number and returns `0` or `1` for 43 bytes:
```
n=>/(.).*\1/.test(n)|[...''+n].some(e=>n%e)
```
Takes input as a number and returns `1` or `0` for 45 bytes:
```
n=>!/(.).*\1/.test(n)&![...''+n].some(e=>n%e)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
ÑÃÙQ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MTDzYdnBv7/b2xpaAoA "05AB1E – Try It Online")
Same algorithm as [this answer to a related question](https://codegolf.stackexchange.com/a/164415/6484).
[Answer]
# [Python 3](https://docs.python.org/3/), 54 bytes
Returns `False` when a number is a Lynch-Bell number. Takes strings as input. Came up with on my own but very similar to Rod's. I would've commented under his post but I don't have any reputation yet.
```
lambda s:len({*s})<len(s)+any(int(s)%int(c)for c in s)
```
[Try it online!](https://tio.run/##VY3BDoIwEETvfMVeTLt6oSIaif6Jl4pUm@CWtDUpMX57paBG5rL7JpOZrvc3Q0VUx1Ns5f18keCqtiH@XLoXHtLncCWp55r88C7SqVEZCzVoAoexs8lTnO0YYvYjsd7OuNzMsZxhsRejkaXmkJqtpGvDRZ5jlcEgrYDlbNz0loePm1Qb8poezTdGxoPiU@ovNm0FjPEN "Python 3 – Try It Online")
[Answer]
# Regex (ECMAScript), ~~194~~ ~~171~~ ~~167~~ ~~164~~ ~~155~~ ~~145~~ ~~142~~ 107 bytes
*-35 bytes (142 → 107) [thanks to H.PWiz](https://chat.stackexchange.com/transcript/message/57535240#57535240); this is a complete reimplementation. The primary sources of bytes saved are using* `tail = floor((tail + Digit) / 10) - Digit` *instead of* `tail = floor(tail / 10)` *, and "factoring" the assertions – reusing the expression at the end to mean two different things.*
`^(?!(x{1,9})(((?=(x*)((\1\4){9}x*))\5)*(?=(x*)(\7{9}$))\8\1|(?!\1*$))((?=(x*)((\1\10){9}x*))\11)*(x{10})*$)`
[Try it online!](https://tio.run/##VY9PU8IwEMW/CnScstvSP3FAhRo4efDCQY9WZzIQ2mhIO0mASulnr@GAo7d97/fe7uwnOzCz1qK2kanFhutdpb74d6@p4sfBCy@emhrgRBdJ0H/AcghNS8azDgFgSaEJ3JCTfILtrHMC8ykGV5DfO/PGeQ85ObtqTgKn/vVI@lskxDXd8rRDF@uD5ISxrV6tFqoAjI0Uaw5342iCmBmaZsdSSA4gqeZsI4XigDikai8ltgWVsamlsDCKRpiJLYCiRSy5KmyJi9vzWZgVW4GgNdOGPysLxVv6jngF/C9QC7Ik8wtGW@rq6D2rA5NiM9BMFXw@8EKZbSsNmXikPBNhiO7gEEToeRjvmF2XkKQJ@r7XeLHmNWcWxJVoxNb4fu3etHD5jGT13hqrXSTrup5EZJqmPw "JavaScript (SpiderMonkey) – Try It Online")
Takes its input in unary, as a sequence of `x` characters whose length represents the number.
This was an interesting challenge to solve without molecular lookahead or variable-length lookbehind. The restrictions result in a completely different algorithm being used.
Note that the above version does not reject numbers that have a zero as at least one of their digits, as per the challenge's rules. It costs ~~2 bytes~~ 10 bytes to handle zero correctly, for a total of **~~144~~ 117 bytes**:
`^(?!(x{0,9})(((?=(x*)((\1\4){9}x*))\5)*(?=(x*)(\7{9}$))\8\1|(?!\1*$))((?=(x*)((\1\10){9}x*))\11)*((x{10})+|(?!\1))$)x`
[Try it online!](https://tio.run/##VY9BU8IwEIX/CnQY2G1paRxQoQZOHrxw0KPVmQyENhrSTBKgAv3tNYyDo7d973tvd/aD7ZldGaFdbLVYc7Ot1Cf/ag1V/NB55sVjrQGOdD4K23dYdKE@pcNpgwCwoFCHfshJPsbTtPEC8wmGV5DfebPnvfucnH01J6FX/3ok/S0S4pt@O0kbjH7iiD2s23B0xMRVL84IVQAmVooVh9thPEbMLE2zQykkB5DUcLaWQnFA7FK1kxJPBZWJ1VI4GMQDzMQGQNEikVwVrsT5zfks7JItQVDNjOVPykHxmr4hXgH/C9ScLMjsgtGVpjoET2rPpFh3DFMFn3WCSGabykAmHijPRBShPxjUQWK45syBwGTL3KoEg3iy/b72Lzm4fEEyvXPWGR/JmqZNYzJJ028 "JavaScript (SpiderMonkey) – Try It Online")
The commented version below describes the **~~144~~ 117 byte** version:
```
^ # tail = N = input number
(?! # Negative lookahead - Assert that there's no way for the following to match:
(x{0,9}) # \1 = conjectured digit; tail -= \1
# Assert one of the following two alternatives:
(
# Assert that \1 occurs as a digit of N, and chop it away (and all the digits
# right of it) from tail, returning only the digits left of its found instance.
(
(?=
(x*)((\1\4){9}x*) # \4 = floor((tail + \1) / 10) - \1;
# \5 = tool to make tail = \4
)
\5 # tail = \4
)*
(?=
(x*)(\7{9}$) # assert tail % 10 == 0; \7 = tail / 10;
# \8 = tool to make tail = \7
)
\8\1 # tail = \7 - \1 (all the digits of N left of where \1
# was found, minus \1)
|
# Assert that \1 is not a divisor of N
(?!\1*$)
)
# Assert that \1 occurs as a digit in tail+\1, which will either be a second occurrence
# found further left in N of an already-found occurrence, or any occurrence of a digit
# that is not a divisor of N.
(
(?=
(x*)((\1\10){9}x*) # \10 = floor((tail + \1) / 10) - \1;
# \11 = tool to make tail = \10
)
\11 # tail = \10
)*
# Assert one of the following two alternatives:
(
# Assert tail > 0 and tail % 10 == 0, which means we've found an occurrence of \1
# that isn't the leftmost digit
(x{10})+
|
# Assert tail == 0 and tail != \1, which means we've found that \1 is the leftmost
# digit of N and \1 != 0 (which needs to be asserted, otherwise we'd always find
# a phantom occurrence of the digit 0 left of the leftmost digit of N)
(?!\1)
)$
)
x # Prevent N=0 from being matched
```
The version above is very slow, so I'm keeping my **144 byte** solution here:
`^(?!(?=(x*)\1{9})(x{0,9})(?=(x{10})*$|(.*(?=\1$)((?=(x*)(\6{9}x*))\7)*?\B(?=(x*)(\8{9}\2$))\9))((?!\2*$)|\4((?=(x*)(\12{9}x*))\13)*\2(x{10})*$))`
[Try it online!](https://tio.run/##TY/NbsIwEIRfBRCC3UBCnCJaSE2kSj1w4dAe61aywCRujRPZ5qckPDtNpEJ72t35ZjWaT77ndmVk4XxbyLUw21x/ie@LoVocWi8ifT4WACc6H3mXD0jakFA4eshIOT0jHMtw2MxGLEl4Rq9bQeDVNyNdhF8zsEntrhdk9@gl7OmmP9Q6i7o1mGJjb7PI62LFxn@vJLr@kjv0WHQLQrx4oxMGLn91RuoUMLBKrgRMhv4YMbY0jA@ZVAJAUSP4WkktALFN9U4pLFOqAlso6aDv9zGWGwBN00AJnboM51FVSbvkS5C04MaKhXaQvoXviFcg/gM9JwmZNRhdZvJDZ6H3XMl1y3CdilmrM1DxJjcQy0cqYjkYYB3YOXYCIwrBHUgMttytMjCIpe31irqSg6YFiYuds87Ulvh8voR@FIbhDw "JavaScript (SpiderMonkey) – Try It Online")
```
^ # tail = N = input number
(?! # Negative lookahead - Assert that there's no way for the following to match:
(?=(x*)\1{9}) # \1 = floor(N / 10)
(x{0,9}) # \2 = take a guess at a numeral that may occur as any
# digit of N, even the rightmost one; tail -= \2
# Assert that \2 occurs as a digit in N, and if it does, identify the rest of N to
# the left of that digit, so that we can set tail equal to it later (so we can later
# assert that \2 is not duplicated).
(?=
(x{10})*$ # Skip the rest if we picked the rightmost digit of N
|
( # \4 = tool to make tail = \8
.*(?=\1$) # tail = \1
# Loop through chopping away each rightmost decimal digit of tail, one by one
(
(?=
(x*) # \6 = floor(tail / 10)
(\6{9}x*) # \7 = tool to make tail = \6
)
\7 # tail = \6
)*? # Only iterate until we find the first match of the
# following:
\B # Leave at least one digit remaining (to avoid
# thinking we've found a zero-digit when there isn't
# actually one)
(?=(x*)(\8{9}\2$)) # \8 = floor(tail/10); \9 = tool to make tail = \8;
# assert that tail % 10 == \2, i.e. that our guessed
# digit matches the current rightmost digit of tail
\9 # tail = \8
)
)
# \2 is now one of the decimal digits of N.
# Assert that either of the following two alternatives could match, and in the
# context outside of the negative lookahead, that neither of them can match:
(
# Assert tail is not divisible by \2. It doesn't matter that tail == N-\2
# instead of N, because that doesn't alter tail's divisibility by \2.
(?!\2*$)
| # or...
# Assert that \2 doesn't occur as any decimal digit left of where it was found
\4 # tail = \8 if \8 is set, otherwise no change; this
# relies on ECMAScript NPCG behavior.
# Chop away any number (minimum 0) of rightmost decimal digits of tail
(
(?=(x*)(\12{9}x*)) # \12 = floor(tail / 10);
# \13 = tool to make tail = \12
\13 # tail = \12
)* # Iterate any number of times, minimum 0
\2 # tail -= \2
(x{10})*$ # assert tail is divisible by 10
)
)
```
# Regex (ECMAScript + `(?*)`), 81 bytes
`^(?!(?*(((?=(x*)(\3{9}(x*)))\4)+))((?!\5+$)|\1((?=(x*)(\8{9}x*))\9)*\5(x{10})*$))`
This challenge is much easier to solve with molecular lookahead; it's the version I implemented first.
Working on this alerted me to the presence of a bug in my regex engine [(now fixed)](https://github.com/Davidebyzero/RegexMathEngine/issues/6).
```
^ # tail = N = input number
(?! # Negative lookahead - Assert that there's no way for the following to match:
(?* # Molecular lookahead - cycle through all possible matches of the following:
( # \1 = tool to make tail = the final value of \3
# Loop through chopping away each rightmost decimal digit of tail, one by one
(
(?=(x*)(\3{9}(x*))) # \3 = floor(tail / 10); \4 = tool to make tail = \3;
# \5 = tail % 10
\4 # tail = \3
)+ # Iterate at least once, otherwise \5 could be unset
# The above loop relies on ECMAScript no-empty-optional behavior. This
# prevents it from matching when the final result of zero is again divided
# by 10, which would yield a value of \5 = 0, making it look like one of N's
# digits was zero and preventing all values of N from matching.
)
)
# \5 is now one of the decimal digits of N, and tail==N again
# Assert that either of the following two alternatives could match, and in the context
# outside of the negative lookahead, that neither of them can match:
(
(?!\5+$) # Assert tail is not divisible by \5
| # or...
# Assert that the \5 doesn't occur as any decimal digit left of where it was found
\1 # tail = \3
# Chop away any number (minimum 0) of rightmost decimal digits of tail
(
(?=(x*)(\8{9}x*)) # \8 = floor(tail / 10); \9 = tool to make tail = \8;
\9 # tail = \8
)* # Iterate any number of times, minimum 0
\5 # tail -= \5
(x{10})*$ # assert tail is divisible by 10
)
)
```
# Regex (ECMAScript 2018), 85 bytes
`^(?!((?=(x*)(\2{9}(x*)))\3)+((?<=(?=(?!\4+$))^.*)|((?=(x*)(\7{9}x*))\8)*\4(x{10})*$))`
[Try it online!](https://tio.run/##TY5NT8JAEIb/ijQmO0Nh0yKJSll68sCFgx6thE27lDHrtu4uH0npb6@tiZHbm3memXk/5Um63FLtp6YqVOdElFjxqsqXSw1v3pIpuZXnXbeFdASQCriMEbJZ89wOCTF7wLCfL8XA0lE2D@8Rt3yM13/7sbcHOXvCcTaHSxNHLY57r9txpylXEE@mMWJi1feRrAJmlSw0GcWQ5332am28snvZqw2Z@ugXta1y5Rx3viDTIq8MsN@NiRarphSau1qTBzZlmNAewIiSa2VKf8DV7Holt5EbIFFL64brUL5HH4h/QN0Cs4rTeDFg9AdbnYO1OUlNxZ2VplSLuyDUyb6ykNBSqITCEPuHwSXgVtV9eSDkX9LnB7CIzU3x6uj52ZJXAC5lmWELxjAkTJyIk7bFLprOoij6AQ "JavaScript (Node.js) – Try It Online")
This is a port of the molecular lookahead version. The most direct port would be replacing `(?*A)B` with `A(?<=(?=B)^.*)`, but that would result in an 89 byte regex.
```
^ # tail = N = input number
(?! # Negative lookahead - Assert that there's no way for the following to match:
# Loop through chopping away each rightmost decimal digit of tail, one by one
(
(?=(x*)(\2{9}(x*))) # \2 = floor(tail / 10); \3 = tool to make tail = \2;
# \4 = tail % 10
\3 # tail = \2
)+ # Iterate at least once, otherwise \4 could be unset
# The above loop relies on ECMAScript no-empty-optional behavior. This prevents it
# from matching when the final result of zero is again divided by 10, which would
# yield a value of \4 = 0, making it look like one of N's digits was zero and
# preventing all values of N from matching.
# \4 is now one of the decimal digits of N, and tail==\2
# Assert that either of the following two alternatives could match, and in the context
# outside of the negative lookahead, that neither of them can match:
(
(?<= # Variable-length lookbehind - used to go back to start
(?=
# now tail==N again
(?!\4+$) # Assert tail is not divisible by \4
)
^.* # Go back to start, then execute the above lookahead
)
| # or...
# now tail==\2
# Assert that the \4 doesn't occur as any decimal digit left of where it was found
# Chop away any number (minimum 0) of rightmost decimal digits of tail
(
(?=(x*)(\7{9}x*)) # \7 = floor(tail / 10); \8 = tool to make tail = \7;
\8 # tail = \7
)* # Iterate any number of times, minimum 0
\4 # tail -= \4
(x{10})*$ # assert tail is divisible by 10
)
)
```
[Answer]
# [Scratch](https://scratch.mit.edu/), 249 bytes
[Try it online!](https://scratch.mit.edu/projects/513627304/)
I feel as though this could be improved by a few bytes, but I'm not sure...
```
when gf clicked
ask()and wait
set[C v]to()
set[N v]to(answer
repeat(length of(n
change[C v]by(1
add(letter(C)of(N))to[B v
end
say[T
repeat(C
set[D v]to(item(1)of[B v
delete(1)of[B v
if<<[B v]contains(D)?>or<not<((N)/(D))=(round((N)/(D)))>>>then
say(
```
Alternatively, 34 blocks.
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
[:(<.-:~.)10&#.%]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600bPR0rer0NA0N1JT1VGP/a3L5OekpaNiqKQMFtQxsDZX1atSU9JSq67i4UpMz8hXUQ4pKSzIq1SG8NAVjBUsFQwVTGFfHSsEcxjZUMFIwg2lzS8wpTkVoM1UwUUCwTRX@AwA "J – Try It Online")
Take input as list of digits.
* `10&#.%]` The list of quotients. Returns floats.
* `(<.-:~.)` Does the unique of that list `~.` match `-:` the list formed by rounding every element down to an integer `<.`?
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
D⁼QaDḍ$Ạ
```
[Try it online!](https://tio.run/##y0rNyan8/9/lUeOewESXhzt6VR7uWvD//39DIzMA "Jelly – Try It Online")
[Answer]
# PHP, ~~62~~ 48 bytes
```
while($i=$argn[$k++])$r|=$argn%$i|$$i++;echo!$r;
```
Run as pipe with `-nR` or [test it online](http://sandbox.onlinephpfunctions.com/code/4bb7b82d9f391bb8862ca1308d60c3c6717bb43f). Empty output for falsy, `1` for truthy.
**breakdown**
```
while($i=$argn[$k++]) # loop through digits
$r|= # set $r to true if
$argn%$i # 1. number is not divisible by $i
|$$i++; # 2. or digit has been used before
echo!$r; # print negated $r
```
[Answer]
# [Haskell](https://www.haskell.org/), 61 bytes
```
(#)=<<show
(d:r)#n=notElem d r&&mod n(read[d])<1&&r#n
_#_=0<3
```
[Try it online!](https://tio.run/##ZcrBCoIwGADg@57ih8VQmNCaK4rtICFeIrx0KpHBFCW3yRQ6RM@@unf@vkEvz26a4jvDcCmu1a2oSjjXNeDsg3r1iAlOlZTL4F8oMaeQYqecX8ups2AgEGK9AZeETpu7aVLJCAnYoRa3ait5tHp0oMB4BDCH0a2wAatn6OF@oGy3p/zIRPOPIqdCUMZ/h@esiV8 "Haskell – Try It Online")
Defines an anonymous function `(#)=<<show` which, given a number, returns `True` or `False`.
[Answer]
# [ruby -n](https://www.ruby-lang.org/), 40 bytes
```
p gsub(/./){$'[$&]||$_.to_i%$&.hex}<?0*8
```
[Try it online!](https://tio.run/##KypNqvz/v0Ahvbg0SUNfT1@zWkU9WkUttqZGJV6vJD8@U1VFTS8jtaLWxt5Ay@L/f3MuQyMzLlMTLlNTLmNLQ1MuSwszc2NDo3/5BSWZ@XnF/3XzAA "Ruby – Try It Online")
Read in the number as a string. Substitute each character (digit) with a subsequent occurrence of that character, if present, or the whole number modulo that digit. This will result in a string of only `0`s if and only if this is a Lynch-Bell number. Why? If there's a repeated digit, every instance of the last stays the same, and since the input doesn't contain zeroes that means a non-zero digit. Otherwise, we're just checking whether every digit evenly divides the number.
Since there are no 8-or-more-digit Lynch-Bell numbers (formal proof: OEIS says so), checking whether the resulting string is lexicographically earlier than the string `'00000000'` is equivalent to checking whether it's all zeroes.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~15~~ ~~14~~ ~~11~~ ~~10~~ 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ì®yUÃ¥Uìâ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7K55VcOlVezi&input=WzcsMTI2LDU0LDU1LDM5MTVdCi1t)
[Answer]
# Excel, ~~76~~ 74 bytes
*-2 bytes using `ROWS` instead of `COUNTA`*
```
=LET(n,LEN(A2),d,MID(A2,SEQUENCE(n),1),AND(ROWS(UNIQUE(d))=n,MOD(A2,d)=0))
```
[Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnBGANF6irExkYlu-?e=dn5d5s)
```
LET( 'Assign Variables
n,LEN(A2) ' n = # of digits
d,MID(A2,SEQUENCE(n),1) ' d = array of digits
AND(ROWS(UNIQUE(d))=n,MOD(A2,d)=0) 'Result
ROWS(UNIQUE(d))=n ' # unique d = n
MOD(A2,d)=0 ' number mod d = 0
AND( ) ' and all tests
```
Original
```
=LET(n,LEN(A2),d,MID(A2,SEQUENCE(n),1),AND(COUNTA(UNIQUE(d))=n,MOD(A2,d)=0))
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 22 bytes
```
{&/~(t*t~?t:10\x)!\:x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpNv06jRKukzr7EytAgpkJTMcaqovZ/mrq5gqGRmYKpiYKpqYKxpaHpfwA "K (ngn/k) – Try It Online")
* `(...t:10\x)` get the individual digits of the input, storing in `t`
* `(t*t~?t...)` if the digits aren't all unique, multiply them by 0 (otherwise leave them as-is)
* `(...)!\:x` mod the input by each of the digits (with `x mod 0` == `x`)
* `&/~` are all the remainders 0?
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 57 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.125 bytes
```
:₌Kf↔$f⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiOuKCjEtm4oaUJGbigbwiLCIiLCIxMjciXQ==)
Bitstring:
```
010100100010101011101010110011110100011101011011111010110
```
[Answer]
# [Uiua](https://uiua.org), 13 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
≍⊝⌊.÷-@0$"_".
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4omN4oqd4oyKLsO3LUAwJCJfIi4K4oi1ZiA3XzEyNl81NF81NV8zOTE1)
Not too bad, given the bulky syntax to convert a number into its decimal digits. The main idea is taken from [alephalpha's Nekomata answer](https://codegolf.stackexchange.com/a/266132/78410).
Note: the symbol for "match" (test if two arrays are structurally equal as a whole) has been changed from `≅` to `≍`.
Also, this code doesn't work when the input contains a 0, because division by 0 gives NaN, floor of NaN is still NaN, and two NaNs are equal.
```
≍⊝⌊.÷-@0$"_". input: a positive integer
$"_" stringify the input
-@0 subtract '0' from each char, giving decimal digits as numbers
÷ . divide the original number by each digit
≍⊝⌊. test if this array, floored and deduplicated, still equals itself
```
A version that also handles zero digits (giving falsy) in 15 bytes ([Try it](https://www.uiua.org/pad?src=ZiDihpAg4omN4oqaPTDiioPil7_iipstQDAkIl8iLgriiLVmIDdfMTI2XzU0XzU1XzM5MTVfMTI2MA==)):
```
≍⊚=0⊃◿⊛-@0$"_".
-@0$"_" decimal digits of input
⊃◿⊛ . push (input % digits, classification of digits)
(classify: assign a unique index to each unique element)
⊚=0 indices where input % digits == 0
≍ match?
```
The final match gives 1 if and only if the number is Lynch-Bell, because:
* `indices where input % digits == 0` has the length equal to the number of digits if and only if `input % digits == 0` is all true,
* its result is precisely `0 1 2 ... x-1` where `x` is the number of digits in that case, and
* the classification is the same if and only if the digits are all unique.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
SÖP¹DÙQ*
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f8/@PC0gEM7XQ7PDNT6/9/Y0tAUAA "05AB1E – Try It Online")
[Answer]
# Mathematica, 57 bytes
```
Tr@Boole[IntegerQ/@Union[s=#/IntegerDigits@#]]==Length@s&
```
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
This is a solution in Python 2, whose whole purpose is to output `True` for truthy and `False` for falsy:
```
lambda n:len(set(n))==len(n)and not any((int(n)%int(x)for x in n))
```
[Try it online!](https://tio.run/##VcqxCoNAEATQ3q/YRtwtNTEhgfsTmxM9FMycmCv061e3Ea4a3sysR5oiGg2u08X/@sETvssI/o@JIeKcAeIxEGIij4N5hm2lxS4hbrTTDLreum5WBq7elUhxq25emdtnzjbj41NboXoC "Python 2 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 37 bytes
```
(.).*\1
0
.
<$&$*1>$_$*
<(1+)>\1+
^$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0NPU08rxpDLgEuPy0ZFTUXL0E4lXkWLy0bDUFvTLsZQm4srTuX/f3MuQyMzLlMTLlNTLmNLQ1MA "Retina – Try It Online") Link includes test cases. Explanation: The first stage replaces any duplicate digit with a zero. The second stage replaces each digit with its unary representation followed by the unary representation of the original number. The third stage then computes the remainder of the division of original number by each non-zero digit. If the number is a Lynch-Bell number then this will delete everything and this is tested for by the final stage.
[Answer]
## Haskell, ~~260~~ ~~241~~ ~~201~~ 162 bytes
```
f([x])=1<2
f(x:xs)=not(x`elem`xs)&&(f xs)
r n i= n`mod`(read[(show n!!i)]::Int)==0
q n 0=r n 0
q n i=r n i&&q n(i-1)
p n=length(show n)-1
s n=q n(p n)&&f(show n)
```
Explanation
```
f ([x]) = True f function checks for
f (x:xs) = not(x `elem` xs) && (f xs) repeated digits
r n i = n `mod` (read [(show n !! i)] :: Int) == 0 checks whether num is
divisible by i digit
q n 0 = r n 0 checks wether n divisible
q n i = r n i && q n (i-1) by all of its digits
p n = length (show n) - gets length of number
s n = (q n (p n)) && (f (show n)) sums it all up!!!
```
Have significantly shortened thanx to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)
[Answer]
## CJam, 17 bytes
CJam is the Java of golfing languages. It's even interpreted in Java!
```
{_Ab__L|=@@f%:+>}
```
### Explanation:
```
{ e# Stack: 3915
_ e# Duplicate: 3915 3915
Ab e# Digits in base 10: 3915 [3 9 1 5]
__ e# Duplicate twice: 3915 [3 9 1 5] [3 9 1 5] [3 9 1 5]
L| e# Remove duplicates: 3915 [3 9 1 5] [3 9 1 5] [3 9 1 5]
= e# Test equality: 3915 [3 9 1 5] 1
@@ e# Rotate twice: 1 3915 [3 9 1 5]
f% e# Modulo each: 1 [0 0 0 0]
:+ e# Sum: 1 0
> e# Greater than: 1
} e# Output: 1 (truthy)
```
[Answer]
## VBScript, 177 bytes
Hey all, this is my very first CG post, and first attempt, so hope I followed all the rules...
```
Function L(s)
dim i,j,k,m,n
j = Len(s)
redim a(j)
n = 0
for i = 0 to j-1
A(i) = Mid(s,i+1,1)
m = m + s Mod A(i)
if j = 1 then
else
for k = 0 to i - 1
if A(i) = A(k) then n = n + 1
next
end if
next
if m + n = 0 then L = "y" else L = "n"
End Function
```
This can be run from Notepad by adding a line at the end
```
Msgbox L(InputBox(""))
```
And then saving it as .vbs, then double click.
Explanation:
```
Function L(s) 'creates the function "L" taking test number as input
dim i,j,k,t,m,n 'variables
j = Len(s) '"j" gets length of test number
redim a(j) 'creates array "a", size is length of test number
n = 0 'sets repeat character counter "n" to zero
for i = 0 to j-1 'for length of string
A(i) = Mid(s,i+1,1) 'each array slot gets one test number character
m = m + s Mod A(i) '"m" accumulates moduli as we test divisibility of each digit
if j = 1 then 'if test number is of length 1, it passes (do nothing)
else 'otherwise, gotta test for repeats
for k = 0 to i - 1 'for each digit already in array, test against current digit
if A(i) = A(k) then n = n + 1
'repeat char counter "n" stores no of repeats
next 'proceed through array looking for repeat
end if
next 'test next digit for divisibility and repeats
if m + n = 0 then L = "y" else L = "n"
'check for any repeats and moduli,
'then return yes or no for LynchBelledness
End Function
```
VBScript is a bit of blunt instrument for golfing, but hey, I haven't learned Ruby yet...
[Answer]
# [Pyth](https://pyth.readthedocs.io), 10 bytes
```
qiRQKjQT{K
```
[Verify all the test cases.](https://pyth.herokuapp.com/?code=qiRQKjQT%7BK&test_suite=1&test_suite_input=7%0A126%0A54%0A55%0A3915&debug=0)
## How?
```
qiRQKjQT{K ~ Full program.
jQT ~ The list of decimal digits of the input.
K ~ Assign to a variable K.
iRQ ~ For each decimal digit...
i Q ~ ... Get the greatest common divisor with the input itself.
{K ~ K with the duplicate elements removed.
q ~ Is equal? Output implicitly.
```
# [Pyth](https://pyth.readthedocs.io), 11 bytes
```
&!f%sQsTQ{I
```
[Verify all the test cases.](https://pyth.herokuapp.com/?code=%26%21f%25sQsTQ%7BI&input=12&test_suite=1&test_suite_input=%227%22%0A%22126%22%0A%2254%22%0A%2255%22%0A%223915%22&debug=0)
## How?
```
&!f%sQsTQ{I ~ Full program, with implicit input.
f Q ~ Filter over the input string.
%sQsT ~ The input converted to an integer modulo the current digit.
~ Keeps it if it is higher than 0, and discards it otherwise.
! ~ Negation. If the list is empty, returns True, else False.
& {I ~ And is the input invariant under deduplicating? Output implicitly.
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 24 bytes
```
{((,⍵)≡∪⍵)×∧/0=(⍎¨⍵)|⍎⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pDQ@dR71bNR50LH3WsArEOT3/UsVzfwFbjUW/foRUgkRogC0jX/k971DYBxO6b6un/qKv50HrjR20TgbzgIGcgGeLhGfz/Ue@qaqBaHXUrBXWdNJCuQyvUzdUV1A2NzICkqQmIMAUSxpaGpuoA "APL (Dyalog Unicode) – Try It Online")
Simple Dfn, can probably be golfed a bit more. Yield standard APL booleans 1 for truthy, 0 for falsy.
It's worth to mention that the function takes the arguments as strings rather than ints.
### How:
```
{((,⍵)≡∪⍵)×∧/0=(⍎¨⍵)|⍎⍵} ⍝ Dfn, argument ⍵.
⍎⍵ ⍝ Convert ⍵ to integer
| ⍝ Modulus
(⍎¨⍵) ⍝ Each digit in ⍵
0= ⍝ Equals 0? Returns a vector of booleans
∧/ ⍝ Logical AND reduction
× ⍝ multiplied by (the result of)
( ∪⍵) ⍝ unique elements of ⍵
≡ ⍝ Match
(,⍵) ⍝ ⍵ as a vector; the Match function then returns 1 iff all digits in ⍵ are unique
```
[Answer]
# [Python 3](https://docs.python.org/3/), 50 bytes
```
lambda n:all(int(n)%int(d)+n.count(d)<2for d in n)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjEnRyMzr0QjT1MVRKVoaufpJeeXgpk2Rmn5RQopCpl5Cnma/wuKQArSNNTN1TU1ueA8QyMzFL6pCSrXFIVrbGkIEvj/HwA "Python 3 – Try It Online")
Returns `True` if the (zero-free) number is a Lynch-Bell number, `False` otherwise.
] |
[Question]
[
**Task:**
You are an amazing programmer and Stackoverflow-answerer, and you decide to answer every question with a bounty on Stackoverflow. You are so good, that you manage to get all the bounties in all the questions. While you wait for the rep to come flooding in, you write a program that goes and find out what the total amount of rep is in all those bounties.
**Rules:**
* When run,
+ Your program will navigate through the featured tab on Stack Overflow.
+ It will scrape out the value of each bounty,
+ Then it will add it up and display the total
* It has to download data from anywhere on SO (and only SO), but I would recommend using <https://stackoverflow.com/questions?pagesize=50&sort=featured> , as it is only about 10 pages
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins
[Answer]
## JavaScript - ~~176~~ ~~133~~ ~~130~~ ~~108~~ 106
```
function f()(t+=$("[title~=an]").text(),u=$("[rel*=x]")[0])?$("html").load(u.href,f):alert(eval(t));f(t=0)
```
*Edit 1: trimmed some selectors down and used the `?:` suggestion from Google's Closure Compiler (via @Sirko - thanks)*
*Edit 2: initialise `s` inside `d` and initialise `t` as `0` instead of `""`*
*Edit 3: realised I don't actually need to target a specific container and can sweep the whole document, which gets rid of a bunch of `.find` calls and an unnecessary selector (plus the variable holding it)*
*Edit 4: shove the `t` initialiser in the function call to avoid a `;` (it'll get hoisted to the top anyway) and squash the function down to one statement (combine two statements into one inside the ternary statement condition) to drop the `{}`*
**Note**: I'm not sure if it's cheating, but this has to be run from a console window of a browser already pointing at `http://stackoverflow.com/questions?page=1&sort=featured`. It relies on the fact that **jQuery** and the appropriate paging links are available on the page itself. Also, it only appears to work in **Firefox** and not in IE or Chrome.
**Output** (at time of posting):
```
38150 (in an alert dialog)
```
**Exploded/commented**:
```
function f()
//concat all the bounty labels to t (they take the format "+50")
//happens to be elements with title attribute containing word 'an'
(t+=$("[title~=an]").text(),
//find the "next" (has rel=next attribute) button
u = $("[rel*=x]")[0])
?
//if there is a next button, load it, and then recurse f again
$("html").load(u.href,f)
:
//else eval the 0+a+b+...+z tally and alert the result
alert(eval(t))
//kick off the initial scrape (and simultaneously init the total tally)
f(t=0)
```
[Answer]
## Python - ~~232~~, ~~231~~, ~~195~~, ~~183~~, ~~176~~, 174
Parses the HTML from <https://stackoverflow.com/questions?sort=featured> using regular expressions.
The upper bound of `range` in the `for` loop *must* be `number of pages + 1` or else the code will raise `HTTPError` because of 404s. Default number of results per-page is 15, which is what the code uses (omitting `?pagesize=50` saves on characters and is just as effective).
Thanks to **@Gabe** for the tip on reducing char count even further.
**Golfed**:
```
import requests,re;print sum(sum(map(int,re.findall(r"<.*>\+(\d+)<.*>",requests.get("https://stackoverflow.com/questions?sort=featured&page=%u"%i).text)))for i in range(1,33))
```
**Output** (at time of posting):
```
37700
```
**Un-golfed**:
Here's a somewhat un-golfed version that should be a bit easier to read and understand.
```
import requests, re
print sum(
sum(
map( int,
re.findall( r"<.*>\+(\d+)<.*>",
requests.get( "https://stackoverflow.com/questions?sort=featured&page=%u" % i).text
)
)
) for i in range( 1, 33 )
)
```
[Answer]
# Rebol - ~~164~~ ~~133~~ 130 (139 with 404 check)
Parses the html using the `parse` sub-language of Rebol. Checks the first 98 pages. I realised I have the same constraint as the python solution - too many repeats hit 404 errors and stop the execution.
Thanks to @rgchris for many improvements! Updated to check up to 98 pages.
`s: 0 repeat n 99[parse read join http://stackoverflow.com/questions?sort=featured&page= n[15[thru{>+}copy x to{<}(s: s + do x)]]]s`
With error checking for 404s (139):
`s: 0 repeat n 99[attempt[parse read join http://stackoverflow.com/questions?sort=featured&page= n[15[thru{>+}copy x to{<}(s: s + do x)]]]]s`
**Test**
```
>> s: 0 repeat n 20[parse read join http://stackoverflow.com/questions?sort=featured&page= n[15[thru{>+}copy x to{<}(s: s + do x)]]]s
== 23600
>> s: 0 repeat n 99[attempt[parse read join http://stackoverflow.com/questions?sort=featured&page= n[15[thru{>+}copy x to{<}(s: s + do x)]]]]s
Script: none Version: none Date: none
== 36050
```
**Explanation**
Rebol ignores whitespace, hence you can put it all on one line like that if you choose. PARSE takes two inputs, and the first argument *(`read join ...`)* is fairly self-explanatory. But here are some comments on the parse dialect instructions, in a more traditional indentation:
```
s: 0
repeat n 99 [
parse read join http://stackoverflow.com/questions?sort=featured&page= n [
;-- match the enclosed pattern 15 times (the rule will fail politely when there are less entries)
15 [
;-- seek the match position up THRU (and including) the string >+
thru {>+}
;-- copy contents at the current position up TO (but not including) <
copy x to {<}
;-- (Basically, run some non-dialected Rebol if this match point is reached) the do is a bit dangerous as it runs the string as code
(s: s + do x)
]
]
]
;-- evaluator returns last value, we want the value in S
;-- (not the result of PARSE, that's a boolean on whether the end of input was reached)
s
```
[Answer]
# Ruby, 260
```
require'open-uri'
require'zlib'
i=b=0
d=''
until /"has_more":f/=~d
i+=1
d=Zlib::GzipReader.new(open("http://api.stackexchange.com/2.2/questions/featured?site=stackoverflow&page=#{i}&pagesize=100")).read
b+=d.scan(/"bounty_amount":(\d+)/).map{|x|x[0].to_i}.reduce :+
end
p b
```
Uses the Stack Exchange API.
Output (as of time of original post):
```
37200
```
I'm not counting the `&pagesize=100` in the character count, because it works without it, but I just added that for convenience while testing. If you remove that, it does the same thing (except it eats more quota and takes slightly longer).
[Answer]
# Rebmu - ~~108~~107
```
rtN99[parseRDrj[http://stackoverflow.com/questions?sort=featured&page=N][15[thru{>+}copyXto{<}(a+JdoX)]]]j
```
**Test**
(at 19:05 AEST)
```
>> rebmu [rtN99[parseRDrj[http://stackoverflow.com/questions?sort=featured&page=N][15[thru{>+}copyXto{<}(a+JdoX)]]]j]
Script: none Version: none Date: none
== 79200
```
[Rebmu](https://github.com/hostilefork/rebmu/tree/2965e013aa6e0573caa326780d97522a425103f0) looks rather cryptic, but it is quite readable once you get the hang of it. Let's start by unmushing it and laying it out properly.
```
rt n 99 [
parse rd rj [
http://stackoverflow.com/questions?sort=featured&page= n
][
15 [
thru {>+}
copy x to {<}
(a+ j do x)
]
]
]
j
```
Rebmu is a dialect of Rebol so you can see the similarities in the solution. Rebmu can't reduce the size of every statement yet, but it is an evolving language. Thanks again to @rgchris for the improvements to my first attempt.
[Answer]
# Ruby - 197
Short version:
```
require 'nokogiri'
require 'open-uri'
s=0
(1..33).each{|p|Nokogiri::HTML(open("http://stackoverflow.com/questions?page=#{p}&sort=featured")).css('.bounty-indicator').each{|b|s+=b.content.to_i}}
p s
```
Human friendly version:
```
require 'nokogiri'
require 'open-uri'
s=0
(1..33).each do |p|
Nokogiri::HTML(open("http://stackoverflow.com/questions?page=#{p}&sort=featured")).css('.bounty-indicator').each do |b|
s += b.content.to_i
end
end
puts s
```
And answer - `39700`
# Ruby with script parameters - 139
```
require 'nokogiri'
require 'open-uri'
s=0
(1..33).each{|p|Nokogiri::HTML(open(ARGV[0]+p.to_s)).css(ARGV[1]).each{|b|s+=b.content.to_i}}
p s
```
To run this from bash just type
```
ruby code_golf_stack_overflow2.rb http://stackoverflow.com/questions?sort=featured\&page= .bounty-indicator
```
[Answer]
## PHP - 121 bytes
```
<?for(;preg_filter('/>\+(\d+)/e','$t+=\1',@file('http://stackoverflow.com/questions?sort=featured&page='.++$n)););echo$t;
```
Using a regex 'eval' modifier, to avoid using `array_sum` or similar. Seems to be the shortest solution among valid entries.
[Answer]
## PHP, ~~134~~, ~~131~~, 127
`while($q=array_sum(preg_filter('#.*>\+#',0,file("http://stackoverflow.com/questions?sort=featured&page=".++$n))))$s+=$q;echo$s;`
Will loop through **all** pages, `pagesize` is not set to save bytes so more `GET`s.
Very Very Dirty, but... taking advantage of `PHP`'s "flaws" !
* no space after `echo`
* `while` stops at assignment
* output after `RegEx` replace is a string starting with the bounty amount
* `array_sum()` adds up strings
* `$n` and `$s` are initialized, but starting from nothing is equiv. as starting from zero
* etc...
[Answer]
**Bash 206**
optimizations possible, too lazy
```
s=0;for i in `seq 1 11`;do for j in `wget -q -O - "http://stackoverflow.com/questions?pagesize=50&sort=featured&page=$i" | grep -o -E "bounty worth [0-9]*" | grep -o -E "[0-9]*"`;do s=$(($s+$j));done;done;echo $s
```
result:
```
39450
```
[Answer]
# Javascript - ~~129~~ ~~119~~ ~~110~~ 107 characters
## EDIT: INVALID ANSWER! This only handles the "Top featured questions", which only has a fraction of them. Alconja's answer is more valid.
```
s="#mainbar";t="";eval("$(s).find('.bounty-indicator').each(function(){t+=this.innerHTML});alert(eval(t))")
```
Execute on <https://stackoverflow.com/?tab=featured> in a console window. Based on the solution by Alconja.
Golfed it a bit more by removing unneeded whitespaces.
Used eval to remove the function call, clearing another 9 characters.
cleared out some more unneeded whitespace.
[Answer]
# Java, 540 chars
***Warning: the number of active bounties is ~470. This code will access a page on stackoverflow that many times. It may get you in trouble with them for making so many data requests.***
```
import java.io.*;import java.net.*;public class B{public static void main(String[]A){String u="http://stackoverflow.com/questions",d;Long i,s=i=0L,n=i.parseLong(o(u).replaceAll("^.*b.>(\\d+).*$","$1"));while(i++<n){d=o(u+"?pagesize=1&sort=featured&page="+n).replaceAll("^.*ion.>.(\\d+).*$","$1");s+=d.matches(".*\\D.*")?0:n.parseLong(d);}System.out.print(s);}static String o(String s){String d="";try{BufferedReader r=new BufferedReader(new InputStreamReader(new URL(s).openStream()));while((s=r.readLine())!=null)d+=s;}finally{return d;}}}
```
My output was `23400`, but when I ran @TonyH's code, I got `37550`. Bad news.
Pretty code:
```
import java.io.*;
import java.net.*;
public class StackOverflowBounty {
public static void main(String[] args) {
String u = "http://stackoverflow.com/questions", d;
Long i, s = i = 0L, n = i.parseLong(o(u).replaceAll("^.*b.>(\\d+).*$", "$1"));
while (i++ < n) {
d = o(u + "?pagesize=1&sort=featured&page=" + n).replaceAll("^.*ion.>.(\\d+).*$", "$1");
s += d.matches(".*\\D.*") ? 0 : n.parseLong(d);
}
System.out.print(s);
}
static String o(String s) {
String d = "";
try {
BufferedReader r = new BufferedReader(new InputStreamReader(new URL(s).openStream()));
while ((s = r.readLine()) != null) {
d += s;
}
} finally {
return d;
}
}
}
```
The way this works is simple. It reads from the url `http://stackoverflow.com/questions"` to determine the number of questions that have bounties (note: if the number increases, the program fails, but if it drops, it works fine). It searches for this number using the regex: `b.>(\\d+)`. This has worked in all tests to date, but if someone asked a question that matches that regex, this might not work.
Then, we open the url `http://stackoverflow.com/questions?pagesize=1&sort=featured&page=` + `current question #`. In other words, we open a new page for each featured question, and force the number of questions to be only `1`, so we will get them all. The reputation part will always match `ion.>.(\\d+)`, so I use that to find it. I split the operation into two parts so that I could cheaply check if the number of questions reduced (ie the string returned is not an integer).
Then, we sum up all the reputation and print it.
It took about 3 minutes and 20 seconds to run on my machine.
---
Does anyone know why it isn't printing the right number?
[Answer]
## C# - 407
```
class B{void Main(string[] a){var o=0;for(int i=1;i<11;i++){var r=((System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(string.Format(a[0]+"&page={0}",i)))).GetResponse();if(r.ContentLength>0){using(var s=new StreamReader(r.GetResponseStream()))foreach(Match m in Regex.Matches(s.ReadToEnd(),"bounty worth (.+?) "))o+=int.Parse(m.Value.Substring(m.Value.IndexOf('h')+2));}}Console.Write(o);}}
```
Using Stackoverflow.com. Same as below, except no Gzip decompressing and different regex.
**Test**
```
> prog.exe http://stackoverflow.com/questions?pagesize=50&sort=featured
38150
```
Weirdly, getting a different value than below.
---
## C# - 496
This uses api.stackexchange which is gzipped and json.
```
using System.IO.Compression;class B{void Main(string[] a){var o=0;for(int i=1;i<11;i++){var r=((System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(string.Format(a[0]+"&page={0}",i)))).GetResponse();if(r.ContentLength>0)using(var s=new StreamReader(new GZipStream(r.GetResponseStream(),CompressionMode.Decompress)))foreach(Match m in Regex.Matches(s.ReadToEnd(),@"bounty_amount"":(.+?),"))o+=int.Parse(m.Value.Substring(m.Value.IndexOf(':')+1).Replace(",",""));}Console.Write(o);}}
```
**Unminified:**
```
using System.IO.Compression;
class B
{
void Main(string[] a)
{
var o = 0;
for (int i=1; i<11; i++) {
var w = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(string.Format(a[0]+"&page={0}",i)));
if(w.GetResponse().ContentLength > 0)
using(var s = new StreamReader(new GZipStream(w.GetResponse().GetResponseStream(),CompressionMode.Decompress)))
foreach(Match m in Regex.Matches(s.ReadToEnd(), @"bounty_amount"":(.+?),"))
o += int.Parse(m.Value.Substring(m.Value.IndexOf(':')+1).Replace(",", ""));
}
Console.Write(o);
}
}
```
**Test**
Default pagesize:
```
> prog.exe http://api.stackexchange.com/2.2/questions/featured?site=stackoverflow
25300
```
Pagesize=100:
```
> prog.exe "http://api.stackexchange.com/2.2/questions/featured?site=stackoverflow&pagesize=100"
37400
```
[Answer]
# jQuery 191
```
i=0;function f(p){$.get('//api.stackexchange.com/2.2/questions/featured?site=stackoverflow&page='+p,function(d){for(x in d.items)i+=d.items[x].bounty_amount;d.has_more?f(p+1):alert(i)})};f(1)
```
It works from anywhere in stackexchange(and many other sites), no need to be in a specific page as in @Alconja/@NateKerkhofs answers
[Answer]
## PHP - 139
**Golfed:**
```
<?php
$a=file_get_contents('http://stackoverflow.com/?tab=featured');preg_match_all('/n">\+([0-9]+)<\/div>/',$a,$r);echo array_sum($r[1]);
```
**Ungolfed - 147**
Simple `file_get_contents` / `preg_match` / `array_sum`
```
<?php
$a = file_get_contents('http://stackoverflow.com/?tab=featured');
preg_match_all('/n">\+([0-9]+)<\/div>/', $a, $r);
echo array_sum($r[1]);
```
**Test:**
>
> php run.php
>
>
> 10250
>
>
>
[Answer]
# Bash 174
Based on <https://codegolf.stackexchange.com/a/25180/7664>:
```
s=0;for i in {1..11};do for j in `wget -qO- "stackoverflow.com/questions?pagesize=50&sort=featured&page=$i"|cut -d' ' -f18|egrep '^[0-9]+$'`;do s=$(($s+$j));done;done;echo $s
```
[Answer]
# Python (174 characters):
Expanding on the python answer above (don't have enough karma to comment):
```
import requests,re;print sum(sum(map(int,re.findall(r"<.*>\+(\d+)<.*>",requests.get("http://stackoverflow.com/questions?sort=featured&page=%u"%i).text)))for i in range(1,33))
```
Requests in lieu of urllib cuts down on 2 chars.
[Answer]
# Ruby (176 chars):
Following Tony H.'s example of using hard-coded page numbers, here's what I got:
```
require'open-uri';b=0;(1..29).each{|i|d=open("http://stackoverflow.com/questions?sort=featured&page=#{i}").read;b+=d.scan(/<.*>\+(\d+)<.*>/).map{|x|x[0].to_i}.reduce 0,:+};p b
```
gave me 35300 at the time of writing.
] |
[Question]
[
>
> [Robber's thread](https://codegolf.stackexchange.com/questions/136151/restricted-mini-challenges-robbers-thread)
>
>
>
Your task as cops is to select three things:
* A programming language
* An OEIS sequence
* A byte set
You are then to secretly write a program in that language that computes the nth term sequence using only the bytes in the set. You will reveal the three pieces of information so that robbers can try to figure out the program.
Answers will be scored by the number of bytes in the byte set with more score being good. Cracked answers have an automatic score of 0. If your answer is uncracked after one week you may reveal the intended program and mark your answer as "safe".
Answers must be capable of calculating every term in the b-files of the sequence, but are not required to calculate any terms after.
Sequences can be either 1 or 0 indexed for both cops and robbers.
Here is a [Python Script](https://tio.run/##RYxBDoMwDATvvMLyKVGPvVUtr@ADFIwSCezIMVLz@kARtMed3Z1ULAjfa30Xo0wGL0DEpwWCiwRSanfYNIOMdA6KrApH/tdJI5vDbv8OsqReYxYGJVuVaXwA3rKp6@fZfSDyzz@JwgG@Ou99rRs) that checks if your code matches the given byte set.
[Answer]
## [Haskell](https://www.haskell.org/), [A209229](https://oeis.org/A209229), ([cracked](https://codegolf.stackexchange.com/a/136257/20260))
11 characters (including newline):
```
s<=[ ]
how!
```
Outputs True/False as an indicator function for powers of 2:
```
1 => True
2 => True
3 => False
4 => True
5 => False
6 => False
7 => False
8 => True
9 => False
...
```
Inputs are positive integers.
[Answer]
# [Python 2](https://docs.python.org/2/), [A000045](https://oeis.org/A000045) ([Cracked](https://codegolf.stackexchange.com/a/136173))
```
ml:= input(as,forge)
```
it contains a whitespace and a newline
[Try it Online!](https://tio.run/#python2)
[Intended solution](https://tio.run/##Dci7CoAwDEbhvU/R8Q9kUEehD@PgJaBpqOng08cuh49jn19VlwgroOQjnI7asmTR3DY9d4hadxCtxl6c3/4Ag8TjJWuijntXGFHEPP0)
[Answer]
## Haskell, [A000045](https://oeis.org/A000045) ([cracked](https://codegolf.stackexchange.com/a/136279/71256))
I made up my mind, I think I like `t` more than `s`.
So let's use these 30 bytes (including newline) instead:
```
abcdeFgh|jklmnopqrtTuvwxyz
=()
```
Please note that the general challenge description demands that
>
> Answers must be capable of calculating every term in the b-files of the sequence [...].
>
>
>
In this case, the [b-file](https://oeis.org/A000045/b000045.txt) goes up to the 2000th number, which is way beyond what can be computed using `Int`.
[Answer]
# Octave, [A000290](https://oeis.org/A000290), [Cracked](https://codegolf.stackexchange.com/a/136202/31516)!
The sequence is the square numbers: **0, 1, 4, 9, 16, 25, 36, 49 ...** (so that you don't have to check the link).
```
'()/@^_
```
[Answer]
## Haskell, [A000045](https://oeis.org/A000045) ([Cracked](https://codegolf.stackexchange.com/a/136260/20260))
Everyone likes Fibonacci numbers, I like Haskell...
I have carefully selected 30 bytes for you: the lowercase letters except `f`, `i` and `t`, you get the uppercase letters `F` and `T` and the pipe symbol `|` instead, and the three symbols `=()`, and newline. Here they are again:
```
abcdeFgh|jklmnopqrsTuvwxyz
=()
```
[Answer]
# Haskell, [A034262](https://web.archive.org/web/20170610111339/http://oeis.org/A034262), 43 bytes, [cracked](https://codegolf.stackexchange.com/a/136363/56433)
`!"#%',.=?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_{|}~`
Computes `a(n) = n³ + n`.
[Answer]
## Haskell, [A009056](https://oeis.org/A009056) ([cracked](https://codegolf.stackexchange.com/a/137762/34531))
Another simple one, now again with enough letters to make it look like ordinary Haskell and maybe for you to amaze me by finding a solution completely different from mine.
The sequence is *Numbers >=3* and the charset consists of these 30 bytes:
```
{[abcdefghijklmnopqr uvwxyz]}.
```
---
The crack has some nice techniques. I was just thinking of this:
>
> `head . flip drop [ floor pi .. ]`
>
>
>
[Answer]
# C (C99), [A000005](https://oeis.org/A000005), 25 Bytes#, [Cracked!](https://codegolf.stackexchange.com/questions/136151/restricted-mini-challenges-robbers-thread/136209#136209)
These are the bytes for a full problem, takes n as a command line argument and outputs answer to stdout.(Space is included in bytecount).
```
<=>,;!"()*%+acdfhimnoprt
```
[Answer]
# [Unary](https://esolangs.org/wiki/Unary), [A002275](https://oeis.org/A002275), 1 Byte
Byte set:
```
0
```
I had to at least try it :3
(I don't think it will be particularly hard seeing as every command in the language is available)
[Answer]
# Perl 5, [A000030](https://oeis.org/A000030) ([Cracked](https://codegolf.stackexchange.com/a/136232/9365))
Byte set:
```
imnprt7 $;()<>=~.
```
[Try it online!](https://tio.run/#perl5)
[Answer]
## JavaScript (ES6), 17 bytes, [A000290](https://oeis.org/A000290) ([Cracked](https://codegolf.stackexchange.com/a/136266/58563))
Again, this is the simple square sequence a(n) = n2.
Byte set:
```
$()=>CI`abelotv{}
```
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), [A057077](https://oeis.org/A057077), 77 bytes
Periodic sequence `1, 1, -1, -1`. As a list:
```
a(0) = 1
a(1) = 1
a(2) = -1
a(3) = -1
a(4) = 1
a(5) = 1
a(6) = -1
...
```
Character set (edited), which includes a newline and a space character:
```
!%&(),0123456789;?@ABCDEFGHIJKLMOPQRSTUVWXYZ^abcdefghijklmnopqrstuvwxyz[]#.
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/19BQVNBkwtIKCo4cCko6Cno/f8PAA "Hexagony – Try It Online")
[Answer]
## Haskell, [A000045](https://oeis.org/A000045) ([cracked](https://codegolf.stackexchange.com/a/136560/34531))
It's cracked, and I won't start a new version, but if you want to play more: it's possible without `y`, and it's possible to be efficient.
---
I apologize for leading you in wrong directions by giving a `g`.
Let's do the same without!
Here are the 29 remaining bytes (including newline):
```
abcdeFh|jklmnopqrtTuvwxyz
=()
```
Again, remember that `Int` won't be enough to compute the 2000th Fibonacci number which is needed because it is in the b-file.
[Answer]
## Haskell, [A000045](https://oeis.org/A000045) ([cracked](https://codegolf.stackexchange.com/a/136650/34531))
This is kindof (as announced) not a new version, but completely different. (Right?)
I still hope I can make you rediscover my nice little observation.
This time you are asked to implement the Fibonacci sequence using a charset of size 17, which (as far as I know) contains only ~~one~~ two unneeded chars:
```
eilnt=(,).[ ]_:0!
```
Note that there is no newline (but feel free to show a version which has them for readability) and remember that you have to be able to compute the 2000th Fibonacci number.
[Answer]
# Cubix, [A000027](http://oeis.org/A000027) (SAFE) 17 points
```
!&')-/0;@Oiru.NSQ
```
My solution:
```
!O!;i)!/u&!!r-)0'u;;!@
```
watch it online [here](http://ethproductions.github.io/cubix/?code=IU8hO2kpIS91JiEhci0pMCd1OzshQA==&input=NTU=&speed=20)
I originally did this without `.NSQ` but I figured I could add them safely.
Explanation:
This sequence is just "The Positive Integers". However, Cubix has three input commands, `i`, which reads in a single char (pushing `-1` if input is empty), `A`, which reads in the rest of the input as chars (pushing a `-1` to the bettom of the stack), and `I`, which reads the next number off the input (pushing `0` if there isn't a match). So naturally, I only provided `i` which reads in digits as their ascii value. uh-oh. Additionally, `-1` is the usual marker for end of input, in conjunction with `?` so I got rid of `?`, forcing me to use `!` (skip next instruction if TOS is not zero) for control flow. Finally, I thought I needed `&` to concatenate digits for printing with `O` (which outputs the top of stack as a number), but I realize now that that wasn't necessary either!
Another part of the challenge was originally to not have `.` the no-op character, but you can use pairs of `!` instead if you're careful:
```
! O
! ;
i ) ! / u & ! !
r - ) 0 ' u ; ;
! @
. .
```
`i)` : read input, increment.
`!/` : if top of stack is zero (end of input), turn left
left: `;O.@` : pop top of stack, output as number, halt.
otherwise:
`u'0`: push char code of `0` to top of stack
`)-r`: increment, subtract, and rotate
`;;` : pop top of stack twice
`u&` : concatenate digits
`!!` : net zero effect, now we are at `i)` again.
[Answer]
# [Seed](https://esolangs.org/wiki/Seed), [A005408](https://oeis.org/A005408) (Odd Numbers) - Safe
Here's a slightly more challenging one. You may use any characters valid in Seed:
```
[0-9 ]
```
You shouldn't be able to brute force this one in a week unless you have a monster of a computer. Good luck! It's crackable.
### Hint
>
> This is the Befunge-98 program used in my solution: `9&2*1-.@` (the `9` can be removed, but my solution just happens to have one)
>
>
>
### Solution
```
8 47142938850356537668025719950342285215695875470457212766920093958965599014291682211474803930206233718243166021324700185443274842742744297183042397910454208210130742260519105651032450664856693714718759816232968955289663444878636053035645231246428917992493766505872029989544065894418166685284738859999912471659057565000392419689361271972485444731284404987238803115210428572945108908191097214978382112218242627719651728712577306652405452922782307249485947045215982784790396555726144526602778473387279897334709142853151393812930171163300904436548870603006549005515709074682843356844201220668045057407146751793470423217099467145255174198241606814578351260769359571053755888106818197239116973006365593563235361647743411341624822052103816968153274122434280200888824954875622811325064255818154979564925710534165572852442761249176778416688044630942040966271963723430245979221181930857841829694362184653939393940015797332978459794253176110314873994228261888801228999293570329618551223457182420746927212801550646743152754821640064626761542582557138452651970009253770914346130172884305622027370793496993281847017017643506435562229916984107083951938286577012273222191422054315198157936674247934699496471202544270325061352014830137178245082445717253260177560449757186762445707057028987371278573629077370632470496186218574320801798046510846708620502139560277546345198686675095078255875594169064796673074708822106659920187882062247609587560174781170641367430722951002242213604709887062481149928551745163110045572994991844223216663621203042075294195007458339984527333125093390189721042315604498435269143549420166732177200370228527273606218617171975362431824163269672003982537382982066136613799403024924018145511099557720492305303748099327810811511080314262364010281851651151072957475365629128068033597559560186625877942054704386175359499573139930378099420149452745731809033737756051947913924265484582800618244473333957173960222243311738522875022546610298627492222587971756897328087719407454153248557203886421828643453889090192355970705084245312184441674098515659253482621260617211786550204852895652236768886852209506535523414991099331857674826373947830587028494510697603296607361093480842935154672353288419699354739650168309017848485131553416956405911683526896232046773861961911767319373432460217755874481607587604361758089936007730253450733375831228127106295259261723611771334468553746160739548375950046831923765023329346333968732796413192682936767133122325481273354810124729664400173367781325488656859581438769940474229394692089519981810909719628263357284973442177568041416363386891516725592952892168077523560584005586276794967492051823290615767599202657060820223928678900774601616908031321346819422162123048834532926372862962159255934240435694566497798544870186550219886342379298214007368081326725550763589917206162393892085506551547475259270513853987294911388226039365971184089828739349642347312302559286882065147953715607221387657413593069535573044067517274676745306396611760657091792151803798859781616126637075577936361782593546481811651450365118155866449850474140044293772144065341051900055416408240857348697564252386403719942197789892382627153382011984996644288495699209129097948405810551134169739499539470610790009272281731894550593600643079188663110695127017324336488487580799309995227054576681630676222848231145106058050452439356753552872060820230589152143268436210090733908507724084889788244157692417246691477400856716677564609725979550100138132944851304473466485128295568194188600539248624248078558656162635444219199062786468487219220160009464328883337821175254405764395407405891483810757405446047244460754827113527540703326714751461178900155717130399854358953609995319006890674085682111514072508440632941090209366005504352890092326935445829213294943731517698438648298921337375443947066950275955144209037675013663600062205168551851984361951824731229113379464426979717688372371011461890139087487634586087688796134318950140718824105959727161482389914414206768064990410615468858520426399188835467970981786227122743162945627167772066100574532803061925537235491026486409948728571706557098859331941260622260924660292578136091523126589085799981416326395824628987154802653126685882440760385315869346960183809644486238810912663304360284449610976505715001267334297285036791711464142665122000857666018757370925847113798258537503747803972255591351740843663253694303946089997282812556281486820325652814785261116697261899511762129550421005941055852897451832731304151488058522478260009347144486599715629242208891126238083949281490804191584238425634093683587199278186505945727829025071885767559828670803412582690901456978557379916793144695491189633486065077294485660840922713748873840986104486221528464294334436081663106336911265802650605150347413103936140565054608396116572669757269475369570465915381045895991937087068526458273755454602799814909213983801968791431574508976448235055061998715636460946550584682626461010298101802277643570201189324102499951196290880892383380284543173390448406975616650185808619832614403133944687275834716343817926764699295672501869876060896683204343897481630037607159476461359111190545646447421653872016775582115425356868533678655969328210255235050133718364831289991244684695035034122861927276046255405376531096051541299607470934463981741370397268760811035606321455156217990078359217247117349544774085111287345436916077577032709684005131011429476229617901273007027774182864475737502587896225475248267937497254066190335088823904767397814233350286976811901982274477445433872253983823904938249655089770642137858608313524715533520654523880832056453080193644871440738737277389718589793074725139142291918837706550037934799585495183374639955887618135803388399608755212147742199481865453122900714456703147150994585431640652462593333773031385396586933380738103697887063571042512186708015948688088011290197524699274772775288900864690592106393483764109837848793374117655194139018455509931621247697015323332300969105814058088442693320033876473960017819576425062784644138417943454576404265382986995583045527928832
```
[Answer]
# [Python 2](https://docs.python.org/2/), [A000045](https://oeis.org/A000045) ([Cracked](https://codegolf.stackexchange.com/a/136183/53880))
```
l:= input(a,forge)[]
```
it contains a whitespace and a newline
[Try it Online!](https://tio.run/#python2)
[Intended solution](https://tio.run/##HYoxCoAwDAD3viJjAh3UUehLxMEhakDSUOLg66N1Objj7PGz6hRhBSn5h5z22kBAFNqmB6Oo3Y5Es2UvnheGPmgf8Ev0K3fVNVkTdbxY0YgixuEF)
[Answer]
# R, [A000142](http://oeis.org/A000142), ([Cracked](https://codegolf.stackexchange.com/a/136186/67312))
Byte set:
```
-()*,`=cfinotu
```
Intended solution:
>
> `f=function(n,c=n==n)'if'(n,f(n-(n==n),c*n),c*(n==n))`
>
>
>
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), [A000027](https://oeis.org/A000027), [Cracked](https://codegolf.stackexchange.com/a/136192/34388)
```
!"#%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
That's right! You get all of ASCII! Wait... there's no `$`... what's `$` again in cQuents? Oh, yeah, the index builtin. Well, tough luck :/
Intended Solution:
>
> `#|A:A`
>
>
>
[Try it online!](https://tio.run/##Sy4sTc0rKf4PBAA "cQuents – Try It Online")
[Answer]
# CJam, [A000042](https://oeis.org/A000042), [cracked by Lynn](https://codegolf.stackexchange.com/a/136236/53880)
Byte set:
```
{})_%si
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), [A000004](http://oeis.org/A000004), 5 bytes, Cracked
Just messing around to start off. Should be easy for anyone familiar with Ruby. It's a low score, but whatever.
```
/np.$
```
---
[Cracked, unintended exploit](https://codegolf.stackexchange.com/questions/136151/restricted-mini-challenges-robbers-thread/136227#136227)
[Cracked (intended answer using `n` flag)](https://codegolf.stackexchange.com/a/136255/6828)
[Answer]
# Python 3, [A007504](http://oeis.org/A007504) ([Cracked](https://codegolf.stackexchange.com/a/136288/72043))
This byteset, including newline:
```
bfuwo)nm1h[=(t+;0a
sig%pr, le:]
```
My code does not provide infinite output, but can compute the entire b-list.
[Answer]
# R, [A000290](http://oeis.org/A000290), ([cracked](https://codegolf.stackexchange.com/a/136213/67312))
Byte set:
```
()%cfinotu
```
[Answer]
## [Snowman](https://github.com/KeyboardFire/snowman-lang), 212 bytes, [A000042](http://oeis.org/A000042)
```
#$%&*01:;=?@CEFGHIJLMOQUVXYZbcdefghijlmnopqsuvxyz~
```
... plus space, [0x00-0x1f inclusive, and 0x7f-0xff inclusive](https://codegolf.stackexchange.com/questions/136150/restricted-mini-challenges-cops-thread/136316#comment333426_136150).
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), [A000217](https://oeis.org/A000217), [Cracked](https://codegolf.stackexchange.com/a/136320/63641)
Byteset:
```
$:=1;
\-
```
~~Note that this uses a feature that I haven't pushed the documentation for yet, so I'll push that tonight, if you wait until then. (Or you can slop through my source code... have fun).~~ Documentation pushed. Would be a byte less if a recent bugfix was on TIO.
Intended solution:
>
> `=1-1:--\1$
> ;$`
>
>
>
[Try It Online!](https://tio.run/#cquents)
[Answer]
## JavaScript (ES6), ~~13~~ 10 bytes, [A000045](http://oeis.org/A000045), [Cracked](https://codegolf.stackexchange.com/questions/136151/restricted-mini-challenges-robbers-thread/136371#136371)
This should be easy.
This is the Fibonacci sequence: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
Byte set:
```
$()-:<=>?[]_~
```
**Edit:**
It can be even done with the following 10 bytes:
```
$()-:=>?_~
```
[Answer]
# R, [A105311](http://oeis.org/A105311), ([Cracked](https://codegolf.stackexchange.com/a/136409/67312))
Byte set:
```
'%(),:=acdegilnopstx
```
[Answer]
# Python3, [A008615](http://oeis.org/A008615), [Cracked](https://codegolf.stackexchange.com/a/136335/72043)
Bytemap (with newline):
```
n)ir=-
(u0*pt
```
[Answer]
# [Befunge](https://esolangs.org/wiki/Befunge), [A000142](https://oeis.org/A000142), 29 Bytes, ([Cracked](https://codegolf.stackexchange.com/questions/136151/restricted-mini-challenges-robbers-thread/136454#136454))
```
Byte Set: @.$_ ^*:\v>-1&
```
If you can't tell, that Byte set includes a space.
This should be *moderately* easy to solve.
Edit: Forgot the "A" before the OEIS
[Answer]
# R, [A105311](http://oeis.org/A105311), ([cracked](https://codegolf.stackexchange.com/a/136457/67312))
```
'%(),:=acdeginpstx
```
Let's try this without the `l` or `o`.
Since this has been cracked, the intended solution:
>
> `cat(diag(diag((a=scan()))%x%diag((a==a):a)),sep='')`. `diag` is an interesting function, that can be used in three different ways. When presented with a single integer (`diag(n)`), it creates a NxN matrix with 1 on the diagonal. When presented with a vector (`diag(1:n)`), it creates an NxN matrix with the vector on the diagonal. When presented with a matrix (`diag(diag(n))`), it returns the diagonal as a vector. `%x%` computed the Kronecker product of two matrices, where each element in matrix 1 is multiplied with each element in matrix 2 separately. Doing this with a length `n` identity matrix and a `1:n` diagonal matrix, creates a length `n^2` diagonal matrix with `1:n` repeated `n` times. `diag` extracts that again, and `cat` prints.
>
>
>
] |
[Question]
[
Your task is to generate the nth term of the RATS sequence, where n is the input. The RATS sequence is also known as the Reverse Add Then Sort sequence. This sequence can also be found here: <http://oeis.org/A004000>.
test cases:
```
0 > 1
1 > 2
2 > 4
3 > 8
4 > 16
5 > 77
6 > 145
7 > 668
```
For example, the output for 5 is 77 because 16 + 61 = 77. After this the 77 is sorted.
Shortest submission wins. This is my first challenge so i hope this is not a duplicate or something.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 11 ~~12~~ bytes
```
1i"tVPU+VSU
```
Input is a *string* (with single quotes) representing an integer in *unary*. String input is allowed by the challenge, and unary [is a valid format](https://codegolf.meta.stackexchange.com/a/5344/36398).
[**Try it online!**](http://matl.tryitonline.net/#code=MWkidFZQVStWU1U&input=JzExMTExMTEn)
### Explanation
```
1 % push number 1 to the stack
i % input. Will be a string of "n" ones
" % for loop: repeat n times (consumes string)
t % duplicate
V % convert to string
P % reverse
U % convert to number
+ % add
V % convert to string
S % sort
U % convert to number
% loop is implicitly ended
% stack content is implicitly displayed
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Code:
```
$FDR+{
```
Explanation:
```
$ # Push 1 and input
F # For N in range(0, input)
D # Duplicate top of the stack
R # Reverse top of the stack
+ # Add top two items
{ # Sort top of the stack
# Implicitly print top of the stack
```
This also works with a **0 byte** program.
[Answer]
## Pyth, ~~17~~ ~~13~~ 12 bytes
```
uS`+vGv_GQ\1
```
```
u Q\1 reduce range(input()) on base case of "1" (string)
+vG eval the string (to get a number), and add...
v_G the same number, reversed first and then eval'd
S` convert back to string and sort
```
[Try it on the online interpreter](https://pyth.herokuapp.com/?code=uS%60%2BvGv_GQ%5C1&input=7&debug=0).
[Answer]
## CJam, 15 bytes
```
1ri{_sW%i+s$i}*
```
[Test it here.](http://cjam.aditsu.net/#code=1ri%7B_sW%25i%2Bs%24i%7D*&input=10)
### Explanation
```
1 e# Push 1 as the start of the sequence.
ri e# Read input and convert to integer N.
{ e# Run this block N times...
_s e# Duplicate and convert to string.
W% e# Reverse string.
i+ e# Convert back to integer and add to previous value.
s$ e# Convert to string and sort.
i e# Convert back to integer for the next iteration.
}*
```
[Answer]
# Python 2, 72
```
f=lambda x,n=1:x and f(x-1,int(''.join(sorted(`n+int(`n`[::-1])`))))or n
```
Recursive function, makes use of the Python 2 shorthand for `__repr__`, which will break once the function reaches very large values (an `L` will be appended to the number's string), I'm not certain from the spec if there is a place where we can stop, but if not changing to `str()` only adds 6 bytes, but then it becomes slightly shorter to output as a string, at 75 bytes:
```
f=lambda x,n='1':x and f(x-1,''.join(sorted(str(int(n)+int(n[::-1])))))or n
```
1 byte saved thanks to trichoplax on this version
[Answer]
# JavaScript ES6, 70 bytes
*Saved 1 byte thanks to @user81655*
```
f=n=>n?+[...+[...''+(b=f(n-1))].reverse().join``+b+''].sort().join``:1
```
*sigh* JavaScript is really verbose. A **lot** (> 50%) of the code is just case to string + array function + join + cast to int. I've tried reduce, eval, and all sorts of stuff but this seems to be the shortest.
[Try it online](http://vihanserver.tk/p/esfiddle/?code=f%3Dn%3D%3En%3F%2B%5B...''%2B((b%3Df(n-1))%2B%20%2B%5B...''%2Bb%5D.reverse().join%60%60)%5D.sort().join%60%60%3A1%0A%0Af(7)) (All browsers work)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes
```
0,1 .|-1=:0&Rr+R=o.
```
### Explanation
```
0,1 . § If Input is 0, unify the Output with 1
| § Else
-1=:0&R § unify R with the output of this main predicate, with input = Input - 1
r+R=o. § Reverse R, add it to itself and order it, then unify with the Output.
```
[Answer]
## Haskell, 67 bytes
```
import Data.List
g i=i:g(sort$show$read i+read(reverse i))
(g"1"!!)
```
Usage example: `(g"1"!!) 7`-> `"668"`.
It's a direct implementation of the definition: starting with `"1"`, repeatedly append the reverse-add-sort result of the current element. The main function `(g"1"!!)` picks the `i`th element.
[Answer]
# Julia, 77 bytes
```
n->(x=1;for _=1:n x=(p=parse)(join(sort(["$(x+p(reverse("$x")))"...])))end;x)
```
This is a lambda function that accepts an integer and returns an integer. To call it, assign it to a variable.
Ungolfed:
```
function f(n::Int)
# Begin x at 1
x = 1
# Repeat this process n times
for _ = 1:n
# Add x to itself with reversed digits
s = x + parse(reverse("$x"))
# Refine x as this number with the digits sorted
x = parse(join(sort(["$s"...])))
end
# Return x after the process (will be 1 if n was 0)
return x
end
```
[Answer]
# Jelly, ~~13~~ 12 bytes
I'm sure this can probably be golfed, as this is my first answer in Jelly/in a tacit language.
```
DUḌ+ðDṢḌ Performs RATS
1Ç¡ Loops
D Converts integer to decimal
U Reverses
Ḍ Converts back to integer
+ Adds original and reversed
ð Starts new chain
D Converts back to decimal
Ṣ Sorts
Ḍ Back to integer again
1 Uses 1 instead of input
Ḍ Uses line above
¡ For loop
```
EDIT: Saved 1 byte, thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)
[Answer]
# [Perl 6](http://perl6.org), 40 bytes
```
{(1,{[~] ($_+.flip).comb.sort}...*)[$_]} # 40
```
( If you want it to return an Int put a `+` right before `[~]` )
### Usage:
```
# give it a lexical name
my &RATS = {…}
say RATS 5; # 77
# This implementation also accepts a list of indexes
# the first 10 of the sequence
say RATS ^10; # (1 2 4 8 16 77 145 668 1345 6677)
```
[Answer]
## Java 1.8, 251 bytes
```
interface R{static void main(String[]a){int i,r,n=1,c=0,t=Byte.valueOf(a[0]);while(++c<=t){i=n;for(r=0;i!=0;i/=10){r=r*10+i%10;}n+=r;a[0]=n+"";char[]f=a[0].toCharArray();java.util.Arrays.sort(f);n=Integer.valueOf(new String(f));}System.out.print(n);}}
```
### Expanded
```
interface R{
static void main(String[]args){
int input,reversed,nextValue=1,count=0,target=Byte.valueOf(args[0]);
while(++count<=target){
input=nextValue;
for(reversed=0;input!=0;input/=10){reversed=reversed*10+input%10;}
nextValue+=reversed;
args[0]=nextValue+"";
char[]sortMe=args[0].toCharArray();
java.util.Arrays.sort(sortMe);
nextValue=Integer.valueOf(new String(sortMe));
}
System.out.print(nextValue);
}
}
```
[Answer]
## Seriously, 17 bytes
```
1,`;$R≈+$S≈`n
```
[Try it online!](http://seriously.tryitonline.net/#code=MSxgOyRS4omIKyRT4omIYG4&input=NQ)
Explanation:
```
1,`;$R≈+$S≈`n
1 push 1
,` `n do the following n times:
;$R≈ reverse
+ add
$S≈ sort
```
[Answer]
# Lua, ~~179~~ 156 Bytes
~~I can't see how I could golf it more, but I'm sure there's a way.~~ Thanks to @LeakyNun I took the time to come down on this and golf it the proper way, I could maybe still win some bytes by using another approach.
```
k=0z=table
for i=0,io.read()do
t={}(""..k+(""..k):reverse()):gsub("%d",function(d)t[#t+1]=d
end)z.sort(t)k=k<1 and 1or tonumber(z.concat(t,""))
end
print(k)
```
### Ungolfed and explanations
```
k=0
z=table -- z is a pointer on the table named table
-- it allows me to use its functions
-- while saving 4 bytes/use
for i=0,io.read() -- Iterate n times for the nth element
do
t={}
(""..a+(""..a):reverse()) -- we add k with its "reversed" value
-- and convert the whole thing to a string
:gsub(".",function(d) -- for each character in it, use an anonymous fucntion
t[#t+1]=d end) -- which insert them in the array t
z.sort(t)
a=a<1 and 1 or -- if i==0, k=1
tonumber(z.concat(t,"")) -- else we concat t in a string and convert it to number
end
print(k)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) 2, 11 bytes, language postdates challenge
```
;1{↔;?+o}ⁱ⁽
```
[Try it online!](https://tio.run/nexus/brachylog2#@29tWP2obYq1vXZ@7aPGjY8a9/7/b/4/CgA "Brachylog – TIO Nexus")
## Explanation
```
;1{↔;?+o}ⁱ⁽
{ }ⁱ Repeatedly apply the following,
1 starting at 1,
; ⁽ a number of times equal to the input:
↔ reverse,
;?+ add the original input,
o then sort the resulting number
```
I'm not quite clear on what this does with zero digits, but the question doesn't state any particular handling, and they probably don't appear in the sequence anyway.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
!¡ödOdS+↔1
```
[Try it online!](https://tio.run/##yygtzv7/X/HQwsPbUvxTgrUftU0x/P//vwUA "Husk – Try It Online")
1-indexed.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~70~~ 66 bytes
```
f=lambda n,a=1:n<1or int(''.join(sorted(`f(n-1)+f(n-1,-1)`))[::a])
```
[Try it online!](https://tio.run/##HYxBDoIwEEX3nmLChplYiGXZiBcxJIyBQolMSe3GEM5eqqv/Fu/97RtnL01Ktn3z@hoYRHGrjdy1D@AkYlnWi3eCHx/iOGBvUSpN1/@oTD3R0xjuKNlfkRsILNOI@kbmAlvIJ1DsB1QP2I@iztbKEZ0Ci44onQ "Python 2 – Try It Online")
[Answer]
## ES6, 79 bytes
```
n=>eval("r=1;while(n--)r=+[...+[...r+''].reverse().join``+r+''].sort().join``")
```
82 bytes without `eval`:
```
n=>[...Array(n)].reduce(r=>+[...+[...r+''].reverse().join``+r+''].sort().join``,1)
```
All those conversions are painful.
@edc65 I actually saved 4 bytes by switching from `map` to `reduce` this time... no doubt you'll prove me wrong again though.
[Answer]
## Python 2, 91 Bytes
Input as Integer, result is printed to the screen.
```
def f(n):
t=1
for i in range(n):t=int("".join(sorted(str(int(str(t)[::-1])+t))))
print t
```
This could be a lot shorter with some recursion magic I guess, but I cant wrap my head around it yet. Gonna have a fresh look later and hopefully improve this one.
[Answer]
## Python 2, 83 bytes
```
def f(n):
v='1'
for _ in v*n:v=''.join(sorted(str(int(v)+int(v[::-1]))))
print v
```
[Answer]
# Mathematica 10.3, ~~66~~ 61 bytes
```
Nest[FromDigits@Sort@IntegerDigits[#+IntegerReverse@#]&,1,#]&
```
Quite simple.
[Answer]
# PHP, 102 Bytes
```
$r=[1];$i++<$argn;sort($v),$r[]=join($v))$v=str_split(bcadd(strrev($e=end($r)),$e));echo$r[$argn];
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/3ce999f7aa824bbe12ccfe4421222922a3f64698)
## PHP, 95 Bytes
n <= 39
```
for($r=[1];$i++<$argn;sort($v),$r[]=join($v))$v=str_split(strrev($e=end($r))+$e);echo$r[$argn];
```
[Answer]
# [Java](http://openjdk.java.net/), ~~171~~ ~~167~~ ~~163~~ 160 bytes
```
int f(int n){int a=n>0?f(n-1):0,x=10,b[]=new int[x],c=a,d=0;for(;c>0;c/=x)d=d*x+c%x;for(a+=d;a>0;a/=x)b[a%x]++;for(;a<x;c=b[a++]-->0?c*x+--a:c);return n>0?c:1;}
```
[Try it online!](https://tio.run/nexus/java-openjdk#JZDPioMwEMbP61OEQiHZGFdPBdPYJ9hTj5LDGLUEbBSN2yzis7uT7WU@mG/@/GamtRmsIWaAZSHfYN12WOdJT2N0bIsCylX5radOFKzM06CKPG1qrVz3IujXQadGQdqqXPbjTKWpcmm@VGCtaj8DN@fwnweuWgnoQfSaGs5Bc/5ugWuQRmGOcy0EbjPYKASUhsm58@vsSGQwZSH3Y3ozLx48ys9oW/JEcnr3s3WPWsP8WNiWfMTJkd8imL2qi7ScM3L/XXz3zMbVZxPW@8FRy0@kIiceD4o/oCzDBzAmkz3Zjz8 "Java (OpenJDK 8) – TIO Nexus")
Not the longest entry! \o/
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 20 bytes
```
{x{.o@<o:$x+.|$x}/1}
```
[Try it online!](https://tio.run/##y9bNz/7/P82quqJaL9/BJt9KpUJbr0alolbfsPZ/mrqixX8A "K (oK) – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 56 bytes
```
Stream.iterate("1"){p=>p.toInt+p.reverse.toInt+""sorted}
```
[Try it online!](https://tio.run/##LcwxCsMgFAbgPaf4cVIKkhzAQMcOnXoCa57Ukj5FHyEQcnbboeO3fC341ff8fFMQ3H1i0C7ES8O1FBwDsPkVEQ79IZX8xyah6oW0mpQ5ipuLlXxjuRRbaaPa6G@lWq5Cy9kBPUIyptHYmH9JeGmGm1FqYllZR83GmOHsXw "Scala – Try It Online")
An infinite stream.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 9 bytes
```
=1:sZ+\rZ
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/39bQqjhKO6Yo6v9/AA "cQuents – Try It Online")
1-indexed.
## Explanation
```
=1 first term is 1
: sequence mode
each term equals
s sort( )
Z previous
+ plus
\r reverse( )
Z previous
```
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 51 bytes
```
$.=join'',sort(($.+reverse$.)=~/./g)while$_--;say$.
```
[Try it online!](https://tio.run/##K0gtyjH9/19FzzYrPzNPXV2nOL@oRENDRU@7KLUstag4VUVP07ZOX08/XbM8IzMnVSVeV9e6OLFSRe//f/N/@QUlmfl5xf91fU31DAwN/usm5gAA "Perl 5 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~7~~ 5 bytes
```
1?(ms
```
[Try it Online!](http://lyxal.pythonanywhere.com?s=?flags=&code=1?(ms&inputs=7&header=&footer=)
## Explained
```
1?(ms
1? # Push 1 followed by the input
( # for n in range(0, input):
m # push tos + tos[::-1] (palindromize on integers doesn't make it a palindrome)
+s # add and sort the result
```
It's a shame how in order to remain competitive, one has to port other answers. Why do I say this? Because I have a nifty 21 byte function that accomplishes the same task:
```
@f:1|0=[1|n⨪@f;:ʼn+]s;
```
Example usage:
```
6 @f; , # Single number
0 11 r °f; z # Provide a test case unit kinda display
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~91~~ ~~89~~ ~~87~~ 76 bytes
```
$ofs=''
for($c="1";$args[0]--){$c="$("$(+$c+"$($c[20..0])")"|% t*y|sort)"}$c
```
[Try it online!](https://tio.run/##JcvNCoMwEATgu08hYVtNJRK1f1LyJOKhLIk9CCkboRT12VO7wvANDMzbfyyFlx1HhZ5sBGfmCN4Fk2WJ85QDGlGJBzxpCJ3ulZLzf4J8SwFYbAXY1bosdS@FFMshnU7fJXiapFgB45ocwaWardiabdgze2Gv7I29s@3@2s9NG38 "PowerShell Core – Try It Online")
PowerShell converts strings to `long` by default. The maximum length would always be 19 chars.
Cool challenge!
-2 bytes thanks to Mazzy!
[Answer]
# Axiom, 146 bytes
```
c(r:String):NNI==reduce(+,[(ord(r.i)-48)*10^(#r-i) for i in 1..#r]);f(n:INT):NNI==(n<1=>1;v:=f(n-1);v:=v+c(reverse(v::String));c(sort(v::String)))
```
test and results [RATS sequence]
```
(3) -> [[i, f(i)] for i in 0..20]
(3)
[[0,1], [1,2], [2,4], [3,8], [4,16], [5,77], [6,145], [7,668], [8,1345],
[9,6677], [10,13444], [11,55778], [12,133345], [13,666677], [14,1333444],
[15,5567777], [16,12333445], [17,66666677], [18,133333444], [19,556667777],
[20,1233334444]]
```
] |
[Question]
[
Almost six years ago, fellow PPCG member steenslag [posted](https://codegolf.stackexchange.com/q/958/13486) the following challenge:
>
> In a standard dice (die) the numbers are arranged so that opposite
> faces add to seven. Write the shortest possible program in your
> preferred language which outputs a random throw followed by 9 random
> tippings. A tipping is a quarter turn of the dice, e.g. if the dice is
> facing 5, all possible tippings are 1,3,4 and 6.
>
>
> Example of desired output:
>
>
>
> >
> > 1532131356
> >
> >
> >
>
>
>
So, now that everybody has completely forgotten about it and the winning answer has long since been accepted, we'll be writing a program to validate the die tipping sequences generated by the submitted solutions. (This makes sense. Just pretend it does.)
# Challenge
Your [program or function](http://meta.codegolf.stackexchange.com/a/2422/13486 "Default for Code Golf: Program, Function or Snippet?") is given a sequence such as `1532131356`. Validate that each consecutive digit is:
* Not equal to the previous digit
* Not equal to *7* minus *the previous digit*
(You don't have to validate the first digit.)
## Rules
* Your program must return a [truthy value if the input is valid and a falsey value](http://meta.codegolf.stackexchange.com/a/2194/13486 "Interpretation of Truthy/Falsey") otherwise.
* You can assume that the input consists of only the digits 1-6 and is at least 1 character long. Sequences won't have a fixed length like in steenslag's challenge.
* You can take the input as a string (`"324324"`), an array or array-like datastructure (`[1,3,5]`) or as multiple arguments (`yourFunction(1,2,4)`).
Standard [I/O](http://meta.codegolf.stackexchange.com/q/2447/13486) and [loophole](http://meta.codegolf.stackexchange.com/q/1061/13486) rules apply.
# Test cases
## Truthy
```
1353531414
3132124215
4142124136
46
4264626313135414154
6
2642156451212623232354621262412315654626212421451351563264123656353126413154124151545145146535351323
5414142
```
## Falsey
* Repeated digit
```
11
3132124225
6423126354214136312144245354241324231415135454535141512135141323542451231236354513265426114231536245
553141454631
14265411
```
* Opposing side of die
```
16
42123523545426464236231321
61362462636351
62362462636361
```
[Answer]
# Python 2, 43 45 bytes
```
lambda s:reduce(lambda p,n:n*(7-p!=n!=p>0),s)
```
# 43 bytes (inspired heavily by @Zgarb)
```
lambda s:reduce(lambda p,n:n*(p>0<n^p<7),s)
```
This function combines my reduce statement with the bit-flicking logic from @Zgarb's answer, for a combination that is shorter than both.
Both answers output the following:
* 0 if the input is not a valid sequence
* The last digit of the sequence if it is valid
[Answer]
## Python, 44 bytes
```
lambda x:all(0<a^b<7for a,b in zip(x,x[1:]))
```
Bitwise magic!
This is an anonymous function that takes a list of integers, and checks that the XOR of every two consecutive elements is between 1 and 6 inclusive.
## Why it works
First, the XOR is always between 0 and 7 inclusive, since 7 is `111` in base 2, and our numbers have at most 3 binary digits.
For the equality, `a^b == 0` if and only if `a == b`.
Also, we have `7-a == 7^a` when `0 ≤ a ≤ 7`, and thus `a^b == 7` if and only if `a == 7^b == 7-b`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes
***-2 bytes for Osable's smart idea of using a product.***
```
¥¹D7-Á+«P
```
[Try it online!](https://tio.run/nexus/05ab1e#@39o6aGdLua6hxu1D60O@P8/2lDHOBYA "05AB1E – TIO Nexus")
```
¥ # Push deltas.
¹D7-Á # Push original array, and 7 - [Array] shifted right once.
+ # Add original to the 7 - [Array] shifted right.
« # Concat both.
P # Product, if either contain a zero, results in 0, meaning false.
```
Third approach using 05AB1E, that doesn't use the pairwise command:
* `0` if it violates the tipsy properties.
* `Not 0` if there was nothing preventing it from being tipsy.
[Answer]
# R, ~~39~~ ~~37~~ ~~32~~ 31 bytes
```
all(q<-diff(x<-scan()),2*x+q-7)
```
[Try it online!](https://tio.run/##K/r/PzEnR6PQRjclMy1No8JGtzg5MU9DU1PHSKtCu1DXXPO/iYKRgpmCCRCDaGMFQyg2BYoZgjGQ9R8A "R – Try It Online")
Takes input from stdin. Uses `diff` to see if any two consecutive digits are the same; then compares each digit to 7 minus the previous digit. Returns `TRUE` or `FALSE`.
Saved 5 bytes thanks to Jarko Dubbeldam, and another thanks to JayCe.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
$ü+7ʹüÊ*P
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@69yeI@2@eGuQzsP7zncpRXw/7@xobGRoZGJkaEpAA "05AB1E – TIO Nexus")
[Answer]
## R, 49 44 bytes
```
!any(rle(x<-scan())$l-1,ts(x)==7-lag(ts(x)))
```
Reads input from stdin (separated by space) and outputs `TRUE/FALSE`. Will give a warning if input is of length one but still works.
Edit: saved a couple of bytes thanks to @rturnbull
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
ü+7å¹ü-0å¹g_~~_
```
[Try it online!](https://tio.run/nexus/05ab1e#@394j7b54aWHdh7eo2sAotPj6@ri//83NjQ2MjQyMTIyBQA "05AB1E – TIO Nexus") or as a [Test suite](https://tio.run/nexus/05ab1e#RZBNTkNBDIP3uQog4fxxnC65ARIS6m24RXc92OvnVwk0I00cO4knx8/X9/328nH/5Xl75/m8XK@X1@NQDUetjlKlslMTQIeqjebm9ubCo4bSdGyQRLo9QrpZPoPOoJUFZ7jPnshqSBVlkEvEWAOE7VmwiHzXltBnxTmuM6Q/eznBZNcyjsaYBKg7e5whkebdETzOniB1BqfNtO2yEUvI4TVXcuEUH5iY51r4QykgUOBCXgd1k2dvb4Yavm93sXKtd0VfYP7D1QM)
[Answer]
## JavaScript (ES6), ~~43~~ 40 bytes
Returns `0` / `true`.
```
f=([k,...a],n=0)=>!k||k-n&&7-k-n&&f(a,k)
```
### Test cases
```
f=([k,...a],n=0)=>!k||k-n&&7-k-n&&f(a,k)
console.log('Testing truthy cases ...');
console.log(f('1353531414'));
console.log(f('3132124215'));
console.log(f('4142124136'));
console.log(f('46'));
console.log(f('4264626313135414154'));
console.log(f('6'));
console.log(f('2642156451212623232354621262412315654626212421451351563264123656353126413154124151545145146535351323'));
console.log(f('5414142'));
console.log('Testing falsy cases ...');
console.log(f('11'));
console.log(f('3132124225'));
console.log(f('6423126354214136312144245354241324231415135454535141512135141323542451231236354513265426114231536245'));
console.log(f('553141454631'));
console.log(f('14265411'));
console.log(f('16'));
console.log(f('42123523545426464236231321'));
console.log(f('61362462636351'));
console.log(f('62362462636361'));
```
[Answer]
# [Perl 6](http://perl6.org/), 22 bytes
Using a regex:
```
{!/(.)<{"$0|"~7-$0}>/}
```
Takes the input as a string. Inspired by [G B's Ruby answer](https://codegolf.stackexchange.com/a/104048/14880).
How it works:
* `/ /`: A regex.
* `(.)`: Match any character, and capture it as `$0`.
* `<{ }>`: Dynamically generate a sub-regex to be matched at that position.
* `"$0|" ~ (7 - $0)`: The sub-regex we generate is one that matches only the previous digit, or 7 minus the previous digit (e.g. `5|2`).
Thus the overall regex will match iff it finds an invalid consecutive pair of digits anywhere.
* `{! }`: Coerce to a boolean (causing the regex to be matched against `$_`), negate it, and turn the whole thing into a lambda (with implicit parameter `$_`).
# [Perl 6](http://perl6.org/), 38 bytes
Using list processing:
```
{all ([!=] 7-.[1],|$_ for .[1..*]Z$_)}
```
Takes the input as an array of integers.
How it works:
* `.[1..*] Z $_`: Zip the input list with an offset-by-one version of itself, to generate a list of 2-tuples of consecutive digits.
* `[!=] 7 - .[1], |$_`: For each of those, check if `(7 - b) != a != b`.
* `all ( )`: Return a truthy or falsy value depending on whether all loop iterations returned True.
[Answer]
## Python, 38 bytes
```
f=lambda h,*t:t==()or 7>h^t[0]>0<f(*t)
```
A recursive function that takes arguments like `f(1,2,3)`.
This makes use of argument unpacking to extract the first number into `h` and the rest into the tuple `t`. If `t` is empty, output True. Otherwise, use [Zgarb's bit trick](https://codegolf.stackexchange.com/a/104074/20260) to check that the first two die rolls are not incompatible. Then, check that the result also holds on the recursive call on the tail.
[Answer]
## Ruby, 34 bytes
```
->s{!s[/[16]{2}|[25]{2}|[34]{2}/]}
```
[Answer]
# JavaScript ~~61~~ 43 bytes
Comments have mentioned I can't use C# linq functions without including the using statement, so here's the exact same in less bytes using standard JS...
```
f=a=>a.reduce((i,j)=>i>6|i==j|i+j==7?9:j)<7
```
# C#, ~~99~~ ~~67~~ 65 bytes
Takes input as an int array `a`
```
// new solution using linq
bool A(int[]a){return a.Aggregate((i,j)=>i>6|i==j|i+j==7?9:j)<7;}
```
```
// old solution using for loop
bool A(int[]a){for(int i=1;i<a.Length;)if(a[i]==a[i-1]|a[i-1]+a[i++]==7)return false;return true;}
```
Explanation:
```
// method that returns a boolean taking an integer array as a parameter
bool A(int[] a)
{
// aggregate loops over a collection,
// returning the output of the lambda
// as the first argument of the next iteration
return a.Aggregate((i, j) => i > 6 // if the first arg (i) > than 6
| i == j // or i and j match
| i + j == 7 // or i + j = 7
? 9 // return 9 as the output (and therefore the next i value)
: j // otherwise return j as the output (and therefore the next i value)
)
// if the output is ever set to 9 then it will be carried through to the end
< 7; // return the output is less than 7 (not 9)
}
```
[Answer]
# ><> (Fish) 47 bytes
```
0:i:1+?!v\!
0n;n1< >
!?-{:-"0"/^
!? -{-$7:/^
```
Pretty simple;
Line 1: check to see if inputted a number, if no number (EOF) then we have a truthy to print else checks.
Line 2: print outcome.
Line 3: turn input into number (ASCII 0 - from input), then check if it's equal to previous input.
Line 4: check if input is opposite side of die.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) 128 Bytes
```
(()){{}(({}<>)<>[({})])}{}([]){{{}}<>}{}([]){{}({}({})<>)<>([][()])}{}(<{}>)<>(([])){{}{}({}[(()()()){}()]){<>}<>([][()])}({}{})
```
Outputs 0 for falsey, or -7 for truthy.
[Try it Online!](http://brain-flak.tryitonline.net/#code=KCgpKXt7fSgoe308Pik8Plsoe30pXSl9e30oW10pe3t7fX08Pn17fShbXSl7e30oe30oe30pPD4pPD4oW11bKCldKX17fSg8e30-KTw-KChbXSkpe3t9e30oe31bKCgpKCkoKSl7fSgpXSl7PD59PD4oW11bKCldKX0oe317fSk&input=MiA2IDQgMiAxIDUgNiA0IDUgMSAyIDEgMiA2IDIgMyAyIDMgMiAzIDUgNCA2IDIgMSAyIDYgMiA0IDEgMiAzIDEgNSA2IDUgNCA2IDIgNiAyIDEgMiA0IDIgMSA0IDUgMSAzIDUgMSA1IDYgMyAyIDYgNCAxIDIgMyA2IDUgNiAzIDUgMyAxIDIgNiA0IDEgMyAxIDUgNCAxIDIgNCAxIDUgMSA1IDQgNSAxIDQgNSAxIDQgNiA1IDMgNSAzIDUgMSAzIDIgMw) (Truthy)
[Try it Online!](http://brain-flak.tryitonline.net/#code=KCgpKXt7fSgoe308Pik8Plsoe30pXSl9e30oW10pe3t7fX08Pn17fShbXSl7e30oe30oe30pPD4pPD4oW11bKCldKX17fSg8e30-KTw-KChbXSkpe3t9e30oe31bKCgpKCkoKSl7fSgpXSl7PD59PD4oW11bKCldKX0oe317fSk&input=NiA0IDIgMyAxIDIgNiAzIDUgNCAyIDEgNCAxIDMgNiAzIDEgMiAxIDQgNCAyIDQgNSAzIDUgNCAyIDQgMSAzIDIgNCAyIDMgMSA0IDEgNSAxIDMgNSA0IDUgNCA1IDMgNSAxIDQgMSA1IDEgMiAxIDMgNSAxIDQgMSAzIDIgMyA1IDQgMiA0IDUgMSAyIDMgMSAyIDMgNiAzIDUgNCA1IDEgMyAyIDYgNSA0IDIgNiAxIDEgNCAyIDMgMSA1IDMgNiAyIDQgNQ) (Flasey)
**Explanation (t stands for top and s stands for second from the top):**
```
(()) # push a 1 to get this loop started
{{} # loop through all pairs, or until 2 are equal
(({}<>)<>[({})]) # pop t, push t on the other stack, and t - s on this one
}{} # end loop and pop one more time
([]) # push the height of the stack
{ # if the height isn't 0 (there were equal numbers)...
{{}}<> # pop everything from this stack and switch
} # end if
{{} # for every pair on the stack: pop the height and...
({}({})<>)<> # push t + s on the other stack leaving s on this one
([][()]) # push the height - 1
} # end loop when there is only 1 number left
{}(<{}>)<> # pop t, pop s, push 0 and switch stacks
(([])) # push the height twice
{ # loop through every pair
{}{} # pop the height and what was t - 7
({}[(()()()){}()]) # push t - 7
{<>}<> # if t is not 0 switch stacks and come come back
# if t is 0 (ie, there was a pair that added to 7) just switch once
([][()]) # push height - 1
} # end loop
({}{}) # push t + s (either 0 + 0 or 0 + -7)
```
[Answer]
# MATLAB, 30 bytes
```
@(a)all(diff(a)&movsum(a,2)-7)
```
[Answer]
# PHP, 63 bytes
```
for($d=$argv[$i=1];$c=$argv[++$i];$d=$c)$d-$c&&$d+$c-7?:die(1);
```
takes input as list of command arguments; exits with `1` (error) if input is invalid, `0` (ok) if valid.
Run with `-nr`.
**input as string argument, 65 bytes**
```
for($d=($s=$argv[1])[0];$c=$s[++$i];$d=$c)$d-$c&&$d+$c-7?:die(1);
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~57~~ ~~44~~ 41 bytes
*([Crossed out 44 is still regular 44](http://meta.codegolf.stackexchange.com/a/7427/42963))*
```
0-notin($args|%{7-$_-$l-and$l-ne($l=$_)})
```
[Try it online!](https://tio.run/nexus/powershell#@2@gm5dfkpmnoZJYlF5co1ptrqsSr6uSo5uYlwIk81I1VHJsVeI1azX///9v9t/wv/F/MwA "PowerShell – TIO Nexus")
*(OP has clarified that taking input as separate arguments is OK - saved 13 bytes ... saved another 3 bytes by eliminating `$b`)*
We're looping through the input `$args` a digit at a time. Each digit, we verify that the `$l`ast digit is `-n`ot`e`qual to the current digit `$_`, and that `7-$_-$l` is some number other than zero (which is truthy). Those Boolean results are encapsulated in parens and fed into the right-hand operand of the `-notin` operator, checking against `0`. In other words, if there is any `False` value anywhere in the loop, the `-notin` will also be `False`. That Boolean is left on the pipeline, and output is implicit.
Lengthy because of the `$` requirement for variable names, and that Boolean commands `-ne` `-and` are verbose in PowerShell. Oh well.
[Answer]
# Processing, ~~93~~ ~~92~~ 90 bytes
*Changed* `||` *to* `|` *: 1 byte saved thanks to @ClaytonRamsey*
*Started counting backwards: 2 bytes saved thanks to @IsmaelMiguel*
```
int b(int[]s){for(int i=s.length;--i>0;)if(s[i-1]==s[i]|s[i-1]==7-s[i])return 0;return 1;}
```
Takes input as an array of ints, output `1` for true or `0` for false.
### Ungolfed
```
int Q104044(int[]s){
for(int i=s.length;--i>0;)
if(s[i-1]==s[i]|s[i-1]==7-s[i])
return 0;
return 1;
}
```
[Answer]
**C ~~47~~ 44 bytes**
```
F(char*s){return!s[1]||(*s^s[1])%7&&F(s+1);}
```
takes a string of digits (or a zero terminated array of bytes)
Explanation
`F(char*s){`
according to the standard `int` return type is implied. (saving 4 bytes)
`return` unconditional return because this is a recursive function
using shortcut evaluation:
`!s[1]||` if the second character is *nul* return true
`((*s^s[1])%7&&` if the first two charcters aren't legal false
`F(s+1))` check the rest of the string in the same way
that confusing expression
`*s` is the first character `s[1]` is the second
`*s^s[1]` exclusive-ors them together if they are the same the result is 0
if they add to 7 the result is 7 , (if they differ and don't add to 7 the result is between 1 and 6 inclusive)
so `(*s^s[1])%7` is zero for bad input and non-zero otherwise, thus false if these 2 characters are bad, and true otherwise
**comment:** as this function call uses only end-recursion (only the last statement is a recursive call) an optimiser could translate the recursion into a loop, this is a happy conicidence and is obviously not worth any golf score, but in the real word makes it possible to process strings of any length without running out of stack.
[Answer]
# Python, 71 bytes
```
f=lambda s:len(s)<2or(s[0]!=s[1]and int(s[0])!=7-int(s[1]))and f(s[1:])
```
Uses a recursive approach.
Explanation:
```
f=lambda s: # Define a function which takes an argument, s
len(s)<2 or # Return True if s is just one character
(s[0]!=s[1] # If the first two characters matches or...
and int(s[0])!=7-int(s[1]) # the first character is 7 - the next character, then return False
)and f(s[1:]) # Else, recurse with s without the first character
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 28 bytes
```
M`(.)\1|16|25|34|43|52|61
^0
```
[Try it online!](https://tio.run/nexus/retina#RZDLTYRBDIPv6QNpuSCcVwuc6ACttpDpffn8rwSaOcSxkzh5u309nt@P28f7j4725Jzq03Umzyrun8@nanhqdZQqlZ2aADpUbTQ/tzcXHjWUpmODJNLtEdLN8ht0Bq0sOMN99URWQ6oog1wixhogbM@CReS/toQ@K65xnSH92csJJruWcTTGJEDd2eMMiTTvjuBx9gKpK7hspm2XjVhCDq@5kgunWGBiXmdhh1JAoMCFfA7qJq/evgw1rG93sXKtb0VfYP7D1S8 "Retina – TIO Nexus")
Alternatively:
```
M`[16]{2}|[25]{2}|[34]{2}
^0
```
[Try it online!](https://tio.run/nexus/retina#RZDLbQNBDEPv6iNAjqZ@LeSUCowE7sNJ7evHXSDBDDCiSEkcvb1/PI7Px1379czfn3vO9Vb7je/bcaiGo1ZHqVLZqQmgQ9VGc3N7c@FRQ2k6Nkgi3R4h3SyfQWfQyoIz3KsnshpSRRnkEjHWAGF7Fiwi37Ul9FlxjusM6c9eTjDZtYyjMSYB6s4eZ0ikeXcEj7MnSJ3BaTNtu2zEEnJ4zZVcOMUHJuZaC38oBQQKXMjroG7y7O3NUMP37S5WrvWu6AvMf7h6AQ)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
dG2YCs7-h
```
The input is an array of numbers representing the digits.
The output is a non-empty array, which is truthy if all its entries are non-zero, and falsy otherwise (read more about MATL's criterion for truthy and falsy [here](https://codegolf.stackexchange.com/a/95057/36398)).
[Try it online!](https://tio.run/nexus/matl#@5/ibhTpXGyum/H/f7ShgrGCKRQbKpiAcCwA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#bVI9T0MxDNz5FdnexBA7DiMDbF0ZQFUlkBDqwETL0KG//ZH4zuYNHfJl587nS95fd@vnTt6eTg/3x/VxOf/8no@X5bp8fXyfLsvh@WXd16LFOGppcxzu9nOvRcYsIzZXG1HPZnTe6B7FLKWPaPcV@DFshMhrzjzv4qaz@s6csTpSvC6GkS8yzXdKnGW1rU6wqc/mSlANyM4Yuo0MGFv2ZTxb8jVHhlPwRkcnQNGXca6l3nBP3D30HHXRnRCt9Azn5jjLO418gQ@NSpUtdUVG0oPA/nNZuiisa@ma0Ne5Vr423FG@gHnXm9/Cd1DvvBILXxCJ31GpQja64880apGS3rljNevGv4JeZOVmts/sHw).
### Explanation
```
d % Take input implicitly. Consecutive differences
G % Push input again
2YC % Overlapping blocks of length 2, arranged as columns of a matrix
s % Sum of each column
7- % Subtract 7, element-wise
h % Concatenate horizontally. Implicitly display
```
[Answer]
# C# (with Linq) ~~90~~ ~~81~~ ~~73~~ ~~71~~ ~~69~~ 68 Bytes
```
using System.Linq;n=>n.Aggregate((p,c)=>p<9|c==p|c==103-p?'\b':c)>9;
```
## Explanation:
```
using System.Linq; //Obligatory import
n=>n.Aggregate((p,c)=> //p serves as both previous character in chain and error flag
p<9 //8 is the error flag, if true input is already invalid
|c==p
|c==103-p //103 comes from 55(7) + 48(0)
?'\b' //'\b' because it has a single digit code (8)
:c) //valid so set previous character, this catches the first digit case as well
>8; //as long as the output char is not a backspace input is valid
```
[Answer]
**C, 81 bytes, was 85 bytes**
```
int F(int *A,int L){int s=1;while(--L)s&=A[L]!=A[L-1]&A[L]!=(7-A[L-1]);return s;}
```
Input is an array of integers A with length L.
Returns 1 for true and 0 for false. The input is checked from the end to the start using the input length L as the array index.
[Answer]
## Haskell, 37 bytes
```
f(a:b:c)=a+b/=7&&a/=b&&f(b:c)
f _=1<2
```
Usage example: `f [1,5,2]` -> `False`.
Simple recursion. Base case: single element list, which returns `True`. Recursive case: let `a` and `b` be the first two elements of the input list and `c` the rest. All of the following conditions must hold: `a+b/=7`, `a/=b` and the recursive call with `a` dropped.
[Answer]
## JavaScript, 40 bytes
```
f=i=>i.reduce((a,b)=>a&&a-b&&a+b-7&&b,9)
```
Takes advantage of the JavaScript feature that `&&` will return the last value that is parsed (either the falsy term or the last term). `0` is passed along if it doesn't meet the conditions, and the previous term is passed along otherwise. The 9 makes sure that it starts with a truthy value.
[Answer]
# Groovy, 61 bytes
```
{i=0;!(true in it.tail().collect{x->x in [7-it[i],it[i++]]})}
```
[Answer]
# Python 2, 58 Bytes
```
lambda x:all(x[i]!=x[i+1]!=7-x[i]for i in range(len(x)-1))
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 39 bytes
```
0>i'0'-::&0)?v1n;>&!
?=0+=7+@=}:{:<;n0^
```
[Try it online!](http://fish.tryitonline.net/#code=MD5pJzAnLTo6JjApP3Yxbjs-JiEKPz0wKz03K0A9fTp7Ojw7bjBe&input=MjY0MjE1NjQ1MTIxMjYyMzIzMjM1NDYyMTI2MjQxMjMxNTY1NDYyNjIxMjQyMTQ1MTM1MTU2MzI2NDEyMzY1NjM1MzEyNjQxMzE1NDEyNDE1MTU0NTE0NTE0NjUzNTM1MTMyMw)
[Answer]
## Batch, 102 bytes
```
@set s=%1
@set/an=0%s:~0,2%,r=n%%9*(n%%7)
@if %r%==0 exit/b
@if %n% gtr 6 %0 %s:~1%
@echo 1
```
Ungolfed:
```
@echo off
rem grab the input string
set s=%1
:loop
rem convert the first two digits as octal
set /a n = 0%s:~0,2%
rem check for divisibility by 9 (011...066)
set /a r = n %% 9
rem exit with no (falsy) output if no remainder
if %r% == 0 exit/b
rem check for divisibility by 7 (016...061)
set /a r = n %% 7
rem exit with no (falsy) output if no remainder
if %r% == 0 exit/b
rem remove first digit
set s=%s:~1%
rem loop back if there were at least two digits
if %n% gtr 6 goto loop
rem truthy output
echo 1
```
] |
[Question]
[
A time in the format hhMMss is represented by six numbers in the range 0..9 (e.g.`100203` for 3 seconds after 2 minutes after 10am (10:02.03), or `155603` for three seconds after 56 minutes after 3pm (15:56.03).
Treating these times as integers, these numbers are therefore in the range `000000` to `235959`; but not all numbers in that range are valid times.
Normally, though, integers aren't represented with leading 0s, right?
So, this challenge is to take a numeric input (without leading 0s), and say whether it represents a proper time or not when the leading 0s are put back.
### Input
Any integer, as a string or an integer type, in the range `0..235959` inclusive. all numbers as strings will be input with no leading 0s (e.g. `2400`, not `002400`). The time `000000` maps to `0`; or [exceptionally as](https://codegolf.meta.stackexchange.com/questions/8395/is-the-empty-string-an-acceptable-decimal-representation-of-0) . Inputs outside of this range should return Falsy, but there is no requirement that they are supported.
### Output
Truthy/Falsy value - by which I mean there must be a consistent distinction in the output between True and False - e.g. True could be output as `1` and False could be any other output (or even a variable output) - as long as it can be documented how to tell what is True and what is not.
### More Challenge Details
Given the input integer, figure out if the number represents a time (Truthy) or not (Falsy).
A number represents a time if a time (hhMMss) with leading 0s removed is the same as the number.
e.g. 00:00.24 is represented by 24
e.g. 00:06.51 is represented by 651
e.g. 00:16.06 is represented by 1606
e.g. 05:24.00 is represented by 52400
e.g. 17:25.33 is represented by 172533
There are therefore some numbers that can't represent times:
e.g. 7520 - this can't represent hhMMss because 00:75:20 isn't a time
As a general rule, the valid numbers fall into the pattern:
`trimLeadingZeros([00..23][00..59][00..59]);`
*The following numbers are the entire set of inputs and the required answers for this challenge*
**Seconds only (e.g. 00:00.ss, with punctuation and leading 0s removed, -> ss)**
`0 to 59` - Truthy
`60 to 99` - Falsy
**Minutes and seconds (e.g. 00:MM.ss, with punctuation and leading zeros removed, -> MMss)**
`100 to 159` - Truthy
`160 to 199` - Falsy
etc, up to:
`2300 to 2359` - Truthy
`2360 to 2399` - Falsy
`2400 to 2459` - Truthy
`2460 to 2499` - Falsy
etc, up to:
`5900 to 5959` - Truthy
`5960 to 9999` - Falsy
**Hours 0..9, minutes and seconds (e.g. 0h:MM.ss with punctuation and leading zeros removed -> hMMss)**
`10000 to 10059` - Truthy
`10060 to 10099` - Falsy
etc, up to:
`15800 to 15859` - Truthy
`15860 to 15899` - Falsy
`15900 to 15959` - Truthy
`15960 to 19999` - Falsy
`20000 to 20059` - Truthy
`20060 to 20099` - Falsy
`20100 to 20159` - Truthy
`20160 to 20199` - Falsy
etc, up to:
`25800 to 25859` - Truthy
`25860 to 25899` - Falsy
`25900 to 25959` - Truthy
`25960 to 25999` - Falsy
etc, up to:
`95800 to 95859` - Truthy
`95860 to 95899` - Falsy
`95900 to 95959` - Truthy
`95960 to 99999` - Falsy
**Hours 10..23, minutes and seconds (e.g. hh:MM.ss with punctuation and leading zeros removed -> hhMMss)**
`100000 to 100059` - Truthy
`100060 to 100099` - Falsy
`100100 to 100159` - Truthy
`100160 to 100199` - Falsy
etc, up to:
`105800 to 105859` - Truthy
`105860 to 105899` - Falsy
`105900 to 105959` - Truthy
`105960 to 109999` - Falsy
This pattern is then repeated up to:
`235900 to 235959` - Truthy
(`236000 onwards` - Falsy, if supported by program)
Leading 0s must be truncated in the input, if strings are used.
Code golf, so least bytes wins - usual rules apply.
[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
[Answer]
# Python, ~~45~~ ~~43~~ ~~38~~ 27 bytes
For inputs up until 239999:
```
lambda n:n/100%100<60>n%100
```
You can [try it online](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKk/f0MBAFYhtzAzs8kCM/wVFmXklGmkaRsaGBmaWmpr/AQ)! Thanks @Jitse and @Scurpulose for saving me several bytes ;)
For inputs above 239999 go with 36 bytes:
```
lambda n:n/100%100<60>n%100<60>n/4e3
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~33~~ 25 bytes
*-7 bytes thanks to Kevin Cruijssen*
```
60>*.polymod(100,100).max
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPvfzMBOS68gP6cyNz9Fw9DAQAeINfVyEyv@W3MVFGXmlaQpKKmapSjY2imoFsfkKekoqMTrKNTpATWn5RcpGOgomFrqKJgBaUsgDTIAKAARMgALQoVBHCNjkNR/AA "Perl 6 – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~1~~9 [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")
-10 bytes thanks to Kevin Cruijssen.
Anonymous tacit prefix function. Takes argument as integer.
```
⍱59<100∘⊤
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HvRlNLG0MDg0cdMx51Lfmf9qhtwqPevkddzY961zzq3XJovfGjtomP@qYGBzkDyRAPz@D/hgq2CmkKBlwQ2tSAywDMMIMxLC25dHV1odJAo2EsU0uoAkO4UkOgWoiskTFcoZExXKWRMVypkTG6uQiTDQwQZhsYIEw3MEDRY2RqgbDE1AJhi6kFwhpTC7ibLJHUWyKpt0RSbwlWD7ID4WIDAwA "APL (Dyalog Extended) – Try It Online")
`100∘⊤` convert **T**o base-100
`59<` are they, each, greater than 59?
`⍱` are none of them true?
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~13~~ 12 bytes, supports inputs > 235959
```
твR₅0šR12*‹P
```
[Try it online!](https://tio.run/##yy9OTMpM/W90eK7NuS3ap@eUVdorKTxqm6SgZF/5/2LThU1Bj5paDY4uDDI00nrUsDPgv87/aEMdMwMdQwMgBtJGxgYgAsQyAbFMgCxTSwMQAVFlACZBbFMLAzAJZluC2SA1RmA1RmA1RgaGYDbYZLB6I7B6I7B6I7B6S7C4JVjcEixuibALQkF4hhCeIZgHsdwAYrsBxHoDiP3GEMONoTwzsHNM4IaBQCwA "05AB1E – Try It Online")
```
—Ç–≤ # convert input to base 100
R # reverse
‚ÇÖ # 255
0š # convert to list and prepend 0: [0, 2, 5, 5]
R # reverse: [5, 5, 2, 0]
12* # times 12: [60, 60, 24, 0]
‹ # a < b (vectorizes
P # product
```
[Answer]
# [Python](https://docs.python.org/3/), 35 bytes
```
f=lambda n:n<1or(n%100<60)*f(n/100)
```
A recursive function which returns `1` or `True` (which are truthy) if valid or `0` (which is falsey) if not.
**[Try it online!](https://tio.run/##VVLBTsMwDL3zFb6gJVDASZtqmbZ9BD@AiljHpC0dXXdA0769pLGdil5q@/n5OU8@/w7fXSiX534c282xOX1@NRBWYW26XoVHg7iuUT@1KrzFWI9t10Pbd6ePAoYODgGUwgKc1wWoOkY@RbG1AENVM5UN1W05AbZ0nNUpY6xKWMVYlbCKMOcxqTjOSClrJTVEJ3lNOeNuSdssneQ15YJ73lZwzxvzXjTfynxL863Mt2gIN4IbwuXNpG9F35K@FX1L@lb0LenHH@Ge@F74nvhe@J74Xvh@tmf2hwyZHRKLMPcY7jG5x3CPkR42ErOTyFZi9hLZTMxuItuJ2c@SH1ymHr16gPhdw@HnunvfXa7H4QIbuMWL0zBdW5iurG/Cfqfmw3sGo@@JeO4PYVCLCYLbalvfJ5iCly3c7ovXOOTUDDO5@C@m9fgH "Python 3.8 – Try It Online")** \*
### How?
`True` and `False` are equivalent to `1` and `0` respectively in Python.
The function (`f=lambda n:...`) checks that the last up-to-two digits as an integer (`n%100`) are less than sixty (`<60`), chops them off (`n/100`) and multiplies by a recursive call `*f(...)` until an input of zero is reached (`n<1or`) at which point `True` is returned. If at any stage the check fails a `False` is placed in the multiplication, which will then evaluate to `0` (a falsey value).
---
\* Only `f(0)` evaluates to `True`, but `set((True, 1, 1, ..., 1))` evaluates to `{True}` due to the equivalence of `True` and `1` in Python.
[Answer]
# Java 8, 38 bytes
```
n->n%100<60&n%1e4<6e3&n%1e6<24e4&n<1e6
```
[Try it online!](https://tio.run/##dY8xT8MwEIXn5lfcQmUPsUKbRmoTOoAYGFjIiBhMcgQHx47sSyGq@tuDSQYGxPTe3TvdfdfKk4zb@mNSXW8dQRtqMZDS4kma2nZ59Cfw5FB2opzl//zOao0VWefzKKq09B4epTJwjlb98KpVBZ4kBTlZVUMXIhZWKtOAdI1/fuFwhmi1WjDABYEbMPgJS4fxPKQLhGjQoJOEjHGIj/OwMPhFD4bYZrvb7/acC606Rew6SbioFjb2yygaZ4c@XL8d2WTio7kKg0WWrIPBtMhwO7us2KSYrk0R7BR2oiE3lkiMizfr7mX1zsrRE3bCDnQ49OEf0uYH9RJdpm8 "Java (JDK) – Try It Online")
Basically an improvement of @Kevin Cruijssen's solution; I don't have enough reputation for a comment. üòÑ
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 7 bytes
```
bȷ2<60Ạ
```
[Try it online!](https://tio.run/##RY27DYNAEEQbIphbPvJK5PRhiQRdA6RO3IYLcG4JkSEktwGNLLezAcHNzoyebqYx59ns@f9J3@FYPrav2/t8fQczVB2qhPLKlRou7hp3TXGtwiUoUN23D1Dpld4ZISNkBImeP5MX8kJeyCt7Za/s9d6KEylFSkwxjlhHzCP2a08X "Jelly – Try It Online")
A monadic link taking an integer and returning `1` for true and `0` for false.
Thanks to @KevinCruijsen for saving 6 bytes!
[Answer]
# [LibreOffice Calc](https://i.stack.imgur.com/QvapB.png), 43 bytes
```
=MAX(MOD(A1,100),MOD(A1/100,100),A1/4e3)<60
```
Basically a ~~blatant rip-off~~ respectful port of @RGS excellent Python answer so go and upvote them. Only posted as I have not seen a LibreOffice Calc answer on here before and I was messing about while calculating my tax return this evening (code golf is much more fun). Screenshot of some test cases below.
[![enter image description here](https://i.stack.imgur.com/QvapB.png)](https://i.stack.imgur.com/QvapB.png)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 12 bytes
```
[6-9].(..)?$
```
[Try it online!](https://tio.run/##PZGxDsJADEP3@w6QykDlpL0TmRj5CIQEAwMLA@L/j4tdsVQ@x3qJ1c/z@3o/@n663Pu1HeM2T/N8OO96R6lRGkpEMaDYeNl42nj7MgxfaqqWKr01vTW9Nb11eDWQlJqKJLGSBlTqRp1@PXHLqVI3avqh7fRDF@Q@cpwcJ8fJcRh9o2/0eTP5Tr6T7@Q7@U6@kz@@ww/mg/lgPpgP5oP5@NfaerHM1myrBs1MM9PMNDPOVBxqDlWHukPlofZQfaj/osMXXT7@A/AD "Retina 0.8.2 – Try It Online") Link includes test cases. Accepts input from `0` to `239999` and outputs `0` for times, `1` for non-times. Explanation: Simply checks whether the second or fourth last digit is greater than `5`.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~27~~ ~~22~~ 18 bytes
*Saved 4 bytes when @NahuelFouilleul pointed out that it doesn't need to be a look-ahead in the regex*
```
$_=!/[6-9].(..)*$/
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lZRP9pM1zJWT0NPT1NLRf//f0MLIy4jY1NLU8t/@QUlmfl5xf91fU31DAwN/usW5AAA "Perl 5 – Try It Online")
Since the input is guaranteed to be less than 236000, the hours can be ignored as they will always be valid. This pattern match checks if there is a 6, 7, 8, or 9 in the tens digit of the minutes or seconds. The match is then negated to get truthy for valid dates and falsy for invalid ones.
[Answer]
# [W](https://github.com/A-ee/w), 6 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
Source compression ftw!
```
♀♥@p▒ö
```
Uncompressed:
```
2,a60<A
```
## Explanation
```
2, % Split number into chunks of length 2
% The splitting is right-to-left *instead* of left-to-right.
A % Is all items in the list ...
a60< % ... less than 60?
```
[Answer]
# [J](http://jsoftware.com/), ~~32~~ ~~26~~ ~~23~~ 16 bytes
```
60*/ .>100#.inv]
```
[Try it online!](https://tio.run/##ZY@xDsIwDET3foUFQwUq4ZLIVVypLEhMTOxMiAoYYOvvh6hiiM3g4aS757tXXrl2onGgljoCDeV2jo6X8yn32O7JHTywds/3fM2b5n57fMjTSBOhFvxTWFSvlEhTWwtOSZba7HXWi9TmEHU4RJ0OUcdD/H9u3gOmAGAqAAYSOJkanEwPTqYIJ71ELEMsQyxDFoadWyj5Cw "J – Try It Online")
*-16 bytes (!!) thanks to Adam. This new solution uses the approach from [his APL answer](https://codegolf.stackexchange.com/a/200094/43319) so be sure to upvote that.*
Convert the input to base 100, check that all digits are less than 60.
Note the most significant digit is guaranteed to be less than 24 by the allowed inputs.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ìL e<60
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7EwgZTw2MA&input=MjM1OTU5)
[Answer]
# Java 8, ~~45~~ 43 bytes
```
n->n%100<60&n%1e4/100<60&n%1e6/1e4<24&n<1e6
```
Improved by [*@Joja*'s Java answer](https://codegolf.stackexchange.com/a/200131/52210) by removing the divisions, so make sure to upvote him/her as well!
[Try it online.](https://tio.run/##TVFBbsIwELzzihVSUaKEsDYBNST0B6UHjoiDCaFyCgYRQ1WhvD1dr0FwGc@sxzv2ulZXNay3P125V00Dn0qbWw9AG1udd6qsYOEkwNemrkoLZUA7YMKcim2PoLHK6hIWYGAOnRl@mDeBWExxQKRKRy9iOqJCIdOBKUh0uTt@umz2dPze5XrUWzjQFYKlPWvzvVqDCn3@7njmaA0zMNWvu@BqfRPxFGOKiAWtcowOHEsdS4lNMnTgXcjo@OQdGZlnzJ1HskeyR6Jgzp3ZL9kv2S/Zn3E943rG9eyZ5RevhFeClQ9Hn44@Hn3@2DenN@CjC7YhD@A5gno@FDnUxdxhFD22AZZ/ja0OyfFikxONz@5NoKM66s@gH5mkdCK8/1zb/QM)
**Explanation:**
```
n-> // Method with integer parameter and boolean return-type
n%100<60 // Check whether the seconds are smaller than 60
&n%1e4/100<60 // and the minutes are smaller than 60
&n%1e6/1e4<24 // and the hours are smaller than 24
&n<1e6 // and the entire number is smaller than 1,000,000
```
[Answer]
# [Turing Machine Code](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse), ~~336~~ 548 bytes
Prints 't' for true and 'f' for false.
```
0 * * r !
! * * r "
! _ _ l b
b * _ l t
" * * r £
" _ _ l c
c * * l c
c _ _ r 4
£ * * r $
£ _ _ l d
d * * l d
d _ _ r 3
$ * * r ^
$ _ _ l e
e * * l e
e _ _ r 2
^ * * r &
^ _ _ l g
g * * l g
g _ _ r 1
& * * l &
& _ _ l O
O 1 1 r a
O 2 2 r 1
O * * * f
a * * r 2
1 0 0 r 2
1 1 1 r 2
1 2 2 r 2
1 3 3 r 2
1 * * * f
2 0 0 r 3
2 1 1 r 3
2 2 2 r 3
2 3 3 r 3
2 4 4 r 3
2 5 5 r 3
2 * * * f
3 * * r 4
4 0 0 r t
4 1 1 r t
4 2 2 r t
4 3 3 r t
4 4 4 r t
4 5 5 r t
4 * * * f
f * * l f
f _ _ r n
n * _ r n
n _ f * halt
t * * l t
t _ _ r y
y * _ r y
y _ t r halt
```
[Try it online!](http://morphett.info/turing/turing.html?e0baa286625720d3ac74f1152ded6589)
*Added a chunk of bytes thanks to @Laikoni for spotting my misread of the question.*
[Answer]
# x86-16, IBM PC DOS, ~~46~~ ~~ 44 ~~ 39 bytes
```
00000000: d1ee 8a0c ba30 4c88 5401 03f1 4ed1 e9fd .....0L.T...N...
00000010: b303 ad86 e0d5 0a4b 7502 b628 3ac6 7d02 .......Ku..(:.}.
00000020: e2f0 d6b4 4ccd 21 ....L.!
```
Build and test `ISTIME.COM` with `xxd -r`.
**Unassembled listing:**
```
D1 EE SHR SI, 1 ; SI = 80H
8A 0C MOV CL, BYTE PTR[SI] ; CX = input length
BA 4C30 MOV DX, 4C30H ; DH = 60+16, DL = '0'
88 54 01 MOV BYTE PTR[SI+1], DL ; 'zero' pad byte to the left of input
03 F1 ADD SI, CX ; SI to end of input string
4E DEC SI ; remove leading space from length
D1 E9 SHR CX, 1 ; CX = CX / 2
FD STD ; read direction downward
B3 03 MOV BL, 3 ; counter to test if third iteration (meaning hours)
LOD_LOOP:
AD LODSW ; AX = [SI], SI = SI - 2
86 E0 XCHG AH, AL ; endian convert
D5 0A AAD ; binary convert
4B DEC BX ; decrement count
75 02 JNZ COMP ; if not third time through, go compare
B6 28 MOV DH, 40 ; if third, set test to 24+16
COMP:
3A C6 CMP AL, DH ; is number less than DL?
7D 02 JGE NOT_VALID ; if not, it's invalid
E2 F0 LOOP LOD_LOOP ; otherwise keep looping
NOT_VALID:
D6 SALC ; Set AL on Carry
B4 4C MOV AH, 4CH ; return to DOS with errorlevel in AL
CD 21 INT 21H ; call DOS API
```
A standalone PC DOS executable. Input via command line, output DOS exit code (errorlevel) `255` if Truthy `0` if Falsy.
**I/O:**
Truthy:
[![enter image description here](https://i.stack.imgur.com/9LgzJ.png)](https://i.stack.imgur.com/9LgzJ.png)
Falsy:
[![enter image description here](https://i.stack.imgur.com/td36s.png)](https://i.stack.imgur.com/td36s.png)
Thanks to @PeterCordes for:
* -2 bytes use DOS exit code for Truthy/Falsy result
* -3 bytes eliminate ASCII conversion before `AAD`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
‹⌈⍘N⭆¹⁰⁰℅ι<
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYwzexIjO3NFfDKbE4NbgEKJ6u4ZlXUFriV5qblFqkoamjABH1TSzQMDQw0FFwBpqSmFwClMvUBAIdBSUbJU1N6///jYxNLU0t/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Accepts input from `0` to `239999` and outputs a Charcoal boolean, `-` for times, no output for non-times. Explanation:
```
¹⁰⁰ Literal 100
⭆ Map over implicit range and join
ι Current index
‚ÑÖ Unicode character with that ordinal
N Input as a number
‚çò Convert to string using string as base
‚åà Character with highest ordinal
‹ Is less than
< Character with ordinal 60
Implicitly print
```
`BaseString` always returns `0` for a value of `0` (bug?) but fortunately this is still less than `<`.
Alternative solution, also 11 bytes:
```
⌈⍘N⭆¹⁰⁰›ι⁵⁹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sSIztzRXwymxODW4BCiUruGZV1Ba4leam5RapKGpowAR9U0s0DA0MNBRcC9KTSwBymTqKJhaaoKA9f//RsamlqaW/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Accepts input from `0` to `239999` and outputs `0` for times, `1` for non-times. Explanation:
```
¹⁰⁰ Literal 100
⭆ Map over implicit range and join
ι Current index
› Greater than
⁵⁹ Literal 59
N Input as a number
‚çò Convert to a string using string as base
‚åà Maximum
Implicitly print
```
`BaseString` doesn't require the string base to have distinct characters, so this string just has 60 `0`s and 40 `1`s.
Unfortunately taking the base numerically returns an empty list for an input of zero, which takes an extra three bytes to handle, pushing the byte count above 11. But fortunately I can substitute an acceptable non-zero number in only two bytes, so another 11-byte alternative is possible:
```
›⁶⁰⌈↨∨Nχ¹⁰⁰
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO9KDWxJLVIw8xAR8E3sSIztzRXwymxOFXDv0jDM6@gtMSvNDcJKK@po2BoACYMNIHA@v9/I2NTS1PL/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Accepts input from `0` to `239999` and outputs a Charcoal boolean, `-` for times, no output for non-times. Explanation:
```
⁶⁰ Literal 60
› Is greater than
N Input as a number
‚à® Logical Or
χ Predefined variable `10`
↨ ¹⁰⁰ Convert to base 100 as a list
‚åà Maximum
Implicitly print
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~14~~ 9 bytes
-5 bytes thanks to ngn
```
*/60>100\
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NSkvfzMDO0MAg5n@auqWlgqEpEFsYKBgZmxooWFqCRSxAYgYgzn8A "K (ngn/k) – Try It Online")
Based on [Ad√°m's APL solution](https://codegolf.stackexchange.com/a/200094/75681) and Kevin Cruijssen's suggestion.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~18~~ 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
‚óÑ+‚ñë2/i‚ïô‚ïü<
```
[Try it online.](https://tio.run/##PZIxTgQxDEX7nIKeAtuZhLHEUZDQNgtIIBqOwAUoFkTF3eYig/08osko/l/@P2/39fT@9Pj2ct4fru737fvjevv6tJvn7fKzXX7v9l2aNmvD25Q2tbk3lZiJNo2hxlRjbBaC9VDiiGsfeZ15TbWnuqS6pLqkuqS6hDrWUIeHGkdcfeR15pXAiiRUMlZkMJlMZha5Tc9Y0xNnTtbBZDLBs@JxPF718TiejFKyjCwjy8gysoysOPEoHsWjeBQPMOhj9DH6GH2MPkYfo4/Rx@hj9DH6WD2dPc4eZ4@zx9nj7HH2OHucPc4eZ4//IzwYFsSieGA8OAJSeF186jfmffkpp5ZTcRZzKehS1KWwS3GXAi9FXgq9FHsp@FL0hZrxp4FJLyi9qPR0/gE)
**Explanation:**
```
‚óÑ+ # Add builtin 10,000,000 to the (implicit) input-integer
‚ñë # Convert it to a string
2/ # Split it into parts of size 2: [10,hh,mm,ss]
i # Convert each to an integer
‚ïô # Pop and push the maximum
‚ïü< # And check if it's smaller than builtin 60
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# [Red](http://www.red-lang.org), 63 bytes
```
f: func[n][either n % 100 > 59[return 0][if n > 1[f n / 100]]1]
```
[Try it online!](https://tio.run/##HYsxDgIxDAS/sjqJEpEggjBFHkFruUB3ji5NQJbv/SGh2Slm1nTrL91Y0MsT5WgrN2Gtvquh4YQYAjISsakf1hCEaxkmI/LkZRYiUXr5mL7XHQ6OiXC9jedwNDc9wv0PIuGv1ebsWM55QYGL9B8 "Red – Try It Online")
Of course the recursive function with integers is much shorter than the below version that works on strings.
# [Red](http://www.red-lang.org), ~~139~~ ~~130~~ 115 bytes
```
func[s][s: pad/left/with s 6 #"0"
not any collect[foreach n collect[loop 3[keep to 1 take/part s 2]][keep n > 60]]]
```
[Try it online!](https://tio.run/##PYxBCoMwFET3nmJI18VoqzQuPES3IYsQExRDEuIvxdPbgG1Xb5hhXrbT8bSTVJUbcLhXMHJTchuQ9FR766h@LzRjQ48L46wKkaDDDhO9t4aki9lqMyP8Gx9jwk2u1iZQRAPSq62TzlQsrVLnEjCi50qp42cgSNZ0goG1d84LGs7Fye7B@28QgimZ8hJImpj28mLXkcGBiuoD "Red – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~33~~ 32 bytes
```
p=%100\<60;echo $[$1$p&$1/100$p]
```
[Try it online!](https://tio.run/##S0oszvj/v8BW1dDAIMbGzMA6NTkjX0ElWsVQpUBNxVAfKKxSEPv//39DU0tTSwA "Bash – Try It Online")
Input is passed as an argument.
Output is 0 (falsey) or 1 (truthy).
(I've deleted an earlier 45-byte version that used egrep.]
[Answer]
# [Zsh](https://www.zsh.org/), 28 bytes
```
e=%100/60;(($1$e||$1/100$e))
```
[Try it online!](https://tio.run/##fU/RCoMwDHzPVwiL2MKG7UYFN50fIj7IqHQgG0wfxtRv77oYX5eH5HrXHLnP4HwnpPC2jLVSaaYuQqBGO8@o08CgldLbm3tGWIEE6CIqxcDkKwg/V5AzYxgEgaTjiRhySkqqhD2yzSxnM7MyYYRVsO/7CLCL2n60r0c72uEMQrgyOO9Rxy7cTMc6glLCLwCH2VLwk8Q/m0VR4IST6OusqVUj9RJXVaEO5sp98V8 "Zsh – Try It Online")
Returns via exit code.
Since `$parameters` are expanded before `((arithmetic))`, $e expands to `%100/60` before arithmetic is done.
There are 2 other 28 byte solutions I found as well, albeit not as interesting:
```
((h=100,$1%h/60||$1/h%h/60))
```
```
(($1%100/60||$1/100%100/60))
```
[Answer]
# [Turing Machine Simulator](http://morphett.info/turing/turing.html), ~~299~~ ~~272~~ 269 bytes
```
0 _ _ l 1
0 * * r 0
1 * _ l 2
* _ t * t
2 6 f * f
2 7 f * f
2 8 f * f
2 9 f * f
2 * _ l 3
3 * _ l 4
4 6 f * f
4 7 f * f
4 8 f * f
4 9 f * f
4 * _ l 5
5 0 _ l 6
5 1 _ l 6
5 2 _ l 6
5 3 _ l 6
5 * _ l 7
6 _ t * t
6 1 t * t
6 2 t * t
6 * f * f
7 _ * * t
7 1 _ * t
7 * f * f
```
[Run in Turing Machine Simulator](http://morphett.info/turing/turing.html?073d1e0b9d119d1e74708bcb2957d99d).
Halts with `t` on the tape for true inputs and a prefix of the input and `f` for false inputs.
[Answer]
# T-SQL, ~~42~~ 41 bytes
Saved 1 byte thanks to @Neil
Supports all positive integer input
Returns 1 for true, 0 for false
```
DECLARE @ INT=235959
PRINT-1/~(@/240000+@/100%100/60+@%100/60)
```
[Answer]
# VBA, 177 bytes
```
Sub a()
x=1: i=""
If Len(i)<6 Then Do Until Len(i)=6: i="0"&i: Loop
s = Right(i, 2): m = Left(Right(i,4),2): h = Left(i,2)
If s>59 Or m>59 Or h>23 Then x=0
Debug.Print s
End Sub
```
Works for values above 235959, assigns x to output 1 or 0 with input as i
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~50~~ ~~48~~ 46 bytes
*-2 bytes each thanks to @kanine and @l4m2*
```
a=>a.padStart(6,0).match(/../g).every(x=>x<60)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifk1qikGb7P9HWLlGvIDEluCSxqETDTMdAUy83sSQ5Q0NfT08/XVMvtSy1qFKjwtauwsbMQPN/QVFmXolGmoaSkbGppamlkqamtQIXkqCZgZkBSPA/AA "JavaScript (V8) – Try It Online")
[Answer]
# [JavaScript (Node.js)], 26 bytes
```
f=>!/[6-9].(..)?$/.test(f)
```
Simple Javascript Regular Expression
JavaScript (Node.js) – [Try It Online](https://tio.run/##y0osSyxOLsosKNFNSkxKzdHNy09J/f@/xDbN1k5RP9pM1zJWT0NPT9NeRV@vJLW4RCNN839yfl5xfk6qXk5@ukaJhoGmJheqiKWphaUlpiimkAk2MVNs6kywCWJVaYYpaGSMU9gUm7AZWPg/AA)
[Answer]
# T-SQL, 64 bytes
```
SELECT*FROM t WHERE 60>LEFT(RIGHT('000'+v,4),2)AND 60>RIGHT(v,2)
```
Input is taken from pre-existing table *t* with varchar field *v*, [per our input standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341).
Outputs 1 row (with the original value) for "true", and 0 rows for "false".
Accepts only values in the specified range (`0` to `235959`), so doesn't validate the first 2 digits.
[Answer]
# [PHP](https://php.net/), 60 bytes
```
<?=preg_match('#\d+([01]\d|2[0-3])([0-5]\d){2}#',$argn+1e6);
```
[Try it online!](https://tio.run/##K8go@P/fxt62oCg1PT43sSQ5Q0NdOSZFWyPawDA2JqXGKNpA1zhWE8jVNQXyNauNapXVdVQSi9LztA1TzTSt//83Mja1NLXkMjI2g1BcRiZQAQPDf/kFJZn5ecX/dd0A "PHP – Try It Online")
Basically regex and not much golfable, but fun. Inputs above 235959 are indeterminate.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 76 bytes
supports ***any*** number
```
!FreeQ[FromDigits/@Join@@@IntegerDigits/@Tuples[Range/@{24,6,10,6,10}-1],#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X9GtKDU1MNqtKD/XJTM9s6RY38ErPzPPwcHBM68kNT21CCYaUlqQk1ocHZSYl56q71BtZKJjpmNoACZqdQ1jdZRj1f4HFGXmlSg4pEcbGZtamlrG/v8PAA "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
For the non-zero digits on a standard [numpad](https://en.wikipedia.org/wiki/Numeric_keypad)
```
789
456
123
```
consider placing a [chess knight](https://en.wikipedia.org/wiki/Knight_(chess)) at any digit and moving it around with any number of normal L-shaped jumps, tracing out a positive decimal integer. What positive integers can be expressed in such a way?
One of them is `38`, since the knight could start on the `3` and move left and up to the `8`. `381` and `383` are also possible.
`3` itself is possible if no jumps are taken (which is allowed). `5` is as well, but no other digits can be reached from the `5`, so it is the only number where the digit `5` appears.
Write a program or function that takes in a positive decimal integer (you may take it as a string if desired) and prints or returns a [truthy](http://meta.codegolf.stackexchange.com/a/2194/26997) value if the number can be expressed by a knight on a numpad in the way described, but otherwise outputs a [falsy](http://meta.codegolf.stackexchange.com/a/2194/26997) value.
**The shortest code in bytes wins. Tiebreaker is earlier answer**
## Examples
Truthy:
```
1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276
```
Falsy:
```
10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760
```
[Answer]
## Python 2, 52 bytes
```
f=lambda n:n<6or`n%100`in'18349276167294381'*f(n/10)
```
Checks that any two consecutive digits are in the string `'18349276167294381'`. To get consecutive digits, rather than doing `zip(`n`,`n`[1:])`, the function repeatedly checks the last two digits and removes the last digit.
[Answer]
# Jelly, ~~19~~ ~~15~~ 14 bytes
```
Doȷ’d3ạ2\P€=2P
```
[Try it online!](http://jelly.tryitonline.net/#code=RG_It-KAmWQz4bqhMlxQ4oKsPTJQ&input=&args=NjE4MzQ5Mjc2) or [verify all test cases](http://jelly.tryitonline.net/#code=RG_It-KAmWQz4bqhMlxQ4oKsPTJQCsOH4oKs4oKsRw&input=&args=W1sxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5LCAxNiwgMTgsIDM4LCA2MSwgODEsIDI5NCwgMzQ5LCAzODEsIDM4MywgNzI5LCA3NjcsIDM4MTgzLCAzODM4MywgMTgzNDkyNzYsIDE4MzQ5Mjc2MSwgNjE4MzQ5Mjc2XSwKIFsxMCwgMTEsIDUwLCA1MywgNTUsIDY1LCA5NSwgMTAwLCAxODAsIDE4MiwgMTg0LCAxODUsIDE4NiwgMTg3LCAxODgsIDE4OSwgMjA5LCAzMDUsIDIwMDksIDUwMzAsIDM4MzgzODQsIDQ4MzgzODMsIDE4MzQ5Mjc2MF1d).
### How it works
```
Doȷ’d3ạ2\P€=2P Main link. Argument: n (integer)
D Convert n to base 10 (digit array).
ȷ Yield 1000.
o Logical OR. This replaces each 0 with 1000.
’ Decrement each digit.
d3 Divmod; replace each digit k with [k:3, k%3].
ạ2\ Pairwise reduce by absolute difference.
For each pair of adjacent digits [i, j], this computes
[abs(i:3 - j:3), abs(i%3 - j%3)].
P€ Compute the product of each result.
n is a Numpad's Knight Number iff all products yield 2.
=2 Compare each product with 2.
P Multiply the resulting Booleans.
```
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~58~~ 40 bytes
Thanks to Sp3000 for suggesting this idea:
```
M&!`..
O%`.
A`16|18|27|29|34|38|49|67
^$
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYApNIWBcZCsKJShHYApNJiFgLi4KTyVgLgpBYDE2fDE4fDI3fDI5fDM0fDM4fDQ5fDY3Ck1gXiQKKUdgCsK2CiwgCilHYCw&input=MSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOSwgMTYsIDE4LCAzOCwgNjEsIDgxLCAyOTQsIDM0OSwgMzgxLCAzODMsIDcyOSwgNzY3LCAzODE4MywgMzgzODMsIDE4MzQ5Mjc2LCAxODM0OTI3NjEsIDYxODM0OTI3NgoKMTAsIDExLCA1MCwgNTMsIDU1LCA2NSwgOTUsIDEwMCwgMTgwLCAxODIsIDE4NCwgMTg1LCAxODYsIDE4NywgMTg4LCAxODksIDIwOSwgMzA1LCAyMDA5LCA1MDMwLCAzODM4Mzg0LCA0ODM4MzgzLCAxODM0OTI3NjA) (Slightly modified to run the entire test suite at once.)
Prints `1` for truthy and `0` for falsy results.
### Explanation
```
M&!`..
```
Find all overlapping matches of `..`, i.e. all consecutive pairs of digits, and join them with linefeeds.
```
O%`.
```
Sort the digits in each line, so that we only need to check half as many pairs.
```
A`16|18|27|29|34|38|49|67
```
Remove all lines which correspond to a valid move.
```
^$
```
Count the matches of this regex. That is, if all lines were removed, this matches the resulting empty string once, otherwise it fails to match and gives zero instead.
[Answer]
# Pyth - ~~35~~ 28 bytes
```
!s.bt/@c`C"_xÖ({ζz"2tsNYztz
```
[Test Suite](http://pyth.herokuapp.com/?code=%21s.bt%2F%40c%60C%22_x%C3%96%28%7B%C3%8E%C2%B6z%222tsNYztz&input=38&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A16%0A18%0A38%0A61%0A81%0A294%0A349%0A381%0A383%0A729%0A767%0A38183%0A38383%0A18349276%0A183492761%0A618349276%0A10%0A11%0A50%0A53%0A55%0A65%0A95%0A100%0A180%0A182%0A184%0A185%0A186%0A187%0A188%0A189%0A209%0A305%0A2009%0A5030%0A3838384%0A4838383%0A183492760&debug=0).
[Answer]
# Ruby, 57 bytes
Anonymous function. Argument is a string.
```
->n{(0..n.size).count{|i|!"16729438183492761"[n[i,2]]}<1}
```
Program with the test suite:
```
f=->n{(0..n.size).count{|i|!"16729438183492761"[n[i,2]]}<1}
a=%w{1 2 3 4 5 6 7 8 9 16 18 38 61 81 294 349 381 383 729 767 38183 38383 18349276 183492761 618349276
10 11 50 53 55 65 95 100 180 182 184 185 186 187 188 189 209 305 2009 5030 3838384 4838383 183492760}
a.each {|e|p [e, f[e]]}
```
I just encoded all the possible knight moves into a string and checked if every 2 digits within the input existed in that string.
[Answer]
# grep 58 bytes
```
grep "^((?=18|16|29|27|34|38|49|43|61|67|72|76|81|83|94|92).)*.$"
```
Because really, if you cannot beat grep...
[Answer]
## Haskell 46 bytes
```
q=zip<*>tail
all(`elem`q"16729438183492761").q
```
Usage example: `all(`elem`q"16729438183492761").q $ "183492761"` -> `True`
How it works: It uses the lookup string found in [@Kevin Lau's answer](https://codegolf.stackexchange.com/a/78031/34531). `q` makes a list of pairs of adjacent chars from a string, e.g. `q "1672" -> [('1','6'),('6','7'),('7','2')]`. The function returns true if all pairs from the input appear in the pairs from the lookup string. `q` turns single digit inputs into the empty list, so `elem` always succeeds.
[Answer]
## JavaScript (ES6), ~~65~~ 62 bytes
```
s=>[...s].every((c,i)=>!i|"16729438183492761".match(s[i-1]+c))
```
Returns true or false. I'd previously tried a recursive solution, which takes 63 bytes, and `map` and even `reduce` but they took me 73 bytes.
Edit: Saved 3 bytes thanks to @user81655.
[Answer]
# C, ~~85~~ 81 bytes
Golfed:
```
i;f(char*b){i=*b++-49;return*b?(*b=="8749x7214"[i]||*b=="6983x1632"[i])&&f(b):1;}
```
Old non-recursive version (85 bytes):
```
i;f(char*b){for(;(i=*b++-49),*b&&*b=="8749x7214"[i]||*b=="6983x1632"[i];);return!*b;}
```
Old code with white-space and main program:
```
i;
f(char*b){
for (; (i=*b++-49), *b // i = index of digit + 1 in following arrays
&&*b=="8749x7214"[i] // 1st possible jump for 1..9
||*b=="6983x1632"[i]; // 2nd possible jump for 1..9
);
return !*b;
}
main(){
char b[16];
while(scanf("%s", b) == 1) printf("%d",f(b));
return 0;
}
```
This accepts space-delimited numbers via standard input and outputs 0 if not-numpad-knight, or 1 otherwise.
The new 81-byte recursive version shaves 4 bytes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~38~~ ~~37~~ 29 bytes
This uses [@QPaysTaxes idea](https://codegolf.stackexchange.com/questions/78024/a-numpads-knight-numbers#comment190581_78024).
```
I:8JK5:7Pvj!Uttnqh?)d|2:EQm}h
```
The output is a 2D, complex, non-empty array. It is truthy if all its values have nonzero real part, and falsy otherwise.
[**Try it online!**](http://matl.tryitonline.net/#code=STo4Sks1OjdQdmohVXR0bnFoPylkfDI6RVFtfWg&input=NjE4MzQ5Mjc2)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 29 bytes
Code:
```
"1Ôž±ÎqäÚ"•5(«U2÷¹¦2÷«vXyå})P
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=IjHDlMW-wrHDjnHDpMOaIuKAojUowqtVMsO3wrnCpjLDt8Krdlh5w6V9KVA&input=MA).
[Answer]
# MATL, ~~25~~ ~~24~~ ~~33~~ 26 bytes
Shaved off 1 byte thanks to @LuisMendo!
@Dennis found a bug, and then fixed it! Thanks!
```
'bSVYXbTUZW'j47-)d2^48\1=A
```
Takes integer as input. Outputs 1/0.
[Try it online!](http://matl.tryitonline.net/#code=J2JTVllYYlRVWlcnajQ3LSlkMl40OFwxPUE&input=MzgzODM)
[Answer]
# C, ~~140~~ 92 bytes
```
c;L(char*i){while(*i&&(!c||*i=="6743x1212"[c-49]||*i=="8989x7634"[c-49]))c=*i++;return !*i;}
```
*Assuming ASCII*
**Detailed** [*Try it here*](http://ideone.com/bs2Ui7)
```
// valid transition from x to n[x-'1'][0 or 1]
int n[9][2] =
{
{'6','8'},{'7','9'},{'4','8'},
{'3','9'},{'x','x'},{'1','7'},
{'2','6'},{'1','3'},{'2','4'}
};
// i is a pointer to where to start on a string
bool L(char * i)
{
char c = 0;
// move if not \0 and (not-first-char or is a valid move)
while((*i) && (!c || (*i)==n[c-'1'][0] || (*i)==n[c-'1'][1]))
{
c = (*i++);
}
return !(*i); // success if it's \0
}
```
[Answer]
# Julia, ~~51~~ 49 bytes
```
n->diff(["@1634@8725"...][digits(n)+1]).^2%48⊆1
```
### Verification
```
julia> f=n->diff(["@1634@8725"...][digits(n)+1]).^2%48⊆1
(anonymous function)
julia> all(map(f,(1,2,3,4,5,6,7,8,9,16,18,38,61,81,294,349,381,383,729,767,38183,38383,18349276,183492761,618349276)))
true
julia> any(map(f,(10,11,50,53,55,65,95,100,180,182,184,185,186,187,188,189,209,305,2009,5030,3838384,4838383,183492760)))
false
```
[Answer]
## Actually, 30 bytes
```
;#pXZdX`Σ"67294381";'1+R+íu`Mπ
```
Takes input as a string. Outputs a positive integer for true and 0 for false.
[Try it online!](http://actually.tryitonline.net/#code=OyNwWFpkWGDOoyI2NzI5NDM4MSI7JzErUivDrXVgTc-A&input=IjM4MzgzIg)
Explanation:
```
;#pXZdX`Σ"67294381";'1+R+íu`Mπ
(implicit) push input
;#pXZdx push zip(n[:-1], n[1;]) (pairs of digits)
`Σ"67294381";'1+R+íu`M map:
Σ join digits
"67294381";'1+R+ push "16729438183492761" (the magic string used in many other solutions)
íu 0-based index (-1 if not found), increment so 0 is not found and >=1 is the 1-based index
π product
```
[Answer]
## PowerShell v2+, ~~105~~ 96 bytes
```
param($a)((1..$a.length|%{'27618349294381672'.IndexOf($a[$_-1]+$a[$_])+1})-join'*'|iex)-or$a-eq5
```
Iterates through the input (which must be encapsulated with `""`) by verifying that the index of any sequential pair of characters is in the valid lookup string. I see Kevin Lau had [something similar](https://codegolf.stackexchange.com/a/78031/42963), but I came up with this independently. Each of those indices are added with `+1`, as the `.IndexOf()` function will return `-1` if the string isn't found. This will turn "not found"s into `0`.
We then `-join` all the resultant integer values with `*` and pipe that to `iex` (similar to `eval`). This will mean if any one of the indices is not found, the entire expression will result in `0`. That is encapsulated in parens and `-or`'d with `$a-eq5` for the special case of input `"5"` to achieve our resultant output.
### Test Runs
```
PS C:\Tools\Scripts\golfing> 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276 | %{.\numpad-knight-numbers.ps1 "$_"}
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
PS C:\Tools\Scripts\golfing> 10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760 | %{.\numpad-knight-numbers.ps1 "$_"}
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
```
[Answer]
# C, ~~78~~ 85 bytes
```
char*a="9614397052";f(x){int b=x/10;return!b||b*x%5&&abs(a[x%10]-a[b%10])%6==1&f(b);}
```
Since everyone else has taken the input as a string, I tried doing it in integers. It works recursively from the least-significant digit (`a%10`); if it's the only digit, then return true. Otherwise, return true only if the tens digit (`b%10`) can't be reached from the units digit, and (recursively), the rest of the input satisfies the same test.
The test for reachability works by encoding the knight's tour linearly, and converting each digit to its position (zero to seven) on the tour. For digits `0` and `5`, we assign position nine, which is disconnected from the other positions. Then, mutually reachable numbers differ by one (mod eight); i.e. `a[x%10]-a[b%10]` is either ±1 or ±7. So we test the absolute difference (mod 6) against 1.
This solution works for any character encoding that is valid for C (i.e. digits have contiguous codes from 0 to 9).
[Answer]
# Java 8, ~~179~~ 167 Bytes
Places the number pad ints (minus 5 and 0) in a circle. `l` holds the circle index of these ints. If the difference of two indices is +/- 3 mod 8, then there is a knights move between the ints corresponding to those indices. Note that `x` is an `int[]`.
```
x->{if(x.length<2)return 1;int[] l={0,0,1,2,7,0,3,6,5,4};int o=l[x[1]];for(int i:x){int n=l[i];if(i%5==0||(Math.abs(n-o)!=3&&Math.abs(n-o)!=5))return 0;o=n;}return 1;}
```
**Update**
* **-11** [16-12-10] Switched to a lambda
* **-1** [16-12-10] Use `<2` instead of `==1`
] |
[Question]
[
## Challenge
Unlike the circumference of a circle (which is as simple as \$2\pi r\$), the [circumference (arc length) of an ellipse is hard](https://en.wikipedia.org/wiki/Ellipse#Circumference).
Given the semi-major axis \$a\$ and semi-minor axis \$b\$ of an ellipse (see the image below, from Wikipedia), calculate its circumference.
By definition, you can assume \$0 < b \le a\$ for input values. The output value must be within \$10^{-6}\$ relative error from the expected answer for the given test cases.
[![enter image description here](https://i.stack.imgur.com/tZRuK.png)](https://i.stack.imgur.com/tZRuK.png)
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Formulas
Relevant information can be found on [Wikipedia](https://en.wikipedia.org/wiki/Ellipse#Circumference) and [MathWorld](https://mathworld.wolfram.com/Ellipse.html). \$C\$ is the value of the circumference; \$e\$ and \$h\$ are helper values. The last two are Ramanujan's approximations, the first of which (the crossed-out one) does not meet the error requirements. The second approximation formula (Equation 5) barely does ([verification](https://tio.run/##ZVBNT8JAEL3vrxhuu5R@bEujHjyZGDlJwDPJNlKLgYJUDsZw0hCElOjB1LMx0ZsHY0g42n@yf6TOthIg7mEyb@a9N7MjBl39/EZ0@xeZXDzXTuXk0SKYHTcw1OsIub2/B041k7PXzEcs44Wc3f18OnLyhJxm4wjj2UmtmQnsusRTGhK1h512hOmtTOZUxitNxt8sTTQjTWT8QUty@mK4aUJVT897yzULW2Um4y9uWdaYkKHoiXB0KUK@tnOUR8HVDbes/BTOy2oIxgKsxhu1rdQBhmKBf2NBzu9hd1muXIJ0yS2tGFPVVQF3ElB8EDxMNwvuQhuhnL6btnx4MwGvhMMFUGoZB/mDNPmzYVDZqCrADUs9vk3wCCGs7/tkAIcw6FCheQyiUQ/djE7os9zXLYWMCt1jrdDMGa2QtWyy1jiFSofoanhNqaMQlhyPMUZIgCSaqwutUm4Noxw0cAKT4jVyPR4jQOEv)) for up to \$a=5b\$ (which is also the upper limit of the test cases, so you can use it for your answer).
$$
\require{enclose} \\
\begin{align}
e &= \sqrt{1-\frac{b^2}{a^2}} \\
C &= 4aE(e) = 4a\int^{\pi/2}\_{0}{\sqrt{1-e^2 \sin^2 \theta} \;d\theta} \tag{1} \\
C &= 2 \pi a \left(1-\sum^{\infty}\_{n=1}{\left(\frac{(2n-1)!!}{(2n)!!}\right)^2 \frac{e^{2n}}{2n-1}}\right) \tag{2} \\
h &= \frac{(a-b)^2}{(a+b)^2} \\
C &= \pi (a + b) \left( 1 + \sum^{\infty}\_{n=1} { \left( \frac{(2n-1)!!}{2^n n!} \right)^2 \frac{h^n}{(2n-1)^2} } \right) \tag{3} \\
C &= \pi (a + b) \sum^{\infty}\_{n=0} { \binom{1/2}{n}^2 h^n } \tag{4} \\
\enclose{horizontalstrike}{C} &\enclose{horizontalstrike}{\approx \pi \left( 3(a+b) - \sqrt{(3a+b)(a+3b)} \right)} \\
C &\approx \pi (a+b) \left( 1+ \frac{3h}{10 + \sqrt{4-3h}} \right) \tag{5}
\end{align}
$$
## Test cases
All the values for C (circumference) are calculated using Equation 4 with 1000 terms, and presented with 10 significant figures.
```
a b C
1 1 6.283185307
1.2 1 6.925791195
1.5 1 7.932719795
2 1 9.688448220
3 1 13.36489322
5 1 21.01004454
20 10 96.88448220
123 45 556.6359936
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
```
Perimeter[#~Disk~#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PyC1KDM3tSS1KFq5ziWzOLtOOVbtf0BRZl6Jgr5Dur5DdbWhno6hXq0OkDaCMUwhDCOojDGUNoXSRgZAhgFYqRFQzsRUr7b2/38A "Wolfram Language (Mathematica) – Try It Online")
-2 bytes from @Roman (see comments)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~68~~ 67 bytes
```
f=lambda a,b,k=2:k>>9or(1-b*b/a/a)*(k-4+3/k)/k*f(a,b,k+2)+6.28319*a
```
[Try it online!](https://tio.run/##XcxBDoIwEIXhvadwOdMOlJkCERO4yzSm0VSBEDaeviYujGX55f1563u/L7PPOY5PfYWbnpUCpVGuaZqGZQOugglOnaKBVLXWu4QumQjfzgravpaL58FoXrfHvEMEJkY8/VTLwV3hcvWFDmVD3Pw/iae2Q8wf "Python 3 – Try It Online")
An exact infinite series, given sufficiently accurate values of \$2\pi \approx 6.28319\$ and \$\infty \approx 9\$.
### ~~69~~ 68 bytes
```
f=lambda a,b,k=0:k//7*.785398*a*(8-k)or f(a+b,2*(a*b)**.5,k*b/a/2+4)
```
[Try it online!](https://tio.run/##XczLCsIwEIXhvU/R5cx0mmtDo9CHmSBBibaldOPTx52YLj/@w9k@x2NdfK15fsk73aUTTlxmcytaT6SmGPw1khDEoeC6dxmkT@wIhBISqcCFkhbt@hHrtj@XAzJYtoiXn5Q7OTRuq290Whq25v/JeR4DYv0C "Python 3 – Try It Online")
Another exact series, given sufficiently accurate values of \$\frac\pi4 \approx .785398\$ and \$8 \approx 7\$. This one converges extremely quickly, using just five recursive calls for each test case! The recursion exactly preserves the invariant value
$$\left(1 + \frac{kb}{8a}\right)C(a, b) - \frac{kb}{8a}C(a + b, 2\sqrt{a b}),$$
which can then be approximated as \$(1 - \frac k8)2\pi a\$ when \$a, b\$ become sufficiently close.
[Answer]
# [R](https://www.r-project.org/), ~~60~~ 57 bytes
```
function(a,b,c=a+b,h=3*(a-b)^2/c)pi*(c+h/(10+(4-h/c)^.5))
```
[Try it online!](https://tio.run/##hc7NjoIwEMDxu09h4qWVWjsznX4ceBUNNCWQIBp2fX7WJV4kAXuaNPnN/McpdWN63po85iHl67255r7vHj@5nJrnkH67@yAqVatUVkWt2pKOojrV8oLnJB/dUaSiPQswhbCn9vV10Szl6k4Bav//QO4P8@A0BoLAZPxuHWlUnygi@wgQeQvxB/I6EnqIfgvhIi9qF4K1AdGsI1ogIE3Ohtc5XEe8QAjagDHWst3IM7MC81bR6e95gHOg5TdidtoRx0huN01/ "R – Try It Online")
Straightforward implementation of Ramanujan's 2nd approximation (eq 5).
Rather sadly, this approximation comes out as ~~much~~ more concise than a more-interesting **different approach** prompted by the comments: 'draw' a big ellipse, and measure around the edge of it (unfortunately counting the actual pixels wasn't going to work...):
**[R](https://www.r-project.org/), ~~90~~ ~~65~~ 62 bytes**
*Edit: -3 bytes by calculating hypotenuse length using `abs` value of complex number*
```
function(a,b,n=1e5)sum(4*abs(diff(b*(1-(0:n/n)^2)^.5)+1i*a/n))
```
[Try it online!](https://tio.run/##hc/dboMgFAfw@z7FSXqjnWWAoLKkr9JG2aGSKG4IS/b0jpomy5rUccPn75w/ftHW6zga9Og0XiZzwWGwHzOeFhOdDnZyWVt0hTsxlPkcx0wc2m7O3q0xWXfI2DGjb@7V5Ween4nMX5g9tGmbL3twU0DQfeuuCA7CBL299ujhqx0izmAmDx2GkE5araNv9Td0McAwJeDBR3cMdsTdHlJrsDPM0RirLbpwKzYiprnHX@zxM1qP4@3BZNa71H0YMNXb7Z59NGMF3AbLYb8uKsKbkjWypPUGIrz4ixSXtWJMyS0k/6CaqJLXTNVbiD/EU6RqGiEazulzVD4gVpKyEk1qx58j@YA4I5RRKoQUG/Hoqhi9K1WR/@MxvgYU8o6krEhVSqXKarcsPw "R – Try It Online")
**How?** (ungolfed code):
```
circumference_of_ellipse=
function(a,b # a,b = axes of ellipse
n=1e6){ # n = number of pixels to 'draw' across 'a' axis
x=a*0:n/n # x coordinates = n pixels from 0 to a
y=b*(1-(x/a)^2)^.5) # y coordinates = to satisfy (x/a)^2 + (y/b)^2 =1
# we could actually draw the (quarter) ellipse here
# with 'plot(x,y)'
step_y=diff(y) # step_y = change in y for each step of x
step_x=a/n # step_x = size of each step of x
h=(step_y^2+step_x^2)^.5 # h=hypotenuse of triangle formed by step_y & step_x
sum(4*h) # sum all the hypotenuses and multiply by 4
# (since we only 'drew' a quarter of the ellipse)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ ~~25~~ 23 [bytes](https://github.com/abrudz/SBCS)
Thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) for -5 bytes!
Assumes `⎕IO←0`.
```
f←○1⊥+×9(×⍨*×.5!⍨⊢)∘⍳⍨-÷+
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI9656YBGY@mdxs@6lqqfXi6kdaj3hUaeqaKQOpR72ZLzcPTLbUedcwAsoEiuoe3a@PSA1atAWIeng7V37VYE6TjP6pyS43D04GyWghlizRRbAC5TwGoRcFQIU3BkAvO0zNC45ui8FFljVF4aCoNQFwDhElGINUmpv8B "APL (Dyalog Unicode) – Try It Online")
This calculates
$$
\pi \cdot \sum\_{n=0}^{8} (a+b) \cdot \left( h^{\prime n} \binom{1/2}{n} \right) ^2 \qquad h^\prime = {{a-b}\over{a+b}}
$$
which is a good enough approximation using the 4th formula.
For the explanation the function will be split into two. `f` is the main function and `g` calculates \$ \left( \alpha^{\prime n} \binom{1/2}{n} \right) ^2 \$ for \$n\$ from \$0\$ to \$\omega-1\$:
```
g ← (×⍨*×.5!⍨⊢)∘⍳
f ← ○1⊥+×9g⍨-÷+
```
Starting with `a f b` from the right:
`-÷+` calculates \$h^\prime = (a-b)÷(a+b)\$.
`g⍨` is `g` commuted => `9 g⍨ h' ≡ h' g 9`. `g` returns a vector of the 9 values of \$\left( h^{\prime n} \binom{1/2}{n} \right) ^2\$.
`+×` multiplies \$a + b\$ to this vector.
`1⊥` converts the resulting vector from base 1, which is the same as summing the vector.
`○` multiplies the resulting number by \$\pi\$.
Now to `h' g 9`:
`⍳` is an index generator, with `⎕IO←0`, `⍳9` results in the vector `0 1 ... 8`.
The remaining train `×⍨*×.5!⍨⊢` is now called with \$h^\prime\$ as a left argument and the vector \$v = (0,1, \cdots, 8)\$ as a right argument:
`.5!⍨⊢` is the commuted binomial coefficient called with the vector `v` on its right and \$0.5\$ on its left. This calculates \$\binom{1/2}{n}\$ for all \$n \in v\$.
`*×` multiplies this vector element-wise with \$h^\prime \* n\$ (\$\*\$ denotes exponentiation).
`×⍨` is commuted multiplication, which given only a right argument, seems to use this as left and right argument? and squares the vector element-wise.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 63 bytes
```
->a,b,h=1r*(a-b)/a+=b{3.141593*a*((154+53*h*=h)*h*h/1e4+h/4+1)}
```
[Try it online!](https://tio.run/##VdC7boQwEAXQPl8xIg1Pw/iFXZAfQRQ2AnmjlRLxiBSxfDsxsGiVZop7Zm4xw2x/t77asg@T2tRVOMShyWyUm6SyCyPIUWgWmzgMUfBEsNjFlYv8dDl2PHE5TzBat/oNoMYUAPYhCVUMlWBF2aSHEJo@RVNRakQtLhGnlEQzWqIuL6FXmyZSKc4VpcUp7BJkhEmu/CE9RVxCkRRYFJwL/mwr9n0/tCT/25D6Pu4vhZBEMqE1k14a0pnWwQKP/TPtA77naYTAQAXvi1nTgNw/53EKdQQJBPaI7StWR9wf8Vj1tS9pXkr5wUN3N9Ptp4NuGL6GYzcc8zbDiBg7rgGs2x8 "Ruby – Try It Online")
A [direct port](https://tio.run/##VdC7asQwEAXQPl8xOI38kvW2tOD0KQLpzRaSsXHCQoIfgeD1tztaec2SZop7Zm4xw@x@t67a8hebueXNTv3p9P6aINRXfEiQzV2cJKywaeXiAlGSIpH3hfUhwTJObbxu9RNATTMAuA2FmeZUS07KcxYEs@wuhsnSUGrkIXKXEhvOSmrKQ9jRZrDSWgjNGNmFH0I55kpof8h2kYcwigklRAgp7m3ktu@HUfh/G2W@T/hLKRVWXBrDlZczbm3TwwJX/5SsucL3PI0QWajgebFrFuHL5zxOyMSQQuRC7B6xDnEX4rHqal9yfigTgYf2YqePnxbaYfgawi4aiyanMbZuXCNYtz8 "Ruby – Try It Online") of @Arnauld's [JavaScript answer](https://codegolf.stackexchange.com/a/211770/92901) is shorter (58 bytes). However, I like the 63-byter above because it differs from other approaches in that it's a cubic polynomial: no square roots, no infinite series.
[This excellent review](http://www.ebyte.it/library/docs/math05a/EllipsePerimeterApprox05.html) lists nearly 40 different methods for approximating the circumference of an ellipse, with graphs of the relative error in each approximation as a function of \$b/a\$. Inspection of the graphs shows that only a few of the listed methods are capable of satisfying the required tolerance of \$10^{-6}\$ for all test cases. Since several answers here had already explored 'Ramanujan II' (eq. (5)), I decided to look at the Padé approximations 'Padé 3/2' and 'Padé 3/3'.
A [Padé approximant](https://en.wikipedia.org/wiki/Pad%C3%A9_approximant) is a rational function with coefficients chosen so as to match the largest possible number of terms in a known power series. In this case, the relevant power series is the infinite sum that appears in eq. (4). The Padé 3/2 and Padé 3/3 approximants for this series are mathematically straightforward (see the review linked above) but not suited to code golf. Instead, an *approximation to the approximants* is obtained by least-squares fitting. The resulting cubic polynomial (with truncated coefficients), as implemented in the code, is
$$
0.0053h^3 + 0.0154h^2+0.25h+1.
$$
Note that this function is overfitted to the test cases, partly because of the truncation and partly because the fit was optimised using only those values of \$h=(a-b)^2/(a+b)^2\$ that occur in the test cases. (Consequently, `Math::PI` cannot be substituted in place of `3.141593`, despite having the same byte count, without yielding relative errors above the \$10^{-6}\$ threshold for the two test cases for which \$b/a=1/2\$.)
[Answer]
# x87 machine code, ~~65~~ ~~59~~ 53 bytes
```
00000000: d9c1 d9c1 dec1 d9ca dee9 d8c8 d9c1 d8c8 ................
00000010: def9 6a03 8bf4 de0c ff04 df04 d9c1 dee9 ..j.............
00000020: d9fa 8304 06de 04de f9d9 e8de c1d9 ebde ................
00000030: c9de c95e c3 ...^.
```
Listing:
```
D9 C1 FLD ST(1) ; load a to ST
D9 C1 FLD ST(1) ; load b to ST
DE C1 FADD ; a + b
D9 CA FXCH ST(2) ; save result for end
DE E9 FSUB ; a - b
D8 C8 FMUL ST(0), ST(0) ; ST ^ 2
D9 C1 FLD ST(1) ; copy a + b result to ST
D8 C8 FMUL ST(0), ST(0) ; ST ^ 2
DE F9 FDIV ; calculate h
6A 03 PUSH 3 ; load const 3
8B F4 MOV SI, SP ; SI to top of CPU stack
DE 0C FIMUL WORD PTR[SI] ; ST = h * 3
FF 04 INC WORD PTR[SI] ; 4 = 3 + 1
DF 04 FILD WORD PTR[SI] ; load const 4
D9 C1 FLD ST(1) ; load 3h to ST
DE E9 FSUB ; 4 - 3h
D9 FA FSQRT ; sqrt(ST)
83 04 06 ADD WORD PTR[SI], 6 ; 10 = 4 + 6
DE 04 FIADD WORD PTR[SI] ; ST + 10
DE F9 FDIV ; 3h / ST
D9 E8 FLD1 ; load const 1
DE C1 FADD ; ST + 1
D9 EB FLDPI ; load PI
DE C9 FMUL ; * PI
DE C9 FMUL ; * ( a + b ) from earlier
5E POP SI ; restore CPU stack
C3 RET ; return to caller
```
Callable function, input `a` and `b` in `ST(0)` and `ST(1)`. Output in `ST(0)`. Implements Ramanujan's 2nd approximation (eq 5) in full hardware 80-bit extended precision.
Test program:
[![enter image description here](https://i.stack.imgur.com/iP4N0.png)](https://i.stack.imgur.com/iP4N0.png)
[Answer]
# JavaScript (ES7), ~~59~~ 56 bytes
*Saved 2 bytes thanks to @DominicvanEssen*
```
a=>b=>Math.PI*((h=3*(a-b)**2/(a+=b))/(10+(4-h/a)**.5)+a)
```
[Try it online!](https://tio.run/##dc1NTsNADIbhPafI0pMonrE9np/FdM8CiStMSkuKqgbRiuuHIJCIUrHxwnr0vW/1s173H6f3W3@ZXg7zscy17Iaye6q3EZ8fW4CxSAu1H0zbsoXalcEYC@Q68P1o6/JGNV018366XKfzAc/TKxyBmsYsx5jG2iYgJ6Gk4uLDhiGvWWaNmSjrHdM/FjELR8rxjvE6mjGk5H1idhsma0aCEnxaJnnDdM2Y0JFz3qvfRt03c7/RgP9EicWA1x@mGjCI5ixh/gI "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~31~~ 30 bytes
-1 byte thanks to Jonah!
```
[:o.1#.+*i.@9*:@(^~*0.5!~[)-%+
```
[Try it online!](https://tio.run/##fc6xCsJAEATQPl8xicjlLmbZu@TALAgBwcrKNmATDGqTP8ivn2cfthimeDDMN1VkFlwEBicwJKclXB/3W5pkJX@gxn1oHJyM9XNzTLHcJtsem2QLFK/5vcIwDQbnUgJqD2ABvM29oxRUjYoGdblTNaoa@K@e7e6p0GXsY8b0Aw "J – Try It Online")
Essentially a J port of [@ovs's APL solution](https://codegolf.stackexchange.com/a/211775/75681).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~97~~ ~~92~~ 91 bytes
Saved ~~4~~ 5 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!!
Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
float f(a,b,k)float a,b,k;{k=k?:2;k=k>999?1:(1-b*b/a/a)*(k-4+3/k)/k*f(a,b,k+2)+6.283185*a;}
```
[Try it online!](https://tio.run/##dZLbjpswEIbv8xSjSJE4GINtbPCyh4uqT9FEK0NMi0ghAi6iRnn2dDhksxu1CGyP/f3j32OK4GdRXK/loTUDlI4hOandOZrG2bl@qd@eeIbdq9b6jT05LMi9PDShcT2nDmJfhLUb1t6i9rnrK8pTwVLpmexyrZoBfpuqcdzVeQX4zOkH2w/v5scOXuDMCDDKx0YSwF4QGAcRznBxyR5V@V318KIill8E9nS0xWD3s@RmTEQJAUU1l4lmTONmCdWCJ0wnY6CpStM4TvlkQVCh4hSX0RlnNGJRFMcyRkzROyalokpIrYX6auDYV4e2wd1ZZAM1LxW/TOdBN5tab0/f@fakv@En1wQ@x2KNyeZsbQfOWMuq2dsT6qJsGT5DX/2xbenczuqGy4T3MZOB70@0C/Ml3A0azLVcxkTssgcgvwH5fwCLwEed/430iEw/iPu4sreHYbRQmrx3@sB@AsbTFm3XYWIEZvD5VtA7duwQLJ31piSwKSF4HdtNv22wloZATqAnWOsl027Z4LK6XP8C "C (gcc) – Try It Online")
Port of [Anders Kaseorg](https://codegolf.stackexchange.com/users/39242/anders-kaseorg)'s [Python answer](https://codegolf.stackexchange.com/a/211780/9481).
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 20 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
-ëΣ_¬/²3*_4,√♂+/)π**
```
Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/211776/52210), and thus also implements a modification of the fifth formula.
[Try it online.](https://tio.run/##y00syUjPz0n7/1/38Opzi@MPrdE/tMlYK95E51HHrEczm7T1Nc83aGn9/2@oZ6AAxFyGekZQ2hRMG0HFjaG0KZQ2MgAxDEAqjUByJkAJAA)
**Explanation:**
```
- # b-a
ëΣ # a+b
_ # Duplicate
¬ # Rotate stack: b-a,a+b,a+b → a+b,b-a,a+b
/ # Divide
² # Square
3* # Multiply by 3
_ # Duplicate
4, # Subtract from 4
√ # Square-root
♂+ # Add 10
/ # Divide
) # Increment by 1
π* # Multiply by PI
* # Multiply by the a+b we've duplicated
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~25~~ 24 bytes
```
4EllipticE[1-(#2/#)^2]#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b738Q1JyezAMhzjTbU1VA20lfWjDOKVVb7H1CUmVcSraxrl@bg4BetHBurpqDvoFBdbahjWKtTbahnBKVNwTSEZwwmoSIGOoYGIBVGxjomprW1//8DAA "Wolfram Language (Mathematica) – Try It Online")
-1 thanks to @AndersKaseorg
Note that Mathematica uses a different convention for elliptic integrals, hence the square root disappears.
[Answer]
# Haskell, 73 bytes
```
e a b=(a+b)*pi*(1+3*l/(10+sqrt(4-3*l))+3*l^5/2^17)where l=((a-b)/(a+b))^2
```
Experimenting with an improved version of (5):
$$E(a,b) = \pi (a+b) \left( 1 + \frac{3h^2}{10 + \sqrt{4-3h^2}} + \frac{3h^{10}}{2^{17}}\right)$$
[Answer]
# [MATL](https://github.com/lmendo/MATL "MATL – Try It Online"), 19 bytes
```
y/U_Q.5t_hlbZh*YPE*
```
[Try it online!](https://tio.run/##y00syfn/v1I/ND5Qz7QkPsMwKSpDKzLAVev/fyMuQwA) Or [verify all test cases](https://tio.run/##y00syfmf8L9SPzQ@UM@0JD7DMCkqQysywFXrv0vIf0MuINQzApOmQBLEMgZiMNuAyxCIjIy5TEwB).
### Formula used
This is based on formula (1) from the challenge description,
\[
C = 4a\int^{\pi/2}\_{0}{\sqrt{1-e^2 \sin^2 \theta} ;d\theta} = 4 a\,E(e),
\]
where \$e\$ is the eccentricity,
\[
e = \sqrt{1 - b^2/a^2},
\]
and \$E\$ is the [complete elliptic integral of the second kind](https://en.wikipedia.org/wiki/Elliptic_integral#Complete_elliptic_integral_of_the_second_kind). This integral can be expressed in terms of [Gauss' hypergeometric function](https://en.wikipedia.org/wiki/Hypergeometric_function), \${}\_2F\_1\$, as follows:
\[
E(e) = \tfrac{\pi}{2} \;{}\_2F\_1 \left(\tfrac12, -\tfrac12; 1; e^2 \right).
\]
Combining the above gives the formula used in the code:
\[
C = 2\pi a \;{}\_2F\_1 \left(\tfrac12, -\tfrac12; 1; 1 - b^2/a^2 \right).
\]
### Code explanation
```
y % Implicit inputs: a, b. Duplicate from below
% STACK: a, b, a
/ % Divide
% STACK: a, b/a
U_Q % Square, negate, add 1
% STACK: a, 1-(b/a)^2
.5t_h % Push 0.5, duplicate, negate, concatenate
% STACK: a, 1-(b/a)^2, [0.5, -0.5]
1 % Push 1
% STACK: a, 1-(b/a)^2, [0.5, -0.5], 1
b % Bubble up in the stack
% STACK: a, [0.5, -0.5], 1, 1-(b/a)^2
Zh % Hypergeometric function, 2F1
% STACK: a, 2F1([0.5, -0.5], 1, 1-(b/a)^2)
* % Multiply
% STACK: a * 2F1([0.5, -0.5], 1, 1-(b/a)^2)
YPE % Push pi, multiply by 2
% STACK: a * 2F1([0.5, -0.5], 1, 1-(b/a)^2), 2*pi
* % Multiply. Implicit display
% STACK: 2*pi*a * 2F1([0.5, -0.5], 1, 1-(b/a)^2)
```
[Answer]
# APL(NARS), 21 chars
```
a←⎕⋄{√+/×⍨a×1 2○⍵}∫○2
```
test:
```
a←⎕⋄{√+/×⍨a×1 2○⍵}∫○2
⎕:
1 1
6.283185307
a←⎕⋄{√+/×⍨a×1 2○⍵}∫○2
⎕:
123 45
556.6359936
```
it is based on the parametric representation of ellipse something as
`phi(t)=(a cos(t),b sin(t)) t∊[0,2π)`
and the formula for find the lenght of the curve $$L(\varphi)=\int\_0^{2\pi} \left| \varphi'(t) \right|dt $$
where `phi'(t)=(a -sin(t), b cos(t) ) t∊[0,2π)`.
It is possible calculate more digit in that integral but solution is more long, as in
```
⎕FPC←3000⋄a←⎕⋄300⍕{√+/×⍨a×1 2○⍵}∫○2v
⎕:
1 1
6.283185307179586476925286766559005768394338798750211641949889184615632812572417997256069650684234135964296173026564613
294187689219101164463450718816256962234900568205403877042211119289245897909860763928857621951331866892256951296467
573566330542403818291297133846920697220908653296426787214520498282547
300⍕○2v
6.283185307179586476925286766559005768394338798750211641949889184615632812572417997256069650684234135964296173026564613
294187689219101164463450718816256962234900568205403877042211119289245897909860763928857621951331866892256951296467
573566330542403818291297133846920697220908653296426787214520498282547
```
[Answer]
# [SageMath](https://sagemath.org), 37 bytes
```
lambda a,b:4*a*elliptic_ec(1-b*b/a/a)
```
[Try it online!](https://sagecell.sagemath.org/?z=eJw1jUEKgzAURPeB3OHvzA8xmlQ3QnuRtpSfVCGgVmx24t0b23Q278EMzHC-cTbS5J4EpFzXSJL9OIYlBv_ovTClk66iipAzzobXCp7ePYQZrsJoZTSqRPuX9ic2N6fMNtPWServ1KauaTXeO84gZVnDHEWx7VBeYNsLnb4miuK4UzAIeQgifgCCUywB&lang=sage&interacts=eJyLjgUAARUAuQ==)
Uses the elliptic integral formulation.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ ~~21~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÆnIOn/3*D4s-tT+/>IOžqP
```
Implements the fifth formula. Input as a pair \$[a,b]\$.
-1 byte thanks to *@ovs*.
[Try it online](https://tio.run/##yy9OTMpM/f//cFuep3@evrGWi0mxbkmItr6dp//RfYUB//9Hm@oYxgIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w22V/vp5xlouJsW6JSHa@naV/kf3FQb81/kfHW2oYxirE22oZwSlTcE0hGcMJqEiBjqGBiAVRsY6JqaxsQA).
**Explanation:**
```
Æ # Reduce the (implicit) input-pair by subtraction: a-b
IO # Push the input-pair again and sum it: a+b
/ # Divide them by one another: (a-b)/(a+b)
n # Square it: ((a-b)/(a+b))²
3* # Multiply it by 3: ((a-b)/(a+b))²*3
D # Duplicate that
4α # Take the absolute difference with 4: |((a-b)/(a+b))²*3-4|
t # Take the square-root of that: sqrt(|((a-b)/(a+b))²*3-4|)
T+ # Add 10: sqrt(|((a-b)/(a+b))²*3-4|)+10
/ # Divide the duplicate by this:
# (a-b)²/(a+b)²*3/(sqrt(|((a-b)/(a+b))²*3-4|)+10)
> # Increase it by 1:
# (a-b)²/(a+b)²*3/(sqrt(|((a-b)/(a+b))²*3-4|)+10)+1
IO # Push the input-sum again: a+b
žq # Push PI: 3.141592653589793
P # Take the product of the three values on the stack:
# ((a-b)²/(a+b)²*3/(sqrt(|((a-b)/(a+b))²*3-4|)+10)+1)*(a+b)*π
# (after which the result is output implicitly)
```
Note that I use \$\left|3h-4\right|\$ instead of \$4-3h\$ in my formula to save a byte, but given the constraints \$0<b\leq a\$, \$h\$ will be: \$0\leq h<1\$, and thus \$3h\$ will be at most \$2.999\dots\$.
I also use \$h=\left(\frac{a-b}{a+b}\right)^2\$ instead of \$h=\frac{(a-b)^2}{(a+b)^2}\$ to save another byte (thanks to *@ovs*).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
≧×χφNθNηI×⁴ΣEEφE²∕⁺ιλφ₂⁺××θθ⁻Σι⊗₂Πι××ηη⁻⁻²Σι⊗₂⁻⊕ΠιΣι
```
[Try it online!](https://tio.run/##bZC/bsIwEMbn5ilutCVXalA3pqosDFQIeAETX/BJiU2cmAHEs7t2nLZR1OWsz9/97l@lpausbELYyetH39PFHOiiB3aiFnsB5ZuAmq@Lrbn64cu3Z3SsW2gddUZZzL5HVVsHrObwKF4mY0M3Usi2pnLYohlQsY315ya@xHnqIQAjucgfp2AkYA6OQHbqREalErrYYN/4uMCx89Lhwdr8MVXMsRPQRXhHJhoo4GeiGaM4/@uWoxagf6kcV2n4f/nsz6dX46Y8103HehZ7R2Zgn7Kfzs7ek8P5OoQSyvB6a74B "Charcoal – Try It Online") Link is to verbose version of code. Works by approximating the line integral for a quadrant. The default precision is unfortunately only ~5 significant figures so the first four bytes are needed to increase the precision to ~7 significant figures. Further increases are possible for the same byte count but then it becomes too slow to demonstrate on TIO. Explanation:
```
≧×χφ
```
Increase the number of pieces \$ n \$ in which to divide the quadrant from \$ 1,000 \$ to \$ 10,000 \$. `≧×φφ` would increase it to \$ 1,000,000 \$ but that's too slow for TIO.
```
NθNη
```
Input the ellipse's axes \$ a \$ and \$ b \$.
```
I×⁴Σ
```
After calculating the approximate arc length of each piece into which the quadrant was subdivided, take the sum, multiply by \$ 4 \$ for the whole ellipse and output the result.
```
EEφE²∕⁺ιλφ
```
Create a list of pieces of the quadrant. In the ellipse equation \$ \left ( \frac x a \right ) ^ 2 + \left ( \frac y b \right ) ^ 2 = 1 \$ we can set \$ \left ( \frac {x\_i} a \right ) ^ 2 = \frac i n \$ and \$ \left ( \frac {y\_i} b \right ) ^ 2 = 1 - \frac i n \$. Given a piece index \$ i \$ we want to calculate the distance between \$ ( x\_i, y\_i ) \$ and \$ ( x \_{i+1}, y\_{i+1} ) \$. For each \$ i \$ we calculate \$ j = \frac i n \$ and \$ k = \frac {i+1} n \$ and loop over the list.
```
₂⁺××θθ⁻Σι⊗₂Πι××ηη⁻⁻²Σι⊗₂⁻⊕ΠιΣι
```
The distance \$ \sqrt { ( a \sqrt k - a \sqrt j ) ^ 2 + ( b \sqrt { 1 - j } - b \sqrt { 1 - k } ) ^ 2 } \$ expands to \$
\sqrt { a^2 \left ( j + k - 2 \sqrt { j k } \right ) + b^2 \left ( (1 - j) + (1 - k) - 2 \sqrt { (1 - j) (1 - k) } \right ) } \$ which expands to \$
\sqrt { a^2 \left ( j + k - 2 \sqrt { j k } \right ) + b^2 \left ( 2 - (j + k) - 2 \sqrt { 1 + j k - (j + k) } \right ) } \$.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~28~~ 26 bytes
```
○+×1+∘(⊢÷10+∘√4-⊢)3×2*⍨-÷+
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//9H0bu3D0w21H3XM0HjUtejwdkMDEPtRxywTXSBf0/jwdCOtR70rdA9v1/6f9qhtwqPevkddzY961zzq3XJovfGjtomP@qYGBzkDyRAPz@D/hgppCoZchnpGUNoURAMA "APL (Dyalog Extended) – Try It Online")
ovs's conversion to a train.
-2 using `√`.
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 35 bytes
```
{h←3×2*⍨⍺(-÷+)⍵⋄(○⍺+⍵)×1+h÷10+√4-h}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/vzrjUdsE48PTjbQe9a541LtLQ/fwdm3NR71bH3W3aDya3g0U0gbyNA9PN9TOOLzd0ED7UccsE92M2v9pQI2PevsedTU/6l3zqHfLofXGj9omPuqbGhzkDCRDPDyD/xsqpCkYchnqGUFpUzAN5gEA "APL (Dyalog Extended) – Try It Online")
Uses Equation 4.
Longer than the other APL answer because there's more than one usage of \$h\$.
[Answer]
# [Symja](https://symjaweb.appspot.com/), 35 bytes
```
f=N(4*#1*EllipticE(1-#2*#2/#1/#1))&
```
[Try It Online!](https://symjaweb.appspot.com/input?i=f%3dN%284%2a%231%2aEllipticE%281%2d%232%2a%232%2f%231%2f%231%29%29%26%3bf%2820%2c10%29)
A port of the SageMath answer in Symja.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 35 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
MP*ºH=3*(U-V ²/(U±V)/(A+(4-H/U ¬ +U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TVAqukg9MyooVS1WILIvKFWxVikvKEErKDQtSC9VIKwgK1U&input=MTIzCjQ1)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
I÷S²3×÷ạ4½+⁵Ʋ$‘×S×ØP
```
A monadic Link accepting a pair of `[a, b]` which yields the result of formula 5.
**[Try it online!](https://tio.run/##ATYAyf9qZWxsef//ScO3U8KyM8OXw7fhuqE0wr0r4oG1xrIk4oCYw5dTw5fDmFD///9bMTIzLCA0NV0 "Jelly – Try It Online")**
---
I thought formula 4 would be the way to go, but only got 21:
```
9Ḷ.c×⁹I÷S*⁸¤²ʋ€×ØP×SS
```
[Try it online!](https://tio.run/##ATgAx/9qZWxsef//OeG4ti5jw5figblJw7dTKuKBuMKkwrLKi@KCrMOXw5hQw5dTU////1sxMjMsIDQ1XQ "Jelly – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 40 bytes
```
A,hQeQJc^-GH2^+GH2**.n0+GHhc*3J+T@-4*3J2
```
[Try it online!](https://tio.run/##K6gsyfj/31EnIzA10Cs5TtfdwyhOG0hoaenlGQAZGclaxl7aIQ66JkDa6P//aEM9Ix3DWAA "Pyth – Try It Online")
Just formula 5, like most other answers here.
[Answer]
# [Perl 5](https://www.perl.org/), 70 bytes
```
sub{my$s;map$s+=sqrt+($_[0]*cos)**2+($_[1]*sin)**2,0..1570795;4e-6*$s}
```
[Try it online!](https://tio.run/##TZBNj9owEIbv/hUW9ZIQghN/JTEh6vZSqepWPbQ9LQiFykGR@KoddouW7V@nttnS5DCe9/HMO@MclN6Iy9Eo@NCabjr90bUbGJjjNigBaqqLOa5etidkym19QGZcmV@6G4do@Zguop97M4oi6iVZRKbdORmnGBORp7kUJVeTLELm9VICN@K7ciO@7LUqwfYE7zurK2v8aA6btlvE/kjmuySezQK7AIHuu8YM04KRQrA0BwTTHpdU5JIQKSwXN55jyWhOpF0D0J6PxFlRcF5QmgLW44RhlvHCNlEgepwSnJI05VxwQFPPfZQZvvkQ6py4bxMiwxkTUrLszR/68UTgIhOcSSEBaPY69K8fvQB3uT2FqI7RKkbq92FU3aNl@cbRet9VQ9Rc70c3rLSuXPHEFfTpUqtNVa9M6ETi/Ur4zsK6a58UtHCvfflBt7sO/muBM/euKIKTDL6HwdfPEAZwCoOPHz49BGWvYQDr6m7CDFxdjzqxicCsgXaURYQY6HZ2GXbCbXpnc@6H@/WclM1/yTFV890AXH9X9cck4fzbeFT5mBg/uBnYKzQcxOqp3iBii87z5/F5jtDwvNaxStZKg9fLXw "Perl 5 – Try It Online")
# [Perl 5](https://www.perl.org/), 78 bytes
```
sub f{($a,$b)=@_;$H=3*(($a-$b)/($a+=$b))**2;3.141593*$a*(1+$H/(10+sqrt 4-$H))}
```
With the `a+=b` trick stolen from the Javascript answer.
[Try it online!](https://tio.run/##TZHbbtswDIbv9RRCqtaH2LJ1sq04xrqbIcM67GLbVRMEDiAHBnKa5bYrmuzVM0npMhsCRX4if9LgQXUbcX7SCj60up9MfvbtBnr6aeuVZ/20gs2bj@oIrYLqflmiWcVC34DYgMTc48o4QRjSkmHCiZAsRHXokzGaJT5Jx/pX10Meo1kQnM43Fz2u4iw0DeC2PqDlY7oIXRaJfXMMIIvEYSsbhLrdGWj9KMWYiDzNpTgBO/APZQf@uu9UCbav8L43cWVEH/Vh0/aLyF3JfJdE06nnlYBA@11shmnBSCFYmgOC6YBLKnJJiBSGiyvPsWQ0J9I0B3SgI3FWFJwXlKaADThhmGW8MEUUiAGnBKckTTkXHNDUcWdlhq86hFol7sqEyHDGhJQsA6DZd777y@AN2Mft62U3EVK/D2ZBaFm@c7Te91XzvrkrVF1X2dTYPg/pslObql5p3waJUyvhjYF13z4raOC@c@mHrt318F8JnNrpwxDGGfwAvW9fIPTgBHqfPn5@8MpBwQjW1W3MNFxdrjoxjsCsgaaVQYRoaCe2HraBnfTW@Nw1d@PZUDb/Q46pmu9GrguE1R@d@PPv46ByNtGucTMyT@huFKnneoOISTrOX8bHOUJ3x3UXqWStOnA6/wU "Perl 5 – Try It Online")
Or this one which is 13 bytes less (but uses core module List::Util)
# [Perl 5](https://www.perl.org/) -MList::Util=sum, ~~74~~ ~~65~~ 65+16 bytes
```
sub f{4e-6*sum map sqrt+($_[0]*cos)**2+($_[1]*sin)**2,0..1570795}
```
[Try it online!](https://tio.run/##TZDLbtswEEX3/IqBq0S2LFPiSxItC003BYqm6KLtKjYMuaAMAX6VlJMGcfrrLkmnrrQYzj0zc4fUQemNOB@NgvvWdNPpj67dQGiO27A8m@MKmheuJllkAWzrA5hfuhsPg@VDuoh@7s0oiqiXZBGZdudknGJMRJ7mUrx63@/K@X7Za1Wi7TPcdVZX1uvBHDZtt4j9kcx3STybhWGJCLjvEjNMC0YKwdIcEUx7XFKRS0KksFxceY4lozmRdjmiPR@Js6LgvKA0RazHCcMs44Udokj0OCU4JWnKueCIpp77KDN89SHUOXE/JkSGMyakZNmbP/j1ROAiE5xJIRFq9nroXz96Qa64fR4GdRys4kD9Poyqu2BZvvFgve@q5lIdXaHSunKtE1fu06VWm6pemaETiXcr4Z2Fddc@KrBwr337Qbe7Dv6NwMy9KopgksF7CL9@BghhCuHHD5/uw7I3MIC6upkwA6vLUSc2EZg1YFdZRIgBd2OXYSfcTW9szv1yfz0nZfNfckzVfDdAl59V/THJcP5tPKp8TIxf3AxsKbgdxOqx3gTENp3mT@PTPAhuT2sdq2StNHo9/wU "Perl 5 – Try It Online")
Which numerically calculates a variant of formula (1).
I was surprised this worked with sin and cos of integers up to 1570795 ≈ 500000π. But the tests in the question in "Try it online" has relative error < 0.000001. Guess `sin²(the integers)` is "averaged out" good enough.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 29 bytes
```
{_:+_P*@:-@d/_*3*_4\-mqA+/)*}
```
[Try it online!](https://tio.run/##S85KzP1fWPe/Ot5KOz5Ay8FK1yFFP17LWCveJEY3t9BRW19Tq/Z/3f9oUwXDWAA "CJam – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 31 bytes
```
f(a,b)=4*a*ellE((1-b^2/a^2)^.5)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboW-9M0EnWSNG1NtBK1UnNyXDU0DHWT4oz0E-OMNOP0TDUhqm4WJhYU5FRqJCro2ikUFGXmlQCZSiCOkkJyYk6ORpqOQqKmpo5CdLShjoJhLJBhqGcEZ5lCWTARYygNFzcAMgzAao2AciamsbFQi2HOBAA)
[Answer]
# [Python](https://www.python.org)/[mpmath](https://mpmath.org), 51 bytes
```
lambda a,b:8*elliprg(0,a*a,b*b)
from mpmath import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxNCsIwEEb3PcUsM2EsxqqUojdxk6CxgfwRxoVncRMQvZO3UVI378EH73u8853nFOvTHk-vG9vV-Bm8DuasQZOZRnnx3uVyFWvS8rdIg50tKUDIQfMMLuRUWP7Tg00FGFwEIRQpJKH6XfOmcd-4pQFx6iAXF1kwgRWSEZePWhd_AQ)
Using Carlson's symmetric integrals – as seen [here](https://codegolf.stackexchange.com/a/257775/110698) – not only removes the need to sort input, it saves 1 byte off the bog-standard \$4aE(e)\$ formula. As given in [DLMF 19.30.5](https://dlmf.nist.gov/19.30#E5), \$L=8R\_G(0,a^2,b^2)\$.
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [22 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
┴þ5‡Ô縄”R¤ËíÜç›WðÙÝÁ*
```
[Try it!](https://zippymagician.github.io/Arn?code=cGkqKDMqKCtcKS06LygqMys6fSkqKzMqOn0=&input=WzEgMV0KWzEuMiAxXQpbMiAxXQpbMjAgMTBd&flags=ZQ==) A pretty good approximation, but not exact for the larger values. Uses the crossed out formula (which I assume was removed due to the innacuracy). For any wondering, I managed to get the non-crossed out formula 5 to 33 bytes, but I couldn't figure out how to shorten it (and it was even less accurate than this one).
# Explained
Unpacked: `pi*(3*(+\)-:/(*3+:})*+3*:}`
```
pi Variable; first 20 digits of π
*
(
3
*
(+\) Folded sum ([a, b] -> a + b)
-
:/ Square root
(
_ Variable; initialized to STDIN; implied
*
3
+
_ Implied
:} Tail
)
*
_ Implied
+
3
*
_ Implied
:}
Ending parentheses implied
```
] |
[Question]
[
Within the scope of this question, let us consider only strings which consist of the character `x` repeated arbitrary number of times.
For example:
```
<empty>
x
xx
xxxxxxxxxxxxxxxx
```
(Well, actually it doesn't have to be `x` - any character is fine as long as the whole string only has 1 type of character)
Write a regex in any regex flavor of your choice to match all strings whose length is n4 for some non-negative integer n (n >= 0). For example, strings of length 0, 1, 16, 81, etc. are valid; the rest are invalid.
Due to technical limitations, values of n bigger than 128 are hard to test against. However, your regex should, at least in theory, work with all numbers up to infinity (assuming unlimited memory and computation time).
Note that you are not allowed to execute arbitrary code in your regex (to Perl users). Any other syntax (look-around, back-reference, etc.) is allowed.
Please also include a short explanation about your approach to the problem.
(Please don't paste auto generated regex syntax explanation, since they are useless)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). For each regex flavor, the regex compatible with that flavor having the shortest length in bytes wins in that category. The shortest of all of the answers wins overall.
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
---
Note that this challenge was originally posted as a puzzle, not code-golf. But the actual answers basically treated it as code-golf anyway, just without actually specifying their sizes in bytes. That has now been fixed, to give the challenge objective winning criteria and make it on-topic for CGCC.
## Scoreboard
| Regex engine(s) | Length in bytes / Winner(s) |
| --- | --- |
| **ECMAScript** | **41** – [DC.223051](https://codegolf.stackexchange.com/a/223051/17216) |
| **ECMAScript / Python or better** | **43** – [DC.223051](https://codegolf.stackexchange.com/a/223051/17216) |
| **Boost** | **43** – [DC.223051](https://codegolf.stackexchange.com/a/223051/17216) |
| **Python** | **43** – [DC.223051](https://codegolf.stackexchange.com/a/223051/17216) |
| **Python (with `[regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`)** | **43** – [DC.223051](https://codegolf.stackexchange.com/a/223051/17216) |
| **Ruby** | **43** – [DC.223051](https://codegolf.stackexchange.com/a/223051/17216) |
| **Perl** | **32** – [DC.223048](https://codegolf.stackexchange.com/a/223048/17216) |
| **Java** | **32** – [DC.223048](https://codegolf.stackexchange.com/a/223048/17216) |
| **PCRE** | **35** – [DC.223129](https://codegolf.stackexchange.com/a/223129/17216), [DC.223048](https://codegolf.stackexchange.com/a/223048/17216) |
| **Perl / PCRE** | **35** – [DC.223129](https://codegolf.stackexchange.com/a/223129/17216), [DC.223048](https://codegolf.stackexchange.com/a/223048/17216) |
| **PCRE1 / PCRE2 v10.33 or earlier** | **34** – [DC.223129](https://codegolf.stackexchange.com/a/223129/17216) |
| **PCRE2 v10.34 or later** | **32** – [DC.223048](https://codegolf.stackexchange.com/a/223048/17216) |
| **.NET** | **32** – [DC.223048](https://codegolf.stackexchange.com/a/223048/17216) |
| **Perl / Java / PCRE v10.34 or later / .NET** | **32** – [DC.223048](https://codegolf.stackexchange.com/a/223048/17216) |
| **Perl / Java / PCRE / .NET** | **35** – [DC.223048](https://codegolf.stackexchange.com/a/223048/17216) |
| **Perl / Java / PCRE / .NET, no lookarounds** | **39** – [primo](https://codegolf.stackexchange.com/a/22084/17216) |
[Answer]
# Perl / Java / PCRE / .NET, 39 bytes
## Another Solution
This is, in my opinion, one of the most interesting problems on the site. I need to thank [deadcode](https://codegolf.stackexchange.com/a/21951) for bumping it back up to the top.
```
^((^|xx)(^|\3\4\4)(^|\4x{12})(^x|\1))*$
```
**39 bytes**, without any conditionals or assertions... sort of. The alternations, as they're being used (`^|`), are a type of conditional in a way, to select between "first iteration," and "not first iteration."
This regex can be seen to work here: <http://regex101.com/r/qA5pK3/1>
PCRE interprets the regex correctly, and it has also been tested in Perl up to *n = 128*, including *n4-1*, and *n4+1*.
---
**Definitions**
The general technique is the same as in the other solutions already posted: define a self-referencing expression which on each subsequent iteration matches a length equal to the next term of the forward difference function, *Df*, with an unlimited quantifier (`*`). A formal definition of the forward difference function:
\$D\_f(n)=f(n+1)-f(n)\$
Additionally, higher order difference functions may also be defined:
\$D\_f^2(n)=D\_f(n+1)-D\_f(n)\$
Or, more generally:
\$D\_f^k(n)=D\_f^{k-1}(n+1)-D\_f^{k-1}(n)=\sum\limits\_{i=0}^k{(-1)^i}{k\choose i}f(n+k-i)\$
The forward difference function has a lot of interesting properties; it is to sequences what the derivative is to continuous functions. For example, *Df* of an *n*th order polynomial will always be an *n-1*th order polynomial, and for any *i*, if *Dfi* = *Dfi+1*, then the function *f* is exponential, in much the same way that the derivative of *ex* is equal to itself. The simplest discrete function for which *f* = *Df* is *2n*.
---
***f(n) = n2***
Before we examine the above solution, let's start with something a bit easier: a regex which matches strings whose lengths are a perfect square. Examining the forward difference function:
\$D\_f=[1,3,5,7,9,\dots]=2n+1\$
Meaning, the first iteration should match a string of length *1*, the second a string of length *3*, the third a string of length *5*, etc., and in general, each iteration should match a string two longer than the previous. The corresponding regex follows almost directly from this statement:
```
^(^x|\1xx)*$
```
It can be seen that the first iteration will match only one `x`, and each subsequent iteration will match a string two longer than the previous, exactly as specified. This also implies an amazingly short perfect square test in perl:
```
(1x$_)=~/^(^1|11\1)*$/
```
This regex can be further generalized to match any *n*-gonal length:
Triangular numbers:
`^(^x|\1x{1})*$`
Square numbers:
`^(^x|\1x{2})*$`
Pentagonal numbers:
`^(^x|\1x{3})*$`
Hexagonal numbers:
`^(^x|\1x{4})*$`
etc.
---
***f(n) = n3***
Moving on to *n3*, once again examining the forward difference function:
\$D\_f=[1,7,19,37,61,\dots]=3n^2+3n+1\$
It might not be immediately apparent how to implement this, so we examine the second difference function as well:
\$D\_f^2=[6,12,18,24,30,\dots]=6n+6\$
So, the forwards difference function does not increase by a constant, but rather a linear value. It's nice that the initial ('*-1*th') value of *Df2* is zero, which saves an initialization on the second iteration. The resulting regex is the following:
```
^((^|\2x{6})(^x|\1))*$
```
The first iteration will match *1*, as before, the second will match a string *6* longer (*7*), the third will match a string *12* longer (*19*), etc.
---
***f(n) = n4***
The forward difference function for *n4*:
\$D\_f=[1,15,65,175,369,\dots]=4n^3-6n^2+4n-1\$
The second forward difference function:
\$D\_f^2=[14,50,110,194,302,\dots]=12n^2-24n+14\$
The third forward difference function:
\$D\_f^3=[36,60,84,108,132,\dots]=24n+36\$
Now that's ugly. The initial values for *Df2* and *Df3* are both non-zero, *2* and *12* respectively, which will need to be accounted for. You've probably figured out by now that the regex will follow this pattern:
```
^((^|\2\3{b})(^|\3x{a})(^x|\1))*$
```
Because the *Df3* must match a length of *12* on the second iteration, *a* is necessarily *12*. But because it increases by *24* each term, the next deeper nesting must use its previous value twice, implying *b = 2*. The final thing to do is initialize the *Df2*. Because *Df2* influences *Df* directly, which is ultimately what we want to match, its value can be initialized by inserting the appropriate atom directly into the regex, in this case `(^|xx)`. The final regex then becomes:
```
^((^|xx)(^|\3\4{2})(^|\4x{12})(^x|\1))*$
```
---
**Higher Orders**
A fifth order polynomial can be matched in with the following regex:
`^((^|\2\3{c})(^|\3\4{b})(^|\4x{a})(^x|\1))*$`
*f(n) = n5* is a fairly easy excercise, as the initial values for both the second and fourth forward difference functions are zero:
```
^((^|\2\3)(^|\3\4{4})(^|\4x{30})(^x|\1))*$
```
For six order polynomials:
`^((^|\2\3{d})(^|\3\4{c})(^|\4\5{b})(^|\5x{a})(^x|\1))*$`
For seventh order polynomials:
`^((^|\2\3{e})(^|\3\4{d})(^|\4\5{c})(^|\5\6{b})(^|\6x{a})(^x|\1))*$`
etc.
Note that not all polynomials can be matched in exactly this way, if any of the necessary coefficients are non-integer. For example, *n6* requires that *a = 60*, *b = 8*, and *c = 3/2*. This can be worked around, in this instance:
```
^((^|xx)(^|\3\6\7{2})(^|\4\5)(^|\5\6{2})(^|\6\7{6})(^|\7x{60})(^x|\1))*$
```
Here I've changed *b* to *6*, and *c* to *2*, which have the same product as the above stated values. It's important that the product doesn't change, as *a·b·c·…* controls the constant difference function, which for a sixth order polynomial is *Df6*. There are two initialization atoms present: one to initialize *Df* to *2*, as with *n4*, and the other to initialize the fifth difference function to *360*, while at the same time adding in the missing two from *b*.
[Answer]
# Perl / PCRE / .NET, 66 bytes
[This (ir)regular expression](http://regex101.com/r/vH3nD8) seems to work.
```
^((?(1)((?(2)\2((?(3)\3((?(4)\4x{24}|x{60}))|x{50}))|x{15}))|x))*$
```
This regex is compatible with PCRE, Perl, .NET flavors.
This basically follows a "difference tree" (not sure if there's a proper name for it), which tells the regex how many more x's to match for the next fourth power:
```
1 16 81 256 625 1296 2401 ...
15 65 175 369 671 1105 ...
50 110 194 302 434 ...
60 84 108 132 ...
24 24 24 ... # the differences level out to 24 on the 4th iteration
```
`\2`, `\3`, `\4` stores and updates the difference as shown on the 2nd, 3rd and 4th rows, respectively.
This construct can easily be extended for higher powers.
Certainly not an elegant solution, but it does work.
[Answer]
# ECMAScript / Perl / Java / Python / Ruby / PCRE / .NET, 50 bytes
Here is a solution that does not use conditionals, forward-declared or nested backreferences, lookbehind, balancing groups, or regex recursion. It only uses lookahead and standard backreferences, which are very widely supported. I was inspired to operate under these limitations due to [Regex Golf](http://regex.alf.nu/), which uses the ECMAScript regex engine.
The way this 50 byte regex works is conceptually rather simple, and completely different than all the other submitted solutions to this puzzle. It was surprising to discover that this kind of mathematical logic was expressible in a regex.
```
\2 \4 \5
^((?=(xx+?)\2+$)((?=\2+$)(?=(x+)(\4+)$)\5){4})*x?$
```
(Capture groups are labeled above the regex)
The regex can be generalized to any power simply by replacing the `4` in `{4}` with the desired power.
[Try it online!](https://tio.run/##TY/BTgIxFEV/BScE3qPOMIPEBbXMygUbFroUTRp4dKql07QFRpBvH4eoibube25yc97lQYa11y6mwekN@V1tP@iz9cLSsfdE6rFxACcxH4/aNyhnUApoGlbiqmB9/Cl@YwcYwmrCsI@rOzxPLzhqyn47Gp8wi/Vz9NoqwCwYvSa4v02niDyInB8rbQjACE9yY7QlQLwRdm8MnpUwWXBGRximQ@R6C2CFygxZFSucT76@dFjKJWjhpA@0sBHUS/6K@AfoP7DzoixmV4yx8vUxWdiDNHrT89IqmvUSZvi29sD1gyCuGcPuMGmSzJMjGUFjtpNxXYFHPIfBwHVKEa4WBXf7GKLvJvxyafN0WuT5Nw "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript (SpiderMonkey)
[Try it online!](https://tio.run/##TY7BboMwEER/JUKRvFuCBVF6wXU49ZBLDu2xtIoFDtmKGmo7CRLh2ym0qpTbzL6d3flUF@UKS62PTFPq0clYWPmiq@euhVdvyVTcquth/ADIJHRdmGG@Dpc42z8xj0OEfBPiEvNH7DcDPnTZcjxwV1OhIVlFCaKw@vtMVgOzWpU1Gc2QF5P2eme8tkc1rfZk2rNPW9sU2jnufElmQN4YYL@JVS23fSVr7tqaPLCIoaAjgJEVr7Wp/Am369uN3F7tgWSrrJuvQ/UWvyP@A30PzDbJknTG6E@2uQY7c1E1lQurTKXTRRDW4thYEPQktaAwxOlh0AXc6nYqD4T8S/niBBaxvyvenD2/WvIawGUsNyxlDENC4WQihgHHONokcfwD "JavaScript (Node.js) – Try It Online") - ECMAScript (Node.js - faster)
[Try it online!](https://tio.run/##RU5BasMwEPzKEkSsrWwsB@dSWbED6bWn3upUpCUGgZq4kgsuQv26KzuBXpaZ2dmd6c/WbKfPHyBWgDfXj5MBkotIZXXYv@x3AbqrpcRJLqqdQA@6iwx9b/VlgFV7WYkAjZGuN3qgSZak7vvdDfFEpVmRFnj@mk31v8qjjo9EoZh/uZh4so2pNugb81ocZZz8KO65@k6JruSyjogx9LoDSpMxgRGiCRHkL@TE5uiJW6@Xcku3WLwQt65EixCCUk/PB6WmN0prSceR1dhuGMGZ3sAsM6RtyZBgu0VfBnwYazJNPCsLzv8A "Perl 5 – Try It Online") - Perl (faster still)
[Try it online!](https://tio.run/##bVLvb9owEP3ev@IWdcIm4Iaq/TI3Qtu0SZPWbWo/ApNM4oBbx8lspwQQfzs7h@xHJfLlfHcv7/ye70m8iPFT/nxUZV1ZD0@YM1WxIYf/K41X@mzNypVssXNRN0utMsi0cA7uhTKwh77mvPAYXiqVQ4kd8uitMisQduVmCwp@bauNg09tJmuvKvzzAuCz0hKK1MhNdyQRy6pcMuxHlH9oikJamT9IkUsLyw72ukj@/NmnBaW8n@tGnm/WgZ8Qly5Rg8i/KiMJpW9S02hNVUEck78aoR2JrobDYUTp/jX0xECIP0uwRwb/lwEJrpBhibhn7uJ0MDeDED0/nGqHH8J7aQ3YtD@h2rIOAxzl6MayqrQUBnZpgYySw2MmjEHpytSNhxSC2r5GHrfOy5IpQzn0OjsYWwv3TbYer9lZDNAbovHuyHECGUT0Evv@bAEa2wHFXK2VJ9EYHwHxHkyCnS/G4xpYVgvrJCZEz5IFHYGZnG0yLc3Kr@@uYQoBCe8wTBbImK2FnS3aXk@XmcmCw3trxdaxQmlN2tGgHXSmABSVDdrwGqlJOJi71EwwxDEKvBc@W6NDJbJZVp4y0m2uwQX/iOSnjWEbK2rSj8iqevu9eBBmJXFSMjKUBqUFkBLHmxy9C2@7o73JFTq2scpLEh6V8l3qbRPe51@7Rg99QaK3LkJLKD@E7yJs1fEnIdOUtG08pfPr@JKG9HQI5ZiS@U1ML@n8lu5vDnTYTi@PYZeOyfj6Nkl@Aw "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##NY7LasMwEEX3/opBeDETP5DcZGNH@ENsF0KrNCqKbEYqdSj9djdK6O7OPZzLLLd4mf3LZq/LzBHCLZRsys8w@w5YsxBie0XsNa5r0dPYFDml8xlSXRCO@4JyGg/0s/@l3drn210bVFupqQOrZXaeGRxYn@brEN@tbzNw2tVhcTaiqARlYM/gjEdHx6YFN6hJu0FOGSTZJ5lP/sOg9REToPKZ1ESFovteGmBTB3PitwtyCWIVO/8gCdkWFk4KPQqtuv9v5q9Yf7ONBkNk9ESbrJqDlH8 "Python 3 – Try It Online") - Python
[Try it online!](https://tio.run/##PY7RS8MwEMbf/SvOUlhutSEt28tqKMUV8WXC9K2dRVnWBUJW0oxVRP/1mmy6hxz5fvd9d2eOH5@jAQ5r0Yqho1qcYFm8FtSI9@3dBS4WT4@r53X5ULyUGUjOMjjtpRKgeCtsfwMgd6CqONlwHtQ6yFxDVYzSON1kIPTWORyhfaekJZN4gn8RqoRu7Z7gfeoylcu72DWyOxjQIDV4SO2hkSRhSKk3XqXznWeRYAimGoH/gMk8kLf@zu5o@/M8f3fitJHagv5f4at/TVOulk0zvhGSczIMUY51GoXo5eXjcYSknkUYYj3Hr9k3Toc8HEcWp3PGfgE "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##XVBRa8IwEH73V4QQaM62Wos6JJa@bANh7GHbm3WhdtGW1TSkEQrib3cXt6c95Ljv7r7vu5ypzW2dm9oQZklG6JSSCTFWHaVVpi0rxYPpZJxLWZetk1V3Mk2rbMELEMXbtA8iEuA7YFEelR/QTmnXcymfNy9PUkJEZoCSKCxGjW5krxynprJqsi@rb2cxyLY5NY5GhM7T1Xy1fEhXCwpidOgsZ02WCNZmB1Tv@fvH4@YVBFxIc@Cs3fbOtkpjBvFsl2W00BRwuD/vsYPlKIniGXi@GkzbfSlOYxrhuEB@1Z2189x1iqQtCmBMdmJEyN1Z/2Gm19m9j1kYAloTfr/QqXRVzZmN0MyfS5WOB0MQMQ0A5OJXbEBVdef3EgS/MhPEY8K0uKLN9d9ZOYjbJ@d5xochzKFIQwYe/ia@HAIv5iEwKBZwmV9hPOTsdkvi5TJJfgA "PHP – Try It Online") - PCRE (fastest)
[Try it online!](https://tio.run/##RY/RioMwEEV/RWTATLMpVtqXSrDQ536BuiDutAayicQUpZJvd3XLsm9zDpfLnd6O5IaOtF7AydLRg6b6fDY0skuyfDJWSDZNvMAq44Abvo9Nc2TVkSNgdcL5GHA3FbAkl4/4ar97pekrxhxeMs3v1lHTdgx0pEwEyvRPjzM0ErQYeq18LOJc3Rk0@9Y@jRfaR9kW4BKaMq3DWsDAyFIZX/@aHIzQ9MeHjTnHeetw@1vj244GlkzJDgy@9Qvn0SlPorODD@usQ/7PkTB2fVkrQxGYEMKSiuyUpj8 "PowerShell – Try It Online") - .NET
It works by repeatedly dividing away the smallest fourth power of a prime that the current value is divisible by. As such the quotient at each step is always a fourth power, iff the original value was a fourth power. A final quotient of 1 indicates that the original value was indeed a fourth power; this completes the match. Zero is also matched.
First it uses a lazy capture group `\2` to capture the number's smallest factor larger than 1. As such, this factor is guaranteed to be prime. For example, with 1296 (6^4) it will initially capture `\2` = 2.
Then, at the beginning of a loop that is repeated 4 times, it tests to see if the current number is divisible by `\2`, with `(?=\2+$)`. The first time through this loop, this test is useless, but its purpose will become apparent later.
Next inside this inner loop, it uses the greedy capture group `\4` to capture the number's largest factor smaller than itself: `(?=(x+)(\4+)$)`. In effect this divides the number by its smallest prime factor, `\2`; for example, 1296 will initially be captured as `\4` = 1296/2 = 648. Note that the division of the current number by `\2` is implicit. While it is possible to explicitly divide the current number by a number contained in a capture group (which I only discovered four days after posting this answer), doing this would make for a slower and harder-to-understand regex, and it is not necessary, since a number's smallest factor larger than 1 will always match up with its largest factor smaller than itself (such that their product is equal to the number itself).
Since this kind of regex can only "eat away" from the string (making it smaller) by leaving a result at the end of the string, we need to "move" the result of the division to the end of the string. This is done by capturing the result of subtraction (the current number minus `\4`), into the capture group `\5`, and then, outside the lookahead, matching a portion of the beginning of the current number corresponding to `\5`. This leaves the remaining unprocessed string at the end matching `\4` in length.
Now it loops back to the beginning of the inner loop, where it becomes apparent why there is a test for divisibility by the prime factor. We have just divided by the number's smallest prime factor; if the number is still divisible by that factor, it means the original number might be divisible by the fourth power of that factor. The first time this test is done it is useless, but the next 3 times, it determines if the result of implicitly dividing by `\2` is still divisible by `\2`. If it is still divisible by `\2` at the beginning of each iteration of the loop, then this proves that each iteration divided the number by `\2`.
In our example, with an input of 1296, this will loop through as follows:
`\2` = 2
`\4` = 1296/2 = 648
`\4` = 648/2 = 324
`\4` = 324/2 = 162
`\4` = 162/2 = 81
Now the regex can loop back to the first step; this is what the final `*` does. In this example, 81 will become the new number; the next loop will go as follows:
`\2` = 3
`\4` = 81/3 = 27
`\4` = 27/3 = 9
`\4` = 9/3 = 3
`\4` = 3/3 = 1
It will now loop back to the first step again, with 1 as the new number.
The number 1 cannot be divided by any prime, which would make it a non-match by `(?=(xx+?)\2+$)`, so it exits the top-level loop (the one with `*` at the end). It now reaches the `x?$`. This can only match zero or one. The current number at this point will be 0 or 1 if and only if the original number was a perfect fourth power; if it is 0 at this point, it means that the top-level loop never matched anything, and if it is 1, it means the top-level loop divided a perfect fourth power down until it wasn't divisible by anything anymore (or it was 1 in the first place, meaning the top-level loop never matched anything).
It's also possible to solve this in 49 bytes by doing repeated explicit division (which is also generalized for all powers – replace the desired power minus one into the `{3}`), but this method is far, far slower, and an explanation of the algorithm it uses is beyond the scope of this Answer:
```
^((x+)((\2(x+))(?=(\4*)\2*$)\4*(?=\5$\6)){3})?x?$
```
[Try it online!](https://tio.run/##TZDBboJAEIbvPgUlRmegIKClqXTl1IMXD@1RbLLRFbZdFrK7Kq167QP0EfsiFpKa9DIzf77DzDdvdE/1WvHaeLrmG6bKSr6zj4sikh2sZ5Y/NTXAJ5mNnMsrQOMiQBZ1HSElkE0czCKnj@3Q5uyun8WIx/EZU2jSPl6c0Sf6pnoxissc0NeCrxnEt94EMdEkSA4FFwxAEMXoRnDJAPGGyJ0QeMyJ8HUtuIGhN8SEbwEkyX3BZG4KnEWnE9cLugBOaqo0m0sD@TJYIV4B@w/kLEzDaYfRFKo62HO5p4JvLEVlzqaW7YpkWylI@CNhCXddbBeWxG5sX7GaUQMc/ZKadQGqddSDQd1KGeg8wqTeGW0UcHdo/Xx9W0MXoFxGq7QrfxdPA3TL5f01tg84ny@BF8VBL44CLx4HvTB6iHvRJAh/AQ "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# Perl / Java / PCRE / .NET, 53 bytes
## Solution
```
^((?=(^|(?<=^x)x|xx\2))(?=(^|\2\3))(^x|\4\3{12}xx))*$
```
This regex is compatible with Java, Perl, PCRE and .NET flavors. This regex uses quite a range of features: look-ahead, look-behind and forward-declared back-reference. Forward-declared back-reference kinds of limits the compatibility of this regex to a few engines.
## Explanation
This solution makes use of the following derivation.
By fully expanding the summation, we can prove the following equality:
![\sum\limits_{i=1}^n (i+1)^4 - \sum\limits_{i=1}^n i^4 = (n+1)^4 - 1](https://i.stack.imgur.com/SK5OM.gif)
![\sum\limits_{i=1}^n i^4 - \sum\limits_{i=1}^n (i-1)^4 = n^4](https://i.stack.imgur.com/3c4dY.gif)
Let us combine the summation on the left-hand-side:
![\sum\limits_{i=1}^n (4(i+1)^3 - 6(i+1)^2 + 4(i+1) - 1) = (n+1)^4 - 1](https://i.stack.imgur.com/pKD07.gif)
![\sum\limits_{i=1}^n (4i^3 - 6i^2 + 4i - 1) = n^4](https://i.stack.imgur.com/HEYQb.gif)
Subtract the 2 equations (top equation minus bottom equation) and then combine the summations on the left-hand-side, then simplify it:
![\sum\limits_{i=1}^n (12i^2 + 2) = (n+1)^4 - n^4 - 1](https://i.stack.imgur.com/7pwDX.gif)
We obtain the difference between consecutive fourth powers as power sum:
![(n+1)^4 - n^4 = \sum\limits_{i=1}^n (12i^2 + 2) + 1](https://i.stack.imgur.com/YXU4U.gif)
This means that the **difference** between consecutive fourth powers will **increase** by (12n2 + 2).
To make it easier to think, referring to the [difference tree in Volatility's answer](https://codegolf.stackexchange.com/a/19413/6638):
* The right-hand-side of the final equation is the 2nd row in the difference tree.
* The increment (12n2 + 2) is the 3rd row in the difference tree.
---
Enough mathematics. Back to the solution above:
* The `\2` capturing group maintains a series of odd number to calculate i2 as seen in the equation.
Precisely speaking, the length of the `\2` capturing group will be 0 (unused), 1, 3, 5, 7, ... as the loop iterates.
`(?<=^x)x` sets the initial value for the odd number series. The `^` is just there to allow the look-ahead to be satisfied in the first iteration.
`xx\2` adds 2 and advance to the next odd number.
* The `\3` capturing group maintains the square number series for i2.
Precisely speaking, the length of the `\3` capturing group will be 0, 1, 4, 9, ... as the loop iterates.
`^` in `(^|\2\3)` sets the initial value for the square number series. And `\2\3` adds the odd number to the current square number to advance it to the next square number.
* The `\4` capturing group (outside any look-ahead and actually consume text) matches the whole right-hand-side of the equation we derived above.
`^x` in `(^x|\4\3{12}xx)` sets the initial value, which is `+ 1` the right-hand-side of the equation.
`\4\3{12}xx` adds the increase in difference (12n2 + 2) using n2 from capturing group `\3`, and match the difference at the same time.
This arrangement is possible due to the amount of text matched in each iteration is more than or equal to the amount of text needed to execute the look-ahead to construct n2.
[Answer]
# .NET, ~~39~~ 37 bytes
```
^(?=((?>^((?<-1>x)+|x)|\1\2\2))*$){2}
```
[Try it online!](https://tio.run/##RY9Ra4MwFIX/isgFk7qU6NOoS1vY836BWhB3WwPZjcQUpTa/3enG2MuB73A4nNPbEd3QoTELOFU6vOFUHw6EIzsny4WdFGOn42WVN5EdJ54@J/6ssiqvcs53wOc8LMn5JX63X702@BnzAh5KFlfrsGk7BibSFIGm/u75DI0CI4beaB@LuNBXBs2@tXfywvgo3wKpgqaUdVgLGJAqNfn6xymAhME/zjZOUz5vHW7/0fi2w4ElU7ID4r/2g8@j0x5FZwcf1llZ8c@RILu@NJowAgohLFLk8lXKbw "PowerShell – Try It Online")
Not only does this outgolf [primo's amazing answer](https://codegolf.stackexchange.com/a/22084/17216), but it runs at very close to exactly the same speed under .NET's regex engine.
This solution uses the .NET-specific feature of balanced groups, where every time a group is captured, it's pushed onto the stack for that particular group, and can then be popped off the same number of times. The popping is done in `(?<-1>`...`)` above.
This regex works by:
1. Asserting that \$N/\2\$ is a perfect square, using a perfect analogy of the `^(\1xx|^x)*$` perfect square regex (which uses a nested backreference), and in so doing, pushing capture group `\2` onto the stack the same number of times as \$\sqrt{N/\2}\$. This is done with capture group \$\2=1\$.
2. Redefining capture group \$\2\$ to actually be \$\sqrt N\$ as found by the first main loop iteration, when we pop all copies of `\1` off the stack at the beginning of the second iteration of the main loop. Then we assert \$N/\2\$ to be a perfect square using this new definition of \$\2\$.
So it's basically a double square root, like my two other recent answers to this challenge, but this time using .NET's balanced groups to take the square root. (Also, it doesn't return the fourth root in a capture group, just the square root in `\2`.)
And like my 41 byte ECMAScript answer, it can be modified to match \$8\$th powers, \$16\$th powers, etc., by changing the `2` in `{2}` to \$log\_2 n\$ to match \$n\$th powers.
```
^ # tail = N = input number
# Main loop - Execute the following in an lookahead, so that on the second iteration
# we can start again from zero.
(?=
# Capture group \1:
# Run the following inner loop; for every iteration, push the captured contents
# onto the balanced group stack for \1. This will later be used as a count.
# And since this is a loop with a minimum iteration count of zero, regardless of
# what is done inside, we're guaranteed to be able to match N=0.
(
# Evaluate the following in an atomic group, because otherwise the regex engine
# would backtrack into it, changing the value of \2.
(?>
# Execute this if and only if we're on the first iteration of this inner loop.
# The atomic group around it prevents the other alternative from being taken.
^
# Define \2 to be one of the following two:
(
# Pop all copies of \1 off the stack, asserting that at least one
# was pushed. If this is the first iteration of the main loop, \1
# has not yet captured anything, and this won't match (and thus will
# go to the next alternative below). This also clears \1's value,
# allowing the next iteration of the main loop to start off properly.
(?<-1>x)+
|
# \2 = 1
x
)
|
# If \1 has a value (which implies \2 also has a value), then \1 = \1 + \2*2;
# tail -= \1. On the Kth iteration, this will give us head = K^2 * \2. This
# uses the fact that (n+1)^2 - n^2 = 2n + 1. The 1 comes from \2's initial
# value.
\1\2\2
)
)* # Loop the above zero or more times
$ # Assert tail == 0
){2} # Loop the main loop above exactly twice
```
# Perl / PCRE2 v10.34 or later, ~~41~~ ~~40~~ ~~38~~ ~~37~~ ~~35~~ 33 bytes
```
^(?=(?|^((\1|x))|\1(\1\2))*+$){2}
```
[Try it online!](https://tio.run/##RU5BasMwEPzKEkSsrW1suQRCZcUOpNeeeqsTkYYYBGriSi64yOrXXcUN9LLMzM7uTHc2ejV9fAMxHJy@no4aSMYDFeVu@7rdeGivhhIrcl5uODpQbWDoOqMuPSyay4J7qLWwnVY9jdIosV/vtg8nMklZwvD8eTNV/2oedHwiEvntlw2JR1PrskBX6ze2F2Hme37PVXdKVCnmdUBxjE61QGk0RDBAMCGC@IGMmAwdscvlXG7uFooz/teVKO69l/L5ZSfldKCVoNV4oLRh44A4NiygpkB8iAm6wk9Tnq4fVwX7BQ "Perl 5 – Try It Online") - Perl
[Try it on regex101](https://regex101.com/r/v9Bzlc/1) / [Attempt This Online!](https://ato.pxeger.com/run?1=XVBBTsMwEBTXvsJYluKlSduEFlq5US6AVAlxAG6kWGlwSETqRI4rVWr7A37ABQkh3gSvYdNy4uD17Hp2Zr1vH3Vev_8cvU4jBIQZEhLap6RHaqOepVF1maSKO_3eSSRlnpRWptWyLkplYh6DiG_7jeMSB0-GRfmsWoK2StuGS3k1u76UElziA0qisOgUupCNspzWqVG9RZK-WINBlsWysNQldBhMhpOz82AyoiA6WWU4K8KBYGWYoXrD7-4vZjcgYEOKjLPyobGmVBoReP48DGmsKSC5WS3wBcvuwPV8aPvVui6rJ8WpR12kC-xPq5W2be80wKYHFMA4mIsOIXtn_ZczPQ3374i6XUBrwvcbWiY2zTkzLpq161KJ5c7acZkGALJpRyxApXnVziUIfsUXpM0J02KHNrt_a-UgPlc288bfx488Cnm0feQ89rdrgG3sI4oDgJMug02wOxDf_66vgTc-HQX-If0F) - PCRE2
This is a port of the .NET version, using group-building (with a nested backreference) instead of a balanced group. Thanks to the use of a branch reset group `(?|`...`)` to reset the value of `\2` beteween iterations of the main loop, it too can be modified to match \$8\$th powers, \$16\$th powers, etc., by changing the `2` in `{2}` to \$log\_2 n\$ to match \$n\$th powers. Commented version to come.
# Perl / PCRE, ~~41~~ ~~40~~ ~~38~~ ~~37~~ 35 bytes
```
^((?=(?|^((\2|x))|\2(\2\3))*+$)){2}
```
[Try it online!](https://tio.run/##RU7LasMwEPyVJYhYW9v4EQKlsmIH0mtPvdWpSEsMAjVxJRdcZPXX3U0a6GV3ZvYx0x@tWc8f38CsAG/O7wcDLBNEZbXbPm83Abqz5czJXFQbgR50Rwx9b/VpgEV7WogAjZGuN3rgURol7uvNDXSikrRICjx@XpbqfzUnHR@YQnH55cjxYBtTlegb81LsJdV8L26@@kaZruR1TCiO0esOOI/GCEagJUSQP5Axm6Fnbrm8hrtmo@CF@MvKtAghKPX4tFNqfuW8lryeqLflNCJObUmoXSHexQzRl2Ge8/R@tS6LXw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##hVNrb9owFP3Or7hja7EhVAlMU5WQVl3XaR9YOyEqbQIWseCAteBEjhl9wF8fu7ZJmz6kRUj4ce855557Hed5ex7Hu7dcxOlqxqCXx5IdLU5q8WIqIcpHEwhhUP@4Xv/@1V39uL39Plx8WC/I7ichpyE53eD/uLO5oXQz7uBq3KW02XpH6X1nu6PP0@oONPMwylteUHukLNSMZ5qzeiS5mD894xmesunyZdxJjQsFOS5VxKTMJIkzUSgwNTSXrCimc0bvkcf3YwyAXg/2p3ppzpmYpQFIplZSgBdsDeRyygWhcF8D/PIRsqVMkJy2vUnoBrDCmG4nUpDpnU6Y48IEG0yrDi/ylQpAOwtNyQKoqkM5uZI2W7JilSq71nUkScGUA9lKIe1cLexN9ofFKpOj7sRSIWpowKM4W@Y8ZSR34Nv54CL6dDU86/dhY3fXw8/HDhxaQrsoGVxqoXgC5I1ktPQhMZ4mBKvBaAfqGshIkzBFJSYdDmY@HBRjgd2tYFqePXCCCUSLv9NOGXPmTKVcMGK7woVjfaIBxnil50YUpgkXa5yqjBMTdBRH6C2h1AHhOZBnBV7bm4SLGWm0G3ti/QlPG4Qxb8JqX3xf6MPTV3ChZeJbgEJ8JH/Esk3TdIKt7W4kvJY3CXCillg4KRxo3DS0MCylwMtJWMl/MIKHQs9MLxReAK0Wr1Zsu6pnoewsu2ExkcyBy@t@3wHk4Ng189uPgwPdSsllM/coJyG4sNmUoOiDmYiLweBqEF1efT0bnn95LqCEuKOAzuhKSWMsGrY/wYtQ20YcVf2iePAq1J6@h2IOD/8j5gle3YcLPXT1p7jb1x2r2G0jtjUzsr4dRckYKqEPj33/6mrbnds@fu@67t84SafzYtdOtff/AA "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XVBRa4MwEH7vrwgSMNfGVt0eBqn4sDkojG3YsZfaBediFWwMardC29/uTtnL@pDkLt/33X13pjD9MjSFIbQhAbEWFpkT06idbJSp0kwxezGfhlIWadXJrN6bslJNwhIQSbxobU5sPDl@yp0aCLpTumuZlI@rp0hK4MQDLImFxST/acpOsfXbQxTH3Hq9jyOffFsg/gNYpO1S3TF7YMj3KF6vXp5tuOZZiUbtJK8bRsvAFbQKcjTRDvjqGQScSJkzWm3arqmUxggcbxsEow7J7eETEfzmLnc8GPTqaKr6SzHLsTjSBeqz@oBWMFn6KNpgAbzdrZgQMnbWfznVy2DEMZrNAFsTNi5yn3ZZwWjDsdmwVZXiZEebUw0A5DRYLEFlRT34EgRH8QQZckK1uGCby9X2GYj@g7EwYOEZ38Q/HwHOiY9RcgMwnVGAk3/pe9e5u3Vd9xc "PHP – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=XVDNTsJAEI5XnmKzbtIdaKFUVMjScFETEuNBvVHclLqFxrJttktCAryBb-CFxBifSZ_GKXDysPP7fd_MzsdnuSj3v2fvwxEGhBkSEtqhpE1Ko-bSqDKPE8WdTrs5knIR51YmxbLMcmUiHoGIHjuV4xIHX4pFOVc1QFulbcWlvBvf30oJLukCSqKwaGQ6k5WynJaJUe1ZnLxZg0bm2TKz1CW0Fwx6g6vrYHBJQTTSwnCWhb5geZiiesWfnm_GDyBgQ7KUs3xSWZMrjRF43WkY0khTQHC1mmEHy67vel2o-Wpd5sWr4tSjLsIF8pNipW3NHQZImqAAWn8qGoQcJutTzvQwPPQxarUARxN-uNAytsmCM-PisPpcKrbcWTsu0wBANvWKGahkUdR7CYJf6QpS54RpscMxu39n5SC-Vjb1-j_nL5yPQj7aoo-C7RpgGwUYRRcAzRYD2AS7I3R_ct--1-_5vn9M_wA) - PCRE2
PCRE1 and earlier versions of PCRE2 did not support quantifying a lookaround, automatically short-circuiting a loop count of \$2\$ or more to be \$1\$. So this version needs to wrap the lookaround in a dummy group in order to quantify it.
Not that it was necessary – but because this challenge and primo's answer talk about testing up to \$128^4\$, I decided to do a test run on this regex. I tested it on all integers from \$0\$ to \$130^4\$ inclusive (that's *all* integers in that range, not just \$n^4-1\$, \$n^4\$, and \$n^4+1\$) using [RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine), and there were no false positives or negatives. It took about 4 days of computing time, single-threaded.
# PCRE1 / PCRE2 v10.33 and earlier, ~~36~~ 34 bytes
```
^((?=(?|^((\2|x))|\2(\2\3))*$)){2}
```
[Try it online!](https://tio.run/##hVNrb9owFP3Or7hla7EhVAlI05aQVl3XaR9YOyEqbQIWseCAteBEjjP6gL8@dm1Dmz6kRUj4ce855557Hed5ex7H2zdcxGk5Y9DLY8mOFye1eDGVEOWjCYQwqH9crX7/6pY/bm@/DxfvVguy/UnIaUhO1/g/7qxvKF2PO7gadyltvqX0vrPZ0udZdQeaeRjlLS@oPTIWasYzTVk9klzMn57xDE/ZdPky7qTGhYIclypiUmaSxJkoFJgSmktWFNM5o/fI4/sxBkCvB7tTvTTnTMzSACRTpRTgBRsDuZxyQSjc1wC/fIRsKRMkp21vEroBlBjT7UQKMr3TCXNcmGCDadXhRV6qALSx0JQsgKo6lJMrabMlK8pU2bWuI0kKphzISoW0c7WwN9kfFqtMjroTS4WooQGP4myZ85SR3IFv54OL6NPV8Kzfh7XdXQ8/v3fgyBLaxZ7BpRaKJ0AOJKN7HxLjaUKwGox2oK6BjDQJU1Ri0uFw5sNhMRbY3Qqm5dkBJ5hAtPg77ZQxZ85UygUjtitcONYnGmCMt/fciMI04WKNU5VxYoKO4wi9JZQ6IDwH8qzAa3uTcDEjjXZjR6w/4WmDMOYgrPbF94U@PH0FF1omvgUoxEfyRyzbNE0n2MruRsJreZMAJ2qJhZPCgcZNQwvDUgq8nISV/AcjeCj0zPRC4QXQavFqxbarehb2nWU3LCaSOXB53e87gBwcu2Z@u3FwoFsped/MHcpJCC6s13tQ9MFMxMVgcDWILq@@ng3PvzwXsIe4o4DO6EpJYywatj/Bi1DbRhxV/aJ48CrUjr6HYo6O/iPmCV7dhws9dPWnuJvXHavYbSM2NTOyvh1FyRgqoQ@Pfffqaput2@58cF33b5yk03mxbafa@38 "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XVDBboMwDL33KyIUibiFFthpShGHjUmVpm6i0y6lixgLBYkGFNKtUttvZwbtsh6S2Hnv2c9uy7ZfRm3ZEqpJSKyFReak1XIvtGzrLJfMXsynkRBlVhuRN4e2qqVOWQo8TRad7RAbT4GfYi8HgjJSmY4J8bR6joUAh/iAJbEwnxQ/ujKSbd4e4yRxrNeHJA7ItwX8P4BFOpMpw@yBId7jZLN6Wdtwy7NShdpJ0WhGq9DjtA4LNNEN@GoNHM6kKhitt53RtVQYgevvwnDUIbk7fiKC347nuD4Menlq6@ZLMsu1HKRz1OfNEa1gsgxQtMUCeHs7PiFk7Kz@cqqW4YhjNJsBtiZsXOQhM3nJqHaw2bBVmeFkJ9uhCgDIebBYgczLZvDFCY7iczLkhCp@xTbXm@0z4P0HY1HIogu@aXA5AVzSAKP0DmBKAc7Bte89N7j3PO8X "PHP – Try It Online") - PCRE2 v10.33
PCRE1 automatically forces capture groups with nested backreference(s) to be atomic, thus allowing us to save 1 byte by omitting the possessive quantifier. Early versions of PCRE2, like the one still on TIO, had the same behavior.
# .NET, ~~38~~ 36 bytes
```
^(?=(?>^((?<2>\2|x))|\2(\2\1))*$){2}
```
[Try it online!](https://tio.run/##RY/RaoMwGIVfReQHk9qUmKtRl1ro9Z5ALYj7WwNZIjFFqc2zO90Yu/wOh49zejuiGzrUegEnS4d3nOrj0eBIzslyJYUkxelKSPEuTpV4TZS@KkEqUWWU7oDOIizJeR9f7FevNH7GNIen5PnNOmzajoCOlIlAmf7h6QyNBM2GXisfszhXNwLNobUP45n2kdgKqYSm5HVYBQSMLJXx9U@Sg2Ea/zjbOE3pvDnc4aPxbYcDSaZkB4b@xk86j055ZJ0dfFhnZfk/R8zY9aRWBiMwIYSFM8HfOP8G "PowerShell – Try It Online")
This is the Perl / PCRE version backported to .NET, using its feature of recapturing numbered groups by using the number as a name, seen as `(?<2>`...`)` above.
# Perl / Java / PCRE2 v10.34 or later, ~~41~~ ~~39~~ 37 bytes
```
^(?=(^(\3?x)|(?=(\3?x))\1\2\2)*+$){2}
```
[Try it online!](https://tio.run/##RU5BasMwEPzKEkSsrW0suzSHyIodSK899VYnIg0xCNTElVxwUdWvu7IbyGWZmZ3dme5s9NP48Q3EcHD6ejpqIBkPVJS77et246G9GkqsYLzccHSg2sDQdUZdelg0lwX3UGthO616GqVRYr/ebR9OZJLmSY7nz8lU3VUWdFwTiXz6ZUPi0dS6LNDV@i3fizDZnt9y1Y0SVYp5HVAco1MtUBoNEQwQTIggfiEjJkNH7HI5l5u7heI5/@9KFPfeS/n8spNyPNBK0ANtHqsBfyY8I2zypmgKfIgJusKPI0tXK8bYHw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVLbjtowEH3nK6ZRK2wu3kBfqnoj1FatVGm3rZZHYCWTOGDWcVLbWbJL@XY6DullJfIynpmTMz7HsxOPYrzLHk6qqErrYYc5UyUbcPi/UnulL9as3MgGO72qXmuVQqqFc3ArlIEDdDXnhcfwWKoMCuyQubfKbEDYjVusKPitLfcOPjeprLwq8c8ewBelJeSJkfv2SCKWlplk2I8o/1jnubQyu5MikxbWLexlkfz5s0tzSnk31408328DPyEuWaMGkd0oIwmlrxJTa01VThyTP2uhHYmuBoNBROnhJfTMQIi/SHBABv@XAQmukGGNuAfuhkl/afohen48144/hPfSGrBJd0K1RRUGOMrRjXVZaikMPCc5MkoO81QYg9KVqWoPCQS1XY3Mn5yXBVOGcuh0tjC2Fe6bbDxes7UYoDNE492R4wwyiOgkdv3FCjS2A4q5SitPojE@AuI9mBg7X43HNbCsEtZJTIhexCs6AjO52GRamo3fXk9hBgEJ7zFMVsiYboVdrJpOT5uZyYrDB2vFk2O50po0o37Tb00ByEsbtOE1EhNzMNeJmWAYDlHgrfDpFh0qkM2y4pyRdnMNLvgnJD9vDNtbUZFuRFpWT9/zO2E2EifFI0NpUJoDKXC8ydC78LbPtDO5RMf2VnlJwqNS/px4W4f3@deu0EOfk@iNi9ASyo/h64WtOt2TWULuyfLtrKG/wrk90eVkOV1O6WD4mh6mx1NYn1M8nsbv4vg3 "Java (JDK) – Try It Online") - Java
[Try it on regex101](https://regex101.com/r/v9Bzlc/2) / [Attempt This Online!](https://ato.pxeger.com/run?1=XVDBTsJAEI1XvmKzWdMdaKGtopCl4aImJMaDerOwKXULjWXbbJeEBPkD_8ALiTF-k36NU-TkYWffzL43b3beP6pltf85eRuNERBmSERoj5IuqYxaSKOqIkkVd3rd9ljKZVJYmZarKi-UiXkMIr7v1Y5LHDwZFuVCNQRtlbY1l_JmcnstJbgkAGyJjUUr17msleW0So3qzpP0xRoMsshXuaUuoefh8Hx4cRkO-xREKysNZ3nkC1ZEGXav-cPj1eQOBGxJnnFWPNXWFEojAi-YRhGNNQUk1-s5vmDZ9V0vgEavNlVRPitOPeoiXaA-LdfaNtpRiKInbIDRn4oWIQdnfcyZHkWHd0SdDqA14YcNrRKbLjkzLpo161KJ5c7GcZkGALJtRsxBpcuymUsQ_EogSJMTpsUObXb_1spBfK5t5g2-T2d8HPEZj8_GG3ht8AFBHMRhHEK7w2Ab7v7I--P15XuDs34Y_KW_) - PCRE2
Unfortunately, without the branch reset group, it cannot be generalized by changing the `{2}` to anything higher, because the value of `\3` is not reset from iteration to iteration. The only way I can think of to generalize in that way makes it much longer, at **~~55~~ 53 bytes**:
```
^(?=(^(\4?x)(?=(x*))|(?=(((?!\3)\4)?x))\1\2\2)*+$){2}
```
[Try it online!](https://tio.run/##bVJdb9swDHzvr2CNDZGSVHWyPgxTjWAbNmDAug3NY5wCii0nSmXZk@TGbZbfnlGO91GgfqFIno@6E7fiQVxs8/ujKuvKethizlTFhhz@rzRe6RdrVq5li52zullplUGmhXNwI5SBPfQ154XH8FCpHErskLm3yqxB2LVbLCn4ja12Dj61may9qvDPM4DPSksoEiN33ZFELKtyybAfUf6hKQppZX4rRS4trDrY8yL582efFpTyfq4be77bBH5CXLJCDSL/qowklJ4nptGaqoI4Jn82QjsSXQ6Hw4jS/XPoiYEQ/yLBHhn8XwYkuESGFeLuuRslg9QMQvT8cKodfgjvpTVgk/6Eass6DHCUoxurqtJSGHhKCmSUHOaZMAalK1M3HhIIavsamT86L0umDOXQ6@xgbCPcN9l6vGZnMUBviMa7I8cJZBDRS@z7iyVobAcUc7VWnkQX@AiI92Bi7HwxHtfAslpYJzEhehEv6RjM5MUm09Ks/eZ6CjMISHiHYbJExmwj7GLZ9nq6zEyWHN5bKx4dK5TWpB0P2kFnCkBR2aANr5GYmIO5TswEw2iEAm@EzzboUIlslpWnjHSba3DBPyL5aWPYzoqa9COyqn78XtwKs5Y4KR4bSoPSAkiJ402O3oW3faK9yRU6trPKSxIelfKnxNsmvM@/do0e@oJEr12EllB@CN9Z2KrjHZkl5I6kV7OWhmM7pPRXOBAyO0/f0PSKYoemk3SaTulw9Irup4djWKdjfDGN38bxbw "Java (JDK) – Try It Online") - Java
# Perl / Java / PCRE2 v10.34 or later / .NET, 40 bytes
```
^(?=((?>^(\3?x)|(?=(\3?x))\1\2\2))*$){2}
```
[Try it online!](https://tio.run/##RU5BasMwEPzKEkSsbWwsuzSHyLIdSK899VYnIg0xCNTElVxwUdWvu7IbyGWZmZ3dme5s9NP48Q3EcHD6ejpqICkPVBS77eu29NBeDSVWMF6UHB2oNjB0nVGXHhbNZcE91FrYTqueRkkU269324cTGSdZnOH5czJVd5UFHTdEIp9@2ZB4NLUucnS1fsv2Iky257dcdaNEFWJeB7RaoVMtUBoNEQwQTIggfiElJkVH7HI5l5u7heIZ/@9KFPfeS/n8spNyPNBKUFqVB9o8VgP@THRG2GRN3uSIDwRd7seRJes1Y@wP "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVLbjtMwEH3frxgiUO1evGl5QXhDBQgkJBbQ9rHtSm7itO46TrCdbdrSby/jNFxW2ryMZ@bkjM/xbMWjGG2zh7MqqtJ62GLOVMn6HP6v1F7pZ2tWrmWDnauqXmmVQqqFc3ArlIEjdDXnhcfwWKoMCuyQmbfKrEHYtZsvKfiNLXcOPjWprLwq8c8rgM9KS8gTI3ftkUQsLTPJsB9R/qHOc2lldidFJi2sWtjTIvnzZ5fmlPJurht6vtsEfkJcskINIvuqjCSUvkhMrTVVOXFM/qyFdiS67vf7EaXHp9ALAyH@WYIjMvi/DEhwjQwrxD1wN0h6C9ML0fPTpXb6IbyX1oBNuhOqLaowwFGObqzKUkth4JDkyCg5zFJhDEpXpqo9JBDUdjUy2zsvC6YM5dDpbGFsI9w32Xi8ZmsxQGeIxrsjxwVkENFJ7PrzJWhsBxRzlVaeRCN8BMR7MDF2vhiPa2BZJayTmBA9j5d0CGb8bJNpadZ@czOBKQQkvMUwXiJjuhF2vmw6PW1mxksO760Ve8dypTVphr2m15oCkJc2aMNrJCbmYG4SM8YwGKDAW@HTDTpUIJtlxSUj7eYaXPCPSH7ZGLazoiLdiLSs9t/zO2HWEifFQ0NpUJoDKXC8ydC78LYH2plcomM7q7wk4VEpPyTe1uF9/rUr9NDnJHrlIrSE8lP4rsJWne/JNCFk@u6eLF5PG/orpO2JLsaLyWJCaf8lPU5O57BB53g0id/E8W8 "Java (JDK) – Try It Online") - Java
To make the regex *fully* general to all four of these engines (ignoring PCRE1, because it's an outdated version of the same engine), we must not use balanced groups, recaptured groups, branch reset groups, or possessive quantifiers.
It is possible shorten the regex, while still supporting this exact set of regex engines, by dropping the pretense of a 2-iteration loop and [doing the two stages separately](https://codegolf.stackexchange.com/a/223048/17216).
[Answer]
# ECMAScript, 41 bytes
```
^((?=(x(x*)|)(?=(\2*)\3+$)(\2*$\4))\5){2}
```
[Try it online!](https://tio.run/##TY@9bsIwFIVfJY0QuTdpQkhLB1zD1IGFoR0JlSwwiVvHsWwDKT9rH6CP2BdJkwGp25G@I53zfbADsxsjtIutFltuqlp98q/WUMWP3isvXhoNcKKzUdi@A8wpNNCEeME@5lmI@UM0wD4N8kfEfILn7NqGoxMmrn5zRqgCMLFSbDg83cddhViakmMpJAeQ1HC2lUJxQLyjai8lngsqE6ulcBDEARKxA1C0SCRXhStxll0uwi7ZEgTVzFi@UA6KVbpGvAH@H6jZeD6e9hhdaeqjv1AHJsXWM0wVfOr5kSS72gARz5QTEUXYDVbUb/zEcM2ZA4FJxdymBIN4tsOh7qQc9B5jovfOOgMiCrzf7x8viKpVtr5dJddrm8bZJE3/AA "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript (SpiderMonkey)
[Try it online!](https://tio.run/##TY5LbsIwEECvghCSZwixkrRscA2rLtiwaJeECisxYargpLb5SIFtD9Aj9iJpUgmJ3ZPefN6nOimXWap9aKpct05Gwso3Xbxeanj3lkzBrTpv2w@AhYQLXMZ4xR7TZIzpUzDCnkbpM2I6xSa5tVvuSso0xJMwRhRWfx3JamBWq7wkoxnyrGOvl8Zru1PdaEOmPvpZbatMO8edz8nckFcG2P/GpJTzppAld3VJHljIUNAOwMiCl9oUfo/z5Holt1IrIFkr6/rrUKyjDeJd6Edh5vEinvUa/d5W5@HSnFRJ@cAqU@jZYBiUYldZEPQitaAgwO7hQQ4vQ2513eUDIT8on@3BIjYP6dXR87MlrwHcgqWGzRjDgAI2@P3@GbDgsE4292rhZCxuN2yjMJlG0R8 "JavaScript (Node.js) – Try It Online") - ECMAScript (Node.js - faster)
[Try it online!](https://tio.run/##RY/BaoNAEIZfZZEBd2JWjGkvkaUpocecelQLYje6sNmVdUWJ9doH6CP2Ray2lNz@b/7hY6YxvbBtLZSawfLUikoM@eGgRU@P/vxG6ROnAx02@IFrzOINZvsAcE2QPSBmjzjG0@wft97JXBupxPv25XR@fi2tbJyHCdx4lFyMFUVZU1BEagJSN53DEQoOirWNks5jXiIvFIqwNJ12TDkSrwsBhyKN8mkRUNA8ldrlv5MENFPin3crBwGOq@PKwYbnwpW1aKk/@BvQ@NfccOytdILVpnXTctkuuTNh2ix/K6kF8UCT788vAostrKzpmjaN81AJXbkavWma5ojt9lH0Aw "PowerShell – Try It Online") - .NET, in ECMAScript emulation mode
This uses a "higher technology" than my older [50 byte ECMAScript answer](https://codegolf.stackexchange.com/a/21951/17216) (which was my very first post on this site), and unlike its algorithm (which works individually on prime factors), does actual division (or multiplication, depending on how you look at it) in a way that works thanks to the Chinese remainder theorem, as [explained in this post](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420). The upshot of this is that it returns the \$n\$th root in a capture group when asserting a number is an \$n\$th power, whereas the prime-factoring algorithm is completely unaware of what the root was.
This regex takes the square root twice in a row, asserting each time that the input was a perfect square. The same square-testing regex is used [in the second answer in this post](https://codegolf.stackexchange.com/questions/144561/golf-the-pseudoprimes/179024#179024). It could be modified to take \$8\$th powers, \$16\$th powers, etc., by changing the `2` in `{2}` to \$log\_2 n\$ to match \$n\$th powers.
```
^ # tail = N = input number
(
(?=
(x(x*)|) # \2 = potential square root; \3 = \2-1, or unset if \2==0, in
# order to match N=0 using ECMAScript NPCG behavior;
# tail = N-\2
(?=
(\2*)\3+$ # if \2*\2 == \2+tail, the first match here must result in \4==0
)
(\2*$\4) # assert \2 divides tail, and \4==0; \5 = tool to make tail = \2
)
\5 # tail = \2
){2} # Loop the above exactly 2 times
```
# ECMAScript / Python or better, 43 bytes
```
^((?=(x(x*))(?=(\2*)\3+$)(\2*$\4))\5){2}|^$
```
This version is NPCG-independent, allowing it to work on a wide variety of regex engines:
[Try it online!](https://tio.run/##TY9NTsMwEIWvEqKqmUlImgbKosHtikU3XcCyKZLVuo7BcSzbbUN/thyAI3KRkEggsXl60jfSvO@NHqjdGKFdbLXYMlPV6p19tIYodvSeGX9qNMCJzEZh@wowJ9BAEyL2rchCLO6iAfZtUNwjFhM8Z9fL66ANRydMXP3ijFAcMLFSbBg83MbdVW5Jmh9LIRmAJIbRrRSKAeINUXsp8cyJTKyWwkEQB5iLHYAiPJFMcVfiLLtchF3SJQiiqbFsoRzwVbpG/APsP1Cz8Xw87TG60tRHf6EOVIqtZ6jibOr5kcx3tYFcPBKWiyjC7mFF/MZPDNOMOhCYVNRtSjCIZzsc6k7KQe8xzvXeWWdARIH3/fnlBRFUq2w97@N38DTtlK/XNo2zSZr@AA "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript (SpiderMonkey)
[Try it online!](https://tio.run/##TZDPboJAEIdfhRiTnSm6AVov0NVTD148tEfRuMEVp8GF7q5Kglz7AH3EvgiFpk28TL7kmz@/zLu8SJsZqtxUl3vVWREkRryq/KWu4M0Z0jk38rrrtgALATXUD4gDpdEDpo/@GAcap0@I6QybqL1tx92O24IyBeFkGiImRn2cyShgRsl9QVox5FnPTi21U@Yg@9aGdHV2cWXKTFnLrduTbpGXGtjvxKQQ8yYXBbdVQQ7YlGFCBwAtcl4onbsjzqPbjexKroBEJY0dtkO@DjaI/0LdCz0PF2E8aHRHU15HS32RBe09I3WuYm/kF8mhNJDQs1AJ@T72B09iVI@4UVUfHwj5SbrsCAaxuYtenh2/GnIKwC5YqlnMGPrkM@/788tjPpzW0WYxlL/scdC/yYowaVvsgmk0C4If "JavaScript (Node.js) – Try It Online") - ECMAScript (Node.js - faster)
[Try it online!](https://tio.run/##RU7BToNAFLz3KzbNS3dfgXah9tJlC03q1ZM3aUk1VDdZKQImmHU9@gF@oj@CC5p4eZmZzLyZqqj1un9@I1ALYvTl4aQJLIWjMt7vbndbOzlfagaN5CLeCjREnR1DU9WqbMk0K6fCklTLptKqZTSgfvN637QukvtB6IdYvAym5F/lTscN5CiGX41rPNWpjiM0qb4LD9JdfhB2QsjYrP4EULEcDQ55HhqXZbSjHSiUH0uol2igmc3GXeMstzkUvzNBLSj5/vwidMEgSnRRPrZPEG04Cmttnl/f7PO8PzKWSNaxbo44oCyaY7byAAcE2RVitkYT2fcj9D0PwhXnPw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVLRbtMwFH3fV1yiTrXbzks7eCGLJkAgTWKAtse2k9zEad05TrCdNVvpKx/AJ/Ij5To1jEnLy/W99@Rcn@O75vf8ZJ3f7WVZV8bBGnMmKzZI4P9K46R6sWbEUrTYOaqbhZIZZIpbC1dcathCqFnHHYb7SuZQYofcOCP1ErhZ2umcgluZamPhY5uJ2skK/zwC@CSVgCLVYtMdScSyKhcM@xFN3jdFIYzIrwXPhYFFB3teJH//DGlBaRLm2pFLNivPT4hNF6iB55@lFoTSV6lulKKyIJaJ7w1XlkSng8EgonT7HHpgIMS9SLBFBvePAQlOkWGBuLvEDtP@TPd9dMnuUNt9484Jo8Gk4YRqy9oPsDRBNxZVpQTX8JgWyCgSuMm41ihd6rpxkIJXG2rk5sE6UTKpaQJBZwdjK26/iNbhNTuLAYIhCu@OHAeQRkSQGPrTOShsexSztZKORCf4CIh3oGPsXGqHa2BYzY0VmBA1jed0BHr8YpMpoZdudT6BC/BIeIthPEfGbMXNdN4GPV2mx/ME3hnDHywrpFKkHfXbfmcKQFEZrw2vkeo4AX2e6jGG4RAFXnGXrdChEtkMKw8Z6TZX44J/QPLDxrCN4TUJI7KqfvhaXHO9FDgpHmlKvdICSInjdY7e@bd9pMHkCh3bGOkE8Y9Kk8fUmca/z1O7Rg9dQaLjHH7//AXHeYTOjKBkS1M1NZmEnUEznkrBIkLRm5gmO/8d@UXc3xJykZKWtANK/Wk2GdDZ2bBH/ak3e03p7A3dTnY/bnt7v3f7@GR8Fsd/AA "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##bVLBctowEL3zFVvKFAnbBEPbg42TmX5Cp4d2gHgcIWxNjayx5IGEcO0H9BPzIaUrGQik1WFntdp9@/atmFJBztjhvZCsbJYcpg9Vpc1NzXO@HRZK3XZYkdWQqtkCEvja/bLZ/HyYND8eH79/Kz5vCnK4J@QuIVuyHVBqvfl4QOcTr0et15t/pHT@ie7G@@f73oG@Le/6MFBJqrww7rxyEEih5tn6tiOkAVWjTXldVzVhldQGHKXBmmud5ZzutFlGEcMEmE7hGLWui3O5LGOouWlqCWG8d5DrTEhCYdcBPGqG3UouiaJBuEhGMTSYMxmnBip7swW5dRwe5gqZY1A1Jnb1LSenWxQ54bAdUf5VKIoEyzSn8Smq15lhBWyK7AizqmogttfTuVfOTSkkJ@2AQvptWxqfqNtjS@QIl5OZShCXMGQp0iSU@iBDH1Sl8bl9WQm5JP2gT@MzgAzx1ea8Sy5HjCJpg3f/wQXP5XsQUoiw@StWuxnbTvJNe5vJ0AsXMS5mrbkh2of@tm@JoRYaH63i5/qzCCKRVvppIsMYPE9cTuymXgG51DfVPKtZQcjFBPSDxQ/Ewncy@7gW@hbnhPVEAQe0hEl/LlEeXEMY/5PabqJqjP1fwpouvPz6jRZd22Q2XgzxL@WmIPS6fN@59lp7/Jgowf4wCsLJaPSHrcos14egdPOlbry/ "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##TY5BTsMwEEX3OcXIqlRPkkZxApsEi4MkqVSB2xo5TjR2RStgywE4IhcJnSIkdn/mz3/z50s8Tr5e7DhPFCFcQk4mfwmTb4E0CSGWrZSPWp7lOUVk1Vcp9nW2Qlar/g6xv8e36uN9u1qu951qNmpoweoy2U8EDqxnbhHis/VNAk67IszORik2AhOwe3DGS4cPVQOuU4N2XTkkwGHPYdr5g5HWR8kG5r9KDZgpvPJg1GSKYHb0dJSUgziL1F@5DB7ZZ2EbmImD2N42WrV/paZTLF7JRiNDJOkxW8P35xesMx652VgcaDrNQSI/vWH/b8C4YKBEXMqNqsvyBw "Python 3 – Try It Online") - Python
[Try it online!](https://tio.run/##TY5NTsMwEIX3OcXIilRP/hQ3sEmwOEiSShW4qZHjRLYrUgFbDsARuUjIFCGxezPz3jdvvobzZKtVj/PkAvirz5wa1JK9@Mk24KRjjK0Hzh8lX/iSIJLq9gl2VRojqbi7Q@zu8W3/8X6I183fijoXfQNaltFpcmBAW0IXPjxrW0dgpCn8bHTgLGcYgT6BUZYbfNjXYFrRS9OWfQQUthR2Rzsorm3gdMDsV4keU4EbD0Z5a114dXRPZ@4yYAtL7IYm9kgWErqG2VEWm9tGiuav13QJxavTQXEfHLeY7uD78wt2KY1UbiwGN11mz5H@3rD/N6CMV1AirmUuqrL8AQ "Python 3 – Try It Online") - Python (with `[regex](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)`)
[Try it online!](https://tio.run/##PY5NasMwEIX3OcWrMVjjxkJ22k2NCIF020XpLnZESxRHIBSjOMSlP8seoEfsRVxb0G6GNx@8b8afX14HD4lH3ei@5U5fsF49rbjXz7sSRooSl4OxGlY2ujuNaA@7yfJayqhyUTlyuxGcZ0VdQrtdAPzUWtOxJEtoBuyPHg7GjT1R8@6oDMsFcR40/3sws6iPUkeQn/ABmKvpg/Y8XQ52I/Nx98Z1cPMEP1/fSOYsLrBEXHCrXdMdGOEOkzE0/sZMqfuHtVLDlrGlZD3rU6IpVUVK1eI6pinF1Q1RdUtvxcf7Nh4GkeULIX4B "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##XVHNjtMwEL73KSzLUmZaN01DCypu1AsgrYQ4LNyarpUN7iYicSzHKxV1e@UBeMR9kTKu4MLBo29@vm9@7Bp33e5c45jwrGB8wVnKnDdP2hvXVbWBZJFOd1o3VRd0PfSu7YwvoURV3i/GRLKE3pGC@snEAhuMDSNo/enu80etUbIlkiQJq0lrWz2aANzV3qSPVf0jeDK6a/s2cMn4Kt@sNm/f5Zs1RzU5Dh5EW2RKdMWR1Ef4@u3D3RdUeGbtEUS3H4PvjCWE8@WhKHhpOVLx@PxIGQrLTM6XGPnm5LrhuwE@55LKFfHr4dmGyN3mRNqTANnsoCaM3Trbv76w2@KWJzSbIbVmcLtQX4W6AeElNYvnMlWA5JRIYVGKHpGd45QtmroZ4miK0TZLxaLPhE05e/31m/EUTO/CTxD9Pj/gLnv/b6ubj@pCA13@@wBAdX0A2BVwgtMUMaIyn2L5ZiYwIlGuEMs1nvPLy4O4XrN5vs6yPw "PHP – Try It Online") - PCRE (fastest)
[Try it online!](https://tio.run/##RY9RaoQwEIavEsKAmbURdduXldCFPvcE6oLYrAayicSIstbXHqBH7EWstpS@/d/8w8dMZ0fp@lZqvYITuZONnMrTyciRnYP1wtizYBObDoh7KtIDFscQcE9QPCIWTziny/sF1uD8QF/srVNavlHM4C7i7GqdrOqWgSbKEFCmGzzOUAnQvO@08pTTTF0ZVFFtB@O59iTdF0IBVR6XyyZgYESujC9/JhkYruUfJzuHIc674ybARa@Vr1vZs2AKDmDwt7njPDrlJW9t75ftsiT7Z8KN3d7VykhCwZCvj08Cmy1qnB26Pk/LSEvT@BbpsixrzJNjHH8D "PowerShell – Try It Online") - .NET
```
^ # tail = N = input number
(
(?=
(x(x*)) # \2 = potential square root, which must be positive; \3 = \2-1;
# tail = N-\2
(?=
(\2*)\3+$ # if \2*\2 == \2+tail, the first match here must result in \4==0
)
(\2*$\4) # assert \2 divides tail, and \4==0; \5 = tool to make tail = \2
)
\5 # tail = \2
){2} # Loop the above exactly 2 times
|^$ # Allow us to match N=0, which can't be matched above
```
[Answer]
# Perl / Java / PCRE / .NET, 35 bytes
```
((\2x|^x)+)\1(\3xx|x(?=\2$))+$|^x?$
```
This beats [primo's solution](https://codegolf.stackexchange.com/a/22084/17216) by 4 bytes while supporting the exact same set of regex engines.
[Try it online!](https://tio.run/##RU5Na8MwDP0roojGIglxsu0yx00K3XWn3ZbOdKMBg9dmdgYebvbXM7cr9CL0PqT3hr01D/PnD6AVEMzxY2cACxGhrDfrl/Vqgv5oGTrJRb0SFED3EVEYrD6MsOgOCzFBa6QbjB5ZkieZ@353YzxRWV5mJe2/zqbmxvLI0yMqEudfLibubGvqikJrXsutjJNvxTVXXyHqWl7kuKUpBd0DY4lPwEM0EYH8hQJtQQHdcnkpd@kWi5fivytqMU2TUk/PG6VmxrrKn948pdSVrLvz/uRZI7sKiVKMQoPzzPP7ivM/ "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVLbbtswDH3vV3BGh0hJqjoZ9jLVKLZhAwas29A@Jhmg2HKiVqY9SW7c27dnlONdCtQvNMmjQ50jXqtbdXJd3OxN1dQuwDXlwtRiLOH/ShuMfbHm9EZ31Dlq2rU1OeRWeQ8XyiA8wFDzQQUKt7UpoKIOuwrO4AaU2/jFikPYunrn4VOX6yaYmk4eAXw2VkOZod71vywReV1oQf2Eyw9tWWqni0utCu1g3cOeF9mfk0Naci6HuX4a5G4b@Rnz2Zo0qOKrQc04f5Vhay03JfNC/2qV9Sw5HY/HCecPz6EHBsbCiwQPxBD@MhDBKTGsCXcj/SQbLXEUY5BPh9rTDxWCdgguG/5IbdXEAZ5LcmNd11YrhPusJEYt4SpXiCTdYNMGyCCqHWrs6s4HXQmDXMKgs4eJrfLfdBfomr3FAIMhlu5OHAcQEmKQOPQXK7DUjijhG2sCS07oEQgfAFPqfMFAa@BEo5zXlDC7SFd8Cjh7sSmsxk3Yns3hHCIS3lGYrYgx3yq3WHWDnj7D2UrCe@fUnRelsZZ101E36k0BKGsXtdE1Mkwl4FmGMwqTCQm8UCHfkkMVsTlRHTLWby7Sgn8k8sPGiJ1TDRtG5HVz9728VLjRNCmdIudRaQmsovFYkHfxbe/5YHJNju2cCZrFR@XyPguuje/zr92Qh6FkyWufkCVcPsXvKG7VnrHlvHv82fEJX87Y8k3XPXbsPFvOjzmfHFPj/Hgfl2efnszfpulv "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##nVJNi9swEL37VwxCYM3Gjj82bcnKbi7tQqD00O1tvRWOo6xFHdnIChiy@e3pOLSXHleHQfPx3hvNaFeP7XX7@FSC0/UeYreHMARXFKF61wmDYjO0A3AHJbCEwRIGp1@V00NXN1qEyfJuo1Rbd141/XEwnXaVqFBWP5IxjEg8ggMF1aueC6zX1o9Cqcftt69KYQQZEiURy8BYo0btBRsap5e7uvntHRnVmaPxLAK2yter9cdP@foDQxkceie4KVPJu/JA7KN4@vll@x0lnsEcBO@eR@86bemGcfZSlqyyDKl4PO0oQ@EojeIMZ7yehq7fa8FiFlG5JHzTn6yfsUVOoGciIJu@yADgpmz/@twW5S1Pt8UCSRrEbULH2jet4C4isXlcuvYinMKIW0SE89yiQd20/dyXBHpKJmH2gVt5IZnLf2MVKK9CVPn09mvCBVaZqO6n6W0Sm7LKOeKCU2LDr@9bdHCTji0wfnYPD3F2YZ8bmsmSti/1pBtITqNLdsYm83/4l7qm8SpP0z8 "Bash – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XVDBasMwDL33K4wxxFqSNsm6jeKGXLZBYeyw7dZ0Js2cJix1jONCoN23Z0rZaQcLSU/vPVmmNuM6M7UhzJKU0AUlc2KsOkirTFuUinuL@U0mZV20Tpbd0TStsjnPQeRvi94LiIevwqY8qGlAO6Vdz6V83rw8SQkBiQElUVjMGt3IXjlOTWnVfF@U385ikG1zbBwNCF0mq@Xq/iFZ3VEQs6qznDVpJFibVqje8/ePx80rCDiTpuKs3fbOtkpjBmG8S1Oaawo43J/2iGA7iIIwhomvBtN2X4rTkAY4LpBfdiftJu46QdIWBTBGOzEj5Oqs/2qm1@kVx8z3Aa0Jv17oWLiy5swGaDadSxWOe4MXMA0A5Dyt2IAq627aSxD8SizIVBOmxQ/a/Pw7Kwcxcp4nw@VzAB/ymOe3w3AZeJbmCQPwGQIZG8coXCZR9As "PHP – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=XVHNTtwwEFav-xSWsRRP19lNUgqsvNEe2q20UgVVQFwIWCE4rNWsEzleGgl4kl6QUNW36b19mk4WLu3B4_n55vtm7O_P7bp9-vPm13yBDmGOpIROKZmQ1ulb5XRbF6XmwXTydqHUuqi9KptNa2rtcp6DzLNpFwgS4KkwqW71ALBeW99xpT6tPi-VAkFiQEoklqPqmzNe89Ozj8ssE_TLh2yZkDsK8t8CknS-sJ4HA0KdL7PT1clxACBHxhrVac9pWzo9uS7Kr96hUbXZGE8FofvJbH92cJjM3iPtqGocZyaNJKvTCufrBonVMUi4J6birL7ovKu1RQ_C-DJNaW4pILjbXmMF0yISYQxDv-7burnRnIZUIFxif9lscUoM5gk2XSAB2uhSjgjZKdvXmNl5uqujNx4DShO-e-NN4cs1Z06g2PDgusCl-0AwCwDkfhjRgC7XzTCXJLhKLMkQE2blI8o8_vcxHOSPra_Co997nOdJ_3DVwxjymOfv-v6h54s0TxjAmGFhwV6gT6_XzyiM4yiKXsK_ "PHP - Attempt This Online") - PCRE2
[Try it online!](https://tio.run/##RY/RaoQwFER/JcgFk9os0dKXlbALfe4XqAWxd9dAeiMxi2Fdv91qS@njmRmGmcFN6McerV3B68rjFWNzPBJO/JyunNdFfHxEkYk65/VLjI/IT7ouQIgMNuMEa3p@Tt7c12AsfiaihLtW5cV5bLueg2WGGBgabkHM0GqwchysCYlMSnPh0B46d6MgbWDFHsg0tJVqlq2AA@nKUGh@lBJIWvzjfOcsE/Pe4Q/vbeh6HHka0ycg8SvfxTx5E1D2bgzLNisv/5lJcttHawgZ0LIsq5LFq1Lf "PowerShell – Try It Online") - .NET
It works by first finding two consecutive triangular numbers whose sum is \$n\$ (using the equivalent of `(\1x|^x)+` to find the smaller one), so that \$\sqrt n\$ will be the triangular root of the larger triangular number. Then it tries to match that root as itself being a perfect square, using the equivalent of `(\1xx|^x)+$`.
If it did not need to match \$0^4\$, the regex would be **34 bytes**, and if it didn't need to match \$1^4\$ either, it would be 30 bytes.
```
# tail = N = input number
( # \1 = a triangular number T_0; tail -= \1;
# \2 = triangular root of \1
(
\2x # On iterations after the first, \2 = \2 + 1
|
^x # On the first iteration, \2 = 1
)+ # Iterate the above any nonzero number of times
)
# T_1, the next consecutive triangular number after \1, is \1 + \2 + 1.
# N is a perfect square iff tail == T_1.
\1 # tail -= \1
(
\3xx # On iterations after the first, \3 = \3 + 2
|
x # On iterations after the first, \3 = 1
(?=\2$) # Assert that this is the first iteration, while
# simultaneously asserting that N is a perfect square,
# because if tail == \2 here, it will have equalled \2+1
# before this loop began.
)+ # Iterate the above any nonzero number of times
$ # Assert tail == 0
|
^x?$ # Allow us to match N=0 or N=1, which can't be matched above
```
Alternative 35 bytes:
```
((\2x|^x\B|^)+)\1(\3xx|x?(?=\2$))+$
```
This avoids the special cases for \$n\in [0,1]\$ at the end, while working around PCRE1's atomic behavior, by hinting that the group 2 loop should only capture \$1\$ `x` in its initial iteration if there are more `x`s following it. This way we can get the same behavior as the 32 byte version below, where both `\1` and `\2` capture an empty string when \$n\in [0,1]\$ – but unlike that version, this happens for \$n=1\$ without any backtracking.
# Perl / Java / PCRE2 v10.34 or later / .NET, 32 bytes
```
((\2x|^x?)+)\1(\3xx|x?(?=\2$))+$
```
This drops 3 bytes at the cost of sacrificing support for PCRE1 and older versions of PCRE2, because they automatically force capture groups with nested backreference(s) to be atomic – which would prevent `x?` from ever matching \$0\$ instead of \$1\$, blocking \$1^4\$ from being matched.
If it did not need to match \$0^4\$, the regex would be **31 bytes**.
[Try it online!](https://tio.run/##RY7NasMwEIRfZQki1mIbS257iazYgfTaU291KtIQg0BNXMkFFcV9dVdxA7ksO7M/8/VHa56mzx8gVkAw58PeAClElLLabl436xG6s6XESSaqtcAAuosKQ2/1aYBFe1qIERojXW/0QJM8ydz3hxviicpynnE8fl2X6rvLoo8rolBcf7mYuLeNqUoMjXnjOxkr24lbrr5Jois5j2OXphh0B5QmPgEPcQkR5C8UxBYYiFsuZ7iZLYJz8c9KtBjHUannl61SE6Vt6S/vvsYUW07bB@8vvqa1bEuCmJJpYvljydgf "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVLvb9owEP3OX3GLOmEDdQPTvsyN0DZt0qR1m8pHYJJJHOLWcTLbKYG2fzs7h@xHJfLlcnfP7/ye7048iMu77P6oyrqyHu4wZ6piIw7/Vxqv9NmalVvZYmdQNxutUki1cA5uhDLwCH3NeeExPFQqgxI7ZOGtMlsQduuWawq@sNXOwac2lbVXFZ4cAHxWWkKeGLnrfknE0iqTDPsR5R@aPJdWZrdSZNLCpoO9LJI/J/s0p5T3c93E810R@AlxyQY1iOyrMpJQ@ioxjdZU5cQx@asR2pHoajQaRZQ@voSeGAjxZwkekcH/ZUCCK2TYIO6eu3EyXJlhiJ4/n2rPP4T30hqwSf@Hass6DHCUoxubqtJSGDgkOTJKDotUGIPSlakbDwkEtX2NLPbOy5IpQzn0OjsYK4T7JluP1@wsBugN0Xh35DiBDCJ6iX1/uQaN7YBirtbKk@gSHwHxHkyMnS/G4xpYVgvrJCZEL@M1nYCZnm0yLc3WF9czmENAwjsM0zUypoWwy3Xb6@kyM11zeG@t2DuWK61JOxm2w84UgLyyQRteIzExB3OdmCmG8RgF3gifFuhQiWyWlaeMdJtrcME/IvlpY9jOipr0I9Kq3n/Pb4XZSpwUTwylQWkOpMTxJkPvwtseaG9yhY7trPKShEel/JB424T3@deu0UOfk@i1i9ASyp/DNwhbdSRkNWuffrZzOqarKVm9adundk7myWp2Qen44hg25xhfzt7G8W8 "Java (JDK) – Try It Online") - Java
[Attempt This Online!](https://ato.pxeger.com/run?1=XVHNbtQwEBbXfYqRZSke1tlNQvlZeaMcYJFWQgWliEtTrDQ43YisEzleiNT2SbhUQoi34Q5Pw2TbCxw8np9vvm_G_va93_V3fx79WmfkAHeQAlsyWEDvzJV2pm_LyohguXicab0rW6-rbt83rXGFKFAV-XIIJAR0akrqKzMBrDfWD0Lr19s3G61RQoxEScRqVn91jTfi7P2rTZ5L9u5lvkngC0P1b4FIBl9aL4IJoT9s8rPt29MAUc0a2-jBeMH6ypnFZVl99o6Mbpt945kEdpKsTlbPnierp0Q7qzsneJNGirdpTfMNk8T2FBVeQ1ML3p4P3rXGkodhfJGmrLAMCTwcLqlCaRnJMMap34x9230ygoVMElxRf9UdaEoK1gk1nRMB2ehCzQCOyvYh5nadHuvkzedI0iCOb7wvfbUT3EkSmx7clLT0GEhuERGupxEbNNWum-ZSQKvECqYYuFW3JHP738cIVD8Ovg5f_AYhimS8-ThmOMciFsWTcbwZM5GlRcIR5_wed_dw_YzCOI6i6D78Cw "PHP - Attempt This Online") - PCRE2 v10.40+
[Try it online!](https://tio.run/##RY9Ra4MwFIX/isgFk6Up6thLJVjo836BOhB3WwPZjcQUQ62/3enG2ON3OHycM9gJ3dijMSs4VTm8YWhOJ8KJnZOVsToPz49QcsHrjNWvITxDyUpV58C5gDU5H@KL/Rq0wc@YF/BQaXG1DtuuZ2AiTRFoGu6ez9AqMHIcjPaxjAt9ZdAeO3snL42P8r0gFLRV2iybgAGpSpNvfpICSBr842xnIfi8O9zxvfVdjyNLQvICxH/jB58npz3K3o5@2WZlxT9Hkux20GjCCGhZljWV@VuafgM "PowerShell – Try It Online") - .NET
---
# Perl / Java / PCRE / .NET, 39 bytes
```
^(?=((\2x|^x)*)\1(\2?x)?)(\4\3\3|^\3)*$
```
This was a stepping stone from [40 bytes](https://codegolf.stackexchange.com/a/223129/17216) to the 35 byte answer above.
Try it online! - [Perl](https://tio.run/##RU5BasMwEPzKEkSsTWws2@2hlRU7kF576q2KRVpiEKiJK7ngorhfdxU30MsyMzu7M93Rmvvp4xuI5eDN@f1ggKQ8UFHuti/bzQjt2VLiBOPlhqMH3QaGvrP61MNCnhZ8hNoI1xnd0yiJYvf15vpwouIkizM8fl5N1b/Kgo6PRCG//nIh8WBrU@boa/Oa7UWYbM9vufpGiS7FvA5ovUavW6A0GiIYIJgQQfxASmyKnrjlci43dwvFM/7XlWg@jqNST887paaGVoJSmQ@XZsAVyizgasAKqbyThSwujSxwRaaJJfkDY@wX "Perl 5 – Try It Online") / [Java](https://tio.run/##bVLLbtswELznK7ZCC5N@MLLTXsoIRlu0QIGmLZKj5QC0RNl0KEolqVhO4m93l7L6CBBdlrs7muUMdyvuxWSb3x1VWVfWwxZzpio25PB/pfFKv1izci1b7JzVzUqrDDItnIMroQw8Ql9zXngM95XKocQOufFWmTUIu3aLJQW/sdXOwec2k7VXFf55BvBFaQlFYuSuO5KIZVUuGfYjyj82RSGtzK@lyKWFVQd7XiR//uzTglLez3Vjz3ebwE@IS1aoQeTflJGE0leJabSmqiCOyV@N0I5E58PhMKL08Tn0xECIf5HgERn8XwYkOEeGFeLuuBslg9QMQvT8cKodfgrvpTVgk/6Eass6DHCUoxurqtJSGHhICmSUHG4yYQxKV6ZuPCQQ1PY1crN3XpZMGcqh19nB2Ea477L1eM3OYoDeEI13R44TyCCil9j3F0vQ2A4o5mqtPIkm@AiI92Bi7Hw1HtfAslpYJzEhehEv6RjM9MUm09Ks/eZyBnMISHiPYbpExmwj7GLZ9nq6zEyXHD5YK/aOFUpr0o4H7aAzBaCobNCG10hMzMFcJmaKYTRCgVfCZxt0qEQ2y8pTRrrNNbjgn5D8tDFsZ0VN@hFZVe9/FNfCrCVOiseG0qC0AFLieJOjd@FtH2hvcoWO7azykoRHpfwh8bYJ7/OvXaOHviDRGxehJZQfwncWtup4S@YJIemsfbpt6ZCmUzzPWzqnJH2bXqQXT7fpBR2@PoYFOsaT2bs4/g0 "Java (JDK) – Try It Online") / [PCRE1](https://tio.run/##nVJNj5swEL3zK0aWJTxZCJBkW2UN5dKuFKnqYbe3ZWMR4iyoxCDjSEjZ/PZ0iLqXHteH0Xy998Zj78qhvm4enzOwutxDaPfg@2DT1FefOr6X5n3dA7eQAYsYzKG3@k1Z3bdlpYUfzWe5UnXZOlV1x75ptS1EgbJ4igY/IPEADpRUb3pqME4bNwilHjc/fyiFASRIlEQsvcY0atBOsL6yer4rqz/OklFtc2wcC4CtFuvV@svXxfqeofQOnRW8yWLJ2@xA7IN4/v198wslnqE5CN6@DM622pCHYfKaZawwDKl5OO2oQukgDsIEJ7we@7bba8FCFlC7JHzVnYybsOmCQC9EQDZ@lR7ATdn8i7lJs1udvLs7JGkQtw0dS1fVgtuAxKZ16dIJf/QDbhARztOIDeqq7qa5JNBVEglTDNzIC8lc/lurQHndijwToliM79sRZ1gk5Ocj5iiKVbEslu/bYokzfv3cY3s3@dAA42f78BAmF/ator3M6QdIPeoKotNgo11joulPfJSucZjcx3H8Fw "Bash – Try It Online") / [PCRE2 v10.33](https://tio.run/##XVBda8IwFH33V4QQaK5Wbf3YkFj6sg2EsYdtb0ZD7aItq2lIIxR0v727lT3tIZdzP845N9cWtluntrCEOZIQOqVkQqzTJ@W0rbJc82A6GaZKFVnlVV6fbVlpJ7kEId@nTRCSAN8Ri@qk@wHjtfENV@pl8/qsFIQkBpREYTEoTaka7Tm1udOTQ5Z/e4dBVeW59DQkdDFbLVYPj7PVkoIYHGvHWZlEglXJEdUb/vH5tHkDAVdSHjmrto13lTaIYBzvkoRKQwGHm8sBO1gOo3AcQ8/Xra3qL83pmIY4LpCf1xfje@56hqQtCmCMdmJAyN3Z/OXMrJN7H9FoBGhN@P1C58znBWcuRLP@XDrzPGiDkBkAINd@xRJ0XtT9XoLgV2JB@pwwI37Q5uffWTmIbs/ThHM5a2/7FoYgY8RpCylwuZBzOb/t5RyGrOuicbyMougX "PHP – Try It Online") / [PCRE2 v10.40+](https://ato.pxeger.com/run?1=XVFLbtswEEW3PgVBEBDHkWxJdj8GLWjROoCBIimUoJswJhSVioXKlEDRrYAkJ-kmQFD0Nt0np8nIyaZdcDifN-_NkL8e2m17__Tm7zJFhzBLEkKnlExIa_W1srqt80JzbzoZp0pt89qpotm1Va2t5BKEzKad5xMPT4lJda0HgHHauI4rdbz-vFIKfBIBUiKxGJU_beU0Pzv_tMoyn375mK1i8oOC-LeAJJ3LjePegFBfV9nZ-vTEAxCjylSq047TtrB6cpUX351Fo-pqVznqEzqPF_PFu_fx4i3SjsrGclYloWB1UuJ83SCxPgEBN6QqOasvOmdrbdCDILpMEioNBQR3-yusYNoP_SCCoV_3bd1805wG1Ee4wP6i2eOUGCxjbLpAArThpRgRclA2rzEzy-RQR-_oCFCa8MMb73JXbDmzPooND65zXLr3fGYAgNwMI1agi20zzCUIrhIJMsSEGXGHMnf_fQwH8XvvyuDDo7fhacK5jPvbTQ9jkBH6aQ8pcDmXMzm73cgZjNkL_P71-hMGURSG4Uv4DA "PHP - Attempt This Online") / [.NET](https://tio.run/##RY/daoQwFIRfReSAiTaLP9ubleBCr/sERkHs2RpIE4lZlHXz7FZbSu/mG4ZhZjQz2mlApTawvLb4iUtzuWicyTXaWlJxQkS@PNuFxlRku64WWlEizqIQxbMVBY1hi64v4Zv5GqXCj5CW8OBpeTMWu34goAKpA5B6vDu6QsdBsWlU0oUsLOWNQHfqzV07plyQH4GEQ1enjd8LCGheS@2aH6cEzRT@cXZwktD16LCn9871A04kWqIYNP21H3SdrXTIBjM5v8/Kyn8OmDb7TyU1BqC991vK8tc0/QY "PowerShell – Try It Online")
Alternative 39 bytes, slower in most of the regex engines:
```
^(\1\4\4|^(?=((\3x|^x)*)\2(\3?x)$)\4)*$
```
# Perl / Java / PCRE2 v10.34 or later / .NET, 38 bytes
```
^(\1\4\4|(?=((\3x|^x?)+)\2(\3x)$)\4)*$
```
This was a stepping stone from [40 bytes](https://codegolf.stackexchange.com/a/223129/17216) to the 32 byte answer above.
Try it online! - [Perl](https://tio.run/##RY5fS8MwFMW/ymWENde2NJ31QdOsHcxXn3xbtjBlhUDcalKhktWvXtM68OVyf@f@Oac9WfMwfnwDsRy8ubwfDZCMBxTldvO6WQ/QXCwlTjBerjl60E0g9K3V5w4W8rzgA9RGuNbojkZplLivN9eFE5WkeZLj6XNaqv5VFnR8Igr59MsFx6OtTblCX5tdvhehsj2/@eobEl2KeRy6OEavG6A06iPoISwhgviBjNgMPXHL5RxuzhaC5/wvK9F8GAalnl@2So0HKnNZyOJKK0GpvO@vh77CGOVqAoIoC7wj48jS1SNj7Bc "Perl 5 – Try It Online") / [Java](https://tio.run/##bVJdb9swDHzvr@CMDpGSVHW67mWqEWzDBhRYt6F9jFNAseVEqSx7kty4SfPbM8rxPgrULzTJ01F34lo8irN1/nBQZV1ZD2vMmarYkMP/lcYr/WrNyqVssXNSNwutMsi0cA5uhDKwg77mvPAYHiuVQ4kdcuetMksQdulmcwp@ZauNgy9tJmuvKjx5AvBVaQlFYuSm@yURy6pcMuxHlH9qikJamd9KkUsLiw72skj@nOzTglLez3VjzzerwE@ISxaoQeTflJGE0jeJabSmqiCOyV@N0I5E58PhMKJ09xJ6ZCDEv0qwQwb/lwEJzpFhgbgH7kbJIDWDED3fH2v7n8J7aQ3YpP9DtWUdBjjK0Y1FVWkpDGyTAhklh7tMGIPSlakbDwkEtX2N3D05L0umDOXQ6@xgbCXcd9l6vGZnMUBviMa7I8cRZBDRS@z7szlobAcUc7VWnkRn@AiI92Bi7Fwbj2tgWS2sk5gQPYvndAxm8mqTaWmWfnV1AVMISPiAYTJHxmwl7Gze9nq6zEzmHD5aK54cK5TWpB0P2kFnCkBR2aANr5GYmIO5SswEw2iEAm@Ez1boUIlslpXHjHSba3DBPyP5cWPYxoqa9COyqn76UdwKs5Q4KR4bSoPSAkiJ402O3oW33dLe5Aod21jlJQmPSvk28bYJ7/OvXaOHviDRWxehJZTvw3cStupwT9JJeplePpNpQkj6rn2@b6d0RNOLkNBTml7S4ekh7M8hPrt4H8e/AQ "Java (JDK) – Try It Online") / [PCRE2 v10.40+](https://ato.pxeger.com/run?1=XVFBbtswEESvfgVBEBU3pmxJUdoatOBD6wIGiqRQil7ChFBUKhYqUwJFpwaSvKSXAEHR3_SevqYrJ5f0wOUOd3ZmSf586Nbd_d9Xf-YLTAhzJCN0SsmEdM5caWe6pigND6aTg4XW66Lxumw3Xd0Yp7gCqfJpHwgS4KrwUF-ZgWC9sb7nWn9cfVpqDYLEgJIoLEfVD1d7w0-_fFjmuaCf3-fLhFxTkC8LKNL7wnoeDAz9dZmfrk6OAwA5qm2te-M57UpnJpdF-d07DLqpN7WngtA0maWzN2-T2RHKjqrWcVZnkWRNVuF8_WCxOgYJN6SuOGvOeu8aYzGDMD7PMqosBST320us4LGIRBjD0G92XdN-M5yGVCBdYn_ZbnFKBPMEm85QAGN0LkeE7J3tM2Z2nu3rmI3HgNaE7994U_hyzZkTaDY8uCnw0rtAMAsA5GYYsQZTrtthLknwKrEkAybMyju0ufvvYzjIX1tfhe8eX19wFatUpbd8kXGuDne3F7sFjEElAwAGKoUD9sS-f95-R2EcR1H0BP8B "PHP - Attempt This Online") / [.NET](https://tio.run/##RY9Ra4MwFIX/isgFk9oUde6lElro836BsSDutgayG4kpSq2/3enG2ON3OHyc09kBXd@iMQs4WTq841gdj4QDO0fLlalU5Sp/sZNkTL2Nr@t44jFX2QYcuMr5DpbovA8v9qvTBj9DXsBTJsXNOqybloEJNAWgqXt4PkEtwYi@M9qHIiz0jUF9aOyDvDA@yLZCLKEuk2peBQxIlpp89ZMUQMLgH6cbxzGfNoc7fNS@abFn0RjtgPhv/OTT4LRH0drez@ustPjnQJBdbxpNGADN87wkIntPkm8 "PowerShell – Try It Online")
Alternative 38 bytes, slower in most of the regex engines:
```
(?=((\2x|^x?)+)\1(\2x)?)(\4\3\3|^\3)*$
```
---
# Perl / Java / PCRE, 39 bytes
```
^((((\3|^x)xx)*)x?+)(?=(\1*)\2+$)\1*$\5
```
[Try it online!](https://tio.run/##RU7LasMwEPyVJYhYG9tYdvElsmIH0mtPvdWJSEMMAjVxJRdUVPfXXcUNZA/LzOxjpj8bXU4f30AMB6@vp6MGkvFARbXbvm43I3RXQ4kVjFcbjh5UFxj63qjLAIv2suAjNFrYXquBRmmU2K93O4QTmaR5kuP587ZUP1QWdFwTifz2ywbHo2l0VaBv9Fu@F6GzPb/7qjslqhLzOKA4Rq86oDRyETgIS4ggfiEjJkNP7HI5h5uzheA5/89KFB/HUcrnl52U04GGap9@Dg6dwxW6OkZaC9rmK2yLmGAApC2niaVFydgf "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVLvT9swEP3OX3GLmGq3xaRMfJmJ0DZt0iTYJvjYFslNnNbgXDLboQHG396d0@wHEv5i393zO7/nu1X36ui2uNuZqqldgFuKhanFWML/mTYY@2rO6bXuqHLQtCtrcsit8h4ulUF4giHngwq03demgIoq7Do4g2tQbu3nSw5h4@qth89drptgarp5APDFWA1lhnrbH1ki8rrQguoJlx/bstROF1daFdrBqoe9TLI/N4ew5FwOff00yO0m8jPmsxVpUMWFQc04f5Nhay03JfNC/2yV9Sw5Ho/HCedPL6F7BsbCqwRPxBD@MhDBMTGsCHcn/SQbLXAU9yCf97nnHyoE7RBcNpxIbdXEBp5LcmNV11YrhMesJEYt4TpXiCTdYNMGyCCqHXLs@sEHXQmDXMKgs4eJjfLfdBfomb3FAIMhlt5OHHsQEmKQONTnS7BUjijhG2sCS47oEwgfAFOqfMVAY@BEo5zXFDA7T5d8Cjh7tSisxnXYnJ3AOUQkvKdttiTGfKPcfNkNevoIZ0sJH5xTD16UxlrWTUfdqDcFoKxd1EbPyDCVgGcZzmibTEjgpQr5hhyqiM2Jah@xfnKRBvwTke8nRmydatjQIq@bh@/llcK1pk7pFDmPSktgFbXHgryLf/vIB5NrcmzrTNAsfiqXj1lwbfyff@WGPAwlS976hCzh8jmugzhVuxtGa/Hu103Hu46PeXc@4ew8Y4vZmC9OJoecDoeL010coF16dHKapr8B "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##nVJLb9swDL77VxCCAIuJHT@abkhlN5e2QIBhh3W3uhUcR6mNOrIhK4CBLL89o4P1smN5IPj6@FEUt@VQXzZPzzlYXe4gtDvwfbBZ5qsvie9l677ugVvIgUUMFtBb/a6s7tuy0sKPFrO1UnXZOlV1h75ptS1EgbL4FQ1@QOQB7Cmo3vVUYJw2bhBKPW1@PCqFASRILamx9BrTqEE7wfrK6sW2rD6cJaXa5tA4FgBbpqvl6tv3dHXLUHr7zgre5LHkbb6n7oN4/v2w@YkST9DsBW9fBmdbbcjCMHnNc1YYhlQ8HLeUoXAQB2GCE16PfdvttGAhC6hcEr7qjsZN2Cwl0As1IB2/Sg/gymz@@dxk@TVP1nyORA3iuqFD6apacBsQ2bQuXTrhj37ADSLCaRqxQV3V3TSXBHpKImHygRt5Jprzf2sVKC9vgqS4@fM24jjiDMf1HMU6F0UywyKdcySDF7eXr322d6UPDTB@snd3YXJm9xXtZUEXIPWoK4iOg422jYmmm/hMXeJwmcbxXw "Bash – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XVDfa4MwEH7vXxFCwFzVVl27UVLpyzYojD1se6ttsC5WmY0hpiB0@9vdWfa0wB336/u@y5nKDOuNqQxhlqSEzimZEWPVSVplmrxQ3JvPphspq7xxsmjPpm6UzXgGInubd15APLQSi/KkxgHtlHYdl/J5@/IkJQQkBqREYjGpdS075Tg1hVWzY158OYtONvW5djQgdJGsFqv7h2S1pCAmZWs5q9NIsCYtkb3j7x@P21cQcCV1yVmz65xtlMYIwnifpjTTFHC4uxyxg@UgCsIYRrzqTdN@Kk5DGuC4QHzRXrQbsesEQTskQB/txYSQm7L@y5lep7c@Rr4PKE347ULn3BUVZzZAsfFcKnfc672AaQAg13HFGlRRteNeguBXYkHGnDAtflDm599ZOYjhwPFld9@HHvoeptBvfOCblGfxFLLEZ4ABy5bDEIWLJIp@AQ "PHP – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=XVDdSsMwFMbbPUUIgeZs7dbWTR1Z6Y0KA_FCvVs11JraYpeWNIOC-ga-gTeC6Dvp03i67cpATs7P953v5Lx_NkXz8XvwtojRIcyQiNAJJWPSGPUojWqqNFPcmYyHsZRFWlmZ1eumrJRJeAIiuZq0jkscvDkm5aPqAdoqbVsu5fny4kxKcEkA2BIbi0GpS9kqy2mTGTW-T7Mna9DIqlyXlrqETsP5dH50HM5nFMQgrw1nZeQLVkU5dm_59c3p8hIEPJMy56xatdZUSqMHXnAbRTTRFBDcbu6xgmnXd70Aer7qmqp-UJx61EW4QH5Wb7TtuYsQSStsgNa_FQNCtsp6HzO9iLZ19EYjQGnCtxtapzYrODMuivXrUqnlTue4TAMAee5HLEFlRd3PJQh-JRCkjwnT4hVlXv-tlYP42tjcO_lx7jie5PDlroOugyF08Qh4HPEkGEISjhigw5LZDv6xf759bxr6_i76Aw "PHP - Attempt This Online") - PCRE2
This is the same as the 40 byte regex below, but drops .NET support by using a possessive quantifier, `x?+` instead of `|^$`, to match \$0^4\$. This works because `x?+` will always consume 1 `x` if it can, and will only consume 0 `x`s if \$\it\text{tail}=0\$, which can happen in two ways:
* If the input was \$0\$, in which case `\1` and `\2` will have both captured \$0\$, and the second half of the regex will match.
* If the input was nonzero, in which case `\2` will have captured the entire nonzero input value, making it impossible for the second half of the regex to match, as `\2+` won't be able to match with \$\it\text{tail}=0\$.
# Perl / Java / PCRE / .NET, ~~42~~ 40 bytes
```
^((((\3|^x)xx)*)x)(?=(\1*)\2+$)\1*$\5|^$
```
[Try it online!](https://tio.run/##RU7LasMwEPyVJYhYG9tYdvGlshIH0mtPvVWJSEsMAjVxJRdUVPfXXcUNZA/LzOxjpj9ZU08f30Ash2Au70cDpOCRima3fdmuR@gulhInGG/WHAPoLjIMvdXnARbyvOAjtEa43uiBJnmSua83N8QTleVlVuLp87q0uass6vhIFPLrLxcdj7Y1TYWhNa/lXsTO9vzmq2@U6EbM44jSFIPugNLEJ@AhLiGC@IWC2AIDccvlHG7OFoOX/D8r0XwcR6WenndKTQcaSz78HDx6jyv0SDeCynKFskoJRkBkPU0sr2rG/gA "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##bVLLbtswELznK7ZCCpO2w8gpcikjBG3RAgWatkiOtgPQEmUzoVYqScXK69vdpaw@AoQXcneHs5zh3qg7dXRT3O5M1dQuwA3FwtRiLOH/TBuMfTXn9Fp3VDlo2pU1OeRWeQ8XyiA8wpDzQQXa7mpTQEUVdhWcwTUot/bzJYewcfXWw@cu100wNd08APhirIYyQ73tjywReV1oQfWEy49tWWqni0utCu1g1cNeJtmfm0NYci6Hvn4a5HYT@Rnz2Yo0qOKbQc04f5Nhay03JfNC/2qV9Sw5Ho/HCeePL6F7BsbCqwSPxBD@MhDBMTGsCHcr/SQbLXAU9yCf97nnnyoE7RBcNpxIbdXEBp5LcmNV11YrhIesJEYt4SpXiCTdYNMGyCCqHXLs6t4HXQmDXMKgs4eJjfLfdRfomb3FAIMhlt5OHHsQEmKQONTnS7BUjijhG2sCS47oEwgfAFOqfMVAY@BEo5zXFDA7T5d8Cjh7tSisxnXYnJ3AOUQkvKdttiTGfKPcfNkNevoIZ0sJH5xT916UxlrWTUfdqDcFoKxd1EbPyDCVgGcZzmibTEjghQr5hhyqiM2Jah@xfnKRBvwTke8nRmydatjQIq@b@x/lpcK1pk7pFDmPSktgFbXHgryLf/vAB5NrcmzrTNAsfiqXD1lwbfyff@WGPAwlS976hCzh8jmugzhVu2tGa/Hu6brjXcfHvOPsPGOL2ZgvTiaHnA6Hi9On68NdnKBdenRymqa/AQ "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##nVJLb9swDL77VxCCAIuJHT@abkhlL5etQIBhh3W3uhEcR6mNObIhK4CBNL89pYP1smN5IPj6@FEUd@VQXzePTzlYXe4htHvwfbBZ5qtPie9l677ugVvIgUUMFtBb/aqs7tuy0sKPFrO1UnXZOlV1x75ptS1EgbL4HQ1@QOQBHCioXvVUYJw2bhBKPW5@/lAKA0iQWlJj6TWmUYN2gvWV1YtdWf11lpRqm2PjWABsma6Wqy9f09U9Q@kdOit4k8eSt/mBug/i6c/3zS@UeIbmIHj7PDjbakMWhslLnrPCMKTi4bSjDIWDOAgTnPB67NturwULWUDlkvBVdzJuwmYpgZ6pAen4RXoAN2bzz@cmy295suZzJGoQtw0dS1fVgtuAyKZ16dIJf/QDbhARztOIDeqq7qa5JNBTEgmTD9zIC9Fc/lurQHndCpLi7m074jjiDEcU61wUyQyLdM6RDF7cv2359XO/7d34QwOMn@3DQ5hc2LeKFrOgE5B61BVEp8FGu8ZE01F8pK5xuEzj@B0 "Bash – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XVDfa8IwEH73rwgh0Jy22na6IbH4sg2EsYdtb1ZD7VJbVtOQRiiof3t3lT0tcMf9@r7vcqY0/WptSkOYJQmhM0qmxFh1lFaZOssV92bT8VrKMqudzJuTqWplU56CSD9mrecTD63AojyqYUA7pV3LpXzdvL1ICT6JACmRWIwqXclWOU5NbtX0kOU/zqKTdXWqHPUJncfL@fLxKV4uKIhR0VjOqiQUrE4KZG/559fz5h0EXEhVcFZvW2drpTGCINolCU01BRxuzwfsYNkP/SCCAa86UzffitOA@jguEJ83Z@0G7CpG0BYJ0Ic7MSLkrqz/cqZXyb2P0WQCKE34/UKnzOUlZ9ZHseFcKnPc6zyfaQAgl2HFClReNsNeguBXIkGGnDAtbihz@3dWDqLfc3zpw3XfQdfBGDrg64Sn0RjSeMIAA5YurnvW92Ewj8PwFw "PHP – Try It Online") / [Attempt This Online!](https://ato.pxeger.com/run?1=XVDdSsMwFMbbPUUIgeZs7dbWTR1Z2Y0Kgnih3q0u1Jq6YJeWNIOC-ga-gTeC6Dvp03i67cpATs7P953v5Lx_1qv64_fgbTZHhzBLEkJHlAxJbdWjtKous1xxbzTsz6VcZaWTebWudalsylMQ6fWo8Xzi4S0wKR9VBzBOGddwKc8vLs-kBJ9EgC2xsehpo2WjHKd1btXwPsufnEUjS73WjvqEjuPpeHp0HE8nFESvqCxnOgkFK5MCuzf85vb04goEPBNdcFYuGmdLZdCDILpLEpoaCghuNvdYwbQf-kEEHV-1dVk9KE4D6iNcID-vNsZ13FmMpAU2QBveiR4hW2Wzj5mZJds6eoMBoDTh2w2tM5evOLM-inXrUpnjXuv5zAAAee5G1KDyVdXNJQh-JRKkiwkz4hVlXv-tlYP42rgiOPnhS44nPXxZttC20IcW-DzhadSHNB4wQIelk5cl2-E_9s93GIzjMNxFfw "PHP - Attempt This Online") - PCRE2
[Try it online!](https://tio.run/##RY/daoNAEIVfRWTAXe0GteQmsiSQ6z6BPyB2Ehe2s7JucInx2a22lM7V@Q6Hw5zBTGjHHrVewcrS4h19fToRTuwSrQ3brnp/NZ57z2PuOTtLVmUxr/IE@CagOr4aWKPLW3g1X4PS@BnyAp4yLW7GYtv1DHSgKABFw8PxGVoJWoyDVi4UYaFuDNpDZx7khHZBvgcSCW2Z1stWwIBkqcjVP04BJDT@cbZzkvB577CHj9Z1PY4s8lEMxH/tJ58nqxyK3oxu2d7Kin8OBJltqFaEAdCyLGsq8mOafgM "PowerShell – Try It Online") - .NET
This uses the equivalent of `^(\1xx|^x)*$` to match a perfect square using a nested backreference (made more complicated by needing to capture that square minus \$1\$), and then uses a square-testing algorithm which works thanks to the Chinese remainder theorem (which only requires ECMAScript or better, and is the reason for needing to capture the square minus \$1\$), to assert that the captured perfect square is the square root of the inputted number. The latter algorithm is [explained in this post](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420), and this exact square-testing regex is used [in the second answer in this post](https://codegolf.stackexchange.com/questions/144561/golf-the-pseudoprimes/179024#179024).
```
^ # tail = N = input number
( # \1 = the largest perfect square for which the
# subsequent expression matches; tail -= \1
( # \2 = \1 - 1
( # \3 = nested backreference
# On the first iteration, \3 = 1 + 2 = 3;
# on subsequent iterations, \3 = \3 + 2
(\3|^x)
xx
)* # iterate \3 any number of times (may be zero); \2
# becomes the total of all these iterations
)
x # \1 = \2 + 1
)
# Assert that N == \1^2
(?=
(\1*)\2+$ # iff \1*\1 == N, the first match here must capture \5=0
)
\1*$\5 # assert \1 divides N-\1, and \5==0
|
^$ # Allow us to match N=0, which can't be matched above
```
] |
[Question]
[
As code-golfers, we're not used to releasing (*surely*). We're gonna need a few tools to help us do that.
Of course, to help marketing a new release, we need a nice and shiny Release Version. Who doesn't get excited when they hear about version 3.0.0?
### Task
Your task will be to write a program/routine/... to increment a version number.
You need to increment the version number and reset the "less important" ones (i.e. patch version).
You get two arguments: the current version (ex "1.0.3") as a string, and an index to know which one to update (0 or 1-indexed).
Example, 0-indexed:
```
next-version("1.0.3", 0) # 2.0.0
next-version("1.2.3.4.5", 2) # 1.2.4.0.0
next-version("10.0", 0) # 11.0
next-version("3", 0) # 4
next-version("1", 7) # ERROR
next-version("01", 0) # ERROR
```
The version is a string, each part is a number, separated with a dot. There can be no leading, no trailing or no consecutive dots (and nothing outside of numbers/dots). There is no limit to the size of the version string.
`^[1-9]\d*(\.[1-9]\d*)*$`
The error case (last two examples) is undefined behavior. What happens in case of wrong inputs is of no relevance to this challenge.
As usual, standard loopholes are forbidden. You're allowed to print or return the string.
[Answer]
# Japt, ~~16~~ 11 bytes
```
¡V«´V+ÂX}'.
```
[Test it online!](http://ethproductions.github.io/japt/?v=master&code=oVartFYrwlh9Jy4=&input=IjEuMi4zIiAy) Input number is 1-indexed.
Based on my JavaScript answer. This takes advantage of one of Japt's most helpful features: splitting one string on another before mapping each item, then joining on that string again after mapping.
### Ungolfed and explanation
```
¡ V« ´ V+Â X}'.
Um@V&&!--V+~~X}'.
Implicit: U = input string, V = input number
Um@ }'. Split U at periods, then map each item X by this function:
V&& If V is 0, return V.
!--V+~~X Otherwise, decrement V and return X + !V (increments X iff V was 1).
'. Re-join the result with periods.
Implicit: output last expression
```
[Answer]
# Vim ~~20~~ 25 bytes
I unfortunately realized that it didn't handle the case of updating the last number, so I had to add bytes. This is 1-indexed.
```
DJA.0@"t.qq2wcw0@qq@qx
```
[TryItOnline](http://v.tryitonline.net/#code=REpBLhswQCJ0LgFxcTJ3Y3cwG0BxcUBxeA&input=NQoxLjIuMy40LjU)
Unprintables:
```
DJA.^[0@"t.^Aqq2wcw0^[@qq@qx
```
This takes the arguments in reverse order, as separate lines:
```
3
1.2.3.4.5
```
Explanation:
```
DJ # Delete the input argument, and join lines
A.^[0 # Add a period to the end
@"t. # Move to the "Copy register"th period
^A # Increment the number under the cursor
qq @qq@q # Until an error
2w # Move the cursor forward to the next number
cw0^[ # Change the number to 0
x # Delete the last '.'
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), ~~13~~, 12 bytes
```
Àñf.ñò2wcw0
```
[Try it online!](http://v.tryitonline.net/#code=w4DDsWYuw7EBw7Iyd2N3MA&input=MS4yLjMuNC41&args=MQ)
This is 0-indexed.
There is a `ctrl-a` (ASCII 0x01) in there, so here is a readable version:
```
Àñf.ñ<C-a>ò2wcw0
```
Explanation:
```
À " 'arg1' times
ñ ñ " Repeat the following:
f. " Move to the next '.' character
<C-a> " Increment the next number
ò " Recursively:
2w " Move two words forward
cw " Change this word
0 " to a '0'
```
[Answer]
# JavaScript (ES6), ~~44~~ ~~42~~ ~~40~~ 37 bytes
*Saved 3 bytes thanks to @Neil*
```
x=>i=>x.replace(/\d+/g,n=>i&&+n+!--i)
```
Input number is 1-indexed.
### Test snippet
```
f = x=>i=>x.replace(/\d+/g,n=>i&&+n+!--i)
console.log(f("1.0.3")(1))
console.log(f("1.2.3.4.5")(3))
console.log(f("10.0")(1))
console.log(f("1")(8))
```
[Answer]
# Perl, ~~40~~ ~~37~~ 34 + 1 = 35 bytes
-2 bytes thanks to @Dada. -3 bytes thanks to an idea I got from reading @ETHproductions's Japt code.
Run with the `-p` flag.
```
$a=<>;s/\d+/$a--<0?0:$&+!($a+1)/ge
```
[Try it online!](https://tio.run/nexus/perl#@6@SaGtjZ12sH5Oira@SqKtrY2BvYKWipq2ooZKobaipn576/7@hnoGeMZcBl6GekZ6xnomeKZcRl6GBngFIiMv8v24BAA "Perl – TIO Nexus")
### Breakdown of the code
```
-p #Wraps the program in a while(<>){ ... print$_} statement.
#Input is read into the $_ variable
$a=<>;s/\d+/$a--<0?0:$&+!($a+1)/ge
$a=<>; #Reads the version update into $a
s/ / /ge #Substitution regex:
g #Repeats the substitution after first match
e #Interprets replacement as Perl code
\d+ #Matches 1 or more digits, and stores match in $&
? : #Ternary operation
$a--<0 #Checks if $a is negative and then decrements $a
?0 #If negative, we've passed our match; print 0 instead
:$&+!($a+1) #Otherwise, we're either printing $& + 0 (if $a was positive) or $& + 1 (if $a was 0).
#Since substitution implicitly modifies $_, and -p prints $_, it prints our answer
```
[Answer]
# C# ~~116~~ 104 Bytes
```
using System.Linq;(v,i)=>string.Join(".",v.Split('.').Select(int.Parse).Select((x,n)=>n==i?x+1:n>i?0:x));
```
## Explanation
```
using System.Linq;(v,i)=> //Anonymous function and mandatory using
string.Join(".", //Recreate the version string with the new values
v.Split('.') //Get individual pieces
.Select(int.Parse) //Convert to integers
.Select(
(x,n)=> //Lambda with x being the part of the version and n being the index in the collection
n==i
?x+1 //If n is the index to update increment x
:n>i //Else if n is greater than index to update
?0 //Set to zero
:x)); //Otherwise return x
```
[Try it here](https://dotnetfiddle.net/f2t5oZ)
[Answer]
# Python 2, 84 Bytes
I feel like this could really be shorter.. Might need a way to have a non-enumerate option.
```
lambda s,n:'.'.join(str([-~int(x)*(i==n),x][i<n])for i,x in enumerate(s.split('.')))
```
If we were able to take the version as a list of strings, there's a 75-byte solution:
```
g=lambda s,n:(str(-~int(s[0]))+'.0'*~-len(s))*(n<1)or s[0]+'.'+g(s[1:],n-1)
```
Furthermore, if both the input and output were lists of numbers, there's a 64-byte solution:
```
g=lambda s,n:([-~s[0]]+[0]*~-len(s))*(n<1)or [s[0]]+g(s[1:],n-1)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ”.V€‘⁹¦µJ’<⁹×j”.
```
1-indexed.
**[TryItOnline!](http://jelly.tryitonline.net/#code=4bmj4oCdLlbigqzigJjigbnCpjBK4bmr4oG54oCYJMKlwqZq4oCdLg&input=&args=IjEzLjEyLjExLjEwLjkuOC43LjYi+NQ)**
### How?
```
ṣ”.V€‘⁹¦µJ’<⁹×j”. - Main link: currentVersion, theIndex
ṣ”. - ṣplit left (currentVersion) at occurences of '.'
V€ - eVal €ach (creates a list of integers)
⁹ - right argument (theIndex)
¦ - apply to given index(es)
‘ - increment
µ - monadic chain separation (call the above result z)
J - range(length(z)) i.e. ([1,2,3,...,length])
’ - decrement i.e. ([0,1,2,...,length-1])
⁹ - right argument (theIndex)
< - less than? i.e. ([1,1,...,(1 at theIndex),0...,0,0,0]
× - multiply by z (vectortises) - zeros out all of z after theIndex
j”. - join with '.'
```
[Answer]
# **MATLAB, 85 bytes**
```
function f(s,j);a=split(s,'.');a(j)=string(double(a(j))+1);a(j+1:end)='0';join(a,'.')
```
One based, and first attempt at golf!
[Answer]
# V ~~14~~ 20 bytes
Again, I had to add code for the corner case of incrementing the final digit.
(1-indexed)
```
DJA.0@"t.ò2wcw0òx
```
[TryItOnline](http://v.tryitonline.net/#code=REpBLhswQCJ0LgHDsjJ3Y3cwG8OyeA&input=NQoxLjIuMy40LjU)
Unprintables:
```
DJA.^[0@"t.^Aò2wcw0^[òx
```
This takes the arguments in reverse order, as separate lines:
```
3
1.2.3.4.5
```
[Answer]
## Batch, 119 bytes
```
@set s=%1
@set i=%2
@set t=
@for %%i in (%s:.=,%)do @set/an=!!i*(%%i+!(i-=!!i))&call set t=%%t%%.%%n%%
@echo %t:~1%
```
1-indexed.
[Answer]
# Perl 6, 67 bytes, 0-indexed
```
->$v,$i {$v.split('.').map({++$>$i??($++??0!!$_+1)!!$_}).join: '.'}
```
Explanation:
```
->$v,$i {$v.split('.').map({++$>$i??($++??0!!$_+1)!!$_}).join: '.'}
->$v,$i { } # function taking version/index to increment
$v.split('.') # split by dot
.map({ }) # for each version number
++$>$i?? # if an anonymous variable ($), incremented,
# is greater than $i (index to increment)
($++?? ) # if it's not the first time we've been over $i
# (using another anonymous value, which gets default-init'd to 0)
0 # then 0 (reset lower version numbers)
!!$_+1 # otherwise, increment the number at $i
!!$_ # otherwise return the number part
.join: '.' # join with a dot
```
[Answer]
# PowerShell 3+, ~~75~~ 74 bytes
```
($args[0]-split'\.'|%{$m=!$b;$b=$b-or$args[1]-eq$i++;(+$b+$_)*$m})-join'.'
```
### Ungolfed
```
(
$args[0] -split '\.' |
ForEach-Object -Process {
$m= -not $b
$b = $b -or ($args[1] -eq $i++)
(([int]$b) + $_) * $m
}
) -join '.'
```
### Explanation
Parameters are accepted using the `$args` array.
1. Split the version string on `.`, then for each element:
1. `$m` is set to be `-not $b`. On first run, `$b` will be undefined which will be coalesced to `$false`, so `$m` will start as `$true`. `$m` is intended to be a multiplier that's always `0` or `1` and it will be used later. `$m` must be evaluated here because we want it to be based on the last iteration's `$b` value.
2. `$b` is set to itself `-or` the result of comparing an iterator `$i` with `$args[1]` (the index parameter). This means `$b` will be set to `$true` here once we're on the element that is to be incremented. Additionally, it will be `$true` in every subsequent iteration because the conditional is `-or`'d with its current value.
3. `$b` is converted to a number using unary `+` (`$false` => `0`, `$true` => `1`), then added to the current version element `$_` which is a `[string]`, but PowerShell always tries to coalesce the argument on the right to the type on the left, so arithmetic will be performed, not string concatenation. Then this value will be multiplied by `$m`, which is still `[bool]` but will be implicitly coalesced.
2. Re-join the resulting array with `.`.
So, the first iteration where `$b` becomes `$true`, `$b` would have been `$false` when `$m` was evaluated, making `$m` equal `$true`, which will keep the multiplier at `1`.
During that run `$b` becomes `$true` and is added to the version element (as `1`), thereby incrementing it, and since the multiplier is still `1`, that will be the end result.
So on the next iteration, `$b` will already be `$true`, making `$m` equal `$false`, which will make the multiplier `0`. Since `$b` will forever be `$true` now, the multiplier will always be `0`, so every element returned will be `0` too.
[Answer]
# PHP, 81 bytes
awfully long. At least: the Elephpant still beats the Python.
```
foreach(explode(".",$argv[1])as$i=>$v)echo"."[!$i],($i<=$n=$argv[2])*$v+($i==$n);
```
loops through first argument split by dots: `"."[!$i]` is empty for the first and a dot for every other element;
`($i<=$n)` and `($i==$n)` are implicitly cast to integer `0` or `1` for integer arithmetics.
[Answer]
# R, ~~100~~ ~~95~~ ~~92~~ 86 bytes
Unusually for R, this uses 0-indexing. Anonymous function with two arguments (a string and an integer). Likely can be golfed down a tad.
```
function(v,i)cat((x=scan(t=el(strsplit(v,"\\."))))+c(rep(0,i),1,-x[-(0:i+1)]),sep=".")
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 22 bytes
```
'.¡vy²N‹i0*}²NQi>})'.ý
```
[Try it online!](http://05ab1e.tryitonline.net/#code=Jy7CoXZ5wrJO4oC5aTAqfcKyTlFpPn0pJy7DvQ&input=MS4wLjAuMC4zCjA)
I don't know how to do if-else in 05AB1E, so this is longer than it should be.
[Answer]
# Coffee-script: 77 67 Bytes
```
f=(p,i)->((z<i&&v||z==i&&~~v+1||0)for v,z in p.split '.').join '.'
```
Woot! Time for cake and coffee for the beta release.
Thanks to @ven and @Cyoce I shaved 10 Bytes!
[Answer]
# Python 3, ~~89~~ 86 bytes
```
lambda v,c:'.'.join((str((int(x)+1)*(i==c)),x)[i<c]for i,x in enumerate(v.split('.')))
```
very naive way of getting things done
Edit: rewritten the conditional by referring to @kade
[Answer]
# JavaScript (ES6), ~~57~~ 55 bytes
```
(s,x)=>s.split`.`.map((j,i)=>i==x?+j+1:i>x?0:j).join`.`
```
Examples:
```
n=(s,x)=>s.split`.`.map((j,i)=>i==x?+j+1:i>x?0:j).join`.`
console.log(n('1.0.3', 0))
console.log(n('1.2.3.4.5', 2))
console.log(n('10.0', 0))
console.log(n('3', 0))
console.log(n('1', 7))
```
Not the best JS implementation but it's fairly simple and follows the logic you'd expect.
[Answer]
## Powershell, ~~80~~ ~~100~~ ~~95~~ 92 Bytes
Saved 5 bytes by using a const for the `-1..if`
Saved 3 bytes by using `!$b` instead of `$b-eq0`
```
filter x($a,$b){[int[]]$y=$a.Split('.');-1..((-$b,-1)[!$b])|%{$y[$_]=0};$y[$b]++;$y-join'.'}
```
Explanation:
```
filter x($a,$b){
[int[]]$y=$a.Split('.') #Split input into integer array
$y[$b]++ #Increment 'major' version no. ($b) by one
-1..((-$b,-1)[!$b])|%{$y[$_]=0} #Set all trailing numbers to 0, now also checks for $b=0 cases.
$y-join'.' #Join back into '.' seperated Array
}
```
Test Cases:
```
x "1.0.3" 0
x "1.2.3.4.5" 2
x "10.0" 0
x "1" 7
2.0.0
1.2.4.0.0
11.0
Index was outside the bounds of the array.
```
[Answer]
**Objective-C 531 Bytes**
```
#import<Foundation/Foundation.h>
int main(int argc,const char *argv[]){@autoreleasepool{NSString *s=[NSString stringWithUTF8String:argv[1]];NSInteger n=strtol(argv[2],NULL,0);NSArray *c=[s componentsSeparatedByString:@"."];if(c.count<=n)NSLog(@"ERROR");else{int i=0;NSMutableString *v=[[NSMutableString alloc]init];for(;i<n;++i)[v appendFormat:@"%@.",[c objectAtIndex:i]];[v appendFormat:@"%li", strtol(((NSString *)[c objectAtIndex:i++]).UTF8String,NULL,0)+1l];for(;i<c.count;++i)[v appendString:@".0"];NSLog(@"%@",v);}}return 0;}
```
compile:
```
clang -fobjc-arc -Os main.m -o main
```
usage:
```
./main 1.2.3 1
```
[Answer]
# Javascript ES6: 60 bytes
```
n.split(".").map((n,r)=>{return r>i?n=0:n}).join("."),n[i]++}
```
[Answer]
# R, 75 bytes
```
f=function(a,b){n=scan(t=a,se=".");m=-n;m[b]=1;m[1:b-1]=0;cat(n+m,sep=".")}
```
Indexing is 1-based. You can play with it online [here](http://www.r-fiddle.org/#/fiddle?id=Dl6usKXg&version=1).
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 31 bytes
Requires `⎕IO←0` (**I**ndex **O**rigin 0), which is default on many systems. Full program body; prompts for text input (version) and then numeric input (index).
```
' '⎕R'.'⍕⎕(⊢∘≢↑↑,1+⊃)⊃⌽'.'⎕VFI⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862vNSK0riy1KLijPz8/6rK6gDJYPU9dQf9U4FsjQedS161DHjUeeiR20TgUjHUPtRV7MmED/q2QtS1Tc1zM3zUe@8/0CT/iuAAbKBXIZ6BnrGXAZcWKWM9Iz1TPRMuYywShvoGWDXiMM8A0Mc9nCZAwA "APL (Dyalog Unicode) – Try It Online")
`⍞` prompt for text input
`'.'⎕VFI` **V**erify and **F**ix **I**nput using period as field separator (fields' validities, fields' values)
`⌽` reverse (to put the values in front)
`⊃` pick the first (the values)
`⎕(`...`)` apply the following tacit function to that, using evaluated input as left argument:
To explain the non-tacit equivalents of each function application we will now use `⍺` to indicate the left argument (the index) and `⍵` to indicate the right argument (the list of individual numbers of the originally inputted current version number).
`⊃` equivalent to `(⍺⊃⍵)` use `⍺` to pick an element from `⍵`
`1+` add one to that
`↑,` equivalent to `(⍺↑⍵),` prepend `⍺` numbers taken from `⍵`
`⊢∘≢↑` equivalent to `(⍺⊢∘≢⍵)↑` equivalent to `(≢⍵)↑` take as many numbers from that as there are elements in `⍵`, padding with zeros if necessary
`⍕` format (stringify with one space between each number)
`' '⎕R'.'` PCRE **R**eplace spaces with periods
[Answer]
# Java 8, 130 bytes
```
s->n->{String r="",a[]=s.split("\\.");for(int l=a.length,i=-1;++i<l;)r+=(i>n?0:new Long(a[i])+(i<n?0:1))+(i<l-1?".":"");return r;}
```
**Explanation:**
[Try it here.](https://tio.run/##lVDBbsIwDL3zFVZOidpaLWwXSstt0qTtxBF6yErowoJbJSkTQv32Lgy0y6SJST7Yz@/Zft7Lo0zaTtF@@zHWRjoHr1LTeQLgvPS6hn1gYO@1wV1Ptdct4dMtWay81dTEf3KeyatG2Riu5LKEGgoYXVJSUp6vINiCsViuq8Kh64z2nG02yES@ay3X5MEUEo2ixr/HukiyPIr0wuTCRgXXJS3TOalPeGmp4XKtKxFxvbigmfhOTZItGbI5CxOt8r0lsPkw5sFkiK5/M8Hnze6x1Vs4hBfw62nrCqS4vANgdXJeHbDtPXah5Q3xGmXXmRNnGaY4Y@JWpkLkd0imOMMHfPyRTe@SpZj@b9Gvu4bJMH4B)
```
s->n->{ // Method with String and Integer parameters and String return-type
String r="", // Result-String
a[]=s.split("\\."); // String-array split by the dots
for(int l=a.length, // Length of the array
i=-1;++i<l;) // Loop from 0 to `l` (exclusive)
r+= // Append the result-String with:
(i>n? // If index `i` is beyond input `n`:
0 // Append a zero
: // Else:
new Long(a[i]) // Convert the current String to a number
+(i<n? // If index `i` is before input `n`
0 // Leave the number the same by adding 0
: // Else:
1)) // Add 1 to raise the version at index `n`
+(i<l-1? // If we've haven't reached the last iteration yet:
"." // Append a dot
: // Else:
"" // Append nothing
); // End of loop
return r; // Return the result-String
} // End of method
```
[Answer]
# LiveScript, ~~53~~ 52 bytes
```
->(for e,i in it/\.
[+e+1;0;e][(i>&1)+2*(i<&1)])*\.
```
-1 byte thanks to @ASCII-only!
Old Explanation:
```
(a,b)->x=a/\.;x[b]++;(x[to b] ++ [0]*(x.length-1-b))*\.
(a,b)-> # a function taking a and b (version and index)
x=a/\.; # split a on dot, store in x
x[b]++; # increment at the given index
(x[to b] # slice be from 0 to the index
++ # concat (both spaces are necessary so it's not interpreted as an increment operator
[0]*(x.length-1-b)) # with enough zeros to fill the array back to its original size (x's size)
*\. # join on dot
```
Another self-answer... Not that anyone golfes in LiveScript anyway. :P
I was working on another version:
```
(a,b)->(a/\.=>..[b]++;..[b to *]=0)*\.
```
But `*` is too overloaded to be recognized in a splicing index, thus `=0` will try to access `0[0]`. So you need to write something like `..[b to ..length- b]=[0]*(..length-1-b)` and it's longer in the end.
[Answer]
# [Haskell](https://www.haskell.org/), ~~136~~ 129 bytes
```
import Data.List.Split
import Data.List
f s n|(x,z:y)<-splitAt n(splitOn "."s)=intercalate "."(x++[show$read z+1]++map(\_->"0")y)
```
[Try it online!](https://tio.run/##XYuxCsIwFAB3v@IROiTEBludxAqCo@DgqCIPTWkwTUPywLb479E6uh3HXYPxqa1NybS@CwR7JFQHE0mdvDU0@9ezGiK4N@/n43oQmzxO1Y7A8R8dHTDFoqiMIx3uaJH0ZHgv5Tk23SsLGh8wyuIqZYueX275li2YGERq0TioAHz4zpBBDaxQpVqqFYMyfQA "Haskell – Try It Online")
---
[Original](https://tio.run/##XY09C8IwGAb3/oqH0CElGqw6CRUER8HBUUVeNKXBNA1JoB9/PlpHt@OGu4bCWxmTkm5d5yOOFEmedIjy4oyO2b/OagTYStuo/JMMRQUmGR@EuIam63Ov6IVJlHchWnL89lju2YoVY5EBfaO8Ah8W024sqjD3DxGW/@hs51AoUkvaogKc/06QowYr5Vpu5JahTB8 "Haskell – Try It Online")
[Answer]
# Pyth - 21 bytes
```
j\.++<Kcz\.Qhs@KQmZ>K
```
[Test Suite](http://pyth.herokuapp.com/?code=j%5C.%2B%2B%3CKcz%5C.Qhs%40KQmZ%3EK&test_suite=1&test_suite_input=2%0A1.2.3.4.5%0A0%0A10.0&debug=0&input_size=2)
] |
[Question]
[
## The task
In this challenge, you are given a number and a list.
Your task is to remove from the list all occurrences of the given number except the first (leftmost) one, and output the resulting list.
The other elements of the list should be left intact.
* The number will be a positive integer below 1000, and the list will only contain positive integers below 1000.
* The list is not guaranteed to contain any occurrences of the given number. It may even be empty. In these cases you should output the list as-is.
* Input and output formats are flexible within reason. You can output by modifying the list in place.
* The lowest byte count wins.
## Test cases
```
5 [] -> []
5 [5] -> [5]
5 [5,5] -> [5]
10 [5,5] -> [5,5]
10 [5,5,10,10,5,5,10,10] -> [5,5,10,5,5]
2 [1,2,3,1,2,3,1,2,3] -> [1,2,3,1,3,1,3]
7 [9,8,7,6,5] -> [9,8,7,6,5]
7 [7,7,7,7,7,7,7,3,7,7,7,7,7,7,3,7,1,7,3] -> [7,3,3,1,3]
432 [432,567,100,432,100] -> [432,567,100,100]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes
```
üoEė
```
[Try it online!](https://tio.run/##yygtzv7///CefNcj0////29o8D/aVMdUx9AAhOCsWAA "Husk – Try It Online")
* Saved 1 byte thanks to Razetime
* Saved 2 bytes thanks to Jo King
Thanks to Razetime for suggesting `ü` and Jo King for letting me know I could leave the superscript arguments out, saving me 2 bytes. It removes duplicates with a custom predicate that makes sure both arguments are equal to the number to be removed.
Explanation:
```
üoEė
ü Remove duplicates by binary function (implicit second argument)
o Compose 2 functions
ė Make a list of 3 elements (first element is implicitly added)
E Are they all equal?
```
[Answer]
# [R](https://www.r-project.org/), 30 bytes
```
function(l,d)unique(l,l[l!=d])
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jRydFszQvs7A0FcjMic5RtE2J1fyfppGZV5KanlqkYaCpY6rJlaaRrGGqY6pjaABCcJYmCP8HAA "R – Try It Online")
`unique()` has the signature `unique(x,incomparables = FALSE,...)`; this sets `incomparables` to the elements that aren't equal to `d`, so only `d` is uniquified.
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
l,n=input()
for x in l:
if~n-x:print x;n^=-(x==n)
```
[Try it online!](https://tio.run/##ZYvNCoMwEITveYrFk8IISaw/VfIkwV6KYkBWEUvTS1/dGgtFKLvMNzvszK91mFhvz8GNHam68909iqJtBBvH82ONE9FPC3lyTGMtyPVvTn09L45X8g3fTBp7YzjZjqgRoW1b5MLmX8WJ6iCUDPtzey6FVdDIcNIWmoS9okKJIrRLYUucJ/u7VODxeck08mJPpETwO9tgPg "Python 2 – Try It Online")
Prints output one entry per line.
The idea is to store whether we have already encountered the entry-to-remove `n` in the sign of `n` rather than a separate Boolean variable. When we see a list entry that equals `n`, we negate `n`. To decide whether to print the current entry `x`, we check if it equals `-n`, which checks that it equals the original `n` and that we've already negated `n` due to an earlier match. Note that since `n` and list entries are positive, there's no way to get `x==-n` before `n` is negated.
Well, actually, instead of negating `n`, it's shorter to bit-complement it to `~n`, which is `-n-1`. To do the conditional complementing, we note that we can convert `[x,~x][b]` to `x^-b` (as in [this tip](https://codegolf.stackexchange.com/a/40795/20260)), using that bitwise xor `^` has `x^0==x` and `x^-1==~x`. So, we do `n^=-(x==n)`.
[Answer]
# JavaScript (ES6), ~~32~~ 30 bytes
Expects `(x)(list)`.
```
x=>a=>a.filter(v=>v^x||a[a=0])
```
[Try it online!](https://tio.run/##ldDRDkMwFAbg@z1FLys5o2Vlu@BFxJLGWCzCgogL7249YpuELl1VW/L79PQhe9mmTfHsjlV9y6Y8nIYwkqrbeVF2WUP7MOqvwzjKWIYssaa0rtq6zOyyvtOcEiIsGieWRcya45A4OewZwhhBQ2gQMGX2Ec7@R0DPAGfYPysNuzBLdFuZqzQOLniwGrVbRO2dm@8tGCjwAmcIwDeoFcFvehcLYH15myeO8/wjxPDd7s5OHpaqRhC@@ogxwLWafxzcOo3J6QU "JavaScript (Node.js) – Try It Online")
### How?
All values `v` that are not equal to `x` are preserved thanks to `v^x`. The first value that is equal to `x` is kept as well because `a[0]` is guaranteed to be a positive integer (except if `a` is empty, but then we don't enter the `.filter()` loop to begin with). For the next values that are equal to `x`, we have `a = 0` and `a[0] === undefined`, so they are rejected. This test doesn't throw an error because Numbers are Objects, so it's legal to access the (non-existent) property `'0'` of `0`.
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
a%(b:c)|a==b=b:filter(/=a)c|1<2=b:a%c
_%x=x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1FVI8kqWbMm0dY2yTbJKi0zpyS1SEPfNlEzucbQxggolKiazBWvWmFb8T83MTNPwVahoCgzr0RBRcHE2EhBVSEaSOmYmpnrGBoY6IDYQDr2PwA "Haskell – Try It Online")
Ungolfed:
```
dedupl v (x:xs)
| x == v = x : filter (/= v) xs
| otherwise = x : dedupl v xs
dedupl _ [] = []
```
---
# [Haskell](https://www.haskell.org/), 40 bytes
This version takes a (negative) predicate for input instead.
```
f%(b:c)|f b=b:f%c|1<2=b:filter f c
_%x=x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P01VI8kqWbMmTSHJNskqTTW5xtDGCMTKzClJLVJIU0jmiletsK34n5uYmadgq1BQlJlXoqCioKFva2JspKmgqhANpHVMzcx1DA0MdEBsIB37HwA "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 60 bytes
Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved 2 bytes thanks to [ErikF](https://codegolf.stackexchange.com/users/79060/erikf)!!!
```
t;f(d,l)int*l;{for(t=0;*l;++l)*l==d&&t++||printf("%d ",*l);}
```
[Try it online!](https://tio.run/##fZNdb4IwFIbv/RUnJJgWasaHgK5j@yGbF4uVhaTDRbgwU347O/SAsNUMie9p3@d8pCn71cd@33WNLJgSmpdV42l5KY4n1uSBxNj3Nfd0nqvlsvH96/XrhEzBHFeBIzzNZdvhBny@lxXji8sC8Ok3oDnUTfi6gxwuQSt/70e0nwjLiUfnjrf@x0smLwz6d4osNiU2FJGIxfzfIjMit2IjMpHe67shIhPzX2ytQqNW9pay13EkkhSpIBB93OuM9QxbE2uOVdApksQka5KEJCXJSDYk27/91XRq42lFZmacYmDxKgDrE8pKHc5IB3IIn6Auvw/HgplK/GFYebSU4PuG40CX4tZYYRFqbvydnNse6MGuLXu8esxVHC8fYJObN42phiH1K4Y7M4Y68xs4L@TWrsI6DIEXB5xHx@FiyON2W1g9gzNvab4Ym3urRqpdtN0P "C (gcc) – Try It Online")
Inputs a number and a pointer to a null terminated array (as there's no way to know the length of an array passed into a function in C) and outputs the filtered array to `stdout`.
### Explanation
```
f(d, // function taking the duplicate number d,
l)int*l;{ // a null terminated array of int l
for( // loop...
t=0; // init test flag t to 0, this will mark the
// 1st (if any) occurance of d
*l; // ...over the array elements
++l) // bumping the array pointer each time
*l==d // if the array element isn't d...
&&t // or it's the 1st time seeing d
++ // unmark t by making it non-zero
||printf("%d ",*l); // ...then print that element
}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18~~ ~~15~~ 10 [bytes](https://github.com/abrudz/SBCS)
Thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) for -8 bytes!!!
```
∊⊢⊆⍨≠∨<\⍤=
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/9/eNujtgnVj3p3AZECBG8FIhBVCyTmKhTk51SmZebkKKTlFykYWugZqBcDxZf8f9TR9ahr0aOutke9Kx51LnjUscIm5vA22/9pQPMe9fY96mp@1LvmUe@WQ@uNH7VNfNQ3NTjIGUiGeHgG/1dQMFVIA5qyRoEYAHIFF0SLjimxGkyhOkwVTInXYWhAmg4UPUAGECFYOPVAlQEdaATUaggkjVFIXNbB1IAxULc5ULelggWQNiPgZJBuuEqoTnMUaIzBMwTTIJ0gGmKniTHIxSDS1AyowsAAzAbR2O1EVgnEAA "APL (Dyalog Unicode) – Try It Online")
Example inputs: left argument `3`, right argument `1 2 3 4 3 4`.
`=` does element-wise not-equal comparison. `=> 0 0 1 0 1 0`
`<\` Scans with less-than. This keeps just the first `1`, all other places are `0`. `=> 0 0 1 0 0 0`
`≠∨` does element-wise *OR* with the `≠` mask. `=> 1 1 1 1 0 1`.
`⊢⊆` partitions the input based on the vector, including positions with positive integers. `=> (1 2 3 4) (4)`
`∊` flattens the nested array. `=> 1 2 3 4 4`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)'s suggestion to use `Ẇ` in place of `W€`
```
Ẇi¦⁹ḟ
```
A full program accepting the list and the value which prints the Jelly representation of a list with all but the first occurrence of the value removed (empty lists print nothing, lists with one element print that element).
**[Try it online!](https://tio.run/##y0rNyan8///hrrbMQ8seNe58uGP@////o02MjXQUTM3MdRQMDQx0FMBcICtW4T@QCQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hrrbMQ8seNe58uGP@/8PL9R/ubFF51LTmxPJHDXP@/4@Ojo7VUTCN5dKJjjZFsEAMNI6hAZwH4kAwMg@hxlBHwUhHwRjIR2MAlRiBVVjqKFjoKJjrKJhBDDcHi5qDhdCQMW5BQwgbrt/EGGiJqRlIxgDoJDAXyIoFM2O5YgE "Jelly – Try It Online").
### How?
```
Ẇi¦⁹ḟ - Link: list, A; value V
¦ - sparse application...
i ⁹ - ...to indices: first occurrence of V in A ([0] if no V found)
W - ...action: all non-empty sublists (since ¦ zips, the element, z, at any
given index of A will be [z])
ḟ - filter discard occurrence of V (leaves the [z] as is)
- implicit print
```
---
I thought `ḟẹḊ¥¦` would work for 5, but it fails with a divide by zero error with `[5,5]` and `5`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~10~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
kȶV©T°
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=a8i2VqlUsA&input=WzQzMiw1NjcsMTAwLDQzMiwxMDBdCjQzMgotUQ)
-3 bytes thanks to caffeine!
```
kȶV©T° :Implicit input of array U and integer V
k :Remove the elements in U that return true
È :When passed through the following function
¶V :Is equal to V?
© :Logical AND with
T° :Postfix increment T (initially 0)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ê0X.;Ï
```
Integer as first input, list as second input.
[Try it online](https://tio.run/##yy9OTMpM/f//cJdBhJ714f7//w0NuKINDQx0TIHQ0ACCkHixAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWCy9EF/w93GUToWR/u/394vc7/6GhDAx0gNtAxBUIgG4UZG6ujEG2qEw2jTeEMHQgTpBmNDdGJZoYR0A4dIx1jHSQSLGGuE22pY6FjrmMGNQUoYK6DDI0xeIYgGqzYxBhoMIgwNTMHuxzEBtJw96D4Bt1vsQA).
**Explanation:**
```
Ê # Check for each value in the second (implicit) input-list whether it's NOT equal
# to the first (implicit) input-integer (1 if NOT equal; 0 if equal)
0X.; # Replace the first 0 with a 1
Ï # And only keep the values in the (implicit) input-list at the truthy (1) indices
# (after which the result is output implicitly)
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + sed, 49 bytes
```
sed "s/\b$1\b/_/;s/\b$1\b \?//g;s/_/$1/"<<<${*:2}
```
[Try it online!](https://tio.run/##S0oszvifVpqXXJKZn6eQpqFZ/b84NUVBqVg/JknFMCZJP17fGsZWiLHX108HcuP1VQz1lWxsbFSqtayMav/XcnGlKZiCMIwE04YGKAwQhcwCShgpGAKxMTIJFDVXsFSwAJJmYM3maNAYg2cIooEqTYyNwNjUDChmYABmA@n/AA "Bash – Try It Online")
Takes the first argument as the duplicate and the rest as the array.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 [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"))
Translation of [Galen Ivanov's J solution](https://codegolf.stackexchange.com/a/212384/43319).
Anonymous tacit infix function, taking number as left argument and list as right argument (though argument order can be switched by changing the `⊢`s into `⊣`s).
```
∊⊢⊆⍨≠∨∘≠⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8f9ahtQvXh6Y/6pvo5qz/q3aVuBSQedS541LtV4VF3i4IGkPGodzOQ1LQF0Z2LgMxahUe9cxUK8nMq0zJzchTS8osUDC30DNSLFYA6/z/q6HrUtehRV9uj3hVRjzpWPOqYEQUU@J8GtOpRb9@jruZHvWse9W45tN74UdtEoM3BQc5AMsTDM/i/goKpQhrQ9DUKxACQK7ggWnRMidVgCtVhqmBKvA5DA9J0oOgBMoAIwcKpB6oM6EAjoFZDIGmMQuKyDqYGjIG6zYG6LRUsgLQZASeDdMNVQnWao0BjDJ4hmAbpBNEQO02MQS4GkaZmQBUGBmA2iMZuJ7JKIAYA "APL (Dyalog Unicode) – Try It Online")
`⊢` on the right argument
…`∘≠` apply nub-sieve (Boolean list with Trues where unique elements occur first), then:
…`∨` element-wise OR that with:
`≠` Boolean list with Trues where elements in the list are different from the number
…`⊆⍨` corresponding to runs of Trues in that, extract runs in:
`⊢` the list
`∊` **ϵ**nlist (flatten)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~26~~ 24 bytes
```
#2/.(a=#)/;a++>#:>Set@$&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lIX08j0VZZU986UVvbTtnKLji1xEFF7X9AUWZeSbSyrl2ag4NyrFpdcHJiXl01V7WpjkJ1ba0OhGGKYOlA2IYGWDg6QAYQwVlgSSOgnKGOkY6xDhIJljEHyljqWOiY65hBDQKJmOsgQ2MMniGIBqs2MQaZDSJNzYDiBgY6IDaQrq3lqv0PAA "Wolfram Language (Mathematica) – Try It Online")
The pattern `(a=#)` to be matched is only evaluated once, at the very start. Then, the condition `a++>#` is only evaluated when the pattern is matched - so `a` will have been incremented on subsequent matches.
[Answer]
# [Red](http://www.red-lang.org), 46 bytes
```
func[n b][try[replace/all find/tail b n n[]]b]
```
[Try it online!](https://tio.run/##ZU9BDoMwDLvzCv8AGAO2PWPXKIcWWg2pKqiCw17fpcA2JJrKduLWUoLp49P0xJl9INrFd@ShmebwpmAmpzqTK@dgB9/nsxocNDw8MWuOdgxGdS9sXzLIqSFRu6j/Crsui3OTWO5PbeYFVApUOODmtKA7bkLNN0gmLY5VnboyMWN9fq0kPEHdiFEU60CYM6YpjNrAIm0UPw "Red – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
f=lambda n,l:l.count(n)>1and f(l.pop(~l[::-1].index(n)),l)or l
```
[Try it online!](https://tio.run/##ZU49b4MwEN35FbcF1AvCUEJrKdnStUs3xADBCBTHthxok6V/nZ5DEpAq2/fufdg@c@1brZJxbLayPFV1CQoll@FBD6r3VbBjpaqh8WVotPF/Zc75mhVhp2pxITtAGWgLcvxpOyngyw6CewC9vToA6JSBratD7wfh2ciO8OYoBImgyT2VxhffJTHK5TwuXhwmvJiCxnY0SePTXAHC6tzqQdZQiRXddglxOQjTw/7zY2@tthwqK8rjmEJewHpH1aM2nfp0IjhTFi05zgqyyO1n90zc1cKLIWcYY4KLOqUewu0UXgb5O75hhpvHRzN1ZobLlfxjzOF00Qn3V18TGoAKphuKRBG6nnAKLg0n/gE "Python 3 – Try It Online")
This function will recursively pop the last instance of the given value until no more than one instance is present. Then it returns the list.
or, for the same byte count
```
lambda n,l:[j for i,j in enumerate(l)if j!=n or i==l.index(n)]
```
[Try it online!](https://tio.run/##ZU47b4MwEN75FdcpRr1GPEpokeiWrl26UQ9QjDA1BjnQJr@enkMSkCLb9933ONv9aag7HU5V@jWpvC3KHDSqJGug6gxIbEBqEHpshckHwZQrK2geUg3WTVO1lboUR6ZdPv3VUgn4NKNIHIDBnCwAzfeQ2joOzN0eeiUJz45GUAgduW3eM/GbE6NclgT80WKY8DnYG6kHVjH6mYuwOdTdqEooxIambUIcv0U/wP7jfW9MZxIojMh/pggyDk9vVB1qo7mPZoIL9b01x0VB37P71t0SF5U7AWQ@Bhjiqs6pq3A@3Ikhe8UXjHF3fWih1oxxvcI75lucB61wufU5pA9QwWhHEc9D2xPOwbVhxX8 "Python 3 – Try It Online")
This is just a simple filter.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ʒÊD¾ms_½
```
[Try it online!](https://tio.run/##yy9OTMpM/f//1KTDXS6H9uUWxx/a@/9/tKmOAhAZGkAwMi@Wy9AAAA "05AB1E – Try It Online")
**Commented**:
```
ʒ # filter the first input on ...
Ê # not equal to the second input (n)?
D # duplicate this value
¾ # push the counter variable initially 0
m # power (value != n)**(counter)
# this is only 0 if value==n and counter is positive
s # swap to (value != n)
_ # negate this
½ # increment the counter variable if this is truthy (value == n)
```
[Answer]
# [Perl 5](https://www.perl.org/), 36 bytes
```
sub{$n=pop;$i=0;grep$n-$_||!$i++,@_}
```
[Try it online!](https://tio.run/##jVJta8IwEP6eX5GVY1S8QKuL3SwZ/QP7tm8iBVkqBU1LW2Gi/vYuSX1JtcL6csk9z93lyHOlrDa83dWSfsu6mc@/ikrGZLunkIm23q0OoERZlDHkIojXlSxBMUiPxxfIx2NM0lMbk6yofEL1s6Ac6WJJxaexS3RA3qH8HsYBIgx6DA5xqDf6u@6usWfUSZnojBAnOEXHdvEXwP5OSqRTPvAdI5xd2nDcXliE7jt98EKzdiUMcH/S29S0Zyyf6eAgQLPXa5fiEhYcbDF63uToYJft3geFsMnrBkH@liORQBqfKZqsi0a8QuYn5wg1unKQq6wQnhKgNGBo0UVpTx9Jqck1BbwuJa99z7roJeYkD20FXfBEfgol00bPWa7WccvNkDAzKoTbAWB2DqyDNzcMXB9vyOMIsP4IkMmg8OxBeBL1ro71btKQ/xSZ9UQmWrwn0rIBaf8A "Perl 5 – Try It Online")
Pop last input value from @\_ into $n. The remaining @\_ is the input list. Filter (grep) @\_ for the values that either isn't equal to $n (`$n-$_` is truthy when $n and current list value $\_ is different) or is the first equal to $n since `!$i++` is truthy for the first and not for the rest.
[Answer]
# [J](http://jsoftware.com/), ~~15~~ 10 bytes
-5 bytes thanks to xash!
```
]#~=<:~:@]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Y5XrbG2s6qwcYv9rcilwpSZn5CsoKJgqpCkYqBggc3VMkXmmcK6hAYirgM4FMYAIzoJpNgJKGwJJY2QSJmkOlLRUsADSZnADwYLmKNAYg2cIoiEaTIxBVoBIUzOghIEBmA2k/wMA "J – Try It Online")
## My initial solution:
# [J](http://jsoftware.com/), 15 bytes
```
[#~~:+i.@#@[=i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o5Xr6qy0M/UclB2ibTP1/mtyKXClJmfkKygomCqk1SkYqBig8HVMUbimcL6hAZivgMEHsYAIzoLpNwLJGwIpY2QSJmsOkrVUsAAyzOBmQkTNUaAxBs8QREN0mBiDbQFRpmZAGQMDMBtI/wcA "J – Try It Online")
[Answer]
# APL+WIN, 19 bytes
Prompts for vector followed by element to be removed:
```
((v≠n)+<\v=n←⎕)/v←⎕
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5raJQ96lyQp6ltE1NmmwcUB8pr6pdBGP@BSrj@p3E96l3DZcqVBsRgUgFBGxpAGAqGBiAEZ0EkDBWMFIwVkEguI6CopYKFgrmCGVC3OZBnroAMjTF4hiAarNLE2EjB1AwoYmCgAGIDaZAYFwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~13~~ 12 bytes
```
F+ṀΓ·:f≠⁰↕≠⁰
```
[Try it online!](https://tio.run/##yygtzv7/30374c6Gc5MPbbdKe9S54FHjhkdtUyGM////Gxr8jzbVMdUxNAAhOCsWAA "Husk – Try It Online")
user's answer.(-3 bytes, then -1 byte.)
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
J²fI§e←of≠²→↕≠²⁰
```
[Try it online!](https://tio.run/##yygtzv7/3@vQpjTPQ8tTH7VNyE971Lng0KZHbZMetU2FMBs3/P//3@R/tLkOMjTG4BmC6FgA "Husk – Try It Online")
~~Can probably be shortened with `Γ`.~~
There may be an extremely short solution with `ü` as well.[user's answer](https://codegolf.stackexchange.com/a/212417/80214)
+2 bytes after supporting numbers not in the list.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 42 bytes
```
a=>b=>a.Where((x,i)=>x!=b|i==a.IndexOf(b))
```
[Try it online!](https://tio.run/##jY7BCoJAFEX3fsXL1QxMogtXOrOJAkNo6VrtVQ/sCc5IQvXtpi5s0yK4i3s5cLi13daWxkPPdZqTdSmxMwqWPVUF2Z77O3Zl1eDCjIHLBEHDWGpTaVMGxQ07FGJQJLUZNrp6kdZlkPEZh9NFVFKOieftWrZtg0HRkcOcGIV1HfE1OLbEwle@mr2C8QHrESHhGatYReGctcFbiiiUUiZ/WOG3Fr6S8QM "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), ~~62~~ ~~61~~ 58 bytes
```
a=>s=>{val(c,d)=s splitAt s.indexOf(a)+1;c++d.filter(a!=)}
```
[Try it online!](https://tio.run/##fY9BT4MwFMfvfIrnrQ3PDYYMnSnJjh6MB48Lh0rLgiEV18YsWfbZsR2TlI0JlP55/f0erS55w7uvj09ZGnjltQK5N1IJDeu2PQQAP7yB7QpelAGWw7v83thYjHPHWa5ZfrAsKVFQpkG3TW3WBvSsVkLu3yrCaRg/l2EoZlXdGLkj/I7RYwf2ErICC5z@gqBXQ2sKDLbWJJoGDmx3tTKNIhVJ0UGEUgrzOdznsCmmibRHHJHeQjD1@lxRcTSJ4X8g2myfIY3F89Klv@j1GBeYoPf25L/qaVz6We8/4SNmuBztdqjdcDL07@TqK3az189VJ/fwkJxP4UK6tGYUoct29nx/1Y4iCI7dLw "Scala – Try It Online")
* Thanks to [Galen](https://codegolf.stackexchange.com/users/75681/galen-ivanov) for -1 character
* Thanks to [user](https://codegolf.stackexchange.com/users/95792/user) for -3 characters
[Answer]
# [Haskell](https://www.haskell.org/), 55 bytes
```
f n=foldl(\a x->if x==n&&x`elem`a then a else a++[x])[]
```
[Try it online!](https://tio.run/##ZVFha8MgEP0rRxgl1iskzdJsMLs/sMFgH42sQg0pM7ZEx/Jh/z3TrJiM4nn33vOdB9pK@6m0HscGDGvO@qjTWsKw2Z8aGBgzq9VwUFp1BwmuVQYkKG0VSEr5IAgXYydPBlgnL68fcPly765/McCTJoWE0tS2528whNJkpnqiBPa1iVoftNrAGt6kter4PNvvoGfMTT1r3/GTGtToyNOGpyVy4YNgQKUI@4oxsjyLFJcC@uojIhHVq2@LPMctFrjIYtamHXwV8kd8wAp305QZ/51VuFzFDctDFcFXzHfeF356SOXOO7IMA/ZV/FeDQgRq5fwb@Q8ELcZf "Haskell – Try It Online")
* Previous answer was complicated and not so good so I decided to try a more expressive approach inspired by @Caagr98 answer, mine is still longer but I feel better now =)
---
# Previous 72 bytes
```
g b n(h:t)
|h/=n=h:g b n t
|b>0=g 1n t
|1>0=h:g 1n t
g b n _=[]
f=g 0
```
[Try it online!](https://tio.run/##ZZHfSsMwFMbv9xSH4kWyHrFd7TqHmS@gIHiZhdFhuw6zONqIN3v3epKOtEPy53zfL18SSJqy@6q07vsD7MGwZm35DC7NgzCiWXsGlsB@k4gDpINJybhFb4fMTkg1qymS9KfyaECcyvPbDs4/9sO2rwZkVDOI4ph1zfcvGB7H0Wi1txw2WxNY69jWwBzey66rPl/G@B20Qli/Z047LsygRsuf7yXLUSrqHJ3KlRtXjcGlSbA4BUiVelAq0GtugTLFBWY4mdXI/HC5AuUTrrDApb9l1MNagdOW/XOpq8rlsvHMx4xud1O@pESSoNNU1S11hCvUlaU3qulftOr/AA "Haskell – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~50~~ 31 bytes
```
param($a,$b)$b|?{$_-$a-or!$o++}
```
-19 bytes thanks to mazzy!
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9vyCxKDFXQyVRRyVJUyWpxr5aJV5XJVE3v0hRJV9bu/Z/LReXhppKmoKhgYKpjqmOoQEIwVmaCrpZ@Zl5Cuo66lB1RgqGOkY6xjpIJKYicwVzHWRojMEzBNFIGv8DAA "PowerShell Core – Try It Online")
Iterates on the array passed as the second parameter and ignores the duplicate occurrence of the first parameter.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 117 113 93 bytes
```
function x(i,j){var d,e,o=[];for(x in i){e=i[x]==j;!(e&&d)?o.push(i[x]):0;e?d=1:0;}return o;}
```
[Try it online!](https://tio.run/##FchNCoMwEEDhq6QbSWAqFn8WDcGDBBfBjG1EMpKoBMSzp5a3@ODN5jBxDG7dnp4s5jztftwceZa4g1mchwnMAgIpPciJAk/MeebEicrpNCg1ywfHorCip3Ld45f/t3hXEnurXrdXwG0PnpG88kg@0oLlQh@euK5raFvo7poGugE6IWT@AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IΦη∨⁻ιθ⁼κ⌕ηι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zpyS1SCNDR8G/SMM3M6@0WCNTR6FQU0fBtbA0MadYI1tHwS0zLwWkIlMTDKz//4820ok21DHSMdZBImNj/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
η Input list
Φ Filtered where
ι Current element
⁻ Subtract (i.e. does not equal)
θ Input integer
∨ Logical Or
κ Current index
⁼ Equals
⌕ First index of
ι Current element in
η Input list
I Cast to string
Implicitly print
```
The last character could also be `θ` of course since the two variables are equal at that point.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~55~~ 52 bytes
Thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for -3 bytes!
Output is newline-separated.
```
n,l=input()
x=1
for d in l:
if x|d-n:print d;x*=d-n
```
[Try it online!](https://tio.run/##ZU1Lb8IwDL77V/iWMTlSH5RuTL2tHOHCbcoB2iCiVWkVBVEk/nuxYZrQpljfw/bnDJd47H02NX1rsUKl1OSpq5wfTvFlBmOVwqEP2KLz2C0B3QHHa6v9cgjOR2w/xteK7cRBgPPRdRa34WR5E2O4CCHa0TYoH9zdI6i0rtefWiuQeWOHiPVmVYfQh0doH@zueyoIvwwIFj9ELNLkryIWXL/KQMaDlDLK6QkNlNx@pzcqaSF5sSU9v/yfS4UNzHM5KVgsuJkkJJrZ3AA "Python 2 – Try It Online")
[Answer]
# [K (Kona)](https://github.com/kevinlawler/kona), 21 bytes
```
{y@&(~x=y)+(!#y)=y?x}
```
[Try it online!](https://tio.run/##y9bNzs9L/P8/zaq60kFNo67CtlJTW0NRuVLTttK@ovZ/WrSptYZmLBeI1jEF0QoKptamUKahgbWpAjITSIEQnAXRYGRtqGCkYKyAREIkzK0tFSwUzBXMoIYABcwVkKExBs8QRIMUmxgbWQOxgqkZUNDAQAHEBtKx/wE "K (Kona) – Try It Online")
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 28 bytes
```
[@y:0@b[b\y=:b+@b*¬]"!keep]
```
[Try it online!](https://tio.run/##bVBLDoIwFNxzitFNQQMpIKAkmt4DWVDtQomFAC64k6fwYrWlakg0r5k3v3bRfqhOtTgrVbAxp4wX/Djuc75mfPV8lMtFLURbKpYPoh8cx3UAN4EGz/vSZM7xViH9p6CJPl9m08jcDBEhxgxtlplshy0ypJ/XJi/DfOIfFZpt@5s4spCk2qcUhuutUw@FbgRBwKquA5OmLkECAqM70XYgvn@wUsL8wuR6IHquzUWiuQ9wStyqVr0A "Stacked – Try It Online")
## Explanation
```
[@y:0@b[b\y=:b+@b*¬]"!keep]
[ ] anonymous function (expects 2 args)
@y save top as y
0@b initialize b = 0
: [ ]"! for each element E in the input array:
b\ save the current value of b for later computation
y= b+@b b = max(b, y == E)
b y=: *¬ not both (old b) and (y == E) are true
for y != E, and for the first y == E, this is 1, else 0
this generates a mask of 1s and 0s
keep keep only the elements in the input which correspond to a 1
```
## Other Solutions
**51 bytes:** `[@y()@z{e:[z e push][z y∈¬*]$!e y=ifelse}[[email protected]](/cdn-cgi/l/email-protection)]`
**41 bytes:** `[@y::inits[:y index\#'1-=]map\y neq+keep]`
**36 bytes:** `[@y:0@b[b\:y=b\max@b y=*¬]map keep]`
**33 bytes:** `[@y:0@b[b\:y=b+@b y=*¬]map keep]`
[Answer]
# PHP 63 Bytes
Number provided in $n, list provided in $a,
```
$p=explode($n,$a,2);echo$p[0].$n.str_replace("$n,", '', $p[1]);
```
# Ungolfed:
```
$p = explode($n,$a,2);
echo $p[0].$n.str_replace("$n,", '', $p[1]);
```
e.g.
```
$n=432;
$a="[432,567,100,432,100]";
$p = explode($n,$a,2);
echo $p[0].$n.str_replace("$n,", '', $p[1]);
```
(I'm unsure if it's ok not to count the input into the bytes, or the opening '<?php' for that matter...)
] |
[Question]
[
### Introduction:
A Dutch BSN (BurgerServiceNummer) is valid when it complies to the following rules:
* It only contains digits.
* The length should be either 8 or 9 in length.
* When the digits are indexed as `A` through `I`, the result of the following sum: `9xA + 8xB + 7xC + 6xD + 5xE + 4xF + 3xG + 2xH + -1xI` (NOTE the -1 instead of 1!) should be divisible by 11, and should not be 0.
### Challenge:
**Input:** A string or char-array representing the BSN.
**Output:** A [truthy or falsey](https://codegolf.meta.stackexchange.com/a/2194/52210) result whether the input is a valid BSN.
### Challenge Rules:
* The input format should be a string or char-array. You are not allowed to use an int-array of digits, or a (possibly octal) number. (You are allowed to convert it to an int-array of digits yourself, though, but not directly as argument.)
* Despite the restriction on the input above, you can assume all test cases will contain one or more digits (`[0-9]+`)
* Regarding the BSN with length 8 instead of 9, the Dutch Wikipedia states the following: "*For the eleven-test and for other practical uses, a leading zero is added to make the number of length 9.*" ([source](https://nl.wikipedia.org/wiki/Burgerservicenummer#cite_note-2))
### 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, 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.
* Also, please add an explanation if necessary.
### Test cases:
```
// Truthy test cases:
111222333
123456782
232262536
010464554
10464554
44016773
// Falsey test cases:
000000000
192837465
247594057
88888888
73
3112223342
000000012
```
[Answer]
# JavaScript (ES6) 57
Input as an array of chars. `reduceRight` saves the day!
```
s=>!(i=1,t=s.reduceRight((t,v)=>t-v*++i),!t|t%11|(i|1)-9)
```
**Test**
```
F=
s=>!(i=1,t=s.reduceRight((t,v)=>t-v*++i),!t|t%11|(i|1)-9)
;['111222333','123456782','232262536','010464554','10464554','44016773']
.forEach(t=>{
var r=F([...t]);console.log(t,r)
})
;['000000000','192837465','247594057','88888888','73','3112223342','3112223342']
.forEach(t=>{
var r=F([...t]);console.log(t,r)
})
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~23~~ 21 bytes
```
`()DgLR*OD11Ö89¹gåP0Ê
```
[Try it online!](http://05ab1e.tryitonline.net/#code=YCgpRGdMUipPRDExw5Y4OcK5Z8OlUDDDig&input=MTA0NjQ1NTQ) or as a [Test suite](http://05ab1e.tryitonline.net/#code=fHZ5YCgpRGdMUipPRDExw5Y4OXlnw6VQMMOKLA&input=MTExMjIyMzMzCjEyMzQ1Njc4MgoyMzIyNjI1MzYKMDEwNDY0NTU0CjEwNDY0NTU0CjQ0MDE2NzczCjAwMDAwMDAwMAoxOTI4Mzc0NjUKMjQ3NTk0MDU3Cjg4ODg4ODg4CjczCjMxMTIyMjMzNDI)
**Explanation**
```
` # push input as individual chars onto stack
( # negate top value
) # wrap in list
DgLR # range [len(input) ... 1]
*O # multiply with list of digits and sum
D11Ö # is evenly divisible by 11
89¹gå # len(input) is 8 or 9
P # product of sum/divisible by 11/len in (8,9)
0Ê # not equal to 0
```
[Answer]
## R, 86 67 bytes
Edit: Thanks to Jarko Dubbeldam for suggesting the dot product!
```
l=length(x<-scan(,""));s=as.double(x)%*%c(l:2,-1);!s%%11&s&l>7&l<10
```
Reads input from stdin and store as an array/vector of characters. Subsequently convert to numeric,multiply with the vector `9...2,-1` and check all conditions.
[Answer]
## JavaScript (ES6), ~~61~~ ~~60~~ ~~59~~ 58 bytes
Takes an array of chars as input. Returns `false` / `true`.
```
a=>!(a.map(c=>s-=--k?-c*k-c:c,k=a.length&9,s=0)|!s|k|s%11)
```
### Test cases
```
let f =
a=>!(a.map(c=>s-=--k?-c*k-c:c,k=a.length&9,s=0)|!s|k|s%11)
// truthy
console.log(f([..."111222333"]));
console.log(f([..."123456782"]));
console.log(f([..."232262536"]));
console.log(f([..."010464554"]));
console.log(f([..."10464554"]));
console.log(f([..."44016773"]));
// falsy
console.log(f([..."000000000"]));
console.log(f([..."192837465"]));
console.log(f([..."247594057"]));
console.log(f([..."88888888"]));
console.log(f([..."73"]));
console.log(f([..."3112223342"]));
```
[Answer]
## C, ~~112~~ ~~101~~ ~~96~~ ~~98~~ 104 bytes
*Thanks to @MartinEnder for saving ~~5~~ 3 bytes ~~while fixing my code~~!*
```
j,i,k,l;f(char*s){l=strlen(s);for(i=l,j=k=0;j<l;)k+=(s[j++]-48)*(i>1?i--:-1);return!(k%11)&&k&&(l^8)<2;}
```
Returns 0 if invalid, 1 if valid. [Try it online!](https://tio.run/nexus/c-gcc#DcVLDoIwEADQvbeQhGYG2sQpLohD9SBGE6IQ@rGaFleEs6Nv8zYnrfQy8AiPqU9VxiWYPKcwRMjI4zuBNUE6482BXRcYfW0gX11d39SxxQrsmS5WqZMi5DTM3xT34EsiFMILAeHeYqd53b16GwGXT7JxHqEon4X8R0Ra66ZpCkRet@0H "C (gcc) – TIO Nexus")
[Answer]
# R, ~~95~~ ~~79~~ 93 bytes
```
function(x){y=as.double(el(strsplit(x,"")));z=y%*%c((q<-length(y)):2,-1);(z&!z%%11&q>7&q<10)}
```
Unnamed function that takes a string as argument. At first I overread the requirement of having a string as input instead of a number, but that's good, because it saves some bytes on conversion.
I am not sure how to interpret the array of characters, but if that means that you can use a vector of stringed digits `"1" "2" "3" "4" etc` as input, it becomes a bit shorter even:
```
function(x){y=as.double(x);z=y%*%c((q<-length(y)):2,-1);(z&!z%%11&q>7&q<10)}
```
Splits x into a numeric vector, then appends a 0 if length is 8, then calculates the dotproduct of vector y and `c(9,8,7,6,5,4,3,2,-1)`. Tests if the result is both nonzero and divisible by 11.
Saved 16 bytes thanks to the logic by @Emigna, implicitly appending the 0 in the creation of the vector `c(length(x):2,-1)`.
Forgot to add check for length 8/9, so +14 bytes :(
[Answer]
## Perl, 58 bytes (52 + 6)
```
@N=(-1,2..9);$r+=$_*shift@N for reverse@F;$_=$r&&/^\d{8,9}$/&&!($r%11)
```
Run with
```
perl -F// -lapE
```
Input passed through `STDIN`:
***Usage***
```
echo 232262536 | perl -F// -lapE '@N=(-1,2..9);$r+=$_*shift@N for reverse@F;$_=$r&&/^\d{8,9}$/&&!($r%11)'
```
---
Outputs `1` for as the truthy value, `0` or nothing for falsey values.
[Answer]
# C++14, ~~107~~ 106 bytes
-1 byte for `int` instead of `auto` in for loop.
As unnamed lambda returning via reference parameter. Requires input to be `std::string` or a container of char, like `vector<char>`.
```
[](auto c,int&r){int i=c.size();r=7<i&&i<10?-2*c.back()+96:~1<<9;for(int x:c)r+=(x-48)*i--;r=r%11<1&&r>0;}
```
Ungolfed and usage:
```
#include<iostream>
#include<string>
auto f=
[](auto c, int& r){
int i = c.size();
//if the size is correct, init r to -2*I so we can add I safely later
//otherwise such a big negative number, that the final test fails
r = 7<i && i<10 ? -2*c.back()+96 : ~1<<9;
for (auto x:c)
r += (x-48)*i--;
r = r%11<1 && r>0;
}
;
using namespace std;
using namespace std::literals;
int main(){
int r;
f("111222333"s,r); std::cout << r << std::endl;
f("123456782"s,r); std::cout << r << std::endl;
f("010464554"s,r); std::cout << r << std::endl;
f("10464554"s,r); std::cout << r << std::endl;
f("44016773"s,r); std::cout << r << std::endl;
std::cout << std::endl;
f("000000000"s,r); std::cout << r << std::endl;
f("192837465"s,r); std::cout << r << std::endl;
f("73"s,r); std::cout << r << std::endl;
f("88888888"s,r); std::cout << r << std::endl;
f("3112222342"s,r); std::cout << r << std::endl;
std::cout << std::endl;
f("99999999"s,r); std::cout << r << std::endl;
f("999999999"s,r); std::cout << r << std::endl;
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
V€U×JN1¦µL:2=4×Sµ11ḍa
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=VuKCrFXDl0pOMcKmwrVMOjI9NMOXU8K1MTHhuI1h&input=&args=IjExMTIyMjMzMyI)** or [run all test cases](http://jelly.tryitonline.net/#code=VuKCrFXDl0pOMcKmwrVMOjI9NMOXU8K1MTHhuI1hCsW8w4figqxL4oKsWQ&input=&args=WyIxMTEyMjIzMzMiLCIxMjM0NTY3ODIiLCIyMzIyNjI1MzYiLCIwMTA0NjQ1NTQiLCIxMDQ2NDU1NCIsIjQ0MDE2NzczIiwiMDAwMDAwMDAwIiwiMTkyODM3NDY1IiwiMjQ3NTk0MDU3IiwiODg4ODg4ODgiLCI3MyIsIjMxMTIyMjMzNDIiXQ)
Truthy return values are non-zero (and are, in fact, the multiple of 11 sum).
### How?
```
V€U×JN1¦µL:2=4×Sµ11ḍa - Main link: string of digits e.g. "111222333"
V€ - eval each - effectively cast each to an integer (keeps leading zeros)
U - upend e.g. [ 3, 3, 3, 2, 2, 2, 1, 1, 1]
J - range(length) e.g. [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
× - multiply e.g. [ 3, 6, 9, 8,10,12, 7, 8, 9]
1¦ - apply to index 1 (first element)
N - negate e.g. [-3, 6, 9, 8,10,12, 7, 8, 9]
µ - monadic chain separation e.g. z=[-3, 6, 9, 8,10,12, 7, 8, 9]
L - length(z) e.g. 9
:2 - integer divide by 2 e.g. 4
=4 - equals 4? e.g. 1
S - sum(z) e.g. 66
× - multiply e.g. 66
µ - monadic chain separation e.g. z=66
11ḍ - divides(11, z) e.g. 1
a - and z (for z=0 case) e.g. 66 (truthy)
```
[Answer]
# Befunge, 72 bytes
```
>+~>:0`v
^1\-*68_\2/4-!00p*8>1-10p\910gv
@.!+!\%+56:*g00$ _^#!:g01+*-<<
```
[Try it online!](http://befunge.tryitonline.net/#code=Pit-PjowYHYKXjFcLSo2OF9cMi80LSEwMHAqOD4xLTEwcFw5MTBndgpALiErIVwlKzU2OipnMDAkICBfXiMhOmcwMSsqLTw8&input=MTExMjIyMzMz)
**Explanation**
```
>+~>:0`v Read characters from stdin until EOF, converting each digit into
^1\-*68_ a number on the stack, and keeping a count of the characters read.
\2/4-!00p Save !(count/2-4), which is only true for valid lengths (8 and 9).
* Multiply the EOF (-1) with the final digit; this is the initial total.
8>1-10p\910gv Loop over the remaining 8 digits, multiplying each of them by 9-i and
^#!:g01+*-<< add to the total; i goes from 7 down to 0, so 9-i goes from 2 to 9.
$ Drop the loop counter.
*g00 Multiply total by the length calculation (invalid lengths become 0).
%+65: Make a copy of the total, and calculate modulo 11.
!\ Boolean not the other copy to check for zero.
!+ !(total%11 + !(total)) is only true for non-zero multiples of 11.
@. Output the result and exit.
```
[Answer]
# MATL, 36 bytes
Not the [longest MATL program I've ever written](https://codegolf.stackexchange.com/a/97341/32352), but I like how `if`/`else` statements get very lengthy very quickly in golfing languages. I feel that this solution may not be optimal in MATL, but as of yet I can't optimize it any further. I'm thinking of using the double 0 somewhere, and maybe cut down on the `t`'s everywhere.
```
48-tn8=?0wh]tn9=?P[a2:9]*st11\~Y&}x0
```
[Try it online!](http://matl.tryitonline.net/#code=NDgtdG44PT8wd2hddG45PT9QW2EyOjldKnN0MTFcflkmfXgw&input=JzExMTIyMjMzMyc) Explanation:
```
48- % Subtract 48 (ASCII '0')
tn % Duplicate. Get length.
8=? % If length equals 8
0wh % Prepend 0 to the duplicate
] % End if.
t % Duplicate again.
n9=? % If length equals 9.
P % Reverse the duplicate
[a2:9]* % Element-wise product with [-1 2 ... 9]
s % Sum
t11\ % Duplicate sum, modulus 11
~Y& % Result on stack: modulus==0 AND sum!=0
} % Else
x0 % Remove the duplicate. Put 0 on stack.
% Display implicitly.
```
[Answer]
## PowerShell v2+, 96 bytes
```
param($n)$i=8-($n.count-eq8);!(($b=($n|%{(-"$_",(($i+1)*+"$_"))[!!$i--]})-join'+'|iex)%11)-and$b
```
OK, I'll admit, this looks like a complete mess. And it kinda is. But, bear with me and we'll get through it.
We take input `$n` (as a `char`-array) and set `$i` equal to `8` minus a Boolean value for whether there are 8 items in `$n`. Meaning, if there are 8 items, then `$i` would be `7`.
The next section combines the calculation with our output. Working from the inside, we loop through `$n` with `$n|%{...}`. Each iteration, we use a pseudo-ternary to come up with one of two results -- either `-"$_"` or `(($i+1)*+"$_")`. The index is based on whether `$i` is `0` or not (i.e., we've hit the `-1xI` case from the challenge equation), which gets post-decremented for the next go-round. Those are all gathered up in parens and `-join`ed together with `+`. For example, with input `111222333` at this point we'd have `9+8+7+12+10+8+9+6+-3`. That is piped to `iex` (short for `Invoke-Expression` and similar to `eval`) before being stored into `$b`. We then take that `%11` and perform a Boolean-not `!(...)` on that (i.e., so if it is divisible by 11, this portion is `$true`). That's coupled with `-and$b` to ensure that `$b` is non-zero. That Boolean result is left on the pipeline and output is implicit.
### Examples
```
PS C:\Tools\Scripts\golfing> 111222333,123456782,232262536,010464554,10464554,44016773|%{"$_ -> "+(.\dutch-burgerservicenummer.ps1 ([char[]]"$_"))}
111222333 -> True
123456782 -> True
232262536 -> True
10464554 -> True
10464554 -> True
44016773 -> True
PS C:\Tools\Scripts\golfing> 000000000,192837465,247594057,88888888,73,3112223342,000000012|%{"$_ -> "+(.\dutch-burgerservicenummer.ps1 ([char[]]"$_"))}
0 -> False
192837465 -> False
247594057 -> False
88888888 -> False
73 -> False
3112223342 -> False
12 -> False
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 26 bytes
```
!UGg*R!s0&)s-t11\~Gn8-tg=v
```
The result is a non-empty column vector, which is [truthy iff all its entries are nonzero](https://codegolf.stackexchange.com/a/95057/36398).
[Try it online!](http://matl.tryitonline.net/#code=IVVHZypSIXMwJilzLXQxMVx-R244LXRnPXY&input=JzExMTIyMjMzMyc)
Or [verify all test cases](http://matl.tryitonline.net/#code=YFhLCiFVS2cqUiFzMCYpcy10MTFcfktuOC10Zz12CiFEVA&input=JzExMTIyMjMzMycKJzEyMzQ1Njc4MicKJzIzMjI2MjUzNicKJzAxMDQ2NDU1NCcKJzEwNDY0NTU0JwonNDQwMTY3NzMnCicwMDAwMDAwMDAnCicxOTI4Mzc0NjUnCicyNDc1OTQwNTcnCic4ODg4ODg4OCcKJzczJwonMzExMjIyMzM0MicKJzAwMDAwMDAxMic) with each result on a different line.
### Explanation
This tests the three conditions in the following order:
1. Weighted sum is nonzero;
2. Weighted sum is dividible by 11;
3. Length is 8 or 9.
Consider input `'8925'` for the explanation. `;` is the row separator for matrices.
```
! % Implicit input. Transpose into a column vecvtor
% STACK: ['8'; '9'; '2'; '5']
U % Convert each digit to number
% STACK: [8; 9; 2; 5]
Gg % Push a row array of ones as long as the input
% STACK: [8; 9; 2; 5], [1 1 1 1]
* % Multiply, element-wise with broadcast
% STACK: [8 8 8 8; 9 9 9 9; 2 2 2 2; 5 5 5 5]
R % Upper triangular part
% STACK: [8 8 8 8; 0 9 9 9; 0 0 2 2; 0 0 0 5]
! % Transpose
% STACK: [8 0 0 0;8 9 0 0;8 9 2 0;8 9 2 5]
s % Sum of each column. This multiplies last element by 1, second-last by 2 etc
% STACK: [32 27 4 5]
0&) % Split into last element and remaining elements
% STACK: 5, [32 27 4]
s % Sum of array
% STACK: 5, 63
- % Subtract
% STACK: -58. This is the result of condition 1
t11\ % Duplicate. Modulo 11
% STACK: -58, 8
~ % Logical negation
% STACK: -58, 0. This gives condition 2
Gn % Push numnber of entries in the input
% STACK: -58, 0, 4
8- % Subtract 8. For valid lengths (8 or 9) this gives 0 or 1
% STACK: -58, 0, -4
tg % Duplicate. Convert to logical: set nonzero values to 1
% STACK: -58, 0, -4, 1
= % 1 if equal, 0 otherwise. Lenghts 8 or 9 will give 1. This is condition 3
% STACK: -58, 0, 0
v % Vertically concatenate the entire stack. This is truthy iff all values
% are non-zero. Implicitly display
% STACK: [-58; 0; 0]
```
[Answer]
# Haskell, ~~116~~ ~~112~~ 102 bytes
```
f x=div(length x)2==4&&g x>0&&h x
h=((==0).(`mod`11)).g
g=sum.zipWith(*)(-1:[2..]).map(read.(:[])).reverse
```
`g` counts the sum used in the eleven-proef of `h`, while `f` also checks for the correct length and that the eleven-proef is not 0. Especially the checks of `f` take a lot of bytes.
EDIT: saved 10 bytes thanks to Lynn and `div` rounding down.
[Answer]
## PHP ~~139~~ 128 bytes
```
$u=-1;$i=$argv[1];while($u<=strlen($i)){$c+=($u*(substr($i,-(abs($u)),1)));$u +=$u<0?3:1;}echo($c>0&&!($c%11)&&$u>8&&$u<11?1:0);
```
Could not get the CLI to just echo the true of false. Had to make do it this way. Any ideas?
128 bytes: Turned "true" and "false" to 1 and 0.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~111~~ ~~110~~ 104 bytes
*-1 byte thanks to [@Kevin-cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)*
*-6 bytes by reading the rules (yay)*
```
lambda s:len(s)in(8,9)and not(x:=sum(a:=[*map(lambda n,m:int(n)*m,s[::-1],range(1,10))])-2*a[0])%11and x
```
[Try it online!](https://tio.run/##fY/NboMwEITveQpfEDYikX8xscSpj0E5uAohSOAg20jJ09PYuFXbQ/c0K83sfrM8/e1uWL3YbWjet0nPHxcNnJp6Ax0aDazLM9LmAszdw4dq3DpDrZq2mPUCk9uUsxqNhwYVc@lapY6kK602Qw9JSTBCHTrSQre4Qxkh4dhju94t8Hb1tycYDWhzQgillDGWlyAnlHFRyZqGhTJKKypYFRZMMK@4EDzafmjOMamkZHmnDuA12rneejDA/Ql6Wd6060HmwGWMbYDt/WpNojjlIEsy5hcbGn3H0eEQiK96cn0ixl8TUc60ZpJXIhJzKc4cCxmWOk3QMrZjqSqP9dIRQv@QB8IB7g//od8NkX6Xv@hTHG2f "Python 3.8 (pre-release) – Try It Online")
There's probably more golfing to do, but this is what I have for now.
[Answer]
## Python 2, 102 bytes
```
def f(i):S=sum(a*b for a,b in zip([-1]+range(2,10),map(int,i)[::-1]));return(7<len(i)<10)*(S%11<1)*S>0
```
[Answer]
# Python 2, 96 bytes
```
def g(s):u=7<len(s)<10and sum(x*int(('0'+s)[-x])for x in range(2,10))-int(s[-1]);print(u%11<1)*u
```
Takes a string as input. The function adds a `'0'` to the front of the string whether it needs it or not, and uses Python's negative indices to add elements, starting from the end of the string and working back-to-front.
The `-1xI` is handled separately, using a second call to `int()`. I couldn't figure out how to avoid this without costing more bytes than I saved.
`def g(s):u=7<len(s)<10and sum(x*int(('0'+s)[-x])for x in range(10))-2*int(s[-1]);print(u%11<1)*u` would work just as well, since it would add `1` times `s[-1]` but then subtract it twice, and it would also add `0` times (something) which of course wouldn't affect the sum.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 345 Bytes
Includes +3 for `-a`
```
([]){{}({}[((((()()()){}){}){}){}]<>)<>([])}{}<>([][(()()()()){}]){({}[()]){([]){{}{}([])}}}{}([{}])({}({}){})({}({})({}){})({}(({}){}){})({}(({})({})){}{})({}(({})({}){}){})({}((({}))({}){}){}{})({}((({}){}){}){})(({}(((({})){}){}){}{}{}<(((()()())()){}{})>)){{}({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}[{}]<(())>){((<{}{}>))}{}(<()>)}{}
```
Truthy is 1, Falsy has a 0 on the top of the stack.
[Try it Online!](http://brain-flak.tryitonline.net/#code=KFtdKXt7fSh7fVsoKCgoKCkoKSgpKXt9KXt9KXt9KXt9XTw-KTw-KFtdKX17fTw-KFtdWygoKSgpKCkoKSl7fV0peyh7fVsoKV0peyhbXSl7e317fShbXSl9fX17fShbe31dKSh7fSh7fSl7fSkoe30oe30pKHt9KXt9KSh7fSgoe30pe30pe30pKHt9KCh7fSkoe30pKXt9e30pKHt9KCh7fSkoe30pe30pe30pKHt9KCgoe30pKSh7fSl7fSl7fXt9KSh7fSgoKHt9KXt9KXt9KXt9KSgoe30oKCgoe30pKXt9KXt9KXt9e317fTwoKCgoKSgpKCkpKCkpe317fSk-KSl7e30oe30oPD4pKTw-eygoe30pKXsoe31bKCldKTw-fXt9fXt9PD4oW3t9KClde31be31dPCgoKSk-KXsoKDx7fXt9PikpfXt9KDwoKT4pfXt9&input=MDAwMDAwMDEy&args=LWE)
I'm pretty sure there is a shorter way to do the multiplication in a loop, but I haven't found it yet.
```
#reverse and subtract 48 from all numbers (ASCII -> decimal)
([]){{}({}[((((()()()){}){}){}){}]<>)<>([])}{}<>
([][(()()()()){}]) #height - 8
{({}[()]){ #if not 0 subtract 1
([]){{}{}([])} #if still not 0 pop everything
}}{} #this loop pops everything unless there are 8 or 9 digits
([{}]) # -I
({}({}){}) # H*2
({}({})({}){}) # G*3
({}(({}){}){}) # F*4
({}(({})({})){}{}) # E*5
({}(({})({}){}){}) # D*6
({}((({}))({}){}){}{}) # C*7
({}((({}){}){}){}) # B*8
(({}(((({})){}){}){}{}{} # A*9 pushed twice with:
<(((()()())()){}{})>)) # 11 under it
{{} #if not 0
({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{} # mod 11
[{}]<(())>){((<{}{}>))}{} # logical not
(<()>) # push 0 to exit loop
}{}
# implicit print
```
[Answer]
## C#, ~~120~~ 115 bytes
This loops through the `char[]` it receives as input and returns true or false:
```
bool b(char[]n){int r=0,k,i=0,l=n.Length;for(;i<l;i++){k=i==l-1?-1:l-i;r+=k*(n[i]-48);}return r>0&r%11<1&l<10&l>7;}
```
Fiddle:
<https://dotnetfiddle.net/3Kaxrt>
I'm sure I can scrape out a few bytes, especially in the messy `return`. Any ideas welcome!
Edit: Saved 5 bytes thanks to Kevin. I had no idea I could use `&` instead of `&&`!
[Answer]
# PHP, ~~86~~ ~~85~~ ~~84~~ ~~83~~ ~~82~~ 79 bytes
Note: uses PHP 7.1 for negative string indices.
```
for($l=log10($a=$argn);~$c=$a[-++$x];)$s+=$x>1?$x*$c:-$c;echo$s%11<1&$l>7&$l<9;
```
Run like this:
```
echo 010464554 | php -nR 'for($l=log10($a=$argn);~$c=$a[-++$x];)$s+=$x>1?$x*$c:-$c;echo$s%11<1&$l>7&$l<9;';echo
> 1
```
# Version for PHP < 7.1 (+10 bytes)
```
echo 010464554 | php -nR 'for($l=log10($a=$argn);~$c=$a[strlen($a)-++$x];)$s+=$x>1?$x*$c:-$c;echo$s%11<1&$l>7&$l<9;';echo
```
# Explanation
```
for(
$l=log10( # Take the log of the input number.
$a=$argn # Set input to $a
);
~$c=$a[-++$x]; # Iterate over digits of input (reverse). Negate to
# change every char to extended ASCII (all truthy),
# without changing empty sting (still falsy, ending
# the loop).
)
$s+=$x>1? # Add current char to the sum...
?$x*$c:-$c; # multiplied by $x, unless $x is 1; subtract it.
echo
$s%11<1 & # Check if sum is divisible by 11, and
$l>7 & # log of the input is greater than 7, and
$l<9; # log of the input is less than 9. Outputs 0 or 1.
```
# Tweaks
* Shorter way to distinguish between empty string and `"0"`, saved a byte
* Since `10000000` is invalid, no need to compare with `greater than or equals`, `greater than` suffices, saving a byte
* Shorter way to subtract least significant digit
* Negate char instead of XOR, saving a byte
* Saved 3 bytes by using `-R` to make `$argn` available
[Answer]
# Java 8, ~~115~~ ~~98~~ 94 bytes
```
b->{int l=b.length,i=l,r=0;for(;l>7&l<10&i-->0;)r-=(b[i]-48)*(l-i<2?1:i-l);return r>0&r%11<1;}
```
I'm surprised no one has posted a Java answer yet, so here is one.
-4 bytes thanks to *@ceilingcat*.
**Explanation:**
[Try it here.](https://tio.run/##nZJfa8IwFMXf/RRBmLTDlPxrU1fbMfY8X3wUH9JaNS6mkkZBpJ@9i1v3JoPsPgTC5cc593AO4iJgc6r1YfPZV0q0LfgQUt9GAEhta7MVVQ0W9y8AZdOoWmhQBdVemNUaXMLMLbqRe1orrKzAAmiQg76Exc3hQOVlpGq9s/upzNXU5CjbNibIVMEnao7RREJYoCw0MA/KlVxDlobPgYJyTl7xi4QqzExtz0YDU6CJecJ4jrOuz@6Kp3OpnOIgfGnkBhyd82BpjdQ7506EP7aX19bWx6g52@jkVlbpQEdVMMYYE0IopePINu/uojdjxDUIw@@r/uAIZXHCU@LJEUpIQmKaeHIII5awOGa@Pv@HMYZwwvnDVP72@Tu@PmckpZwlsW@ejMczhmLuyaXDeGLctyd06BfzLcoQI37MdaOu/wI)
```
b->{ // Method with character-array as parameter and boolean return-type
int l=b.length, // Length of the array
i=l, // Index-integer, starting at this length
r=0; // The result-sum, starting at 0
for(;l>7&l<10 // Start looping if the length is either 8 or 9
&i-->0;) // And continue looping downwards while the index is larger than 0
r-= // Decrease the result-sum by:
(b[i]-48) // The current digit
*( // Multiplied by:
l-i<2? // If `l-i` is 1:
1 // Simply multiply by 1
: // Else:
i-l); // Multiply by `i-l`
return r>0 // Return if the result-sum is larger than 0,
&r%11<1;} // and if the result-sum is divisible by 11
```
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 58 bytes
```
iy9L[r'0r!]ppry9=[pp8[f'0-srlrpsrl`*r,]p'0-N&+[92+%!u;]]u;
```
[Try it online!](https://tio.run/##y6n8/z@z0tInukjdoEgxtqCgqNLSNrqgwCI6Td1At7gop6gASCRoFenEFgAF/NS0oy2NtFUVS61jY0ut//83NDQ0MjIyNjYGAA "Ly – Try It Online")
I thought this would be shorter... There's probably room for improvement?
First part, input digits, pad with leading `0` if necessary
```
i - input all digits (as codepoints)
y - push the stack size onto the stack
9L[ !]p - if/then block, true if <9 digits
r'0r - reverse stack, push 0, reverse again
p - pop the stack size entry off the stack
```
Second part, only process digits if we end up with 9 digits
```
r - reverse the stack
y - push the stack size info the stack
9=[pp ... ] - if/then block, true if stack size is 9
```
Third part, process the first 8 digits
```
8[ ,]p - loop 8 times
f - bring digit forward
'0- - convert from char to int
s - save digit value
rl - copy digit to bottom of stack
rp - delete from top of stack
s - save current loop var
rl - copy to bottom of stack
` - increment by one
* - multiple with current digit
r - reverse stack
```
Fourth part, process last digit, sum results
```
'0- - convert digit from char to int
N - negate
&+ - sum all entries on the stack
```
Fifth part, "is it zero?" and "is divisible by 11?" checks
```
[ ] - if/then block, true is sum is non-zero
92+ - push 11 onto the stack
%! - modulo math to get remainder, invert the result
u; - print top of stack as int, then exit
```
Last part, prints "falsey" if some success criteria wasn't met
```
u; - print top of stack (which will be 0) and exit
```
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 88 bytes
```
$0="0"$0,n=gsub(a," ")-1{b=n-9;c=9}!b||b==1{for(d-=$n;++b<n;e=d%11)d+=$b*c--}1,$0=!e*!!d
```
[Try it online!](https://tio.run/##DcxBCoMwEAXQq5iQgpoMZCIVJP7DOMa6ECK0lC7Us6e@A7zpt5ViPLTXxruM9fOVenK60g3xIcg0xBnDpeQ8BeDjtb/rRDA5WitjjgvSg7lJFkbamehid3dqaZVKpYQuhD48u/4P "AWK – Try It Online")
And one I had fun golfing, just to abuse the flexibility of AWK.
```
$0="0"$0 - append "0" to the input
gsub(a," ')-1 - re-parse the input, one char per arg
,n= -1 - set "n", decr RC to get number of chars
{ } - code block...
b=n-9; - set "b" to first char to use
c=9 - set "c" to initial multiplier val
!b||b==l - true is we got 8 or 9 chars
{ } - code block...
for( ) - loop over initial 8 chars
d-=$n; - init: "d" set to neg of last digit
++b<n; - test: ends after 8 chars processed
e=d%11 - loop-end: "e" is remainder of "%11"
d+=$b*c-- - loop-code: multiply and add next digit
1, - unconditionally run implicit "print $0" code block
$0=!e*!!d - "$0" is 1 if accum value is non-zero and divisible by 11
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~42~~ 41 bytes
-1 byte from @ngn's improvements
```
{(4=-2!#x)&t&~11!t:+/(|-1,2+!8)*-9#0,.'x}
```
[Try it online!](https://ngn.codeberg.page/k/#eJxdjssKgzAQRfd+hY9itWqbmUwSNfRLRLAbobRQkCwUq99eakwXvau5B+5h+npO6FpgEI1pbOIVIDB1dkneBeSYBWV6KqqI5efjuHieqedDM61D3fu+P+ru9dBJ19/uTz3qSQ9pu3imCQEAETnnoYZ2A8hJSFWiA8gRJQouHWDASJIQ9Jv8dSIGUimr3BYuoWZ2UWHJFUnhAJISFTGhHCj3uP612YvvHxM6ssvBgg/I/EQY)
Takes the input as a list of characters.
* `.'x` convert each digit to its integer (e.g. convert `"123"` to `1 2 3`)
* `-9#0,` prepend a `0`, then take the last nine values (handles padding 8-digit codes, and avoids errors on input that is not 9 digits long)
* `(|-1,2+!8)*` generate `9 8 7 6 5 4 3 2 -1`, and multiply the parsed digits by this
* `t:+/` take the sum, storing in variable `t`
* `t&~11!t` check that 11 evenly divides t, and that t is non-zero
* `(4=-2!#x)&` also check that the input is 8 or 9 characters long (literally: the length of the input (integer) divided by 2 is equal to 4)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 65 bytes
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
```
->n{a,*b=n.to_i.digits
i=1
b[6]&&(b[..7].sum{_1*i+=1}-a)%11<1||p}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY_PCoJAEMbvPkUERVkuzuzsrkIGXXoJEVGi2EN_SD1E-iRdJOqd6m2KdPfQXIbvB98339we5yq_tPd19KzKrRe8V97ycM3mbh4dWHlMNdvonS4LR0fg5LFMxuNJHjOmElZU-2sKrp5F0HjZdASwgLo-NX3Q6zRYx0MAQETO-TBxOoCchFQBGoAcUaLg0gAffJIkBFnLnybyQSr1i6y-1TqXGesKMeCKpLCHSImQfKEMCPoxWtmSvG9NtmUfDl_Q_de23f4A)
[Answer]
## Clojure, 114 bytes
Well this is something, `-` substracts the rest of the arguments from the first one so that handles the special case of weight `-1`. This function returns `nil` for inputs of invalid length, but on `if` clauses they operate the same as `false`. `(#{8 9}(count v))` returns `nil` if length of `v` is not 8 or 9.
```
(fn[v](if(#{8 9}(count v))(#(and(< % 0)(=(mod % 11)0))(apply -(map *(range 1 10)(reverse(map #(-(int %)48)v)))))))
```
Test cases:
```
(pprint (group-by f (map str [123456782 232262536 "010464554" 10464554 44016773 "000000000" 192837465 247594057 88888888 73 3112223342 "000000012"])))
{true ["123456782" "232262536" "010464554" "10464554" "44016773"],
false ["000000000" "192837465" "247594057" "88888888" "000000012"],
nil ["73" "3112223342"]}
```
[Answer]
# [Perl 5](https://www.perl.org/), 63 + 2 (`-F`) = 65 bytes
```
$F[-1]*=-1;map$s+=++$i*$_,reverse@F;say/^.{8,9}$/&&$s&&!($s%11)
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FLVrXMFbLVtfQOjexQKVY21ZbWyVTSyVepyi1LLWoONXBzbo4sVI/Tq/aQseyVkVfTU2lWE1NUUOlWNXQUPP/f0NDQyMjI2Nj43/5BSWZ@XnF/3V9TfUMDA3@67oBAA "Perl 5 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╪╦µΘç}<╔▼◘╞i∟~¿≥←║▐√ 4u
```
[Run and debug online!](https://staxlang.xyz/#c=%E2%95%AA%E2%95%A6%C2%B5%CE%98%C3%A7%7D%3C%E2%95%94%E2%96%BC%E2%97%98%E2%95%9Ei%E2%88%9F%7E%C2%BF%E2%89%A5%E2%86%90%E2%95%91%E2%96%90%E2%88%9A+4u&i=111222333%0A123456782%0A232262536%0A010464554%0A10464554%0A44016773%0A%0A000000000%0A192837465%0A247594057%0A88888888%0A73%0A3112223342%0A000000012&a=1&m=2)
## Explanation
Uses the unpacked version to explain.
```
i%8A:byr{]ei^*mBN+|+c11%!L|A
i Suppress implicit eval
%8A:b Length is 8 or 9 (Element #1 on the final stack)
yr Reverse input
{ m Map each element with
]e Its numerical value
i^* Multiplied current 1-based loop index
BN+ Negate the first element
|+ Sum (Element #2 on the final stack)
c11%! Sum is multiple of 11 (Element #3 on the final stack)
L|A Collect all the three elements and `and` them.
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 96 bytes
```
lambda i:7<len(i)<10*((S:=sum(a*b for a,b in zip([-1,*range(2,10)],map(int,i[::-1]))))%11<1)*S>0
```
[Try it online!](https://tio.run/##fY/NboMwEITveQpfImxEKq9/MEFJL32EHNMcjCDEEjHIkEP68hQbt6paqXOalXZnvxme0623vBjc3B7f507fq1ojU6pD11hsyAFoivGpPI6PO9Zpha69QzqrkLHowwz4vIMsddq2DWYZUHLJ7nrAxk6ZOZflDi5k0RbgACQ9vdLZn0/uMd2ePuGcAABjjHOeZCgBxoXMVcH8wDhjOZM89wMFKnIhpQhrP7wQFHKleHIpN2iRHsfGTajF6xOyrLzpsUHbEdWmRrafkGumh7OR4iVB22jD/eAWdlz1fYe/MwjZbDz3VXdjE7nplwLQnhVciVwGbqHkXlCp/FBEea9CRx4Li1AyhgD7xe85W7w@/KfDuhA6rPZvh5hByPwJ "Python 3.8 (pre-release) – Try It Online")
Similar to [@TFeld's Python 2 answer](https://codegolf.stackexchange.com/a/102500/106393), but uses Python 3.8 assignment expressions and a few other tricks to get it down to 96 bytes.
[Answer]
# TI-Basic, 60 bytes
```
max(length(Ans)={8,9})sum(seq(int(10fPart(expr(Ans)/₁₀^(I)))(I-2(I=1)),I,1,9
not(fPart((Ans+not(Ans))/11
```
Takes input in `Ans` as a string. Output is stored in `Ans` and is displayed.
] |
[Question]
[
Create a cat program, a.k.a a program that takes an input and prints it.
...Except, the program will randomly take characters away from your input and print that instead.
Each character in the input should have generally equal odds to be removed with the program, though, as it is hard to make that, the odds for each character can vary by 10% at most.
Your program should take the input, then randomly remove characters from the input, then print that version again. (You can print with trailing newlines or other characters in case your language has to print newlines.)
If the input was `BOOOWL`, it shouldn't remove all Os with an equal chance: each character (not unique) should be considered, so instead of every O combined having a 1/5 chance (for example), each O should have a 1/5 chance, so, instead of there being a 1/5 chance of `BWL`, there should be a 1/5 chance of `BOWL`, `BOOWL`.
Input is restricted to STDIN or closest equivalent.
Each character *must* have a minimum of 10% and a maximum of 30% chance to be removed.
Each character's odds should be calculated individually.
You can use any component of your language supporting random actions, be it functions or something other.
Output must be through STDOUT or the closest equivalent. If your language does have STDOUT, do not output in any other way. If your language cannot output strings as text, use closest equivalent (C's character array output's OK here).
This is code golf. Shortest program wins.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), 2 bytes
```
5ö
```
The `-f` flag "runs the program on each element in the first input, outputting an array of those that return a truthy value." `5ö` returns a random number between 0(inclusive) and 5(exclusive). Like JavaScript, 0 is falsy in Japt.
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=NfY&input=IkJvd2wi)
[Answer]
# [Python 3](https://docs.python.org/3/), 63 bytes
```
from random import*
for c in input():print(end=c[random()<.2:])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocaXlFykkK2TmAVFBaYmGplVBUWZeiUZqXoptcjRErYamjZ6RVazm//9O/uE@AA "Python 3 – Try It Online")
# [Python 2](https://docs.python.org/2/), ~~67~~ 65 bytes
```
from random import*
print''.join(c for c in input()if.8>random())
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVqKvrZeVn5mkkK6TlFykkK2TmAVFBaYmGZmaanoUdRIuGpub//0pO/uE@SgA "Python 2 – Try It Online")
Each character has a 20% chance of beeing dropped.
Different approach, same length:
```
from random import*
print''.join(c[random()<.2:]for c in input())
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVqKvrZeVn5mkkR0NkNTRt9IysYtPyixSSFTLzgKigtERDU/P/fyUn/3AfJQA "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 4 bytes
```
ΦS‽⁵
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUjDM6@gtCS4BCiUrqGpoxCUmJeSn6thqqmpaQ1SmZ9elJibC5RUCCitqspJLVZQU3DOT0lVcM/PSeP6r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input a string
Φ Filter where nonzero
‽⁵ Random number 0..4
Implicitly print
```
You can use any number from `4` to `10` to get chances of `25%` to `10%` respectively.
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 11 bytes
```
>#@~3j4???,
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@3U3aoM84ysbe31/n/Pzk/JVUhPT8nDQA "Befunge-98 (PyFunge) – Try It Online")
Each character has a 25% chance of being removed. This decision is made at the three `?` instructions.
`?` sets the program counter to one of the four directions, with equal probability. In this case, up & down wrap back around to the same instruction, so we can ignore those as options.
There are two ways out of the forest of `?`s: to the right (output) and to the left (no output). This situation is symmetric, so if starting from the middle `?`, there is a \$p\_2 = 1/2\$ chance of outputting. The chance of outputting if starting from the right `?` is \$p\_3 = 1/2 \* 1 + 1/2 \* p\_2 = 3/4\$. Therefore, after reading a character, we jump to the rightmost `?` to determine whether or not to output.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 23 bytes
Generates an array of the same size as the input (strings in Octave are character arrays), checks each of the random numbers whether it is greater than `0.2` and then uses logical indexing to extract the characters at the corresponding positions.
```
@(s)s(rand(size(s))>.2)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQaNYs1ijKDEvRaM4syoVyNO00zPS/J@SWVygkZhXrKHk6OTs4uqmpKn5HwA "Octave – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 5 bytes
```
5X’µƇ
```
[Try it online!](https://tio.run/##y0rNyan8/9804lHDzENbj7X////fOT8lVSE9PydNIa2kHAA "Jelly – Try It Online")
A monad which takes a Jelly string as its argument and returns the processed Jelly string. When used as a full program implicitly prints the output. Each character has a 20% chance of being removed.
## Explanation
```
µƇ | Filter using the following as a monad for each character:
5X | - Random number between 1 and 5
’ | - Decreased by 1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 bytes
Each character has a 1 in 5 chance of being removed. The `5` can be changed to anything between `4` & `9`, inclusive, or `A` for `10` to change the odds.
```
Æ5ö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xjX2&input=IkJvd2wi)
```
Æ5ö :Implicit input of string
Æ :Filter by
5ö : Random integer in the range [0,5), with 0 being falsey
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 5 bytes
```
sfO4Q
```
[Try it online!](https://tio.run/##K6gsyfj/vzjN3yTw/3@lxKTklFQlAA "Pyth – Try It Online")
```
sfO4Q Implicit: Q=eval(input())
f Q Filter characters of Q where the following is truthy:
O4 Random number in the range [0-4)
Any non-zero value is truthy, so this will drop characters 25% of the time
s Concatenate into string, implicit print
```
---
Previous version, 8 bytes:
```
s*Vm!!O4
```
[Try it online!](https://tio.run/##K6gsyfj/v1grLFdR0d/k/3@lxKTklFQlAA "Pyth – Try It Online")
```
s*Vm!!O4QQ Implicit: Q=eval(input())
Trailing QQ inferred
m Q Map each character in Q using:
O4 Choose random integer in [0-4)
!! Logical NOT twice - maps 0 to 0, anything else to 1
The result is a list of 0s and 1s, with 0 having 25% chance to appear
*V Q Vectorised multiplication of the above with Q
s Concatenate into string, implicit print
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
Select[RandomReal[]>.2&]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg1JzW5JDooMS8lPzcoNTEnOtZOz0gt9n9AUWZeSbSyrl2ag3NGYlFicklqUbGDcmydS36dqZq@QzWXkpN/uI8SV@1/AA "Wolfram Language (Mathematica) – Try It Online")
Takes a list of characters as input. Each character has a `.2` chance to be removed.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ʒ₄Ω≠
```
-1 byte thanks to *@Grimy*.
[Try it online](https://tio.run/##yy9OTMpM/f//1KRHTS3nVj7qXPD/v1N@eQ4A) or [run the same program 10 times](https://tio.run/##yy9OTMpM/R/i9v/UpEdNLedWPupc8L9W579TfnkOAA).
Each character has a 25% change of being dropped.
**Explanation:**
```
ʒ # Filter the characters of the (implicit) input-string by:
₄ # Push 1000
Ω # Pop and push a random digit from it
≠ # And check that it's NOT 1 (!=1)
# (after which the result is output implicitly)
```
`≠` could also be `_` (`==0`).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
t&n&r.2>)
```
Exaplanation:
```
t implicitly take input and duplicate it
&n compute the size of the input and...
&r generate a random array of that size
.2> check which entries of that array are greater than 0.2
) and use the result using logical indices to extract certain characters of the input
```
[Try it online!](https://tio.run/##y00syfn/v0QtT61Iz8hO8/9/dUMjYxNTs8Sk5JTUNHUA "MATL – Try It Online")
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 20 bytes
```
u$w\A|UDw@?;...>o._U
```
[Try it online!](https://tio.run/##Sy5Nyqz4/79UpTzGsSbUpdzB3lpPT88uXy8@9P//pPzyHAA "Cubix – Try It Online")
Longer than I had hoped as I had a number of no-ops that I can't seem to get rid of. The chance to drop a character is 25%. I assume this is okay.
```
u $
w \
A | U D w @ ? ;
. . . > o . _ U
. .
. .
```
[Watch it run](https://ethproductions.github.io/cubix/?code=dSR3XEF8VUR3QD87Li4uPm8uX1U=&input=Ym93bA==&speed=20)
Brief explanation:
* `A|A` this initialises the the stack, Input all, reflect back, Input all (just an EOI -1)
* `;?` pop to of stack, test for EOI (-1).
* `_?@` if negative, reflect back into test and end on halt
* `$D` jump the `\` into the random direction setter.
+ from the direction setter, 3 direction lead to the `o` for output then back into the loop, one misses the `o` in it's path and goes straight to the loop.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~10~~ 9 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function. Each character has exactly 20% chance of being removed.
```
⊢⌿⍨4≥∘?5¨
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/R12LHvXsf9S7wuRR59JHHTPsTQ@t@K/J9ahvKlA6TT0kI1UhObFEIbEkVaEyv7RIITOvoBTITU/MzFNU/w8A "APL (dzaima/APL) – Try It Online")
`5¨` zero for each character
`?` random integer range 1–5 for each character
`4≥` Boolean mask for those integers that are less than or equal to 4
`⊢⌿⍨` filter the argument using that mask
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 15 bytes
```
/./_?(`.
```
[Try it online!](https://tio.run/##K0otycxLNPz/X19PP95eI0GPCwL@/w8oyk8vSszNzcxLVwgorarKSS1WUFNwzk9JVXDPz0kDAA "Retina – Try It Online") Explanation:
```
/./_
```
Process each character individually.
```
?(`
```
Perform a substitution at random. The first substitution deletes the character, while the other three leave it unchanged, thus giving a `25%` chance of deleting the character. This can be decreased as necessary by appending additional pairs of newlines.
[Answer]
# [R](https://www.r-project.org/), ~~32~~ 23 bytes
```
function(x)x[rt(x,3)<1]
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrMiuqhEo0LHWNPGMPZ/mkZxSVFxQU5miYaSR2pOTr5CeX5RToqiko6CkpJmdLRhbKzmfwA "R – Try It Online")
A function taking a character vector as input and returning a processed character vector. Each character has a 20% chance of being removed.
Thanks to @Roland and @Giueseppe for helping save 7 bytes, and @JDL for a further 2!
[Answer]
# T-SQL 2012, 83 bytes
Looping through the input from right to left removing 0 or 1 character.
25% chance for each character getting removed.
```
DECLARE @i varchar(max)='The cat ate my homework'
DECLARE @ int=len(@i)WHILE @>0SELECT
@i=stuff(@i,@,str(rand()*2)/2,''),@-=1PRINT @i
```
Explanation:
>
> `rand()*2` returns a float, which can't be used in the `stuff` command.
>
>
> The `str` converts this into a varchar after rounding to nearest whole number. The float is being converted to a varchar(which isn't allowed as third parameter in `stuff` either).
>
>
> This varchar has a 25% chance of being '2', 50% chance of being '1', 25% chance of being '0'. Dividing by 2, there is a 25% chance of result being 1. This division converts the varchar to an integer.
>
>
> Integer is the expected third parameter in `stuff` function.
>
>
>
**[Try it online](https://rextester.com/FSYQ7693)**
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
#~5>6?@$~#
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/letM7czsHVTqlP9rcnEVpRaWZhalKqjnleamFmUmq3MVJeal5OdmVqWqq3NxpSZn5CtopCkZaioYGigoKxkoxCvoWKlnpObk5CuU5xflpKhz/QcA "J – Try It Online")
Similar to Adam's APL answer, though I actually wrote it before looking at his.
* `6.. $~ #` Take the length of input `#` and shape `$~` the number 6 into a list that long.
* `?@` Treat each six in that list as a die and roll `?` it.
* `>5` Is the die less than 5 (possible values are 0..5)? Use that boolean result to create a bit mask.
* `#~` Filter the input with that mask.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 18 bytes
```
s/./.2<rand&&$&/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX09fz8imKDEvRU1NRU0/PfX/f0MjYxNTM3MLS4N/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
Each character has a 20% chance of being dropped.
[Answer]
# Javascript, ~~46~~ ~~44~~ 51 bytes
```
i=>alert([...i].filter(c=>Math.random()>.2).join``)
```
+7 bytes because of the added STDOUT requirement
-2 bytes thank to Birjolaxew
---
original answer:
44 bytes without the STDOUT requirement
```
i=>[...i].filter(c=>Math.random()>.2).join``
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~51~~ ~~46~~ 30 bytes
```
s=>s.flatMap(x=>if(math.random>.2)Some(x)else None)
```
[Try it online!](https://tio.run/##Lcs9DgIhEEDhnlNMtoKGwtJkSTyANusFRhhklb/AJK4xnh23sHrN97rFiKPcHmQZLNDGlF2HU63wEcKRB39cuK35Ppt/R59N1z4in7HKbTarlwk56IbZlWT0QS0lkdwUxU5wKZnUqPvKMUsvp2sgsMiATJDeEHb7Ku05KSW@Y/wA "Scala – Try It Online")
PS. Like in many other solutions, the probability of dropping char is 20%.
# Update:
-5 bytes by using String instead of Option[String] in flatMap
```
s=>s.flatMap(x=>if(math.random>.2)x+""else "")
```
30 bytes by using filter
```
s=>s.filter(x=>math.random>.2)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 71 bytes
```
var y=new Random();foreach(var k in ReadLine())if(y.Next(5)<4)Write(k);
```
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LLFIodI2L7VcISgxLyU/V0PTOi2/KDUxOUMDJJWtkJmnEJSamOKTmZeqoamZmaZRqeeXWlGiYappY6IZXpRZkqqRrWn9/79TfnkOAA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~43~~ 42 bytes
```
for(;''<$l=$argn[$i++];rand()%5&&print$l);
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKzV1W1UcmxVEovS86JVMrW1Y62LEvNSNDRVTdXUCooy80pUcjSt//938g/3@ZdfUJKZn1f8X9cNAA "PHP – Try It Online")
Each character has 20% of chance to be removed.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 50 bytes
This program has a 20% chance of dropping a letter. Unfortunately the random number generator isn't seeded so you get the same sequence on each run. Basically the only trick is inverting the input character to halt the loop on EOF.
```
main(c){for(;c=~getchar();rand()%5&&putchar(~c));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mzOi2/SMM62bYuPbUkOSOxSEPTuigxL0VDU9VUTa2gFCJWl6ypaV37/39IRmaxAhAlKpSkFpf8S07LSUwv/q9bDgA "C (gcc) – Try It Online")
## [C (gcc)](https://gcc.gnu.org/), 64 59 bytes
Thanks to ceilingcat for the -5 bytes.
If you want the RNG seeded on each run.
```
main(c){for(srand(&c);c=~getchar();rand()%5&&putchar(~c));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mzOi2/SKO4KDEvRUMtWdM62bYuPbUkOSOxSEPTGiyqqWqqplZQChGrS9bUtK79/z8kI7NYAYgSFUpSi0v@JaflJKYX/9ctBwA "C (gcc) – Try It Online")
[Answer]
# [Lua](https://www.lua.org), ~~69~~ 68 bytes
```
for c in io.lines(nil,1)do io.write(math.random()>.2 and c or '')end
```
[Try it online!](https://tio.run/##TY6xTsQwEET7@4pJFVvKWYLyCiiorjiuuC9Y4iVZLvYKZyOLrw9GSIhuZnbfaJaN9uMRN@aIiTMXMi0Br2oo/LlJabkpEt0Zo0ZG1XKXPA342Fb7O0l7pxw1hUMim8OvWVur0zWYJHbe7@9aMEIyRMMimVeXZRkefNSfpBYxdv9w55/CI5psUCP73nOO@36tbeYJ5zYlRy4D6syFESUifWGcqdBoXFZUzgaaSPJzd3ghO@HCWju4c59AeKNWTNb5bw "Lua – Try It Online")
Kinda straightforward, but seems to be shortest version: iterate over stdin char by char (with `io.lines`… that name is misleading), then based on random value either print one or empty string (e.g. nothing).
[Answer]
# Java
Non-terminating: 82 bytes
```
v->{for(int i;;i=System.in.read(),System.out.print(Math.random()<.2?"":(char)i));}
```
[Terminating (TIO): 105 bytes](https://tio.run/##ZY6xTsMwFEX3fMVTJ1uiFmLEpEx061SJBTG8OHbyUseObMdtifLtwSA2prPce88dMON@aC@bshgjnJAcLBW5pINBpeG4ZE8tGPb@g8wh9cFfI7zdlJ4SeSfXapobSwpiwlTwmx/LDjunQK77@AQMXfzfLJ4jGKi3vD8sGQO4@nyPSY@CnDQ@sPICSDpRLpLFxmrGD4@SaieCxpbxh7@4n5OYiiqxE6ZeBHStHxl/EU@vu90zUz0GTpzLdZOVEYa52Vouq3XdsFGtNl1Pw8WOzk8hpjlfb/evbw)
```
v->{var n=System.in;for(int i;n.available()>0;i=n.read(),System.out.print(Math.random()<.2?"":(char)i));}
```
[Answer]
# [Zsh](https://www.zsh.org/), 50 bytes
```
for c (${(s::)"$(<&0)"})
((RANDOM%5))&&echo -nE $c
```
[Try it online!](https://tio.run/##HY6xasMwFEX39xWXYBkJEtOli@mS0o5tobOgCPvZFjhPQXohpKXf7iod7xnOPd9l2bYpZQywzY8tfe92jX1qH9zu15G1n8f3l4838@hc2/KwJBzkFc2wbc9rODGiIgl0YQxBEeYQpes6Oq7XcCvgoFFmnG6Icr5oB/NliOiQMa1hrhCZw7j/d9Zx95ONUrRSpAnXqEu66B6175yj6OQoZIYwjzzinl2vC/cw3njvxWevnjz9AQ "Zsh – Try It Online")
Similar to RobLogic's answer, but following the input requirements more closely, and works for inputs with backslashes.
`"$(<&0)"` instead of `"<&0"` or `$(<&0)` because the first doesn't work in substitutions, and the second eats newlines. The `-nE` flags are necessary to prevent backslashes from being parsed as escape sequences, and to prevent newlines being inserted.
`echo -nE`
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 5 bytes
```
æƒ√∞*
```
[Try it online!](https://tio.run/##y00syUjPz0n7///wsmOTHnXMetQxT@v/f3WP1JycfB2F8vyinBRFdQA "MathGolf – Try It Online")
## Explanation
```
æ foreach character...
ƒ random float in range [0,1)
√ take square root (making P(x < 0.5) = 0.25)
∞ pop a, push 2*a
* repeat character int(x) times
```
Each character will be repeated 0 or 1 times, depending on the random value. Since the expected value after the square root is shifted, there is a 25% probability that each character is removed.
### Alternative 5-byter
```
gÉ;4w
```
Filter the characters by a random number in [0, 4]. Due to how filtering works, I have to discard the actual character within the filter loop, which adds 1 byte.
[Answer]
# [Zsh](http://zsh.sourceforge.net/), ~~53~~ ~~41~~ 40 bytes
[Try it Online!](https://tio.run/##qyrO@P8/Lb9IIVlBQ6Vao9jKStOwVlNDI8jRz8XfV9VEU1NNraAoM68kTUEl@f///0GJBYnJmfmlxQpuqTmZeakKzvl5xaW5qcUKHvm5qeX5RdmKAA)
```
for c (${(s::)1})((RANDOM%4))&&printf $c
```
Converts the input to an array of characters, then tries to print each element `c`, unless it's eaten by the `((RANDOM%4))` evaluating to false!
*~~[53 bytes](https://tio.run/##qyrO@P8/Lb9IQUPDOtNGRdnQOlNbW1OzWkMjyNHPxd9X1cTOQFNTTS01OSNfQUml2jA6M7Y2JlnJuvb///9BiQWJyZn5pcUKbqk5mXmpCs75ecWluanFCh75uanl@UXZigA)~~, Original*
*~~[41 bytes](https://tio.run/##qyrO@P8/Lb9IIVlBQ6Vao9jKStOwVlNDI8jRz8XfV9VEU1NNLTU5I19BJTkmJvn///9BiQWJyZn5pcUKbqk5mXmpCs75ecWluanFCh75uanl@UXZigA)~~, thanks to @GammaFunction*
[Answer]
# [GFortran](https://gcc.gnu.org/fortran/), 120 bytes
Not too bad, if we use the deprecated [`RAN()`](https://gcc.gnu.org/onlinedocs/gfortran/RAN.html#RAN) function, which is **pseudo**-random, i.e. you get the same sequence each time. The proper way to generate random numbers in GFortran is with `CALL RANDOM_SEED()` and `CALL RANDOM_NUMBER(R)` but that's a lot of bytes!
```
character(99)S;read(*,'(A)')S;do i=1,len_trim(S)
if(ran(0)*5.gt.1)then;write(*,'(A)',advance="no")S(i:i)
endif;enddo;end
```
[Try it online!](https://tio.run/##NYuxDoIwFAB3vqKy0BIkMjggYTAmxlk@wLy0r/AitOZR5PMrxrhc7oazngOD2/f2JzHqARh0QJZ1rbqGEYzMi0yeVbal8YLaqhjRPQLTJDuVkJXbKA8qP5Z9KCsVBnTNyhTwPxZg3uA0tqnzqeoknUgl6AzZZqPxX8Z4hxdo8sssrjiSQ3Hxbl4mnMXNT7h6fu4@)
[Answer]
# Oracle SQL, 133 bytes
```
select listagg(decode(sign(dbms_random.value-0.2),1,substr(x,level,1)))within group(order by level)from t connect by level<=length(x)
```
It works with an assumption that input data is stored in a table t(x), e.g.
```
with t(x) as (select 'The cat ate my homework' from dual)
```
] |
[Question]
[
The *harmonic series* is the "infinite sum" of all the fractions of the form \$\frac1n\$ for \$n\$ positive integer. I.e. the harmonic series is
$$\frac11 + \frac12 + \frac13 + \frac14 + \cdots$$
It is well-known that [this sum diverges](https://www.wolframalpha.com/input/?i=Harmonic+series), which means that if you define
$$ H\_n = \frac11 + \frac12 + \cdots + \frac1n$$
Then the value of \$H\_n\$ goes to infinity. This can also be stated in a different way: for any positive value \$x\$ you pick, there is some value \$N\$ such that, to the right of \$N\$, the \$H\$ values are bigger than \$x\$:
$$\forall\ x\ \exists\ N: n > N \implies H\_n > x $$
# Your task
Write a program/function that takes as input a positive number `x` (not necessarily an integer) and outputs the first integer `n` for which
$$H\_n \geq x$$
In theory your program must work for arbitrary `x`, even if in practice you are limited by the memory and/or precision of your programming language/computer.
# Test cases
```
1.5 -> 2
2 -> 4
3 -> 11
3.1415 -> 13
4 -> 31
5 -> 83
7.5 -> 1015
10 -> 12367
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest solution wins! Standard loopholes are forbidden by default. Happy golfing.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 13 bytes
*-1 bytes thanks to ngn*
```
{⊃⍸⍵≤+\÷⍳⌈*⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHXc2Penc86t36qHOJdszh7Y96Nz/q6dACCtQCVRxaoWCoZ6pgpGCsoGCsZ2hiaKpgomCqYA4UMzQAAA "APL (Dyalog Classic) – Try It Online")
A dfn solution that takes a right argument.
### Explanation:
```
{ } ⍝ dfn
⊃ ⍝ Take the first of
⍸ ⍝ The indexes of the truthy values of
⍵≤ ⍝ The right argument is smaller than or equal to
\+ ⍝ The cumulative sum
÷ ⍝ The reciprocal of each of
⍳ ⍝ The range 1 to
⌈ ⍝ The ceiling of
*⍵ ⍝ e to the power of the right argument
```
[Answer]
# [Python 3](https://docs.python.org/3/), 35 bytes
```
f=lambda x,n=1:x>0and-~f(x-1/n,n+1)
```
[Try it online!](https://tio.run/##VYxBCoMwFET3nsJlvtU0vypCQe@SVkMD5ickKcSNV0@7KaSLgTePYdwRX5b6rI2zPtbhCNU3PGzRb8@3D9rSro2ODEXTjJDVvEvzWGWdWprxnhYhae1OxVKHV2rpgpCd1xSZYshHgOrXbgX3JXMcsBwOBZd@@rtDAZA/ "Python 3 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes
```
{+([\+](1 X/1..*)...*>=$_)}
```
[Try it online!](https://tio.run/##JYvBDoJADETv/YoejICESukCXuh3mCAxHiAhWZSwXojx21dYL/NmMjNzv9jKTyseB2zQf9K4vaVdzHg9M9EpoU20OdyTr3ePFWmbDa8F7fjsnSq52Y7vOMo0SlTbvPNMJWaKBRQ7DMgOZhBiw6FiAbNTGEK@CNT/E@dcAufBFlLVPw "Perl 6 – Try It Online")
### Explanation:
```
{ } # Anonymous code block taking one argument
+( ) # Return the length of
[\+]( ) # The cumulative sum
1 X/ # Of the reciprocal of all of
1..* # 1 to infinity
... # Take from this until
*>=$_ # It is larger than or equal to the input
```
[Answer]
# JavaScript (ES6), ~~32~~ 29 bytes
*Saved 3 bytes thanks to @Shaggy*
```
f=(n,k=0)=>n>0?f(n-1/++k,k):k
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfb1kDT1i7PzsA@TSNP11BfWztbJ1vTKvt/cn5ecX5Oql5OfrpGmoahnqmmJheqmBGGiDGmiJ6hiSGmVhMMEUw15iAr/wMA "JavaScript (Node.js) – Try It Online")
---
# Non-recursive version, 35 bytes
```
n=>eval("for(k=0;(n-=1/++k)>0;);k")
```
[Try it online!](https://tio.run/##bc1BDoMgEIXhvcdwNRMiZSqNC4J3IRaaCmEaNV6frs24/fK/vDWcYV@27@8YKr9jS75VP8czFOgTb5C9cVAHTw@lMs7Gocs9toXrziXqwh9IQPqF2F3tKWSUosmSnFohspluLskgtj8 "JavaScript (Node.js) – Try It Online")
---
### Approximation (25 bytes, not fully working)
This gives the correct result for all but the first test case.
```
n=>Math.exp(n-.5772)+.5|0
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1s43sSRDL7WiQCNPV8/U3NxIU1vPtMbgf3J@XnF@TqpeTn66RpqGkaYmF6qIMaaInqGJoSmGsAmGCKYacz1MMUMDTc3/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
∞.ΔLzOI@
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTfKr8PR3@/zcFAA "05AB1E – Try It Online")
```
∞.Δ # first integer y such that:
L # range [1..y]
z # invert each [1, 1/2, .., 1/y]
O # sum
I@ # >= input
```
[Answer]
# [R](https://www.r-project.org/), ~~39~~ 33 bytes
```
x=scan();sum(cumsum(1/1:x^x)<x)+1
```
[Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTurg0VyO5NBdEGeobWlXEVWjaVGhqG/431jM0MTT9DwA "R – Try It Online")
For a more limited x:
# 29 bytes
```
sum(cumsum(1/1:9^8)<scan())+1
```
[Try it online!](https://tio.run/##K/r/v7g0VyO5NBdEGeobWlnGWWjaFCcn5mloamob/jc0@A8A "R – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, 31 bytes
*Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) (based on [@John](https://codegolf.stackexchange.com/users/90260/john)'s answer) for making a correction and saving 1 byte at the same time.*
```
@(n)sum(cumsum(1./(1:3^n))<n)+1
```
[**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zuDRXI7k0F0QZ6ulrGFoZx@VpatrkaWob/i9JLS5RsFWINtQzVTBSMFYw1jM0MTRVMFEwVTAHChkaxFpzpWQWF2gkFhUlVqaV5mmk6SiANGnqqWv@BwA)
### Explanation
The code uses the fact that `1+1/2+···+1/m` is lower-bounded by `log(m)`. Therefore, given `n` the solution to the challenge is less than `exp(n)`, or less than `3^n` (to save bytes).
So the code computes the cumulative sum of the vector `[1, 1/2, 1/3, ..., 1/(3^n)]`, and the solution is `1` plus the number of entries that are less than `n`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes
```
(i=0;#//.x_/;x>0:>x-1/++i;i)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPT1sBaWV9fryJe37rCzsDKrkLXUF9bO9M6U1Ptf0BRZl6JvkOavkO1oZ6pjpGOsY6xnqGJoamOiY6pjjlQyNCg9j8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~49~~ 40 bytes
Saved 9 bytes thanks to @JoKing!!!
```
lambda n,s=0,i=1:s<n and-~f(n,s+1/i,i+1)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIU@n2NZAJ9PW0KrYJk8hMS9Fty5NAyiobaifqZOpbaj5v6AoM69EI03DUM9UU5MLxjNCYhsjs/UMTQyRFZogsZHFzVGMMzTQ1PwPAA "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~52~~ ~~51~~ 49 bytes
Saved a bytes thanks to @ceilingcat!!!
Saved 2 bytes thanks to @S.S.Anne!!!
```
i;f(n,s)float n,s;{for(s=i=0;s<n;s+=1./++i);n=i;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOk0jT6dYMy0nP7FEAciyrk7LL9Iots20NbAutsmzLta2NdTT19bO1LTOs820rv2fm5iZp6FZzVVQlJlXkqahpJoSk6ekk6ZhqGeapqlpjSFupIdV2BiXsKGJIXaDTLDrMMUubI7DOYYGEPW1/wE "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~31~~ 30 bytes
```
->x{b=0;x-=1r/b+=1while x>0;b}
```
[Try it online!](https://tio.run/##DchBCoAgEADAr3hvMzeTDmEfEQ8tJAUFEUQb5tu35jjnRY8kL/XImbwZuPZ4NlR5vJd1mxWPZqAiAbWDFixYjR066MBB/xeaqPfpyC@/hwoMKgWOscgH "Ruby – Try It Online")
[Answer]
# [K (Kona)](https://github.com/kevinlawler/kona), ~~21~~ 20 bytes
```
{1+*&~x>+\1.%1+!3^x}
```
[Try it online!](https://tio.run/##y9bNzs9L/P8/zaraUFtLra7CTjvGUE/VUFvROK6i9n@auqGeqYKRgrGCsZ6hiaGpgomCqYI5UMjQ4D8A "K (Kona) – Try It Online")
Inspired by [Jo King's APL solution](https://codegolf.stackexchange.com/a/199193/75681)
Switched from oK to Kona, as it has `power`
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 45 bytes
*Some inspiration taken from @[Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9); go upvote [their answer](https://codegolf.stackexchange.com/a/199194/89298)!*
```
i;g(x,s)float x,s;{for(s=i=0;s<x;s+=1./++i);}
```
* `i;g(x,s)float x,s;`: Old-style function definition. Abuses the fact that old-style function definition don't require all the arguments to be passed (so old-style variadic functions would work) to declare an extra local variable. Having the `i` as a global variable causes the exploit below to work.
* `for(s=i=0;s<x;s+=1./++i);`: same old stuff as before, harmonic function, yada yada. Note that `s=i=0` is allowed; the `i=0` is an integer that is converted to a `float` and assigned to `s`.
* The `i` variable is stored in the `%eax` (return) register, so nothing is required to initialize it. (thanks @[Cody Gray](https://codegolf.stackexchange.com/users/58518/cody-gray)!)
[Try it online!](https://tio.run/##XU/RbsIwDHzPV1ggpETpSrOBJi0NP8L6gNKms9QlqAkIgfrtJSUaKvNL7nyx76zfWq3HEWVLL5lnpnOHABHJm3E99QpVIX15kZ4rka85RyaHcYlWd6e6gdKHGl3@syMEbYDfA1p6dlgzciMQK60Lel@BejRSeyqRb032ZO/5jHy8ErER86@bubqdk8@XlaL40wZJUpp4EUw5AygoZHxK8HhtnKFBs/UT7ouKRZVzYP9CH/s4buhi1X7Bqqu/7SKbrgtVBi19AMZk8kyWfRNOvY1mZBjv "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 72 bytes
Recursive solution.
```
i;float h(n){return n?h(n-1)+1./n:0;}g(float x){for(i=0;h(i++)<x;);--i;}
```
Explanation:
* `i;`: counter for finding the first integer `n` where `h(n) >= x`.
* `float h(n)`: recursive function taking an `int` parameter and returning the term of the Harmonic series for `n`.
* `return n?h(n-1)+1./n:0;` - recursive function calculating the Harmonic series and stopping at `0`.
* `g(float x)`: function finding the first `i` where `h(i) >= x`.
* `for(i=0;`: start loop and initialize `i` to `0` (functions must be reusable).
* `h(i++)<x`: loop while `h(i) < x`.
* `--i;` returns `i-1` by exploiting GCC's behavior when compiling without optimization; intermediate results are all stored in the `eax`/`rax` register.
[Try it online!](https://tio.run/##XVDbboMwDH3PV1idKsUK0GRtNamB7UM6HqpAIBJLJppO1RDfzkKzVXR@sY@PL8dWaaPUNBmpO3fy0FKLQ1/7S2/BvgWUCmQi29gDl2NDY9EVB@16agouW2oYw/wqUaapkeP0ZKzqLlUN@dlXxmXtKyHGevg4GUu/nKmQDASCxVFeHUsobomYnk1ke53c0XO2ANtHIHZiWbpbsvsleHkYKfgfN0oS1YR7YNbpoQAug8vhbL5rp6lXuLmHR15iYBkD/Cf6sw/tmq7WzQHWXfVuV8l8nS8TaOgtQJRxZ1z5@2UuyTj9AA "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 83 bytes
Non-recursive solution.
```
i;float h(n){float r=0;for(;n;)r+=1./n--;r=r++;}g(float x){for(i=0;h(i++)<x;);--i;}
```
Explaining the part that's different from the previous solution:
* `float r=0;`: this is our result. Initialize it to `0`.
* `for(;n;)`: Loop until `n` is `0`.
* `r+=1./n--;`: Add the next iteration of the Harmonic series. Also decrement `n` so we don't have to do that in the last part of the `for` loop.
* `r=r++;` is like `return n;` but shorter. It's similar to the fake `return` in the previous solution but does it with the floating-point return register instead of the integer return register. We have to have the `++` just so GCC doesn't optimize it out as redundant (and yes, some optimizations are enabled without a flag).
[Try it online!](https://tio.run/##XU/RbsMgDHznK6xOlUCENGytJtVhP9LloSIhQcpIRelUrcq3Z6RoVTq/4PMdvrMWrdbTZNH0wzFARx27pdarAs3gKTpkniuZb5wQ6JXnHMeWJtE1qqPGRm1HLeesvCJDISyO04t1ur/UDZTnUNsh7z4IsS7A19E6@j3YmpEbgVhpVdCHCtR9kMZzyXxnsgd6zRfg7RnIrVxKt0t2twTvTytl8ceNSFKaeA/MOQMoKDA@JZztTzMYGjTbPNpDUbHIcg7sX@iTj98NXa3bPaz7@tOtsvm6UGXQ0nvDGCbPZOmbcPEumpFx@gU "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
(#1)
x#n|x>0=(x-1/n)#(n+1)|1>0=n-1
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0PZUJOrQjmvpsLOwFajQtdQP09TWSNP21CzxhAokqdr@D83MTNPwVYhN7HAV0GjoCgzr0QvTVMh2lDPVEfBSEfBGIj0DE0MgTwTHSBhDhI3NIj9/y85LScxvfi/bnJBAQA "Haskell – Try It Online")
[Answer]
# Java 8, ~~71~~ 43 bytes
```
x->{int n=0;for(;(x-=1d/++n)>0;);return n;}
```
-28 bytes by porting [*@Arnauld*'s non-recursive JavaScript answer](https://codegolf.stackexchange.com/a/199185/52210).
[Try it online.](https://tio.run/##ZY/BbsIwDIbvPIXFKVHV0GxMkxaVN4ALx22HLA1TWHGrxkWdUJ@9S0MOVLtY@vzbv3@f9VXn5@pnMrX2Hvba4W0F4JBsd9LGwmHG2ADDqqb/qi0MXIXmuArFkyZn4AAIJUxDvrvNk1gW6tR0TLEhL2W1yTLku0Jx1VnqOwRU46Tm9Tb4hfXkcm1cBZcQgR2pc/j9/gma3@@T9cSkeImXEz49wvMChNzKxez2ERbK69JUFv@ei7GimP532PaUgh1/PdmLaHoSbchMNbIoZ@u3D1pnKMydebIdpz8)
**Explanation:**
```
x->{ // Method with double as both parameter and integer as return-type
int n=0; // Result-integer `n`, starting at 0
for(;(x-=1d/++n) // Decrease `x` by 1/(n+1), by first increasing `n` by 1 with `++n`
>0;); // And continue doing this until `x` is 0
return n;} // Then return `n` as result
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 21 20 [bytes]
[New Solution TIO](https://tio.run/##S8/PSStOLsosKPlv@t@gWlNP19DeIUZXzyHGwK42JT/G@v9/AA "GolfScript – Try It Online")
[Old Solution TIO](https://tio.run/##S8/PSStOLsosKPlvaPDfKtnaQK86RlNP19DeQVsv2aY2Jd/6/38A "GolfScript – Try It Online")
The new solution takes our input and recursively subtracts the inverses from it until we get the solution. Very messy stack management, could probably be done cleaner.
### New Solution (20)
```
0{).-1?@\-.@\0>}do\;
```
### New Solution Explanation
```
0{).-1?@\-.@\0>}do\; #Take in a number c as input, and output the lowest n s.t. Hn<x
0 # The stack is now [c n=0]. We're just using n here for clarity.
{ }do # Until we pop a TRUE, loop the following
{) }do # Increment n by 1
{ . }do # Then duplicate it
{ -1? }do # Raise the dupe to the power of 1 (inverse)
{ @\ }do # Move our c to the second element of the stack, between n and 1/n
{ - }do # Subtract. Stack is now [n c-(1/n)]
{ . }do # Duplicate c-(1/n)
{ @\ }do # Move n back to the second element of the stack
{ 0>}do # Check if our c-(1/n) is less than zero. If so, leave the loop.
{ }do # If not, repeat, but with c-(1/n) as our new c.
\; # Remove c once it's below 0, leaving our tally. This gets outputted.
```
### Old Solution (21)
```
:c;0.{\).-1?@+.c<}do;
```
### Old Solution Explanation
```
:c;0.{\).-1?@+.c<}do; # Take in a number c and find the lowest n s.t. Hn>c
:c; # Set c to our goal number, then pop it from our stack.
0. # Make our stack [0 0]. Let will be our n, right will be our running sum.
{ }do # At the end of each loop, if the top of the stack isn't 0, repeat.
{\) }do # Move the n to the top of the stack and increment it by 1.
{ .-1? }do # Duplicate it, then inverse it.
{ @ }do # Bring our running total to the top (now third in the stack behind 1/n and n)
{ + }do # Add the top two elements (running total + 1/n)
{ . }do # Duplicate the running total
{ c<}do # If it's less than c, print 1 (repeat do), else 0 (stop do)
; # Pop our running total, leaving behind just our n.
```
Shouldn't be too hard to shave a char off somewhere.
Got one.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 10 9 bytes
```
fgZ=-Qc1T
```
[Try it online!](https://tio.run/##K6gsyfj/Py09ylY3MNkw5P9/Qz1TAA "Pyth – Try It Online")
Explaination:
```
# Implicit Q=eval(input())
f # The first element T of [1,2,3,...] where
gZ # 0 >=
=-Qc1T # Q = Q - (1/T)
# Implicit print
```
-1 -2 bytes thanks to @issacg
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
1İ€S<¬ʋ1#
```
A monadic Link accepting a number which yields a list containing one integer; as a full program it prints that integer.
**[Try it online!](https://tio.run/##y0rNyan8/9/wyIZHTWuCbQ6tOdVtqPwfKKBnCgA "Jelly – Try It Online")**
### How?
```
1İ€S<¬ʋ1# - Link: number, x
1 - set left to one
1# - count up (from n=left) finding the first (1) n such that:
ʋ - last four links as a dyad - f(n, x)
İ€ - inverse each (of [1..n])
S - sum
< - less than (x)?
¬ - logical NOT
```
---
```
‘!İ€Ä<⁸S‘
```
Is another 9 but it's much less efficient as \$x\$ gets bigger since it builds a list of the first \$(x+1)!\$ harmonic numbers.
[Answer]
# [Red](http://www.red-lang.org), 53 bytes
```
f: func[n][i: 0 until[0 >= n: n -(1.0 /(i: i + 1))]i]
```
[Try it online!](https://tio.run/##DctBCoMwEEbhq/xLpZhmqkEI1EN0O8yiaIIDMpag50@zfR@vpK1@0sZSc0S@bWUT1giP2y492GN5wyIMQ0fO49k1VDxAfS/arrOk77o3Z3IBL4wYHU0UMCFgbom8MH5F7QIb4rAgw0TqHw "Red – Try It Online")
Simple iterative solution.
# [Red](http://www.red-lang.org), 78 bytes
```
f: func[n /a i][either a[either n > 0[f/a n -(1.0 / i)i + 1][i - 1]][f/a n 1]]
```
[Try it online!](https://tio.run/##NY2xCsMwDER/5caWYidqYgoZ8hFdhQeTWESLWkz6/a6Gdrp3PI5rde/PunPuskA@trFhKNDMVc@jNpQ/GFaMLC4N4UJxxAC9Km6gzIrgkX/aqcur1bId3phiwh0TpkgzJcxIeMSUGe@mdsIfl7BCYD77Ag "Red – Try It Online")
I know this is way longer than other recursive solutions, but I wanted to post it because of the fact that [Red](http://www.red-lang.org) functions have fixed arity. In order to simulate default values for the additional parameters, we need to use a `refinement` - here it's `/a`- whenever we need the value of the `i` parameter.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 27 bytes
```
rds1@1moiT{1j?/g1++cm0>=}fi
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KKXY0MEwNz8zpNowy14/3VBbOznXwM62Ni3z/39zPVMA "Burlesque – Try It Online")
For some reason save/load seems to be working a bit funny with this one on TIO. To test the code, use the following:
# [Burlesque](https://github.com/FMNSSun/Burlesque), 28 bytes
```
rd@1moiT{1j?/++cm0>=}x/4iafi
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KMXBMDc/M6TaMMteX1s7OdfAzra2Qt8kMzEt8/9/cz1TAA "Burlesque – Try It Online")
```
rd # Read input as double
[s1] # Save slot 1
@1 # 1.0
mo # Infinite multiples of {1.0, 2.0, 3.0...}
iT # All tails of {{}, {1.0}, {1.0,2.0}, {1.0,2.0,3.0},...}}
{
1j?/ # Reciprocal
++ # Sum
[g1] # Get slot 1 (not working)
cm # UFO operator (-1 on <, 0 on ==, 1 on >)
-1.> # 0 or 1
}
x/ # Reorder stack
3ia # Insert input at position 3 of array (before compare)
fi # Find first index
```
[Answer]
# [J](http://jsoftware.com/), 29 28 bytes
*-1 byte thanks to RGS*
Shameless translation of [Jo King's APL answer](https://codegolf.stackexchange.com/a/199193).
```
3 :'>:1 i.~y&<:+/\%}.i.<.^y'
```
Probably a lot of room for improvement, but I couldn't find a shorter tacit way.
[Try it online!](https://tio.run/##DcgxDkBAEAXQ3il@JCzB2LE2kgkaiUqlFo0QNGoFV1@K17zT@aQ2NAKFFBryywjdOPTOQFQrjIPeO6wlyafgoYNqmm/lYm9d9gubrxExWRQwMMQlW5SwqP5iHbsP "J – Try It Online")
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 52 bytes
```
define f(x){
scale=999
for(s=i=0;s<x;s=s+1/i)i=i+1
}
```
[Try it online!](https://tio.run/##TU7NToQwEL73KcaeaHZcmfKftT6JF4WyaeIWQruK2fDsyBZQe/r@p@/1PDe6NVZDG43ixlz99qFVVVWs7YbIKaPik3seT065Az0ZYZQ5EJtmtrU@O9OA185HxvZXj3rsde11I9iNwfKa6@XyDWpZD74I4rnzi2QC7gdjPaxl4PD4AhzvgWCaFqJ7@EHB7zCsw39dDl9DZ888yNO/Uf5qOZvYHL5HxwylYAFLTDeUINEOj5RShpRsPMVktzIsd7VYZiimbKMUI8kkLwRbeY5SFnsUc8o3XCLlxX6UJFaUlLFgPw "bc – Try It Online")
If you need more precision, change the 999 to 9E3 or 9E9. Expect memory usage to skyrocket and performance to plummet.
I'm testing a variant that prints as it passes integers. It matches [OEIS A004080](https://oeis.org/A004080) so far
(23 -> 5471312310).
With scale=9, it is correct to 11 -> 33617 but is off by 4 for 12.
With scale=99, it is so far accurate to 25 -> 40427833596.
Since scale=99 can't be extended without adding another byte, I'm not going to claim it.
[Answer]
## [W](https://github.com/A-ee/w) `d`, 8 bytes
Let's see if I can come tied with 05AB1E ...
```
♠wⁿ=^φ→§
```
Uncompressed:
```
kJrJb<!iX
```
Explanation
```
iX % Foreach in [1 .. +inf],
% find first number that satisfies:
k % Range of 1 .. number
Jr % Reciprocal each
J % Summation of entire list
b<! % Is that >= the input?
```
[Answer]
## [W](https://github.com/A-ee/w) `d`, ~~11~~ 9 bytes
```
╪ª4PĽ┌∙×
```
Uncompressed:
```
i1ak/+rb<!W
```
## Explanation
```
i W % Find the first number from 1 to positive infinity
% That satisfies this condition
ak % Generate a range from 1 to the number
1 / % Find the reciprocal of every item (automatically vectorises)
+r % Reduce by addition
b<! % Is this number greater than or equal to the input?
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~12~~ ~~11~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
>0©ÒßUÉ/°T
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=PjCp0t9VyS%2bwVA&input=My4xNDE1)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
⊞υ¹W‹ΣυIθ⊞υ∕¹⊕LυILυ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1RHwVDTmqs8IzMnVUHDJ7W4WCO4NFejVFNHwTmxuESjUFNTUwGm0iWzLDMlVcNQR8EzL7koNTc1ryQ1BagpL70EKA9UCTQpoCgzr0QDrBdJwvr/f2M9QxNDs/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ¹
```
Start off with `n=1`, pushing `1/1` to the predefined list.
```
W‹ΣυIθ
```
Repeat while the list sums to less than the target...
```
⊞υ∕¹⊕Lυ
```
... push the next Egyptian fraction to the list.
```
ILυ
```
Output the length of the list, i.e. `n`.
It might be possible to reduce the floating-point inaccuracy slightly by adding a `Reverse` after the `Sum`.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), [`-hr`](https://github.com/JonoCode9374/Keg/blob/master/Keg.py#L791), 12 [bytes](https://github.com/JonoCode9374/Keg/blob/master/Codepage.txt)
```
0&0{¿⑻>|:⑨⑱⑼
```
Uses the most recent Keg interpreter, so no TIO thus far.
## Explained
```
0&
```
We store `0` in the register as this will be the means of storing the total sum of the series.
```
0
```
We then push `0` onto the stack, as this will be what keeps track of the term number (`n`)
```
{¿⑻>|
```
The condition of the while loop is that it will repeat while the input (which is automatically filled if no input is given -- the reason why this doesn't have a TIO link) is greater than the value in the register.
```
⑨
```
We then increment the top of the stack to get to the next term. This is done before the reciprocal is taken so that we avoid an "off-by-one" error.
```
:⑱⑼
```
We then take the reciprocal of the top of the stack and add it to the register (`⑱` = `1/x` and `⑼` = `register += t.o.s`). `-hr` will automatically print the top of the stack at end of execution as an integer.
Here is a [Try it online](https://tio.run/##AScA2P9rZWf//8K/wq5pMCYwe8KpaeKRuz584pGoOuKRseKRvP//M/8taHI "Keg – Try It Online") version that uses a variable to keep track of the input. This is mainly just so that y'all can see that the algorithm works, as the variables can be replaced with the above 12 byter.
[Answer]
# [Scratch 3.0](https://scratch.mit.edu), 15 blocks / 127 bytes
[![Scratch blocks](https://i.stack.imgur.com/6MrY2.png)](https://i.stack.imgur.com/6MrY2.png)
```
when gf clicked
ask()and wait
set[n v]to(0
set[t v]to(0
repeat until<(t)>(answer
change[n v]by(1
change[t v]by((1)/(n
end
say(n
```
Just a port of my Keg answer, so [Try it on~~line~~ Scratch!](https://scratch.mit.edu/projects/366608019/)
[Answer]
# [Julia 1.0](http://julialang.org/), ~~27~~ 24 bytes
```
>(x,i=1)=1+(0<x-1/i>i+1)
```
[Try it online!](https://tio.run/##DchBCoAgEAXQ6zg0Tf5U2qQXiRYtJ0QiCrz91Fu@8616oJsV11kzKGNwfu0jJi06gOy6tT21iZPiNkjimQMHQUTiyImXv@B3IvsA "Julia 1.0 – Try It Online")
-3 bytes thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz)
the same approach as [xnor](https://codegolf.stackexchange.com/a/199201/98541)
[Answer]
# [Python 3](https://docs.python.org/3/), 39 bytes
```
lambda n:sum(1/x for x in range(1,n+1))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUSHPqrg0V8NQv0IhLb9IoUIhM0@hKDEvPVXDUCdP21BT8/9/AA "Python 3 – Try It Online")
Pretty simple.
] |
[Question]
[
Your job is to simulate a couple of keystrokes that a user types in.
**Input**
A string array or string with a delimiter of your choice (outside the range 32-126) containing at least one 'keystroke'.
This array will only contain two types of string: passive keystrokes (single chars) and commands (chars within brackets `[ ]`).
* Passive keystrokes
1. ASCII character codes `[32-126]`
* Commands:
1. `[B]` : backspace (remove last character added if there is one)
2. `[C]` : copy all of what has already been written
3. `[D]` : delete all of what has been written
4. `[P]` : paste what has been copied
**Output**
The string produced by the keystrokes.
**Examples**
```
['H', 'e', 'l', 'l', 'o'] -> 'Hello'
['H', 'e', 'l', 'l', 'o', ' ', '[C]', '[P]'] -> 'Hello Hello '
['[D]', 'D', '[B]'] -> ''
['H', '[C]', 'i', '[P]', '[C]', '[P]'] -> 'HiHHiH'
['e', '[C]', '[B]', 'I', ' ', 'l', 'i', 'k', '[P]', ' ', 'b', '[P]', '[P]', 's', '!'] -> I like bees!
['N', '[P]'] -> 'N'
['#', '5', '0', 'K', '0', '0', '1', '[D]', '#', 'n', 'o', 't'] -> '#not'
['H', 'o', 'w', ' ', '[D]', 'H', 'e', 'y'] -> 'Hey'
['s', 'u', 'd', '[B]', 'p', '[C]', '[D]', 'I', ' ' , 'h', 'a', 'v', 'e', ' ', '[P]', 'p', 'e', 'r', '!'] -> 'I have supper!'
```
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!**
[Answer]
# Vim, ~~76, 64, 62~~, 58 keystrokes
*Thanks to Loovjo for saving 7 keystrokes*
---
Did someone say **simulate keystrokes?** Well then, it's a good thing my favorite language to golf in is all *about* simulating keystrokes!
```
:no s :%s/\M[
sB]/<C-v><C-h>
sC]/<C-v><esc>0y$A
sD]/<C-v><esc>"_S
sP]/<C-v><C-r>"
s<bs>\n
S<C-r>"
```
Input comes in this format:
```
h
e
l
l
o
[C]
[P]
```
This is a pretty straightforward answer. It just translates each "command" to the vim keystroke equivalent of that command. Let's take it line by line.
```
:no s :%s/\M[
```
This saves a *ton* of bytes. Vim has a builtin "command line" where you can create mappings, change settings, save files, etc. Here we are creating a mapping. `:no` is short for `:nnoremap` which means "When we are in normal mode, substitute this left hand side for this right hand side." Since we are calling `:%s/` *five different times*, this saves a lot. The `\M` is a nice trick. It means that the following search will be "Very No Magic", which means that the regex `[B]` will match the literal text `[B]` rather than a range containing just a B in it. Since the majority of the substitute commands have a brackets in them, we fill in the first one.
Then, we call five substitute commands. It's worth noting why I called `<C-v>` so many times. Characters like `<esc>`, `<C-v>`, `<C-r>`, etc. are unprintable characters, and must be typed into the command line with a `<C-v>`.
* [B]: backspace. This one is pretty easy. Simply substitute each `[B]` with `Ctrl-h`, which is equivalent to backspace in vim.
* [C]: copy all of what has already been written. This is translated to `<esc>0y$A`. This means:
```
<esc> " Escape to normal mode
0 " Move to the beginning of this line
y$ " Yank to the end of the line
A " Re enter insert mode at the end of this line.
```
We could *almost* simply do `Y` in place of `0y$` which means "yank the whole line", but this also grabs a newline that we don't want.
* [D]: delete all of what has been written. This is `<esc>"_S`. As before, `<esc>` exits insert mode so we can run commands. There are some things that are more convenient here. So we do
```
S " Delete this whole line and enter insert mode again
"_ " Send it to 'the black hole register'. This is just so that we don't overwrite the main register.
```
* [P]: paste what has been copied. This one is also very straightforward. It is just `<C-r>"` which means `Insert the contents of register '"'`. `"` happens to be the main register that 'y' yanks to.
Now that we have translated all of the commands, we must join all the lines together by removing all of the newline characters. Thanks to our mapping, this is just
```
s<bs>\n
```
The `<bs>` is a backspace, (ASCII 0x08) and we need it because of the `[` we filled in.
By now, we have translated the input into vim code, and we just need to run it. So we:
```
S " Delete this whole line and enter insert mode
<C-r>" " Insert the keystrokes of register '"' as if they were typed by the user
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 33 bytes
```
q~{_[`';"];""L~""]:L~"]\1>3b=}%s~
```
[Try it online!](http://cjam.tryitonline.net/#code=cX57X1tgJzsiXTsiIkx-IiJdOkx-Il1cMT4zYj19JXN-&input=WyJzIiAidSIgImQiICJbQl0iICJwIiAiW0NdIiAiW0RdIiAiSSIgIiAiICAiaCIgImEiICJ2IiAiZSIgIiAiICJbUF0iICJwIiAiZSIgInIiICIhIl0)
## Explanation
```
q~ Read an evaluate input list.
{ }% Map over each string in it:
_ Duplicate the string, say S.
[`';"];""L~""]:L~"] Replace it the following list:
[repr(S) '; "];" "L~" "]:L~"]
\ Bring S on top of the stack.
1> Chop off the first char.
3b Base-3 conversion.
= Modular index into the list.
s~ Concatenate and run as CJam code.
```
The “hash function” `1>3b` maps
* single-character strings to **0** (= 0 mod 5),
* `[B]` to **291** (= 1 mod 5),
* `[D]` to **297** (= 2 mod 5),
* `[P]` to **333** (= 3 mod 5),
* `[C]` to **294** (= 4 mod 5).
This value (mod 5) is used as an index into a list of CJam code snippets:
* For single-character strings, say `h`, the snippet `"h"` is returned, which pushes a single-character string to the stack.
* For `[B]`, the snippet `;` is returned, which pops an element.
* For `[D]`, the snippet `];` is returned, which clears the stack.
* For `[P]`, the snippet `L~` is returned, which appends variable `L` onto the stack.
* For `[C]`, the snippet `]:L~` is returned, which stores the current stack in the variable `L`.
These snippets are concatenated and executed; the final stack is printed implicitly by CJam. `L` is initially the empty list, so the copy buffer is initially “empty”.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~34~~ ~~33~~ ~~31~~ 27 bytes
Uses [CP-1252](http://www.cp1252.com/) encoding.
```
õUvygiyJë"XJ¨DU\"4äyáÇ5%è.V
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w7VVdnlnaXlKw6siWErCqERVXCI0w6R5w6HDhzUlw6guVg&input=WydzJywgJ3UnLCAnZCcsICdbQl0nLCAncCcsICdbQ10nLCAnW0RdJywgJ0knLCAnICcgLCAnaCcsICdhJywgJ3YnLCAnZScsICcgJywgJ1tQXScsICdwJywgJ2UnLCAncicsICchJ10)
**Explanation**
```
õU # initialize X as the empty string
v # for each y in input
ygiyJ # if len(y) == 1 join y with stack
ë # else
"XJ¨DU\" # push this string
4ä # split into 4 parts (of size [2,1,2,1])
yá # push only letters of y
Ç5% # mod its ascii code by 5
è # index into the string above with this
.V # evaluate as 05AB1E code
```
The pairs of functions evaluated in the code above are:
```
DU # [C] -> duplicate and store in X
XJ # [P] -> push X and join with stack
¨ # [B] -> remove last char of string
\ # [D] -> remove top of stack
```
Saved 4 bytes using the `mod 5` trick from [Lynn's CJam answer](https://codegolf.stackexchange.com/a/95825/47066)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~50 51~~ 48 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṿ”;;µṭ“Ṗ“ø©“ḣ0“;®”
L>1a2ị$i@“BCDP0”ịÇ
Ç€“⁶Ṗ©”;FV
```
**[TryItOnline](http://jelly.tryitonline.net/#code=4bm-4oCdOzvCteG5reKAnOG5luKAnMO4wqnigJzhuKMw4oCcO8Ku4oCdCkw-MWEy4buLJGlA4oCcQkNEUDDigJ3hu4vDhwrDh-KCrOKAnOKBtuG5lsKp4oCdO0ZW&input=&args=WydlJywgJ2UnLCAnZScsICdbQl0nLCAnW0NdJywgJ1tCXScsICdbRF0nLCAnSScsICcgJywgJ2wnLCAnaScsICdrJywgJ1tQXScsICdbQl0nLCAnICcsICdiJywgJ1tQXScsICdzJywgJyEnXQ)**
Or [all test cases](http://jelly.tryitonline.net/#code=4bm-4oCdOzvCteG5reKAnOG5luKAnMO4wqnigJzhuKMw4oCcO8Ku4oCdCkw-MWEy4buLJGlA4oCcQkNEUDDigJ3hu4vDhwrDh-KCrOKAnOKBtuG5lsKp4oCdO0ZWCsOH4oKsWQ&input=&args=W1snSCcsICdlJywgJ2wnLCAnbCcsICdvJ10sWydIJywgJ2UnLCAnbCcsICdsJywgJ28nLCAnICcsICdbQ10nLCAnW1BdJ10sWydbRF0nLCAnRCcsICdbQl0nXSxbJyddLFsnZScsICdbQ10nLCAnW0JdJywgJ0knLCAnICcsICdsJywgJ2knLCAnaycsICdbUF0nLCAnICcsICdiJywgJ1tQXScsICdbUF0nLCAncycsICchJ10sWydOJywgJ1tQXSddLFsnIycsICc1JywgJzAnLCAnSycsICcwJywgJzAnLCAnMScsICdbRF0nLCAnIycsICduJywgJ28nLCAndCddXQ)
### How?
```
Ṿ”;;µṭ“Ṗ“ø©“ḣ0“;®” - Link 1, CreateCodeLookupValueList: keystroke
“Ṗ“ø©“ḣ0“;®” - list of strings, ["Ṗ","ø©","ḣ0"";®"] - these are Jelly code for:
Ṗ : pop (i.e. delete last entry)
ø© : niladic separation and copy to register (i.e. copy)
ḣ0 : head to 0 (i.e. delete all entries)
;® : concatenate with value of register (i.e. paste)
µ - monadic chain separation
Ṿ - uneval - make a Jelly code version of the keystroke
e.g. "I" -> "“I”"
”; - string literal ";" |
; - concatenate e.g. ";I" v
ṭ - tack, to make the list ["Ṗ","ø©",";®","“I”"]
a keystroke - a command will evaluate to a string like
"“[C]”" but wont be accessed)
L>1a2ị$i@“BCDP0”ịÇ - Link 2, ConvertAKeystokeToJellyCodeString: keystroke
L>1 - length greater than 1? (i.e. isCommand?)
$ - last two links as a monad
a - and
2ị - index 2 of the keystroke (0 due to and for a passive keystroke)
“BCDP0” - Literal string "BCP0"
i@ - find first matching index of, with reversed arguments
ị - index into
Ç - call last link (1) as a monad (get code to replace this keystroke)
Ç€“⁶Ṗ©”;FV - Main link: list of keystrokes
Ç€ - call last link (2) as a monad (convert to Jelly code)
“⁶Ṗ©” - literal string "⁶Ṗ©" - setup the register with an empty string:
⁶ :literal " ";
Ṗ : pop the space to give an empty string;
© : places it into the register
; - concatenate (put that at the front)
F - flatten list (lists and strings are equivalent in Jelly)
V - evaluate the string
```
For example
```
The input:
['e', '[C]', '[B]', 'I', ' ', 'l', 'i', 'k', '[P]', ' ', 'B', '[P]', '[P]', 's', '!']
Becomes the Jelly code:
"⁶Ṗ©;“e”ø©Ṗ;“I”;“ ”;“l”;“i”;“k”;®;“ ”;“B”;®;®;“s”;“!”"
Which then evaluates to
"I like Bees!"
```
- with a capital `'B'` as a test case, since before I fixed a bug it would have returned `"I likeees!"`
[Answer]
# JavaScript (ES6), ~~84~~ ~~80~~ ~~77~~ 76 bytes
*Saved 3 bytes thanks to @Neil, 1 more thanks to @edc65*
```
x=>x.reduce((s,[c,z])=>z<'C'?s.slice(0,-1):z<'D'?t=s:z<'P'?"":s+=z?t:c,t="")
```
`.map` is two bytes longer:
```
x=>x.map(([c,z])=>s=z<'C'?s.slice(0,-1):z<'D'?t=s:z<'P'?"":s+=z?t:c,s=t="")&&s
```
### Test snippet
```
f=x=>x.reduce((s,[c,z])=>z<'C'?s.slice(0,-1):z<'D'?t=s:z<'P'?"":s+=z?t:c,t="")
console.log(f(['e', '[C]', '[B]', 'I', ' ', 'l', 'i', 'k', '[P]', ' ', 'b', '[P]', '[P]', 's', '!']))
```
```
<button onclick="console.log(f(I.value.split('\n')))">Run</button>
<br><textarea id=I rows=10>H
e
l
l
o
[C]
[P]</textarea><br>
```
[Answer]
# Python 2, 96 95 93 bytes
```
r=c=""
for o in input():c=[c,r][x=="[C]"];r=[r+c,r[:-1],r,"",r+o][ord(o[1:2]or"E")%5]
print r
```
[Answer]
# Perl, ~~53~~ 50 bytes
Includes +1 for `-p`
Give input on STDIN terminated by newlines (the last newline may be left out, so it counts as a string separated by newlines):
```
keystrokes.pl
H
e
[C]
[D]
a
b
[B]
[P]
z
^D
```
gives
```
aHez
```
`keystrokes.pl`:
```
#!/usr/bin/perl -p
$\.=/^.$/?$&:/P/?$a:(/C/?$a=$\:chop($\x=/B/))x0}{
```
Almost caught the Jelly answer but the fiend escaped to 48 bytes...
[Answer]
# Python ~~120 119~~ 116 bytes
```
f=lambda s,r='',c='':f(s[1:],*{'B':(r[:-1],c),'C':(r,r),'D':('',c),'P':(r+c,c),'':(r+s[0],c)}[s[0][1:2]])if s else r
```
**[Ideone](http://ideone.com/bijrJb)**
A recursive function with input, `s`, a list of the key-strokes.
Each recursive call updates the return text, `r` and, in the case of a `[C]`, the clipboard, `c` until `s` is empty.
The new values of `r` and `c` are found by indexing into a dictionary, `{...}`, and passed with unpacking, `*`. For the passive keystrokes `s[0][1:2]`will return an empty string and the key `''` will be used instead.
[Answer]
# Haskell, ~~136 133 130~~ 127 bytes
```
k c b(('[':m:_):i)|m<'C'=k c[q|b>"",q<-init b]i|m<'D'=k b b i|m<'P'=k c""i|1<3=k c(b++c)i
k c b(s:i)=k c(b++s)i
k c b[]=b
k""""
```
[Try it on Ideone.](http://ideone.com/Kz9wO8)
**Explanation:** `k` performs a tail recursion over a list of commands. `b` is the buffer in which the string is constructed, `c` saves the copied part.
```
k c b ("[B]":i) = k c (take(length b - 1)b) i -- remove last element of buffer
k c b ("[C]":i) = k b b i -- set copy to buffer
k c b ("[D]":i) = k c "" i -- clear the buffer
k c b ("[P]":i) = k c (b++c) i -- append content of copy to the buffer
k c b (s:i) = k c (b++s) i -- append char to the buffer
k c b [] = b -- command list is empty, return buffer
f = k "" "" -- initialise copy and buffer with empty strings
```
**Edit:** To save some bytes the commands`[B][C][D][P]`are no longer matched exactly but compared: less than `'C'`? -> `B` and so on.
Thanks to [@nimi](https://codegolf.stackexchange.com/users/34531/nimi) for saving 3 bytes.
[Answer]
# Mathematica, 100 bytes
```
""<>Fold[Switch[#2,"[B]",Most@#~Check~{},"[C]",a=#,"[D]",{},"[P]",#~Join~a,_,Append@##]&,a={};{},#]&
```
Anonymous function. Takes a list of strings as input and returns a string as output. Ignore any messages generated.
[Answer]
# Java 7, ~~207~~ 203 bytes
```
String c(String[]a){String r="",c=r;for(String s:a){int k=s.length(),l=r.length(),z;if(k>1){z=s.charAt(1);r=z<67?l>0?r.substring(0,l-1):"":z<68?r:z<69?"":z<81?r+c:r+s;c=z==67?r:c;}r+=k<2?s:"";}return r;}
```
This can most definitely be golfed some more, ~~but this is my initial answer. Will edit after I found something to remove those `equals`-checks..~~ replaced with `charAt`, but can probably still be golfed..
**Ungolfed & test code:**
[Try it here.](https://ideone.com/YHXSe2)
```
class M{
static String c(final String[] a) {
String r = "",
c = r;
for(String s : a){
int k = s.length(),
l = r.length(),
z;
if(k > 1){
z = s.charAt(1);
r = z < 67
? l > 0
? r.substring(0, l-1)
: ""
: z < 68
? r
: z < 69
? ""
: z < 81
? r + c
: r + s;
c = z == 67
? r
: c;
}
r += k < 2
? s
: "";
}
return r;
}
public static void main(String[] a){
System.out.println(c(new String[]{ "H", "e", "l", "l", "o" }));
System.out.println(c(new String[]{ "H", "e", "l", "l", "o", " ", "[C]", "[P]" }));
System.out.println(c(new String[]{ "[D]", "D", "[B]" }));
System.out.println(c(new String[]{ "H", "[C]", "i", "[P]", "[C]", "[P]" }));
System.out.println(c(new String[]{ "e", "[C]", "[B]", "I", " ", "l", "i", "k", "[P]", " ", "b", "[P]", "[P]", "s", "!" }));
System.out.println(c(new String[]{ "N", "[P]" }));
System.out.println(c(new String[]{ "#", "5", "0", "K", "0", "0", "1", "[D]", "#", "n", "o", "t" }));
System.out.println(c(new String[]{ "H", "o", "w", " ", "[D]", "H", "e", "y" }));
System.out.println(c(new String[]{ "s", "u", "d", "[B]", "p", "[C]", "[D]", "I", " ", "h", "a", "v", "e", " ", "[P]", "p", "e", "r", "!" }));
}
}
```
**Output:**
```
Hello
Hello Hello
HiHHiH
I like bees!
N
#not
Hey
I have supper!
```
[Answer]
# PHP, 131 Bytes
17 Bytes save by @IsmaelMiguel ternary operator
```
<?$c=[];foreach($_GET[a]as$v)($t=$v[1])!=P?$t!=C?$t!=B?$t!=D?$o[]=$v:$o=[]:array_pop($o):$c=$o:$o=array_merge($o,$c);echo join($o);
```
[Answer]
# PHP, 108 bytes
```
for(;null!==$s=$argv[++$i];)($g=$s[1])!=B?$g!=C?$g!=D?$o.=$g!=P?$s:$c:$o='':$c=$o:$o=substr($o,0,-1);echo$o;
```
Uses a string based approach rather than an array based one.
Use like:
```
php -r "for(;null!==$s=$argv[++$i];)($g=$s[1])!=B?$g!=C?$g!=D?$o.=$g!=P?$s:$c:$o='':$c=$o:$o=substr($o,0,-1);echo$o;" a b "[C]" "[B]" "[P]" "[C]" "[D]" j "[P]"
```
edit: saved 8 bytes by fiddling the order of the ?:s and making them negative to avoid having to use so many brackets;
[Answer]
# SpecBAS - 216 bytes
```
1 s$,t$="": INPUT a$: DIM b$(SPLIT a$,NOT ",")
2 FOR EACH l$ IN b$()
3 CASE l$
4 WHEN "[B]": s$=s$( TO LEN s$-1)
5 WHEN "[C]": t$=s$
6 WHEN "[D]": s$=""
7 WHEN "[P]": s$=s$+t$
8 OTHERWISE : s$=s$+l$
9 END CASE
10 NEXT l$: ?s$
```
Input is given as a string with commas, which is then turned into array.
[![enter image description here](https://i.stack.imgur.com/eI2NA.png)](https://i.stack.imgur.com/eI2NA.png)
[Answer]
# [V](https://github.com/DJMcMayhem/V), 49 bytes
```
íÛBÝ/
íÛCÝ/0y$A
íÛDÝ/"_S
íÛPÝ/"
íî
0éiD@"
```
[Try it online!](http://v.tryitonline.net/#code=w63Dm0LDnS8WCArDrcObQ8OdLxYbMHkkQQrDrcObRMOdLxYbIl9TCsOtw5tQw50vFhIiCsOtw64KMMOpaURAIg&input=SAplCmwKbApvCiAKW0NdCltQXQ)
Since this contains unprintable characters, here is a hexdump:
```
0000000: eddb 42dd 2f16 080a eddb 43dd 2f16 1b30 ..B./.....C./..0
0000010: 7924 410a eddb 44dd 2f16 1b22 5f53 0aed y$A...D./.."_S..
0000020: db50 dd2f 1612 220a edee 0a30 e969 4440 .P./.."....0.iD@
0000030: 22
```
This is just a direct translation of [my vim answer](https://codegolf.stackexchange.com/a/95734/31716) so that I could compete with Jelly. Unfortunately, I'm still one byte over, but I'm still working on the last one. :)
I'm more proud of that answer anyway, so if you want a very detailed explanation, read that one instead.
[Answer]
## Actually, 56 bytes
```
''j"'[B]"'XaÆ"'[C]""k;╗i"aÆ"'[P]""╜i"aÆ"'[D]"'éaÆ''+ƒkΣR
```
[Try it online!](http://actually.tryitonline.net/#code=JydqIidbQl0iJ1hhw4YiJ1tDXSIiazvilZdpImHDhiInW1BdIiLilZxpImHDhiInW0RdIifDqWHDhicnK8aSa86jUg&input=WydIJywgJ2UnLCAnbCcsICdsJywgJ28nLCAnICcsICdbQ10nLCAnW1BdJ10)
Explanation:
```
''j"'[B]"'XaÆ"'[C]""k;╗i"aÆ"'[P]""╜i"aÆ"'[D]"'éaÆ''+ƒkΣR
''j insert an apostrophe between every pair of commands
"'[B]"'XaÆ"'[C]""k;╗i"aÆ"'[P]""╜i"aÆ"'[D]"'éaÆ replace:
"'[B]"'XaÆ "'[B]" with "X"
"'[C]""k;╗i"aÆ "'[C]" with "k;╗i"
"'[P]""╜i"aÆ "'[P]" with "╜i"
"'[D]"'éaÆ "'[D]" with "é"
''+ prepend an apostrophe
now the input has been converted to the equivalent Actually program ("'<character>" pushes the character, "X" removes the last character, "k;╗i" saves the current stack state to a register, and "╜i" pushes the saved stack state)
ƒ execute the code
kΣ concatenate the characters
R reverse the string
```
[Answer]
# Java, 181
```
String v(String[]a){String r="",c=r;for(String s:a){try{int p=s.charAt(1)%5;r=p<1?r+c:p>2?"":p==1?r.length()<2?"":r.split(".$")[0]:r;c=p==2?r:c;}catch(Exception e){r+=s;}}return r;}
```
More readable version:
```
String v(String[]a){
String r="",c=r;
for(String s:a){
try{
int p=s.charAt(1)%5;
r= p<1
? r+c
: p>2
? ""
:p==1
? r.length()<2
?""
:r.split(".$")[0]
:r;
c=p==2?r:c;
}catch(Exception e){
r+=s;
}
}return r;
}
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 46 bytes
```
vXKx"@gtnq?2)XJ66=?3L)}J67=?XK}J68=?vx}K]]]]&h
```
[Try it online!](http://matl.tryitonline.net/#code=dlhLeCJAZ3RucT8yKVhKNjY9PzNMKX1KNjc9P1hLfUo2OD0_dnh9S11dXV0maA&input=eydIJywgJ2UnLCAnbCcsICdsJywgJ28nLCAnICcsICdbQ10nLCAnW1BdJ30) Or [verify all test cases](http://matl.tryitonline.net/#code=YAp2WEt4IkBndG5xPzIpWEo2Nj0_M0wpfUo2Nz0_WEt9SjY4PT92eH1LXV1dXSZoCl1EVA&input=eydIJywgJ2UnLCAnbCcsICdsJywgJ28nfQp7J0gnLCAnZScsICdsJywgJ2wnLCAnbycsICcgJywgJ1tDXScsICdbUF0nfQp7J1tEXScsICdEJywgJ1tCXSd9CnsnSCcsICdbQ10nLCAnaScsICdbUF0nLCAnW0NdJywgJ1tQXSd9CnsnZScsICdbQ10nLCAnW0JdJywgJ0knLCAnICcsICdsJywgJ2knLCAnaycsICdbUF0nLCAnICcsICdiJywgJ1tQXScsICdbUF0nLCAncycsICchJ30KeydOJywgJ1tQXSd9CnsnIycsICc1JywgJzAnLCAnSycsICcwJywgJzAnLCAnMScsICdbRF0nLCAnIycsICduJywgJ28nLCAndCd9CnsnSCcsICdvJywgJ3cnLCAnICcsICdbRF0nLCAnSCcsICdlJywgJ3knfQp7J3MnLCAndScsICdkJywgJ1tCXScsICdwJywgJ1tDXScsICdbRF0nLCAnSScsICcgJyAsICdoJywgJ2EnLCAndicsICdlJywgJyAnLCAnW1BdJywgJ3AnLCAnZScsICdyJywgJyEnfQ).
### Explanation
```
v % Push empty array
XK % Copy to clipboard K. This initiallizes it as empty
x % Delete
" % Implicitly input cell array. For each
@g % Push current cell's contents
t % Duplicate elements
n % Number of elements
q? % If more then 1
2) % Get second char. Copy to clipboard J
66=? % If it ss 'B'
3L) % Remove last element from string built up to now
} % Else
J67=? % If it was a 'C'
XK % Copy string built up to now into clipboard K
} % Else
J68=? % If was a 'D'
vx % Delete stack. This deletes string built up to now, if any
} % Else: it was a 'P'
K % Paste from clipboard K
] % End if
] % End if
] % End if
] % End if
&h % Horizontally concatenate stack
% Implicitly end for
% Implicitly display
```
[Answer]
# TCL, 186 bytes
```
proc t w {foreach "B C P N D r Q" [list {[string range $r 0 end-1]} {[set Q $r]} {$r$Q} {$r$g}] break;foreach g $w {eval "set c \$[string index ${g}N 1]";eval "set r \"$c\""};return $r}
```
Nicely formatted:
```
proc t w {
foreach "B C P N D r Q" [list {[string range $r 0 end-1]} {[set Q $r]} {$r$Q} {$r$g}] break;
foreach g $w {
eval "set c \$[string index ${g}N 1]"
eval "set r \"$c\""
}
return $r
}
```
I just wanted to prove I could do this in TCL
[Answer]
# Scala, 158 bytes
```
(i:Seq[String])=>(("","")/:i){case((a,c),k)=>if(k.size<2)(a+k,c)else
if(k=="[B]")(a dropRight 1,c)else
if(k=="[C]")(a,a)else
if(k=="[D]")("",c)else(a+c,c)}._1
```
Ungolfed:
```
(i:Seq[String]) => i.foldLeft(("", "")){
case ((res,clipboard),key) =>
if (k.size == 1) (res+key,clipboard)
else if (k=="[B]") (res dropRight 1, clipboard)
else if (k=="[C]") (res, res)
else if (k=="[D]") ("", clipboard)else(acc+clipboard,clipboard)
}._1
```
Solves this problem as a fold with the result and the clipboard as accumulator. Sadly, scala doesn't have a ternary conditional operator, but instead uses `if else` as an expression.
[Answer]
# PHP 7.1, ~~95~~ 92 bytes
Note: requires PHP 7.1 for negative string offsets.
```
for(;n|$i=$argv[++$x];)($l=$i[1])?$l^r?$l^s?$l^t?$o.=$c:$o="":$c=$o:$o[-1]="":$o.=$i;echo$o;
```
Without negative string offsets (101 bytes):
```
php -r 'for(;n|$i=$argv[++$x];)($l=$i[1])?$l^r?$l^s?$l^t?$o.=$c:$o="":$c=$o:$o=substr($o,0,-1):$o.=$i;echo$o;' e [C] [B] I ' ' l i k [P] ' ' b [P] [P] s ! 2>/dev/null;echo
```
Run like this:
```
php -nr 'for(;n|$i=$argv[++$x];)($l=$i[1])?$l^r?$l^s?$l^t?$o.=$c:$o="":$c=$o:$o[-1]="":$o.=$i;echo$o;' e [C] [B] I ' ' l i k [P] ' ' b [P] [P] s !;echo
> I like bees!
```
# Explanation
```
for(
;
n|$i=$argv[++$x]; # Iterates over the input until null.
)
($l=$i[1])? # Check if this item is a command, if so set to $l
$l^r? # If the command is not B
$l^s? # If the command is not C
$l^t? # If the command is not D
$o.=$c # Then it's P, so paste the clipboard ($c)
:$o="" # It's D, so delete output
:$c=$o # It's C, so copy output to clipboard
:$o[-1]="" # It's B, so remove the last output char
:$o.=$i; # No command, add the current item to the output.
echo$o; # Print the output.
```
# Tweaks
* Saved 3 bytes by combining the output handling with the command handling
] |
[Question]
[
Write the smallest program that maps strings injectively to outputs and maps itself to 2020.
To be clear, your program \$p\$ must have the following properties:
1. every possible input string \$s\$ has a well-defined output \$p(s)\$,
2. for every pair of strings \$s\$ and \$t\$ with \$s\neq t\$, it holds that \$p(s)\neq p(t)\$, and
3. \$p(p)=2020\$.
Be sure to explain why your submission satisfies properties 1 and 2. For property 3, the output can be a string or any type of number.
**Edit 1:** Programs need to be proper quine variants. Reading the source code is not allowed.
**Edit 2:** Note that as a consequence of property 2, it holds that \$p(s)\neq p(p)\$ for every \$s\neq p\$.
[Answer]
# awk, 4 bytes
The structure of an awk program is *`pattern { action }`*. If *pattern* evaluates to true, *{ action }* is performed. If *{ action }* is omitted, the default is to output the current input record.
Code:
```
2020
```
As `2020` always evaluates to true, the program always prints it's input, therefore satisfying properties 1. and 2. When the input is the program itself it satisfies property 3. \$p(p)=2020\$ — even \$p(p)=p\$.
Some test cases:
```
$ echo 2020 | awk '2020'
2020
$ echo 0 | awk '2020'
0
$ echo "" | awk '2020'
$ echo foo | awk '2020'
foo
```
Would've been more glorious back in the good old days:
```
$ echo 1 | awk '1'
1
```
[Answer]
# JavaScript (ES6), 23 bytes
Returns either the input string with a leading \$0\$, or \$2020\$ if the input is the program.
```
f=s=>s=='f='+f?2020:0+s
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbY1q7Y1lY9zVZdO83eyMDIwMpAu/h/cn5ecX5Oql5OfrpGmoaSR2pOTr6OQnh@UU6KopKmJheaPEgfFmEcpgNV/gcA "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
Generates a unique BigInt by using each byte of the input string, then applies a XOR to the result in such a way that \$f(f)=2020\$.
```
f=s=>(g=s=>Buffer(s).every(b=>t=t<<8n|BigInt(b),t=1n)&&t)(s)^g('f='+f)^2020n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbY1k4jHUQ6laalpRZpFGvqpZalFlVqJNnaldiW2NhY5NU4ZaZ75pVoJGnqlNga5mmqqZVoAtXFpWuop9mqa6dpxhkZGBnk/U/OzyvOz0nVy8lP10jTUPJIzcnJ11EIzy/KSVFU0tTkQpOnpt1A4/8DAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 45 bytes
Based on one of the classic Ruby quines, `_="_=%p;puts _%%_";puts _%_`. Prints `2020` if the input is the source, otherwise prints the Ruby representation of the input (encapsulated in quotes, various characters like `"` and `\` are escaped, etc.)
```
_="_=%p;p$_==_%%_ ?2020:$_";p$_==_%_ ?2020:$_
```
[Try it online!](https://tio.run/##KypNqvz/P95WKd5WtcC6QCXe1jZeVTVewd7IwMjASiVeCSaGECJR@b/8gpLM/Lzi/7p5AA "Ruby – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~81~~ ~~60~~ ~~59~~ ~~57~~ 56 bytes
-21 Thanks to Jo King
Outputs 2020 if the input matches the program, otherwise the input concatenated to itself 5 time (eg. `abc` becomes `abcabcabcabcabc`)
```
exec(a:='print(5*[i:=input(),404][i=="exec(a:=%r)"%a])')
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj0cpWvaAoM69Ew1QrOtPKNjOvoLREQ1PHxMAkNjrT1lYJpkq1SFNJNTFWU12TfJ0A "Python 3.8 (pre-release) – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 56 bytes
Outputs 2020 if the input matches the program, otherwise the input concatenated to itself 5 time (eg. `abc` becomes `abcabcabcabcabc`)
```
a='i=input();print 5*[i,404][i=="a=%r;exec a"%a]';exec a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9FWPdM2M6@gtERD07qgKDOvRMFUKzpTx8TAJDY609ZWKdFWtcg6tSI1WSFRSTUxVh3K/v9fSUmJXM1ArQA "Python 2 – Try It Online")
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~77~~ ~~67~~ 65 bytes
-10 Thanks to Jo King
Outputs 2020 if the input matches the program, otherwise the input concatenated to itself 5 time (eg. `abc` becomes `abcabcabcabcabc`)
```
lambda s:5*[s,404][s==(a:='lambda s:5*[s,404][s==(a:=%r)%%a]')%a]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfpmCrEPM/JzE3KSVRodjKVCu6WMfEwCQ2utjWViPRylYdt5RqkaaqamKsuiaQ@F9QlJlXopGmkZlXUFqioamp@d/IAAA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 2 bytes
```
20
```
This is a refined solution to James Brown's solutions.
If the input is 20 [source code], prints 2020 - otherwise prints [string]+20, which is unique and easily reversible.
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/38gAhAE "GolfScript – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
“Ṿ;⁾v`³⁽¥ŒṾ⁼?”v`
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/dZP2rcV5ZwaPOjxr2Hlh6dBBR51LjH/lHD3LKE/0SoAQA "Jelly – Try It Online")
A full program that takes a string as its input. It outputs an unevaluated Jelly version of the input unless provided with itself, in which case it outputs 2020.
Thanks to @JonathanAllan for pointing out a flaw in my original version!
## Explanation
```
“Ṿ;⁾v`³⁽¥ŒṾ⁼?”v` | Evaluate as Jelly code the following, using itself as the argument:
Ṿ | - Unevaluate (effectively wraps string back into “”
;⁾v` | - Append "v`"
³ ⁼? | - If equal to the program’s argument:
⁽¥Œ | - Then: 2020 (compressed integer)
Ṿ | - Else: Unevaluated version of the program’s original argument
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 47 bytes
```
<say "<$_>~~.EVAL"eq($!=get)??2020!!@$!>~~.EVAL
```
[Try it online!](https://tio.run/##K0gtyjH7/9@mOLFSQclGJd6urk7PNczRRym1UENF0TY9tUTT3t7IwMhAUdFBRREmS7IGAA "Perl 6 – Try It Online")
Outputs `2020` if the input matches the program, otherwise the input surrounded in brackets.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"34çìD«QiŽ7ìëû"34çìD«QiŽ7ìëû
```
[Try it online](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1wOrQ7MPLrX/PCaw6sP78YqSIpaAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9TVnl4gr2SwqO2SQpK9v@VjE0OLz@8xuXQ6sDMo3vND685vPrwbqyC/2t1SFDNRaxSrpLU4hIuIwMjA67EpGSuRK5EEEoEAA).
**Explanation:**
```
"34çìD«QiŽ7ìëû" # Push this string
34ç # Push 34, and convert it to a character: '"'
ì # Prepend it in front of the string
D« # Append a copy of the string to itself
Qi # If it's equal to the (implicit) input:
Ž7ì # Push compressed integer 2020
ë # Else:
û # Palindromize the (implicit) input
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž7ì` is `2020`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~190~~ ~~196~~ ~~194~~ ~~192~~ ~~180~~ 176 bytes
Thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for pointing out a bug.
Trailing newline seems accepted in some other answers, so will use that to fix a bug pointed out by [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob). (Also -12 bytes thanks to the same.)
-4 bytes thanks to @ceilingcat.
Assumes little-endian, ASCII, `sizeof(int) >= 4`, all the good stuff.
Outputs the input string preceded by a dollar sign, unless given its own source code, in which case it outputs `2020`.
```
*s="*s=%c%s%1$c,u[99]={'0202'};f(int*t){puts(bcmp(u+2,t,sprintf(u+2,s,34,s))?putchar(36),t:u);}",u[99]={'0202'};f(int*t){puts(bcmp(u+2,t,sprintf(u+2,s,34,s))?putchar(36),t:u);}
```
[Try it online!](https://tio.run/##S9ZNT07@/1@r2FYJiFWTVYtVDVWSdUqjLS1jbavVDYwMjNRrrdM0MvNKtEo0qwtKS4o1kpJzCzRKtY10SnSKC4qAMmlgXrGOsYlOsaamPVBRckZikYaxmaZOiVWppnWtErUN/A9UpJCbmJmnoclVzcWZpqGUkZqlpGkNZgKtMICxYTTQczG09GEM1b0IcnntfwA "C (gcc) – Try It Online")
[Answer]
# Java 10, 128 bytes
```
s->{var t="s->{var t=%c%s%1$c;t=t.format(t,34,t);return t.equals(s)?2020:0+s;}";t=t.format(t,34,t);return t.equals(s)?2020:0+s;}
```
[Try it online.](https://tio.run/##rZDPSsNAEIfveYohNLDBdonVk0v0CayHHq2HyXYrmyabujMJSMmzx40G9CKh0Msyf76B77cldrgq98dBV0gEz2jdOQKwjo0/oDawGVuAl6I0mkGLLXvr3oFSFeZ9FB5iZKthAw5yGGj1eO7QA@fxb5nohJLbhVacszw0vkYWvLy7X3KqvOHWO2BpPlqsSFD6tM7W2UN2Q6qPL74Y1Oh0aosqOE1qXWP3UIdok/3rG2D6k2v7SWxq2bQsT2HFlRNOavHHfXeNHLvLg8Tp9xf/rziisxAb4lkICz3LTEAf9cMX)
**Explanation:**
[quine](/questions/tagged/quine "show questions tagged 'quine'") part of the explanation:
* `var t` contains the unformatted source code
* `%s` is used to input this String into itself with `t.format(...)`
* `%c`, `%1$c`, and the `34` are used to format the double quotes
* `t.format(t,34,t)` puts it all together
Challenge part of the explanation:
* `t.equals(s)` checks if the input-String is equal to the source code
* `?2020`: if it is, return `2020` as result
* `:0+s`: if not, return the input-String with a prepended 0 as result instead
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~26~~ 23 bytes
Outputs 2020 if the input matches the program, otherwise the input concatenated to itself 2020 time (eg. ab becomes ababab...ababab)
```
*2020|qjN B"*2020|qjN B
```
[Try it online!](https://tio.run/##K6gsyfj/X8vIwMigpjDLT8FJCYn9/7@SkhIOOaDMv/yCksz8vOL/uikA "Pyth – Try It Online")
## Explanation
```
*2020|qjN B"*2020|qjN B
B"*2020|qjN B : Evaluates to ("*2020|qjN B", "*2020|qjN B")
jN : join with '"' as seperator (will be source code)
|q : True if source is equal to input else input
*2020 : Multiply by 2020 (i.e. True -> 2020, input -> 2020 * input)
```
---
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
Not sure if the following solution is valid, it will only work if the year is 2020.
```
*.d3|qjN B"*.d3|qjN B
```
[Try it online!](https://tio.run/##K6gsyfj/X0svxbimMMtPwUkJwfz/X0lJCasMUPxffkFJZn5e8X/dFAA "Pyth – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 56 bytes
```
".a=.}:0 :0
echo@>2020[^:(]-:'".a=.}:0 :0',LF,a&[)1!:1[3
```
[Try it online!](https://tio.run/##y/r/X0kv0Vav1spAwcqAKzU5I9/BzsjAyCA6zkojVtdKHUlWXcfHTSdRLVrTUNHKMNqYfJ0A "J – Try It Online")
A full program. Unless provided with itself prints each character on a separate line.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 24 bytes
```
OvA="¶`OvA=`+Q+A?2020:U³
```
[Try it online!](https://tio.run/##y0osKPn/37/M0Vbp0LYEEJ2gHajtaG9kYGRgFXpo8///6rgl1QE "Japt – Try It Online")
## Explanation
Outputs 2020 if the input matches the program, otherwise the input 3 times (eg. ab becomes ababab)
```
OvA="¶`OvA=`+Q+A?2020:U³
A="¶`OvA=`+Q+A?2020:U³ // Set value of A to "¶`OvA=`+Q+A?2020:U³"
Ov // Evaluate A as japt code
`OvA=`+Q+A // Concatenate "OvA=", '"' and A (Q = '"')
¶ ?2020:U³ // If equal to input then 2020 else input concatenated to itself 3 times
```
] |
[Question]
[
Your objective is to take input like
```
Pie is good. I just ate a bunch of pies early this morning. Actually, it was closer to the afternoon. Mornings are good.
```
and create an array of the indexes of the string where the letters that make up the word "Llama" appear (one of each in order). For example, let me show the letters pointed at with carets to show the indexes:
```
Pie is good. I just ate a bunch of pies early this morning. Actually, it was closer to the afternoon. Mornings are good.
^ ^ ^ ^ ^
```
So the array would look like:
```
[44, 67, 76, 105, 114]
```
(If your application uses a indexing that's not 0-based, the numbers will look different. That's fine.)
If the text has no llama, then the array should be empty, nil, null, or undefined.
Any code language is accepted. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") contest, so the least characters win!
[Answer]
# Perl, 52 bytes
The solution is provided as function that takes the string as argument and returns a list of positions.
* One-based positions, case-sensitive search, without newlines: **52 bytes**
```
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/;@+[1..$#+]}
```
The case-sensitive search returns an empty array in the example of the question, because after matching the first three letters the lowercase letter `m` is missing in the input text.
* Support of newlines: + 1 byte = **53 bytes**
```
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/s;@+[1..$#+]}
```
The text can now span several lines.
* Case-insensitive search: + 1 byte = **54 bytes**
```
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/si;@+[1..$#+]}
```
Now the example in the question reports a list of index positions,
they are one-based numbers:
```
[45 68 77 106 115]
```
* Zero-based positions: + 9 bytes = **63 bytes**
```
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/si;map{$_-1}@+[1..$#+]}
```
Result for the example in the question:
```
[44 67 76 105 114]
```
**Ungolfed:**
The latter variant includes more or less the other variants.
```
sub l {
# pop() gets the last argument
pop() =~ /(l).*?(l).*?(a).*?(m).*?(a)/si;
# the letters inbetween are matched against ".*?",
# the non-greedy variant of ".*". Thus ".*?"
# matches only as few as possible characters.
# The modifier /i controls the case-sensitivity
# and means ignore case. Without the case matters.
# Modifier /s treats the string as single line,
# even if it contains newlines.
map { $_-1 } # subtract 1 for zero-based positions
@+[1..$#+]
# Array @+ contains the end-positions of the last
# submatches, and of the whole match in the first position.
# Therefore the first value is sliced away.
# @+ is available since Perl 5.6.
}
# test
my @result = l(<<"END_STR");
Pie is good. I just ate a bunch of pies early this morning. Actually, it was closer to the afternoon. Mornings are good.
END_STR
print "[@result]\n";
```
[Answer]
# sed, 299+1
Yes, sed can find a llama. No, sed can't do math. This is the longest answer so far, at 299+1 characters, because I had to teach sed to count.
This answer requires a sed with extended regular expressions (`sed -E` or `sed -r`). I used OpenBSD [sed(1)](http://www.openbsd.org/cgi-bin/man.cgi?query=sed&apropos=0&sektion=0&manpath=OpenBSD%20Current&arch=i386&format=html). Input is one string per line. (Therefore, the string may not contain a newline.) Output is a line of numbers, or nothing.
Usage (+1 character for `-r`):
```
$ echo 'All arms on all shoulders may ache.' | sed -rf llama.sed
1 2 12 26 30
```
Source code (299 characters):
```
s/%/z/g
s/(.*)[Aa]/\1%/
s/(.*)[Mm](.*%)/\1%\2/
s/(.*)[Aa]((.*%){2})/\1%\2/
s/(.*)[Ll]((.*%){3})/\1%\2/
s/(.*)[Ll]((.*%){4})/\1%\2/
/(.*%){5}/!d
s/[^%]/z/g
:w
s/(z*)%/\10 z\1/
s/z*$//
s/z0/1/
s/z1/2/
s/z2/3/
s/z3/4/
s/z4/5/
s/z5/6/
s/z6/7/
s/z7/8/
s/z8/9/
s/([0-9]z*)z9/z\10/g
s/(z*)z9/1\10/
/[%z]/bw
```
The program first replaces the llama with five `%`. (All `%` in this program are literal.) The first command `s/%/z/g` changes any `%` to `z` in the input line. The next five commands find the llama, so *All arms on all shoulders may ache.* becomes *A%% arms on %ll shoulders %ay %che.* Because each `.*` is greedy, I always finds the llama on the right: *llama llama* would become *llama %%%%%*. If I can't get five `%`, then `/(.*%){5}/!d` deletes the input line and skips the next commands.
`s/[^%]/z/g` changes every character but `%` to `z`. Then I enter a loop. `s/(z*)%/\10 z\1/` changes the first `%` to `0`, copies zero or more `z` from left to right, and adds one more `z` to right. This is so the number of `z` will equal the index. For example, `zz%zzz%...` becomes `zz0 zzzzzzzz%...` because the first `%` was at index 2, and the next `%` is at index 8. `s/z*$//` removes extra `z` from the end of the string.
The next eleven commands count `z` by removing each `z` and counting up from `0`. It counts like `zzz0`, `zz1`, `z2`, `3`. Also, `1zzzz9` becomes `z1zzz0` (later `23`), or `zzzz9` becomes `1zzz0` (later `13`). This loop continues until there are no more `%` or `z`.
[Answer]
# CJam - 33
```
lel"llama"{1$#)_T+:T\@>}/;]___|=*
```
It gets the 1-based indexes (2 more bytes for 0-based)
Explanation:
`l` reads a line from the input (replace with `q` for whole input)
`el` converts to lowercase
`"llama"{...}/` executes the block for each "llama" letter
`1$` copies the current string
`#` finds the index of the letter
`)_` increments and duplicates
`T+:T` adds T (initially 0), updates T and leaves it on the stack
`\@` swaps items around, now we have current-T, index, string
`>` slices the string starting at the index
`;` pops the remaining string
`]` gathers the indexes in an array
At this point we have all the 1-based indexes; iff any letter was not found, the array will have duplicates.
`___` makes 3 more copies of the array
`|` (with 2 array copies) removes duplicates
`=` compares, resulting in 0 if there were duplicates or 1 if not
`*` multiplies the array 0 or 1 times accordingly
[Answer]
## Fortran - ~~154~~ 148
Fortran sucks at golfing, but just to prove that parsing strings can be done in a math-based language, I did it:
```
function f result(r);integer::r(5),j=1;do i=1,len(s);if(s(i:i)==a(j:j).or.s(i:i)==b(j:j)) then;r(j)=i;j=j+1;endif;enddo;if(any(r==0))r=0;endfunction
```
I saved a few characters by eliminating the not-required `f` at the end of `endfunction` and used `if(any(r==0))` instead of `if(.not.all(r>0))`.
This requires:
1. `s` to be the string with text
2. `a` to be the lower-case test (i.e., `llama`)
3. `b` to be the upper-case test (i.e., `LLAMA`)
The full, un-golfed program is
```
program find_llama
character(len=123) :: s = "Pie is good. I just ate a bunch of pies early this morning. Actually, it was closer to the afternoon. Mornings are good."
character(len=5) :: a="llama",b="LLAMA"
print *,f()
contains
function f result(r)
integer::r(5),j=1
do i=1,len(s)
if(s(i:i)==a(j:j).or.s(i:i)==b(j:j)) then
r(j)=i
j=j+1
endif
enddo
if(any(r==0)) r=0
end function
end program find_llama
```
[Answer]
# Ruby, ~~56~~ ~~65~~ 63
**Edit**: +9 characters so that it is case-insensitive.
Defines a function (lambda, technically) `f`.
```
f=->s{i=0;'LLAMA'.chars.map{|c|i=s.upcase.index(c,i+1)||break}}
```
Returns `nil` if there is no llama. If it has to be `[]` (empty array), then just add `||[]` before the last `}` for a total of **4 extra** characters.
Readable version:
```
innerLlama = -> str{
index = 0;
str.downcase!
arr = 'llama'.each_char.map{|char|
index = str.index(char, index + 1)
break unless index
}
# uncomment this line for empty array on failure
#arr || []
}
```
[Answer]
## C# - 119
Takes string, outputs array. Null if no llama in string.
```
int[]a(string s){var i=0;var o="llama".Select((x,y)=>i=s.IndexOf(x,y>0?i+1:0));return o.All(x=>x>=0)?o.ToArray():null;}
```
[Answer]
# C - 53
Compile with:
```
gcc -D L=\"llama\" -D W=\"Lie\ is\ good.\ \ I\ just\ ate\ a\ bunch\ of\ pies\ early\ this\ morning.\ \ Actually,\ it\ was\ closer\ to\ the\ afternoon.\ \ Mornings\ are\ good.\"
```
I tested this compile command with cygwin's gcc. Other environments might handle spaces, and other special characters differently.
The 0-based result is stored into array `r`. Its contents are undefined if there is no llama in the string.
* Case-sensitive (53)
`i,m,r[5];main(){for(;W[i];i++)W[i]==L[m]?r[m++]=i:i;}`
* Case-insensitive (58)
`i,m,r[5];main(){for(;W[i];i++)(W[i]|96)==L[m]?r[m++]=i:i;}`
[Answer]
# Python, 100
I am the worst golfer ever. :P
Thanks to @xnor for shaving off 6 bytes.
```
g,n,o='llama',0,[]
for i in s:
if g:exec("o+=[n];g=g[1:];"*(i.lower()==g[0])+"n+=1")
o*=len(o)>4
```
`o` contains the array after.
**EDIT**: Fixed.
**EDIT 2**: `len(g)` to `g`, `o==5` to `o>4` as per @xnor's suggestions.
**EDIT 3**: @WolframH fixed it.
[Answer]
# JavaScript (ECMAScript 6) - 68 Characters
```
(/((((.*l).*l).*a).*m).*a/.exec(s)||[]).map(x=>x.length-1).reverse()
```
Assumes that the string to test is in the variable `s`. If you want to turn it into a function then prepend `f=s=>` (for an additional 5 characters).
**Outputs:**
```
[]
```
**Case Insensitive - 69 Characters**
```
(/((((.*l).*l).*a).*m).*a/i.exec(s)||[]).map(x=>x.length-1).reverse()
```
**Outputs:**
```
[68, 80, 93, 105, 114]
```
**Case Insensitive & First Match - 74 Characters**
```
(/((((.*?l).*?l).*?a).*?m).*?a/i.exec(s)||[]).map(x=>x.length-1).reverse()
```
**Outputs:**
```
[44, 67, 76, 105, 114]
```
[Answer]
## Python 71
Assumes input in `s`. Output in `o`.
```
F=s.lower().find
o=F('l'),
for c in'lama':o+=F(c,o[-1]+1),
o*=min(o)>=0
```
**Edit:** Changed from lists to tuples to save 2 bytes.
[Answer]
# Python 100
```
import re
x=input()
print[re.search(r"l.*?(l).*?(a).*?(m).*?(a)",x,re.I).start(i) for i in range(5)]
```
Sample:
```
in = Pie is good. I just ate a bunch of pies early this morning. Actually, it was closer to the afternoon. Mornings are good.
out = [44, 67, 76, 105, 114]
in[out] = ['l', 'l', 'a', 'M', 'a']
```
[Answer]
## Haskell, 111
```
import Data.Char
l i(a:as)t@(b:bs)|a==b=i:l(i+1)as bs|True=l(i+1)as t
l _ _ _=[]
r s=l 0(map toUpper s)"LLAMA"
```
Ungolfed:
```
import Data.Char
llama :: Int -> String -> String -> [Int]
llama i (a:as) t@(b:bs)
| a==b = i : llama (i+1) as bs
| otherwise = llama (i+1) as t
llama _ _ _ = []
runme :: String -> [Int]
runme s = llama 0 (map toUpper s) "LLAMA"
```
Example:
```
*Main> r "Pie is good. I just ate a bunch of pies early this morning. Actually, it was closer to the afternoon. Mornings are good."
[44,67,76,105,114]
```
[Answer]
## Matlab, 61 ~~96~~
Searches the string and replaces everything up to each match with gibberish before searching for next character. Will leave `s` undefined if an the word does not occur.
```
t='llama';for q=1:5;s(q)=min(regexpi(z,t(q))),z(1:s(q))=0;end
```
Note that the charcount could be reduced if case sensitivity is allowed.
**Previous versions**
```
try;t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end;catch;end
```
Searches the string and replaces everything up to each match with gibberish before searching for next character. Error handling (try-catch-end) could maybe be dropped, then the program would crash (but s would be undefined as required) if llama not found.
Implementation:
```
>> z='Pie is good. I just ate a bunch of pies early this morning. Actually, it was closer to the afternoon. Mornings are good.';
>> try;t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end;catch;end
>> s
s =
45 68 77 106 115
```
Without error handling:
```
t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end
```
[Answer]
**Language Java**
```
final int[] wordIndexInSentence(String sentence, String word)
{
final int[] returnArr = new int[word.length()];
int fromIndex = 0;
word = word.toUpperCase();
sentence = sentence.toUpperCase();
for (int i = 0; i < word.length(); i++)
{
final char c = word.charAt(i);
returnArr[i] = sentence.indexOf(c, fromIndex);
fromIndex = returnArr[i] > 0 ? returnArr[i] + 1 : fromIndex;
}
return returnArr;
}
```
[Answer]
# Rebol, 97
```
f: func[s][a: copy[]foreach n"llama"[if none? s: find s n[return[]]append a index? s s: next s]a]
```
Usage example in Rebol console:
```
>> f "Pie is good. I just ate a bunch of pies early this morning. Actually, it was closer to the afternoon. Mornings are good."
== [45 68 77 106 115]
>> f "nearly llami"
== []
>> f "Llama"
== [1 2 3 4 5]
>> f reverse "llama"
== []
```
Rebol uses 1-based indexing. Returns empty list `[]` if no llama sequence found (case insensitive).
Ungolfed:
```
f: func [s] [
a: copy []
foreach n "llama" [
if none? s: find s n [return []]
append a index? s
s: next s
]
a
]
```
[Answer]
# Python (70)
```
r=[];c=-1
for x in'llama':c=s.lower().find(x,c+1);r+=[c]
r*=1-(-1in r)
```
We search of each character in `'llama'` in turn, starting after the location of the previously-found character. If no character is found, `c` becomes the default value of `-1`, in which case the last line turns `r` into the empty list.
Edit: Found out that `str.find(s,...)` can be invoked as `s.find(...)`, saving 4 characters.
[Answer]
# OpenEuphoria, 147128
I have two examples. First, the shortest:
```
object t=and_bits(gets(0),#DF),L="LLAMA",i=0,X={}for j=1 to 5 do
i=find(L[j],t,i+1)X&=i
end for
if find(0,X) then X={} end if?X
```
I can get it down to 126 characters if I use "or" instead of "and" like the C version does up above. However, this also matches the string `''!-!` as `llama`. Uncommon, but still a possible error.
```
object t=or_bits(gets(0),96),L="llama",i=0,X={}for j=1 to 5 do
i=find(L[j],t,i+1)X&=i
end for
if find(0,X) then X={} end if?X
```
And then the version using regular expressions:
```
include std/regex.e
include std/sequence.e
include std/utils.e
object X=regex:find(new("(?i)(l).*?(l).*?(a).*?(m).*?(a)"),gets(0))
? iff(atom(X),{},vslice(X[2..6],2))
```
Both take input from STDIN and post to STDOUT.
EDIT: Shorter regex example:
```
include std/regex.e
include std/sequence.e
object X=regex:find(new("(?i)(l).*?(l).*?(a).*?(m).*?(a)"),gets(0))
if atom(X)then?{}else?vslice(X[2..6],2)end if
```
[Answer]
# Powershell - ~~121~~ 85
I'm still practicing with Powershell, expect this could be improved
$s contains the string, result is in array $a
Original version
```
$a=@();$w="llama";$n=$c=0;foreach ($i in $s.tochararray()) {if ($i -eq $w[$n]) {$a+=$c;$n+=1} $c+=1};$a*=$a.length -gt 4
```
Ungolfed
```
$a=@()
$w="llama"
$n=$c=0
foreach ($i in $s.tochararray()) {
if ($i -eq $w[$n]) {
$a+=$c
$n+=1
} $c+=1
}
$a*=$a.length -gt 4
```
New version, with massive thanks to @goric
```
$a=@();$n=$c=0;[char[]]$s|%{if($_-eq"llama"[$n]){$a+=$c;$n++}$c++};$a*=$a.length-gt4
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ŒlẹⱮ“ṫɠ»Ż>ƇḢ¥@\Ḋ
```
[Try it online!](https://tio.run/##Jc0xCsIwGMXxq7wDiEcQHR0ED@AS69c2JSaSpIibW8Gxk4ODCE6C4NbarVLBY6QXiYHuv/f@GQlx8L4rhXvX/evZHy@ufvyubdM1k2/hqlt7n65cdfKfoitdffZ@yQncIFFqMwbmyHJjwSyBYZ3LKIWKseNkQEyLA2wa8FZpyWUS/CyyOQvNEbjFnhlEQhnSsCrI8BFb0lIpGehiGBkwTUPuDw "Jelly – Try It Online")
## How it works
```
ŒlẹⱮ“ṫɠ»Ż>ƇḢ¥@\Ḋ - Main link. Takes a string on the left
Œl - Lowercase
“ṫɠ» - Compressed string: "llama"
Ɱ - For each character in "llama":
ẹ - Find the indexes of that character in the input
Ż - Prepend 0
¥ - Last 2 links as a dyad f(x, y):
>Ƈ - Keep elements of x greater than y
Ḣ - Take the first element
@\ - Reduce the list by the f(y, x)
Ḋ - Dequeue
```
[Answer]
# PHP
no PHP answer yet? I think a language heavily string-oriented can beat at least a math-based one
```
function x($s){$i=$j=0;$r=str_split('llama');$s=strtolower($s);while($i<strlen($s)){if($s[$i]==$r[$j]){$r[$j]=$i;$j++;if($j>4)return$r;}$i++;}return[];}
```
152 against fortran 154, job done :P
ungolfed
```
function x($s){
$i=$j=0;$r=str_split('llama');
$s=strtolower($s);
while($i<strlen($s)){
if ($s[$i]==$r[$j]){
$r[$j]=$i;
$j++;
if($j>4)
return $r;
}
$i++;
}
return[];
}
```
if the caller always passes a lowercase string, it lowers to 137
[Answer]
# JavaScript, 122 115
```
function(s,b){z=[];for(i=0;i<5;i++){z.push(b=s.toLowerCase().indexOf("llama"[i],++b))};return z.indexOf(-1)<0?z:[]}
```
Defines a function that takes a string as its only argument (second arg is a cheap `var`) and returns either an empty array or a 5-element array.
Drops to 108 if I take the input on a single char variable (`s`) and leave the output in another (`b`):
```
var b=((z="llama".split('').map(function(a){return (b=s.toLowerCase().indexOf(a,++b))})).indexOf(-1)<0?z:[])
```
Edit: Swapped out map for for loop.
[Answer]
# APL, 47
```
+\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞
```
Not the shortest code, but quite warped, in an APL way.
**Explanation**
`'amall',⊂⍬⍞` Make an array of 6 elements: the letters 'amall' and a subarray of 2 elements, themselves subarrays: the empty array and a line of characters read from input.
`{...}/...` Reduce (right-fold) the 6-element array using the provided function.
`a s←⍵` Decompose the right argument into the array of indices and the remaining substring (initially the empty array and the full string.)
`~⍺∊s:⍬⍬` If the substring does not contain the next letter `⍺` stop the computation and return the empty array.
`a,←n←s⍳⍺` Otherwise, find its position, call it n, and append it to the array of indices.
`a(n↓s)` Make and return an array of 2 elements: the extended array of indices and the remaining substring.
`+\↑⊃...` Unpack the output of the folding, take the first element (the array of indices) and scan it with addition, to turn relative offsets into absolute ones.
**Examples**
```
+\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞
All cats meow aloud.
2 3 6 10 15
```
```
+\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞
Some cats purr instead.
```
[Answer]
# Julia, 76
Another regex example using Julia language.
```
f(s)=(m=match(r"(?i)(l).*?(l).*?(a).*?(m).*?(a)",s);m==nothing?m:m.offsets)
```
[Answer]
# ARM Thumb-2 machine code, 42 bytes
Machine code (little endian hexdump):
```
2500 a208 f812 3b01 b15b 5d44 b144 3501
42a3 d003 f084 0420 42a3 d1f6 c120 e7f1
2100 4770 6c6c 6d61 0061
```
Commented assembly:
```
.syntax unified
.arch armv6t2
.thumb
.globl llama
.thumb_func
// Input:
// r0: null terminated string
// r1: output uint32_t array, must be 4 byte aligned
// Output:
// if it matches, the ONE-INDEXED offsets are stored in r1
// otherwise, r1 is set to NULL. (Elements are still
// modified).
llama:
// index
movs r5, #0
// lookup table
adr r2, .LLAMA
// loop through "llama"
.Llama:
// Read byte from llama string, increment
ldrb r3, [r2], #1
// end at null terminator
cbz r3, .LlAmA
.LLama:
// r4 = str[r5]
ldrb r4, [r0, r5]
// if we reach the null terminator, we don't have a match.
cbz r4, .LlaMa
// increment r5 (this is what makes it one indexed)
adds r5, #1
// check for a direct match
cmp r3, r4
beq .LLAma
// flip the case by xoring 1<<5
eor r4, r4, #0b00100000
// test the case when flipped
cmp r3, r4
bne .LLama
.LLAma:
// *r1++ = index
stm r1!, {r5}
// loop indefinitely (trip condition is the first cbz)
b .Llama
.LlaMa:
// If we don't have a match, set r1 to NULL.
movs r1, #0
.LlAmA:
// Otherwise, return.
bx lr
.LLAMA:
.asciz "llama"
```
] |
[Question]
[
This challenge is inspired by [@LuisMendo's MATL answer](https://codegolf.stackexchange.com/a/200008/75323) to my "[binary multiples](https://codegolf.stackexchange.com/a/200008/75323)" challenge.
# Task
Pick a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge that is *open* and that has been posted *before* this one; let me call it the *"linked challenge"*. The *linked challenge* must be a challenge whose task involves producing output.
Write the shortest code possible that satisfies the following restrictions:
* Your code must contain the characters `b`, `u` and `g` in your program, in this order and consecutively (case-insensitive, so "bug", "BUG", "Bug", "bUg", ... are all fair game.);
* Your code must *not* contain the letters `b`, `u` and `g` more than once (case-insensitive);
* Your code should be a valid submission for the *linked challenge*;
* When any subset of the (case-insensitive) characters `bug` are removed, your program no longer fulfils the task of the *linked challenge*. This may happen because your program now produces the wrong output (i.e. fails test cases), because it halted with an error, because it runs indefinitely and never returns (if this is the case, be prepared to prove your program runs indefinitely), etc.
* Your code should not be an integral copy - nor a trivial modification\* - of a submission that already exists in the *linked challenge* (for example, you may not copy [@LuisMendo's MATL answer](https://codegolf.stackexchange.com/a/200008/75323) to my "[binary multiples](https://codegolf.stackexchange.com/a/200008/75323)" challenge);
# Input
Your program takes input as per the specs of the *linked challenge* you choose.
# Output
Your program, in its correct state (i.e. with a bug\*\*), must abide by the output specs of the *linked challenge* you choose.
\* This is subjective so I appeal to your common sense; any imaginative modification should be fair game, even if in retrospective it is "trivial". This "no trivial modifications" rule will be "enforced" by me downvoting answers I think disrespect this...
\*\* Sit down, take a moment to let this sink in. Your program has a bug. And yet your program is correct.
# Posting an answer
When you post your answer, please provide a link to your *linked challenge*.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your written feedback. Happy golfing!
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Challenge: [Output with the same length as the code](https://codegolf.stackexchange.com/q/121056/84206)
```
BUG³
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QlVHsw)
## Explanation
`B`, `U`, and `G` are variables for 11, the input, and 16 respectively.
When applied to a number, `³` brings it to the third power.
In Japt, only the last expression is outputted, so only \$16^3 = 4096\$ is outputted, which is the same length as the code (4).
Since `B` and `U` are ignored, removing them have no effect on the output. However, their removal changes the length of the program, making it invalid. Removing `G` raises either the input (`U`) or 11 (`B`) to the third power. While \$11^3 = 1331\$ is 4 bytes, the program `B³` is only two bytes, making the output invalid. The variable `U` defaults to 0 when there is no input given, and \$0^3 = 0\$, which is only one byte long.
[Answer]
# Polyglot, 31 bytes
Linked challenge: [“Hello, World!”](https://codegolf.stackexchange.com/q/55422/58563)
This is a full program, as per the original challenge requirements.
```
print('Hello, World'+'bug!'[3])
```
[Try it in JavaScript (V8)!](https://tio.run/##y0osSyxOLsosKNEts/j/v6AoM69EQ90jNScnX0chPL8oJ0VdWz2pNF1RPdo4VvP/fwA)
[Try it in Python!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ90jNScnX0chPL8oJ0VdWz2pNF1RPdo4VvP/fwA)
[Try it in Ruby!](https://tio.run/##KypNqvz/v6AoM69EQ90jNScnX0chPL8oJ0VdWz2pNF1RPdo4VvP/fwA) (thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan) for pointing this out)
[Answer]
# JavaScript (ES7), 47 bytes
Linked challenge: [How many petals around the rose](https://codegolf.stackexchange.com/q/200386/58563)
```
a=>a.map(n=>t+=n**3&parseInt('bug',35)%9,t=0)|t
```
[Try it online!](https://tio.run/##XZFfS8MwFMXf@ynyok1nLetNGqaQiqDCcOAHKH2IsxvKTEdbB4Lfva4Njcc@9M@5Jzn53ZsPczLttnk/dte2fqv6ne6Nzk3yaY7c6ry70naxEJdH07TV2nY8fP3ah7HIooubuNPL6Kfrt7Vt60OVHOo9D4qiSGOWljFbnp9REApRusIoJDpZ6QqjUN4hTCNMI0wjTCNMI0wTLo0mQSiE3yPcj3eGNDUJ5R2JbBLZJLJJZJPIJpEtc2lyEoRCeILMVb0zpK0mobyjkE0hm0I2hWwK2dR8bjiGoQskHPpFf7hcTM78@pWfHAKKcX2KIxOz8@aDo9n@vyNS343D@NewGHfS6NHsztVUzdzbZZVBUp2q5pvzwsTMlhHTOdtxc/5qZqPgjoUvzyG7ZeHT/Xrz@BBG/S8 "JavaScript (Node.js) – Try It Online")
### How?
This is a port of [my Python answer](https://codegolf.stackexchange.com/a/200429/58563) to the linked challenge. This answer requires a bitwise AND with a constant, which happens to be \$6\$.
This \$6\$ is obtained with the cumbersome `parseInt('bug',35)%9` and removing any subset of characters from `bug` would produce a different (and therefore invalid) constant.
```
s | parseInt(s, 35) | mod 9
-------+-----------------+-------
'bug' | 14541 | 6
'ug' | 1066 | 4
'bg' | 401 | 5
'bu' | 415 | 1
'g' | 16 | 7
'b' | 11 | 2
'u' | 30 | 3
'' | NaN | NaN
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 156 bytes
Answer to [99 bugs in the code](https://codegolf.stackexchange.com/questions/165623/99-bugs-in-the-code). Not competitive, but funny.
```
#define S"%d bugs in the code\n"
d;f(i){for(i=99;i;i=d)printf(S S"Take one down and patch it aro\x75nd\n"S"\n",i,i,d=(d=i+rand()%21-16)<0?0:d);printf(S,0);}
```
Also beats the C solution there.
[Try it online!](https://tio.run/##NYzNCsIwEITveYqlUkiwhVZQqbH4EPXYS8wm7SImpcYfKH32mIszMMxh5tPloHWMGzSWnIEuyxFur@EJ5CCMBrRH07uMobScxGL9zKltGkmSWhTTTC5Y3qXfVd0N@IRA/3GgHMKkgh6BAqjZ99/j3mECdVmKgpKx5djSdk5TLvJdXdYHca4u1QmF/HOLSsg1pg4PRY6/PaFgC4Mky4Vka/wB "C (gcc) – Try It Online")
[Answer]
# [Triangular](https://github.com/aaronryank/triangular), 6 bytes
Linked to Challenge: [Shortest code to produce infinite output](https://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output)
```
bug>%<
```
[Try it online!](https://tio.run/##KynKTMxLL81JLPr/P6k03U7V5v9/AA "Triangular – Try It Online")
[Answer]
# [PHP](https://php.net/), 16 bytes
Solving [Output programming language name](https://codegolf.stackexchange.com/questions/107964/output-programming-language-name)
```
echo'2=7'^'bug';
```
[Try it online!](https://tio.run/##K8go@G9jXwAkU5Mz8tWNbM3V49STStPVrf/b2/0HAA "PHP – Try It Online")
Omitting any of the letters in `bug` outputs a wrong string. However, it won't cause any errors so that error messages containing `PHP` can never be outputted. All PHP answers in that challenge exploit either PHP flags, which cannot contain the word `bug`, or PHP errors, which omitting a letter from `bug` could still result in an output that fulfils the requirements.
[Answer]
# [Python 3](https://docs.python.org/3/), 24 bytes
```
while __debug__:print(1)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/vzwjMydVIT4@JTWpND0@3qqgKDOvRMNQ8/9/AA "Python 3 – Try It Online")
*Linked challenge: [Shortest infinite loop producing output](https://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output?noredirect=1&lq=1)*
Uses the fact pointed out by @Bubbler:
>
> Python has a built-in constant called `__debug__` which is True by default. Removing some of its bug will obviously be an error. Though I can't find a suitable challenge for that...
>
>
>
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 6 bytes
Solves [Output with the same length as the code](https://codegolf.stackexchange.com/q/121056/78410).
```
×'BUG'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94P/h6epOoe7qIM7/AgA "APL (Dyalog Extended) – Try It Online")
Prints `1 1 1\n`, 6 bytes in total.
In regular APL, monadic `×` is Signum for numbers (-1 if negative, 1 if positive, 0 if zero). Extended provides an extended (no pun intended) definition for characters (-1 for lowercase, 1 for uppercase).
Because numeric arrays are printed with a space between items, deleting one char out of `BUG` will remove two bytes (`<space>1`) from the output, thus failing to solve the challenge. Deleting two chars will remove four output bytes, and deleting all of them gives only a single newline.
[Answer]
# [Zsh](https://www.zsh.org/)/[Bash](https://www.gnu.org/software/bash/)/others, 15 bytes
Challenge: [Output with same length as code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code)
```
echo BUG{1..3}
```
[Try it online (Zsh)!](https://tio.run/##qyrO@P8/NTkjX8Ep1L3aUE/PuJbr/38A "Zsh – Try It Online")
[Try it online (Bash)!](https://tio.run/##S0oszvj/PzU5I1/BKdS92lBPz7iW6/9/AA "Bash – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 4 bytes
Challenge: [Output with the same length as the code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code)
It's working. But I still didn't manage a 3-byte solution.
```
BUG^
```
[Try it online!](https://tio.run/##S85KzP3/3ynUPe7/fwA "CJam – Try It Online")
# Why it works
```
B "Constant for 11";
U "Constant for 0";
G "Constant for 16";
^ "Bitwise XOR";
```
0 XOR 16 is 16, therefore it outputs `1116`.
# Removing a single character
```
UG^
```
It just outputs `16` without other calculations.
```
BG^
```
It outputs `27` because 11 XOR 16 is 27.
```
BU^
```
It outputs `11` because 11 XOR 0 is 0.
## Removing 2 characters
CJam doesn't have implicit input, so all these programs would throw an error.
[Answer]
# [Lua](https://www.lua.org/) and perhaps a polyglot in concept, ~~25~~ ~~28~~ 32 bytes
Along the lines of Arnauld's answer, linked to challenge [Output programming language name](https://codegolf.stackexchange.com/questions/107964/output-programming-language-name).
```
print('\076\117\097 5.'..#'bUg')
```
[Try it online!](https://tio.run/##yylN/P@/oCgzr0RDPcbA3CzG0NA8xsDSXMFUT11PT1k9KTRdXfP/fwA)
*Added 3 bytes Thanks to @RGS spotting the 'u' in 'Lua'*
*Added 4 bytes Thanks to @MariaMiller for the 'L' and the 'a' as well*
[Answer]
[Create output twice the length of the code](https://codegolf.stackexchange.com/questions/59436/create-output-twice-the-length-of-the-code)
# [MathGolf](https://github.com/maxbergmark/mathgolf), 6 bytes
```
╘╘BUG]
```
[Try it online!](https://tio.run/##y00syUjPz0n7///R1BlA5BTqHvv/PwA "MathGolf – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 24 bytes
This one for real.
Answer to [Swap the parity](https://codegolf.stackexchange.com/questions/118819/swap-the-parity).
```
f(x){x=-(-x^!"bug"[3]);}
```
[Try it online!](https://tio.run/##XU7tasMwDPzvp7hlFOxW2dql@4C0fZEsg9RxUsPmDNsZYSHPntktlDL9OKST7nQybaWc54YPYhz2KU@Hj7vk2LdJkZUin@Z7beRnXyvsnK9193A6MKaNx1elDXjsKttKgjxVFstlGH4EGxlCxaVXzsvKKVeU2GPEhvBEyAhbwjPhhfBKeAvMJouwxZRftfrSNp0Nj4J6nUNjB@70r@oafrUWeMR/rliXQoT71UrgkibWtw2@DU8WNdIDFvW7Segmoi4Jtx46epzF0xmt8r01IQeb5j8 "C (gcc) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 26 bytes
Answer to [Shortest code to produce infinite output](https://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output)
```
f(){printf("bug"+2)&&f();}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oCgzryRNQympNF1J20hTTQ0oaF37HyiokJuYmadRlp@ZoslVzaUABCAprtr/AA "C (gcc) – Try It Online")
[Answer]
## Javascript, 8 characters
Linked question: [Output with the same length as the code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code/121521#121521)
```
bug=>1e7
```
Outputs `10000000`, which has the same length as the program. Removing 1 or 2 characters would make it print the same thing, but wouldn't match the length of the program anymore. Removing all 3 is a syntax error.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
Linked challenge: [Output with same length as the code](https://codegolf.stackexchange.com/q/121056/84206).
*Port of [Embodiment of Ignorance's Japt answer](https://codegolf.stackexchange.com/a/201227/6484).*
```
bugт
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/qTT9YtP//wA "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
**[Reverse Bit Order of 32-bit Integers](https://codegolf.stackexchange.com/questions/36213/reverse-bit-order-of-32-bit-integers)**
```
%Ø%BUGƇḄ
```
[Try it online!](https://tio.run/##y0rNyan8/1/18AxVp1D3Y@0Pd7T8//9f19LCxMLAyNLADAA "Jelly – Try It Online")
I managed to find a challenge that actually uses two of the letters in a productive way.
There's no Jelly answer to the challenge at the time of writing this answer.
## Explanation
```
%Ø%BUGƇḄ Main monadic link
% Modulo
Ø% 2^32
B Convert to binary
U Reverse
Ƈ Filter by
G Format as a grid
Ḅ Convert from binary
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 24 bytes
Linked to [Find the number of integers in the range from 1 to N that ends with 2](https://codegolf.stackexchange.com/questions/200363/find-the-number-of-integers-in-the-range-from-1-to-n-that-ends-with-2)
```
->n{(n+5+"bug".size)/10}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiNP21RbKak0XUmvOLMqVVPf0KD2v7GpXklmbmqxQkq@Qk1mDZeCQkFpSbGCknJ1Zq2CcnWankamZq0SV2peyn8A "Ruby – Try It Online")
[Answer]
Linked to challenge: [Find the number of integers in the range from 1 to N that ends with 2](https://codegolf.stackexchange.com/q/200363/9481)
# [Python 2](https://docs.python.org/2/), ~~95~~ \$\cdots\$ ~~39~~ 35 bytes
Saved a byte (in a previous version) thanks to [Maria Miller](https://codegolf.stackexchange.com/users/92689/maria-miller)!!!
Saved a byte (in an other previous version) thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
```
def f(n):print((n+len("bug")+5)/10)
```
[Try it online!](https://tio.run/##Hcs7DoAgDADQ3VM0TG0Y/IWF22ik2MQUQnDw9NW4veXVp59FF7MjMTAqxdpEO6L6Kym6/c6OfKBxnsi4NBAQhbZpTrgGigPAH0A@MQrZCw "Python 2 – Try It Online")
[Answer]
Linked to challenge: [Find the number of integers in the range from 1 to N that ends with 2](https://codegolf.stackexchange.com/q/200363/9481)
# [C (gcc)](https://gcc.gnu.org/), ~~51~~ ~~42~~ 40 bytes
```
i;f(n){for(i=0;n+=2,"bug"[i++];);n/=10;}
```
[Try it online!](https://tio.run/##HcrNCoMwDADge58iFISEVKYbO2X1RZwHrVRyWByyncRn736uH1@ql5RKUclotOd1Q42NGMdz8NN78b0yD0Jip9g2cpTHqIa0u/@0F/y23i5XYVZyAM/tqxl9NUPdQTXfzQcNkFGJxB3lAw "C (gcc) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
Linked Challenge: [How many petals around the rose](https://codegolf.stackexchange.com/questions/200386/how-many-petals-around-the-rose)
```
a=>a.map(n=>t+=n**3&!!'bug'[2]*6,t=0)|t
```
[Try it online!](https://tio.run/##XZFfS8MwFMXf@ymyF9PWWtabNAwhFUEFUfADlDzE2Q1lpmOrA8HvXteGxmMf@ufck5z87s2HPdnj@vC@765c@9b0G91bXdn80@5jp6vuUrs0FReLBX/92vKaTKqyTi@Tn65ft@7Y7pp8127jqK7rImOFydjy/IyCUAjjC6OQ6JTGF0ahgkOYRphGmEaYRphGmCZ8Gk2CUIiwR/if4AxpahIqOBLZJLJJZJPIJpFNIlvp0@QkCIUIBKWvBmdIW01CBUchm0I2hWwK2RSyqfnccAxDF0g49Iv@cLmYXIb1qzA5BBTj@gJHJmbnzQdHs/1/RxShG4/xr2Ex7qTRo9mdq6la@rfPMlHenJrDdxzXNmPOJExXbBPb81czl0Q3jL88cXbN@MPt4/P9HU/6Xw "JavaScript (Node.js) – Try It Online")
Originally posted as [a golf to Arnauld's answer](https://codegolf.stackexchange.com/questions/201217/ah-why-is-there-a-bug-in-my-program/201218?noredirect=1#comment478744_201218).
[Answer]
# [W](https://github.com/A-ee/w), 6 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
Challenge: [Output the same length as code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code)
```
BUG"2*
```
Repeats the string "BUG" multiple times.
[Answer]
# [Python 2](https://docs.python.org/2/), 13 bytes
Solves [Output with the same length as the code](https://codegolf.stackexchange.com/q/121056/78410).
```
print 'bug'*4
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQT2pNF1dy@T/fwA "Python 2 – Try It Online")
Prints `bugbugbugbug\n`.
---
# [Python 2](https://docs.python.org/2/), 27 bytes
Solves [Hello, World!](https://codegolf.stackexchange.com/q/55422/78410)
```
print'bugHello, World!'[3:]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EPak03SM1JydfRyE8vygnRVE92tgq9v9/AA "Python 2 – Try It Online")
Removing some of `bug` will chop off characters from the beginning of `'Hello, World!'`.
[Answer]
# [J](http://jsoftware.com/), 7 bytes
Solves [I double the source, you double the output!](https://codegolf.stackexchange.com/q/132558/78410)
```
>:Debug
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/7axcUpNK0/9r/k8DAA "J – Try It Online") [Try it online!Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/7axcUpNK06HUf83/aQA)
Prints 1 as given, 2 doubled.
### How it works
Monadic `>:` is "increment" (add 1), dyadic `>:` is "greater or equal" (`x >= y`).
```
>:Debug NB. increment 0; gives 1
>:Debug>:Debug
Debug>:Debug NB. 0 >= 0; gives 1
>: NB. increment it; gives 2
```
---
# [J](http://jsoftware.com/), 12 bytes
Solves [Output with the same length as code](https://codegolf.stackexchange.com/q/121056/78410).
```
echo 6#Debug
```
[Try it online!](https://tio.run/##y/r/PzU5I1/BTNklNak0/f9/AA "J – Try It Online")
Somewhat similar to Python, J has a stdlib variable `Debug` which is initialized to the number 0. `6#` replicates the zero 6 times, and `echo` prints it. The output formatting is identical to APL's (space-separated numbers), so the output is `0 0 0 0 0 0\n`.
Being a terse language, I suspect there could be a more suitable challenge for J which gives a shorter solution using `Debug`.
[Answer]
# [Io](http://iolanguage.org/), 18 bytes
Challenge: [Output programming language name](https://codegolf.stackexchange.com/questions/107964/output-programming-language-name/108201#108201)
(Joke ruiner over here, never mind.)
This errors (outputting the language name) when the bug is inside, and it doesn't error when any part of the bug is removed.
If you think that this uses the `i` character (taken from the question):
>
> Note that this is case sensitive. I can still use the char 'b' because it's different from 'B'.
>
>
>
```
if("bug"size>2,iO)
```
[Try it online!](https://tio.run/##y8z//z8zTUMpqTRdqTizKtXOSCfTX/P/fwA)
## Explanation
```
size // Is the length of
"bug" // the string "bug"
>2 // larger than 2?
if( , // If so,
iO // Access an undefined variable
) // Otherwise, do nothing
```
# [Io](http://iolanguage.org/), 19 bytes
Challenge: [Output with the same length as the code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code)
```
"bug"at(2)cos print
```
[Try it online!](https://tio.run/##y8z//18pqTRdKbFEw0gzOb9YoaAoM6/k/38A "Io – Try It Online")
# Explanation
```
"bug" // The sequence "bug"
at(2) // The 3rd index of that
// (Out-of-bounds indexing returns nil)
// This returns an integer for an in-bound index
cos // Find the cosine of that
// (Cosine over nil throws an error)
print // Print that value to STDOUT. (WITHOUT a newline)
```
# [Io](http://iolanguage.org/), 19 bytes
Challenge:[Shortest infinite loop producing no output](https://codegolf.stackexchange.com/questions/59347/shortest-infinite-loop-producing-no-output)
```
while("bug"at(2),0)
```
[Try it online!](https://tio.run/##y8z//788IzMnVUMpqTRdKbFEw0hTx0Dz/38A "Io – Try It Online")
# Explanation
```
"bug" // Base string "Bug"
at(2) // Try to access the 3rd item of the string
// (Out-of-bounds returns nil)
while( , // While that's true:
// (So a string is always true and nil is always false)
0) // No action needed
```
[Answer]
# Java 8, ~~88~~ 87 bytes
Linked challenge: [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime)
Given a number, outputs truthy/falsey depending on whether it is a prime number.
```
n->{int i="BUG".charAt(2)-70;for(;n%++i%n>0;);System.console().printf("%s",""+(n==i));}
```
[Try it online](https://tio.run/##XZBPa8IwGMbvfoqHQCGhWusug2UVtsvYYe7gdho7xDTOuPqmNNExpJ@9S7VMMIeE98@TH8@zVQc12Zbfna6U93hRlo4jwFIwzVppg0VfAgdnS2ge@yAhY6sdxcsHFazGAoQC0@ny1wezy7Qj7yrDBTbKY2UMoTF1FX8r8WPDBsOe24cxvKVIuUisB7kAv69r14SocIS359eOJvNjT7cFe3x/YpneqOYh8Bsxuc3l2jVcUpKmNqF5LoW8ELK6ibI1Z4lnY8ZSTkVhhZBtJ3sH9X5VRQeDkZPLXcyAL0OUfX18QolzAD3izJ9J2PtilufxTdNhDFwjuU3ZHdgprP5QFuP7r663K@LDrD2F23Z/) (Note: `System.console()` is `System.out` on TIO, since TIO doesn't support console).
**Explanation:**
```
n->{ // Method with integer parameter and no return-type
int i= // Integer `i`, starting at:
"BUG".charAt(3) // Get the third character from String `"BUG"` as unicode value
-70; // and subtract 70 from it, so it'll become 1
for(;n%++i // Increase `i` by 1 first before every iteration with `++i`
%n>0;); // And loop as long as `n` modulo-`i` is not 0
// NOTE: The second `%n` is to stop the loop for input n=1
System.console().printf("%s",
// Print to STDOUT with String format:
""+( // Convert the following boolean to String:
n==i));} // Check if `n` and `i` are equal
```
Prime checker credit goes to [*@SaraJ*'s answer here](https://codegolf.stackexchange.com/a/181611/52210), which is rather ingenious.
Things I had to do to comply to the challenge:
1. The challenge description mentions program (and technically the linked challenge as well), but this isn't possible in Java. I know [five different ways](https://pastebin.com/55PUYiXs) of creating a full program in Java, but each of them requires at least one of the letters `bgu`. Usually I can get past source-restrictions by using `\u`-unicode escapes, but since `u` is one of the restricted characters that's also not an option here. Luckily OP allowed functions as well, which is (much) shorter anyway.
2. I couldn't use `return` since it contains an `u`. And I also couldn't use `System.out.print(...)`, since it contains an `u` as well. So instead, I use [`System.console().printf("format",...)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Console.html#printf(java.lang.String,java.lang.Object...))
3. Since I wanted to print a boolean, the format to use in the `printf` would be `"%b"`. Unfortunately, `b` is blocked, so instead I use `"%s"` and convert the boolean to a string.
4. And last thing to tackle was of course sneaking `bug` in, so it works with it, but doesn't work anymore without it. I've done this by changing the `int i=1;` to `int i="BUG".charAt(2)-31;`, which grabs the third character in the String (the `'G'`) as unicode value (`71`), and subtracts 70 from it to make it `1`. If any of the `B`, `U`, and/or `G` is removed, the `.charAt(2)` will fail with a `StringIndexOutOfBoundsException`.
[Answer]
# [R](https://www.r-project.org/), 15 bytes
Linked challenge: [Output with the same length as the code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code)
```
strrep("bug",5)
```
[Try it online!](https://tio.run/##K/r/v7ikqCi1QEMpqTRdScdU8/9/AA "R – Try It Online")
(or [18 bytes](https://tio.run/##K/r/v7ikqCi1QEMpqTRdT09PScdI8/9/AA) if we include the default `[1] ""` formatting with which [R](https://www.r-project.org/) surrounds its ouput, but this restriction did not seem to be applied to the original linked challenge).
[Answer]
# Batch, 11 bytes
Linked challenge: [Output with the same length as the code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code)
```
@echo %bug%
```
Outputs `ECHO is on.` when run regularly or when some of `bug` is removed, and outputs `%` when all of `bug` is removed.
[Answer]
## Javascript (82 characters)
Linked challenge: [Integer lists of Noah](https://codegolf.stackexchange.com/questions/187879/integer-lists-of-noah)
```
c=>eval('O\x62ject').keys(x={},c.map(a=>x[a]=(x[a]||0)+1)).some(z=>x[z]!=2)&&'bug'
```
It's a bit lame, but I'm defining my outputs as producing 'bug' when input list is not a Noah list, and `false` when it is.
I love this challenge though. Maybe I can find a better solution. :)
[Answer]
# TI-Basic, 6 bytes
Linked challenge: [Output with the same length as the code](https://codegolf.stackexchange.com/questions/121056/output-with-the-same-length-as-the-code)
```
BUG
ᴇ5
```
] |
[Question]
[
Rule 110 is a cellular automaton with some interesting properties.
**Your goal** is to simulate a rule 110 in as few characters as possible.
For those who don't know, rule 110 is simulated line by line in a grid. Each square in a line of the grid looks at the squares above, above-left and above-right to determine what cell it should be.
```
current pattern 111 110 101 100 011 010 001 000
new cell 0 1 1 0 1 1 1 0
```
**Input:** numbers from 0 to 39 representing top row nth input square, in any reasonable format (comma-separated string, list, function arguments). To accommodate 1-indexed languages, numbers may also be 1-indexed and so range from 1 to 40.
Example input:
```
38,39
```
**Output:** A 40 x 40 grid representing the automata running including the first row. You should leave 0 as blank and 1 as any visible printing character. Trailing spaces are allowed, as long as the actual grid can reasonably be distinguished. The bottom of the grid may have a newline but there should not be blank lines between grid lines.
Example output:
```
XX
XXX
XX X
XXXXX
XX X
XXX XX
XX X XXX
XXXXXXX X
XX XXX
XXX XX X
XX X XXXXX
XXXXX XX X
XX X XXX XX
XXX XXXX X XXX
```
etc.
Note: A similar question about 1D cellular automata has already been asked, but I hope that, by using only one rule, shorter answers can be written.
[Answer]
## Ruby, 113 characters
```
c=[0]*41
eval"[#{gets}].map{|i|c[i]=1}"+'
c=(0..39).map{|x|putc" X"[u=c[x]]
110[4*c[x-1]+2*u+c[x+1]]}<<0;puts'*40
```
Takes input on stdin. To use a different rule, simply replace the `110` in the last line with whatever rule you want to try.
Example:
```
$ ruby 110.rb <<< 38,39
XX
XXX
XX X
XXXXX
XX X
XXX XX
XX X XXX
XXXXXXX X
XX XXX
XXX XX X
XX X XXXXX
XXXXX XX X
XX X XXX XX
XXX XXXX X XXX
XX X XX XXXXX X
XXXXXXXX XX XXX
XX XXXX XX X
XXX XX X XXXXX
XX X XXX XXXX X
XXXXX XX XXX X XX
XX X XXXXX X XX XXX
XXX XX XX XXXXXXXX X
XX X XXXXXX XX XXX
XXXXXXX X XXX XX X
XX X XXXX X XXXXX
XXX XX XX XXX XX X
XX X XXX XXX XX X XXX XX
XXXXX XX XXX XXXXXX XX X XXX
XX X XXXXX XXX XXXXXXXX X
XXX XXXX XXX X XX XXX
XX X XX X XX XXX XXX XX X
XXXXXXXX XX XXXXX X XX X XXXXX
XX XXXXXX XXXXXXXX XX X
XXX XX X XX X XXX XX
XX X XXX XX XXX XX XX X XXX
XXXXX XX X XXXXX X XXXXXXXXXX X
XX X XXXXX XX XXX XX XXX
XXX XX XX XXXX XX X XXX XX X
XX X XXXXXX XX X XXXXX XX X XXXXX
XXXXXX X XXX XXXX XXXXXX XX X
```
[Answer]
# Python - 141
```
i=input()
o=range(40)
l=''.join(' X'[c in i]for c in o)
for r in o:print l;l=''.join('X '[l[c-1:c+2]in('XXX',' ','X ','',' ')]for c in o)
```
Run as e.g. `python 110.py <<< 38,39`
[Answer]
# CJam - 47
```
S40*l',/{i'!t}/{N40,S3$S++f{>3<2b137Yb='!^}}39*
```
It uses `!` for "1" cells.
Try it at <http://cjam.aditsu.net/>
**Explanation:**
`S40*` makes a string (array) of 40 spaces
`l',/` reads a line and splits by comma
`{…}/` executes the block for each item (the numbers in string form)
- `i'!t` converts the number to integer and sets the item at that position in the previous string (initially 40 spaces) to '!'
At this point we have obtained the first line.
`{…}39*` executes the block 39 times
- `N` adds a newline
- `40,` makes the array [0 1 … 39]
- `S3$S++` copies the previous line (position 3 on the stack) and pads it with a space on each side
- `f{…}` executes the block for {each number from 0 to 39} and {the padded line}
-- `>3<` takes a slice of 3 items from the padded line starting at the current number
-- `2b` converts from base 2; the items we sliced are not base-2 digits, but characters get converted to their ASCII values and ' ' mod 8 is 0 and '!' mod 8 is 1
-- `137Yb` converts 137 to base 2 (`Y` = 2), obtaining [1 0 0 0 1 0 0 1], which is 110 reversed and negated (on 8 bits)
-- `='!^` gets the corresponding base-2 digit (the array wraps around so the index is taken mod 8) and xor's it with the '!' character, resulting in '!' for 0 and ' ' for 1
[Answer]
## Mathematica, 122 bytes
```
f[a_]:=Riffle[CellularAutomaton[110,Array[If[MemberQ[ToExpression["{"<>a<>"}"],#-1],1,0]&,40],39]/.0->" "/.1->"X","
"]<>""
```
Yes, you might view this as abusing [this loophole](http://meta.codegolf.stackexchange.com/a/1078/8478), but a) that loophole is quite disputed, b) a Cellular Automaton question *needs* a Mathematica answer (especially one about Rule 110) and c) Ventero's Ruby answer is shorter anyway, so I don't think any harm is done.
Most of the characters are used for input parsing and output formatting. The actual automaton is simulated using
```
CellularAutomaton[110,initialGrid,39]
```
This uses periodic boundary conditions (so the grid wraps around).
[Answer]
# q, ~~67~~ ~~62~~ 58 bytes
Assumes no wrap-around:
```
{40{not(2 sv'flip 1 0 -1 xprev\:x)in 0 4 7}\@[40#0b;x;~:]}
```
Old version
```
{40{not(flip(prev;::;next)@\:x)in 3 cut 111100000b}\@[40#0b;x;not]}
{40{not(flip 1 0 -1 xprev\:x)in 3 3#111100000b}\@[40#0b;x;~:]}
```
[Answer]
# Python, 186
```
def r(s,m=range(40)):
s=[int(i in s)for i in m]
for g in m:print''.join([' X'[i]for i in s]);s=[int(not''.join(map(str,s[i-1:i+2]if i else s[:2]))in'111 100 000 00'.split())for i in m]
```
Decent but probably not optimal.
You didn't specify how input is gotten so I just made a function.
Use example:
>
> r([38,39])
>
>
>
Output:
```
XX
XXX
XX X
XXXXX
XX X
XXX XX
XX X XXX
XXXXXXX X
XX XXX
XXX XX X
XX X XXXXX
XXXXX XX X
XX X XXX XX
XXX XXXX X XXX
XX X XX XXXXX X
XXXXXXXX XX XXX
XX XXXX XX X
XXX XX X XXXXX
XX X XXX XXXX X
XXXXX XX XXX X XX
XX X XXXXX X XX XXX
XXX XX XX XXXXXXXX X
XX X XXXXXX XX XXX
XXXXXXX X XXX XX X
XX X XXXX X XXXXX
XXX XX XX XXX XX X
XX X XXX XXX XX X XXX XX
XXXXX XX XXX XXXXXX XX X XXX
XX X XXXXX XXX XXXXXXXX X
XXX XXXX XXX X XX XXX
XX X XX X XX XXX XXX XX X
XXXXXXXX XX XXXXX X XX X XXXXX
XX XXXXXX XXXXXXXX XX X
XXX XX X XX X XXX XX
XX X XXX XX XXX XX XX X XXX
XXXXX XX X XXXXX X XXXXXXXXXX X
XX X XXXXX XX XXX XX XXX
XXX XX XX XXXX XX X XXX XX X
XX X XXXXXX XX X XXXXX XX X XXXXX
XXXXXX X XXX XXXX XXXXXX XX X
```
[Answer]
# Mathematica, 113 chars
Another Mathematica answer using `CellularAutomaton`.
```
Print@@" "["X"][[#]]&/@CellularAutomaton[110,SparseArray[#+1->1&/@ImportString[InputString[],"CSV"][[1]],40],39];
```
[Answer]
# C - 178
This code depends on the fact that each row in a matrix is stored in contiguous memory. Also, it does not print the first row, but it prints the next 40 ones, since the rules only specified a 40x40 grid.
Indented for readability only, the byte count only includes necessary code.
```
a[41][42],i,j,*t;
main(){
while(scanf("%d,",&j)>0)
a[i][j]=1;
for(;i<40;i++,puts(""))
for(j=0;++j<40;)
t=&a[i][j],
putchar((*(t+42)=1&(110>>(*(t+1)?1:0)+(*t?2:0)+(*(t-1)?4:0)))?88:32);
}
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~175 170 169 136 127~~ 124 bytes
−9 bytes thanks to @bmo
```
t(a:b:r:_)=mod(b+r+b*r+a*b*r)2
w%a=take 40.map w.iterate a
d l=t%tail$0:l++[0]
f l=map(" #"!!)%d$(fromEnum.(`elem`l))%succ$0
```
[Try it online!](https://tio.run/##FcqxCoMwFEDR3a942gQSAxLaLg04dmunjiL1WSMVE5X4xM9P7XKHy/niOlrnYiSBpjXBvGXp5060Kqg2Dwrzo/Kc7BxLwtHCVRceF9iLgWxAsoBJB64kTjg4po1TqtJ10h/vcCKDU5amkndM9GH292nzhWiss75xUvJ1@3yYjh6H6c@fsGz0ovCYGPRQXW51/AE "Haskell – Try It Online")
[Answer]
# Microsoft Excel, ~~21~~ 19 characters
(Not sure how to score this actually. I know this takes 39\*40 or 1560 formulas, but they all depend on the first one.)
As a bonus, this works in LibreOffice Calc too.
## The formula
`=(B1<>C1)+C1*(B1>A1`
To get the 40x40:
1. Insert the formula at cell B2. (Don't forget the `=` sign!)
2. Drag the cells to Column AO.
3. Drag these cells to Row 40.
Extra niceties:
1. Conditionally format cells to Good when value is TRUE
2. Set cell widths to 0.3" or something.
## Explanation
* The input is the first row. A value that can be converted to `TRUE`, such as 1 is `TRUE`. A blank cell or anything else is a `FALSE`.
* Column A is just a buffer to make edge cases easier to deal with.
* This is easier to see if you do the conditional formatting stuff.
* The formula is really just a hacky way of saying (B XOR C) + (BCA')
[Answer]
# Lua - 351
Not the ideal language for golfing.
```
s,n,t,u=arg[1],{},table.remove,table.insert
for i=1,40 do u(n,i,'.') end
for i in s:gmatch("%d+")do u(n,i,'x');t(n)end
function a(b) c="";for i=1,40 do c=c..b[i] end;print(c);return c end
for i=1,40 do z= n[40]..a(n)..n[1];for k=2,41 do y=string.sub(z,k-1,k+1);if y=="xxx"or y=="x.." or y=="..." then u(n,k-1,'.')else u(n,k-1,'x')end;t(n)end end
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~135 131~~ 130 bytes
-1 byte thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen) (rearranging `take 40`)
Completely different approach to [FrownyFrog's answer](https://codegolf.stackexchange.com/a/176954/48198) but about the same length:
```
(a?b)r=mod(b+r+b*r+a*b*r)2
r x=0:(zipWith3(?)x=<<tail$tail x++[0])
f y=take 40$map(" o"!!)<$>iterate r[sum[1|elem i y]|i<-[0..40]]
```
Uses \$1\$-indexing and has a leading space on each line, [try it online!](https://tio.run/##FY6xjsIwEER7vmJBKWwsIh9HFcVQUCFxFcUVlnXaiAUsYidyFimc@PdginnFSG80Nxzu1LbTJHDXyGRCdxaNSqpZJoXLTLmeJRiNrsS/7389377FTo6mrhl9W3wAo1JWOzm7wNMw3gk2ugjYiwV0i/lc1sXWMyVkgmSHR7BfL2opgIene/l6ZXVZbrRzU0AfwUBWf/6gf/CJ0zFCCZcckQjPUFWQSx@vq609RHYS8hG4Eu@7yBR5mGxeegM "Haskell – Try It Online")
## Explanation
We're going to work with length-\$41\$ lists with values \$\texttt{0}\$, \$\texttt{1}\$, so let's start with the correct array:
```
f y= [sum[1|elem i y]|i<-[0..40]]
```
Next we're going to iterate the rule \$40\$ times:
```
take 40$ iterate r
```
And finally map each \$\texttt{0}\$ and \$\texttt{1}\$ to some fancy character:
```
map(" o"!!)<$>
```
The function `r` which applies the \$\texttt{110}\$-rule is pretty simple: Using `zipWith3` and some padding we can outsource the actual decision for the next cell to `(?)`:
```
r x=0:(zipWith3(?)x=<<tail$tail x++[0])
```
The `(?)` operator is the most interesting part of the solution: [Previously](https://codegolf.stackexchange.com/revisions/177005/1) I used a Boolean rule generated with a Karnaugh map, but [turns out](http://atlas.wolfram.com/01/01/110/01_01_1_110.html) there is an even more concise way:
```
(a?b)r=mod(b+r+b*r+a*b*r)2
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~31~~ 28 bytes
Hah, Husk is beating Jelly!
```
†!¨↑¨↑40¡ȯẊȯ!ḋ118ḋėΘ`:0M#ŀ40
```
[Try it online!](https://tio.run/##yygtzv7//1HDAsVDKx61TQQTJgaHFp5Y/3BX14n1ig93dBsaWgDJI9PPzUiwMvBVPtpgYvD///9oY8tYAA "Husk – Try It Online")
## Explanation & Ungolfed
Before adding an explanation, let me ungolf this a bit.. Let's first remove the various compositions, add explicit parentheses and uncompress the `¨↑¨` string. Also let's replace `40` with `4` for a more readable explanation:
```
†!"t "↑4¡(Ẋ(!ḋ118ḋė)Θ`:0)M#ŀ4 -- example input: [3]
ŀ4 -- lower range of 4: [0,1,2,3]
M -- map over left argument
# -- | count in list
-- : [0,0,0,1]
¡( ) -- iterate the following indefinitely (example with [0,1,1,1])
`:0 -- | append 0: [0,1,1,1,0]
Θ -- | prepend 0: [0,0,1,1,1,0]
Ẋ( ) -- | map over adjacent triples (example with 1 1 0
ė -- | | create list: [1,1,0]
ḋ -- | | convert from base-2: 6
-- | | convert 118 to base-2: [1,1,1,0,1,1,0]
-- | | 1-based index: 1
-- | : [1,1,0,1]
-- : [[0,0,0,1],[0,0,1,1],[0,1,1,1],[1,1,0,1],[1,1,1,1],[1,0,0,1],...]
↑4 -- take 4: [[0,0,0,1],[0,0,1,1],[0,1,1,1],[1,1,0,1]]
† -- deep map the following (example with [1,1,0,1])
!"t " -- | use each element to index into "t ": "tt t"
-- : [" t"," tt"," ttt","tt t"]
```
[Answer]
# Python 3, 126 bytes (as function)
```
def r(n,r):
for d in range(r):print("".join(" o"[n>>i&1]for i in range(40)));n=sum((110>>(n>>i&7)&1)<<i+1 for i in range(40))
```
## 142 bytes with stdin
```
n,r=map(int,input().split())
for d in range(r):print("".join(" o"[n>>i&1]for i in range(40)));n=sum((110>>(n>>i&7)&1)<<i+1 for i in range(40))
```
## 188, my first attempt and favourite
```
import itertools as t;print("\n".join(map(lambda n:"".join(" o"[n>>i&1]for i in range(n.bit_length())),t.accumulate(range(1,40),lambda n,d:sum((110>>(n>>i&7)&1)<<i+1 for i in range(d))))))
```
[Answer]
# Java, 321 characters
Input passed as argument from command line, for example `java R 38,39`
I have never written more obfuscated java code :-)
```
class R{public static void main(String[]a) {
Integer s=40;boolean[]n,o=new boolean[s];
for(String x:a[0].split(","))o[s.valueOf(x)]=s>0;
for(Object b:o){n=o.clone();
for(int j=0;j<s;j++){
boolean l=j>1&&o[j-1],r=o[j],c=j+1<s&&o[j+1];
n[j]=!(l&c&r|l&!c&!r|!(l|c|r));
System.out.print((r?"X":" ")+(j>s-2?"\n":""));
}o=n;}}}
```
[Answer]
Update:
Correct output example [here](http://codepad.org/zP16o2GX) (with 40 lines not 50):
New output below (removed previous one for brevity):
```
xx
xxx
xx x
xxxxx
xx x
xxx xx
xx x xxx
xxxxxxx x
xx xxx
xxx xx x
xx x xxxxx
xxxxx xx x
xx x xxx xx
xxx xxxx x xxx
xx x xx xxxxx x
xxxxxxxx xx xxx
xx xxxx xx x
xxx xx x xxxxx
xx x xxx xxxx x
xxxxx xx xxx x xx
xx x xxxxx x xx xxx
xxx xx xx xxxxxxxx x
xx x xxxxxx xx xxx
xxxxxxx x xxx xx x
xx x xxxx x xxxxx
xxx xx xx xxx xx x
xx x xxx xxx xx x xxx xx
xxxxx xx xxx xxxxxx xx x xxx
xx x xxxxx xxx xxxxxxxx x
xxx xxxx xxx x xx xxx
xx x xx x xx xxx xxx xx x
xxxxxxxx xx xxxxx x xx x xxxxx
xx xxxxxx xxxxxxxx xx x
xxx xx x xx x xxx xx
xx x xxx xx xxx xx xx x xxx
xxxxx xx x xxxxx x xxxxxxxxxx x
xx x xxxxx xx xxx xx xxx
xxx xx xx xxxx xx x xxx xx x
xx x xxxxxx xx x xxxxx xx x xxxxx
xxxxxx x xxx xxxx xxxxxx xx x
```
Doing another puzzle I learned something interesting about nesting statements in for loops in php, and suddenly they are far more complex than I originally thought. When I get time I reckon I can beat this score considerably. For now though it remains unchanged at a non-competitive 408.
---
My php version 408 characters:
This was a great puzzle. I also spent ages playing with the inputs as these are fascinating things it must be said. Anyway, here is my PHP version (which is nowhere near as good as some of the answers posted but is complete. In 0th position only take above and above right, in 39th position only take above and above left, ie no wrapping. So here is my version:
```
<?php $a='38,39';$b='';$d=explode(',',$a);for($i=0;$i<40;++$i){$c=' ';
foreach($d as $k=>$v){if($v == $i){$c='x';}}$b.=$c;}echo $b."\n";
for($x=1;$x<41;++$x){$o='';for($i=1;$i<41;++$i){if(($i>1)AND(substr($b,$i-2,1)=='x')){
$l=1;}else{$l=0;}if((substr($b,$i-1,1))=='x'){$v=1;}else{$v=0;}if((substr($b,$i,1))=='x'){
$r=1;}else{$r=0;}if((($l+$v+$r)==2)OR(($v+$r)==1)){$o.='x';}else{$o.=' ';}}
echo $o."\n";$b=$o;}?>
```
You can see it and run it here: <http://codepad.org/3905T8i8>
Input is a input string at the start as $a='38, 39';
Output is as follows:
```
xx removed as was too long originally - had 50 lines, not 40 xx
```
Hope you like it!!!
PS I had to add a few line breaks to the code so you could see all of it and not have it stretch accross the page with a scroll bar.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437
```
╦♥µ╤u{£┬íQ<;▀ΦΣ╢╕╚äZ↕áû↑
```
[Run and debug online!](https://staxlang.xyz/#c=%E2%95%A6%E2%99%A5%C2%B5%E2%95%A4u%7B%C2%A3%E2%94%AC%C3%ADQ%3C%3B%E2%96%80%CE%A6%CE%A3%E2%95%A2%E2%95%95%E2%95%9A%C3%A4Z%E2%86%95%C3%A1%C3%BB%E2%86%91&i=%5B38%2C39%5D&a=1&m=2)
Uses the codepoint 1 in CP437 for "1" cells.
Excellent case to show the power of this language.
## Explanation
Uses the unpacked version (29 bytes) to explain.
```
0]40X*,1&xDQ0]|S3B{:b^374:B@m
0]40X* Prepare a tape with 40 cells
,1& Assign 1 to the cells specified by the input
xD Repeat the rest of the program 40 times
Q Output current tape
0]|S Prepend and append a 0 cell to it
3B All runs of length 3
{ m Map each run with block
:b Convert from binary
^ Increment (call this value `n`)
374:B The binary representation of 374
[1,0,1,1,1,0,1,1,0]
which is `01101110` reversed and prepended a 1
@ Element at 0-based index `n`
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~44~~ 36 bytes
```
{"X "39{(2\145)@2/'3':1,x,1}\^x?!40}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6pWilBQMras1jCKMTQx1XQw0lc3Vrcy1KnQMayNiauwVzQxqOXiSlMwtlAwtgQAFsILRw==)
`{` `}` function with argument `x`
`!40` list of ints from 0 to 39
`x?` find their indices in `x`, use `0N` (the "integer null") for not found
`^` which of them are nulls? this gives us the input, negated
`39{` `}\` apply 39 times, collecting intermediate results in a list
`1,x,1` surround the list with 1s (negated 0s)
`3':` triples of consecutive items
`2/'` binary decode each
`@` use as indices in ...
`2\145` binary encode 145 (negated bits of 110)
`"X "` finally, use the 40x40 matrix as indices in the string `"X "` (the `@` here is implicit)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 54 bytes
```
x:Y0X40RAgoL40{Fi,40x@i:01110110@FB(y@>i@<3)Y0.xPxR0s}
```
Pip is turing complete?!
(Jokes aside, this was a fun pip answer.)
## Explanation
```
x:Y0X40RAgoL40{Fi,40x@i:01110110@FB(y@>i@<3)Y0.xPxR0s}
x:Y0X40RAgo Assign 40 spaces to x and replace the input indices with 1
The same value is also yanked to y.
L40{ } Repeat 40 times
Fi,40 Loop variable i through range 1-40
x@i: Assign character at index i to:
01110110@ a number in 01110110 at index:
FB(y@>i@<3) a 3 letter substring of y starting at i, converted to binary.
Y0.x Yank(assign value) of 0 concantenated with x to y
PxR0s Print x with zeros replaced with spaces
```
[Try it online!](https://tio.run/##K8gs@P@/wirSIMLEIMgxPd/HxKDaLVPHxKDCIdPKwNDQEIgNHNycNCod7DIdbIw1Iw30KgIqggyKa////29s8d/YEgA "Pip – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
ṬµØ0jḄ3Ƥị236B¤µ39СYo⁶
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//4bmswrXDmDBq4biEM8ak4buLMjM2QsKkwrUzOcOQwqFZb@KBtv///1szOCwzOV0 "Jelly – Try It Online")
Took some inspiration from Erik's answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes
```
‘;41ṬṖŻ;0Ḅe“¢£¤¦©‘Ɗ3ƤƊ39СYo⁶
```
[Try it online!](https://tio.run/##AUUAuv9qZWxsef//4oCYOzQx4bms4bmWxbs7MOG4hGXigJzCosKjwqTCpsKp4oCYxoozxqTGijM5w5DCoVlv4oG2////MzgsMzk "Jelly – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 99 bytes
```
$_=$"x40;for$b(@F){substr$_,$b,1,1}for$b(1..40){say;s,(?<=(.)).(?=(.)),"$1$&$2"=~/111| $/?$":1,ge}
```
[Try it online!](https://tio.run/##JcnRCoIwFADQXxnjEhtc524qVDbWU299gyiYBNFkMyjKPr1b1NN5OGMfzxUzNA7krbT1MUTo1G6vH@napSlCg9AhIc3/IWNK@832XidUfuuU0doo/xMlECxgKd0rJ6KnEJB7kBvCoZ@Zi5Uo1u8wTqdwSZwdKmPJctZ@AA "Perl 5 – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 370 bytes
```
fn a(f:&[u8]){let mut g=[0;40];for e in f{g[*e as usize]=1;};p(&g);for _ in 0..39{let mut n=[0;40];for e in 0..40{let m=match e{0=>r(g[0]*2+g[1]),39=>r(g[38]*4+g[39]*2),_=>r(g[e-1]*4+g[e]*2+g[e+1])};n[e]=m;}g=n;p(&g);}}fn p(g:&[u8]){println!("{}",g.iter().map(|x|format!("{}",x)).collect::<String>().replace("0"," "));}fn r(b:u8)->u8{match b{0|4|7=>0,1|2|3|5|6=>1,_=>2}}
```
[Try it online!](https://tio.run/##ZZDdboMgFMev16dgXjTQWoPVbVaGL7FLQxpqkJkoNRSTZsKzd6ez280u@X@cc37Y6eJut9YgidtyXU@FIHOvHBomhzSvKcupYO3ZIoU6g9pZ1xuF5AVNl@5LCZ6ywEa81uQnc7xnaJJkh78Z5t8M8HO6@HyQrvlEaqa8sljXVGz2W12ngsTZYZGyQmxy0LIDeCQ@LqrapYuslobaQicwA28@sKC5eVwVAqCNWP@ijbYzrjfPOJpDFOukc8pikgxyxP7q4Ua46GFeCUmac9@rxpXl@4eDpq4ga9XYy0bhiEZxhCICS2CHxadyKsiumop5oTrN1Of@jVc0Tv3eZ/7Fv/IqvSPsQ7h/@SA7gwmaV08Sr4EUoAVhq3D7Bg "Rust – Try It Online")
A probably very naive implementation. Input is a slice of `u8` representing the starting `1`s. Prints rule 110, with `1` as its character.
Ungolfed:
```
fn r110(filled: &[u8]) {
let mut grid = [0; 40];
for e in filled { grid[*e as usize] = 1; }
println!(
"{}",
grid
.iter()
.map(|x| format!("{}",x))
.collect::<String>()
.replace("0", " "));
for _iteration in 0..39 {
let mut next_grid = [0; 40];
for element in 0..40 {
let next = match element {
0 => {
rule(grid[0]*2 + grid[1])
}
39 => {
rule(grid[38]*4 + grid[39]*2)
}
_ => {
rule(grid[element-1]*4 + grid[element]*2 + grid[element+1])
}
};
next_grid[element] = next;
}
grid = next_grid;
println!(
"{}",
grid
.iter()
.map(|x| format!("{}",x))
.collect::<String>()
.replace("0", " "));
}
}
fn rule(bits: u8) -> u8 {
// current pattern 111 110 101 100 011 010 001 000
// new cell 0 1 1 0 1 1 1 0
match bits {
0 | 4 | 7 => 0,
1 | 2 | 3 | 5 | 6 => 1,
_ => 2
}
}
```
```
[Answer]
# JavaScript, 242, 202 bytes
```
// redable version
((...l)=>{
k=Array(40).fill(' ');l.map(x=>k[x]='X')
for(i=0;i++<40;){
console.log(k.join``);
k=k.map((x,i)=> i==0|| (i==k.length) || [" ","XXX","X. "].includes(k.at(i-1)+k.at(i)+k.at(i+1)) ? ' ':'X')
}
})(38,39)
```
Minified:
```
((...l)=>{k=Array(40).fill(' ');l.map(x=>k[x]='X');for(i=0;i++<40;){console.log(k.join``);k=k.map((x,i)=>i==0||(i==k.length)||[" ","XXX","X. "].includes(k.at(i-1)+k.at(i)+k.at(i+1))?' ':'X')}})(38,39)
```
] |
[Question]
[
Given an integer, output five perfect cubes whose sum is that integer. Note that cubes can be positive, negative, or zero. For example,
```
-10 == -64 - 64 + 64 + 27 + 27
```
so for input `-10` you could output `[-64, -64, 64, 27, 27]`, though other solutions are possible. Note that you should output the cubes, not the numbers being cubed.
A solution [always exists](https://math.stackexchange.com/q/207366/24654) -- you might enjoy puzzling this out for yourself. It's further conjectured that four cubes suffice.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes
```
∧5~lLȧᵐ≥₁∧L^₃ᵐ.+?∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HHctO6HJ8Tyx9unfCoc@mjpkagiE/co6ZmoICetj2Q9/9/vInR/ygA "Brachylog – Try It Online")
### Explanation
We basically describe the problem, with the additional constraint that we want the output list to be non-increasing in terms of magnitudes: this forces Brachylog to properly backtrack over all possible combinations of 5 values, instead of infinitely backtracking over the value of the last element of the list.
```
∧ ∧ (disable some implicit stuff)
5~lL L is a list of length 5
Lȧᵐ≥₁ L must be a non-increasing list in terms of magnitude
∧
L^₃ᵐ. The output is L with each element cubed
.+? The sum of the output is the input
```
### Finding different solutions
By appending a `≜`, it's possible to use this predicate to find all solutions with increasing magnitudes: for example, [here are the first 10 solutions for `42`](https://tio.run/##SypKTM6ozMlPN/pvbWjwqG3Do6bGh9sWPGrc9/9Rx3LTuhyfE8sfbp3wqHMpUAIo4hP3qKkZKKCnbQ/kPeqc8/@/idH/KAA)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
Thanks Fatalize for saving one byte
```
~+l₅≥₁.√₃ᵐ∧
```
[Try it online!](https://tio.run/##ASwA0/9icmFjaHlsb2cy//9@K2zigoUu4oml4oKB4oia4oKD4bWQ4oin//9fNDL/Wg "Brachylog – Try It Online")
Firstly `~+` enforces that the output (`.`) must sum to the input. `l₅` again constrains the output, dictating that it must have a length of 5. `≥₁` declares that the list must be in decreasing order (I believe that this is necessary to stop the program entering an infinite loop)
We explicitly unify this list with `.`, the output variable, because our next predicate will "change" the values inside the list. We then take the cube root of each value in the list with `√₃ᵐ`. Since Brachylog is inherently integer-based, this dictates that all the numbers in the list are cube numbers.
Finally, we use `∧` because there is an implicit `.` added to the end of each line. Since we don't want `.` to be unified with the list of cube roots, we unified it earlier on and use `∧` to stop it unifying at the end.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~58~~ ~~57~~ 54 bytes
```
def f(n):k=(n**3-n)/6;return[v**3for v in~k,1-k,n,k,k]
```
[Try it online!](https://tio.run/##VctBCsIwEIXhvafIMikT7CQgVvEk4s4Gy@C0xLTQTa8eA2Kn3f28jzfM6dWzy/nZBhU0mwvdNFeVt2yOp2ts0xj5PpUh9FFNquOFAC0BAwE98hA7TuWIeDbwGd/6l@Yg0Ag0W3D1CiW3gAK4AyfgduAF/B9Wtlib/AU "Python 2 – Try It Online")
---
* -2 bytes, thanks to Rod
* -1 byte, thanks to Neil
[Answer]
# [Python 3](https://docs.python.org/3/), 65 bytes
```
def f(n):k=(n-n**3)//6;return[n**3,(k+1)**3,(k-1)**3,-k**3,-k**3]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI0/TKttWI083T0vLWFNf38y6KLWktCgvGsTX0cjWNtSEMHQhDN1sOBn7Py2/SCFPITNPoSgxLz1VQ9fIQMfIQNOKizO5NCm12BZkOBdnQVFmXomGkmqxlWqxkqpGcWmuBlhaUwdCaf4HAA "Python 3 – Try It Online")
I mean, an explicit formula is even [here](https://math.stackexchange.com/a/1032601/328173) (although he abstracted the construction behind an existential)
[Answer]
# Java 8, ~~178~~ ~~87~~ ~~73~~ ~~71~~ 65 bytes
```
n->new long[]{n*n*n,(n=(n-n*n*n)/6+1)*n*n--,--n*n*n,n=-++n*n*n,n}
```
-6 bytes thanks to *@OlivierGrégoire*.
Same explanation at the bottom, but using the base equation instead of the derived one I used before (thanks to [*@LeakyNun*'s Python 3 answer](https://codegolf.stackexchange.com/a/161234/52210) for the implicit tip):
***k = (n - n3) / 6
n == n3 + (k+1)3 + (k-1)3 - k3 - k3***
[Try it online.](https://tio.run/##LU/BTsMwDL3zFdZOCWnCduFACRIfwC47AoeQdZNL5kyJOzRN/faSLpVt@dmyn597d3G63/9OPric4cMh3R4AkLhLB@c72M4lQIh0/PwGL2YAJNvSHUsUz@wYPWyBwMJE@o26v2X@Ro/FGkFWkL5j@fSsNnJGWje69hqyWqkFjlNbac/DTyi0C/sl4h5ORZ3YccKZ28mq7BCTKHIBrd6s1y3gq61ZKXkfANhdM3cnEwc257LMgQSq1csXr1Rf/jcDYzDvKblrNhzrAUHGC5Ry@XSc/gE)
---
**Old 178 bytes answer:**
```
n->{for(long k=0,a,b,c,d;;){if(n==(a=n*n*n)+(b=(d=k+1)*d*d)+(c=(d=k-1)*d*d)-(d=k*k*k++)-d)return a+","+b+","+c+","+-d+","+-d;if(n==a-b-c+d+d)return-a+","+-b+","+-c+","+d+","+d;}}
```
[Try it online.](https://tio.run/##NZDBboQgEIbvfYqJJxDHuGfKvkH30mPTwwjasLq4UdykMT67HcVmgMkP/IH/u9OL8O66zfY0TfBBPixvAD7EZmzJNnDbJcBnHH34ASv4BILUvLny5DFFit7CDQIY2AJel3YYRT/w7c5UBRV1YQuntVx8K4IxgkzIuaQStRHOdOoic5c71vbQeGrcRc6llEQnxybOYwBSWZGp@ljtsaI7m04PENZolVP/FkwWTB5MpuRxel03nXI857rnHGec1@AdPJiGSMm/vkkmEnu6HYI3eKkqDf7dpM7fPC4wrN8pNo9ymGP5ZHPsg/AqYzyZCiUjlCe/dfsD)
**Explanation:**
I loop `k` from 0 upwards until a solution is found. In every iteration it will check these two equations:
* Positive `k`: *n == n3 + (k+1)3 + (k-1)3 - k3 - k3*
* Negative `k`: *n == n3 - (k+1)3 - (k-1)3 + k3 + k3*
**Why?**
Since ***n - n3 = n\*(1-n)\*(1+n)*** and then ***6|(n-n3)***, it can be written as ***n - n3 = 6k***.
***6k = (k+1)3 + (k-1)3 - k3 - k3***.
And therefore ***n = n3 + (k+1)3 + (k-1)3 - k3 - k3*** for some ***k***.
[Source.](https://math.stackexchange.com/a/1032601/368863)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
‘c3µ;;C;~;³*3
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4xk40Nbra2dreusD23WMv7//7@hAQA "Jelly – Try It Online")
Figure out the formula independently. (x+1)3 + (x-1)3 - 2 × x3 == 6 × x.
---
```
=== Explanation ===
‘c3µ;;C;~;³*3 Main link. Input: (n).
‘ Increment.
c3 Calculate (n+1)C3 = (n+1)×n×(n-1)÷6.
µ Start a new monadic link. Current value: (k=(n³-n)÷6)
; Concatenate with itself.
;C Concatenate with (1-k).
;~ Concatenate with bitwise negation of (k), that is (-1-k)
;³ Concatenate with the input (n).
*3 Raise the list [k,k,1-k,-1-k,n] to third power.
End of program, implicit print.
```
Alternative 13 bytes: [Try it online!](https://tio.run/##y0rNyan8//9Rw4xk40Nbra2dresOb7DWMv7//7@hAQA "Jelly – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~47~~ ~~40~~ 33 bytes
```
@(n)[k=(n^3-n)/6,k,-k-1,1-k,n].^3
```
[Try it online!](https://tio.run/##bYvBCgIhFEX3fcXbiEpPU4SoCaH/mGZAIkFkXjFp0Nebs29zuHDued5L@Dxa9FrrdhUkx@wFzU6RPBwxo8rKolUZadKzawU8KGsGay67sK7hGyuJLXutiUoUnLk0sHOCPbDTP3rojxtxHAlj7/BdF7ENOUksyGtXRkL7AQ "Octave – Try It Online")
Saved 6 bytes thanks to Giuseppe, since I had forgotten to remove some old parentheses. Saved another bytes by changing the signs, thanks to rafa11111.
Uses the formula in the linked [math.se post](https://math.stackexchange.com/a/1032601/92515):
1. Since **n - n^3 = n(1-n)(1+n)** then **6 | (n - n^3)** and we can write **n - n^3 = 6k**.
2. **6k = (k+1)^3 + (k-1)^3 - k^3 - k^3**.
It appears to be longer if I try to *solve* the equation: **(n-n^3)=(k+1)^3 + (k-1)^3 - k^3 - k^3** with regards to **k**, instead of just using the equation.
[Answer]
# Minecraft Functions (18w11a, 1.13 snapshots), 813 bytes
[![perfect cubes in minecraft](https://i.stack.imgur.com/NFzwQ.png)](https://i.stack.imgur.com/NFzwQ.png)
Uses six functions:
a
```
scoreboard objectives add k dummy
scoreboard objectives add b dummy
scoreboard objectives add c dummy
scoreboard players operation x k = x n
function d
function f
scoreboard players operation x k -= x b
scoreboard players set x b 6
scoreboard players operation x k /= x b
scoreboard players set x b 1
function d
scoreboard players operation x c += x b
function f
scoreboard players set x b 1
function d
scoreboard players operation x c -= x b
function f
function d
function e
scoreboard players operation x b -= x c
scoreboard players operation x b -= x c
function c
function b
```
b
```
tellraw @s {"score":{"name":"x","objective":"b"}}
```
c
```
scoreboard players operation x b *= x c
scoreboard players operation x b *= x c
function b
```
d
```
scoreboard players operation x c = x k
```
e
```
scoreboard players operation x b = x c
```
f
```
function e
function c
```
"Takes input" from a scoreboard objective named `n`, create it with `/scoreboard objectives add n dummy` and then set it using `/scoreboard players set x n 5`. Then call the function using `/function a`
Uses the formula from [this math.se answer](https://math.stackexchange.com/a/1032601/249082)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 48 45 bytes
* thanks to @Arnauld for reducing 3 bytes
```
n=>[n,1-(k=(n**3-n)/6|0),~k,k,k].map(x=>x**3)
```
[Try it online!](https://tio.run/##TYlBDoIwEADvvoJjl7SwrQumh/IRwqFBMApsiRDDwfj12ptmLpOZh3/5rX/e111xuA5xdJFd07LUSkxOcJ6fFUNZvxHkZ5KJrlj8Kg7XHOlB7ANvYR6KOdzEKJRGgNN/a1NClBlVFzK2TkIaLZHMFJE12lQ/6yB@AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 21 bytes
```
|_G|&:5Z^3^t!sG=fX<Y)
```
This tries all 5-tuples of numbers from the set `(-abs(n))^3, (-abs(n)+1)^3, ..., abs(n)^3`. So it is very inefficient.
[Try it online!](https://tio.run/##y00syfn/vybevUbNyjQqzjiuRLHY3TYtwiZS8/9/XUMDAA "MATL – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~43~~ 42 bytes
```
p n|k<-div(n^3-n)6=map(^3)[n,-k-1,1-k,k,k]
```
Just the popular answer, translated to Haskell. Thanks to @rafa11111 for saving a byte!
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0AhrybbRjcls0wjTzcvzljTzDY3sUADyIjO08nWNtTJ1jXU0c0Gotj/uYmZeQq2Choxebp2CgVFmXklChpA/Zp2dlBOcWmuCkhAU0FD19BA8z8A "Haskell – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
ḟo=⁰Σπ5m^3İZ
```
[Try it online!](https://tio.run/##AR8A4P9odXNr///huJ9vPeKBsM6jz4A1bV4zxLBa////LTEw "Husk – Try It Online")
Tries all possible lists of 5 cubes, and returns the first one with the correct sum.
### Explanation
```
ḟo=⁰Σπ5m^3İZ
İZ List of all integers [0,1,-1,2,-2,3,-3...
m^3 Cube of each integer [0,1,-1,8,-8,27,-27...
π5 Cartesian power with exponent 5. This returns a list of all possible
lists built by taking 5 elements from the input list. This infinite
list is ordered in such a way that any arbitrary result occurs at a
finite index.
ḟo Find and return the first element where...
Σ the sum of the five values
=⁰ is equal to the input
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 85 81 75 bytes
Saved 4 bytes and then 6 bytes thanks to @ceilingcat's re-ordering of assignments
```
r[5];f(n){r[1]=(n=(n-(*r=n*n*n))/6+1)*n*n--;r[3]=r[4]=-n*n*n;r[2]=--n*n*n;}
```
[Try it online!](https://tio.run/##VY/PDoIwDMbP8BSLicnGtgj@O4h7krmDQWY4UEzhJOHZsZ1ezJrla39t@rWxz6ZZV/SnUEcJakZfBSeBwsoCHRT0lNqddaVYWlujPwSH/hicTZQKe9K/ZFn7ewdS5XOexQFlB5MA4YStyrImdXXiq7RWYmrHiZbW@ZInmZrTaN/2YztJNKUZu3c7RGaqOFFvFtNI9kIqRbkBt31cxPbxF46@G2wMGPRlMHyVYZ@G3Rt2n4BmoBloBpoB21k/ "C (gcc) – Try It Online")
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 53 bytes
```
READ*,N
K=(N**3-N)/6
PRINT*,(/N,1-K,-1-K,K,K/)**3
END
```
[Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/v8PcnV00dLx4/K21fDT0jLW9dPUN@MKCPL0C9HS0dD30zHU9dbRBRFAqK8JVMHl6ufy/78pAA "Fortran (GFortran) – Try It Online")
Fortran outgolfing Python? What's going on here?
[Answer]
# Python 3, ~~65~~ ~~61~~ 60 bytes
```
lambda N:[n**3for k in[(N**3-N)//6]for n in[N,-k-1,1-k,k,k]]
```
Edit: dropped some unnecessary spaces.
Edit: thanks to rafa11111's smart reordering.
Inspired by [this](https://math.stackexchange.com/a/1032601/339905).
[Try it online!](https://tio.run/##FclBCoAgEIXhfaeYpYpSErQQuoIXKBdGWYM1hbTp9Ka81fu/53uPm/ocxjmf/lpWD9ZMJEQf7gQRkCZmy1OWt@3gaqQarVRRaalVlGXO5SpYBJKnfWOFOs1NA09CehnKwJDz/AM)
[Answer]
# [R](https://www.r-project.org/), ~~40~~ 38 bytes
Makes use of the formula in the linked math.SE post. Down to 2 bytes thanks to Giuseppe.
```
c(n<-scan(),k<-(n^3-n)/6,k,1-k,-k-1)^3
```
[Try it online!](https://tio.run/##K/r/P1kjz0a3ODkxT0NTJ9tGVyMvzlg3T1PfTCdbx1A3W0c3W9dQM874v66hwX8A)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~30~~ 26 bytes
```
3*⍨⊢,∘(1 ¯1∘+,2⍴-)6÷⍨⊢-*∘3
```
[Try it online!](https://tio.run/##fU69DgFBEO49xXT2fjasE50HUHmGw/nJnezm1hUiWrmIFY1Eo1HJNQpEpeFN5kXOZKkVM5lvvp98oUr4YB4mclTidt/p4mpXBzRHGMoUBhOtknAOKkuV1JEu@1kv0iQJXDRnXJ98zA9MwOsi6PD8Bpobd1rvx5flLn2DslSplENyLbwa5ms0dxZ7wmExp2UtMZE/l7lzGjdw3GBpe1gztEFnU6BjNo7Atqjg5ommYBa8zpgXDM21IRyfYrglf6ggwGzMf1lTUJdqu/oB)
APL translation of [LeakyNun's answer](https://codegolf.stackexchange.com/a/161234/74163).
Thanks to Adám for 4 bytes by going tacit.
### How?
```
3*⍨⊢,∘(1 ¯1∘+,2⍴-)6÷⍨⊢-*∘3 ⍝ Tacit function
6÷⍨⊢-*∘3 ⍝ (n-n^3)/6 (our k)
-) ⍝ Negate
2⍴ ⍝ Repeat twice; (yields -k -k)
(1 ¯1∘+, ⍝ Append to k+1, k-1
,∘ ⍝ Then append to
⊢ ⍝ n
3*⍨ ⍝ And cube everything
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 20 bytes
```
m^3m‼:_:→:←;K¹÷6Ṡ-^3
```
[Try it online!](https://tio.run/##yygtzv7/PzfOOPdRwx6reKtHbZOAeIK196Gdh7ebPdy5QDfO@P///7qGBgA "Husk – Try It Online")
Uses the formula from [this post](https://math.stackexchange.com/questions/207366/can-any-integer-can-be-written-as-the-sum-of-8-integer-cubes/1032601#1032601).
### Explanation
```
m^3m‼:_:→:←;K¹÷6Ṡ-^3 Implicit input
Ṡ- Subtract itself from it
^3 raised to the third power
÷6 Divide by six
m Map over the value with a list of functions:
; Create a singleton list with
K¹ the function of replace by the input
:← Append the function of decrement
:→ Append the function of increment
‼:_ Append the function of negate twice
m^3 Cube the numbers of the list
```
[Answer]
# x86, ~~41~~ 39 bytes
Mostly straightforward implementation of the formula with input in `ecx` and output on the stack.
The interesting thing is that I used a cubing function, but since [`call label` is 5 bytes](https://stackoverflow.com/q/49700798/3163618), I store the label's address and use the 2 byte `call reg`. Also, since I'm pushing values in my function, I use a `jmp` instead of `ret`. It's very possible that being clever with a loop and the stack can avoid calling entirely.
I did not do any fancy tricks with cubing, like using `(k+1)^3 = k^3 + 3k^2 + 3k + 1`.
Changelog:
* Fix byte count using `not` instead of `neg`/`dec`.
* -2 bytes by not `xor`ing `edx` since it is probably 0 from `imul`.
```
.section .text
.globl main
main:
mov $10, %ecx # n = 10
start:
lea (cube),%edi # save function pointer
call *%edi # output n^3
sub %ecx, %eax # n^3 - n
# edx = 0 from cube
push $6
pop %ebx # const 6
idiv %ebx # k = (n^3 - n)/6
mov %eax, %ecx # save k
call *%edi # output k^3
push %eax # output k^3
not %ecx # -k-1
call *%edi # output (-k-1)^3
inc %ecx
inc %ecx # -k+1
call *%edi # output (-k+1)^3
ret
cube: # eax = ecx^3
pop %esi
mov %ecx, %eax
imul %ecx
imul %ecx
push %eax # output cube
jmp *%esi # ret
```
Objdump:
```
00000005 <start>:
5: 8d 3d 22 00 00 00 lea 0x22,%edi
b: ff d7 call *%edi
d: 29 c8 sub %ecx,%eax
f: 6a 06 push $0x6
11: 5b pop %ebx
12: f7 fb idiv %ebx
14: 89 c1 mov %eax,%ecx
16: ff d7 call *%edi
18: 50 push %eax
19: f7 d1 not %ecx
1b: ff d7 call *%edi
1d: 41 inc %ecx
1e: 41 inc %ecx
1f: ff d7 call *%edi
21: c3 ret
00000022 <cube>:
22: 5e pop %esi
23: 89 c8 mov %ecx,%eax
25: f7 e9 imul %ecx
27: f7 e9 imul %ecx
29: 50 push %eax
2a: ff e6 jmp *%esi
```
---
Here is my testing version that does all the cubing at the end. After the values are pushed on the stack, the cube loop overwrites stack values. It's currently ~~42~~ 40 bytes but there should be some improvements somewhere.
```
.section .text
.globl main
main:
mov $10, %ecx # n = 10
start:
push %ecx # output n
mov %ecx, %eax
imul %ecx
imul %ecx
sub %ecx, %eax # n^3 - n
# edx = 0 from imul
push $6
pop %ecx # const 6
idiv %ecx # k = (n^3 - n)/6
push %eax # output k
push %eax # output k
not %eax # -k-1
push %eax # output -k-1
inc %eax
inc %eax # -k+1
push %eax # output -k+1
dec %ecx # count = 5
add $20, %esp
cube:
mov -4(%esp),%ebx # load num from stack
mov %ebx, %eax
imul %ebx
imul %ebx # cube
push %eax # output cube
loop cube # --count; while (count)
ret
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 43 bytes
```
->n{[~k=(n**3-n)/6,1-k,n,k,k].map{|i|i**3}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOrou21YjT0vLWDdPU99Mx1A3WydPJ1snO1YvN7GguiazJhMoV1v7P0/BVkHX0ICLq0AhLTovFkrpFZfmKtjaKuT9BwA "Ruby – Try It Online")
[Answer]
# [Cubically](https://github.com/aaronryank/cubically), 51 characters, 55 bytes
```
⇒-6-^0+7/0»8
$F:^0%@5-7/0»8^0%@5%@5f1+8^0%@5f1-8^0%
```
[Try it online!](https://tio.run/##Sy5NykxOzMmp/P//UfskXTPdOANtc32DQ7stuFTcrOIMVB1MdSF8MBuI0gy1Iew0Q10Q4/9/UwA "Cubically – Try It Online")
Apparently MDXF forgot to implement the SBCS...
[Answer]
# [Unefunge 98](https://esolangs.org/wiki/Funge-98), 35 bytes
```
j&3k:**-6/:1-\:1+\0\-::!#@_::**.37*
```
[Try it online!](https://tio.run/##K81LTSvNS0/VtbTQLagEM///z1IzzrbS0tI107cy1I2xMtSOMYjRtbJSVHaItwKK6xmba/3/b6IAAA "Unefunge-98 (PyFunge) – Try It Online")
It uses the popular formula from [this math.se answer](https://math.stackexchange.com/a/1032601/249082).
[Answer]
# Perl 5 `-nE`, 48 bytes
```
say$_**3for$i=($_**3-($n=$_))/6,$i,-1-$i,1-$i,$n
```
[hat-tip](//math.stackexchange.com/a/1032601)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 52 bytes
```
$o,(1-($k=($o*$o-1)*$o/6)),(-$k-1),$k,$k|%{$_*$_*$_}
```
[Try it online!](https://tio.run/##VZHfS8MwEMefm7/iGBkk2zLXB0UcA1@cvoyJFXwQmbEeLFvb1CbFybq/vV7qHArHkfvx/eRyKe0nVm6NWaZSW2E7r4vUG1vAIzovJNuziKfaoYMZXAs5ZVE8HscTaKAPeziWhjO4Ra8edPFuc1ALvTN5ncP5hM6m6M7xFA4sOsE6OYsirgtHAxB8bi3w1TTkjFton64pKX7rDSxQu7pCtXzbYOpBJQRtIMGsi252JV1@X9kSK/8FVJSg8ONIDFBb@7L2xDwi1caaAnowhF5oeaqMR3VnnYfeaQBaA1/BqxfkSfiDkKH/wNgfCfsnT3ReZgjLrvsqdIe3XTLSnLZLGfFsCv/CLe245XYkYiX4dia4HXCrYkn@7ELKkVB8S@GIb8ma/p6vBp0dWuKFT2q/AQ "PowerShell Core – Try It Online")
Uses the equation `o=o^3 + (1-k)^3 + (-k-1)^3 + k^3 + k^3`, where `k=o^3 - o`; this is a minor refactoring of the popular `l=o-o^3` (with `k=-l`).
As a side note, the expression `l=o-o^3` looks like a cat with a hurt ear.
] |
[Question]
[
Your task is to write a program or a function that prints an ASCII triangle. They look like this:
```
|\
| \
| \
----
```
Your program will take a single numeric input `n`, with the constraints `0 <= n <= 1000`. The above triangle had a value of `n=3`.
The ASCII triangle will have `n` backslashes (`\`) and vertical bars (`|`), `n+1` lines and dashes (`-`), and each line will have an amount of spaces equal to the line number (0-based, ie first line is line 0) besides the ultimate line.
## Examples:
Input:
```
4
```
Output:
```
|\
| \
| \
| \
-----
```
Input:
```
0
```
Output:
```
```
In this test case, the output must be empty. No whitespace.
Input:
```
1
```
Output:
```
|\
--
```
Input & output must be **exactly** how I specified.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so aim for the shortest code possible!
[Answer]
# C, 58 bytes
```
i;f(n){for(i=2*n;~i--;printf(i<n?"-":"|%*c\n",2*n-i,92));}
```
--
Thanks to @Steadybox who's comments on [this answer](https://codegolf.stackexchange.com/a/109512/16513) helped me shave a few bytes in my above solution
[Answer]
## Javascript (ES6), ~~97~~ ~~85~~ ~~81~~ ~~75~~ 74 bytes
```
n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)
```
Turns out I wasn't using nearly enough recursion
```
f=n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)
console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~15~~ 16 bytes
Saved a byte thanks to *Adnan*
```
FðN×…|ÿ\}Dg'-×»?
```
[Try it online!](https://tio.run/nexus/05ab1e#ARsA5P//RsOwTsOX4oCmfMO/XH1EZyctw5fCuz///zQ "05AB1E – TIO Nexus")
**Explanation**
```
F } # for N in range [0 ... input-1]
ðN× # push <space> repeated N times
…|ÿ\ # to the middle of the string "|\"
Dg # get length of last string pushed
'-× # repeat "-" that many times
» # join strings by newline
? # print without newline
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~18~~ ~~17~~ 16 bytes
*1 byte saved thanks to @nmjcman101 for using another way of outputting nothing if the input is `0`*
```
é\é|ÀñÙá ñÒ-xÀ«D
```
[Try it online!](https://tio.run/nexus/v#@394ZczhlTWHGw5vPDzz8EIFIDVJt@Jww6HVLv///zcAAA "V – TIO Nexus")
Hexdump:
```
00000000: e95c e97c c0f1 d9e1 20f1 d22d 78c0 ab44 .\.|.... ..-x..D
```
### Explanation (outdated)
We first have a loop to check if the argument is `0`. If so, the code below executes (`|\` is written). Otherwise, nothing is written and the buffer is empty.
```
Àñ ñ " Argument times do:
é\é| " Write |\
h " Exit loop by creating a breaking error
```
Now that we got the top of the triangle, we need to create its body.
```
Àñ ñ " Argument times do:
Ù " Duplicate line, the cursor comes down
à<SPACE> " Append a space
```
Now we got one extra line at the bottom of the buffer. This has to be replaced with `-`s.
```
Ó- " Replace every character with a -
x " Delete the extra '-'
```
---
This answer would be shorter if we could whatever we want for input `0`
# [V](https://github.com/DJMcMayhem/V), ~~14~~ 13 bytes
```
é\é|ÀñÙá ñÒ-x
```
[Try it online!](https://tio.run/nexus/v#@394ZczhlTWHGw5vPDzz8EIFIDVJt@L///8mAA "V – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
’⁶x⁾|\jṄµ€Ṫ”-ṁ
```
[Try it online!](https://tio.run/nexus/jelly#ASQA2///4oCZ4oG2eOKBvnxcauG5hMK14oKs4bmq4oCdLeG5gf///zQ "Jelly – TIO Nexus")
### How it works.
```
’⁶x⁾|\jṄµ€Ṫ”-ṁ Main link. Argument: n
µ Combine the links to the left into a chain.
€ Map the chain over [1, ..., n]; for each k:
’ Decrement; yield k-1.
⁶x Repeat the space character k-1 times, yielding a string.
⁾\j Join the character array ['|', '\'], separating by those spaces.
Ṅ Print the result, followed by a linefeed.
Ṫ Tail; extract the last line.
This will yield 0 if the array is empty.
⁾-ṁ Mold the character '-' like that line (or 0), yielding a string
of an equal amount of hyphen-minus characters.
```
[Answer]
# C#, 93 bytes
```
n=>{var s=n>0?new string('-',n+1):"";while(n-->0)s="|"+new string(' ',n)+"\\\n"+s;return s;};
```
Anonymous function which returns the ASCII triangle as a string.
Full program with ungolfed, commented function and test cases:
```
using System;
class ASCIITriangles
{
static void Main()
{
Func<int, string> f =
n =>
{
// creates the triangle's bottom, made of dashes
// or an empty string if n == 0
var s = n > 0 ? new string('-', n + 1) : "";
// a bottom to top process
while ( n-- > 0)
// that creates each precedent line
s = "|" + new string(' ', n) + "\\\n" + s;
// and returns the resulting ASCII art
return s;
};
// test cases:
Console.WriteLine(f(4));
Console.WriteLine(f(0));
Console.WriteLine(f(1));
}
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
lambda x:'\n'.join(['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)])
```
[Try it online!](https://tio.run/nexus/python2#FcpBCsIwEAXQvaeY3Z8kbangqmAvkmSRopERnZZQIQvx6pG@9cvX0F7pvdwS1QlBMTxXUfb4woFg1SEE5LWQkiiVpI87VxOdRw/b/6rlOo8mmnYcOY7o9tnZTCfaiuhOmcU0P3bn7hL/ "Python 2 – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~24~~ ~~22~~ 21 bytes
*Saved 1 byte thanks to Martin Ender*
```
ri_{S*'|\'\N}%\_g+'-*
```
[Try it online!](https://tio.run/nexus/cjam#@1@UGV8drKVeE6Me41erGhOfrq2uq/X/vxEA "CJam – TIO Nexus")
**Explanation**
```
ri e# Take an integer from input
_ e# Duplicate it
{ e# Map the following to the range from 0 to input-1
S* e# Put that many spaces
'| e# Put a pipe
\ e# Swap the spaces and the pipe
'\ e# Put a backslash
N e# Put a newline
}% e# (end of map block)
\ e# Swap the top two stack elements (bring input to the top)
_g+ e# Add the input's signum to itself. Effectively this increments any
e# non-zero number and leaves zero as zero.
'-* e# Put that many dashes
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~51~~ 67 bytes
```
param($n)if($n){1..$n|%{"|"+" "*--$_+"\"};write-host -n ('-'*++$n)}
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp5mZBiKrDfX0VPJqVKuVapS0lRSUtHR1VeK1lWKUaq3LizJLUnUz8otLFHTzFDTUddW1tLWBWmr///9vAgA "PowerShell – TIO Nexus")
*(Byte increase to account for no trailing newline)*
Takes input `$n` and verifies it is non-zero. Then loops to construct the triangle, and finishes with a line of `-`. Implicit `Write-Output` happens at program completion.
[Answer]
# bash + printf, 68 bytes
```
for((;i<$1;))
{
a=$a-
printf "|%$[i++]s\\\\\n"
}
[ $a ] && echo $a-
```
Use "bash *program\_name* *number*" to run. Sample run:
```
bash-4.1$ bash triangle 0
bash-4.1$ bash triangle 1
|\
--
bash-4.1$ bash triangle 2
|\
| \
---
bash-4.1$ bash triangle 3
|\
| \
| \
----
```
[Answer]
# SmileBASIC, 51 bytes
```
INPUT N
FOR I=0TO N-1?"|";" "*I;"\
NEXT?"-"*(N+!!N)
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 39 bytes
```
.*
$*
*\`(?<=(.*)).
|$.1$* \¶
1
-
-$
--
```
[**Try it online**](https://tio.run/nexus/retina#@6@nxaWixaUVk6Bhb2OroaelqanHVaOiZ6iipRBzaBuXIZcul64Kl67u///GAA)
Convert decimal input to unary. Replace each `1` with `|<N-1 spaces>\¶`, print, and undo replace. Replace each `1` with a hyphen, and the last hyphen with 2 hyphens. Tadaa!
[Answer]
# Common Lisp, ~~89~~ 86 bytes
Creates an anonymous function that takes the n input and prints the triangle to `*standard-output*` (stdout, by default).
## Golfed
```
(lambda(n)(when(< 0 n)(dotimes(i n)(format t"|~v@t\\~%"i))(format t"~v,,,'-<~>"(1+ n))))
```
## Ungolfed
```
(lambda (n)
(when (< 0 n)
(dotimes (i n)
(format t "|~v@t\\~%" i))
(format t "~v,,,'-<~>" (1+ n))))
```
I'm sure I could make this shorter somehow.
[Answer]
## C ~~101~~ ~~93~~ 75 bytes
```
f(n){i;for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)printf("-");}
```
Ungolfed version
```
void f(int n)
{
int i;
for(i=0;i++<n;)
printf("|%*c\n",i,92);
for(;n--+1;)
printf("-");
}
```
@Steadybox Thanks for pointing out, makes a lot of sense.
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
```
f=lambda n,k=0:k<n and'|'+' '*k+'\\\n'+f(n,k+1)or'-'[:n]*-~n
```
[Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCnk21rYJVtk6eQmJeiXqOura6grpWtrR4TE5Onrp2mAZTXNtTML1LXVY@2yovV0q3L@19QlJlXopGmYaKp@R8A "Python 3 – TIO Nexus")
Two more solutions with the same byte count.
```
f=lambda n,k=0:n and'|'+' '*k+'\\\n'+f(n-1,k+1)or-~k*'-'[:k]
f=lambda n,s='|':-~n*'-'[:n]if s[n:]else s+'\\\n'+f(n,s+' ')
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 98 bytes
```
256?dse1+d[q]st1=t^124*23562+dsaP2sk[[lkd256r^32*la+dsaPd1+skle>y]srle1<r]dsyx[45Ple1-dse0!>q]dsqx
```
[Try it online!](https://tio.run/nexus/dc#HYzLCoAgEAC/pWsStFt26vEL3sVAWiFQCt0O9eGdTTrOMExGOSzEDgTpaPiC6VoB@xo7OaAgtgrZax08lTCtHdbB/ppAsA9ufgyn4GBMhvi5dS9VoaYc22qOxcU7Z/keZ7PZbXcf "dc – TIO Nexus")
### Explanation
This takes due advantage of dc's `P` command, which utilizes conversion to base `256` on most systems. Therefore, for any input `n`, the program first raises `256` to the `n + 1`th power, multiplies the result by `124` (ASCII character `|`), and then adds `256*92+10=23562` to the product (where `92` is equivalent to the character `\` and `10` is the decimal value of the new-line (`\n`)). This results in a decimal number that when converted to base `256` with `P` results in the output `|\\n` where `\n` is the literal new-line character. A duplicate of this decimal number is also stored on top of register `a`.
Then, a "macro-loop" is invoked, as long as `n > 1`, in which a counter is incremented until `n`, beginning from `2`, and, as the 3rd through `n`th base `256` digits are unset, `256` is raised to each of those increments, a result which is then multiplied by `32` (the ASCII single space character). Then the value on top of register `a` is incremented by the resulting product, thus, on each iteration, setting each one of the unset base `256` digits in the between the `|` and the `\` characters to a single space.
Finally, after all `n-1` lines have been output, another "macro-loop" is invoked in which all the `n+1` dashes are output through the feeding of `45` to `P` on each iteration.
*Note:* The `[q]st1=t` segment makes sure that nothing is output for the input `0` by checking if the incremented input is equal to one, and if it is, simply executes the macro `[q]` which exits the program.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
Nβ¿β«↓β→⁺¹β↖↖β»
```
[Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzmw7tB@LVj9omn9v0qG3So8Zdh3aCWNOACCix@/9/AwA "Charcoal – TIO Nexus")
## Breakdown
```
Nβ¿β«↓β→⁺¹β↖↖β»
Nβ assign input to variable β
¿β« » if β != 0:
↓β draw vertical line β bars long
→⁺¹β draw horizontal line β+1 dashes long
↖ move cursor up one line and left one character
↖β draw diagonal line β slashes long
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 bytes
Saved 2 bytes thanks to @ETHproductions
```
o@'|+SpX +'\Ãp-pUÄ)·
```
[Try it online!](https://tio.run/nexus/japt#@5/voF6jHVwQoaCtHnO4@dB27SBtdd2C0MMt//@bAAA "Japt – TIO Nexus")
### Explanation
```
o@'|+SpX +'\Ãp-pUÄ)·
o // Creates a range from 0 to input
@ // Iterate through the array
'|+ // "|" +
SpX + // S (" ") repeated X (index) times +
'\Ã // "\" }
p-pU // "-" repeated U (input) +1 times
Ä)· // Join with newlines
```
[Answer]
# J, 20 bytes
*-13 bytes thanks to bob*
```
*#' \|-'{~3,~2,.=@i.
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/7WU1RVianTVq@uMdeqMdPRsHTL1/mtyKekpqKfZWqkr6CjUWimkFXNxpSZn5CukKRjCGKb/AQ "J – Try It Online")
## original: 33 bytes
```
(#&'| \'@(1,1,~])"0 i.),('-'#~>:)
```
### ungolfed
```
(#&'| \' @ (1,1,~])"0 i.) , ('-'#~>:)
```
[Try it online!](https://tio.run/##y/r/P81WT0FDWU29RiFG3UHDUMdQpy5WU8lAIVNPU0dDXVdduc7OSpMrNTkjXyFNweT/fwA "J – Try It Online")
[Answer]
# Commodore BASIC (C64/128, TheC64 & Mini, VIC-20, PET, C16/+4) - 46 BASIC Bytes
```
0inputn:ifnthenfori=1ton:?"{shift+B}{left}"spc(i)"{shift+M}":next:fori=.ton:print"-";:next
```
There is a sanity check for zero, but any other positive integer will work.
Note, a C64 has 25 rows and 40 columns text (some PETs and the C128 in VDC mode has 80 columns, the VIC-20 is 22 columns by 23 rows) so the output will be skewed if you exceed the screen limit in either direction.
I've added a screenshot so that you may see the PETSCII characters that I can't make happen in this listing.
[![Commodore C64 Triangle challenge](https://i.stack.imgur.com/eqgz8.png)](https://i.stack.imgur.com/eqgz8.png)
[Answer]
## Pyke, ~~18~~ 17 bytes
```
I Fd*\|R\\s)Qh\-*
```
[Try it here!](http://pyke.catbus.co.uk/?code=I+Fd%2a%5C%7CR%5C%5Cs%29Qh%5C-%2a&input=4)
[Answer]
# Python2, 73 bytes
```
n=input()
w=0
exec'print"|"+" "*w+"\\\\"+("\\n"+"-"*-~n)*(w>n-2);w+=1;'*n
```
A full program. I also tried string interpolation for the last line, but it turned out be a couple bytes longer :/
```
exec'print"|%s\\\\%s"%(" "*w,("\\n"+"-"*-~n)*(w>n-2));w+=1;'*n
```
Another solution at 73 bytes:
```
n=j=input()
exec'print"|"+" "*(n-j)+"\\\\"+("\\n"+"-"*-~n)*(j<2);j-=1;'*n
```
# Test cases
```
0:
1:
|\
--
2:
|\
| \
---
3:
|\
| \
| \
----
6:
|\
| \
| \
| \
| \
| \
-------
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
?'\|- '2GXyYc!3Yc!)
```
[Try it online!](https://tio.run/nexus/matl#@2@vHlOjq6Bu5B5RGZmsaAzEmv//GwMA "MATL – TIO Nexus")
```
? % Implicit input. If non-zero
'\|- ' % Push this string
2 % Push 2
G % Push input
Xy % Identity matrix of that size
Yc % Prepend a column of 2's to that matrix
! % Transpose
3 % Push 3
Yc % Postpend a column of 3's to the matrix
! % Transpose
) % Index into string
% Implicit end. Implicit display
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 41 bytes
```
:~a>0|[a|?@|`+space$(b-1)+@\`][a+1|Z=Z+@-
```
Explanation
```
:~a>0| Gets a, and checks if a > 0
If it isn't the program quits without printing anything
[a| For b=1; b <= a; b++
?@|`+ Print "|"
space$ and a number of spaces
(b-1) euqal to our current 1-based line - 1
+@\` and a "\"
] NEXT
[a+1| FOR c=1; c <= a+1; c++
Z=Z+@- Add a dash to Z$
Z$ gets printed implicitly at the end of the program, if it holds anything
The last string literal, IF and second FOR loop are closed implicitly.
```
[Answer]
## R, 101 bytes
```
for(i in 1:(n=scan())){stopifnot(n>0);cat("|",rep(" ",i-1),"\\\n",sep="")};cat("-",rep("-",n),sep="")
```
This code complies with the `n=0` test-case if you only consider `STDOUT` !
Indeed, the `stopifnot(n>0)` part stops the script execution, displays nothing to `STDOUT` but writes `Error: n > 0 is not TRUE` to `SDTERR`.
**Ungolfed :**
```
for(i in 1:(n=scan()))
{
stopifnot(n>0)
cat("|", rep(" ", i-1), "\\\n", sep = "")
}
cat("-", rep("-", n), sep = "")
```
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
n=input();s='\\'
exec"print'|'+s;s=' '+s;"*n
if n:print'-'*-~n
```
[Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqioWldbKseE6POlVqRmqxUUJSZV6Jeo65dDBJWANFKWnlcmWkKeVYQOV11Ld26vP//TQA "Python 2 – TIO Nexus")
Prints line by line, each time adding another space before the backslash. If a function that doesn't print would be allowed, that would likely be shorter.
[Answer]
## JavaScript (ES6), 71 bytes
```
f=
n=>console.log(' '.repeat(n).replace(/./g,'|$`\\\n')+'-'.repeat(n+!!n))
```
```
<form onsubmit=f(+i.value);return!true><input id=i type=number><input type=submit value=Go!>
```
Outputs to the console. Save 6 bytes if printing to the SpiderMonkey JavaScript shell is acceptable. Save 13 bytes if returning the output is acceptable.
[Answer]
# Befunge-98, 68 bytes
```
&:!#@_000pv<
:kg00 ',|'<|`g00:p00+1g00,a,\'$,kg00
00:k+1g00-'<@,k+1g
```
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
Another function in Python 2, using `rjust`.
```
lambda n:('|'.join(map('\\\n'.rjust,range(n+2)))+'-'*-~n)[4:]*(n>0)
```
[Try it online!](https://tio.run/nexus/python2#DcIxDoMwDADAva/wZhsCohVTJPgIYQiiqYyKiULYqn497enC4Mrb78vqQS3hB9vtEKXdR0LnnGKbtuvMJnl9PUnrBzPX2GDVfJWn3s4V6dhxCUcCAdH/eGVie4OYRDMEEi5TZ@6mn38 "Python 2 – TIO Nexus")
[Answer]
# Perl, 63 bytes
```
$n=shift;print'|',$"x--$_,"\\\n"for 1..$n;print'-'x++$n,$/if$n
```
Ungolfed:
```
$ perl -MO=Deparse triangle.pl
$n = shift @ARGV;
print '|', $" x --$_, "\\\n" foreach (1 .. $n);
print '-' x ++$n, $/ if $n;
```
`$"` is the list separator, which defaults to " ". `$/` is the output record separator, which defaults to "\n". `$_` is the implicit loop variable.
] |
[Question]
[
### Introduction
Let's observe the following string:
```
AABBCCDDEFFGG
```
You can see that every letter has been *duplicated*, except for the letter `E`. That means that the letter `E` has been *de-duplicated*. So, the only thing we need to do here is to reverse that process, which gives us the following **un-de-duplicated** string:
```
AABBCCDDEEFFGG
```
---
Let's take a harder example:
```
AAAABBBCCCCDD
```
You can see that there is an uneven number of consecutive `B`'s, so that means that one of the `BB` was de-duplicated from the original string. We only need to un-de-duplicate this letter, which gives us:
```
AAAABBBBCCCCDD
```
### The challenge
Given a non-empty **de-duplicated** string, consisting of *only alphabetic characters* (either only uppercase or only lowercase), return the **un-de-duplicated** string. You can assume that there will always be at least one de-duplicated character in the string.
### Test cases
```
AAABBBCCCCDDDD --> AAAABBBBCCCCDDDD
HEY --> HHEEYY
AAAAAAA --> AAAAAAAA
N --> NN
OOQQO --> OOQQOO
ABBB --> AABBBB
ABBA --> AABBAA
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission in bytes wins!
[Answer]
# [MATL](http://github.com/lmendo/MATL), 7 bytes
```
Y'to+Y"
```
[Try it online!](https://tio.run/nexus/matl#@x@pXpKvHan0/7@6o5OTozoA) Or [verify all test cases](https://tio.run/nexus/matl#S/gfqV6Srx2p9N8l5L@6o6Ojk5OTMxC4AIE6l7qHaySQdIQAIMsPiP39AwP9QaJApRDKUR0A).
Let's take `'ABBA'` as example input.
```
Y' % Implicit input. Run-length decoding
% STACK: 'ABA', [1 2 1]
t % Duplicate top of the stack
% STACK: 'ABA', [1 2 1], [1 2 1]
o % Modulo 2
% STACK: 'ABA', [1 2 1], [1 0 1]
+ % Add, element-wise
% STACK: 'ABA', [2 2 2]
Y" % Run-length encoding. Implicit display
% STACK: 'AABBAA'
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 11 bytes
```
(.)\1?
$1$1
```
[**Try it online**](https://tio.run/nexus/retina#@6@hpxljaM@lYqhi@P@/o6Ojk5OTMxC4AAGXh2sklyMEcPlx@fsHBvpzgRSACEcA) - *contains all test cases*
[Answer]
## Haskell, 36 bytes
```
u(a:b:c)=a:a:u([b|a/=b]++c)
u x=x++x
```
Usage example: `u "OOQQO"` -> `"OOQQOO"`.
If the string has at least 2 elements, take two copies of the first and append a recursive call with
* the second element an the rest if the first two elements differ or
* just the rest
If there are less than two elements (one or zero), take two copies of the list.
[Answer]
## Perl, 16 bytes
15 bytes of code + `-p` flag.
```
s/(.)\1?/$1$1/g
```
To run it:
```
perl -pe 's/(.)\1?/$1$1/g' <<< 'HEY'
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 17 bytes
```
@b:{~b#=.l#e,|}ac
```
[Try it online!](http://brachylog.tryitonline.net/#code=QGI6e35iIz0ubCNlLHx9YWM&input=IkFCQkIi&args=Wg)
### Explanation
```
Example input: "ABBB"
@b Blocks: Split into ["A", "BBB"]
:{ }a Apply the predicate below to each element of the list: ["AA", "BBBB"]
c Concatenate: "AABBBB"
~b#=. Output is the input with an additional element at the beginning, and
all elements of the output are the same (e.g. append a leading "B")
.l#e, The length of the Output is an even number
| Or: Input = Output (i.e. do nothing)
```
[Answer]
# Ruby, 21 bytes
20 bytes plus the `-p` flag.
```
gsub(/(.)\1?/){$1*2}
```
[Answer]
## JavaScript (ES6), ~~37~~ 30 bytes
*Saved 7 bytes by using the much more efficient '$1$1' like [[other]](https://codegolf.stackexchange.com/a/103269/58563) [[answers]](https://codegolf.stackexchange.com/a/103271/58563) did*
```
s=>s.replace(/(.)\1?/g,'$1$1')
```
### Test cases
```
let f =
s=>s.replace(/(.)\1?/g,'$1$1')
console.log(f("AAABBBCCCCDDDD")); // --> AAAABBBBCCCCDDDD
console.log(f("HEY")); // --> HHEEYY
console.log(f("AAAAAAA")); // --> AAAAAAAA
console.log(f("N")); // --> NN
console.log(f("OOQQO")); // --> OOQQOO
console.log(f("ABBB")); // --> AABBBB
console.log(f("ABBA")); // --> AABBAA
```
[Answer]
# Mathematica, 41 bytes
```
s=StringReplace;s[s[#,a_~~a_->a],b_->b~~b]&
```
Unnamed function that inputs a string and outputs a string. Completely deduplicate then completely undeduplicate. Not real short, but I couldn't do better for now.
[Answer]
# [Befunge 98](http://quadium.net/funge/spec98.html), 24 bytes
```
#@~#;:::#@,~-:!j;$,;-\,;
```
[Try it Online!](https://tio.run/nexus/befunge-98#@6/sUKdsbWVlpeygU6drpZhlraJjrRujY/3/v6Ojo4KTk4KzgouLi4IrEAAA)
`$` can be easily replaced with `-`, and the 2nd `@` with `;`.
I think this can be golfed further due to the `-` at the beginning of both `-,` (or `$,` above) and `-\,`.
**How?**
```
Stack notation: bottom [A, B, C, D] top
#@~ Pushes the first character onto the stack (C henceforth) and ends if EOF
#; No-op to be used later
::: Now stack is [C, C, C, C]
#@,~ Prints C, and if EOF is next (odd consecutive Cs), prints again and ends
Lets call the next character D
- Now stack is [C, C, C-D]
:!j; If C == D, go to "$," Else, go to "-\,"
===(C == D)===
$, C == D (i.e. a pair of Cs) so we discard top and print C (Stack is now [C])
;-\,; Skipped, IP wraps, and loop starts again
===(C != D)===
- Stack is [C, C-(C-D)] By expanding: [C, C - C + D] or just [C, D]
\, Prints C (Stack is now [D])
;#@~#; This is skipped, because we already read the first character of a set of Ds,
and this algorithm works by checking the odd character in a set of
consecutive similar characters. We already read D, so we don't
need to read another character.
```
[Answer]
# Java 7, 58 bytes
```
String c(String s){return s.replaceAll("(.)\\1?","$1$1");}
```
**Ungolfed:**
```
String c(String s){
return s.replaceAll("(.)\\1?", "$1$1");
}
```
**Test code:**
[Try it here.](https://ideone.com/H1m9ph)
```
class M{
static String c(String s){return s.replaceAll("(.)\\1?","$1$1");}
public static void main(String[] a){
System.out.println(c("AABBCCDDEFFGG"));
System.out.println(c("AAAABBBCCCCDD"));
System.out.println(c("AAABBBCCCCDDDD"));
System.out.println(c("HEY"));
System.out.println(c("AAAAAAA"));
System.out.println(c("N"));
System.out.println(c("OOQQO"));
System.out.println(c("ABBB"));
System.out.println(c("ABBA"));
}
}
```
**Output:**
```
AABBCCDDEEFFGG
AAAABBBBCCCCDD
AAAABBBBCCCCDDDD
HHEEYY
AAAAAAAA
NN
OOQQOO
AABBBB
AABBAA
```
[Answer]
# PHP, 65 bytes, no regex
```
while(""<$c=($s=$argv[1])[$i])if($c!=$s[++$i]||!$k=!$k)echo$c.$c;
```
takes input from command line argument. Run with `-r`.
**regex?**
In PHP, the regex used by most answers duplicates every character. would be 44 bytes:
```
<?=preg_replace("#(.)\1?#","$1$1",$argv[1]);
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) 69 Bytes
Includes +3 for `-c`
```
{((({}<>))<>[({})]<(())>){((<{}{}>))}{}{(<{}{}>)}{}}<>{({}<>)<>}<>
```
[Try it Online!](http://brain-flak.tryitonline.net/#code=eygoKHt9PD4pKTw-Wyh7fSldPCgoKSk-KXsoKDx7fXt9PikpfXt9eyg8e317fT4pfXt9fTw-eyh7fTw-KTw-fTw-&input=QUJCQg&args=LWM)
**Explanation:**
```
Part 1:
{((({}<>))<>[({})]<(())>){((<{}{}>))}{}{(<{}{}>)}{}}<>
{ } # loop through all letters
( {} [ {} ]<(())>){((<{}{}>))}{} # equals from the wiki
# but first:
(( <>))<> # push the top letter on the other
# stack twice
( ) # push the second letter back on
{ } # if they were equal:
(< >) # push a 0 to exit this loop
{}{} # after popping the 1 from the
# comparison and the next letter
# (the duplicate)
{} # pop the extra 0
<> # switch stacks
Part 2 (at this point, everything is duplicated in reverse order):
{({}<>)<>}<>
{ } # for every letter:
({}<>) # move the top letter to the other stack
<> # and switch back
<> # Finally switch stacks and implicitly print
```
[Answer]
## brainfuck, 22 bytes
```
,
[
[>->+<<-]
>[>..<<]
>,
]
```
[Try it online.](http://brainfuck.tryitonline.net/#code=LFtbPi0-Kzw8LV0-Wz4uLjw8XT4sXQ&input=QUFBQkJCQ0NDQ0REREQ)
Prints the current character twice, unless it's equal to a character that was just printed twice.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Œgs€2ṁ€€2
```
[Try it online!](https://tio.run/nexus/jelly#@390Unrxo6Y1Rg93NgIpEOv/w91bDrcDWZH//zs6Ojo5OTkDgQsQcHm4RnI5QgCXH5e/f2CgPxdIAYhwBAA "Jelly – TIO Nexus")
[Answer]
# [V](https://github.com/DJMcMayhem/V) 10 bytes
```
ͨ.©±½/±±
```
[TryItOnline](http://v.tryitonline.net/#code=w43CqC7CqcKxwr0vwrHCsQo&input=QUFBQkJCQ0NDQ0REREQKSEVZCkFBQUFBQUEKTgpPT1FRTwpBQkJCCkFCQkE)
Just a find and replace regex like all of the rest in the thread. The only difference is that I can replace anything that would require a `\` in front of it with the character with the same ascii value, but the high bit set. (So `(`, 00101000 becomes `¨`, 10101000)
[Answer]
# [Perl 6](https://perl6.org), 17 bytes
```
s:g/(.)$0?/$0$0/
```
with -p command-line switch
## Example:
```
$ perl6 -pe 's:g/(.)$0?/$0$0/' <<< 'AAABBBCCCCDDDD
> HEY
> AAAAAAA
> N
> OOQQO
> ABBB
> ABBA'
AAAABBBBCCCCDDDD
HHEEYY
AAAAAAAA
NN
OOQQOO
AABBBB
AABBAA
```
[Answer]
## Racket 261 bytes
```
(let((l(string->list s))(r reverse)(c cons)(e even?)(t rest)(i first))(let p((l(t l))(ol(c(i l)'())))
(cond[(empty? l)(list->string(if(e(length ol))(r ol)(r(c(i ol)ol))))][(or(equal?(i ol)(i l))(e(length ol)))
(p(t l)(c(i l)ol))][(p(t l)(c(i l)(c(i ol)ol)))])))
```
Ungolfed:
```
(define (f s)
(let ((l (string->list s)))
(let loop ((l (rest l))
(ol (cons (first l) '())))
(cond
[(empty? l)
(list->string(if (even? (length ol))
(reverse ol)
(reverse (cons (first ol) ol))))]
[(or (equal? (first ol) (first l))
(even? (length ol)))
(loop (rest l) (cons (first l) ol))]
[else
(loop (rest l) (cons (first l) (cons (first ol) ol)))] ))))
```
Testing:
```
(f "ABBBCDDEFFGGG")
```
Output:
```
"AABBBBCCDDEEFFGGGG"
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 10 bytes
```
.¡vy¬ygÉ×J
```
[Try it online!](http://05ab1e.tryitonline.net/#code=LsKhdnnCrHlnw4nDl0o&input=YWJiYmNj)
**Explanation**
```
.¡ # split string into groups of the same char
v # for each group
y # push the group
¬ # push the char the group consists of
yg # push the length of the group
É # check if the length of the group is odd
× # repeat the char is-odd times (0 or 1)
J # join to string
```
[Answer]
# Python3, ~~102~~ 94 bytes
```
from collections import*
lambda s:"".join(c*(s.count(c)+1&-2)for c in OrderedDict.fromkeys(s))
```
Thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for saving 8 bytes! -> bithack.
[Answer]
## R, 81 bytes
```
r=rle(el(strsplit(scan(,""),"")));cat(do.call("rep",list(r$v,r$l+r$l%%2)),sep="")
```
Reads a string from stdin, splin into vector of characters and perform run-length encoding (rle). Subsequently repeat the each values from the rle, the sum of the lengths and the lengths mod `2`.
If we can read input separated by space (implicitly as a vector/array of characters) then we can skip the splitting part and the program reduces to 64 bytes:
```
r=rle(scan(,""));cat(do.call("rep",list(r$v,r$l+r$l%%2)),sep="")
```
[Answer]
# ><> (Fish) 39 bytes
```
0v ;oo:~/:@@:@=?!voo
>i:1+?!\|o !: !<
```
Pretty sure this can be golfed a lot using a different technique.
It takes an input and compares against the current stack item, if it's different it'll print the first stack item twice, if the same it prints them both.
The stack when empty gets supplied with a 0 which prints nothing so can be appended on whenever.
[Answer]
# Pyth, 15 bytes
```
Vrz8p*+hN%hN2eN
```
[Verify all test cases here.](http://pyth.herokuapp.com/?code=Vrz8p*%2BhN%25hN2eN&input=Vrz8pr%2B%2BhN%25hN2eN9&test_suite=1&test_suite_input=AAABBBCCCCDDDD%0AHEY%0AAAAAAAA%0AN%0AOOQQO%0AABBB%0AABBA&debug=0)
Thanks to [Luis Mendo](https://codegolf.stackexchange.com/a/103275/41863) for the methodology.
### Explanation
```
Vrz8p*+hN%hN2eN z autoinitializes to the input
rz8 run-length encode the input, returned as list of tuples (A -> [[1,"A"]])
V for every element N in this list
+hN add the head element of N (the number in the tuple)
%hN2 to the head element of N mod 2
* eN repeat the tail element of N that many times (the letter in the tuple)
p print repeated character without trailing newline
```
As is often the case, I feel like this could be shorter. I think there should be a better way to extract elements from the list than what I am using here.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 28 bytes
```
$args-replace'(.)\1?','$1$1'
```
[Try it online!](https://tio.run/nexus/powershell#@6@SWJRerFuUWpCTmJyqrqGnGWNor66jrmKoYqj@//9/R0dHJycnZyBwAYL/Hq6RICEQ@O/3398/MND/P0gBiHAEAA "PowerShell – TIO Nexus") (includes all test cases)
Port of the [Retina answer](https://codegolf.stackexchange.com/a/103273/42963). The only points of note are we've got `$args` instead of the usual `$args[0]` (since the `-replace` will iterate over each item in the input array, we can golf off the index), and the `'$1$1'` needs to be single quotes so they're replaced with the regex variables rather than being treated as PowerShell variables (which would happen if they were double-quote).
[Answer]
# C, 67 bytes
```
i;f(char*s,char*d){i=*s++;*d++=i;*d++=i;*s?f(i-*s?s:++s,d):(*d=0);}
```
Call with:
```
int main()
{
char *in="AAABBBCCCCDDDD";
char out[128];
f(in,out);
puts(out);
}
```
] |
[Question]
[
This is a simple one: print an ASCII [Gantt chart](https://en.wikipedia.org/wiki/Gantt_chart).
Given tasks' ranges (start-time - end-time Tuples), print a Gantt timeline in the form of `-` characters for each task duration - each task in a new line.
### Example
Say my tasks ranges are `28->35, 34->40, 39->44`, the Gantt will look like this:
```
-------
------
-----
```
### Specifications
* You can write a full program, a named function or an anonymous function.
* Your program/function should accept the tasks via STDIN **or as arguments**.
* Each task should be represented as a string of `start->end` where `start` and `end` are **Integers**. Tasks are separated by spaces or commas. **Alternatively**, you may get it as a Tuple of Integers, or as an Array/Collection of 2 Integers. (For example, in JavaScript you can get it as `[start,end]` - this is allowed).
* Any non-negative number of tasks (arguments) should be supported.
* To make it clear, a single argument of tasks collection is not allowed. You can either parse a single string argument, or support zero-or-more tasks arguments. Where task is a tuple or a collection of size 2.
* You can assume only valid input will be given. That means, each task has a positive duration.
* Return value does not matter, your code must print the timeline on STDOUT.
* Output: per task, `start` spaces followed by `(end-start)` dashes and a `\n`.
* Needless to say, output lines should be ordered correspondingly with the input (tasks) order.
* Trailing spaces before the `\n` are allowed, if that helps you.
### Test cases
```
Input:
(empty)
Output:
(empty)
Input:
0->7,5->6,3->6
Output:
-------
-
---
Input:
5->20,5->20,2->10,15->19
Output:
---------------
---------------
--------
----
```
### Winning
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the least code length (in bytes) wins.
* Traditionally, tie breaker is earlier post.
* "Standard loopholes are no longer funny".
## -----
## EDIT
As many of you understood that it is allowed to have a single tasks collection argument, and since there's no much different between that and the original [varargs](https://en.wikipedia.org/wiki/Variadic_function) requirement,
**it is now allowed to have a single collection argument, if you don't want to use the varargs option, or in case your language does not support varargs.**
[Answer]
# Python 2, 39 Bytes
Straightforward solution using string multiplication :)
```
for x,y in input():print' '*x+'-'*(y-x)
```
Accepts input formatted like so:
```
((5,20),(5,20),(2,10),(15,19))
```
[Check it out here.](http://ideone.com/hPZ0bv)
[Answer]
# CJam, ~~16~~ 14 bytes
```
q~{S.*~'-e]N}/
```
This expects a list of lists as input. For example:
```
[[5 20] [5 20] [2 10] [5 19]]
```
gives:
```
---------------
---------------
--------
--------------
```
**How it works**
```
q~ e# Read the input and parse it as a list of list
{ }/ e# Go over each item in the list in a for loop
S e# S is basically this string - " "
.* e# Multiply each item of the first list with the corresponding index
e# item of the second list. This basically repeats the space
e# X times where X is the first number of the tuple. The second
e# number remains untouched as the second list was only 1 char long
~ e# Unwrap the space string and second number containing list
'- e# Put character '-' on stack
e] e# Make sure that the space is filled with - to its right so as to
e# make the total length of the string equal to the second number
N e# Put a newline. After all iterations, the result is printed
e# automatically to STDOUT
```
[Try it online here](http://cjam.aditsu.net/#code=q%7E%7BS.*%7E%27-e%5DN%7D%2F&input=%5B%5B5%2020%5D%20%5B5%2020%5D%20%5B2%2010%5D%20%5B5%2019%5D%5D)
[Answer]
## Brainfuck, ~~120~~ ~~115~~ 111 bytes
At least it's shorter than Java :) The input is a list of bytes, where each pair is a single line in the gantt.
```
++++[->++++++++<]>[->+>+<<]++++++++++>>+++++++++++++>+[,[->+>+<<]>>[-<<+>>],<[->-<<<<.>>>]>[-<<<.>>>]<<<<<.>>>]
```
**Try out**
<http://copy.sh/brainfuck/>
Set end-of-input to `char` with value `\0`. Example input: `\5\20\5\20\2\10\15\19`.
*Note that setting the end-of-input value to `\0` will have the side effect that no more input will be read (and thus stopping the program) when the input contains the number zero. In BF there is no other way of knowing when the input is exhausted.*
**Explanation\***
```
++++[->++++++++<]> #Store <space> at index 1
[->+>+<<] #Move index 1 to index 2 and 3
++++++++++ #Increment index 1 to <newline>
>> #Move to index 3
+++++++++++++ #Increment index 3 to <dash>
> #Move to (empty) index 4
+ #Increment to start the main loop
[ #Main loop
, #Read first number to index 4
[->+>+<<]>>[-<<+>>] #Copy index 4 to index 5 (index 5 can now be altered)
, #Read second number (the number pair is now stored at index 5 and 6)
< #Move to first number (index 5)
[->-<<<<.>>>] #Decrement index 5 and 6 and print <space> until index 5 equals zero
> #move to second input (index 6)
[-<<<.>>>] #Decrement index 6 and print <dash> until index 6 equals zero
<<<<<.>>> #Print <newline> and move to index 4 (original first number)
] #End of main loop
```
*\*(You won't be able to compile/run this due to the comments)*
[Answer]
# Pyth, ~~36~~ ~~22~~ ~~19~~ 14 bytes
This is my first Pyth program. Jakube helped golf out 5 bytes!
```
FNQ<s*V" -"NeN
```
It expects input in the form `[[5,20], [5,20], [2,10], [15,19]]`.
You can [try it online](https://pyth.herokuapp.com/?code=FNQ%3Cs*V%22+-%22NeN&input=%5B%5B5%2C20%5D%2C+%5B5%2C20%5D%2C+%5B2%2C10%5D%2C+%5B15%2C19%5D%5D&debug=0).
[Answer]
# C++14, 69 bytes
```
[]{int a,b;for(;cin>>a>>b;){cout<<setw(b)<<string(b-a,'-')+'\n';}}();
```
First time golfing, this was a good problem to start with!
[Answer]
# K, 18 bytes
```
`0:" -"@{&x,y-x}.'
```
Expects a list of pairs as input:
```
`0:" -"@{&x,y-x}.'(0 7;5 6;3 6)
-------
-
---
`0:" -"@{&x,y-x}.'(5 20;5 20;2 10; 15 19)
---------------
---------------
--------
----
`0:" -"@{&x,y-x}.'()
```
I unpack each (`'`) tuple using dot-apply (`.`) so that inside the lambda I have access to the start and end value as `x` and `y`, respectively. Then I reassemble these into a (start,length) tuple (`x,y-x`) and apply "where" (`&`). This gives me output like so:
```
{&x,y-x}.'(0 7;5 6;3 6)
(1 1 1 1 1 1 1
0 0 0 0 0 1
0 0 0 1 1 1)
```
Then I simply have to index into a 2-character array using this ragged matrix (`" -"@`) and send it all to stdout (`0:`).
[Answer]
# JavaScript (*ES6*), 63
*Edit* 3 byte saved thx @apsillers
63 bytes not counting the assignment to F as an anonymous function is allowed.
~~A function with a variable number of parameters, as requested.~~
A function with a list of tasks as a single parameter.
Test running the snippet below (being EcmaScript 6, Firefox only)
```
F=l=>l.map(t=>console.log(' '.repeat(l=t[0])+'-'.repeat(t[1]-l)))
// TEST
// for this test, redefine console.log to have output inside the snippet
console.log = (...x) => O.innerHTML += x + '\n';
console.log('* Empty'); F([]);
console.log('\n* [0,7],[5,6],[3,6]'); F([[0,7],[5,6],[3,6]])
console.log('\n* [5,20],[5,20],[2,10],[15,19]');F([[5,20],[5,20],[2,10],[15,19]]);
```
```
<pre id=O></pre>
```
[Answer]
# Scala, ~~67~~ ~~63~~ 59 bytes
```
(r:Seq[(Int,Int)])⇒for((s,e)←r)(println(" "*s+"-"*(e-s)))
```
Usage:
`res0()` or `res0(Seq(28->35, 34->40, 39->44))` etc.
Thanks gilad for shaving 4 bytes using a for expression!
[Answer]
# Ruby: 35 characters
```
->*t{t.map{|s,e|puts' '*s+?-*(e-s)}
```
Sample run:
```
irb(main):001:0> ->*t{t.map{|s,e|puts' '*s+?-*(e-s)}}.call [0,7], [5,6], [3,6]
-------
-
---
```
Updated to accept multiple two-element arrays, one for each task to display. (I think that is what the updated requirement expects.)
[Answer]
**Javascript(ES6), 61/66 chars**
My answer is almost similar to the one posted by @edc65 , but with some improvements.
As tasks in single array are not allowed(so function would be called like this: `a([3,4], [7,15], [0,14], [10, 15])`), correct one would be this(**66 chars** without name assignment):
```
a=(...x)=>x.map(([c,d])=>console.log(' '.repeat(c)+'-'.repeat(d-c)))
```
And if one array argument is allowed(so fn call like this: `a([[3,4], [7,15], [0,14], [10, 15]])`), then it would be(**61 char** without assignment):
```
a=x=>x.map(([c,d])=>console.log(' '.repeat(c)+'-'.repeat(d-c)))
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 12 bytes
```
↑('-'\⍨≤∘⍳)/
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEdtEzXUddVjHvWueNS55FHHjEe9mzX1wXITNYwsFIxNNTWMTRRMDICUpYKJiSaXFleagoGC0aPeLQYgNkidgYK5poapghlQDZCAiZoqGBloQkkjBUMgaWiqYGipCQA "APL (Dyalog Classic) – Try It Online")
APL has no varargs, so the arg here is a single Nx2 matrix.
[Answer]
# SWI-Prolog, 55 bytes
```
a([[A,B]|C]):-tab(A),writef("%r",[-,B-A]),nl,C=[];a(C).
```
Example: `a([[5,20],[5,20],[2,10],[15,19]]).` outputs
```
---------------
---------------
--------
----
```
[Answer]
# Haskell, 76 bytes
```
(#)=replicate
f i=putStr$g=<<(read$'[':i++"]")
g(s,e)=s#' '++(e-s)#'-'++"\n"
```
Input format is a string of comma separated tuples, e.g. `"(1,2),(3,4)"`.
Usage examples:
```
*Main> f "(1,2),(3,4)"
-
-
*Main> f "(0,7),(5,6),(3,6)"
-------
-
---
```
How it works: for input parsing I enclose the input string in `[` and `]` and use Haskell's native `read` function for lists of integer tuples. The rest is easy: for each tuple `(s,e)` take `s` spaces followed by `e-s` dashes followed by a newline and concatenate all into a single string. Print.
# Haskell, 59 bytes
with relaxed input format:
```
(#)=replicate
f=putStr.(g=<<)
g(s,e)=s#' '++(e-s)#'-'++"\n"
```
Now it takes a list of tuples, e.g `f [(0,7),(5,6),(3,6)]`.
Works as described above, but without input parsing.
[Answer]
# Julia, 44 bytes
```
x->for t=x a,b=t;println(" "^a*"-"^(b-a))end
```
This creates an anonymous function that accepts an array of tuples as input and prints to STDOUT.
Ungolfed + explanation:
```
function f(x)
# Loop over the tasks (tuples) in x
for t in x
# Assign a and b to the two elements of t
a,b = t
# Print a spaces followed by b-a dashes on a line
println(" "^a * "-"^(b-a))
end
end
```
Examples:
```
julia> f([(5,20), (5,20), (2,10), (15,19)])
---------------
---------------
--------
----
julia> f([(0,7), (5,6), (3,6)])
-------
-
---
julia> f([])
```
[Answer]
## JavaScript (ES6), ~~106~~ ~~85~~ ~~80~~ 68 bytes
As per the updated requirements, a list of tasks is now acceptable
```
a=>a.reduce((p,v)=>p+=' '.repeat(z=v[0])+'-'.repeat(v[1]-z)+"\n",'')
```
Takes zero or more arguments: **80 bytes**
```
(...a)=>{s='';a.map(v=>s+=' '[r='repeat'](z=v[0])+'-'[r](v[1]-z)+"\n");return s}
```
---
Original attempt, 106 bytes:
```
(...a)=>{for(i=-1,s='',r='repeat';a.length>++i;){s+=' '[r](a[i][0])+'-'[r](a[i][1]-a[i][0])+"\n"}return s}
```
[Answer]
## C: 108 bytes
```
void g(int*l){for(int c=0;*l>=0;c=!c,l++){if(!c)l[1]-=*l;while(l[0]-->0)putchar(c?45:32);c?putchar(10):0;}}
```
Ungolfed:
```
void gantt(int*l) {
for (int c = 0; *l >= 0; c = !c, l++) {
if (!c) l[1] -= *l;
while (l[0]-- > 0) putchar(c? 45 : 32);
c? putchar(10) : 0;
}
}
```
Takes as a parameter a list of integers terminated by `-1`. For example:
```
int list[] = {
28, 35,
34, 40,
39, 44,
-1
};
gantt(list);
```
It uses `c` to toggle between writing spaces and dashes.
[Answer]
# Perl: ~~42~~ 41 characters
Just to have at least one solution with string parsing too.
```
s!(\d+)->(\d+),?!$"x$1."-"x($2-$1).$/!ge
```
Sample run:
```
bash-4.3$ perl -pe 's!(\d+)->(\d+),?!$"x$1."-"x($2-$1).$/!ge' <<< '0->7,5->6,3->6'
-------
-
---
```
[Answer]
# Java 8, ~~280~~ ~~275~~ ~~246~~ ~~204~~ ~~195~~ ~~185~~ 180 bytes
```
void g(String t){for(String s:t.split(",")){String[]a=s.split("->");s="";Integer i;for(i=0;i<i.valueOf(a[0]);i++)s+=" ";for(;i<i.valueOf(a[1]);i++)s+="-";System.out.println(s);};};
```
A method that takes a comma-seperated input string and prints the resulting ascii Gantt Chart to stdout.
Thanks to durron597 and masterX244 for helping me save 10 bytes
[Answer]
# Java, 187 181 197 183 101 bytes
```
void g(int[][]g){for(int[]i:g)for(int j=0;j<i[1];System.out.print(j++<i[0]?" ":j==i[1]?"-\n":"-"));}
```
Ungolfed (sort of):
```
void g(int[][] g){
for(int[] i : g)
for(int j = 0; j < i[1]; System.out.print(j++ < i[0] ? " " : j == i[1] ? "-\n" : "-"));
}
```
Accepts input as 2d array of `int`s. Thanks to [masterX244](https://codegolf.stackexchange.com/users/10801/masterx244) for pointing out that this is allowed by the rules.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 9 bytes
```
ạ\⁾ -xµ€Y
```
[Try it online!](https://tio.run/##y0rNyan8///hroUxjxr3KehWHNr6qGlN5P///6OjTXUUjAxidRQQDCMdBUMwwxAoZGgZGwsA "Jelly – Try It Online")
Takes input as `[[5, 20], [5, 20], [2, 10], [15, 19]]`.
-4 bytes thanks to Erik
[Answer]
# JavaScript (ES8), 54 bytes
```
a=>a.map(([x,y])=>"-".repeat(y-x).padStart(y)).join`
`
```
[Try it online](https://tio.run/##NcexCoMwEADQvZ/hdAeXoxEcOsSf6BgCHhqLYpMQg@jXp@3Q6fFWOWQf85KKCnHydTZVTC/8lgRgT7ocmr5RDWefvBS41ImcZHoWyd8h8hqXMNyGOsawx83zFl8wg7UdtXdHf1rSP3RH@uEcYv0A)
[Answer]
# PowerShell 3.0, ~~48~~36 Bytes
```
$args|%{" "*$_[0]+"-"*($_[1]-$_[0])}
```
Thanks to Mazzy for saving 12 with a better way to pass in the list
Old code and explanation:
```
&{param($b="")$b|%{" "*$_[0]+"-"*($_[1]-$_[0])}}
```
Takes arguments as a list of tuples, e.g. (5,20),(5,20),(2,10),(15,19). Had to default $b to a value to take care of the empty string because it somehow entered the foreach block when called with no input.
[Answer]
# [R](https://www.r-project.org/), ~~117 90~~ 75 bytes
```
function(y)for(i in 1:ncol(y))cat(" "<y[1,i],"-"<diff(y)[i],"
")
"<"=strrep
```
[Try it online!](https://tio.run/##NYlBCsIwEADPzSvCnnZhCybQg5L@wlvxUKILC5pIjJC@PlbB0zAzpcvc5Z1i1ZxwI8kF1Wqy7pRivu@F4loRLIRtcawXhhHCVUX2tXzVABkIML9qKbdnbzaMtuJjrUUbRpzYH9gMw5@e3Y9uYnckZs9nIiPYqH8A "R – Try It Online")
Giuseppe golfed at least 29 bytes off my original answer!
The idea is straightforward: print as many `" "` as necessary followed by as many `"-"` as required. Input is a `2*L` matrix with L the number of pairs. The vectorized function `diff` is used to get the number of "-".
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 13 bytes
```
{" -"@&-':x}'
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpJQVfJQU1X3aqiVv1/iVW1SnRlXZFVmkKFdUJ@trVGQlpiZo51hXWldZFmbC1XSbSBso6igbWGZiyQrWGgYG5tqmBmbaxgpsmloKChpAsBSkCOgpICCCDYIHGINlMFIwNrMGGkYGhgbWiqYGgJ0Q/RggqQDcMug0UlAuhC7P0PAA "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`{` `}'` apply to each - in this case to each pair of numbers from the input
`-':` subtract each prior - transform `(a;b)` into `(a;b-a)`
`&` "where" - transform `(a;b-a)` into a list of `a` zeroes followed by `b-a` ones
`" -"@` use as indices in `" -"`
[Answer]
# VBA (Excel), ~~99~~ 90 bytes
Using Immediate Window and `[A1]` as input eg.`0-1,2-5`
Thanks to @TaylorSott for cutting some bytes.
```
b=Split([A1]):For x=0To Ubound(b):c=Split(b(x),"-"):?Spc(c(0)-0)String(c(1)-c(0),"-"):Next
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 9 bytes
```
ƛ÷ε\-*nt↳
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C6%9B%C3%B7%CE%B5%5C-*nt%E2%86%B3&inputs=%5B%20%5B0%2C7%5D%20%2C%20%5B5%2C6%5D%2C%20%5B3%2C6%5D%20%5D&header=&footer=) Expects a list of lists.
```
ƛ # Map each pair to...
÷ε # Their difference
\-* # -s
nt↳ # Padded to the length of the second.
```
[Answer]
## CoffeeScript, ~~104~~ 82, 65 bytes
List of tasks (ES6): **65 bytes**
```
(a)->a.map (v)->console.log ' '.repeat(v[0])+'-'.repeat v[1]-v[0]
```
List of tasks (ES5 variant): **82 bytes**
```
(a)->a.map (v)->j=-1;s='';s+=(if j<v[0]then' 'else'-') while++j<v[1];console.log s
```
Zero or more arguments: **104 bytes**
```
()->[].slice.call(arguments).map((v)->j=-1;s='';s+=(if j<v[0]then' 'else'-')while++j<v[1];console.log s)
```
Unminified:
```
() -> [].slice.call(arguments).map( # convert to array-like arguments to array and loop
(v) ->
j = -1 # counter
s = '' # initialize string
s += (if j < v[0] then ' ' else '-') while ++j < v[1]
console.log s # print to STDOUT
)
```
[Answer]
## PHP, ~~94~~ 91 bytes
Takes a list of tasks (e.g. `[[5,20],[5,20],[2,10],[15,19]]`). Thanks @IsmaelMiguel for the reminder of variable function names.
```
function x($a){$r=str_repeat;foreach($a as$v){echo$r(' ',$v[0]).$r('-',$v[1]-$v[0])."\n";}}
```
---
Original attempt: 94 bytes
```
function x($a){foreach($a as$v){echo str_repeat(' ',$v[0]).str_repeat('-',$v[1]-$v[0])."\n";}}
```
[Answer]
# PHP, 89 characters (function body)
```
function gantt($x){array_walk($x,function($a){echo str_pad(str_repeat('-',$a[1]-$a[0]),$a[1],' ',0)."\n";});}
```
I was going to go for reading strings, but as a lot of the entries were taking arrays of integer pairs, I figured I would follow suit for the sake of brevity.
For each tuple `$a` in array `$x` I echo a string of dashes repeated `$a[1] - $a[0]` times, padded up to the larger number `$a[1]` with spaces. Then the obligatory newline.
[Answer]
# [Gema](http://gema.sourceforge.net/): 47 characters
```
<D>-\><D><y>=@left{$1;}@repeat{@sub{$2;$1};-}\n
```
Sample run:
```
bash-4.3$ gema '<D>-\><D><y>=@left{$1;}@repeat{@sub{$2;$1};-}\n' <<< '0->7,5->6,3->6'
-------
-
---
```
] |
[Question]
[
The other day, our team went to an escape room. One of the puzzles involved a board of six mechanical switches where you had to find the correct combination of on and off in order to unlock a box, somewhat like this:
```
-v-v-v-
-v-v-v-
```
Being developers, we decided it would be more efficient to try every single one of 2^6=64 combinations than actually solve the puzzle. So we assigned some poor guy to do some binary counting:
```
-v-v-v-
-v-v-v-
-v-v-v-
-v-v-^-
-v-v-v-
-v-^-v-
-v-v-v-
-v-^-^-
```
and so on.
**The challenge**
Write a program that, given the switches all in off position as a string formatted as above, generates all combinations of on and off in any order.
You can write either a full program or a function. Thus, your program can either take in input through stdin, a file, or as a single string argument, and either return or print the output. If returned, the output may be in a list/array/etc. rather than a single string. If the output is a single string, the boards should be separated by newlines (trailing newlines are allowed.)
The input strings will match the regex `r'((-v)+-)(\n(-v)+-)*'` and represent one board with all switches off. This means no zero case, and switches are left-aligned. Each row might not have the same number of switches.
Each output board should be of the exact same format as the input, except that the v's may be replaced by ^'s as required. The output boards can be separated by any number of newlines.
Since runtime is naturally O(2^n) in the number of switches, your code will not be tested on any more than 10 switches in any arrangement.
This is code-golf, so shortest code in number of bytes wins.
**Sample inputs and outputs**
Input:
```
-v-
```
Possible output:
```
-v-
-^-
```
Input:
```
-v-
-v-
```
Possible output:
```
-^-
-^-
-^-
-v-
-v-
-^-
-v-
-v-
```
Since it's extremely tedious to check your answer for bigger numbers of switches, [here's](https://pastebin.com/6P46XLn9) a Python script as a sanity check tool. (I've included a currently commented-out snippet to generate expected output from a given input file in case you want more test cases.) It's quite a bit less flexible in terms of input and output than the spec, unfortunately; put the input string in a file named 'input' and the newline-separated output (sorry, no list formatting) in a file named 'output' in the same directory and run `python3 sanitycheck.py`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~25~~ ~~24~~ ~~23~~ 17 bytes
```
mapM$min"^v".pure
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P802N7HAVyU3M08prkxJr6C0KPV/bmJmnoKtQkFpSXBJkU@egp5CaV5OZl5qsYKKQpqCkm6ZbkwekFD6DwA)
-1 byte thanks to @H.PWiz
-1 byte thanks to @nimi
Returns a list of strings. The TIO has 2 extra bytes for the function declaration - I've seen other people leave it off when they write the function pointfree so I'm doing the same unless told otherwise.
# Previous Answer (25 bytes)
```
g 'v'="v^"
g x=[x]
mapM g
```
The explanations are all for the previous answer, which works pretty much the same way, except I inlined the definition of `g`. The way `g` works now is by using lexical comparison to substitute `^v` for `v` and keep everything else the same.
Interestingly, this works for arbitrary switchboards:
```
>>> mapM g "-----^-----"
["-----v-----", "-----^-----"]
```
# Explanation (Short)
```
g 'v'="v^" -- for 'v', choose between 'v' or '^'
g x=[x] -- for any other character, choose just that character
mapM g -- find all ways to choose characters using g on the given input
```
# Explanation (Long)
`mapM` is a pretty scary function for those not familiar with Haskell. But it's not hard to understand in this context. By making it act on `String`s (which in Haskell are lists of characters), I've specialized it to its definition for lists. So in this context, its type signature is
```
mapM :: (a -> [b]) -> [a] -> [[b]]
-- ^^^^^^^^^^ arg 1: a function from any a to a list of b
-- ^^^ arg 2: a list of a
-- ^^^^^ return: a list of list of b
```
It is actually even more specialized in my usage of it - `a` and `b` are both `Char` - so we can see the type signature as
```
mapM :: (Char -> String) -> String -> [String]
```
Let's quickly look at what `g` does before explaining how `mapM` works.
```
g :: Char -> String
g 'v' = "v^"
g x = [x]
```
`g` uses pattern matching to convert the `Char 'v'` into the string `"v^"`; everything else gets converted to a singleton string (remember, strings are just lists of `Char`s, so we can put `x` in a singleton list). Testing on the REPL, we find this is the case
```
>>> g 'a'
"a"
>>> g 'b'
"b"
>>> g 'v'
"v^"
```
Note that `g` has the right type to be an argument of `mapM` (unsurprisingly!).
We'll explore how `mapM` works by giving it `g` and the argument
```
"-v-\n-v-"
```
as input.
`mapM` first maps `g` over the `String`, and because `g` converts `Char`s to `Strings`, this gives us a list of `Strings`
```
["-", "v^", "-", "\n", "-", "v^", "-"]
```
While this is the correct output type, `mapM` does slightly more. You can think of it as forming all `String`s that you could create from this list if you had to pick a single character from each `String` in it (in order).
So for the first element, you have no choice other than to pick the `Char '-'`. For the second element, you can choose between `'v'` and `'^'`, so on and so forth.
It's roughly equivalent to this python code:
```
result = []
for x1 in "-":
for x2 in "v^":
for x3 in "-":
...
result.append(''.join([x1, x2, x3, x4, x5, x6, x7]))
```
Except that since Haskell separates between `Char`s and `String`s, when it puts the `Char`s into a list, it doesn't need to `join` them.
So the final output is
```
["-v-\n-v-", "-v-\n-^", "-^-\n-v-", "-^-\n-^-"]
```
as desired.
[Answer]
# [Perl 6](http://perl6.org/), 32 bytes
```
{[X~] .comb».&{$_,('^'if /v/)}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjqiLlZBLzk/N@nQbj21apV4HQ31OPXMNAX9Mn3N2tr/xYmVCkoq8TF5Sgpp@UUKaRpKumVgGJMHZShp/gcA "Perl 6 – Try It Online")
* `.comb` splits the string into characters.
* `».&{...}` maps the characters according to the function between the braces.
* `$_, ('^' if /v/)` produces a list of alternates for each character. Only `v` has an alternate: `^`.
* `[X~]` reduces that list with the string-concatenation cross-product operator `X~`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
«Ƭ€”^Œp
```
[Try it online!](https://tio.run/##y0rNyan8///Q6mNrHjWtedQwN@7opIL/h9uPTnq4c8b//7plulxADAA "Jelly – Try It Online")
Output is a list of Jelly strings.
Explanation:
```
«Ƭ€”^Œp Arguments: 1
«Ƭ€”^ Dyad-nilad pair
€ Map over left argument
Ƭ Apply repeatedly until a result that has previously been seen is seen
again, return original and intermediate results
« Dyad: Minimum of arguments
”^ Nilad: Literal: '^'
Note: 'v' is the only character that is greater than '^' and can
appear in the input, so, while for every character c other than 'v'
this operation returns [c], for 'v' it returns ['v', '^']. In this way,
duplicates are never going to appear in the output.
Œp Monad: Cartesian product of elements
```
[Answer]
# [Perl 5](https://www.perl.org/), 29 bytes
```
sub{glob"\Q@_"=~s/v/{v,^}/gr}
```
[Try it online!](https://tio.run/##K0gtyjH9n1upoJKmYPu/uDSpOj0nP0kpJtAhXsm2rli/TL@6TCeuVj@9qPa/dXFipUJafhFQra6dhpJuGRDG5EEpJc3/YBYXhPyXX1CSmZ9X/F/X11TPwNAAAA "Perl 5 – Try It Online")
My first submission!
---
Normally, Perl 5 golfers submit programs instead of functions to save from having to include `sub{}` at a minimum. But they have to add `say`, `say␠`, `say for` or `say for␠` in exchange.
By going the sub approach, I could shorten
```
say for glob"\Q$_"=~s/v/{v,^}/gr # Perl 5, -0n, 32 bytes
```
to
```
sub{glob"\Q@_"=~s/v/{v,^}/gr} # Perl 5, 29 bytes
```
---
The explanation is quite simple. Perl 5 has a builtin [`glob`](http://perldoc.perl.org/functions/glob.html) operator which accepts a shell-like glob pattern which can be used to generate lists of file names (e.g. `foo*.txt`) or list of strings (e.g. `{a,b,c}`). The catch is that the newline needs to be escaped, which I've done using [`quotemeta`](http://perldoc.perl.org/functions/quotemeta.html) (as `\Q`).
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~21 17~~ 15 bytes
```
⊃⊢∘.,.∪'v'⎕r'^'
```
[Try it online!](https://tio.run/##Jc1BCsIwEAXQq8wuCm1RvI4IQ5q2gZCWSVpxXSil0KILwY0bl268g0eZi8Rg@fAXjw8fG5PmFzR1mUqDzmkZAk89Ty8eH1mS8fgWneDlTuIkQsHDleclDr6fAw@36I5kbF9pFwqRdv@IZBOtlQ72u22yqgCen7BeQUPaegdHC@gAwWiroFAqh7P2Vd36aBKJNJYKSPmW7A8 "APL (Dyalog Classic) – Try It Online")
similar to [my k solution](https://codegolf.stackexchange.com/a/188577/24908)
returns an n-dimensional array of strings (n = number of switches)
in easier to explain form: `⊃(∘.,⌿ ⊢ ∪¨ 'v'⎕r'^')`
`'v'⎕r'^'` replace `v`s with `^`s
`⊢ ∪¨`... unions with each of the original characters. it's a vector of strings of length 1 or 2
`∘.,⌿` cartesian product reduction
`⊃` disclose
to get to the fully golfed version we follow the pattern `f⌿ A g¨ B` -> `A f.g B`:
`∘.,⌿ ⊢ ∪¨ 'v'⎕r'^'` -> `⊢ ∘.,.∪ 'v'⎕r'^'`
as a side effect the parentheses are no longer needed
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), ~~27~~ 25 bytes
```
{(?,/,/:\:)/x,'"^"/"v"\x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlrDXkdfR98qxkpTv0JHXSlOSV@pTCmmovZ/goKBlVJMnpKOepqSbhkYxuSBKaX/AA "K (ngn/k) – Try It Online")
`"^"/"v"\` replace `"v"` with `"^"`
`x,'` zip with the original chars
`(?,/,/:\:)/` uniq cartesian product over
[Answer]
# [J](http://jsoftware.com/), 42 bytes
```
]`('v'I.@e.~[)`[}"1'v^'{~2#:@i.@^1#.e.&'v'
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/YxM01MvUPfUcUvXqojUTomuVDNXL4tSr64yUrRwy9RziDJX1UvXUgGr@a3KlJmfkK6QpqOuW6apzQXjqukgAJpgGssSAC6gMjDWJU1sGVQ@mNf8DAA "J – Try It Online")
## explanation
```
]`('v' I.@e.~ [)`[}"1 ('v^' {~ 2 #:@i.@^ 1 #. e.&'v')
```
Let take
```
-v-
-v-
```
as our example input.
* `('v^' {~ 2 #:@i.@^ 1 #. e.&'v')` creates all possible combos of just the switches, ignoring the input format. for our example it produces:
```
vv
v^
^v
^^
```
+ `1 #. e.&'v'` counts the numbers of `v`s in the input.
+ `2 #:@i.@^` raises 2 to that power, produces the integers from 0 to *that* number `i.`, and converts them to binary `#:`
+ `'v^' {~` changes to binary digits to `v` and `^`
* `]`('v' I.@e.~ [)`[}"1` amends the original input, producing one copy of it for each row of the result described in the previous step (ie, all possible `v`/`^` combos). In each copy the `v` of the original input are replaced with one possible sequence of `v`/`^`.
[Answer]
# Java, 202 197 189 191 bytes
Yes, it's a comparatively verbose language, but that's what I consider as classical golfing:
```
import java.util.function.Function;
public class SwitchBored
{
public static void main(String[] args)
{
Function<String, String> f = s->{byte i,j,k,m=1,u='^',d='v',a[]=(s+"\n\n").getBytes();for(i=0,s="";i<m;i++,s+=new String(a))for(j=0,k=0;k<a.length;k++){if(a[k]==d||a[k]==u){a[k]=(i&1<<j++)!=0?u:d;m<<=i>0?0:1;}}return s;};
//System.out.println(f.apply("-v-"));
System.out.println(f.apply("-v-v-v-\n-v-v-v-"));
//System.out.println(f.apply("-v-v-v-\n-v-v-"));
//System.out.println(f.apply("-v-v-v-v-v-\n-v-"));
//System.out.println(f.apply("-v-v-v-v-v-\n-v-v-v-v-v-"));
}
}
```
I thought that a "simple" way of dealing with the line breaks that are necessary to achieve to proper layout was to actually re-use the original input character array, and only fill it with `'v'`s and `'^'`s at the appropriate positions.
*Updates:*
It turned out that *not* storing the positions allows ditching the `int` and array variable declarations (at the cost of checking each position of the array whether it contains an `v` or `^` on the fly), saving 5 bytes.
Another 8 bytes saved by computing the upper limit `(1<<numberOfSwitches)` more compactly.
According to the rule mentioned in the comment, function declaration should be counted, so now it's a lambda...
[Answer]
# [J](http://jsoftware.com/), ~~41 40~~ 24 bytes
```
[:>@,@{<@(,'^'$~'v'=])"0
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63sHHQcqm0cNHTU49RV6tTL1G1jNZUM/mtypSZn5CukgdQbcOmWgSGE5tL8DwA "J – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
def f(s):i=s.find('v');return(i>=0and f(s[:i].replace('^','v')+'^'+s[i+1:])+'\n'or'')+s
```
[Try it online!](https://tio.run/##VYvBCsIwEETv@QpvmxBbrMdI/ZFaoTQJLsg2bGKhXx@3xYvMZebNTNrKa6FrrT7EU9TZOOxzG5G8hhXMjUP5MGm895eJ/L4YHI4th/Se5qDhCed9Z8XYPKDt3CjhQbAwCM41MVKRHwA06yFxRh1Y/ZfqV9Yv "Python 2 – Try It Online")
A non-regex approach.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~75 74~~ 70 bytes
-5 byte thanks to @ceilingcat
```
*b=0;f(char*s){b=b?b:s;*s?f(s+1),*s>46?*s=94,f(s+1),*s='v':0:puts(b);}
```
[Try it online!](https://tio.run/##S9ZNT07@/18rydbAOk0jOSOxSKtYszrJNsk@yarYWqvYPk2jWNtQU0er2M7EzF6r2NbSRAcuZKtepm5lYFVQWlKskaRpXfs/NzEzT0OzGmSMQnF0rK2SbhkYxuSBKSWgFcUgdQA "C (gcc) – Try It Online")
requires the memory `s` points to to be writable
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~129 117 116 110~~ 106 bytes
-10 bytes thanks to [@Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown)
```
f=lambda s:{s.replace('v','{}').format(*['v^'[c<'1']for c in bin(x+i)[::-1]])for i in range(x:=1<<len(s))}
```
[Try it online!](https://tio.run/##PclBCoMwEEDRvacI2cxM2wjSTQnxJJJCtLENaAxRxCKePTWbLv/74bt8Jn9/hJhSXw9mbF@GzXKfy2jDYDqLsMIN9gOo7Kc4mgUvDaxPaDoFFejTWMecZ63zuF0dNVKKSmvKw@URjX9b3GRdKTVYjzPRkUJ0fsEeuVgFJyr@zbMUWfnp6Qc "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 102 bytes
```
i,j,l;f(char*s){for(l=j=0;l++<1<<j;puts(""))for(i=j=0;s[i];i++)putchar(s[i]>64?l&1<<j++?118:94:s[i]);}
```
[Try it online!](https://tio.run/##HYtBCsIwEADvfUYOsus2YKCIdlP7EPVQAtENsUqjXkrfHhsvc5hhnL45l7PUoY7swd2HaZtw9s8JYhe6HUcia6wN/Pq8EyiFWJr8WzrLlYUI11ZOKOK0b/q4KQtRb8yhPTZt8chLfgwyAs6VB6W/@jKuUMjVkn8 "C (gcc) – Try It Online")
[Answer]
# [K4](https://kx.com/download), 44 bytes
**Solution:**
```
-1{@[x;&w;:;]@'"v^"@a\:'!*/a:(+/w:"v"=x)#2};
```
**Examples:**
```
q)k)-1{@[x;&w;:;]@'"v^"@a\:'!*/a:(+/w:"v"=x)#2}"-v-";
-v-
-^-
q)k)-1{@[x;&w;:;]@'"v^"@a\:'!*/a:(+/w:"v"=x)#2}"-v-\n-v-";
-v-
-v-
-v-
-^-
-^-
-v-
-^-
-^-
q)k)-1{@[x;&w;:;]@/:"v^"@a\:'!*/a:(+/w:"v"=x)#2}"-v-v-\n-v-v-v-\n-v-";
-v-v-
-v-v-v-
-v-
-v-v-
-v-v-v-
-^-
-v-v-
-v-v-^-
-v-
-v-v-
-v-v-^-
-^-
-v-v-
-v-^-v-
-v-
-v-v-
-v-^-v-
-^-
-v-v-
-v-^-^-
-v-
-v-v-
-v-^-^-
-^-
-v-v-
-^-v-v-
-v-
-v-v-
-^-v-v-
-^-
-v-v-
-^-v-^-
-v-
-v-v-
-^-v-^-
-^-
-v-v-
-^-^-v-
-v-
-v-v-
-^-^-v-
-^-
-v-v-
-^-^-^-
-v-
-v-v-
-^-^-^-
-^-
-v-^-
-v-v-v-
-v-
-v-^-
-v-v-v-
-^-
-v-^-
-v-v-^-
-v-
-v-^-
-v-v-^-
-^-
-v-^-
-v-^-v-
-v-
-v-^-
-v-^-v-
-^-
-v-^-
-v-^-^-
-v-
-v-^-
-v-^-^-
-^-
-v-^-
-^-v-v-
-v-
-v-^-
-^-v-v-
-^-
-v-^-
-^-v-^-
-v-
-v-^-
-^-v-^-
-^-
-v-^-
-^-^-v-
-v-
-v-^-
-^-^-v-
-^-
-v-^-
-^-^-^-
-v-
-v-^-
-^-^-^-
-^-
-^-v-
-v-v-v-
-v-
-^-v-
-v-v-v-
-^-
-^-v-
-v-v-^-
-v-
-^-v-
-v-v-^-
-^-
-^-v-
-v-^-v-
-v-
-^-v-
-v-^-v-
-^-
-^-v-
-v-^-^-
-v-
-^-v-
-v-^-^-
-^-
-^-v-
-^-v-v-
-v-
-^-v-
-^-v-v-
-^-
-^-v-
-^-v-^-
-v-
-^-v-
-^-v-^-
-^-
-^-v-
-^-^-v-
-v-
-^-v-
-^-^-v-
-^-
-^-v-
-^-^-^-
-v-
-^-v-
-^-^-^-
-^-
-^-^-
-v-v-v-
-v-
-^-^-
-v-v-v-
-^-
-^-^-
-v-v-^-
-v-
-^-^-
-v-v-^-
-^-
-^-^-
-v-^-v-
-v-
-^-^-
-v-^-v-
-^-
-^-^-
-v-^-^-
-v-
-^-^-
-v-^-^-
-^-
-^-^-
-^-v-v-
-v-
-^-^-
-^-v-v-
-^-
-^-^-
-^-v-^-
-v-
-^-^-
-^-v-^-
-^-
-^-^-
-^-^-v-
-v-
-^-^-
-^-^-v-
-^-
-^-^-
-^-^-^-
-v-
-^-^-
-^-^-^-
-^-
```
**Explanation:**
In-place replacement of `"^"`. Determine number of combinations of switches (e.g. 2^n), count up in binary, replace switches...
```
-1{@[x;&w;:;]@'"v^"@a\:'!*/a:(+/w:"v"=x)#2}; / the solution
-1 ; / print to STDOUT, swallow -1
{ } / lambda taking implicit x
#2 / take 2
( ) / do this together
"v"=x / does input = "v" ?
w: / save as w
+/ / sum up
a: / save as a
*/ / product
! / range 0..n
a\:' / convert each to base-2
"v^"@ / index into "v^"
@' / apply each
@[x;&w;:;] / apply assignment to x at indexes where w is true
```
[Answer]
# [R](https://www.r-project.org/), 116 bytes
```
function(x,u=utf8ToInt(x))apply(expand.grid(rep(list(c(118,94)),sum(u>45))),1,function(i)intToUtf8(`[<-`(u,u>45,i)))
```
[Try it online!](https://tio.run/##bY89C8JADIb3/opul4NUKCgotO7uOtnBo171oF7DXU7q4l@v0cEPMBnywcObN2GiYJlvMwrOc14VeZd8y27wMOrWMJyrQjX@/huNV0gmsoUR26HvDUVbCyZ7jWeMlmqlUD3HLOvq6aOJqU7cLbfDxrNc0Iaov4Edyfjj7BTcEYIl6F1kaKEsl7iaa40xXSCt5wstfYlvNafF83bYiSAc9lVxgIRPDJ2AU/b9GeQdqOIq2fhXUVqs/Se@mekB "R – Try It Online")
Function returning a vector of newline separated boards
[Answer]
# JavaScript, 88 bytes
```
s=>(g=n=>n--?g(n)+`
`+s.replace(/v/g,_=>'v^'[i=n&1,n>>=1,i]):'')(2**~-s.split`v`.length)
```
[Try it online!](https://tio.run/##XchBDsIgEEDRtT2Iw1igqStjAh6krdI0FGnI0JSGpVfHhXGhu//@MuYxTZtfd5EvZVYlKc2cIqVJiJtjhLWpTJ3kZtcwTpY1uXH8oTTkO3Re0bHlpLVquR/wCoDsfDq9RJJpDX432chgye1PLFOkFIOVITrWVYeZgcgCkH@zp1//4TOqQS7RE4OeegLE8gY "JavaScript (V8) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 29 bytes
```
T`¶v`;#
+%1`#
v$'¶$`^
%`;|$
¶
```
[Try it online!](https://tio.run/##K0otycxL/P8/JOHQtrIEa2UubVXDBGWuMhX1Q9tUEuK4VBOsa1S4Dm37/1@3DAy5oDQA "Retina 0.8.2 – Try It Online") Explanation:
```
T`¶v`;#
```
Change the newlines into `;`s and the `v`s into `#` markers.
```
+%1`#
```
Replace the `#`s one at a time from left to right.
```
v$'¶$`^
```
Change each line into two lines, one with the `#` replaced with a `v`, one with it replaced with a `^`.
```
%`;|$
¶
```
Change the `;`s back into newlines and space the results apart.
[Answer]
# [Perl 5](https://www.perl.org/) `-0`, 51 bytes
```
$_=<>;s/\s/P/g;s/v/{v,^}/g;say s/P|$/\n/gr for glob
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbGzrpYP6ZYP0A/Hcgo068u04mrBbETKxWAojUq@jF5@ulFCmn5RQrpOflJ///rlgEhF5j8l19QkpmfV/xf19dUz8DQ4L@uAQA "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~80 73~~ 68 bytes
```
f=([x,...y],g=c=>f(y).map(z=>c+z))=>x?g(x).concat(x>'a'?g`^`:[]):[y]
```
[Try it online!](https://tio.run/##HclRCoMwDIDh4zRhmgMIqQfpOgyZLRuulSnSevluyP/wPfxvOWTT72vd@5Sfc2uBwZWOiKrvIivbABXpIyucbPV2IrItY4SCpDmp7FCsETPG6TENzuPgqm//s@VlpiVHCGD64@qeLgxi@wE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/) - construct, 203 bytes
```
def f(a):
b=[0]
for l in a.split():b+=[b[-1]+l.count('v')]
return'\n'.join(''.join(f"{k:b}".zfill(b[-1])[x:y]+'-\n'for x,y in zip(b,b[1:]))for k in range(2**b[-1])).replace('0','-v').replace('1','-^')
```
[Try it online!](https://tio.run/##RY7RisIwEEXf@xUhLzNj22DXt4Bfku1C4yZubEhDrGIVv72b7AoyzFw43MuduMw/U9it67exzOJAsmJ6r7Z9xeyUmGcusEGco3czktT1XmnVdn3txWG6hBnhCpS9ycyXFOAzgDhNLiC81PLHKPWTi7t13uNfltRNLn0NbXaXjluzlJa7i6gbrTrZExU@FpqGcDT4sdn8R0kkE/1wMAhbaKDN7W/SFfIFtMbk8msWOedVe81TvTbfzIjWXw "Python 3 – Try It Online")
First try, not very small but works. There is no elegant string replacement in Python...
The First loop builts a mapping of lines to bit indices, i.e. for each line, the index of the first bit in a bit counter is stored. This is used for indexing the bit counter in the next loop.
The Second loop runs a binary counter, extracts the bits for each line and iteration and joins them. After joining everything together, it is translated back to the switch map format, using string replacement.
I guess, there is a more elegant way by reusing the input string instead of rebuilding it over and over again.
*Edit: inspired by the [Python 3.8 answer](https://codegolf.stackexchange.com/a/188683/86751), here is a much shorter replacing version*
# [Python 3](https://docs.python.org/3/) - replace, 123 bytes
```
def f(a):r=range;n=a.count('v');return'\n'.join(a.replace('v','{}').format(*('v^'[k&2**i>0]for i in r(n)))for k in r(2**n))
```
[Try it online!](https://tio.run/##LY3NCsIwEITvfYqQg5sEDaI3S30RfyDURGN1E5a0IOKzxy3KsAPz7cDkV7kl3NZ68UEE5fSOOnJ49S12zvZpxKJgAt2SLyMhHBHsPUVUzpLPD9f7@b2E9we0DYmerijD6AyHYbExJu7XJ8YiioiCFGqt5zj8IheY1EyRZ4KSUjaridX8j50ZN74 "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
Returns an array. Gets numbers from \$1\$ to \$2^v\$ (where \$v\$ is the number of "v" in the input) and flips switches based on the \$v\$ least significant bits. This allows us to save a byte over iterating from \$0\$ to \$2^v-1\$, because the \$v\$ least significant bits in \$2^v\$ are all zero.
In Ruby, `i[j]` returns the `j`th bit of `i` starting from the least significant bit, aka it is equivalent to `(i>>j)&1`.
```
->s{(1..2**s.count(?v)).map{|i|j=-1;s.gsub(/v/){'v^'[i[j+=1]]}}}
```
[Try it online!](https://tio.run/##TYttC4IwHMTf71OMEeiM/cXe1uqDqIFP1aSmuAcI52dfrRK6g@N@HDeZ@ukv3LOjmuMMYJckCprBSB2fLKXwqMbZCddzlu0VXJWp49SmdI7sOcpF3m95VpbLsnjdKa0wx5sDTF3VghrvQsekkIUkFH1W6KrmhtsBu4AOYTya9@eSByyhH4TE38M6Ef4vgjrZemYZQiHWYn8Q/AI "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
⪫EX²№θv⭆θ⎇⁼λv§v^÷ιX²№…θμv붶
```
[Try it online!](https://tio.run/##XY3BCsIwEER/JexpC@nFqyepHioIBb1ZhZAGG4ibNqbRfn1MY0@yMCyPx4zshZNWmBgbp8nj0WrCkxiwsW/lcMNZZafER84gQFFwdvZJfCxKYhflSLgZD@MkzAvNz@Js52vq1Ach3IGzmvxeB90p1Jz9FVezNKrqba57FuvMMmRyQkstJbKN8QplyNfS@sAtlsF8AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
² Literal 2
X Raised to power
№ Count of
v Literal `v`
θ In input string
E Map over implicit range
θ Input string
⭆ Map over characters and join
λ Current character
⁼ Equal to
v Literal `v`
⎇ Then
v^ Literal `v^`
§ Circularly indexed by
ι Outer index
÷ Integer divided by
² Literal 2
X Raised to power
№ Count of
v Literal `v`
θ In input string
… Truncated to length
μ Inner index
λ Else current character
⪫ ¶¶ Join with newlines
Implicitly print
```
[Answer]
# [PHP](https://php.net/), 93 bytes
```
for(;$j<1<<$x;$j+=print$s)for($x=0,$s=$argv[1];$i=strpos($s,v,$i+1);$s[$i]=$j&1<<$x++?'^':v);
```
[Try it online!](https://tio.run/##NYxBCoMwFET3nmNQQyI02yafHEQidNM2LvSTL8HbRxsoA/MGHgx/ufrAd7/3PDqs3nqP8x6aOKftgKifwUkPAyG88qfMNjokkiPzLiPEFIOkrXKQGSkS1r69aB2GZXgW5WqtU2np/uwu "PHP – Try It Online")
Standalone program, input via command line.
Loop the number of possible permutations of the input string based on the number of `v`'s. While counting up in binary, replace each binary `1` with a `^` and each binary `0` with a `v` in the input string.
] |
[Question]
[
Given a positive integer `n`, output the smallest base `b >= 2` where the representation of `n` in base `b` with no leading zeroes does not contain a `0`. You may assume that `b <= 256` for all inputs.
## Test Cases
```
1 -> 2 (1)
2 -> 3 (2)
3 -> 2 (11)
4 -> 3 (11)
5 -> 3 (12)
6 -> 4 (12)
7 -> 2 (111)
10 -> 4 (22)
17 -> 3 (122)
20 -> 6 (32)
50 -> 3 (1212)
100 -> 6 (244)
777 -> 6 (3333)
999 -> 4 (33213)
1000 -> 6 (4344)
1179360 -> 23 ([12, 9, 21, 4, 4])
232792560 -> 23 ([15, 12, 2, 20, 3, 13, 1])
2329089562800 -> 31 ([20, 3, 18, 2, 24, 9, 20, 22, 2])
69720375229712477164533808935312303556800 -> 101 ([37, 17, 10, 60, 39, 32, 21, 87, 80, 71, 82, 14, 68, 99, 95, 4, 53, 44, 10, 72, 5])
8337245403447921335829504375888192675135162254454825924977726845769444687965016467695833282339504042669808000 -> 256 ([128, 153, 236, 224, 97, 21, 177, 119, 159, 45, 133, 161, 113, 172, 138, 130, 229, 183, 58, 35, 99, 184, 186, 197, 207, 20, 183, 191, 181, 250, 130, 153, 230, 61, 136, 142, 35, 54, 199, 213, 170, 214, 139, 202, 140, 3])
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
f*FjQT
```
**[Verify all the test cases.](https://pyth.herokuapp.com/?code=f%2aFjQT&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A10%0A17%0A20%0A50%0A100%0A777%0A999%0A1000&debug=0)**
## How it works
```
f*FjQT ~ Full program.
f ~ First positive integer where the condition is truthy.
jQT ~ The input converted to base of the current element.
*F ~ Product. If the list contains 0, then it's 0, else it is strictly positive.
0 -> Falsy; > 0 -> Truthy.
~ Output the result implicitly.
```
Although Pyth's `f` operates on `1, 2, 3, 4, ...` (starting at 1), Pyth treats numbers in base 1 (unary) as a bunch of zeros, so base 1 is ignored.
[Answer]
# C, ~~52~~ 50 bytes
```
i,k;f(n){for(i=2,k=n;k;)k=k%i++?k/--i:n;return i;}
```
[Try it online!](https://tio.run/##fc1BCsIwEAXQfU8RCoWEJthGa4gheBE3Eo0MoaOEuio9eyy61HGW//H/BHULoRSQyUWOYo73zMFrmTy65ETyqYG2PaaNUnBAl6/TMyMDtxTAiY1nQC6quWLrPfIaRV43lxPWkkXeC@F@iyZlS8qOlIGUPSmGlL6jiW5pujX8GexoM4b@Zq39tlXYZ/M9upQX)
# C (gcc), ~~47~~ 45 bytes
```
i,k;f(n){for(i=2,k=n;k;)k=k%i++?k/--i:n;n=i;}
```
[Try it online!](https://tio.run/##fc1BCsIwEAXQfU8RCoWEJthGa4gheBE3EokMg6MUd6Vnj0GXOs7yP/6fZK4plQIaQ5aklnyfJUSrMVLAoDBiB31/xI0xcKBAEcJagJ7idgaSqlkaUe8x1yjLtrucqNUiy1Gp8FssK1tWdqxMrOxZcayMA098y/Kt6c/gwJtz/Dfv/bdVEZ/N9@haXg)
---
*Two bytes saved thanks to @Nevay's suggestion on @Kevin Cruijssen's answer!*
[Answer]
# [Haskell](https://www.haskell.org/), ~~56~~ ~~52~~ 48 bytes
```
b#n=n<1||mod n b>0&&b#div n b
f n=until(#n)(+1)2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0k5zzbPxrCmJjc/RSFPIcnOQE0tSTklswzE4UpTyLMtzSvJzNFQztPU0DbUNPqfm5iZZ1tQlJlXopKmYGlp@R8A "Haskell – Try It Online")
Pretty basic but can't think of any good ways to shorten it
EDIT: Thanks to Laikoni for saving me 4 bytes! Don't know why I never thought of `!!0`. I probably should've tried removing those parentheses but I have vague memories of some weird error when you try to use `||` and `&&` together. Maybe I'm confusing it with the equality operators.
EDIT 2: Thanks @Lynn for shaving another 4 bytes! Don't know how I never knew about `until` before now.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
2//.i_/;DigitCount[#,i,0]>0:>i+1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d9IX18vM17f2iUzPbPEOb80ryRaWSdTxyDWzsDKLlPbUO2/pjVXQFFmXolDWrShgYFB7H8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
→V▼MBtN
```
[Try it online!](https://tio.run/##yygtzv5/aFtu/qOmxqJD2/4/apsU9mjaHl@nEr////8bchlxGXOZcJlymXGZcxkacBmacxkZcJkCGQYGXObm5lyWlpYgtgEA "Husk – Try It Online")
### Explanation
```
→V▼MBtN
tN list of natural numbers starting from 2
MB convert the (implicit) input to each of those bases
V▼ find the (1-based) index of the first result where the minimum digit is truthy
→ add 1 to this index
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
2b@Ạ¥1#
```
[Try it online!](https://tio.run/##y0rNyan8/98oyeHhrgWHlhoq////39DAwAAA "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
n=x=input()
b=2
while x:z=x%b<1;b+=z;x=[x/b,n][z]
print b
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8@2wjYzr6C0REOTK8nWiKs8IzMnVaHCqsq2QjXJxtA6Sdu2yrrCNrpCP0knLza6KparoCgzr0Qh6f9/IwA "Python 2 – Try It Online")
This is one byte shorter than a recursive function:
```
f=lambda n,b=1,x=1:b*(x<1)or f(n,b+(x%b<1),[x/b,n][x%b<1])
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
-4 bytes thanks to Adnan
```
1µNвPĀ
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f8NBWvwubAo40/P9vCgA "05AB1E – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
←foΠ`B⁰tN
```
[Try it online!](https://tio.run/##yygtzv5/aFtu/qOmxqJD2/4/apuQln9uQYLTo8YNJX7///835DLiMuYy4TLlMuMy5zI04DI05zIy4DIFMgwMuMzNzbksLS1BbAMA "Husk – Try It Online")
## Explanation
```
-- input N
tN -- tail of [1..] == [2..]
←f( ) -- filter with the following:
`B⁰ -- convert N to that base
Π -- product (0 if it contains 0)
← -- only keep first element
```
[Answer]
# Java 8, ~~61~~ ~~56~~ 54 bytes
```
n->{int b=2,t=n;for(;t>0;)t=t%b++<1?n:t/--b;return b;}
```
[Try it here.](https://tio.run/##hY7BbsIwEETvfMVeKjmiSZO0EKVu6BeUC0fUg20MMoRN5GyQKpRvDw5wrVZar@R9o5k5qouKm9bicXcaTa26Dn6Uw@sMwCFZv1fGwnr63g9gxLQxkuEyhBemI0XOwBoQKhgxXl0nia7yV6pQ7hsvJK1SGVFFL3o@/8q@8ZPe4lhLb6n3CFoOo3x4tb2ug9fT8tK4HZxDHbEh7/Cw/QUVPbps/jqy56TpKWkDohoFJkZk0b3Zvzxn@DvDPxi@YPiS4QXDs5QTcA4557BgI1JOURRci7Is@ZRnzDAbxhs)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
int b=2, // Base-integer, starting at 2
t=n; // Temp-integer, copy of the input
for(;t>0;) // Loop as long as `t` is not 0
t=t%b++<1? // If `t` is divisible by the base `b`
// (and increase the base `b` by 1 afterwards with `b++`)
n // Set `t` to the input `n`
: // Else:
t/--b; // Divide `t` by the `b-1`
// (by decreasing the base `b` by 1 first with `--b`)
// End of loop (implicit / single-line body)
return b; // Return the resulting base
} // End of method
```
~~I have the feeling this can be golfed by using an arithmetic approach.~~ It indeed can, with a port of [@Steadybox' C answer](https://codegolf.stackexchange.com/a/146315/52210), and then golfed by 2 bytes thanks to *@Nevay*.
Old (**61 bytes**) answer:
```
n->{int b=1;for(;n.toString(n,++b).contains("0"););return b;}
```
[Try it here.](https://tio.run/##hY4xb8IwFIR3fsUTky2KldBCFFl071AWxqqDYwwyDc@R/YJUofz21BDW6kn24PvOd3c2V7MMncPz4We0rUkJPo3H2wzAI7l4NNbB7v58CGDFR5ZPLgJKndUh33wSGfIWdoCwhRGX77e7udmW@hii0Kgo7Cl6PAl8WSwaqWxAyj1JzIu51FJHR31EaPQw6imy65s2Rz6Tr8Ef4JJ/iCnn6xuMnGbtfxO5iwo9qS4jalGgsqKUj4H/8hXDXxn@xvA1wzcMrxheFpyBS1hxCWu2ouAcVcWtqOuab3nWDLNh/AM)
**Explanation:**
```
n->{ // Method with Integer as both parameter and return-type
int b=1; // Base-integer, starting at 1
for(;n.toString(n,++b).contains("0"););
// Loop as long as the input in base-`b` does contain a 0,
// after we've first increased `b` by 1 before every iteration with `++b`
return b; // Return the resulting base
} // End of method
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~20~~ 19 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429)
```
1+⍣{~0∊⍺⊥⍣¯1⊢n}≢n←⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@h9qPexdV1Bo86uh717nrUtRTIPbTe8FHXorzaR52L8h61TXjUNxWk9n8alxkA)
As usual, thanks to @Adám for helping out in chat and getting the code to work in TIO. Also, saving 1 byte.
This is tradfn (**trad**itional **f**unctio**n**) body. To use it, you need to assign it a name (which is in TIO's header field), enclose it in `∇`s (one before the name and one in TIO's footer field), and then call it using its name. Since it uses a quad (`⎕`) to take the user's input, it's called as `f \n input` instead of the usual `f input`
### How?
```
1+⍣{~0∊⍺⊥⍣¯1⊢n}≢n←⎕ ⍝ Main function.
n←⎕ ⍝ Assigns the input to the variable n
1+⍣{ }≢ ⍝ Starting with 1, add 1 until the expression in braces is truthy
~0∊ ⍝ returns falsy if 0 "is in"
⊥ ⍝ convert
⊢n ⍝ the input
⍣¯1 ⍝ to base
⍺ ⍝ left argument (which starts at 1 and increments by 1)
```
The function then returns the resulting base.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
@ìX e}a2
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=QOxYIGV9YTI=&input=OTk5)
## Explanation
```
@ }a2
```
Return the first number (`X`) to pass the function, starting at `2`
```
ìX
```
Convert the input number to an array of base-`X` digits.
```
e
```
Check if all digits are truthy.
[Answer]
# JavaScript (ES6), ~~43~~ ~~41~~ 37 bytes
```
n=>(g=x=>x?g(x%b++?x/--b|0:n):b)(b=1)
```
### Test cases
```
let f =
n=>(g=x=>x?g(x%b++?x/--b|0:n):b)(b=1)
console.log(f(1 )) // 2 (1)
console.log(f(2 )) // 3 (2)
console.log(f(3 )) // 2 (11)
console.log(f(4 )) // 3 (11)
console.log(f(5 )) // 3 (12)
console.log(f(6 )) // 4 (12)
console.log(f(7 )) // 2 (111)
console.log(f(10 )) // 4 (22)
console.log(f(17 )) // 3 (122)
console.log(f(20 )) // 6 (32)
console.log(f(50 )) // 3 (1212)
console.log(f(100 )) // 6 (244)
console.log(f(777 )) // 6 (3333)
console.log(f(999 )) // 4 (33213)
console.log(f(1000)) // 6 (4344)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
;.≜ḃ₎¬∋0∧1¬
```
[Try it online!](https://tio.run/##ASoA1f9icmFjaHlsb2cy//87LuKJnOG4g@KCjsKs4oiLMOKIpzHCrP//Nzc3/1o "Brachylog – Try It Online")
### Explanation
```
;.≜ḃ₎ The Input represented in base Output…
¬∋0 …contains no 0
∧1¬ And Output ≠ 1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
n=m=input()
b=2
while m:c=m%b<1;b+=c;m=(m/b,n)[c]
print b
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8821zYzr6C0REOTK8nWiKs8IzMnVSHXKtk2VzXJxtA6Sds22TrXViNXP0knTzM6OZaroCgzr0Qh6f9/QwMDAwA "Python 2 – Try It Online")
-1 thanks to [Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista).
-2 thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) (and now this is a dupe of her solution :D)
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 40 bytes
```
x=>filter(y=>all(digits(y,x)),2..x+3)[0]
```
[Try it online!](https://tio.run/##KyjKL8nP@59m@7/C1i4tM6cktUij0tYuMSdHIyUzPbOkWKNSp0JTU8dIT69C21gz2iD2f0FRZl6JRpqGoabmfwA "Proton – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~79~~ ~~71~~ ~~66~~ ~~63~~ 65 bytes
```
function(n){while(!{T=T+1;all(n%/%T^(0:floor(log(n,T)))%%T)})T
T}
```
[Try it online!](https://tio.run/##VY7LasMwEEX3@grVYDJDByrZjYVd/AtdadcXjiolAiGXWKWFkG93pUAIXVw4zGUO97i6cXXf0SQ/R4h4@jn4YOHupEd9L5@mECDWD7V@BzG4MM9HCPMeImlErGuNZ9RMn9dkl/RhpsUufOQGJDXU0iNtqSNFUpBU1AjaZhCClFLU933hfJCqbzuBzP5@WZPsJ@cXRRGUFE2T02ZVSZe5o6ZFxlxe47mPXA7Bxn06wG0GIjNTgs3zsKHb9cW/UcX5LvNQkYN/DRLP3XVG7q94@XqNFa5/ "R – Try It Online")
This answer is based on Giuseppe's re-arrangement in one single loop.
Saved 8 bytes thanks to JDL, and 6 bytes thanks to Giuseppe.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes
```
`G@Q_YAA~}@Q
```
[Try it online!](https://tio.run/##y00syfn/P8HdITA@0tGxrtYh8P9/c3NzAA "MATL – Try It Online")
-1 byte thanks to Luis Mendo. This program does not handle testcases bigger than 2^53 (`flintmax`, the maximum consecutive integer representable by a floating point type), as the default datatype is `double` in MATL. However, it should be able to find any arbitrary zeroless base below that number.
```
` % Do while
G % Push input
@ _ % Outputs the iteration number, negate.
YA % Convert input to base given by the iteration number, the negative number is to instruct MATL we want an arbitrary high base with a integer vector rather than the default character vector we know from hexadecimal
A~ % If they're not all ones, repeat
} % But if they are equal, we finally
@ % Push the last base
Q Q % As base 1 makes no sense, to prevent MATL from errors we always increase the iteration number by one.
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~56~~ ~~52~~ ~~51~~ 49 bytes
```
:2&v
1(?\:&:&:@%@,:1%-:
v~<
l<*v?=2
&v?/:&+1
n>&
```
[Try it online!](https://tio.run/##S8sszvj/38pIrYzLUMM@xkoNCB1UHXSsDFV1rbgUyupsuHJstMrsbY241Mrs9a3UtA258uzU/v//r1tmZGxkaWBhaWpmZGFgAAA "><> – Try It Online")
The interpreter bugs out on the last 2 testcases.
It only reads the first 16 digits of the input correct and then replaces the rest with other digits.
[Answer]
# PHP, 59+1 bytes
**using builtins**, max base 36:
```
for($b=1;strpos(_.base_convert($argn,10,++$b),48););echo$b;
```
**no builtins, ~~63~~60+1 bytes**, any base:
```
for($n=$b=1;$n&&++$b;)for($n=$argn;$n%$b;$n=$n/$b|0);echo$b;
```
Run as pipe with `-nR` or [try them online](http://sandbox.onlinephpfunctions.com/code/a25caa7efb9ff36eedf301f73f485c4901ce6edd).
[Answer]
# [Actually](https://github.com/Mego/Seriously), ~~12~~ 11 bytes
```
╗1⌠╜¡m'0<⌡╓
```
[Try it online!](https://tio.run/##ASQA2/9hY3R1YWxsef//4pWXMeKMoOKVnMKhbScwPOKMoeKVk///NTA "Actually – Try It Online")
Uses [this consensus](https://chat.stackexchange.com/transcript/message/40769640#40769640). Thanks to [Mego](https://codegolf.stackexchange.com/users/45941/mego) for byte-saving help in [chat](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte).
[Answer]
# J, 26 bytes
```
]>:@]^:(0 e.]#.inv[)^:_ 2:
```
Would love to know if this can be improved.
The main verb is a the dyadic phrase:
```
>:@]^:(0 e.]#.inv[)^:_
```
which is given the input on the left and the constant 2 on the right. That main verb phrase then uses J's Do..While construct, incrementing the right y argument as long as 0 is an element of `e.` the original argument in base y.
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/2PtrBxi46w0DBRS9WKV9TLzyqI146ziFYys/mtyKekpqKfZWqkr6CjUWimkFXNxcaUmZ@QrGCnYKqQpGCJzjCEcEzDHDFnGHMIxhuiB8szAPCMDZJ6hgYHBfwA "J – Try It Online")
[Answer]
# [Lua](https://www.lua.org), ~~77~~ 76 bytes
```
b=2n=...N=n
while~~N>0 do
if N%b<1then
b=b+1N=n
else
N=N//b
end
end
print(b)
```
[Try it online!](https://tio.run/##yylN/P8/ydYoz1ZPT8/PNo@rPCMzJ7Wuzs/OQCElnyszTcFPNcnGsCQjNY8ryTZJ2xCkJjWnOJXLz9ZPXz@JKzUvBYwLijLzSjSSNP///29oYGAAAA "Lua – Try It Online")
[Answer]
# [Milky Way](https://github.com/zachgates/Milky-Way), 38 bytes
```
^^'%{255£2+>:>R&{~^?{_>:<;m_+¡}}^^^}
```
usage: `./mw base.mwg -i 3`
---
## Explanation
```
code explanation stack layout
^^ clear the preinitialized stack []
' push the input [input]
%{ } for loop
255£ push next value from 0..254 [input, base-2]
2+ add 2 to the get the base [input, base]
> rotate stack right [base, input]
: duplicate ToS [base, input, input]
> rotate stack right [input, base, input]
R push 1 [input, base, input, 1]
&{~ } while ToS (=remainder) is true ...
^ pop ToS [input, base, number]
?{ } if ToS (=quotient) ...
_>:<; modify stack [input, base, number, base]
m divmod [input, base, quotient, remainder]
_+¡ else: output ToS (0) + SoS and exit
^^^ pop everything but the input.
```
I'm sure this can be shortened using a while-loop instead of a for loop, but I couldn't get it to work.
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 23 bytes
```
{!2[1+][n\tb all]until}
```
[Try it online!](https://tio.run/##FcgxCsIwGIDRvaf4OlURIUltf@IguUfMEK2FYqyC6SSePdbt8d45Xu@3oZRPbbzeBT@f84WYUljmPKVvccex2mgMLQc6egSt0IJRdCuUQkSw1v69hhbb9mpbeRo3DexPuLGpeS6ZwCO@yg8 "Stacked – Try It Online")
This increments (`[1+]`) **J** starting from two (`2`) while the base**J** representation of the input has no zeroes (`all` and `until`).
[Answer]
# [Perl 5](https://www.perl.org/), 52 + 2 (`-pa`) = 54 bytes
```
$\=1;while($_&&=$F[0]){$\++;$_=int$_/$\while$_%$\}}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxtbQujwjMydVQyVeTc1WxS3aIFazWiVGW9taJd42M69EJV5fJQasQiVeVSWmtrb6/38jYyNLAwtLUzMjCwODf/kFJZn5ecX/dX1N9QwMDf7rFiQCAA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
->n{(2..).find{!n.digits(_1).include? 0}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZFNSgNBEIVx6ylG3CSLDF3_VQvjLpcQETQmDMggmiwk5CRuBtFDxdPYyUwMLa6ar16_V_3o98-X9f1b9zG7-lqvFhPfjSfTdjPCuh7Xi6adby7aet4sm9Xr6A7GddM-PK3nj9dV2m57w_fZ7rma3cBtdVlNphWe7wkHogNRoXGhSUE6EB_ICh-kQgQrnHhUtY9NhQqplM2s4Igow9MfA4AF6XGGw05CC5R_xpE8RNF_Uwj6fmGYyAQxDJDNQFmIPF8nIUBKJKInG6Te50SGLJyIOa8EInEMSZyz3B0C1QRIQBGF80VHCeTIPVGdxTSYWd1CJeWdmgeSQ9GRaJ-TGFUjv-NUPBfrf7jr-vMH)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç╔ü$■╖Ö
```
[Run and debug it](https://staxlang.xyz/#p=80c98124feb799&i=1+%0A2+%0A3+%0A4+%0A5+%0A6+%0A7+%0A10+%0A17+%0A20+%0A50+%0A100+%0A777+%0A999+%0A1000+%0A1179360+%0A232792560+%0A2329089562800+%0A69720375229712477164533808935312303556800+%0A8337245403447921335829504375888192675135162254454825924977726845769444687965016467695833282339504042669808000+&a=1&m=2)
Trivial brute force approach
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 12 bytes
```
T NyYaTD Uoo
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJUIE55WWFURCBVb28iLCIiLCIiLCIxMDAiXQ==)
### Explanation
An iterative solution:
```
T NyYaTD Uoo
a is command-line input; y is ""; o is 1 (implicit)
T Loop until
Ny Min(y) is truthy:
Uo Increment o
aTD Convert a to list of digits in that base
Y Store that list in y
o After the loop, output o
```
---
Alternate solution using filter, also **12 bytes**:
```
@:NaTD_FI2,m
a is command-line input; m is 1000 (implicit)
2,m Range from 2 to 999 (could be 256, but using m is shorter)
FI Filter, keeping elements for which this function returns truthy:
aTD_ Convert a to list of digits in base (function argument)
N Get the minimum
@: Take the first element of the filtered list
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJAOk5hVERfRkkyLG0iLCIiLCIiLCIxMDAiXQ==)
] |
[Question]
[
The three rows of the qwerty keyboard are `qwertyuiop`, `asdfghjkl` and `zxcvbnm`. Your task is to find the longest word that can be typed using only one row of the keyboard, from a given list of words.
Sample input 1
```
artist
home
gas
writer
geology
marine
twerp
```
Output
```
writer
```
(Of the given words, only `gas`, `writer` and `twerp` can be written using a single row, and `writer` is the longest)
The words may not be actual words (so don't assume the third row to be invalid). However, you can assume that there will always be exactly one answer (no more, no less).
Sample input 2
```
wrhuji
bxnzmmx
gllwssjjd
vnccbb
lrkjhgfdsa
tttttt
```
Output
```
bxnzmmx
```
Additional punctuation and whitespaces can be provided in input (as per language requirements). However, no extra output should be given. Input and output are in lower case. **Shortest code wins.**
[Answer]
## Python 2, 84 bytes
```
lambda l:max(l,key=lambda w:(-len({"asdfghjklzxcvbnm".find(c)/9for c in w}),len(w)))
```
Finds the `max` of the input, comparing by fewer keyboard rows spanned, then in increasing length. The keyboard row value is extracted by `"asdfghjklzxcvbnm".find(c)/9`, which takes the middle row to `0`, the bottom row to `1`, and the top row, which is excluded, to `-1`, since `find` gives `-1` for missing values.
Other attempts:
```
lambda l:max((-len({"asdfghjklzxcvbnm".find(c)/9for c in w}),len(w),w)for w in l)[2]
lambda l:max(l,key=lambda w:len(w)-1./len({"asdfghjklzxcvbnm".find(c)/9for c in w}))
lambda l:max([w for w in l if len({"asdfghjklzxcvbnm".find(c)/9for c in w})<2],key=len)
```
[Answer]
# Japt, ~~32~~ 30 bytes
```
;Uf_¬£DbXu)f10Ãä¥ eÃn@Yl -XlÃg
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=O1VmX6yjRGJYdSlmMTDD5KUgZcNuQFlsIC1YbMNn&input=WwoiYXJ0aXN0IgoiaG9tZSIKImdhcyIKIndyaXRlciIKImdlb2xvZ3kiCiJtYXJpbmUiCiJ0d2VycCIKXQ==) Input is an array of strings.
### How it works
```
;Uf_ ¬ £ DbXu)f10Ã ä¥ eà n@ Yl -Xlà g
;UfZ{Zq mX{DbXu)f10} ä== e} nXY{Yl -Xl} g
// Implicit: U = input array of strings
; // Reset variables A-L to various values.
// D is set to the string "QWERTYUIOP\nASDFGHJKL\nZXCVBNM".
UfZ{ } // Take U and filter to only the items Z that return truthily to this function:
Zq // Split Z into chars, then
mX{ } // map each char X by this function:
DbXu) // Return D.indexOf(X.toUpperCase()),
f10 // floored to a multiple of 10.
// This maps each char to 0 for the top row, 10 for the middle, 20 for the bottom.
q ä== // Split the resulting string into chars and check each pair for equality.
e // Check that every item in the result is truthy. This returns true if all chars
// are on the same row; false otherwise.
// Now we have only the words that are entirely on one row.
nXY{ } // Sort by passing each two args X and Y into this function:
Yl -Xl // Return Y.length - X.length. Sorts the longest to the front.
g // Get the first item in the resulting array. Implicitly output.
```
[Answer]
# Python 2.5+ and 3, 93 bytes
Had to test how many strokes for this approach; this uses the fact that `a.strip(b)` results in empty string if `a` solely consists of characters that occur in b.
The function takes list of strings and returns a string.
```
lambda a:max(a,key=lambda x:(~all(map(x.strip,['qwertyuiop','asdfghjkl','zxcvbnm'])),len(x)))
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), 73 bytes
```
G`^([eio-rtuwy]+|[adfghjkls]+|[bcmnvxz]+)$
1!`(.)+(?!\D+(?<-1>.)+(?(1)!))
```
[Try it online!](http://retina.tryitonline.net/#code=R2BeKFtlaW8tcnR1d3ldK3xbYWRmZ2hqa2xzXSt8W2JjbW52eHpdKykkCjEhYCguKSsoPyFcRCsoPzwtMT4uKSsoPygxKSEpKQ&input=YXJ0aXN0CmhvbWUKZ2FzCndyaXRlcgpnZW9sb2d5Cm1hcmluZQp0d2VycAp3cmh1amkKYnhuem1teApnbGx3c3NqamQKdm5jY2JiCmxya2poZ2Zkc2EKdHR0dHR0)
Conclusion: Retina needs a sorting stage.
### Explanation
```
G`^([eio-rtuwy]+|[adfghjkls]+|[bcmnvxz]+)$
```
This is a grep stage: it only keeps lines which are matched by the regex. I.e. those which are formed exclusively from one of those character classes.
```
1!`(.)+(?!\D+(?<-1>.)+(?(1)!))
```
Now we just need to find the largest of the remaining strings. We do this by matching all words which are at least as long than all the words after them. The `1` is a new addition to Retina (released two days ago), which limits this match stage to considering only the first such match. And `!` instructs Retina to print the match (instead of counting it).
[Answer]
## Java, ~~154~~ 142 or ~~142~~ 130 bytes
[Because, ya know, Java.](http://meta.codegolf.stackexchange.com/a/5829)
[C#, for comparison](https://codegolf.stackexchange.com/a/75767/51825).
146 bytes if input has to be a single string with values separated by `\n`:
```
s->java.util.Arrays.stream(s.split("\n")).filter(g->g.matches("[wetyuio-r]*|[asdfghjkl]*|[zxcvbnm]*")).max((a,b)->a.length()-b.length()).get()
```
134 bytes if I can assume input as String[] instead:
```
s->java.util.Arrays.stream(s).filter(g->g.matches("[wetyuio-r]*|[asdfghjkl]*|[zxcvbnm]*")).max((a,b)->a.length()-b.length()).get()
```
Slightly ungolfed:
```
UnaryOperator<String> longestQwertyStr = s ->
java.util.Arrays.stream(s.split("\n")) // Split string input over `\n` and convert to Stream<String>
.filter(g->g.matches("[wetyuio-r]*|[asdfghjkl]*|[zxcvbnm]*")) // Filter to Strings that only use characters from a single row
.max((a,b)->a.length()-b.length()) // Find the max by comparing String length
.get(); // Convert from Optional<String> to String and implicit return single statement lambda
```
Second lambda is a `Function<String[],String>`.
[Answer]
# Jelly, ~~40~~ 34 bytes
```
p“£vẈ¬ḣ“£AS°GƤg“£ḷḳƤ²ƤȤḤ»f/€fµL€Mị
```
[Try it online!](http://jelly.tryitonline.net/#code=cOKAnMOm4bmZxL9neuKAnMKi4buK4bmaLuG4hMOmK-KAnMKjMsmgyKXCouG5v8WSwqbCu2Yv4oKsZsK1TOKCrE3hu4s&input=&args=WyJhcnRpc3QiLCAiaG9tZSIsICJnYXMiLCAid3JpdGVyIiwgImdlb2xvZ3kiLCAibWFyaW5lIiwgInR3ZXJwIl0)
### How it works
```
p“£vẈ¬ḣ“£AS°GƤg“£ḷḳƤ²ƤȤḤ»f/€fµL€Mị
“£vẈ¬ḣ“£AS°GƤg“£ḷḳƤ²ƤȤḤ» Use dictionary compression to yield
['quipo twyer', 'adj flash jg', 'bcmnz xv'].
p Cartesian product; for all pairs of an input
string and one of the rows.
f/€ Reduce each pair by filter, keeping only the
letters in the input string that are on that
particular keyboard row.
f Filter the results, keeping only filtered words
that occur in the input.
µ Begin a new chain.
L€ Get the length of each kept word.
M Get the index corr. to the greatest length.
ị Retrieve the word at that index.
```
[Answer]
# Python 3, 98
Saved 5 bytes thanks to Kevin.
Saved 3 bytes thanks to PM 2Ring.
Saved 3 bytes thanks to Antti Haapala.
Brute forcing it at the moment. I filter the words down to only those contained by a single row, and then sort for max string length.
```
lambda a:max(a,key=lambda x:(any(map(set(x).__le__,['qwertyuiop','asdfghjkl','zxcvbnm'])),len(x)))
```
Test cases:
```
assert f(['asdf', 'qwe', 'qaz']) == 'asdf'
assert f('''artist
home
gas
writer
geology
marine
twerp'''.splitlines()) == 'writer'
assert f('''wrhuji
bxnzmmx
gllwssjjd
vnccbb
lrkjhgfdsa
tttttt'''.splitlines()) == 'bxnzmmx'
```
[Answer]
## PowerShell v2+, 72 bytes
```
($args-match"^([qwertyuiop]+|[asdfghjkl]+|[zxcvbnm]+)$"|sort Length)[-1]
```
Takes input via command-line arguments as `$args`, then uses the [`-match` operator](https://technet.microsoft.com/en-us/library/hh847759(v=wps.620).aspx) with a regex to select only the words that are exclusively made up of one keyboard row. We pipe those results into [`Sort-Object`](https://technet.microsoft.com/en-us/library/hh849912(v=wps.620).aspx) that sorts by the property `Length`. We can do this since strings in PowerShell are all of the `System.String` type, which includes `.Length` as a sortable property. This sorts the strings into ascending order by length, so we take the last one with `[-1]`, leave it on the pipeline, and output is implicit.
**Example**
```
PS C:\Tools\Scripts\golfing> .\longest-word-qwerty-keyboard.ps1 asdf qwe zxc typewriter halls establishment
typewriter
```
[Answer]
# Pyth, ~~45~~ 35 bytes
Thanks to @FryAmThe Eggman for saving me some bytes!
```
elDf}k-LTc."`z:I¿Ç Ì(T4²ª$8·"\`Q
```
[Try it here!](http://pyth.herokuapp.com/?code=elDf%7Dk-LTc.%22%60z%02%3AI%C2%84%C2%BF%C3%87%09%C3%8C%28T4%C2%B2%C2%AA%24%148%C2%B7%22%5C%60Q&input=[%27wrhuji%27%2C+%27bxnzmmx%27%2C+%27gllwssjjd%27%2C+%27vnccbb%27%2C+%27lrkjhgfdsa%27%2C+%27tttttt%27]&test_suite_input=artist%0Ahome%0Agas%0Awriter%0Ageology%0Amarine%0Atwerp%0A&debug=0&input_size=7)
Takes input as a list of words.
## Explanation
```
elDf}k-LTc."..."\`Q # Q = list of all input words
f Q # Filter input with T as lambda variable
c."..."\` # List of all keyboard rows
-LT # Remove all letters of the current input row from the current input
# word. Results in a list of 3 string with one being empty if
# the word can be typed with one row
}k # Check if the list contains an emtpy string
elD # order result list by length and take the last
```
[Answer]
# Ruby, 88 82 69
If I'm not allowed to take a list of strings and must take a multiline string, add +12 to the score and add `.split('\n')` right before the `.grep` call.
Thanks CatsAreFluffy for teaching me about stabby lambdas in Ruby, and further optimizations from manatwork
```
->x{x.grep(/^([o-rwetyui]+|[asdfghjkl]+|[zxcvbnm]+)$/).max_by &:size}
```
[Answer]
## awk , ~~92~~ ~~84~~ 81 bytes
```
(/^([wetyuio-r]+|[asdfghjkl]+|[zxcvbnm]+)$/)&&length>length(a){a=$0}END{print a}
```
saved 3 bytes thanks to @Wolfgang suggestion
[Answer]
# C#, 141 / 112 / (120 bytes)
Contender for worst golfing language, for obvious reasons. Uses "my" locale with qwertz instead of qwerty but works fine otherwise.
Full program without where:
```
static void Main(string[]a){Console.WriteLine(a.OrderBy(x=>x.Length).Last(x=>Regex.IsMatch(x,"^([qwertzuiop]+|[asdfghjkl]+|[yxcvbnm]+)$")));}
```
Only output without Where:
```
Console.WriteLine(a.OrderBy(x=>x.Length).Last(x=>Regex.IsMatch(x,"^([qwertzuiop]+|[asdfghjkl]+|[yxcvbnm]+)$")));
```
Only output (original):
```
Console.WriteLine(a.Where(x=>Regex.IsMatch(x,"^([qwertzuiop]+|[asdfghjkl]+|[yxcvbnm]+)$")).OrderBy(x=>x.Length).Last());
```
[Answer]
# `bash`, 105 bytes
And various other utilities, of course.
```
egrep -x '[wetyuio-r]+|[asdfghjkl]+|[zxcvbnm]+'|awk '{print length($0)"\t"$0;}'|sort -n|cut -f2|tail -n1
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 54 bytes
```
[]y"@Y:nh]2$SP"@Y:!t'asdfghjkl'mw'zxcvbnm'myy+~hhAa?@.
```
This works with [current version (14.0.0)](https://github.com/lmendo/MATL/releases/tag/14.0.0) of the language/compiler.
Input format is (first example)
```
{'artist' 'home' 'gas' 'writer' 'geology' 'marine' 'twerp'}
```
or (second example)
```
{'wrhuji' 'bxnzmmx' 'gllwssjjd' 'vnccbb' 'lrkjhgfdsa' 'tttttt'}
```
[**Try it online!**](http://matl.tryitonline.net/#code=W115IkBZOm5oXTIkU1AiQFk6IXQnYXNkZmdoamtsJ213J3p4Y3Zibm0nbXl5K35oaEFhP0Au&input=eydhcnRpc3QnICdob21lJyAnZ2FzJyAnd3JpdGVyJyAnZ2VvbG9neScgJ21hcmluZScgJ3R3ZXJwJ30)
### Explanation
```
[] % push empty array. Will be used for concatenation
y % take input array implicitly at bottom of stack, and copy onto top
" % for each string
@Y: % push current string
nh % get its length. Concatenate with array of previous lengths
] % end for each
2$S % sort the original copy of input array by increasing string length
P % flip: sort by decreasing length
" % for each string in decreasing order of length
@Y:! % push that string as a column char vector
t'asdfghjkl'm % duplicate. Tru for chars in 2nd row of keyboard
w'zxcvbnm'm % swap. True for chars in 3rd row of keyboard
yy+~ % duplicate top two arrays, sum, negate: true for chars in 1st row
hh % concatenate horizontally twice
Aa % true if any column has all true values
? % if that's the case
@ % push string
. % break for each loop
% end if implicitly
% end for each
% display implicitly
```
[Answer]
# Perl, 81 bytes
`$a=$1 if/^([wetyuio-r]+|[asdfghjkl]+|[zxcvbnm]+)$/&&1<<y///c>$a=~y///c;END{say$a}`
Symbol to letter count pretty high.
[Answer]
# Groovy, 65 characters
```
{it.grep(~/[o-rwetyui]+|[asdfghjkl]+|[zxcvbnm]+/).max{it.size()}}
```
Sample run:
```
groovy:000> ({it.grep(~/[o-rwetyui]+|[asdfghjkl]+|[zxcvbnm]+/).max{it.size()}})(['wrhuji', 'bxnzmmx', 'gllwssjjd', 'vnccbb', 'lrkjhgfdsa', 'tttttt'])
===> bxnzmmx
```
Note that the regular expression used by `.grep()` not requires anchoring, allowing to spare the grouping too:
```
groovy:000> ['ab', 'ac', 'bc', 'abc', 'aca', 'bbc'].grep ~/[ac]+|b+/
===> [ac, aca]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;k_£D·bøXuÃä¦ dÃñÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=O2tfo0S3YvhYdcPkpiBkw/HK&input=WwoiYXJ0aXN0IgoiaG9tZSIKImdhcyIKIndyaXRlciIKImdlb2xvZ3kiCiJtYXJpbmUiCiJ0d2VycCIKXQ)
```
;k_£D·bøXuÃä¦ dÃñÊ :Implicit input of array
k :Remove elements that return true
_ :When passed through the following function
£ : Map each character X
; D : "QWERTYUIOP\nASDFGHJKL\nZXCVBNM"
· : Split on newlines
b : Index of first element that
ø : Contains
Xu : Uppercase X
à : End map
ä : Consecutive pairs of characters
¦ : Reduced by checking for inequality
e : Any true?
à :End filter
ñ :Sort by
Ê : Length
:Implicit output of last element
```
[Answer]
# [Perl 5](https://www.perl.org/) `-l`, 75 bytes
```
map$a[y///c]=$_,grep/^([weo-rtyui]+|[asdfghjkl]+|[zxcvbnm]+)$/,<>;say pop@a
```
[Try it online!](https://tio.run/##FcdLDsIgEADQPadw0YWmReqiKz/xAp6gqWasI0WhTAa0Yjy7GN/uEbJtcnZABbRJKdV32@JUaUZSx3k7oZcc08N05aeFcLnq4Xa3/7xf/fM8uq5cFKra7NYB0ow87SFn4GhCFIN3KDQEMbGJyEKjt14n4YDNiCJOyPT1FI0fQ5aHZlmv6iztDw "Perl 5 – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 56 bytes
```
{x@*&|/&/''~^($`qwertyuiop`asdfghjkl`zxcvbnm)?\:x@:>#'x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJwdjMkSgyAQRO/5ihRJueTi3VQlfkgqJSirIAZQ0CzfHrAP02+mppvU79Bcsk+VVXn+exbn9uWxcevM9dRC2xPKxCDbLXQLGlV5f9ShqW+nPHwPB3IsADSOWweugGmFo1Fo4/SGO2zSirXUdI2koOFj+nCxfwLlnvaGzYLHIwrjplRICSm9tUL0kZex6xCKIM0gGCW9halgFyj/5N0+kg==)
* `x@:>#'x` sort the input (a list of strings) by their lengths, descending, updating `x` with the result
* `($`qwertyuiop`asdfghjkl`zxcvbnm)` generate a list of strings representing which letters are present on each row of a qwerty keyboard
* `~^(...)?\:x` check whether or not each letter of each input word is present or not in each keyboard line
* `&/''` determine if all letters of each input word are present in the same keyboard line or not
* `|/` check that there is at least one keyboard line containing all the letters of each input word
* `x@*&` return the longest word in the input where the above criteria are met
] |
[Question]
[
I love sardines, I can't get enough of them, and so does my computer, the Omnilang 5000, which is language agnostic.
To give my computer the joy of experiencing sardines, I've decided to feed him a number of programs that are capable of displaying on the screen tins of sardines in various orientations, and showing up to ten sardines.
In this challenge, you'll be responsible for creating the programs based on these parameters:
## The input
A number (between 0 and 10) and a letter from one of the following "LR" (representing Left or Right respectively)
For example: `3L` or `5R`; how this is input into the program is up to you.
## Output
An open tin of sardines with the sardines facing the indicated direction, with the key (represented by the "`%`" character) and peeled lid (rolled up tin at the end represented by the "`@`" character) located at the top of the tin.
* All sardines must face the direction indicated by the input.
* All sardines will have bodies five characters long between the gill (either "`)`" or "`(`" ) and the tail "`><`"
* The key and peeled lid roll will always be facing the opposite direction to the sardines.
* The tin must have a 3-D look to it as shown below in the examples.
* The minimum height of the tin is 3 sardines in height. So if a number is less than 3, a tin of 3 sardines in height must be shown, with the inputted number of sardines in it. Otherwise, the tin must be the number of sardines high indicated in the input. So input of `0R` or `0L` will show an empty sardine tin.
* Any other input that can't be validated will not show anything.
For example, for "`3L`"
```
__________
(__________@%
|<*)_____><||
|<*)_____><||
|<*)_____><||
'==========''
```
For "`7R`"
```
__________
%@__________)
||><_____(*>|
||><_____(*>|
||><_____(*>|
||><_____(*>|
||><_____(*>|
||><_____(*>|
||><_____(*>|
''=========='
```
For "`2L`"
```
__________
(__________@%
|<*)_____><||
|<*)_____><||
| ||
'==========''
```
For "`0R`"
```
__________
%@__________)
|| |
|| |
|| |
''=========='
```
"`0L`"
```
__________
(__________@%
| ||
| ||
| ||
'==========''
```
Invalid input will not return anything...
* This is code golf, so the smallest number of characters will win this challenge.
* [No Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) as per usual.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~250~~ 235 + 3 = 238 bytes
```
</~?{" __________"a:="L"i&
o/?=1l
:/}rv?{~$?{"()__________@%":
l< o/?=1
:&oa/&~$?(3$@0-3:
/!?:</"||><_____(*>|"av?@:$-1
/=?/v"|<*)_____><||"a/
\2lo/
\~&
\>:?!\1+$::{a"|"{?:" ||"{?~
<\?=2 lo
"'":~/~?{"''==========":?{
;!?lo<
```
[Try it online](https://tio.run/##RY/BqsIwEEX38xXp0NdWH2Vs3Y1Jpx/gJwSkG7EQCLwH3STm12OtqGd553C5c53/bzlrShJQqcsHnNjgGecKPInpHDDd/xYJqVzFZvcVxx9kcFptGnDlJ6pWqTmW46E9MlAhrAljHPTmN/sh4rTIyGXbgSIjtGDU@1floON6JVC2d57ApgrswFLY7rdkDhNGDMLr0jfxGSTQVkyvnAeskdP2TV2bD8gS4FSI8zrnc24X1T8A "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)! Reads the "L" or "R" from STDIN and assumes the number of sardines is already on the stack (needs a `-v` flag for +3 bytes).
Because of course I had to write this in ><>.
[Answer]
# [Emojicode](http://www.emojicode.org/), ~~456~~ 448 bytes
```
üêãüöÇüçáüêñüêüdüöÇüçáüç¶aüòõ0düçäaüçáüòÄüî§ __________‚ùån(__________@%üî§üçâüçìüçáüòÄüî§ __________‚ùån%@__________)üî§üçâüîÇi‚è©0üêïüçáüçäaüçáüòÄüî§|<*)_____><||üî§üçâüçìüçáüòÄüî§||><_____(*>|üî§üçâüçâüçä‚ñ∂Ô∏è4üêïüçáüîÇi‚è©0‚ûñ3üêïüçáüçäaüçáüòÄüî§| ||üî§üçâüçìüçáüòÄüî§|| |üî§üçâüçâüçâüçäaüçáüòÄüî§'==========''üî§üçâüçìüçáüòÄüî§''=========='üî§üçâüçâüçâ
```
Takes 2 arguments: first one is lines, second one is direction (0 or 1).
[Try it online!](https://tio.run/##S83Nz8pMzk9J/f//w/wJ3R/mz2r6ML@3HcieBsTzUxACvcsSP8yfMdsAKNTblQgRm9HwYf6UJQrxcPBobk@eBoLroAqSB6rtBOLJKHrQNKk6IPiaCE1TmjIf9a80ADplKtQVqFbX2GhpgvXY2dTU4LKrpsbOBqxIQ8sOWREIdz2atu39jn4ThA1QKx/Nm2aM21oFOMBnLZIqNGs7MYxUt4UDdXVcRqojq0I3EhiB/Y0KIOVcCgqgyFMwUjDkAssAAA)
"Readable" ungolfed version and pseudocode version:
```
üêã üöÇ üçá
üêñ üêü d üöÇ üçá
üç¶ a üòõ 0 d
üçä a üçá
üòÄ üî§ __________‚ùån(__________@%üî§
üçâ
üçì üçá
üòÄ üî§ __________‚ùån%@__________)üî§
üçâ
üîÇ i ‚è© 0 üêï üçá
üçä a üçá
üòÄ üî§|<*)_____><||üî§
üçâ
üçì üçá
üòÄ üî§||><_____(*>|üî§
üçâ
üçâ
üçä ‚ñ∂Ô∏è 4 üêï üçá
üîÇ i ‚è© 0 ‚ûñ 3 üêï üçá
üçä a üçá
üòÄ üî§| ||üî§
üçâ
üçì üçá
üòÄ üî§|| |üî§
üçâ
üçâ
üçâ
üçä a üçá
üòÄ üî§'==========''üî§
üçâ
üçì üçá
üòÄ üî§''=========='üî§
üçâ
üçâ
üçâ
üëµ
extendclass int { // this makes the first argument be an int without declaring it
func üêü(int d) {
const a = 0 == d // a bool
if a {
print " __________\n(__________@%"
}
else {
print " __________\n%@__________)"
}
for i in range(1, arg) {
if a {
print "|<*)_____><||"
}
else {
print "||><_____(*>|"
}
}
if 4 > arg {
for i in range(0, arg - 3) {
if a {
print "| ||"
}
else {
print "|| |"
{
}
}
if a {
print "'==========''"
}
else {
print "''=========='"
{
}
}
üëµ
```
[Answer]
# [Python 2](https://docs.python.org/2/), 155 bytes
```
lambda x,y,t='_'*10:'\n'.join(x[::1-2*y]for x in[' %s '%t,'()'[y]+t+'@%']+['|'+('<>**)(%s><<>'%t)[y::2]+'||']*x+['|'+' '*10+'||']*(3-x)+["'"+'='*10+"''"])
```
[Try it online!](https://tio.run/##Lc3dCoIwAIbhWxmD8e3PyHU2VLqPOaIIyagpuoMNvPf1e/rywDvneJuCKUPbl8f5ebmeSdJZxxYnyHpv0Qfs7tMYeHLW1pWR2Q/TQhIZgwNhKyFgUYMLuOxVVDgyeOWwQXE0nZSCs7Vrmu7NhMvWGq@wbfAy/RTIZ/Rv/FAloRwFVWi/nQLUizIvY4hk4EbXorwA "Python 2 – Try It Online")
Input consists of a length 2 tuple. The first element indicates the number of sardines. The second element indicates the direction; `0` for left, `1` for right.
-84 bytes using lambda magic thanks to notjagan and officialaimm
[Answer]
# [Fishing](https://esolangs.org/wiki/Fishing), 1311 bytes
```
v+CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC?CCCDCC[CCCCCCCCCCCCCCCCCCCCC?CCCCCCCCCCCCCCCCCCCC[CCC[CCCCC?CCCC?DDDDD[CCCCCCCCCCCCCCCCCCC?CCCCCCCCCCCCCCCCC[?CCCCCCCCCCCCCCCC_
`3`n{n{In{I{`L`{` __________ `}}!{{rD}}D{{NE`%@__________)`}}!{{E`(__________@%`}}D{{NDE}}}}={d}}! d D{{{{{`><_____(*>`}}!{{E`<*)_____><`}}D!{{{E`|`P}PE`||`ND
[DDDDDD| [DDDDDDDDDDDDDDDDDDDD| D [C?CDDDDDDDDCCCCCCCCCCCCCCCCCCC[DDDDDDDDDDDDDDDDD|[CCCCCCCCCCCCCCCC_
D }=d [^+Cv-|{{{{{` `}} {{{E`||`P}PE`|`ND
D [CCCCCCCCCCCCCCCCCCC?DDDDDDDDD+CCCC D
D E`''=========='`{{{= }}}r{{{ [CCCC D
D [^CCCCCCCv|}}}N D
|DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD]
```
Takes input from `stdin` in the form:
```
5
R
```
Fishing isn't on [Try It Online](https://tryitonline.net), but there's an interpreter for it in Ruby on the linked esolangs page.
This is the first program I've made in Fishing -- in fact, it's the first program I've made in any 2D language -- so it can probably be a lot shorter. Golfing tips are welcome (though I wouldn't be surprised if no one gave any, considering that even I don't know what the heck I just wrote).
Here's a GIF of the path the program takes for input `1R` (sorry for low quality):
![GIF](https://i.stack.imgur.com/xNd9L.gif)
(This was created using an interpreter that I made; there are no publicly available programs that "visualize" Fishing, as far as I know)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes
```
Ôº°‚åà‚ü¶Ôº©Œ∏¬≥‚üߌ∂Ôº¢œá¬≤_‚Üê‚Üì(‚ÜìŒ∂'√ó=œá''‚ÜñÔº∞‚ÜëŒ∂‚Üê‚ÜëŒ∂@%Ôº¶ÔºÆ‚Äú#‚ஂÄπÔº∂Ôº¢“¬´ji‚ÄùÔº¶ÔºÆ‚ÄñÔº¥
```
[Try it online!](https://tio.run/##dY5Lq8IwEIX3/ooQECdSwerOF3rv3QhWRHSlUmJJNdAkvUmq4p@PEesD0VkMzDmH70yypzpRNHNuZAzfSYjoiYtCwOqXGgv/JEDtjV9n0q38qBOEzQC1AoRj7IVIHRh0Jiy1/phpLi10/tRReh/wu3R@CLj2NBdcMAO4jwMUNslLpPYsWOZlRVRkluc36DK/IT/9cPdK1rB6ZaVKIxjLvLDTQmyZBkJQGVjrXp3E1xn0vkXnLM1YYheaSuN9AaTrXAuFrnFwDZNdAA "Charcoal – Try It Online") Link is to verbose version of code. First argument is number of sardines, second is direction (0 = left, 1 = right).
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~51~~ 48 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
!gX⁴‘gj⁰%!⁵‘b⌡"κN╥█*≤⌡║)‘3b-"÷AZ⁴‘∙_"Χccσ«‘⁰e?±↔
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIxZ1gldTIwNzQldTIwMThnaiV1MjA3MCUyNSUyMSV1MjA3NSV1MjAxOGIldTIzMjElMjIldTAzQkFOJXUyNTY1JXUyNTg4KiV1MjI2NCV1MjMyMSV1MjU1MSUyOSV1MjAxODNiLSUyMiVGN0FaJXUyMDc0JXUyMDE4JXUyMjE5XyUyMiV1MDNBN2NjJXUwM0MzJUFCJXUyMDE4JXUyMDcwZSUzRiVCMSV1MjE5NA__,inputs=MSUwQTA_)
Expects input as the 1st one being the count and the 2nd one - left or right represented by 1 or 0.
Explanation:
```
..‘..‘ push 2 compressed strings - the 1st two lines of the box - " __________ " and "%@__________)"
b‚å° input times do
"..‘ push a line with a sardine - "||><_____(*>|"
3b- push 3-input
"..‘∙ get an array of that many "|| |"
_ put all the arrays contents on the stack
"..‘ push "''=========='" - the last line
⁰ wrap all of that in an array
e? if the 2nd input [is not 0]
±↔ reverse the array horizontally
```
[Answer]
# R, 334 bytes 311 bytes
```
s=function(n,d){
a="__________"
b="'=========='"
if(d == "L"){cat(paste(c(" ",a,"\n(",a,"@%\n",rep("|<*)_____><||\n",n),rep("| ||\n",max(c(3-n,0))),b,"'\n"),collapse=""))} else {cat(paste(c(" ",a,"\n%@",a,")\n",rep("||><_____(*>|\n",n),rep("|| |\n",max(c(3-n,0))),"'",b,"\n"),collapse=""))}}
```
Function takes a numeric value for n and a string for the direction.
This is my first time posting, so I'll admit I'm not sure how to count bytes of code.
[Answer]
## C++, ~~307~~ ~~296~~ 292 bytes
```
#include<string>
auto z(int n,char c){std::string r=c-82?" __________\n(__________@%\n":" __________\n%@__________)\n";int l=0;for(;l<n;++l)r+=c-82?"|<*)_____><||\n":"||><_____(*>|\n";for(;l<3;++l)r+=c-82?"| ||\n":"|| |\n";r+=c-82?"'==========''":"''=========='";return r;}
```
Usage :
```
z(<number of sardines>,<'L' or 'R'>);
```
-11 bytes saved thanks to user ThePirateBay
-4 bytes thanks to Zachar√Ω
[Answer]
# [Python 2](https://docs.python.org/2/), 287 bytes
```
n,d=input()
t,a,b,c,e,k=' __________ ','(__________@% ','|<*)_____><|| ','| || ',"'=========='' ",'\n'
print[t+k+a+k+k.join([b]*n)+k+k.join([c]*(3-n))+k*(n<3)+e,t[::-1]+k+a[::-1].replace(*'()')+k+k.join([b[::-1].replace(*')(')]*n)+k+k.join([c[::-1]]*(3-n))+k*(n<3)+e[::-1]][d]
```
[Try it online!](https://tio.run/##ZY3bCoMwEETf/YoglE3iKqhvoqX/kUrxBrWWNUj6UPDfUy/FSh1Y2DnMMPpt7j1F1hLWWUv6ZbhwDBZYYoUNdhmw2ybGGCDwH7icZjCmUiz2nI7jAtimBbiQbQJgLsKVwNFDS0YZr/OK6brg0bfEVZlLEjtf5ZLHPomJSU5pLLwGjUoSP8zn5voFQ6OfRdVwCVzAvl4eAoKD@N9YQ8elL1d1bm2ELPwA "Python 2 – Try It Online")
Input is a comma separated tuple of numbers of this format: `2, 1`. The first number is the amount of fish and the second is is 0 for left and 1 for right.
This started out as an attempt to out-golf the other answer (I totally thought I could), but it sucks. :P If anybody can make head and tail of it and help golf it (I blame it on it being 12 am right now), I'd be glad.
[Answer]
# C# (.NET Core), 289 bytes
```
(h,d)=>{var l=d=='L';string r=(l?" ":" ")+"__________\n"+(l?"(":"%@")+"__________"+(l?"@%":")")+"\n";for(int i=0;i<(h>3?h:3);i++){r+=(l?"|":"||")+(i<h?(d=='L'?"<*)_____><":(d=='R'?"><_____(*>":"")):" ")+(l?"||":"|")+'\n';}var b=(l?"'":"''")+"=========="+(l?"''":"'");return r+b;}
```
[Try it online!](https://tio.run/##jVBNa8IwGL77K14CksR2IjgYNE0rDHZyMNxhhzlGrdUGagpvojC0v71LUia4k88tz1eepDQPZYtVXzaFMfCG7R6Lw@g8AgdjC6tKOLVqC6@F0sxYVHr/@QUF7g0PnsHp8f5jbHWYvhx1mSptYyjrAmMYMhnsQPasjrdcZudTgdDIrZR0ScVgAJSsyQmQhAAQHpHvK9aaRF5jThsvbrVBWYydxL3ivGLXInMDQMmZUCmrs3leJ3MuVBTxM0bhnosLXC4uwVRa52yYkpN0wkNtlpIkkCtHZmng2CRzIcK5X/gH3@DrQp870LWmovPv24R7qOMp9cvkFcNmGiTCBVb2iBow2oiuF/@/87nVpm2q6QcqWy2VrtiOPcbg1nJ@l/nJmVf3mmc3zd2o638B "C# (.NET Core) – Try It Online")
Takes an integer and a char (L, R) as parameters and outputs the resulting string.
Ugh. Had to deal with some annoying string constants, sadly you cant just do `string * length` in C#. And the method with `new string(char, length)` wouldn't have been worth the byte cost.
---
The algorithm works as follows:
1. At the start we determine if the sardines face right or left, since we will then format our strings accordingly. We create a string for the top, with some conditional operators to switch between the L and R perspective.
2. Then we create a loop that runs 3 times at minimum and the left input times at maximum. That way we can create empty spaces if we have less than 3 sardines in our box.
3. Inside this loop we format a string, depending on the perspective and also, if `h > i`, we put a sardine inside of it. If `i >= h`, there will be an empty space where a sardine would normally be.
4. At the end we create the bottom of the box, again formatted according to perspective.
[Answer]
# [Perl 5](https://www.perl.org/), 167 + 1 (-n) = 168 bytes
```
($n,$d)=/(\d+)([LR])/ or die;say('R'eq$d?(reverse$_)=~y/()></)(<>/r:$_)for" __________ ","(__________@%",("|<*)_____><||")x$n,("| ||")x(3-$n),"'==========''"
```
[Try it online!](https://tio.run/##RY1LCsIwFACvEh6RvKep8UM3mlYPoJtuVYqQCAVJaipioXh0Y@mizm5mM7UN9zRG5E5yQ5nCs5kRng7FhRTzgZnKbptri6IQ9sHNDoN92dBYXlL2aRVSrhWhzlXY9OnmA7ByhDGQgH/fT0AidHpKg@a664De/bqPbGSIuE64IwkiGxECYlwVX18/K@@amBzT@WK5iIn7AQ "Perl 5 – Try It Online")
[Answer]
# [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) (ES6), ~~283~~ ~~273~~ ~~269~~ 251 bytes
*Saved 10 bytes thanks to @WallyWest*
*Saved 4 bytes removing extra parens*
*Saved 18 bytes thanks to @ThePirateBay*
Suffers from lack of string reversal in the standard library. Defines a function that takes inputs `n` for number of fish and `d` for direction. Throws if `d` is not "L" or "R".
```
(n,d,_=c=>c.repeat(10),x=_(`_`),z=a=>a.reverse``.join``)=>
([p,q,g,r,s]=d>`L`?d>`R`?[]:[`)`,`(`,`>`,z,y=>z(y.split``)]:
[`(`,`)`,`<`,a=>a.join``,y=>y],` ${x}
`+r([p,x,s(`@%`)])+`
`+(r([`|`,g,`*`,q,`_____`,`><`,`||`])+`
`).repeat(n)+r([`'`,_(`=`),`''`]))
```
[Try it online](https://tio.run/##NY/NboMwEITvPIUPqbxutlZ/bk3t9AFyypUixiIkIqKGAkX5fXZqJ6olW6udb2e8eze6vuiqdnjyzaactmYizxvOTWFsobuyLd1AL8@KDyYnmUvFJ@OMdUEay64vAb1vKg8oYylt@Yd33HGfmY3FCsvwrrFMs/cUCgwK14JPfDT2REfdt3U1hNmoRy0yH@BbwN02kseMIWbnwzXBvIshB@4Jnw9hTs0RmhS6uCBE4xHhC8jjiVnBDJcL7pz638er6AMJzgkGiiFlYNQ0uk5Uvv0dhBFpIkT6xnIlM47lK8u1zJJskSRF4/umLnXd7OiG62/XkhPGCszOW9JaO3UNeXEHkl9eKrWY/gA)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 91 bytes
```
ð\_₀*+ðd+⅛\(\_₀*`@%`++⅛⁰3WG(\|n⁰≥[ð₀*|`<*)_____><`]\|d++⅛)\'\=₀*\'d++⅛¾¹\R=[ƛṘ`<>()``><)(`Ŀ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C3%B0%5C_%E2%82%80*%2B%C3%B0d%2B%E2%85%9B%5C%28%5C_%E2%82%80*%60%40%25%60%2B%2B%E2%85%9B%E2%81%B03WG%28%5C%7Cn%E2%81%B0%E2%89%A5%5B%C3%B0%E2%82%80*%7C%60%3C*%29_____%3E%3C%60%5D%5C%7Cd%2B%2B%E2%85%9B%29%5C%27%5C%3D%E2%82%80*%5C%27d%2B%2B%E2%85%9B%C2%BE%C2%B9%5CR%3D%5B%C6%9B%E1%B9%98%60%3C%3E%28%29%60%60%3E%3C%29%28%60%C4%BF&inputs=R%0A2&header=&footer=)
```
=== Top row ===
√∞\_‚ÇÄ*+√∞d+‚Öõ
√∞ # A space
\_‚ÇÄ* # Ten underscores
+ # Concatenated
√∞d+ # Two more spaces
‚Öõ # Push to global array
=== Next row ===
\(\_‚ÇÄ*`@%`++‚Öõ
\( # The parenthesis
\_‚ÇÄ* # Ten underscores
`@%` # Literal
++‚Öõ # Concatenated and pushed to global array
=== The fishes ===
⁰3WG(\|n⁰≥[ð₀*|`<*)_____><`]\|d++⅛)
⁰3WG # Max(3,fish)
( ) # times....
\| # Push pipe
[ ] # If...
n⁰≥ # Iteration number is greater than or equal to input (missing fish)
ð₀* # Ten spaces
| # Else...
`<*)_____><` # A fish
\|d # `||`
++‚Öõ # Concatenate and push to global array
=== The final row ===
\'\=‚ÇÄ*\'d++‚Öõ
\' # Literal
\=‚ÇÄ* # Ten equalses
\'d # Two more apostrophes
# Concatenated and pushed to global array
=== Flipping + Formatting ===
¾¹\R=[ƛṘ`<>()``><)(`Ŀ
¾ # Push global array
[ # If...
¬π\R= # Input is R
∆õ # Foreach...
·πò # Reverse...
`<>()``><)(`ƒø # Flip brackets
```
] |
[Question]
[
A staircase number is a positive integer **x** such that its **n**th digit (one indexed starting with the least significant digit) is equal to **x % (n + 1)**. Thats a bit of a mouthful so lets look at an example. Take **7211311**, if we take the modular residues of **7211311** on the range 2-8 we get the following:
```
7211311 % 2 = 1
7211311 % 3 = 1
7211311 % 4 = 3
7211311 % 5 = 1
7211311 % 6 = 1
7211311 % 7 = 2
7211311 % 8 = 7
```
These are the digits of **7211311**! Thus **7211311** is a staircase number.
## Task
Write code that takes when given a positive number as input, will output two distinct values one if the number *is* a staircase number and the other if it is not.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition so your aim should be to minimize the number of bytes in your source code.
## Test Cases
Here are the first 13 staircase numbers:
```
1, 10, 20, 1101, 1121, 11311, 31101, 40210, 340210, 4620020, 5431101, 7211311, 12040210
```
[Answer]
# Haskell, 55 ~~57~~ bytes
```
f m|let n#x=n==0||n`mod`10==m`mod`x&&div n 10#(x+1)=m#2
```
A different approach than the other Haskell solution.
*Thanks xnor for saving 2 bytes.*
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~25~~ ~~21~~ ~~16~~ 14 bytes
```
{it+₂;?↔%}ᶠ↔c?
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vzqzRPtRU5O1/aO2Kaq1D7ctANLJ9v//mxsZGhobGgIA "Brachylog – Try It Online")
First Brachylog submission :D ~~probably very ungolfed~~...many thanks to Leaky Nun and Fatalize for encouragement and help to golf this from 25 all the way down to just 14. :) :)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
### Code:
```
ā>%JRQ
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//SKOdqldQ4P//JmZGBgZGBgA "05AB1E – Try It Online")
### Explanation:
```
ā # Get the range [1 .. len(input)]
> # Increment by 1
% # Vectorized modulo
J # Join the array into a single number
RQ # Reverse that number and check if it's equal to the original input
```
[Answer]
# Javascript, ~~42~~ ~~41~~ ~~39~~ 38 bytes
-4 bytes thanks to @Shaggy and @ETHProductions
```
s=>[...s].some(d=>s%i++^d,i=~s.length)
```
This takes the number as a string and returns `false` if the number is a staircase number and `true` otherwise.
Example code snippet:
```
f=
s=>[...s].some(d=>s%i++^d,i=~s.length)
function update() {
o.innerText = f(document.getElementById("i").value)
}
```
```
<input id="i" type="number">
<button onclick="update()">Test</button>
<p id="o">
```
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
f=lambda n,x=0:10**x>n or(`n%(x+2)`==`n`[~x])*f(n,x+1)
```
[Try it online!](https://tio.run/##DcrRCsIgFAbg@57iv4l5nMX0cuBeJAKNsoR2HOKFY6xXt33X37KWT2LTWrBfPz@eHqyqHUY9SFknRsrC8VnU3pCz1rG7/eqdZBBH6zW1kDIiIiN7fr@EVjCaxhOw5MgF3bbjMmHbu@sxZ19EVAgiErU/ "Python 2 – Try It Online")
[Answer]
# Haskell, 60 bytes
Takes the number as an int
```
x n|s<-show n=reverse s==(rem n.(+1)<$>[1..length s]>>=show)
```
[Answer]
# Mathematica, 60 bytes
```
FromDigits@Reverse@Mod[#,Range@Length@IntegerDigits@#+1]==#&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvvfrSg/1yUzPbOk2CEotSy1qDjVwTc/JVpZJygxLz3VwSc1L70kw8EzryQ1PbUIqlBZ2zDW1lZZ7X9AUWZeiYKDQpqCg6GRgYmBkaHBfwA "Mathics – Try It Online")
@alephalpha golfed it to 48
# Mathematica, 48 bytes
```
FromDigits@Reverse@Mod[#,Range[2,Log10@#+2]]==#&
```
next one is 24120020
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~9~~ ~~7~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as a string.
```
Ô¶¡%´J
```
2 bytes saved with help from [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions).
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1LahJbRK&input=IjcyMTEzMTEi)
```
Ô¶¡%´J :Implicit input of string U
Ô :Reverse
¶ :Test for equality with
¬° :Map U
% : Modulo
´J : J (initially -1) prefix decremented
```
[Answer]
# [Neim](https://github.com/okx-code/Neim), 6 bytes
```
ùêß·õñùïÑùê´ùê£ùîº
```
Explanation:
```
ùêß Get the length of the input, then create an exclusive range
·õñ Add 2 to each element
ùïÑ Modulus
ùê´ Reverse
ùê£ Join
ùîº Check for equality
```
[Try it online!](https://tio.run/##y0vNzP3//8PcCcsfzp72Ye7UFiBzNRAv/jB3yp7//w0NAA "Neim – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
DJ‘⁸%⁼Ṛ
```
[Try it online!](https://tio.run/##y0rNyan8/9/F61HDjEeNO1QfNe55uHPW////zY0MDY0NDQE "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
lambda x:all(`x%(i+2)`==`x`[~i]for i in range(len(`x`)))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfll@kkKmQmaeQlplTklqkofE/JzE3KSVRocIqMSdHI6FCVSNT20gzwdY2oSIhui4zFq6hKDEvPVUjJzUPqChBU1Pzv6YOVMzQAAw0Na24FICgoCgzr0Qh8/9/AA "Python 2 – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 32 bytes
```
{$_ eq[~] $_ ¬´%¬´(1+.comb...2)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiVeIbUwui5WAcg4tFr10GoNQ2295PzcJD09PSPN2v/WCsWJlQrpRakFQA06CoZ6eoZGBgYG/wE "Perl 6 – Try It Online")
* `.comb` is the number of characters in the string representation of the input argument `$_` (that is, the number of digits).
* `1 + .comb ... 2` is the sequence of numbers from one greater than the number of digits down to 2.
* `¬´%¬´` is the modulus hyperoperator that gives the remainder when `$_`, the input argument on its left, is divided by each of the elements of the sequence on its right: `$_ % 2, $_ % 3, ...`.
* `[~]` concatenates those digits into a new number, which is compared with the input argument using the string equality operator `eq`.
[Answer]
# [PHP](https://php.net/), 43 bytes
```
for(;$r<$a=$argn;)$r=$a%~++$i.$r;echo$r>$a;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerZG5kaGhsaKhk/T8tv0jDWqXIRiXRFixnralSBGSp1mlrq2TqqRRZpyZn5KsU2akkWv//DwA "PHP – Try It Online")
# [PHP](https://php.net/), 44 bytes
prints 1 for true and nothing for false
```
for(;$r<$a=$argn;)$r=$a%~++$i.$r;echo$r==$a;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerZG5kaGhsaKhk/T8tv0jDWqXIRiXRFixnralSBGSp1mlrq2TqqRRZpyZn5AOFgGLW//8DAA "PHP – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
-1 bytes thanks to [Okx](https://codegolf.stackexchange.com/users/26600/okx).
```
qsjk_m%QhdSl`
```
[Try it online!](https://pyth.herokuapp.com/?code=qsjk_m%25QhdSl%60&input=7211311&debug=0)
**Explanation**
```
QQ # Implicit input
Sl`Q # Generate [1, len(str(Q))]
m%Qhd # For digit d in above range, perform Q % (d + 1)
sjk_ # Reverse, then convert to number
q Q # Test equality with input
```
**Alternate solution**, still 13 bytes (thanks to [karlkastor](https://codegolf.stackexchange.com/users/56557/karlkastor))
```
qi_.e%Q+2k`QT
```
[Try it online!](https://pyth.herokuapp.com/?code=qi_.e%25Q%2B2k%60QT&input=7211311&debug=0) That's essentially the same as the first solution, excepted that it uses `i` to convert from array of numbers to a number, and that the range is generated differently.
[Answer]
# C++,104 bytes
1) original version:
```
int main(){int N,T,R=1;cin>>N;T=N;for(int i=1;i<=log10(N)+1;i++){if(N%(i+1)!=T%10){R=0;}T/=10;}cout<<R;}
```
2) in a readable form:
```
int main()
{
int N, T, R = 1;
cin >> N;
T = N;
for (int i = 1; i <= log10(N) + 1; i++)
{
if (N % (i + 1) != T % 10)
{
R = 0;
}
T /= 10;
}
cout << R;
}
```
[Try it Online!](https://tio.run/##RYtNDoMgGET3noKmMYFgU1nzcwQWhgsQRPslBYzgynh2iquu5s2bjNu21@pcfUJ032P2SEDKZfc2qO7vXLDlo7ojQ1xRtMHnzTqPcpl5hVhQsBAxOW/UgxkmybiDqJTmRmq@pB3fEzQNQn7TykasCW2N0vZasO4xUEYe0vRsJOckR36Zt2QtXDqKEBO/amU/)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~21~~ 19 bytes
```
{⍵=10⊥⌽⍵|⍨1↓⍳1+≢⍕⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR71ZbQ4NHXUsf9ewFsmse9a4wfNQ2@VHvZkPtR52LHvVOBYrW/k971DbhUW/fo67mR71rHvVuObTe@FHbxEd9U4ODnIFkiIdn8P80BTOuNAVzI0NDY0NDAA "APL (Dyalog Extended) – Try It Online")
Creates two lists of digits and check if they are equal.
## Explanation
```
{⍵=10⊥⌽⍵|⍨1↓⍳1+≢⍕⍵} ⍵ → input
≢⍕⍵ length of ⍵ as a string
1+ +1
‚ç≥ range from 1 to that
1‚Üì Drop first element
‚çµ|‚ç® ‚çµ mod each element in range
‚åΩ reversed
10‚ä• converted from base 10
‚çµ= equals the input?
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes
```
n->Vecrev(s=digits(n))==[n%d|d<-[2..#s+1]]
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y4sNbkotUyj2DYlMz2zpFgjT1PT1jY6TzWlJsVGN9pIT0@5WNswNvZ/Wn6RRh5Qj6GOgqGBgY5CQVFmXglQRElB1w5IpIE0av4HAA "Pari/GP – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~66 60 58~~ 57 bytes
* Thanks to @Leaky nun for 6 bytes: remove unneeded `x and` (shouldnot check for 0)
* Thanks to @Einkorn Enchanter for 1 byte: use of `enumerate`
```
lambda x:all(a==`x%(i+2)`for i,a in enumerate(`x`[::-1]))
```
[Try it online!](https://tio.run/##HYrRCsIwDADf/Yq8CAkquD0G@iUqNGKrgS4bpUL9@sztng7ull/7zDZ6DncvMj1fAp2lFJQQYj@inkaKea6gZwE1SPadUpWWMPZ4Y74MDyLfhy1XsXfC4bpDfADNkFGJYalq7W/uKw "Python 2 – Try It Online")
[Answer]
# Python 3: 63 Bytes
```
lambda m:all(int(x)==m%(n+2)for n,x in enumerate(str(m)[::-1]))
```
If I could count the number of times I wished 'enumerate' were shorter...
[Try it online!](https://tio.run/##FctBCoAgEADAr@wl2KWCrJvgS6KDkVHgrqIG9Xqr4xwmPuUIMtWajbe8bhZYW@/xlII3GcMNSjsS7CGBdDecAk4udskWh7kkZJq17tVCVGP6V0alBvXxBQ "Python 3 – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 60 bytes
```
n->{int m=2,r=0,t=1;for(;n>=t;t*=10)r+=n%m++*t;return r==n;}
```
[Try it online!](https://tio.run/##bVBNa9tAEL37VwwBgxQpYld2Uoi6gR566CGh4GPIYS2v03WtkZgdpRij3@6OPoJC2oWd2Z2PN@/Nwb7Zm7pxeNj9vjTt9uhLKI82BHi0HuG8AJiigS2Le6v9DirJRRsmj6/PL2DpNcRDKcBB8LKW/THbt1iyrzH7gfyT3M6Xlh00YC5483D2yFCZPCWjUja62NcUFfhguOBro1VMicFllSTXXJDjlhDIGCy6CwynWAzTBEXmCzNPpQ3uqa22jgIYQPdnTJ51ClqlkMvVWvU/nQ92pcWtxtha5X3RavLru1ypvuN2PRV8yacGnauhqCsGAkIbol4L3v9D430lAJtTYFdldctZIzvjfXS11CrcwzIs8SoFTKHJ2AWOMI5H4O4TvKwIEL6Klv7IO0lmfL@HaF78NyJ7CtnWo6XTxlkqf0WfucnMWNDUjDGizDQ@JP4r4DtRTaJAdIwaJuIz@Xff227RXf4C "Java (OpenJDK 8) – Try It Online")
A non-string version.
[Answer]
## Java 8, 156 149 bytes
```
interface B{static void main(String[]s){String f="";for(int i=1;i<=s[0].length();)f=new Long(s[0])%++i+f;System.out.print(f.equals(s[0]));}}
```
Ungolfed :
```
interface B {
static void main(String[] s) {
String f = "";
for (int i = 1; i <= s[0].length();)
f = new Long(s[0]) % ++i + f;
System.out.print(f.equals(s[0]));
}
}
```
[Try it Online !](https://tio.run/##LYyxDoIwFEV/pSExaUNsrA4OtYubMyNhaOAVi9Bi@8AYwrdXjG4nueeeTs9670dwXfNIyTqEYHQN5LpE1GhrMnvbkEFbRwsM1rVlFdnyQ2JUlknjA91@xCoh7UXF8lDxHlyLd8okM4o6eJHbFm4h0O/K2I7muWW5kcU7IgzcT8jHrYi9o4bDc9J9/KtyXVNK56MQJyE@)
**UPDATE :**
*-7 bytes* : removed useless `{}` and replaced `Integer.parseInt(...)` by `new Integer(...)`
*-9 bytes* : thanks to Kevin Cruijssen, removed a bunch of useless `()`, used `Long` instead of `Integer` and `print` instead of `println`. Thanks Kévin !
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 15 bytes
```
⌊Eθ⁼ιI﹪Iθ⁻⁺¹Lθκ
```
[Try it online!](https://tio.run/##JcrBDkAwEATQX@lxJZVocHIUNxK/sEForFZV/f7aMIfJJG@mDa/JIzGPl3U3DNbZIx0w4AlBqy4kpAhWqxajqJ8Tefh2yLSSd4owkpTRql/cem8CInv2p2Guq9KYwnD@cB7pBQ "Charcoal – Try It Online") Outputs `-` for a staircase number, nothing otherwise. Link is to verbose version of code.
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
f n=foldr(\(k,_)a->10*a+mod n k)0(zip[2..]$show n)==n
```
[Try it online!](https://tio.run/##HcHBCoMwDADQX8nBQ7vNorvt0P2IkxHUzNKYllYY@PFmsPdWrHFhViUQT4nnYl4m3t4W22ffXfC6pRkEou3MEfJwd25s6pq@INZ70Q2DgIdcguzQAAXelwIEQ@/c42/UcyLGT9V2yvkH "Haskell – Try It Online")
[Answer]
## Python 2, 61 bytes
```
lambda x:[`x%(n+2)`for n in range(len(`x`))][::-1]==list(`x`)
```
[Answer]
# q/kdb+, 34 bytes
**Solution:**
```
{s~raze($)x mod'2+(|)(!)(#)s:($)x}
```
**Example:**
```
q){s~raze($)x mod'2+(|)(!)(#)s:($)x}7211311 / this is a staircase number (true)
1b
q){s~raze($)x mod'2+(|)(!)(#)s:($)x}7211312 / this is not (false)
0b
q)t(&){s~raze($)x mod'2+(|)(!)(#)s:($)x}each t:1 + til 1000000 / up to a million
1 10 20 1101 1121 11311 31101 40210 340210
```
**Explanation:**
Cast the input number to a string, count from 0..length of string, add 2 to all, reverse it and feed each number into `mod` along with the original input. Cast the result of the mod to a string and reduce the list, check if it is equal to the string of the input number:
```
{s~raze string x mod'2 + reverse til count s:string x} / ungolfed solution
{ } / lambda function
s:string x / convert input to string, save as s
count / return length of this string
til / like python's range() function
reverse / reverses the list
2 + / adds two to each element in the list
x mod' / ' is each both, so feeds x, and each element of the list to modulo function
string / converts output list to string list ("7";"2";"1"..etc)
raze / reduce list ("721...")
s~ / is s equal to this reduced list, returns boolean
```
**Notes:**
Most of the solution is for generating the `2,3,4..` list, I have another solution that does less stuff, but winds up being 37 bytes after golfing:
```
{s~x mod'reverse 2 + til count s:("J"$) each string x} / ungolfed
{s~x mod'(|)2+til(#)s:("J"$)each($)x} / golfed
```
[Answer]
## Clojure, 75 bytes
```
#(=(sort %)(sort(map(fn[i c](char(+(mod(Integer. %)(+ i 2))48)))(range)%)))
```
Input is a string, using `map` and the trailing `%` ended up being shorter than `for[i(range(count %))]` approach.
[Answer]
# Haskell, 62 bytes
`f x=and$zipWith(==)(reverse$show x)$map(head.show.mod x)[2..]`
Instead of reversing the (infinite) list of moduli, it truncates the list by zipping it with the reversed string-respresentation of the integral x, which it then ensures is equal element-wise.
[Answer]
# [Perl 5](https://www.perl.org/), 41 bytes
39 bytes of code + 2 flags `-pa`
```
map{$\||=$_!=$F[0]%++$n}0,reverse/./g}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaJaamxlYlXtFWxS3aIFZVW1slr9ZApyi1LLWoOFVfTz@9tvr/f3MjQ0NjQ8N/@QUlmfl5xf91fU31DAwN/usWJAIA "Perl 5 – Try It Online")
Outputs nothing (undef) for staircase numbers, 1 for anything else
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L332), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
mækî)%Ñ
```
Input as a string.
[Try it online.](https://tio.run/##y00syUjPz0n7/z/38LLsw@s0VQ9P/P9fyVCJS8nQAEgYgQhDQwOwgKERhDI2BNHGUGETAyOwUmMYw8TMyMAArNHUBKbI3AimzdDIAKbQCKQEREOsM4CQYCMMDeG0IdgZED0A)
**Explanation:**
```
m # Map over each character of the (implicit) input-string,
æ # using the following four characters as inner code-block:
# (implicitly push the current character of the map)
k # Push the input as an integer
î # Push the 1-based map-index
) # Increase it by 1
% # Take the input-integer modulo (1-based) index+1
# After the map, the digits are implicitly joined together to a string
Ñ # Check that this string is a palindrome
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [Arturo](https://arturo-lang.io), 42 bytes
```
$[n][1every? reverse digits n'x->x=n%<=1+]
```
[Try it](http://arturo-lang.io/playground?Ng8O9j)
] |
[Question]
[
This challenge was posted on the DailyProgrammer subreddit, and I figured it would be a great candidate for a code golf challenge. Determining if a letter balances is based on its distance from the point of balance, and the letter's value. The value of a letter can be determined by either taking its one-indexed position in the alphabet, or by subtracting 64 from its ASCII value. Furthermore, the value of a letter is multiplied by its distance from the balance point. Let's take a look at an example, `STEAD`:
```
STEAD -> 19, 20, 5, 1, 4 ASCII values
This balances at T, and I'll show you why!
S T EAD -> 1*19 = 1*5 + 2*1 + 3*4
Each set of letters on either side sums to the same value, so
T is the anchor.
```
However, it should be noted that not all words balance. For example, the word `WRONG` does not balance in any configuration. Also, words must balance on a letter, not between two letters. For example, `SAAS` would balance if there was a letter in the middle of the two `A`s, but since there is none it does not balance.
# The Task
You should create a *program or function* that takes in an **uppercase word** as *input or function arguments*, and then produces one of two outputs:
1. If the word balances, then the word should be printed with the left side, a space, the anchor letter, another space, and the right side.
`function (STEAD) -> S T EAD`
2. If the word does not balance, you should print out the word, followed by `DOES NOT BALANCE`
`function (WRONG) -> WRONG DOES NOT BALANCE`
You may assume that all input will be uppercase and there will only be alpha characters.
# Example I/O
```
function (CONSUBSTANTIATION) -> CONSUBST A NTIATION
function (WRONGHEADED) -> WRO N GHEADED
function (UNINTELLIGIBILITY) -> UNINTELL I GIBILITY
function (SUPERGLUE) -> SUPERGLUE DOES NOT BALANCE
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# Pure bash (no coreutils or other utilities), 125
Standard center of mass calculation using moments about the origin:
```
for((;i<${#1};w=36#${1:i:1}-9,m+=w,M+=w*++i)){ :;}
((M%m))&&echo $1 DOES NOT BALANCE||echo ${1:0:M/m-1} ${1:M/m-1:1} ${1:M/m}
```
### Test output:
```
$ for t in \
> STEAD \
> CONSUBSTANTIATION \
> WRONGHEADED \
> UNINTELLIGIBILITY \
> SUPERGLUE
> do ./wordbal.sh $t; done
S T EAD
CONSUBST A NTIATION
WRO N GHEADED
UNINTELL I GIBILITY
SUPERGLUE DOES NOT BALANCE
$
```
[Answer]
## Python 3, 124
```
w=input()
i=a=b=0
for c in w:n=ord(c)-64;a+=n;b+=n*i;i+=1
m=b//a
print(*[w[:m],w,w[m],"DOES NOT BALANCE",w[m+1:]][b%a>0::2])
```
This code doesn't test potential fulcrums, but rather finds the "center of mass" and checks if it's an integer. It does so by summing the total mass `a` and the position-weighted mass `b`, to find the center of mass `m=b/a`. It then prints either the string split at position `m`, or the string plus `"DOES NOT BALANCE"`, chosen by the `[_::2]` list-slicing trick.
[Answer]
# CJam, 57 bytes
```
l_,,_f{f-W$'@fm.*:+}0#:I){ISIW$=S++t}" DOES NOT BALANCE"?
```
This can still be golfed a bit.
[Try it online here](http://cjam.aditsu.net/#code=l_%2C%2C_f%7Bf-W%24'%40fm.*%3A%2B%7D0%23%3AI)%7BISIW%24%3DS%2B%2Bt%7D%22%20DOES%20NOT%20BALANCE%22%3F&input=UNINTELLIGIBILITY)
[Answer]
## JavaScript (ES6), ~~211~~ ~~200~~ 160 bytes
```
f=w=>{for(j=-w.length;j++;)if(![...w].reduce((p,v,i)=>p+(parseInt(v,36)-9)*(j+i),0))return w.slice(0,-j)+` ${w[-j]} `+w.slice(1-j);return w+` DOES NOT BALANCE`}
```
---
Previous attempt, 200 bytes
Thanks to edc56 and nderscore for helping me golf this
```
f=w=>{for(j=0,r=(a,z)=>[...a][z||`reverse`]().reduce((p,v,i)=>p+(parseInt(v,36)-9)*++i,0);j++<w.length;)if(r(a=w[s=`slice`](0,j))==r(b=w[s](j+1),s))return a+` ${w[j]} `+b;return w+` DOES NOT BALANCE`}
```
### Demo
Firefox and Edge only for now, as it is ES6
```
f=w=>{for(j=1-w.length;j++;)if(!([...w].reduce((p,v,i)=>p+(parseInt(v,36)-9)*(j+i),0)))return w.slice(0,-j)+` ${w[-j]} `+w.slice(1-j);return w+` DOES NOT BALANCE`}
// DEMO
console.log = function(a) {
document.body.innerHTML += a + "<br>";
}
console.log(f('STEAD'));
console.log(f('CONSUBSTANTIATION'));
console.log(f('WRONGHEADED'));
console.log(f('UNINTELLIGIBILITY'));
console.log(f('SUPERGLUE'));
```
[Answer]
# Pyth, 49 bytes
```
jd.xcz,Jhf!s*Vm-Cd64zr_TlzUzhJ,z"DOES NOT BALANCE
```
[Demonstration.](https://pyth.herokuapp.com/?code=jd.xcz%2CJhf!s*Vm-Cd64zr_TlzUzhJ%2Cz%22DOES%20NOT%20BALANCE&input=CONSUBSTANTIATION&debug=0)
Explanation:
```
jd.xcz,Jhf!s*Vm-Cd64zr_TlzUzhJ,z"DOES NOT BALANCE
Implicit: z = input(), d = ' '
f Uz Filter T over range(len(z)).
m z Map the characters in z to
-Cd64 their ASCII values - 64.
*V Vectorized multiplication by
r_Tlz range(-T, len(z)).
This is equivalent to putting the fulcrum at T.
s Sum the weights.
! Logical not - filter on sum = 0.
h Take the first result.
This throws an error if there were no results.
J Save it to J.
,J hJ Form the list [J, J+1].
cz Chop z at those indices,
before and after the fulcrum.
.x If no error was thrown, return the above.
,z".. If an error was thrown, return [z, "DOES N..."]
jd Join the result on spaces and print.
```
[Answer]
# C, ~~236~~ ~~198~~ ~~192~~ ~~188~~ ~~180~~ 173 bytes
```
a,i,j,k,L;f(char*s){L=strlen(s);for(;i<L;i++){for(a=j=0;j<L;j++)a+=(s[j]-64)*(i-j);if(!a)break;}for(;k<L;k++)printf(k-i?"%c":" %c ",s[k]);if(a)printf(" DOES NOT BALANCE");}
```
Expanded with main():
```
#define p printf
a,i,j,k,L;
f(char*s)
{
L=strlen(s);
for(;i<L;i++){
for(a=j=0;j<L;j++)
a+=(s[j]-64)*(i-j);
if(!a)
break;
}
for(;k<L;k++)
printf(k-i?"%c":" %c ",s[k]);
if(a)
printf(" DOES NOT BALANCE");
}
// 83 bytes below
int main(int argc, char **argv)
{
f(argv[1]);
printf("\n");
}
```
Verification:
```
$ ./a.out CONSUBSTANTIATION
CONSUBST A NTIATION
$ ./a.out WRONGHEADED
WRO N GHEADED
$ ./a.out A
A
$ ./a.out WRONG
WRONG DOES NOT BALANCE
$ ./a.out SUPERGLUE
SUPERGLUE DOES NOT BALANCE
```
[Answer]
# CJam, 50 bytes
```
r_'@f-_ee::*:+\:+md"X DOES NOT BALANCEX"@?)/()@]S*
```
Using the Java interpreter, this exits with an error to STDERR for non-balancing words.
If you try the code in the [CJam interpreter](http://cjam.aditsu.net/#code=r_'%40f-_ee%3A%3A*%3A%2B%5C%3A%2Bmd%22X%20DOES%20NOT%20BALANCEX%22%40%3F)%2F()%40%5DS*&input=WRONGHEADED), just ignore everything but the last line of output.
### Idea
My "original idea" turned out to be the same approach [@xnor posted](https://codegolf.stackexchange.com/a/52772) several hours before me. Nevertheless, here it goes:
Given a list of values **(v0, … vn)**, we have that **v\_t** is the anchor of the list if and only if any of the following, equivalent conditions holds:
* **tv0 + … + 1vt-1 == 1vt+1 + … tvn**
* **(0 - t)v0 + … + (n - t)vn == 0**
* **0v0 + … + nvn == t(v0 + … + vn)**
* **t := (0v0 + … + nvn)/(v0 + … + vn)** is an integer.
### Code
```
r e# Read a whitespace separated token from STDIN.
_'@f- e# Push a copy and subtract '@' from each char (pushes code point - 64).
_ee e# Push a copy of the array of values and enumerate them.
::* e# Multiply each value by its index.
:+ e# Add all results.
\:+ e# Add the unmodified values.
md e# Perform modular division. Pushes quotient and residue.
"X DOES NOT BALANCEX"
@ e# Rotate the quotient on top of the string.
? e# If the residue is 0, select the quotient. Otherwise, select the string.
```
At this part, we start having a little fun with overloaded operators.
For the quotient, this happens:
```
) e# Add 1 to the quotient.
/ e# Split the input string into chunks of that length.
( e# Shift out the first chunk.
) e# Pop the last character of the first chunk.
@ e# Rotate the rest of the string on top of the stack.
]S* e# Wrap all three parts in an array and join them, separating by spaces.
```
For the string, this happens:
```
) e# Pop out the last char: "X DOES NOT BALANCE" 'X'
/ e# Split the remainder at X's: ["" " DOES NOT BALANCE"]
( e# Shift out the first chunk: [" DOES NOT BALANCE"] ""
) e# Pop out the last char.
```
At this point, a runtime error happens, since `""` does not have a last char. The stack gets printed and executing is aborted immediately.
[Answer]
# Julia, 122 bytes
```
s->(v=[int(i)-64for i=s];m=dot(v,1:length(s))/sum(v);m==int(m)?join([s[1:m-1],s[m],s[m+1:end]]," "):s*" DOES NOT BALANCE")
```
This creates an unnamed function that accepts a string as input and returns a string. To call it, give it a name, e.g. `f=s->...`.
We treat the word like a one-dimensional system for which we need to find the center of mass. The center of mass is computed as the dot product of the masses with their locations, divided by the total mass of the system. If the computed center is an integer, it corresponds to one of the letters in the word. Otherwise the word doesn't balance.
Ungolfed + explanation:
```
function f(s)
# Create a vector of ASCII code points -- these are the "masses"
v = [int(i)-64 for i in s]
# Compute the center of mass, taking the locations to be the indices
m = dot(v, 1:length(s)) / sum(v)
# Check whether the center corresponds to a letter's position
if m == int(m)
join([s[1:m-1], s[m], s[m+1:end]], " ")
else
m * " DOES NOT BALANCE"
end
end
```
Examples:
```
julia> f("WRONG")
"WRONG DOES NOT BALANCE"
julia> f("STEAD")
"S T EAD"
julia> f("CONSUBSTANTIATION")
"CONSUBST A NTIATION"
```
[Answer]
## PHP, ~~249~~ 174 bytes
Takes one command-line argument.
```
<?for($i=-$l=strlen($w=$argv[1]);$i++;){for($k=$q=0;$l>$k;)$q+=($i+$k)*(ord($w[$k++])-64);$q?:exit(substr($w,0,-$i)." {$w[-$i]} ".substr($w,1-$i));}echo"$w DOES NOT BALANCE";
```
---
Initial attempt:
```
<?function r($a){for($i=$q=0;strlen($a)>$i;){$q+=(ord($a[$i])-64)*++$i;}return$q;}for($i=0;$i++<strlen($w=$argv[1]);)(strlen($w)<2?exit($w):(r(strrev($a=substr($w,0,$i)))==r($b=substr($w,$i+1)))?exit("$a {$w[$i++]} $b"):0);echo"$w DOES NOT BALANCE";
```
[Answer]
# Haskell, ~~161~~ 135 bytes
```
a#b=a*(fromEnum b-64)
v=sum.zipWith(#)[1..]
h![]=h++" DOES NOT BALANCE"
h!(x:y)|v(reverse h)==v y=h++' ':x:' ':y|1<2=(h++[x])!y
f=([]!)
```
Usage example:
```
*Main> putStr $ unlines $ map f ["CONSUBSTANTIATION","WRONGHEADED","UNINTELLIGIBILITY","SUPERGLUE"]
CONSUBST A NTIATION
WRO N GHEADED
UNINTELL I GIBILITY
SUPERGLUE DOES NOT BALANCE
```
How it works: `f` calls the helper function `!` which takes two parameters, the left and right part of the word at a given position. It stops if both parts have equal weight (function `v`) or calls itself recursively with the first letter of the right part moved to the left. It ends with the `DOES NOT BALANCE` message if the right part is empty.
[Answer]
# C, 183 134 bytes
```
h,i,a=1;c(char*s){for(;s[i++]&&a;)for(a=h=0;s[h];)a+=(s[h]-64)*(h++-i);printf(a?"%.*s DOES NOT BALANCE":"%.*s %c %s",i,s,s[--i],s+i);}
```
New Version Explained:
Like the other two entries, it makes use of constant addition on one side and subtraction on the other to hopefully reach zero which is the indication of balance. My original output is reused from the first answer, albeit slightly modified.
```
l,h,i,a,b;c(char*s){for(l=strlen(s);h++<l&&(a^b|!a);)for(i=a=b=0;i<l;i++)i==h?a=b,b=0:(b+=(s[i]-64)*abs(i-h));printf(a==b?"%.*s %c %s":"%.*s DOES NOT BALANCE",a==b?h:l,s,s[--h],s+h);}
```
Old Version Explained:
The first loop (h) is the main iterator for the length of the string. The second loop (i) accumulates (b) until h==i. Once that happens, (b) is stored in (a), reset to 0, and then continues until the end of the string is reached where (a) is compared to (b). If there's a match, the main iterator's loop is broken and the output is printed.
[Answer]
# Ruby 175
```
F=->s{v=->s{(0...s.size).map{|i|(i+1)*(s[i].ord-64)}.inject :+}
r="#{s} DOES NOT BALANCE"
(0...s.size).map{|i|b,a=s[0...i],s[i+1..-1]
v[b.reverse]==v[a]&&r=b+" #{s[i]} "+a}
r}
```
Test it online: <http://ideone.com/G403Fv>
This is a pretty straightforward Ruby implementation. Here's the readable program:
```
F=-> word {
string_value = -> str {
(0...str.size).map{|i|(i+1) * (str[i].ord - 64)}.inject :+
}
result = "#{word} DOES NOT BALANCE"
(0...word.size).map {|i|
prefix, suffix = word[0...i], word[i+1..-1]
if string_value[prefix.reverse] == string_value[suffix]
result = prefix + " #{word[i]} " + suffix
end
}
result
}
```
[Answer]
# R, 190 bytes
As an unnamed function. I think I can get a few more, but that'll have to wait.
```
function(A){D=colSums(B<-(as.integer(charToRaw(A))-64)*outer(1:(C=nchar(A)),1:C,'-'));if(!length(E<-which(B[,D==0]==0)))cat(A,'DOES NOT BALANCE')else cat(substring(A,c(1,E,E+1),c(E-1,E,C)))}
```
Ungolfed a bit with brief explanation
```
function(A){
D=colSums( #column sums of the outer function * character values
B<-(
as.integer(charToRaw(A))-64) # character values
* outer(1:(C=nchar(A)),1:C,'-') # matrix of ranges eg -3:2, -1:4, etc
)
if(!length(
E<-which(B[,D==0]==0) # where the colsum = 0, get the index of the zero
))
cat(A,'DOES NOT BALANCE')
else
cat(substring(A,c(1,E,E+1),c(E-1,E,C))) #cat the substrings
}
```
It doesn't put a newline at the end.
Test run
```
> f=
+ function(A){D=colSums(B<-(as.integer(charToRaw(A))-64)*outer(1:(C=nchar(A)),1:C,'-'));if(!length(E<-which(B[,D==0]==0)))cat(A,'DOES NOT BALANCE')else cat(substring(A,c(1,E,E+1),c(E-1,E,C)))}
>
> f('CONSUBSTANTIATION')
CONSUBST A NTIATION
> f('WRONGHEADED')
WRO N GHEADED
> f('UNINTELLIGIBILITY')
UNINTELL I GIBILITY
> f('SUPERGLUE')
SUPERGLUE DOES NOT BALANCE
>
```
[Answer]
# C, 142 bytes
Credit to **some user** for beating me to it :)
```
i,l=1,j;g(char*v){for(;v[i]&&l;++i)for(j=l=0;v[j];++j)l+=(i-j)*(v[j]-64);printf(l?"%.*s DOES NOT BALANCE":"%.*s %c %s",l?i:--i,v,v[i],v+i+1);}
```
[Answer]
## Java, 240 bytes
```
String b(String s){for(int i=-1,a=s.length(),l=0,r,m;++i<a;){for(r=i;--r>=0;l+=(s.charAt(r)-64));for(m=r=0;++m+i<a;r+=(s.charAt(m+i)-64)*m);if(l==r)return s.substring(0,i)+" "+s.charAt(i)+" "+s.substring(i+1);}return s+" DOES NOT BALANCE";}
```
] |
[Question]
[
Disclaimer: This challenge is inspired by a coding error I once made.
---
Okay, time for a maths lesson. A normal mean average looks like this:
```
Work out the sum of all numbers in a list
then divide by the size of the list.
```
But what if we don't know all the numbers at the time we're working out the average? We need a way to work out the average which can be added to over time. For this reason, I present the algorithm for a Progressive Mean™
```
The running total is the first number in the list
For each of the remaining numbers
Add the number to the running total
Divide the running total by two
```
So in effect we're averaging each number with the current average. (We could add to this later and get the same result)
**BUT**
This doesn't give the same result at all. It gives an average, but it differs from the standard methodology for finding the mean. Now the order of the list of numbers is significant.
Of course, being a curious type, I want to work out if the Progressive Mean™ tells us anything about the order of our list of numbers. So for this reason I want to compare Mean with Progressive Mean™ by means of a simple subtraction:
```
trend = Progressive Mean™ - Standard Mean
```
---
# The Challenge
* Write a piece of code which accepts a list of numbers (in any format) which then calculates three pieces of information about it:
+ Standard Mean
+ Progressive Mean™
+ Trend (Progressive - standard)
* Work in any language you like.
* It's golf, attempt to do the challenge in as few bytes as you can.
* Avoid Standard Loopholes
* I want the output to be human-readable numbers.
* Please include a link to an online interpreter such as tio.run
---
Test Cases:
```
[1,2,3]
Normal Mean: 2.0
Progressive Mean: 2.25
Trend: 0.25
```
```
[3, 2, 1]
Normal Mean: 2.0
Progressive Mean: 1.75
Trend: -0.25
```
```
[10, 20, 30]
Normal Mean: 20.0
Progressive Mean: 22.5
Trend: 2.5
```
```
[300, 200, 100]
Normal Mean: 200.0
Progressive Mean: 175.0
Trend: -25.0
```
```
[10, 100, 10]
Normal Mean: 40.0
Progressive Mean: 32.5
Trend: -7.5
```
```
[4, 4, 9, 8, 1, 8, 6, 9, 1, 1]
Normal Mean: 5.1
Progressive Mean: 2.62890625
Trend: -2.4710937499999996
```
```
[1, 1, 1, 4, 4, 6, 8, 8, 9, 9]
Normal Mean: 5.1
Progressive Mean: 8.5390625
Trend: 3.4390625000000004
```
```
[9, 9, 8, 8, 6, 4, 4, 1, 1, 1]
Normal Mean: 5.1
Progressive Mean: 1.47265625
Trend: -3.6273437499999996
```
[Answer]
# [R](https://www.r-project.org/), 57 bytes
```
function(v,`!`=sum,N=!1^v)c(A<-!v/N,P<-!v/2^c(N:1,N),P-A)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jTCdBMcG2uDRXx89W0TCuTDNZw9FGV7FM308nAEwbxSVr@FkZ6vhp6gToOmr@T9MwtDLW5ErTSNYw0VEAIksdBQsdBUMwaQbmAtmGmiAlhpr/AQ "R – Try It Online")
A clever collaboration with digEmAll and RobinRyder; uses the observation by [Grimmy](https://codegolf.stackexchange.com/a/198894/67312) and Kevin's explanation from the comments, which I replicate below:
>
> For anyone else wondering why the example `[a,b,c,d] -> [a,b,c,c,d,d,d,d]` doesn't match the explanation of the code, it actually transforms `[a,b,c,d]` to `[a,b,b,c,c,c,c,d,d,d,d,d,d,d,d,a]` (so two of each value in comparison to the example). The example confused me for a moment. But nice answer, +1 from me! I also like that it has all these different types of the letter 'A' in the code: `āÅÅAÂƪ`. xD
>
>
>
This uses R's recycling rules to use two copies of `l[1]/2^N` in the sumby just sticking an extra `N` at the end of the decay rate.
# [R](https://www.r-project.org/), 62 bytes
```
function(l)c(p<-Reduce(function(x,y)(x+y)/2,l),a<-mean(l),p-a)
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jRzNZo8BGNyg1pTQ5VQMuXKFTqalRoV2pqW@kk6Opk2ijm5uaCFKtU6CbqPk/TcPQyliT6z8A "R – Try It Online")
Straightforward implementation.
[Answer]
# [J](http://jsoftware.com/), 17 bytes
Translation of [this](https://codegolf.stackexchange.com/a/198889/43319).
```
-:@+/@|.(,,-)+/%#
```
Anonymous tacit prefix function. Returns list of Progressive Mean™, Standard Mean, Trend.
[Try it online!](https://tio.run/##JYtRCoAwDEP/PUVABMWp7SZjE4SdZh@ewbtrupGPpC/p8331vrBdZT3Ku8/Obct6TCMxFB5hqAh0pavAC4IYEstCJL3QdjCfVEbic0Jk0v7aZF0kT@SZNLel7axpmx8 "J – Try It Online")
This consists of three parts: `(2÷⍨+)⌿∘⌽` `(,,-)` `+⌿÷≢`
`+/ % #` is the sum divided by the number of elements
…`⌿@|.` reverses the list and then reduces from right to left using the function:
`-:@+` add next value to previous value and halve that
`(,,-)` is the concatenation of the PM and the SM, concatenated to their difference
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 70 69 bytes
-1 byte thanks to [Kyle Gullion](https://codegolf.stackexchange.com/users/32604/kyle-gullion)
returns `(mean, p_mean, trend)`
```
lambda x:(m:=sum(x)/len(x),[p:=x[0],*[p:=(p+n)/2for n in x]][-1],p-m)
```
[Try it online!](https://tio.run/##VcrBCsMgDAbg@54ix7hZqvUyBJ/EeejYZIWaBteBe3pnexj0kPzh@8Pf9bWQuXKuERzc6jym@2OEYjFZ9/4kLKKfn9RCeraueBXkebuQLyT6IS4ZCCaCEoLvdJDcJVE5T7RiRK8lDBJMEOL0N7ObPphWDdsYdXxVu7el1dbUHw "Python 3.8 (pre-release) – Try It Online")
Alternate version with more of a reducer implementation (89 bytes):
```
lambda x:(m:=sum(x)/(l:=len(x)),[x:=[sum(x[0:2])/2]+x[2:]for n in range(l-1)][-1],x[0]-m)
```
Although this is longer, I suspect this reducer implementation may be useful for future python 3.8 code golfing.
[Try it online!](https://tio.run/##VcpNCsMgEAXgfU8xS4ca4s@mCJ7EziKlsQ2oEZuCPb21WRSyeMPjm5c/23NN@pJL82Dh2sIUb/cJqmHR2Nc7soojC8aGOfWK3FVj3e5OGEU4KjpXpwz5tUCCJUGZ0mNmYZBIbpDE@5CGiC2XJW3MMyc5KA6aEE9/07vJg0nRsUeL41Ts3o8Uv0/7Ag "Python 3.8 (pre-release) – Try It Online")
I know there has to be some more clever tricks to golf this further...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅAIÅ»+;}θ‚Âƪ
```
Outputs as a triplet `[mean, progressive-mean, trend]`.
[Try it online](https://tio.run/##yy9OTMpM/f//cKuj5@HWQ7u1rWvP7XjUMOtw0@G2Q6v@/4820VEAIksdBQsdBUMwaQbmAtmGsQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w62OlYdbD@3Wtq49t@NRw6zDTYfbDq36r/M/OtpQx0jHOFYn2hhIGwJpQwMdIwMdYwOQkAGIbaBjaGAAkTAEc4BsEx0THUsdCx1DIDYDsgwhWkG0DkjODChuARS3BIpaglWC1IFkwGpiYwE).
**Explanation:**
```
ÅA # Calculate the arithmetic mean of the (implicit) input-list
I # Push the input-list again
Å» # Left-reduce it by:
+ # Add the two values together
; # And halve it
}θ # After the reduction, leave only the last value
‚ # Pair it with the earlier calculated arithmetic mean
 # Bifurcate this pair; short for Duplicate & Reverse copy
Æ # Reduce it by subtraction
ª # And append this trend to the pair
# (after which the result is output implicitly)
```
[Answer]
# Scratch 2.0/3.0, 35 blocks/263 bytes
[![Blocks](https://i.stack.imgur.com/xBbNb.png)](https://i.stack.imgur.com/xBbNb.png)
SB Syntax:
```
when gf clicked
set[i v]to(2
set[L v]to(length of[I v
set[T v]to(item(1)of[I v
set[P v]to(T
repeat((L)-(1
change[T v]by(item(i)of[I v
change[P v]by(item(i)of[I v
set[P v]to((P)/(2
change[i v]by(1
end
set[T v]to((T)/(L
say(join(join(join(join(P)[,])(T))[,])((P)-(T
```
It's accidentally a polyglot. I accidentally forgot my password and email for my other scratch account so I had to make a new one so y'all can [Try it on Scratch!](https://scratch.mit.edu/projects/364915100/)
Y'all need to change the input list shown in the top left corner on the project for this to work properly.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~81~~ \$\cdots\$ ~~75~~ 71 bytes
Saved ~~1~~5 bytes thanks to [Reinstate Monica](https://codegolf.stackexchange.com/users/85755/reinstate-monica)!!!
```
def f(l):
m=sum(l)/len(l);p=l[0]
for n in l:p=(p+n)/2
return m,p,p-m
```
[Try it online!](https://tio.run/##ZY1BCsMgEEX3nmKWSi3RGEpMyUlCdo00oEZssujp7aA0IIFx1DfPb/ju782rlF6LAUMtGwi48XM4PDZ28bg9w2gnMRMwWwQPqwc7hJGGm2dNSyAu@xE9OB54uLsU4up3augkObQc1MwYOZnKTFZMCoS4lKhVkTk2KcTlgSyDinccsDSHHke5P/JVXn4sLOtdtvpc6OpK1P@4klV0eSamHw "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), 55 bytes
Returns `[mean, p_mean, trend]`.
```
a=>a.map(v=>t=(s+=v,n++)?(t+v)/2:v,n=s=0)&&[s/=n,t,t-s]
```
[Try it online!](https://tio.run/##dY7RCoMgFIbv9xRehaKVVowanPYg0YW0GhvNYoqv70TZLobB8cDh@78fn9JKPb0fu8nVdpvdAk5CL4uX3LGF3gDWFCxTlJIrNtSSsrr4EzRwkmWDLkExw0yuRzdtSm/rXKzbHS94EAxVDNUjIac/UgciEkRwj/yreUrjgfolOD@QRcQJ2jDkp2Oo9YGwz@EUBz@JJEhNyLZhvNEl4t23OvZGSfza3Qc "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
āÍoîÅΓ‚ÅAÂƪ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//SOPh3vzD6w63npv8qGHW4VbHw02H2w6t@v8/2kRHAYgsdRQsdBQMwaQZmAtkG8YCAA "05AB1E – Try It Online")
The progressive mean is equivalent to a weighted arithmetic mean, with exponentially increasing weights. For example, the progressive mean of a 4 element list `[a, b, c, d]` is the arithmetic mean of `[a, b, c, c, d, d, d, d]`.
```
ā # range [1..length of input]
Í # subtract 2 from each
o # 2**each: [0.5, 1, 2, ...]
î # round up: [1, 1, 2, ...]
ÅΓ # run-length decode
‚ # pair with the input
ÅA # arithmetic mean of each list
 # push a reversed copy
Æ # reduce by subtraction
ª # append
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~20~~ 18 [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")
-2 thanks to Bubbler.
Anonymous tacit prefix function. Returns list of Progressive Mean™, Standard Mean, Trend.
```
(2÷⍨+)⌿∘⌽(,,-)+⌿÷≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X8Po8PZHvSu0NR/17H/UMeNRz14NHR1dTW0gFyjRueh/2qO2CY96@x71TfX0f9TVfGi98aO2iUBecJAzkAzx8Az@n6ZgqGCkYMyVpmAMpA2BtKGBgpGBgrEBSMgAxDYAChlAJAzBHCDbBAgtFSyAmi0UzIAsQ4hWMATJmQHFLYDilkBRS7BKkDqQDFgNAA "APL (Dyalog Unicode) – Try It Online")
This consists of three parts: `(2÷⍨+)⌿∘⌽` `(,,-)` `+⌿÷≢`
`+⌿ ÷ ≢` is the sum divided by the count
`(`…`)⌿∘⌽` reverses the list and then reduces from right to left using the function:
`2÷⍨+` add next value to previous value and divide that by two
`(,,-)` is the concatenation of the PM and the SM, concatenated to their difference
[Answer]
# [Factor](https://factorcode.org/), ~~80~~ 79 bytes
```
: f ( s -- s ) [ mean ] [ dup first [ + 2. / ] reduce ] bi 2dup swap - 3array ;
```
[Try it online!](https://tio.run/##TZBBS8NAEIXv/RXvqMjGTSIlSY8epAeLIJ5KD2s6aRfTNO5MlFL62@MkJVIGljfvezPLbuVKOYb@4325einwRaGhGgcn@4jFiWfxJYPpu6OmJB4JXAjuxGgDiZza4BvBYrZcFXh2ddnVTsjInsxbOO4CMfsfMq/kmr5AhTswjNHjHmsc1MVGxbZrUfnAovoBSYRHtQNtu5JUfHokQ4J/XQuDdLwfi/6MGYAzYiRIcbk2qTbx1MQWiUVq/6EdDKu@vYnEozMZT1o5Ml2SYa4qvlk31hCYK8wU5hPKx5lhYsDX4AUzpWt99UY/rkXU/wE "Factor – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes
```
{a=Mean@#,b=+##/2&~Fold~#,b-a}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@7860dY3NTHPQVknyVZbWVnfSK3OLT8npQ7I102sVfsfUJSZVxKdFl1tqKNgpKNgXBsba80FFzQGCxqiChoaAEWB2NgATbEBWAJIGBoYYGoxhMigSpjoKACRpY6CBVAOTJqBuYaYtkIEwepNwMoswAio2BJVpSXMQIhpEPWGCDP/AwA "Wolfram Language (Mathematica) – Try It Online") Pure function. Takes a list of numbers as input and returns a list of rational numbers as output. I'm pretty sure that improper fractions count as human-readable, but if they aren't, adding `N@` (+2 bytes) to the start causes the function to output approximate numbers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Æm;+H¥/ṄI
```
A full program which accepts a list of decimals which prints:
```
[mean, progressive-mean]
trend
```
**[Try it online!](https://tio.run/##y0rNyan8//9wW661tsehpfoPd7Z4/v//P9pERwGILHUULHQUDMGkGZgLZBvGAgA "Jelly – Try It Online")**
### How?
```
Æm;+H¥/ṄI - Link: list of numbers, A
Æm - arithmetic mean sum(A)/length(A) = mean
/ - reduce (A) by:
¥ - the dyad f(leftEntry, rightEntry):
+ - addition leftEntry + rightEntry
H - halve (leftEntry + rightEntry) / 2 = progressiveMean
; - concatenate [mean, progressiveMean]
Ṅ - print this list and yield it
I - deltas [progressiveMean - mean]
- implicit print (Jelly represents with a single item as the item)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 54 bytes
```
$args|%{$y+=$_;$z=($_+$z)/(2-!$i++)}
($y/=$i)
$z
$z-$y
```
[Try it online!](https://tio.run/##TY/RCoIwGIXv9xQL/nJjv7iphCKD3kS6yDIkRS9CzWdfc7ZqHMbO2fcftq59XvrhdmkaA5WeDZz76/DazzAKDWUBk2ZQCph4xOJwB7UQfCEMxkhDzQlMViGMZiGEQEc1ZUxhjAlHQu1iiTXKGyUxlpjI76VcA4lKyj9EucQHKVKrHGmGVLn96Kw9/3o368jUAZmTxXLP5L5ka9jIzyDn6@PXT5fhva0fAQbFASp6KosgWMwb "PowerShell – Try It Online")
Takes input by splatting. The only neat trick is the `!$i++` bit which negates the first iteration where `$i` is 0 to 1, and all subsequent numbers to 0.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg)(Perl 6), 41 40 bytes
```
{|($/=(.reduce((*+*)/2),.sum/$_)),$0-$1}
```
My original solution had `my \a=`and used `[-]|@a` at the end, but abusing `$/` is always fun, especially with also abusing assignments. Pretty straightforward calculation wise.
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pF31ZDryg1pTQ5VUNDS1tLU99IU0evuDRXXyVe07pGRV9HxUBXxbD2vzVXcWKlQppGtLGOkY5hrOZ/AA "Raku – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 111 109 bytes
```
#define P printf("%f "
f(a,l,i)int*a;{float s=*a++,p=s;for(i=l-1;i--;p+=*a++,p/=2)s+=*a;P,s/=l);P,p);P,p-s);}
```
[Try it online!](https://tio.run/##TY7dCsIwDIXv@xRhIqxby5yIKKHv4L14UWYrhdqVdt449uyzqz8YDgnn5COk47eum@fVVWnjFJzAB@MGXRZrDQXRpWSWGZqiSuKobS8HiKKSdc28iKj7UBpheYuGc/T1Z9OILY2LwROLjbA0TZ8bjxSnmaR7cJfGlZSMBFItgQzhfAEBY8vgrV3WnsEh65g04Y@3yiU6mqfq058hUGj@3HlzoUgynD1b@G8S1PAIDjZIpvkF "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
≔∕ΣθLθη≔§θ⁰ζFθ≔⊘⁺ιζζI⟦ηζ⁻ζη
```
[Try it online!](https://tio.run/##LYzBCsIwEETvfsUeNxBBQUTpqehBQaHgseQQmtgEYkqTtEh/Pm5r4R2Gmcc0Roamky7nMkbberza0SqNr@GDPePw0L5NhiJlw4rNapXp7pX@Ys9hR8tEy7sLQB6sxk26USus3BDRzsaqVcH6hBcZE9aGKg5P68mZ5n/BWJFzXe85/DksHDmcFs6EEHk7uh8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔∕ΣθLθη
```
Calculate the arithmetic mean.
```
≔§θ⁰ζ
```
Start with the first element. We therefore end up averaging this element with itself, but that doesn't affect the final result of course.
```
Fθ≔⊘⁺ιζζ
```
Loop over each element an average it with the progressive mean so far.
```
I⟦ηζ⁻ζη
```
Print the arithmetic and progressive means and their difference.
If we had only needed the result once then `ΣEθ∕ιX²⁻Lθ∨κ¹` could have been used to calculate the progressive mean directly, saving 3 bytes over the naïve method.
[Answer]
# Haskell, 84 bytes
I thought Haskell could do decently here because this challenge works on lists and I tend to think Haskell and lists go well together... But I couldn't come up with anything very clever. Let's see if @xnor drops by and has anything nice :P
```
f(h:l)=g$foldl(\(p,s,w)n->((p+n)/2,s+n,w+1))(h,h,1)l
f[]=f[0]
g(p,s,l)=(s/l,p,p-s/l)
```
I am defining an anonymous function `\(p,s,w) n -> ((p+n)/2, s+n, w+1)` that receives a triplet and the next list element, and does three things: updates the progressive mean, sums the whole list and computes its length. In the end, function `g` does some last-minute calculations.
You can [try it online](https://tio.run/##fY5BDoIwEEX3nGIWLtowQgvEiAmewJ1LZGGipcZaGovh@DgpuizJdKbN/@9P9dU/78bMs2L6YHjTb9RgboZdmEOPE7fbI2MutTwv0KcWp1RyzjRqlNwkqu0a1You6YOdeOZzgw7dliafX9eHhQZuQwLgPuN5fJ8sbMDrYaKhoO1igsyyMiqWWKCMowKhoFOKeIAIHmpSiNUguZiingqBqkbYky30XXjSfeWHix7QKhD7UMTVUaj@r1l2LOgvqZu/ "TIO link with the test cases")
[Answer]
# [PHP](https://php.net/), ~~90~~ 88 bytes
```
function($i){for($j=$i[0];$x=$i[$c++|0];$s+=$x,$j+=$x,$j/=2);return[$s/=$c-1,$j,$j-$s];}
```
[Try it online!](https://tio.run/##VZDRaoMwFIavm6cIci4sptTUMto52RNs7GJ3VorYOC1bIokdha7P7o4ntWxwjP9//u8cQrqmG56eu6ZjDHrlescznrNZLgVfCZ4UAnVCWpKWMRr8kthHMXk8ZBzfAekb5NeCY20F32CLzgey8r7Ra8LWlG6okNkSsJ3G/azHblMFK1K8eZ0N9UlXfWt0CO38UhsbwjGDNo@LFM6jgCqKfkbnogzOAo633zJbzVOr@pPVObhlBtVCYhtrAa5Ir0PKcJsqq4aH/PZEpUPF5/zCZmDxwaAOqZGymaoaw4/O6L3SlTkoH4hgp4MpDV6N/So/@Ysq9eOu3/UXsHjP61/kzZoPq5xrv9XEjZT8T71bpQ@0wserMSbgOvwC "PHP – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum,reduce -pa`, ~~51~~ 50 bytes
```
say+($\=reduce{$a=$a/2+$b/2}@F)-($_=(sum@F)/@F.$/)
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJbQyXGtig1pTQ5tVol0VYlUd9IWyVJ36jWwU1TV0Ml3lajuDQXyNZ3cNNT0df8/99QRwGCTMDITEfBAowsgehffkFJZn5e8X9dX1M9A0MDIO2TWVxiZRVakpljCzRIB2LTf92CRAA "Perl 5 – Try It Online")
Output format is
```
trend
traditional
progressive
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 19 bytes
```
psJr{.+2./}javq.-c!
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/oNirqFpP20hPvzYrsaxQTzdZ8f9/YwMDPQMFIzBpCCIB "Burlesque – Try It Online")
Takes input of the form `300.0 200.0 100.0`. If we didn't have to print the other values would be 3 bytes shorter (i.e. Without the continuation).
Returns progressive mean™, arithmetic mean, trend
```
ps # Parse list to array
J # Duplicate
r{ # Reduce by (Progressive Mean)
.+ # Adding
2./ # Dividing by 2
}
jav # Calulcate regular mean
q.- # Quoted (boxed) subtract {.-}
c! # On a non-destructive stack
```
[Answer]
# [Python 3.8](https://docs.python.org/3/index.html), 91 bytes
I wanted to flatten the recursive relation, and I got this:
```
lambda l:(m:=sum(l)/(n:=len(l)),(p:=sum(l[-i]/2**i for i in range(1,n))+l[0]/2**(n-1)),p-m)
```
[Try it online!](https://tio.run/##VcvBCsIwDAbgu0@RYzI71q4XGfRJ5g4TVy20WenmwaevtYiwQ37C9yfxvT9X1peYsgUD1@zncLvP4AcMg9leAT11yIPxC5eVBMYfj62bur5pHNg1gQPHkGZ@LKgEE539KGuN3KryFttAOSbHO1oclYBegJ6ITn/T1dTBlCxYRsvjqaxeQslvkz8 "Python 3.8 (pre-release) – Try It Online")
The use of `range` instead of the list itself makes it much longer.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 54 bytes
```
->x{a=x.sum/x.size;b=x.inject{|a,b|a/2+b/2};[a,b,b-a]}
```
[Try it online!](https://tio.run/##dZBNTsMwEEb3OUUkNiDiif8dqyoXqbpwqlYqKgi1VCq0PXuw44ljg/BinHH05vnz8dx/Dbt6OZCXy9UtL3A6v7W@7r@3i963@/fX7ebzenNNf3Mtf@5bfl@sfNf0xK3vw0e9g407HB5XDGhT81AE0PVT9RCaeMZV2Knfq2oGRAJYCTAwI0B@EyzOG6ugE0RRw0HFiaWFIhRH0xlDjgXZqAvX/KtjE4mgRE6gj5hSKMPhWGwoHQbEL51@sDy5Anw@zTtLdXwwwkEaRq0w0sali@vlU1Apk6NLxWLJRR0okTwCZGwoLplrbBllTjEL2X95mA/AtZryCB/PCJnlGX4A "Ruby – Try It Online")
Takes a list of numbers in the format `[1.0, 2.0, 3.0]`
and returns an array containing the mean, progressive-mean, and trend, respectively.
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
s!p=(s,p,p-s)
f x=(sum x/sum[1|_<-x])!foldl1(((/2).).(+))x
```
[Try it online!](https://tio.run/##bY7BCoMwEETvfsUKPSQ0xkSlKNQvESmClUqjhqaFHPrv6Zq0l2pYBnZn3pBbZ@5XpZwzsa6JYZrpxNBoAIvbawKbojbyfTkntqXxsKheSUJImlFOOTlSat3UjTPU0C8R4NOPcX7CAQZoJBcMslVyLtp/N0ePgdzc5QqtzA4ivIcihdgFZTA3XsEAp2JQou315Fe5@4Nw90jhk6UfzFebcPWrDZ0B@Ta07gM "Haskell – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 144 122 bytes
```
let f=|y:&[f64]|{let m=y.iter().sum::<f64>()/y.len()as f64;let pm=y[1..].iter().fold(y[0],|acc,x|(acc+x)/2.);(m,pm,pm-m)};
```
Straightforward approach. Shaved 22 bytes thanks SirBogman, and thanks Mabel for showing TIO's Rust support.
[Try it online!](https://tio.run/##jY1fa4MwFMXf9yliH8oNS28b@2etrtsHkTDEJiAY50xaKupnd9E1bA@jFHK4l3PP76Q@Gzuokug0L4GSdiikJerYNdE8UbuN6NrR0McGcytroGjOOope3ekN6LLBQjosNcQZ8ZisXDThiMLn1WdxgiZZCdalWcauHbjxfKXLEGkMmlXjW2jax0NqjKzth/wKQMH8IrMgWSMLkXEUlBFwG@H4smVkscJwS2n89A/CJ2T9i4Quy4gnqjovbVEGMGuj937GiOc2Ljrq4LSffvqZu5vHJ4m7HYc/vGd9L3@w43bvh28 "Rust – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~116~~ 115 bytes
```
v->{float m=0,p=0;for(int i=0;i<a.length;i++){m+=a[i];p+=a[i];p=i!=0?p/2:p;}m/=a.length;return m+"\n"+p+"\n"+(p-m);
```
[Try it online!](https://tio.run/##TU67boNAEOz9FRtXIOBMnC7nc7p0qVw6Li4YyJJ76ViQLMS3k3MAK9PM7sxodxrZy6y5/kyonfUETdhZR6hY1ZmC0Br2vgx847ovhQUUSrYtfEg0MGwgYNFbkhSot3gFHdzoRB5Nfb6A9HUbL@E7KmUl3XUQMDyn@zx9yUf@sNePhyWXzoeOUIGY@uw4/OmgRZ46kfPK@ggNAYYZD5Kp0tT0zTFJ4kEnQp7xwt3KAp9E/uZ2@1fHR70Tj7gvqfMGdLL9NNvEzRS5TMd8Wov963i6tVRqZjtiLpQjZaKKSefULZJxPOfGzTj9Ag "Java (JDK) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 48 bytes
```
[ [ unclip [ + 2 / ] reduce ] keep mean 2dup - ]
```
[Try it online!](https://tio.run/##TY/BTsMwEETv@YpRJU4IsBNUJfABiAsXxKn0YLmb1mrjGHt9QFW/PWysKtTrw@y@mZXdG8tjnL4@3z/eXpDoJ5O3lDAYPuBI0dOp6MfEhl1iZxNCJObfEJ1n9GMUzM7v8VpV5wpyztCo0eBy7Rrp9NJphVqhUf9YzRMlQN2adBktk2epDq0sarEWpW9Xlpoda6Gt0G5hXUnNmZnra@4ybbBB9vbkgoh7eeETtoi0y5ZEHIkCBjIe9S4HPGArgdVdRrnffoXy/V6sdhzCmAhk7GH6Aw "Factor – Try It Online")
[Answer]
# [Arturo](https://arturo-lang.io), 57 bytes
```
$[b][a:average b@[p:fold.seed:b\0b[x y][//x+y 2]a p p-a]]
```
[Try it](http://arturo-lang.io/playground?AGxlmX)
[Answer]
# [Scala](https://www.scala-lang.org/), 126 bytes
Golfed version. [Try it online!](https://tio.run/##TcvNSsQwFAXg/TzFcZhFgp0fZRBtzGI27nwCdXFtE40k6SUJQSl99jp0EITvcDkHbu7I0zy8f5mu4JlchPkuJvYZJ2aMK6CSB7U4pUQ/L09@oPIGfaniocHZ/eKuwXFxcyHn3lhYUdv/r1KPlRJCw@0y6IOyQxLucVt3LvauM1mO4VpX4aTiv6udFe5KHyTvb2F8NmA1qbDXdedN/CifKq834TVu@JyRt2FaTzPAycXio7CCpFxN8y8)
```
def f(v:Array[Float])={var m,p:Float=0;for(i<-v.indices){m+=v(i);p+=v(i);p=if(i!=0)p/2 else p;};m/=v.length;s"$m\n$p\n${p-m}"}
```
Ungolfed version. [Try it online!](https://tio.run/##ZY4/a8MwFMR3fYqrySBR509LKa1pAlmyZcrYdlAcOVWRZSEJkxD82Z1n2VML94bfe3cnhVIa2ffN8VeVEXupLdQlKnsK2DqHGwNaaSALbL2X18@daWT8xnpE/p6D9Jb0muMl6WmUmLLV3@wGh@i1PVNLO9DwyGD1qHO4AslHx1XaV40H1/iYo11oe9KlCmKKADUeqYRrMbH7x2voasg/UJ8gXuIZygQFlywdG2uWFFsYZc/xJ21CNqu/7MzR3BzmqLuMjW5HX4/G8opLIVjH@v4O)
```
object Main extends App {
val a: Array[Float] = Array(9, 9, 8, 8, 6, 4, 4, 1, 1, 1)
val f: Array[Float] => String = v => {
var m, p: Float = 0
for (i <- v.indices) {
m += v(i)
p += v(i)
p = if (i != 0) p / 2 else p
}
m /= v.length
s"$m\n$p\n${p - m}"
}
println(f(a))
}
```
] |
[Question]
[
## Input:
* An integer \$n\$, which is guaranteed to be \$\ge3\$.
* An integer \$d\$, which is one of \$[-1,0,1]\$.
## Output:
A road of size \$n\$, which will be in a north-west direction if \$d=-1\$; a north direction if \$d=0\$; or a north-east direction if \$d=1\$. The road will always be three spaces wide (or five in general if we'd include the outer borders). In addition, there will be a road separator line on the bottom section, and after that alternating while going upwards.
**Some examples:**
Input: \$n=7, d=1\$
Output:
```
/ / /
/ /
/ / /
/ /
/ / /
/ /
/ / /
```
Input: \$n=4, d=-1\$
Output:
```
\ \
\ \ \
\ \
\ \ \
```
## Challenge rules:
* Any amount of leading/trailing spaces and/or newlines are acceptable, as long as it prints the required road somewhere on the screen.
* Instead of the options \$[-1,0,1]\$ you are also allowed to use the options \$[0,1,2]\$ or \$[1,2,3]\$ instead. Also, you can choose which of the three options map to which of the three directions. (Make sure to mention which options you've used if it differs from the \$[-1,0,1]\$ for `[north-west, north, north-east]` respectively that is used in this challenge description!)
* Any reasonable output format is acceptable. The most common is of course to print it to STDOUT, but returning it as a string or 2D character list is fine as well.
## 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 with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
The two examples above, and:
Input: \$n=10, d=0\$
Output:
```
| |
| | |
| |
| | |
| |
| | |
| |
| | |
| |
| | |
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~79~~ ~~78~~ ~~73~~ 72 bytes
```
n,d=input()
c='|\/'[d]
i=n
while i:print' '*(n-i*d)+c,i%2*c or' ',c;i-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/rv7O/iaqukpPQ/TyfFNjOvoLREQ5Mr2Va9JkZfPTollivTNo@rPCMzJ1Uh06qgKDOvRF1BXUsjTzdTK0VTO1knU9VIK1khvwgoqpNsnalra/gfaBgXV2pFarICyGwt4//mOoZcpjq6hlzGOgYA "Python 2 – Try It Online")
Takes `[1,0,-1]` for `[north-west, north, north-east]`
-1 byte, thanks to Neil
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
n,d=input()
s=' '+'|\/'[d]
for c in(s*n)[n:]:print' '*n+s,c+s;n+=d
```
[Try it online!](https://tio.run/##HYzBCgIhFEX37ysebpwZjbKFA4ZfMs1KjRHijahRQf9u1uIszuFy07tuO53bc4v3gMqEV3CYGWONpLeR0qMOIxTLkQv@uR754le47RkdRhrKRONCZjUpR6p9M5Eo0olyIWF9@1foZ9BmeVAwy1NHgf6J7qKl@gI "Python 2 – Try It Online")
Uses `d=-1` for NE, `d=0` for N, and `d=1` for NW. Takes advantage of leading spaces being allowed. The rule that the *bottom* segment of the road have a separator made it tricky to get the parity right; it's achieved by the slicing `(s*n)[n:]` taking the second half of the `2n` alternations between space and a the road character.
[Answer]
# 1. Python 3.5, 122 120 bytes
Script takes two params: n, d.
d: 0, 1, 2 -> \ | /
[tio.run](https://tio.run/##DYtJCsMgFED3PYUIBZWfNgNkEfEkxoWYNlXIV4wUAr27dfuGdJVPxKlWf6SYCzmvUzKEjSstDpuYxwKNPWzev3pYJsONdIqu6@9J9WZu75iJJx5Jtri/GPIlKOyGzsuU28sooYJ56CHwloMDJ1i4j0r1POYmwfFa61zHPw)
```
import sys;(n,d)=[*map(int,sys.argv[1:3])];c="\\|/"[d]
for i in range(n):j=n+~i;print(" "*(i,0,j)[d],c,c*(j%2<1)or" ",c)
```
output:
```
$ ./script.py 6 2
/ /
/ / /
/ /
/ / /
/ /
/ / /
$ ./script.py 6 1
| |
| | |
| |
| | |
| |
| | |
$ ./script.py 6 0
\ \
\ \ \
\ \
\ \ \
\ \
\ \ \
```
## Explanation
```
# parse input params
(n,d)=[*map(int,sys.argv[1:3])]
# select char for "road"
c="\\|/"[d]
# loop n-times
for i in range(n):
# complement (how many lines to end)
j=n+~i
# print
# space i or 0 or j times
# road, center of road if j is even else space, road
print(" "*(i,0,j)[d], c, c*(j%2<1) or " ", c)
```
edit: -2 bytes thanks to Kevin Cruijssen
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~88~~ ~~82~~ ~~80~~ ~~74~~ 71 bytes
-8 bytes thanks to Mazzy
-6 bytes thanks to AdmBorkBork and Mazzy
-3 bytes thanks to AdmBorkBork
```
param($n,$d)$n..1|%{' '*($_,($n-$_))[$d]+($y='/\|'[$d])," $y"[$_%2],$y}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlT0clRVMlT0/PsEa1Wl1BXUtDJV4HKKyrEq@pGa2SEqutoVJpq64fU6MO4mnqKCmoVCpFq8SrGsXqqFTW/q/lUlNJUzBVMOJSV4cyDRBMQxjTTMHwPwA "PowerShell – Try It Online")
Uses [0,1,2] for NW, NE, N. Uses `d` as a list index twice to first get the spacing method (Drops off the list when using 2 which returns 0) and then which character to use when drawing the lines. Appends a list to the string of spaces (which innately has spaces between the members when appended as such) which builds the road. Also swaps between an open lane or a dash based on modulo math.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~100~~ 90 bytes
```
f(a,b,c,d){for(c=a,d="\\|/"[b+1];c--;)printf("%*c %c %c\n",b>0?c+1:b?a-c:0,d,c%2?32:d,d);}
```
[Try it online!](https://tio.run/##XYzRCsIgGEbv9xQhDLT9kq4gmCwfJLvQXxyDsrEtulh79cwuC87Fx@HjIO8QUwrUggMEz5ZwHym2FnxLjHntyNlV8qKQc8WGsY9zoKTc4qb8YiIBdxIaK9k4bTk2AjxgWet93fhcU2u62T5SthRFoAfgkqlieMwTJSSv7KQA8e@O8Htb0xvD1XZT4s8P "C (gcc) – Try It Online")
---
[Well written version](https://tio.run/##jZJRT4MwEMff@RQnhtBp0WKWmIibX8Ann3khbRmXsLJA54vy2bG0shLZ1EvTXsvvf727wpMd58NwjYrXRyHhudMCm7tqGwTvDQo4tKj0W1MIYlaopdrpisLoC2wl19io1UcQgDFeFS3UqGTm9lgSD8EW2AQaGzHYQHwff8M9yLqTRgPEa642wOCMKs9/yJbI54lwS9m0YEtA89WVkRk/SUxe2fwOW9uhEK@OmZ2X5FI11k4acwHOdP@qbBHBpQjJuVC/yNic9q59xZKE0Q2HaBy5CulMeAspta0zTxs9vMQQP7ndOK98J/th7M6@QEWm5P0PsqZJalh7eNQdCcNJ6ZmUUfYX80iXYfrhCw "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ ~~29~~ 23 bytes
```
↷NNη⊘⊕ηUE¹¦¹F⟦²±²⟧«Jι⁰η
```
[Try it online!](https://tio.run/##TYw9C8IwFADn9ldkfIEItro5C1akdHATh5i@2kA@SngJgvjbY4qL2x0cp2YZlJcm50EnTxecCDq3ROqjfWAAzg/1v8/Fh6AdwUmahGOJVUCLjgrPfM2PL0I3QiNYU2zygcGtFazHpySElt85e9fVOdrl6kELti1V9Xuu90/OO7bPm2S@ "Charcoal – Try It Online") Link is to verbose version of code. Now that all of the underlying Charcoal bugs seem to be fixed I can advertise the optimal code. Explanation:
```
↶N
```
Rotate the cursor direction anticlockwise according to the first input, so that 1 becomes north east, 2 north and 3 north west.
```
Nη
```
Input the length of the road.
```
⊘⊕ηUE¹¦¹
```
Print half the length of the road and then stretch it giving the road separator.
```
F⟦²±²⟧«Jι⁰η
```
Print the sides of the road.
@KevinCruijssen subsequently submitted a harder version of this question which was since deleted but users with enough rep can see it here: [The (Hard) Road to Code](https://codegolf.stackexchange.com/questions/181383/) The stretching trick I used in this answer isn't applicable to that question, so instead I wrote the following ~~47~~ 45-byte program:
```
F³«J×ι⊘⊕θ⁰≔…⟦¹ ⟧⊕﹪ι²ιFη«↶§κ⁰F⊖§κ¹§ιⅉP§ιⅉ↑↷§κ⁰
```
[Try it online!](https://tio.run/##dY9Pi8IwEMXP7acYPE0gwtbedk@iB11WENGDlB5KO9qwaVLbtCjiZ49NXNDDepk/5P3em@Rl1uQ6k9YedAMYM7iGwXdX1VuNW1FRi4LDIpM9FbhUeUMVKTPMJ8YYhw/2FQbTthVHhbNLLmlW6hqTiMMIRimHV2Kli05qZzfxrHCsDy19aLAWvTY/dDA4NUtV0Bl/XYKTPXRzerq9SKLBDtaNUE9wCNkje6CrThpRv3/WPeHnrvaLP2EjjuU/N9zCm7VJzCFxJR5@l0z@euR6mtpxL@8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F³«
```
Loop over the sides and separator.
```
J×ι⊘⊕θ⁰
```
Jump to the start of the side.
```
≔…⟦¹ ⟧⊕﹪ι²ι
```
Make an array containing a `1` and a space, but remove the space again if we're drawing the sides rather than the separator.
```
Fη«
```
Loop over each road section.
```
↶§κ⁰
```
Rotate the cursor direction accordingly.
```
F⊖§κ¹
```
Loop over one less than the length of the road section...
```
§ιⅉ
```
... and print alternating elements of the array. The alternation is achieved by cyclically indexing into the array with the Y-coordinate of the cursor.
```
P§ιⅉ
```
Print the last row of this road section, but without moving the cursor...
```
‚Üë
```
... so that the cursor can be moved up ready for the next section instead.
```
↷§κ⁰
```
Rotate the cursor direction back ready for the next section.
[Answer]
# [Kotlin](https://kotlinlang.org), ~~96~~ 92 bytes
```
{n,d->val c="\\|/"[d];(0..n-1).map{println(" ".repeat(n-it*(d-1))+ "$c ${" $c"[it%2]} $c")}}
```
Accepts [0, 1, 2] instead of [-1, 0, 1]
It works similarly to solutions in other languages, but unfortunately Kotlin doesn’t really shine in this one.
`val c=“\\|/“;` retrieves the char to use in road building by taking advantage of the fact that Kotlin treats Strings like an Array of chars (as it should, looking at you Java)
[Try it online!](https://tio.run/##fY@xCsIwGIT3PsVvqPBHm6jFSWnBUfAN2g6hiRBs/5YSBal59posjt5w3PDB3T0G11laXqqD@5PaE@CVXAbBOIgSLvSGYpkp06KMTFuwuv7sWKWbM@6lJHHgslfjPE6WXEfIgMnJjEY5JGHdBnUg@BZY2kI6M0hbVlm3zhsfI/d@CbXQK0vIYU4gKPYQFDAZpW@WDPLVSrohTEL@A/Q/ID7BsJknfjkm@Rc)
[Answer]
# TSQL code, ~~171~~ 117 bytes
I realized this could be written much shorter as code.
```
DECLARE @n INT=7,@d INT=0
,@ INT=0a:PRINT
space(@n-@*@d)+stuff(replicate(substring('\|/',@d+2,1)+' ',3),3,@%2,space(@%2))SET
@+=1IF @n>@ GOTO a
```
# TSQL query, 137 bytes
```
USE master
DECLARE @n INT=6,@ INT=-1
SELECT space(@n-y*@)+z+iif(y%2=1,z,' ')+z
FROM(SELECT top(@n)row_number()over(order
by @)y,' '+substring('\|/',@+2,1)z FROM spt_values)x
```
*USE master* is not necessary, if your database is master already. Some users however have a different default database.
Script when *trying it out* is slightly different. I had to replace space ascii-32 with ascii-160, the spaces were not shown.
**[Try it out](https://data.stackexchange.com/stackoverflow/query/1004939/the-easy-road-to-code)**
Made some tweaks and realized that I could replace
>
> order by 1/0
>
>
>
with
>
> order by @
>
>
>
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~23~~ 22 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
B}⁴H‟m↶⁷?/|∙/╋]\|∙\╋]}
```
[Try it here!](https://dzaima.github.io/Canvas/?u=QiU3RCV1MjA3NEgldTIwMUYldUZGNEQldTIxQjYldTIwNzcldUZGMUYldUZGMEYlN0MldTIyMTkvJXUyNTRCJXVGRjNEJXVGRjNDJTdDJXUyMjE5JTVDJXUyNTRCJXVGRjNEJXVGRjVE,i=NSUwQTI_,v=8)
Uses the direction inputs 0, 1 and 2.
Explanation:
```
...‟ push "--¶¶- ¶¶--"
m mold the horizontal length to the 1st input - a horizontal road
↶ rotate counter-clockwise - so the separator is on the bottom
also replaces the dashes with bars
⁷? ] ]} switch over the 2nd input:
default case (input 2):
/ pad with spaces to a "/" diagonal
|‚àô/‚ïã replace "|" with "/"
case 0:
\ pad with spaces to a "\" diagonal
|‚àô\‚ïã replace "|" with ""
case 1 is empty, but because of a bug, the trailing "}" is still required
```
[Answer]
# JavaScript (ES8), ~~ 90 87 ~~ 85 bytes
Takes input as `(direction)(length)`. Expects \$0\$ for North-West, \$1\$ for North or \$2\$ for North-East.
```
d=>g=(n,w=n)=>n?(c='/|\\'[d]).padStart([n--,,w-n][d])+` ${n&1?' ':c} ${c}
`+g(n,w):''
```
[Try it online!](https://tio.run/##ZcyxCoMwFEDR3a9wKM17xNikFApC9CM6qmBIVCySiIY6tH57qmPpeM9wn@qlFj0Pk2fWmTZ0MhiZ9xJsskqOMrcFaEkun6oipakxnZR5eDV7KC1jSULpWh9Om/j0tmdRkJhkettDb1FD@@ODGSFBO7u4sU1H10MHHCG@I0a/et319qcCQXDE8AU "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 90 bytes
This one draws the output character by character with a little more maths instead of the `.padStart()` method.
Takes input as `(direction)(length)`. Expects \$1\$ for North-West, \$2\$ for North or \$3\$ for North-East.
```
d=>n=>(g=x=>y?` /|\\
`[x+5?17+y%2*4>>--x+5-[,n+1-y,n,y][d]&1&&d:(x=n,y--,4)]+g(x):'')(y=n)
```
[Try it online!](https://tio.run/##ZcjRCoIwFADQd7/Cl/TetlvNDEHY/BAVFKdiyBYZsUH/vnyNHs@59@9@G57L40XG6jFMMmipjFQwSyeVr7r4/GmaqKsdu1WiYP6QHXOliHZTzQ0T5Lnhvq11m4gk0SU4uZuI59iyGRyWaYrgpcEwWLPZdTytdoYJBEJcIEa/e903/9sMQVwQwxc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 31 ~~ 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁶ẋẋƤḂ};€ị“\/|”ẋ3KƊ}Ṛ⁹¡⁶-2¦€ÐeṚ
```
A dyadic Link accepting the length on the left and the negated-direction\* on the right which yields a 2d array of characters.
\* `[north-west, north, north-east]=[1, 0, -1]`
**[Try it online!](https://tio.run/##y0rNyan8//9R47aHu7qB6NiShzuaaq0fNa15uLv7UcOcGP2aRw1zgRLG3se6ah/unPWoceehhUDlukaHlgFVHZ6QChT8f3h55P//hkb/DQE "Jelly – Try It Online")** (footer calls the Link, joins with newline characters and prints the result)
### How?
```
⁶ẋẋƤḂ};€ị“\/|”ẋ3KƊ}Ṛ⁹¡⁶-2¦€ÐeṚ - Link: integer, L; integer, D
⁶ - space character
ẋ - repeat L times
} - using the right argument (D):
Ḃ - mod 2 (0 if D = 0, 1 otherwise ...A would work too)
Ƥ - for each prefix (of the list of spaces):
ẋ - repeat (D mod 2 times)
} - using the right argument (D):
Ɗ - last three links as a monad:
ị“\/|” - index into "\/|" (1-indexed & modular)
ẋ3 - repeat three times - e.g. "\\\"
K - join with spaces "\ \ \"
;€ - concatenate €ach (altered prefix with that list)
¬° - repeat action...
‚Åπ - ...number of times: right argument (-1 repeats 0 times)
·πö - ...action: reverse (i.e. reverse if north-west)
Ðe - for even indexes:
¦€ - sparse application for €ach...
-2 - ...to indices: [-2] (the middle of the road)
⁶ - ...action: a space character
·πö - reverse
```
[Answer]
# Python 2, 127 bytes
```
n,d=input()
c='|/\\'[d]
for i in range(n):t=0if d==0else(i if d<0else n-i);print(' '*t+'{} {} {}'.format(c,' 'if i%2==0else c,c))
```
[Try it online!](https://tio.run/##LYxBCsIwEEX3PcVsZBKNWrsRrDmJdVGSVAfqNKTjQtSzx1CEv3k8/osvuU/c5MzGW@L4FKUrZ/Gz7zq8@Gs1TAkIiCH1fAuK9UlsTQN4a@swzkEVWei8APCWdBsTsSgEXMsG319YhrtSevSinCmmXGjV/BPgjNM656M5/AA)
First two lines taken from @TFeld.
[Answer]
# [Python 2](https://docs.python.org/2/), 93 bytes
```
n,d=input();p=''
while n:g='|/\\'[d];n-=1;print['',' '*n,p][d]+g+' %s '%(g,' ')[n%2]+g;p+=' '
```
[Try it online!](https://tio.run/##LY7BCoMwEETv@YpFkNUaqZFCQcnRXnvpTT20GlRaYkgjrdB/TxPb0zJvhplVqxlnmdtu7gVw0EEQWEl7Pkm1mCguFUckr3F6CJDFwPGzbxqs@7aUKWel0pM0NSJFwJ2kqnVOMiQI4RMwjAbP41qGuaOlSriT1i2Qf@NFL6IgAEav/gCIt@jAv7KprZ142glloDqfKq1n/YvetLjeLctoRg40ZeRI2Rc "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 64 bytes
```
' \|/'{~(_2&|*[:i.[*1 _1{~3=])|."_1((5+[){."1(5,~[)|.@$]*#:@689)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RViavTVq@s04o3UarSirTL1orUMFeINq@uMbWM1a/SU4g01NEy1ozWr9ZQMNUx16qKBgg4qsVrKVg5mFpaa/zW5FLhSkzPyFcwV0hQMIUxTINMIwjQ0BrKN/wMA "J – Try It Online")
* 1 North-West
* 2 North
* 3 North-East
Will try to golf it later
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~129~~ ~~107~~ ~~103~~ 93 bytes
```
a=>b=>{for(char i=a,W="/|\\"[b+1];i>0;)Write("{0,"+(a-i*b+5)+"} {1} {0}\n",W,--i%2<1?W:' ');}
```
-1 for north-east, 1 for north-west, 0 for north
[Try it online!](https://tio.run/##TYy7CsIwFEB3v6IEpPeaBBPFQdNEXPyFDNYhDRbvkkJbp9pvj49FhzMcDpw4yDhQPj9SrOI99OIUR@pSRWl0rrU5WNdYN7VdD59ckA3CW7Z@1jW7NFxfDTll0Pc03oBNSjAOQdKq4TvkbC4m/UbNdWLCCylpuan00R/KokQzZ7No4ftFrRA0/nyPIP9dbxEUmvwC "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 91 bytes
```
£:0=[¥(n₂[`| | |`|`| |`],)|1=[¥(ðn*n₂[`\ \ \\`|`\ \\`]+,)|¥(ð¥‹n-*n₂[`/ / /`|`/ /`]+,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%A3%3A0%3D%5B%C2%A5%28n%E2%82%82%5B%60%7C%20%7C%20%7C%60%7C%60%7C%20%20%20%7C%60%5D%2C%29%7C1%3D%5B%C2%A5%28%C3%B0n*n%E2%82%82%5B%60%5C%20%5C%20%5C%5C%60%7C%60%5C%20%20%20%5C%5C%60%5D%2B%2C%29%7C%C2%A5%28%C3%B0%C2%A5%E2%80%B9n-*n%E2%82%82%5B%60%2F%20%2F%20%2F%60%7C%60%2F%20%20%20%2F%60%5D%2B%2C&inputs=5%0A-1&header=&footer=)
A little better.
[Answer]
# [Red](http://www.red-lang.org), 157 bytes
```
func[s d][p: pick"\|/"d set[a b]reduce pick[[4 1]0[5 + s -1]]d
repeat n s[print pad/left form reduce pick[[p" "p][p p p]]odd?(n + pick[1 0]odd? s)a: a + b]]
```
[Try it online!](https://tio.run/##VY29CsMwEIP3PIXw1FJK4v6Tpe/Q9XqDk7MhtHWM7Wx9d9dkKwIN@pAUrZSHFeLG9cUtfqQEYQo9wjS@1PPbKkGymQwGjlaW0a6E6ATNHZ2xQ8JeMwuaaIM1GR6JQpx8RjDSvq3LcHP84K8eFFSoR6hinkXuG1@3VqjRrQnS1vQwNR6Yi8MVunG44FD9hmP5AQ "Red – Try It Online")
* 1 North-West
* 2 North
* 3 North-East
[Answer]
# Japt, 53 bytes
```
W="|/\\"gV;Æ"{W} {YÉ %2?W:' } {W}"ùVÄ?V?Y+5:5:U-Y+4Ãw
```
[Try it Online!](https://ethproductions.github.io/japt/?v=1.4.6&code=Vz0ifC9cXCJnVjvGIntXfSB7WckgJTI/VzonIH0ge1d9IvlWxD9WP1krNTo1OlUtWSs0w3c=&input=MTAKMQotUg==)
[Answer]
# [Swift 4.2](https://swift.org), ~~112~~ 108 bytes
-4 bytes thanks to Sriotchilism O'Zaic
```
let c=["\\","|","/"][d];(0..<n).map{print((0..<n-$0*(d-1)).map{_ in" "}.joined()+c+" \($0%2==0 ?c:" ") "+c)}
```
[0,1,2] instead of [-1,0,1].
[Try it online!](https://tio.run/##VU7BCoJAFLz3FY@Hwb7UbRVPlnTuG1QidhU26iW10cH22zdDgjrMwMwwzNyftndF6B@sYbhZdoLLPbvEfJjGcO4c6KrGpsEEXxPW2Nam3Qgl5ZZJXo7DOPdmJ43USpg0ozk6gGUE9PJ0tdwZQbGOERoRqWVeVQp2upxiAow1eR@@D4ppX9HiV2b/MqfwBg)
## Explanation
```
let c=["\\","|","/"][d]
```
Determines the street sign to use. (I bet this can be shortened somehow)
```
(0..<n).map{
```
Iterates over the length of the street.
```
(0..<n-$0*(d-1)).map{_ in" "}.joined()
```
Adds the spaces in front of the street.
```
\($0%2==0 ?c:" ")"
```
Adds the middle sign to every other line.
My very first one ☝️, I'm happy about any optimization advices. Learned mostly from that thread: [Tips for golfing in Swift](https://codegolf.stackexchange.com/questions/79203/tips-for-golfing-in-swift?newreg=5f12c38fe2f34c2893c486bec51c5d0e).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 66 bytes
```
->\n,\d{{(' 'x--$ *d%-+^n~(' ',<\ | />[d+1])[1,(n+$++)%2,1])xx n}}
```
[Try it online!](https://tio.run/##HYhLDoIwFEXnrOKGFHm1r0qN0YHKRqgaE2yi0WJwUgK49SqOzud1bR@b@OwwczhEXVrPtu57ypEHrQXmdabVyX@mwXuLAcuyqpU5ysoweSWUktmKfx0C/DjG96WDo0Gc5eLe3Dyl1qeSMQGuaRPaMozkhNYM/RdTMAq5i18 "Perl 6 – Try It Online")
Returns a list of lines.
### Explanation
```
->\n,\d{ } # Block taking n, d
{ } # Reset $ variables
( )xx n # Repeat n times
' 'x # Space times
--$ *d # (-1,-2,-3,...) if d=1
# (0,0,0,...) if d=0
# (1,2,3,...) if d=-1
%-+^n # modulo -~n = n+1
~ # Concat
(' ',<\ | />[d+1]) # Space or line
[1,(n+$++)%2,1] # Alternate middle char
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 90 bytes
```
n,a=*$*.map{|i|-i.to_i}
c='|\/'[a]
n.upto(-1){|i|puts' '*(i*a-n)+c+' '+[' ',c][i%2]+' '+c}
```
[Try it online!](https://tio.run/##HYo7DoAgFMB2TuGgQUEwGFdPgsQg0xtEojAY8ezPz9KkTfe0nIi@tSMrmVxtuDJkATJuM9zEjTRPHdXWEC9TiFstVPMdIcWDFpTVwKzwDXf8Na5ftM5oqHrzB3cj4oBCPQ "Ruby – Try It Online")
UPDATE: Thank you, Kevin, for pointing out that my original submission was missing spaces between the road edges and markers (i.e., 3-width roads instead of 5-width.) That said, there might be a shorter fix for that than `c+' '+...+' '+c`.
Directional information: `-1, 0, 1` maps to `{ north-west, north, north-east }`
Arguments: this reads command-line arguments such as `4 -1` (a four row road, slanted to the north-west).
Additional note: This was tested locally with Ruby v2.6.1, and it appears that *Try It Online* uses Ruby v2.5.3. I have no reason to think it would not work with all other Ruby versions.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 116 bytes
```
d->n->{for(int c="\\|/".charAt(d),i=n;i-->0;)System.out.printf("%"+(d<1?n-i:d>1?i+1:1)+"c%2c %c%n",c,i%2<1?c:32,c);}
```
[Try it online!](https://tio.run/##ZY5Pa4NAEMXv@RSDIOw2uo0WWoiJoRQKPfSUY9PDdlbTSXVX1jEQUj@7tRJyyWn@/B7vvYM@6vhgfgaqG@cZDuOtOqZKlZ1FJmfVXTZruq@KELDSbQvvmiycZwCXb8uax3F0ZKAemdiyJ7v/@ATt962cpABvll8vjqtxf3G27erC5@CdNuvBxLmN83PpvCDLgOtgt/u9DxR@a//MwsiI1jajOM4XmdyeWi5q5TpWzRjFpQjCYC7MKtnYmJYmTzY0T5aJnAcYpgghhjaIMKIwHSW4fEgjlFk/ZFOz/wJKN011EqlUGrFoWDzJG5hcYbK4pYsrfZxgP@uHPw "Java (JDK) – Try It Online")
Takes `d` as one of `0`, `1` or `2`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-R`, 40 bytes
```
Æ=Vg"|\\/";²i1S+iX%2?S:U)iSp[TZÊ-YY]gVÃw
```
[Try it online!](https://tio.run/##y0osKPn//3CbbVi6Uk1MjL6S9aFNmYbB2pkRqkb2wVahmpnBBdEhUYe7dCMjY9PDDjeX//9voaNgyMWlGwQA "Japt – Try It Online")
### Explanation:
```
Æ=Vg"|\\/";²i1S+iX%2?S:U)iSp[TZÊ-YY]gVÃw
// U = road size
// V = direction
Æ Ã // Loop X through [0...U]
= ; // Set U to:
"|\\/" // "|\/"
Vg // [V]
² // Double U
i1 ) // Insert at index 1:
S+ // " " +
X%2?S:U // X%2?" ":U
i // + " "
i // Insert at index 0:
Sp // " " repeated this many times:
[TZÊ-YY] // [0,U.length - X,X]
gV // [V]
w // Reverse output
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ù╒←∩♂2Ωⁿ¡├∩22♀Ç○=÷â╧δÖ↑
```
[Run and debug it](https://staxlang.xyz/#p=97d51bef0b32eafcadc3ef32320c80093df683cfeb9918&i=1+7%0A-1+4%0A0+10&a=1&m=2)
Input is two integers separated by a space.
The first is `d`. -1 specifies north-east. 0 for north. 1 for north-west.
The second parameter is `n`.
These two values will get implicitly parsed from input and placed on the input stack with `n` on top.
Additionally `d` will be accessible from the stax's `x` register since it's the first implicitly parsed value.
For example, input "1 7"
```
Main stack Explanation
---------- -----------
; [7] peek from input stack
m map over integers [1..n] using the rest of the program
output each produced value implicitly
; [1 7] peek from input stack
+ [8] add
.*" [8 [42 34]] 2 character string literal with codepoints 42 and 34
@ [42] get the element at the specified modular index (8)
0 [42 0] literal zero
"|\/"x@ [42 0 92] get codepoint from string literal at input d (from x register)
\ [42 [0 92]] make pair
:B ['\ \ \ '] encode in custom base; it's binary with custom codepoints
_x* ['\ \ \ ' 1] (loop variable) * (input d)
;^ ['\ \ \ ' 1 8] peek from input stack and increment
% ['\ \ \ ' 1] modulus
6+ ['\ \ \ ' 7] add 6
) [' \ \ \ '] left-pad to length
```
[Run this one](https://staxlang.xyz/#c=+++++++++%09Main+stack++++%09Explanation%0A+++++++++%09----------++++%09-----------%0A%3B++++++++%09[7]+++++++++++%09peek+from+input+stack%0Am++++++++%09++++++++++++++%09map+over+integers+[1..n]+using+the+rest+of+the+program%0A+++++++++%09++++++++++++++%09output+each+produced+value+implicitly%0A++%3B++++++%09[1+7]+++++++++%09peek+from+input+stack%0A++%2B++++++%09[8]+++++++++++%09add%0A++.*%22++++%09[8+[42+34]]+++%092+character+string+literal+with+codepoints+42+and+34%0A++%40++++++%09[42]++++++++++%09get+the+element+at+the+specified+modular+index+%288%29%0A++0++++++%09[42+0]++++++++%09literal+zero%0A++%22%7C%5C%2F%22x%40%09[42+0+92]+++++%09get+codepoint+from+string+literal+at+input+d+%28from+x+register%29%0A++%5C++++++%09[42+[0+92]]+++%09make+pair%0A++%3AB+++++%09[%27%5C+%5C+%5C+%27]++++%09encode+in+custom+base%3B+it%27s+binary+with+custom+codepoints%0A++_x*++++%09[%27%5C+%5C+%5C+%27+1]++%09%28loop+variable%29+*+%28input+d%29%0A++%3B%5E+++++%09[%27%5C+%5C+%5C+%27+1+8]%09peek+from+input+stack+and+increment%0A++%25++++++%09[%27%5C+%5C+%5C+%27+1]++%09modulus%0A++6%2B+++++%09[%27%5C+%5C+%5C+%27+7]++%09add+6%0A++%29++++++%09[%27+%5C+%5C+%5C+%27]+++%09left-pad+to+length&i=1+7%0A-1+4%0A0+10&m=2)
[Answer]
# perl -M5.010 -Mfeature=signatures, 97 bytes
```
sub f($n,$d){$x=qw[| / \\][$d];say" "x($d<1?$_*-$d:$n-$_),$x,$",($n-$_)%2?$":$x,$",$x for 1..$n;}
```
] |
[Question]
[
Yesterday while playing with my kid I noticed the number in his toy train:
[![4281](https://i.stack.imgur.com/iBozFm.jpg)](https://i.stack.imgur.com/iBozFm.jpg)
So we have $$4281$$ that can be split into $$4-2-8-1$$ or $$2^2-2^1-2^3-2^0$$
So simple challenge: given a non-negative number as input, return consistent truthy and falsey values that represent whether or not the string representation of the number (in base 10 and without leading zeroes) can be somehow split into numbers that are powers of 2.
Examples:
```
4281 truthy (4-2-8-1)
164 truthy (16-4 or 1-64)
8192 truthy (the number itself is a power of 2)
81024 truthy (8-1024 or 8-1-02-4)
101 truthy (1-01)
0 falsey (0 cannot be represented as 2^x for any x)
1 truthy
3 falsey
234789 falsey
256323 falsey (we have 256 and 32 but then 3)
8132 truthy (8-1-32)
Tests for very large numbers (not really necessary to be handled by your code):
81024256641116 truthy (8-1024-256-64-1-1-16)
64512819237913 falsey
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ýos.œåPZ
```
-1 byte thanks to *@Emigna* by using `Z` (max) for the list of 0s and 1s to mimic an `any` command for `1` (truthy).
[Try it online](https://tio.run/##yy9OTMpM/X@x6f/hufnFekcnH14aEPX/v4WhgZEJAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lxab/h@fmF@sdnXx4aUDUf53/JkYWhlyGZiZcFoaWRkDCwMiEy4DLkMuYy8jYxNzCksvI1MzYyBgoY2wEAA). (NOTE: The `т` in the header is `100` to only get the first 100 power of 2 numbers, instead of the first input amount of power of 2 numbers. It works with the input amount of power of 2 as well, but is pretty inefficient and might timeout on TIO if the input is large enough.)
**Explanation:**
```
Ý # Create a list in the range [0,n], where n is the (implicit) input
# (or 100 in the TIO)
# i.e. 81024 → [0,1,2,3,...,81024]
o # Raise 2 to the `i`'th power for each `i` in the list
# → [1,2,4,8,...,451..216 (nr with 24391 digits)]
s # Swap to take the input
.œ # Create each possible partition of this input
# i.e. 81024 → [["8","1","0","2","4"],["8","1","0","24"],...,["8102","4"],["81024"]]
å # Check for each if it's in the list of powers of 2
# → [[1,1,0,1,1],[1,1,0,0],...,[0,1],[0]]
P # Check for each inner list whether all are truthy
# → [0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0]
Z # Take the maximum (and output implicitly)
# → 1 (truthy)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 54 bytes
```
f=(v,o=10)=>v&v-1|!v?v>o?f(v%o)&f(v/o|0)|f(v,o*10):0:1
```
[Try it online!](https://tio.run/##FYpBDoIwFESvUheS1hTsbysCSeEgxgVBajTIJ2J@WPTutWzmZWbeu6d@Hb6v5ZfP@Bhj9I6TRAdKuJYyyiEcqKMWO8/piCJLOGNQIvjdOyWvUQ3EAecVp7GY8MlvVlcgGZRWsgpqvafSqag0SmYk08ZeqzrxUhpt9t8kCxTci0@/8I25lnm@CSHiHw "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~69~~ ~~64~~ 58 bytes
```
f=(x,m=10,q=!(x%m&x%m-1|!x))=>x<m?q:q&&f(x/m|0)||f(x,10*m)
```
[Try it online!](https://tio.run/##XVBbbsIwEPz3KZaPojiKwY80DVVDD1K1kgGnUCV2SAwYKXdPN6BWwEp@zXhnZ/dHH3W3bneNZ9ZtzDCURRSSuhA82ReTKDzVU1xM9JNAabEMb/X7/nU/nZZRmNc9p32Pt0TwuKbD2tnOVWZWue/oI5W5SEBkaQK5WMhx5xIfHMEEVAJSpS/5As/nTEk18gp/CS4@Z7VuogDFElCbUkrmMRnl4BK@PfjtGaKUSZYzQQnWgHtKZCwF14JgWUrJWP6e91sD9lCvTAs735mqhF0HGhp3QsSVIMckdHuXhLUQooTDX5S66gwyHNbaWudhZaA1TWs6Y73ZgO5AfgUo0Ym2Zwho9T/3qkrUgxi5TuUWuIznttzJwFYfzTg41N2AkrA6eMCmLKjRuXpoF50zhT3F8@EX "JavaScript (Node.js) – Try It Online")
Input as number. The logic part is quite convoluted, so no idea how to untangle it and get rid of `q`.
-11 bytes by golfing the power-of-2 check.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
ŒṖḌl2ĊƑ€Ẹ
```
[Check out the test suite!](https://tio.run/##y0rNyan8///opIc7pz3c0ZNjdKTr2MRHTWse7trx/@GOTWFAps7hdhUg5f7/v4mRhaGCoZmJgoWhpRGQMDAyUTBQMFQwVjAyNjG3sFQwMjUzNjIGyhhDpYECZiaGhoZmCmYmpoZGIH3G5paGxgA "Jelly – Try It Online")
---
### Alternative
Doesn't work for the large test cases due to precision issues.
```
ŒṖḌæḟƑ€2Ẹ
```
[Check out the test suite!](https://tio.run/##y0rNyan8///opIc7pz3c0XN42cMd849NfNS0xujhrh3/H@7YFAZk6xxuVwFS7v//mxhZGCoYmpkoWBhaGgEJAyMTBUMDQwUDBUMFYwUjYxNzC0sFI1MzYyNjoKyxEQA "Jelly – Try It Online")
### How?
**Program I**
```
ŒṖḌl2ĊƑ€Ẹ Full program. N = integer input.
ŒṖ All possible partitions of the digits of N.
Ḍ Undecimal (i.e. join to numbers).
l2 Log2. Note: returns (-inf+nanj) for 0, so it doesn't fail.
ĊƑ€ For each, check if the logarithm equals its ceil.
Ẹ Any. Return 0 if there are no truthy elements, 1 otherwise.
```
**Program II**
```
ŒṖḌæḟƑ€2Ẹ Full program. N = integer input.
ŒṖ All possible partitions of the digits of N.
Ḍ Undecimal (i.e. join to numbers).
Ƒ€ For each partition, check whether its elements are invariant under...
æḟ 2 Flooring to the nearest power of 2.
Ẹ Any. Return 0 if there are no truthy elements, 1 otherwise.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~75~~ 69 bytes
-6 bytes thanks @Arnauld. At most 32-bit support
```
f=x=>+x?[...x].some((_,i)=>(y=x.slice(0,++i))&~-y?0:f(x.slice(i))):!x
```
[Try it online!](https://tio.run/##bc5NDoIwEAXgvbeQhZkGaPoDCJjCQYwxBFtTg9RYY8rGq1dduDGz/V7ezLsMz8GPd3t75LM76RiNCqpLQ7@nlIYD9e6qAY6ZJaqDRQXqJztqYFmaWkI2r3zpWWvg5x8j7TrE3ehm7yZNJ3cGA0khap4Qsvp3XhUY17wRuDOBFhh6HEOJoZDFtm7QpKykkPgWiW7k7Ps3vgE "JavaScript (Node.js) – Try It Online")
Input as a string.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~72~~ 70 bytes
```
f=lambda n,m=10:n>=m/10and(n%m&n%m-1<1and(n/m<1or f(n/m))or f(n,m*10))
```
[Try it online!](https://tio.run/##JU1LDoIwEN1zitlorKmhM61YCPUuGGwkoQOBbjx9bXHx5v2SN@s3fhamlLybh/AaB2AZHKqOny7UqAYeL3wK54wb9njYOvS4bOCLEuKvZLiiEiLF9x53cGDIogRsjASLLZWrKBuVQwlaAmnzsG3me6NJl15TVfm8ViZg4oP3rgJYt4ljflICkX4 "Python 2 – Try It Online")
[Answer]
# JavaScript, 59 bytes
```
s=>eval(`/^(${(g=x=>x>s?1:x+'|0*'+g(x+x))(1)})+$/`).test(s)
```
[Try it online!](https://tio.run/##XVBBbsIwELz7FXtAwoaYxHaahkpJH1IVYcABquBEsQGjtm9PN1StgD3Y8o53ZnY@9Em7dbdvPbfNxvRV0buiNCdd02W8oKNPui1CUYbSvYqXMB1/JZPxdEvDNDBGBftm01G8ZDNvnKeO9evGuqY2s7rZ0rdU5iICkaUR5GIuhzOR@EiwGYGKQKr0OZ/j/ZQpqQZc4S@RiPfZQbc0QFFCRVGJERJPyMAH1/Ld0e8uQFMuec4FIygC95DIeApNB4JnKSOD/j3udwbs8bAyHey9M3UFewca2uaMnaYCOQyh3bsh1MIWIwn8VaVrZxBJYK2tbTysDHSm7Ywz1psNaAdyEaBCJ9peIKDV/9lfVqIeyMhvLLeNaz63cmcDO30yQ3LIuwElYXX0gEtZUINz9bAuOucKd8JwH4PiCQY4ifsf "JavaScript (Node.js) – Try It Online")
Builds a regex like `/^(1|0*2|0*4|0*8|0*16|0*32|…|0*1)+$/` of powers of 2, and tests it on `s`.
Only works up to the precision of JavaScript numbers, of course: eventually the terms in the regex will look like `1.2345678e30` (or `Inf`). But since powers of 2 are easy to represent accurately in floating-point, they'll never be *wrong* integers, which would be more disqualifying, I think.
@tsh saved 14 bytes. Neato!
[Answer]
# [Python 2](https://docs.python.org/2/), 85 bytes
```
f=lambda n:bin(int(n)).count('1')==1or any(f(n[:i])*f(n[i:])for i in range(1,len(n)))
```
[Try it online!](https://tio.run/##dVDRboMwEHvfV1jaA8k0piZhjCL1S6ZOCm0yItEDQVjbr2dXVVth1fJ0Oju2z9051i3pafKbxh6qvQWVVSARKAqS8mXXjjwlKpGbjWp7WDoLL@i9DFv5dBlCuZWegYBA6C19OqGeG0eX33LqehaCF0mmC5UA8hH8Yj/G@gyRpTotUiUffmkqz5j1h6byNANbqDTPZtxCrfWdZKwdaDxUjhPFwTUeYYBF1x5503rohcBKs91SgPPwdsZaXQL92HjbDI5ZK@wsURtROfSu693gKLo97AD9cYK/NoXT/LS5ztXtBpp7kxuoTfZWrJN/wNfcaJMs4x0davvlwCDn2MNoVGMEl0MwiwbMfYXcQGq0nL4B "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~28~~ ~~24~~ 23 bytes
*-4 bytes thanks to Jo King*
```
{?/^[0*@(2 X**^32)]+$/}
```
[Try it online!](https://tio.run/##NYzBCsIwEETv@xU5FGnjQrO76TZBRD9DECsezKmi1FMRvz0mBy/zmMcwr/sya36sZpPMPn8O/XR29tiyOVk7CXeXbdN/8/u2mtQ2186k5wKeAyGQeoRAkWs6LoVc0a4QQRBY/Bhi4aDCUkfynxalnogUQf1AXF9kjCS7/AM "Perl 6 – Try It Online")
Handles powers up to 231.
[Answer]
# APL(NARS), 154 chars, 308 bytes
```
∇r←f w;g;b;z;k
g←{⍵≤0:1⋄t=⌊t←2⍟⍵}⋄→A×⍳∼w≤9⋄r←g w⋄→0
A: z←w⋄b←0⋄k←1
B: b+←k×10∣z⋄z←⌊z÷10
→C×⍳∼g b⋄r←∇z⋄→0×⍳r
C: k×←10⋄→B×⍳z≠0
r←0
∇
h←{⍵=0:0⋄f ⍵}
```
The function for the exercise it is h. The algorithm not seems exponential or factorial... test:
```
h¨ 4281 164 8192 81024 101
1 1 1 1 1
h¨ 0 1 3 234789 256323 8132
0 1 0 0 0 1
h 81024256641116
1
h 64512819237913
0
```
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
f=lambda n,k=10:k<11*n>n%k&n%k-1<(n<k)|f(n/k)|f(n,10*k)*n
```
[Try it online!](https://tio.run/##NY7dCoMwDIWv9Sly02mlsqat9QfnuziGTLpFcQ4c7N1di@wiCd8JyTnzZ71PpPZ9uDz65/XWAwl3Qdm4FjGjjpg7@cqxTal1/DukdD6GQJk5ntE@TAtsMBKkcZQaVaEAtEZAhbUKXSoPKIMcUP9FVVhrENFy4Q@lAC1AaVNWtZ@F1cqzNQWq8EiXNWoe8yaOgh8Fv81DNC8jrZAwNG/IO2CvBBj4dOAjch4f@/0H "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 86 bytes
```
lambda n:re.match('^(%s)*$'%'|'.join('0*'+`1<<k`for k in range(n)),`n`)and 0;import re
```
[Try it online!](https://tio.run/##bc5NDoIwEIbhvaeYhaQtElJQ8Q@u4AmMoUorCExJqQsS745GTWTR7Zsn30w32FJjPKrsNDaivRQCcG9k2Ap7LSk5U69n/px45EnCu66QEu6TRR6laZ0rbaCGCsEIvEmKjAU55kxgAfxQtZ02FowclWh6OQRgzcOWA2Rw1CgD4LOZ6Hv5NopGyYpBlv3IpPPI2fmnfocn2mmXU/vPsRO731g7zyXOunHWrXN3N7HjCw "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
->n{a=*b=1;a<<b*=2until b>n;n.to_s=~/^(0*(#{a*?|}))*$/}
```
[Try it online!](https://tio.run/##FYrdDoIgAIVfha0ulJHyY4ZT7EEYNbhwcytypRsN6NUJb87Zd77z3sw3TSKdRuu1gEaQXg@DgYJudp0fwIy2t9X6un/Er74VGBYHr@E1xLKExzom2VBOECBtgwAnHd0T0ww4jwgwBChrLrzLfW4ZZbtn@UUwUdVTLz64sADp0CSdUjH9AQ "Ruby – Try It Online")
Output is `0` if true and `nil` if false.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->n{n.to_s=~/^(0*(#{(0..n).map{|x|2**x}*?|}))*$/}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vJD@@2LZOP07DQEtDuVrDQE8vT1MvN7GguqaixkhLq6JWy76mVlNTS0W/9r@GoZ6esRFcukAhukInLboiNraWq0AhLdrQwDD2PwA "Ruby – Try It Online")
Only works in theory. Takes forever for large values of `n`
[Answer]
# PHP, 101 bytes
Can´t seem to get this below 100; but I could get it *to* 100 if `101` was a falsy case.
```
function f($s){for($x=.5;$s>=$x*=2;)if(preg_match("/^$x(.*)$/",$s,$m)?!~$m[1]||f(+$m[1]):0)return 1;}
```
returns \$NULL\$ for falsy and \$1\$ for truthy.
[Try it online](http://sandbox.onlinephpfunctions.com/code/06b5edb87454764e8febe11775118f81a28a211b).
**variations:**
```
for($x=.5;$s>=$x*=2;)
while($s>=$x=1<<$i++) # yields notices "undefined variable $i"
?!~$m[1]||f(+$m[1]):0
?~$m[1]?f(+$m[1]):1:0
```
# PHP 5 or older, 95 bytes
```
function f($s){while($s>=$x=1<<$i++)if(ereg("^$x(.*)$",$s,$m)?$m[1]>""?f(+$m[1]):1:0)return 1;}
```
[Answer]
# [Red](http://www.red-lang.org), 212 211 bytes
```
func[n][g: func[x][(log-2 do x)% 1 = 0]repeat i 2 **((length? s: form n)- 1)[b: a:
copy[] k: i foreach c s[append b c if k % 2 = 0[alter a g rejoin b
b: copy[]]k: k / 2]append a g form c if all a[return on]]off]
```
[Try it online!](https://tio.run/##TY3BboMwEETv/oq5RIJIUbGhKUGK8g@9Wj4YWBOKayOHSOnXU5e2kNvMzszbQO38Tq1UzFSzubtGOiW7Cot8KJlY3x0EWo9HugPHGZkKNJKe0ENgv08SS66brhfc4sqHT7j0AJ7KuoKuWOPHL6kwVLEeU9LNFQ1uUo8juRZ1NL3BgF2ERbbUdqIAjQ6BPnzvULMI@qWoSBnwAqH@1j@15eUC0dZCy0DTPTh4p5Q3Rs1j6N0Eg0KUnP0bfixWXfKTeDKZ2CKebZNsu64qX5XIi7fytNnXYy7yJ2ou2PwN "Red – Try It Online")
Another long submission, but I'm not comletely dissatisfied, because there is no built-in for finding all substrings in Red.
## More readable:
```
f: func [ n ] [
g: func [ x ] [ (log-2 do x) % 1 = 0 ]
repeat i 2 ** ((length? s: form n) - 1) [
b: a: copy []
k: i
foreach c s [
append b c
if k % 2 = 0 [
append a g rejoin b
b: copy []
]
k: k / 2
]
append a g form c
if all a[ return on ]
]
off
]
```
[Answer]
# Axiom, 198 bytes
```
G(a)==(a<=1=>2>1;x:=log_2 a;x=floor x)
F(n)==(n<=9=>G n;z:=n;b:=0;k:=1;repeat(b:=b+k*(z rem 10);z:=z quo 10;if G b and F z then return 2>1;k:=k*10;z<=0=>break);1>1)
H(n:NNI):Boolean==(n=0=>1>1;F n)
```
ungolf and test
```
g(a)==(a<=1=>2>1;x:=log_2 a;x=floor x)
f(n)==
n<=9=>g n
z:=n;b:=0;k:=1
repeat
b:=b+k*(z rem 10);z:=z quo 10;
if g b and f z then return 2>1
k:=k*10
z<=0=>break
1>1
h(n:NNI):Boolean==(n=0=>1>1;f n)
(15) -> [[i,h i] for i in [4281,164,8192,81024,101]]
(15) [[4281,true],[164,true],[8192,true],[81024,true],[101,true]]
Type: List List Any
(16) -> [[i,h i] for i in [0,1,3,234789,256323,8132]]
(16) [[0,false],[1,true],[3,false],[234789,false],[256323,false],[8132,true]]
Type: List List Any
(17) -> [[i,h i] for i in [81024256641116, 64512819237913]]
(17) [[81024256641116,true],[64512819237913,false]]
Type: List List Any
(18) -> h 44444444444444444444444444
(18) true
Type: Boolean
(19) -> h 44444444444444444128444444444
(19) true
Type: Boolean
(20) -> h 4444444444444444412825444444444
(20) false
Type: Boolean
(21) -> h 2222222222222244444444444444444412822222222222210248888888888882048888888888888888
(21) true
Type: Boolean
(22) -> h 222222222222224444444444444444441282222222222225128888888888882048888888888888888
(22) true
Type: Boolean
```
[Answer]
# Powershell, 56 bytes
```
$x=(0..63|%{1-shl$_})-join'|0*'
"$args"-match"^(0*$x)+$"
```
Test script:
```
$f = {
$x=(0..63|%{1-shl$_})-join'|0*'
"$args"-match"^(0*$x)+$"
}
@(
,(4281 ,$true)
,(164 ,$true)
,(8192 ,$true)
,(81024 ,$true)
,(101 ,$true)
,(0 ,$false)
,(1 ,$true)
,(3 ,$false)
,(234789 ,$false)
,(256323 ,$false)
,(8132 ,$true)
,("81024256641116" ,$true)
,("64512819237913" ,$false)
) | % {
$n, $expected = $_
$result = &$f $n
"$($result-eq$expected): $result <- $n"
}
```
Output:
```
True: True <- 4281
True: True <- 164
True: True <- 8192
True: True <- 81024
True: True <- 101
True: False <- 0
True: True <- 1
True: False <- 3
True: False <- 234789
True: False <- 256323
True: True <- 8132
True: True <- 81024256641116
True: False <- 64512819237913
```
Explanation:
Builds a regex like `^(0*1|0*2|0*4|0*8|0*16|0*32|…)+$` of powers of 2, and tests it on arguments.
[Answer]
# Japt `-!`, 12 bytes
Takes input as a string.
```
ÊÆòXÄÃex_&ZÉ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=ysbyWMTDZXhfJlrJ&input=IjQyODEiCi0h)
[Answer]
## C# 157 bytes
```
bool P(string s,int i=1)=>i>=s.Length?((Func<ulong,bool>)((x)=>(x!=0)&&((x&(x-1))==0)))(ulong.Parse(s)):(P(s,i+1)||(P(s.Substring(0,i))&&P(s.Substring(i))));
```
You can [Try it online](https://tio.run/##XZHfT8IwEMef2V9xLob04iDrNgaIwwcTnzBZwoMPxocyKjQZrWk3xIz97dgOjMGm6V0/d/e9/ijMoFCan2oj5AaW36biu5nXc8P7rFelKKAomTGQa7XRbOc1Xu/CTcUqa/ZKrOGFCUkQmtNKqRJyYirt9EwgZAUio5jNxTwzwwWXm2r7SMhzLYuHulRyE7iSORJysEnkcJOF2O/bXZ8cBhQxs3tE0qUOc6YNJwbxntgegbijeDw6d7isV@eeJAwEWoVraBHi7GQvdgZv77BmFYMMJP@CX9aAn0QT6gfg0zRxZkKn0dmGUQdo2IXDzndL7JYoTsaTaeeN0jiKzyXxX6nFaUIpTR1JkxGNnHI8ntLYh9Y9@If9BVZsgeyZhqLWmruXk90x0cYbD/6N3pOSRpV8@KpFxRdCcnLrPysNst6tuIbmotKC5qYurZqBJicXiq2PsyvNXuvZ2Z5@AA)
[Answer]
# APL(NARS), 70 chars, 140 bytes
```
P←{k←↑⍴⍵⋄x←11 1‼k k⋄y←⍵⋄∪{x[⍵;]⊂y}¨⍳↑⍴x}
f←{⍵=0:0⋄∨/∧/¨y=⌊y←2⍟⍎¨¨P⍕⍵}
```
test:
```
f¨ 4281 164 8192 81024 101
1 1 1 1 1
f¨ 0 1 3 234789 256323 8132
0 1 0 0 0 1
f 126
0
```
i not try to do other more big numbers...
i have to note that P is not normal partition, but it is one partition
where all element are subset that have member all consecutive, for example
```
⎕fmt P 'abc'
┌4──────────────────────────────────────────────────┐
│┌1─────┐ ┌2─────────┐ ┌2─────────┐ ┌3─────────────┐│
││┌3───┐│ │┌2──┐ ┌1─┐│ │┌1─┐ ┌2──┐│ │┌1─┐ ┌1─┐ ┌1─┐││
│││ abc││ ││ ab│ │ c││ ││ a│ │ bc││ ││ a│ │ b│ │ c│││
││└────┘2 │└───┘ └──┘2 │└──┘ └───┘2 │└──┘ └──┘ └──┘2│
│└∊─────┘ └∊─────────┘ └∊─────────┘ └∊─────────────┘3
└∊──────────────────────────────────────────────────┘
```
note that is absent the element ((ac) (b)) or better ,,¨('ac')'b'
```
⎕fmt ,,¨('ac')'b'
┌2─────────┐
│┌2──┐ ┌1─┐│
││ ac│ │ b││
│└───┘ └──┘2
└∊─────────┘
```
[Answer]
# POSIX ERE, 91 bytes
```
(0*([1248]|16|32|64|128|256|512|1024|2048|4096|8192|16384|32768|65536|131072|262144|524288))+
```
This is totally cheating, based on the text *large numbers (not really necessary to be handled by your code)* in the question; it handles all values in the size range of the examples. Obviously can be extended up to full range of 32- or 64-bit integer types at the expense of size. I mainly wrote it as a demonstration of how the problem naturally fits the tool. A fun exercise would be rewriting it as a program that generates the ERE for arbitrary range then matches against it.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), `-DA=asprintf(&c,` + 108 = 124 bytes
```
p,c;f(a,i){c="^(0*(1";for(i=0;i<31;)A"%s|%d",c,1<<++i);A"%s))+$",c);regcomp(&p,c,1);a=!regexec(&p,a,0,0,0);}
```
[Try it online!](https://tio.run/##XYrBCoJAFEXX9RU2ZMzLCZyZIOPpIugzIhheKgNloi0C89ebtAIt7urcc2iVEzlXCsKMG2GhoYQdebjkkmF2rbhNQrSxlgg75tcP/8QECRnHQWAB@wsgmHcfYJXmdL2UfFH2BaBJZt2V3lPqLyPCfoCts8XNuxhbcGimk7LqMONMqmjt@adDwcSXGAAOPpKhGgVv/C@0Ggda/Xql15toOxQf/m30oPXbtO5J2dnktVvtd4mpv@GCxAs "C (gcc) – Try It Online")
This builds a regex of the powers of 2 up to 2\*\*32, and then matches the input string against it.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
f=(x,c=v=1)=>x<v?x.match('^('+c+')+$'):f(x,c+'|'+(v*=2))
```
[Try it online!](https://tio.run/##XVBBboMwELzzij1UMg6QYJtSUpX0IVUjOcSUVMRG2CFE6t/pOlGrEB9seWZ3Zna/5SBt1R86l2izV9NUl@EYV@VQMlpuxrfhfVwepauakGxDElURodEToa@1r4rID4nCYVFySqfKaGtatWzNV/iR8YLFwPIshoKtub9Tjp8UwRhEDFxkL8Ua3@dccOF5gVUsZZ9o14UjlBtAj4gQSmmwWgReEa7H9SfXXCDMEp4UCaMB2sCcYnmSgemBJXlGA59gzrtGgT4dd6qHg7OqreFgQUJnzoiYGrhvwsCzJvRCiAYp/J1atlYhk0IltTYOdgp61fXKKu3UHqQFvh2hxiRSX2DEqP@9N9VAPIgFt8XcA9cN3dudFTRyUH53qLsHwWF3coBDaRA@uXgYF5MnAmdarKZf "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
The three-dimensional Levi-Civita symbol is a function `f` taking triples of numbers `(i,j,k)` each in `{1,2,3}`, to `{-1,0,1}`, defined as:
* `f(i,j,k) = 0` when `i,j,k` are not distinct, i.e. `i=j` or `j=k` or `k=i`
* `f(i,j,k) = 1` when `(i,j,k)` is a cyclic shift of `(1,2,3)`, that is one of `(1,2,3), (2,3,1), (3,1,2)`.
* `f(i,j,k) = -1` when `(i,j,k)` is a cyclic shift of `(3,2,1)`, that is one of `(3,2,1), (2,1,3), (1,3,2)`.
The result is the [sign](https://en.wikipedia.org/wiki/Parity_of_a_permutation) of a permutation of `(1,2,3)`, with non-permutations giving 0. Alternatively, if we associate the values `1,2,3` with orthogonal unit basis vectors `e_1, e_2, e_3`, then `f(i,j,k)` is the [determinant](https://en.wikipedia.org/wiki/Determinant) of the 3x3 matrix with columns `e_i, e_j, e_k`.
**Input**
Three numbers each from `{1,2,3}` in order. Or, you may choose to use zero-indexed `{0,1,2}`.
**Output**
Their Levi-Civita function value from `{-1,0,1}`. This is code golf.
**Test cases**
There are 27 possible inputs.
```
(1, 1, 1) => 0
(1, 1, 2) => 0
(1, 1, 3) => 0
(1, 2, 1) => 0
(1, 2, 2) => 0
(1, 2, 3) => 1
(1, 3, 1) => 0
(1, 3, 2) => -1
(1, 3, 3) => 0
(2, 1, 1) => 0
(2, 1, 2) => 0
(2, 1, 3) => -1
(2, 2, 1) => 0
(2, 2, 2) => 0
(2, 2, 3) => 0
(2, 3, 1) => 1
(2, 3, 2) => 0
(2, 3, 3) => 0
(3, 1, 1) => 0
(3, 1, 2) => 1
(3, 1, 3) => 0
(3, 2, 1) => -1
(3, 2, 2) => 0
(3, 2, 3) => 0
(3, 3, 1) => 0
(3, 3, 2) => 0
(3, 3, 3) => 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ṁ4IṠS
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bmBNEnhuaBT/zPhuZczwrU7IsOH4oKsR/8 "Jelly – Try It Online")
### Algorithm
Let's consider the differences **j-i, k-j, i-k**.
* If **(i, j, k)** is a rotation of **(1, 2, 3)**, the differences are a rotation of **(1, 1, -2)**. Taking the sum of the signs, we get **1 + 1 + (-1) = 1**.
* If **(i, j, k)** is a rotation of **(3, 2, 1)**, the differences are a rotation of **(-1, -1, 2)**. Taking the sum of the signs, we get **(-1) + (-1) + 1 = -1**.
* For **(i, i, j)** (or a rotation), where **i** and **j** may be equal, the differences are **(0, j-i, i-j)**. The signs of **j-i** and **i-j** are opposite, so the sum of the signs is **0 + 0 = 0**.
### Code
```
ṁ4IṠS Main link. Argument: [i, j, k]
ṁ4 Mold 4; yield [i, j, k, i].
I Increments; yield [j-i, k-j, i-k].
Ṡ Take the signs, replacing 2 and -2 with 1 and -1 (resp.).
S Take the sum.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
```
lambda i,j,k:(i-j)*(j-k)*(k-i)/2
```
[Try it online!](https://tio.run/##XcoxCoNAEEbhWk/xN@JumEVcO0FPkkYRyczoKmLj6TfGQjDNKz7eeuyfJfg4osE7Tt3cDx2YhLQ27MS@jDg9q45tcW7LBgYHlARPqOo0@ZE86TL9s2TdOOwwTBCCWkLuWmR@yJFhvDl@AQ "Python 2 – Try It Online")
### Algorithm
Let's consider the differences **i-j, j-k, k-i**.
* If **(i, j, k)** is a rotation of **(1, 2, 3)**, the differences are a rotation of **(-1, -1, 2)**. Taking the product, we get **(-1) × (-1) × 2 = 2**.
* If **(i, j, k)** is a rotation of **(3, 2, 1)**, the differences are a rotation of **(1, 1, -2)**. Taking the product, we get **1 × 1 × (-2) = -2**.
* For **(i, i, j)** (or a rotation), where **i** and **j** may be equal, the differences are **(0, i-j, j-i)**. Taking the product, we get **0 × (i-j) × (j-i) = 0**.
Thus, dividing the product of the differences by **2** yields the desired result.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes
```
Signature
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/A/ODM9L7GktCj1f0BRZl5JtLKOgpKCrp2Cko5CWrRybKyCmoK@g0JIaUFOanF0taGOgpGOgnEtEMf@BwA "Wolfram Language (Mathematica) – Try It Online")
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 18 bytes
Saved 2 bytes thanks to Martin Ender.
```
Det@{#^0,#,#^2}/2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfJbXEoVo5zkBHWUc5zqhW30jtf0BRZl5JtLKOgpKCrp2Cko5CWrRybKyCmoK@g0JIaUFOanF0taGOgpGOgnEtEMf@BwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# x86, 15 bytes
Takes arguments in `%al`, `%dl`, `%bl`, returns in `%al`. Straightforward implementation using Dennis's formula.
```
6: 88 c1 mov %al,%cl
8: 28 d0 sub %dl,%al
a: 28 da sub %bl,%dl
c: 28 cb sub %cl,%bl
e: f6 e3 mul %bl
10: f6 e2 mul %dl
12: d0 f8 sar %al
14: c3 retq
```
Aside: I think I understand why `%eax` is the "accumulator" now...
[Answer]
# Octave, 20 bytes
```
@(v)det(eye(3)(:,v))
```
Pretty direct implementation of the determinant formula. Permutes the columns of the identity matrix then takes the determinant.
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
(x#y)z=(x-y)*(y-z)*(z-x)/2
```
[Try it online!](https://tio.run/##TYpBDkAwFAWv8hKb/6Ul2HIEJxCLLiS@IoJF27h7dcdmMpPMbC47rWuM5DLPoSOnPefkdUgM2nFZx83Ijg6bOXocp@w3BiJRWBQsK5Agw8LJ8UDQagxVUTRjGv5hvxjjCw "Haskell – Try It Online")
Nasty IEEE floats...
[Answer]
# JavaScript (ES6), 38 bytes
Overcomplicated but fun:
```
(a,b,c,k=(a+b*7+c*13)%18)=>k-12?+!k:-1
```
[Try it online!](https://tio.run/##ZZJNa4QwEEDv/oopWEzWZGkmh5YtcfHQQmmhP0CEjan2w2UtWnoRf7td6@LqDgQPz3nJO8yX/bWNqz@/f@Shesv7wvTMikw4URpmw2x1G7qV0vxa3XETlVLhNrwqN1L1MRhIPIAkUQKGkwq4ScWMICF6SZBYSCwcLXUmmlh6tORyaP4YkkQkiTglThchaUTSiFPjjJwa1YIgmZlbmiTqKVEtyIV1KpRqgZAMXWiaPKaJNSV66b3nxeuiqh@s@2AsSf6X5PivTjmYCFx1aKp9vt5X72zH/NZ2wm@z4eM6DjICv63z5rgyxbhevBsIGAMD3kLw@hzABoLH@Okl6Hac938 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 28 bytes
Using the standard formula:
```
(a,b,c)=>(a-b)*(b-c)*(c-a)/2
```
[Try it online!](https://tio.run/##ZZJNa4QwEEDv/oo5CCYl2TaT25ZYPLRQWugPCMLGVPvBsilaehF/u9WupLoDksPLPPMO8@l@XOfbj69veQqv9diYkTlRCc9Nzpys@BWrpJ9OLx2/xrEAAzYBsFYJmL9SwE0pVgQJ0VuCxEJi4dlS/0QTS58tuR1aP4YkEUkixsT4IySNSBoxNq7I0qg2BMnM2tIkUcdEtSEX1lIo1QYhGbrQNHlMEysmJuVtkhS7JrT3zr8zZu3fakx3bcnB5ODDqQvHencMb@zA0t4NIu2r@fADB5lD2rd1N61MsyzVMBMwBmZ8B9nLUwZ7yB6Kx@dsOHA@/gI "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 5 bytes
*1 byte saved thanks to @Emigna*
```
ĆR¥P;
```
[Try it online!](https://tio.run/##MzBNTDJM/f//SFvQoaUB1v//RxvpKBjqKBjHAgA "05AB1E – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~11~~ 9 bytes
*2 bytes saved thanks to @ngn*
```
+/×2-/4⍴⎕
```
[Try it online!](https://tio.run/##Lcy9DUBQAEXh3hR6EXGvhSRCI6E1AQ2dWMQGNnmLPH8nt7jJKb567PNmqvuhi2GZ25gV16G8qMJ6hm1/W2yTMn2W/C/e34suuuimm@6vC0c4whGOcIQjHOEIxzjGMY5xjGMc4xjnfd8 "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 28 bytes
```
->a,b,c{(a-b)*(b-c)*(c-a)/2}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ0knuVojUTdJU0sjSTcZSCbrJmrqG9X@L7KN1jLQ0zOK5SrSKyjKTylNLtEo0inS1MtNLKiuyawBa7XNtC5QiM7USYsGc2Nja/8DAA "Ruby – Try It Online")
[Answer]
## CJam (16 bytes)
```
1q~{)1$f-@+:*\}h
```
[Online demo](http://cjam.aditsu.net/#code=1q~%7B)1%24f-%40%2B%3A*%5C%7Dh&input=%5B3%202%202%5D). Note that this is based on [a previous answer of mine](https://codegolf.stackexchange.com/a/143775/194) which uses the Levi-Civita symbol to calculate the Jacobi symbol.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 56 bytes
```
->t{t.uniq!? 0:(0..2).any?{|r|t.sort==t.rotate(r)}?1:-1}
```
[Try it online!](https://tio.run/##bU7bioQwDH33K7IFoYIW67wJHT9EZOhqZQWn7fYCzlq/3Smu7tMSQpJzkpxj/OdrH9le3N3qiJfT90cDZY1LQqqMcPlq1mCCI1YZx5gjRjnuBDbZ1tC6oNuuvNPeWWDQlvkVNGZBz@Gvof@xMbqkpXmV3zpihBbx/fDQwjx9VJqUxLeM/Ewan0IZEbz/gkFBmGQEchCLFn08CglAPyspopeDIk@u17CEZYuMEdbPLlJjeyx1ETuMo9RCcYe0soBTmyFIoT0//95clbFLCRpAmluLoAY08mlGXSLksL8B "Ruby – Try It Online")
Once we rule out cases where the values of the triplet are not unique, `t.sort` is equivalent to (and shorter than) `[1,2,3]` or `[*1..3]`
```
->t{
t.uniq! ? 0 # If applying uniq modifies the input, return 0
: (0..2).any?{|r| # Check r from 0 to 2:
t.sort==t.rotate(r) # If rotating the input r times gives [1,2,3],
} ? 1 # return 1;
:-1 # else return -1
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ṁ±Ẋ-S:←
```
[Try it online!](https://tio.run/##yygtzv7//@HOxkMbH@7q0g22etQ24f///9FGOsY6hrEA "Husk – Try It Online")
# Explanation
Straight port of Dennis's [Jelly answer](https://codegolf.stackexchange.com/a/160365/78915). `S:←` copies the head of the list to the end, `Ẋ-` takes adjacent differences, and `ṁ±` takes the sign of each element and sums the result.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
⁼QȧIḂÐfḢ
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//4oG8UcinSeG4gsOQZuG4ov///1szLCAyLCAxXQ "Jelly – Try It Online")
Seems too ungolfed. :(
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 13 bytes
```
L,@dV@GÑ_@€?s
```
[Try it online!](https://tio.run/##S0xJKSj4/99HxyElzMH98MR4h0dNa@yL/6vkJOYmpSQqGNoBkbGdEZc/F5KQkZ2hnSG6kDFI6D8A "Add++ – Try It Online")
[Answer]
**SHELL**, **44 Bytes**
```
F(){ bc<<<\($2-$1\)*\($3-$1\)*\($3-$2\)/2;}
```
tests :
```
F 1 2 3
1
F 1 1 2
0
F 2 3 1
1
F 3 1 2
1
F 3 2 1
-1
F 2 1 3
-1
F 1 3 2
-1
F 1 3 1
0
```
Explanation :
```
The formula is : ((j - i)*(k - i)*(k - j))/2
```
**BC**, **42 Bytes**
```
define f(i,j,k){return(j-i)*(k-i)*(k-j)/2}
```
tests:
```
f(3,2,1)
-1
f(1,2,3)
1
f(1,2,1)
0
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
äN§lüy²Å
```
[Run and debug it](https://staxlang.xyz/#p=844e156c8179fd8f&i=[1,1,1]%0A[1,1,2]%0A[1,1,3]%0A[1,2,1]%0A[1,2,2]%0A[1,2,3]%0A[1,3,1]%0A[1,3,2]%0A[1,3,3]%0A[2,1,1]%0A[2,1,2]%0A[2,1,3]%0A[2,2,1]%0A[2,2,2]%0A[2,2,3]%0A[2,3,1]%0A[2,3,2]%0A[2,3,3]%0A[3,1,1]%0A[3,1,2]%0A[3,1,3]%0A[3,2,1]%0A[3,2,2]%0A[3,2,3]%0A[3,3,1]%0A[3,3,2]%0A[3,3,3]&a=1&m=2)
Translates to `-(b-a)(c-b)(a-c)/2`.
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
1#.2*@-/\4$]
```
[Try it online!](https://tio.run/##Tc0xCsJQFETRPqsYVAiK@ZoZq4AgCFZW1lqJQWzcf/U1VS6PVwxcOJ@6KO2o46BWW@01/L8rOt@ul9ovizenbnc/rB513ah5Pd9fjeqn4zBH5mFmZmZmYRZmmTMTNVETNVETNVETNVETDdEQDdEQDdEQDdEQnUbqDw "J – Try It Online")
Direct translation of Uriel's APL solution into J.
## Explanation:
`4$]` Extends the list with its first item
`2 /\` do the following for all the overlapping pairs in the list:
`*@-` find the sign of their difference
`1#.` add up
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
änUÌ xg
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=5G5VzCB4Zw==&input=WzEsMiwzXQ==)
---
## Explanation
```
:Implicit input of array U
ä :Get each consecutive pair of elements
n :Reduce by subtracting the first from the last
UÌ :But, before doing that, prepend the last element in U
g :Get the signs
x :Reduce by addition
```
---
## Alternative
Takes input as individual integers.
```
NänW ×z
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=TuRuVyDXeg==&input=MSwyLDM=)
[Answer]
# Java 8, 28 bytes
```
(i,j,k)->(i-j)*(j-k)*(k-i)/2
```
Port of [*@Dennis*' Python 2 answer](https://codegolf.stackexchange.com/a/160375/52210).
[Try it online.](https://tio.run/##ZZJBTsMwEEX3nGKUlUPiIGZ2VHADuukSWJg0INupWzVuJYR69uA4WdB@yflSxn6at/jOnI12Wz@2vRkGejU2/N4R2RC745dpO1pPv3lArZrS1lO6nL5cpdtL@tIZoom2pTUFeqZR2drVvtQvympX3iunfUqvbfnA42omDqfPPhELeN7bLe2SgNrEow3fbx@mnJfHbojqsabp5I1XI8aR3IwYQUaQERQEBUG5ARlVGVUZVRlVGVUZVRlVGVUZVQVVBVUFVQVVBVUFVQVVBVXln@p1v3JN8hts41yXzc8Qu12zP8XmkIoU@6BsVdRF5XL6qnh6j0UVmnYp6bLlMv4B)
[Answer]
# [Python](https://docs.python.org/2/), 33 bytes
```
lambda i,j,k:(i^j!=k or-~j-i)%3-1
```
[Try it online!](https://tio.run/##VY7NCsMgEAbP8Sm2h4KCQl1vAd@kFFLaEJM0DWIpvfTV7U@MccHL8I3LzK/Q3SeMrT3GsbmdLw042cuh5u7U7@wAd6/evXJib5SOz86NV9A1sIr/NSEDWHDT/AhcsMp/oU0Lq2bvpgBZlN7aEDnXEn5PSDgItiJSNAUilZHKuMg6oaGyWWRVzPk00g6kHZg7ls9IQ5CGYA5ZMYXoDZGuWTa0w@QOvWEppwylN0Y6l7ahpw2Vc8cH "Python 2 – Try It Online")
I tried for a while to beat the [product-of-differences approach](https://codegolf.stackexchange.com/a/160375/20260), but the best I got was 1 byte longer.
] |
[Question]
[
I find it fascinating how the letters "H" and "I" are very similar. "H" is a horizontal stroke surrounded by two vertical strokes; "I" is a vertical stroke surrounded by two horizontal strokes (depending on your font). I bet this could be nested... You know what that reminds me of? **Fractals**!!!
Let's define the "IHIH" pyramid as follows: The first iteration is this ASCII representation of the letter "I":
```
---
|
---
```
The next iteration has a vertical stroke on either side.
```
| |
|---|
| | |
|---|
| |
```
If you view the "I" in the middle as a single horizontal stroke, then this second iteration is basically an "H". The third iteration adds a horizontal stroke on the top and bottom
```
-------
| |
|---|
| | |
|---|
| |
-------
```
Again, if you view the "H" in the middle as a single vertical stroke, then this iteration is basically an "I". This pattern continues, alternating between "H"s and "I"s on every iteration. For reference, here are the first 6 iterations:
```
1:
---
|
---
2:
| |
|---|
| | |
|---|
| |
3:
-------
| |
|---|
| | |
|---|
| |
-------
4:
| |
|-------|
| | | |
| |---| |
| | | | |
| |---| |
| | | |
|-------|
| |
5:
-----------
| |
|-------|
| | | |
| |---| |
| | | | |
| |---| |
| | | |
|-------|
| |
-----------
6:
| |
|-----------|
| | | |
| |-------| |
| | | | | |
| | |---| | |
| | | | | | |
| | |---| | |
| | | | | |
| |-------| |
| | | |
|-----------|
| |
```
# The Challenge:
Write a program or function that outputs the *N'th* iteration of the IHIH pyramid, and an optional trailing newline. Your input will be a single positive integer in whatever reasonable format you want. You do not have to handle invalid inputs, e.g. non-integers, numbers smaller than 1, etc. Your program must at the very least produce the right output for inputs up to 20. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), standard loopholes are not allowed and the shortest answer in bytes wins!
[Answer]
# Python, ~~165~~ ~~145~~ ~~133~~ 123 bytes
A recursive solution:
```
def i(e):
d="|";a=e*2;x=d+" "*(a-1)+d
if e<1:return d
if e%2:d,x=[" ","-"*(a+1)]
return[x]+[d+z+d for z in i(e-1)]+[x]
```
Called with `print ("\n".join(i(int(sys.argv[1]))))`, where the parameter is the iteration number of the IHIH pyramid.
Thanks to @DJMcMayhem for saving 20 bytes. Taking the idea behind those suggestions further saved another 12 bytes. Thanks to @Maltysen for suggestions that trimmed some more bytes.
The function sets the delimiter `d` to `"|"` and the intervening spaces to `" "` (for odd-numbered iterations), deals with returning in the degenerate case, then resets the delimiter to `" "` and the intervening spaces to `"-"` for even-numbered iterations. The function returns a list of strings for each line of the IHIH, having embedded the result of a recursive call to the function in the right place within the list.
[Answer]
# [Cheddar](https://github.com/cheddar-lang/Cheddar), ~~186~~ ~~177~~ ~~165~~ ~~154~~ ~~148~~ 131 bytes
```
(n,b?,c?,q?,g=s->(n-=1)<0?s:g((q=(c=s.lines[0].len)%4>2?b='|'+" "*c+"|":b='-'*(c+2))+"\n"+s.sub(/^|$/gm,q?'|':' ')+"\n"+b))->g("|")
```
Uses recursion. Will add explanation once done golfing.
[Try it online!](http://cheddar.tryitonline.net/#code=KG4sYj8sYz8scT8sZz1zLT4obi09MSk8MD9zOmcoKHE9KGM9cy5saW5lc1swXS5sZW4pJTQ-Mj9iPSd8JysiICIqYysifCI6Yj0nLScqKGMrMikpKyJcbiIrcy5zdWIoL158JC9nbSxxPyd8JzonICcpKyJcbiIrYikpLT5nKCJ8Iik&input=MQ)
## Explanation
This one is a bit complex too keep track off all the variables I'm using but I'll try to keep it simple:
```
(
n, // Input
b?, // Stores row to add to top/bottom
c?, // Width of string
q?, // false if I-ifying. true if not
g=
s-> // Main logic, s is generated string
(n-=1)<0 ? s : // Decrease input each iteration. Stop when 0
g( // Recurse with....
(
q= ( // Set `q` true if h-ifying. false if I-ifying
c=s.lines[0].len // Set `c` to width of string
) % 4>2 ?
b='|'+" "*c+"|" : // Set `b` to top/bottom row adding
b='-'*(c+2) // `*` is repeat, c is from before
) + "\n" +
s.sub(/^|$/gm, // Add the following to beginning/end of each line
q?'|':' ' // if H-ifying, add `|`s if I-ifying add spaces
) + "\n" + b // Add bottom row, generated from before
)
) -> g("|") // Middle item is `|`
```
This was a pain to golf but its 55 bytes shorter than original.
[Answer]
# Python 2, 93 bytes
Leaky Nun saved 7 bytes.
```
r=range(input()+1)
r=r[:0:-1]+r
for y in r:print''.join('| -'[[x%2,y%2+1][x&-2<y]]for x in r)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~50~~ ~~40~~ ~~31~~ 25 bytes
```
~~[[email protected]](/cdn-cgi/l/email-protection),J+\*\-K+2lheN+jR\*2;eN\*\-KjR"||"+\*dK+J\*dKQ]]\|~~
~~LXR"|-")CbjyW%Q2uy+K\*\-+2lhG+jR\*2;GKQ]\|~~
~~juCGQuC+K\*@"-|"H+3yH+jR\*2;GKQ\|~~
j@CBujR*@"-|"H2CjR*2;GQ\|
```
[Test suite.](http://pyth.herokuapp.com/?code=j%40CBujR%2a%40%22-%7C%22H2CjR%2a2%3BGQ%5C%7C&test_suite=1&test_suite_input=1%0A2%0A3%0A4&debug=0)
### Explanation
This is a recursive algorithm.
In each iteration, we perform three actions:
1. prepend and append a space to each line
2. transpose the array
3. prepend and append to each line either `"-"` or `"|"` depending on the number of iteration.
After the iterations, the odd-numbered outputs will be transposed. Therefore, we transpose them.
```
j@CBujR*@"-|"H2CjR*2;GQ\| input: Q
j@CBujR*@"-|"H2CjR*2;GQ\|Q implicit filling of arguments
u Q\| for Q times, starting with "|", G as current output,
H as number of iterations:
jR*2;G prepend and append a space to each line
(using each line as separator, join [" "," "])
C transpose
jR* 2 prepend and append the following to each line:
@"-|"H the H-th element of the string "-|" (modular indexing)
@CB Q select the Q-th element from [output,
transposed output] (modular indexing)
j join by newlines
```
[Answer]
# [Matricks](https://github.com/jediguy13/Matricks), ~~80~~ 62 bytes
An iterative solution (Recursion in Matricks is hard...)
Run with `python matricks.py ihih.txt [[]] <input> --asciiprint`
```
~~k124;FiQ%2:v;b[m124:Q\*2+3:1;];a{z:Q\*2+1;};:b;v[m45:1:Q\*2+3;];u{zQ\*2+1:;};;:1:n;;~~
k124;FiQ%2:v;b[m124:Q*2+3:2;];B1;:b;v[m45:2:Q*2+3;];V1;;:1:n;;
```
Explanation:
```
k124; # Set the matrix to '|'
F...:1:n;; # Repeat input times, (Q is iteration variable)
iQ%2:...:...; # if statement, check if Q is odd or even
# Q is even,
b; # Make space to the left
v[m45:2:Q*2+3;]; # Set the top 2 rows to '-'s
V1; # Rotate the matrix up 1 unit, moving the topmost row to the bottom
# Q is odd,
v; # Make space above
b[m124:Q*2+3:2;]; # Set the 2 left columns to '|'s
B1; # Rotate the matrix left 1 unit, moving the leftmost row to the right
```
[Answer]
## JavaScript (ES6), ~~92~~ 90 bytes
```
f=
(n,[h,c,v]=n&1?`-- `:` ||`)=>n?(c+=h.repeat(n+n-1)+c)+`
${f(n-1).replace(/^|$/gm,v)}
`+c:v
;
```
```
<input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o>
```
Recursive solution works by taking the previous iteration, adding the `v` character to the sides, then adding the `c` character to the corners and the `h` character along the top and bottom. The set of characters simply alternates each iteration. Edit: Saved 2 bytes by returning `v` when `n=0`.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~52~~ 43 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
```
{v=⊃⍵:h⍪⍨h⍪s,⍵,s⋄v,⍨v,s⍪⍵⍪s}⍣⎕⍪⊃v h s←'|- '
```
`v h s←'|- '` assigns the three characters to three names (**v**ertical, **h**orizontal, **s**pace)
`⊃` the first one, i.e. `|`
`⍪` make into 1×1 table
`{`...`}⍣⎕` get input and apply the braced function that many times
`v=⊃⍵:` if the top-left character of the argument is a vertical, then:
`h⍪⍨` horizontals below
`h⍪` horizontals above
`s,` spaces to the left of
`⍵,s` the argument with spaces to the right
`⋄` else:
`v,⍨` verticals to the right of
`v,` verticals to the left of
`s⍪` spaces above
`⍵⍪s` the argument with spaces below
[TryAPL online!](http://tryapl.org/?a=%u2355%7B%7Bv%3D%u2283%u2375%3Ah%u236A%u2368h%u236As%2C%u2375%2Cs%u22C4v%2C%u2368v%2Cs%u236A%u2375%u236As%7D%u2363%u2375%u236A%u2283v%20h%20s%u2190%27%7C-%20%27%7D%A81%202%203%204%205%206&run)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 84 bytes
```
,[[["|"]]:?:1]i:1:zi:ca~@nw
hh~m["-|":B]:ramggL," "ggS,?:Sz:ca:Srz:caz:Lz:ca:Lrz:ca.
```
[Try it online!](http://brachylog.tryitonline.net/#code=LFtbWyJ8Il1dOj86MV1pOjE6emk6Y2F-QG53Cmhofm1bIi18IjpCXTpyYW1nZ0wsIiAiZ2dTLD86U3o6Y2E6U3J6OmNhejpMejpjYTpMcno6Y2Eu&input=Mw)
A port of [my answer in Pyth](https://codegolf.stackexchange.com/a/90293/48934).
[Answer]
# C, 110 bytes
```
#define R(A,B,C)for(A=n,B=1;A<=n;putchar(C),A-=B|=-!A)
f(n,y,x,w,v){R(y,w,10)R(x,v,"| -"[x/2*2<y?y%2+1:x%2]);}
```
Invoke as `f(n)`. For 111 bytes, I could do:
```
f(n,y,x,w,v){for(y=n,w=1;y<=n;y-=w|=-!y,puts(""))for(x=n,v=1;x<=n;x-=v|=-!x)putchar("| -"[x/2*2<y?y%2+1:x%2]);}
```
i.e., the `#define` saves exactly one byte.
[Answer]
# Dyalog APL, 34 bytes
```
{⍉⍣⍵{b,b,⍨⍉s,⍵,⊃s b←' -|'~⊃⍵}⍣⍵⍪'|'}
```
`{`...`}⍣⍵⍪'|'` Apply function in braces `⍵` times starting with 1x1 matrix of character `|`. The result of each application is the argument for the next application.
`s b←' -|'~⊃⍵` s is space and b is the bar not in the top left corner of the argument (`' -|'~'-'` removes horizontal bar and leaves space and vertical bar)
`s,⍵,⊃s b` add space to left and right (`⊃` picks s from vector s b)
`b,b,⍨⍉` transpose and add b to left and right
For odd numbers this leaves the result transposed, so a final transpose is required.
`⍉⍣⍵` Transpose `⍵` times (once would be enough, but shorter to code this way)
[TryAPL online](http://tryapl.org/?a=%7B%u2349%u2363%u2375%7Bb%2Cb%2C%u2368%u2349s%2C%u2375%2C%u2283s%20b%u2190%27%20-%7C%27~%u2283%u2375%7D%u2363%u2375%u236A%27%7C%27%7D5&run)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 34 bytes
```
'- |'[2+∘.(≤-(1+=)×2|⌈)⍨(⌽,0,⊢)⍳⎕]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CYZcjzra0/6r6yrUqEcbaT/qmKGn8ahzia6Gobat5uHpRjWPejo0H/Wu0HjUs1fHQOdR1yIgbzNQd@x/oMb/6UAjHvX2GQJl1Wur1XXUgTIgXKT@qHerOlC10aOe7UB@cpF6mrrCo965CiVFiSlpeQol@QpAiiv90AqgcaYA "APL (Dyalog Classic) – Try It Online")
(uses `⎕io←1`)
`⍳⎕` is `1 2 ... N`
`(⌽,0,⊢)` is a train that turns it into `-N ... -1 0 1 ... N`
`∘.( )⍨` executes the parentheses for every pair of coordinates `⍺ ⍵`
the train `(≤-(1+=)×2|⌈)` or its dfn equivalent `{(⍺≤⍵)-(1+⍺=⍵)×2|⍺⌈⍵}` produces a matrix like:
```
¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1
0 1 0 0 0 0 0 0 0 1 0
0 1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 1 0
0 1 0 1 0 0 0 1 0 1 0
0 1 0 1 ¯1 ¯1 ¯1 1 0 1 0
0 1 0 1 0 1 0 1 0 1 0
0 1 0 1 ¯1 ¯1 ¯1 1 0 1 0
0 1 0 1 0 0 0 1 0 1 0
0 1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 1 0
0 1 0 0 0 0 0 0 0 1 0
¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1 ¯1
```
`'- |'[2+ ]` makes these valid indices in `⎕IO=1` and picks the corresponding characters
[Answer]
# [Cheddar](http://cheddar.vihan.org/), 107 bytes
```
(n,g=n->n?(f->f(f(g(n-1)," ").turn(1),n%2?"-":"|"))((a,b)->a.map(i->b+i+b)):["|"])->(n%2?g(n).turn(1):g(n))
```
[Try it online!](http://cheddar.tryitonline.net/#code=dmFyIGYgPSAobixnPW4tPm4_KGYtPmYoZihnKG4tMSksIiAiKS50dXJuKDEpLG4lMj8iLSI6InwiKSkoKGEsYiktPmEubWFwKGktPmIraStiKSk6WyJ8Il0pLT4obiUyP2cobikudHVybigxKTpnKG4pKTsKCm4tPnByaW50KGYobikudmZ1c2Up&input=NA)
[Answer]
# Cheddar, 85 bytes
```
(n,r=(-n|>n).map(v->abs v))->r.map(y->r.map(x->"| -"[(x&-2)<y?y%2+1:x%2]).fuse).vfuse
```
My first Cheddar answer. [Try it online!](http://cheddar.tryitonline.net/#code=cHJpbnQoKAogIChuLHI9KC1ufD5uKS5tYXAodi0-YWJzIHYpKS0-ci5tYXAoeS0-ci5tYXAoeC0-InwgLSJbKHgmLTIpPHk_eSUyKzE6eCUyXSkuZnVzZSkudmZ1c2UKKSgxMSkpOw&input=&debug=on)
If I try to write `r=(-n|>n).map(v->abs v).map`, and then `r(y->r(x->…))`, the interpreter crashes. ;-;
[Answer]
# Ruby, ~~81~~ ~~78~~ 77 bytes
This is based on [Lynn's Python answer](https://codegolf.stackexchange.com/a/90311/47581). Golfing suggestions welcome.
**Edit:** 3 bytes thanks to Lynn. Corrections and golfing 1 byte thanks to Jordan.
```
->n{r=(-n..n).map &:abs;r.map{|y|puts r.map{|x|"| -"[x&-2<y ?y%2+1:x%2]}*""}}
```
**Ungolfing:**
```
def f(n)
r = -n..n # Range from -n to n (inclusive)
r = r.map{|i|i.abs} # Turns every element of r positive
r.each do |y|
s = "" # a line of the fractal
r.each do |x| # build up the fractal based on x and y
if x/2*2 < y
s += " -"[y%2]
else
s += "| "[x%2]
end
end
puts s # print the line
end
end
```
[Answer]
## MATLAB, 168 163 bytes
This is probably not the cleverest way to do it: Expanding a string on all sides in `n` steps:
```
function s=g(n);s='|';for m=1:n;if mod(m,2);a=45;b=a;c=0;else a='|';b=0;c=a;end;s=[a repmat(b,1,2*m-1);repmat(c,2*m-1,1) s];s(:,end+1)=s(:,1);s(end+1,:)=s(1,:);end
```
Usage: Save as `g.m` (do I have to add that to the byte count?) and call e.g. `g(15)`.
Ungolfed:
```
function s=g(n)
% // Initialize s
s = '|';
for m=1:n
% // Decide if odd or even number and which symbol to add where
if mod(m,2)
a=45;b=a;c=0; % // char(45) is '-' and char(0) is ' ' (thx to Luis Mendo)
else
a='|';b=0;c=a;
end
% // Add symbols at top and left to s
s = [a repmat(b,1,2*m-1);repmat(c,2*m-1,1) s];
% // Add symbols at right and bottom to s
s(:,end+1) = s(:,1);
s(end+1,:) = s(1,:);
end
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), ~~48~~ ~~45~~ 44 bytes
This is an attempt to port my Ruby answer to Actually. This is way too long and golfing suggestions are very much appreciated. [Try it online!](http://actually.tryitonline.net/#code=dTvCsXV44pmCQeKVl-KVnGDilZ3ilZwiOzJAJTLilZsldeKVmygywrEmPEknLScgJ3wrK0UiwqNNzqMuYE0&input=NQ)
```
u;±ux♂A╗╜`╝╜";2@%2╛%u╛(2±&<I'-' '|++E"£MΣ.`M
```
Here is a 46-byte version which separates out the nested functions so that we can define `"| -"` in fewer bytes. [Try it online!](http://actually.tryitonline.net/#code=dTvCsXV44pmCQeKVl-KVnGA7MkAlMuKVmyV14pWbKDLCsSY8SSJ8IC0iRWAjIuKVneKVnCVywqNNzrVqLiIlwqNN&input=NQ)
```
u;±ux♂A╗╜`;2@%2╛%u╛(2±&<I"| -"E`#"╝╜%r£MΣ."%£M
```
**Ungolfing:**
First algorithm
```
u Increment implicit input.
;±u Duplicate, negate, increment. Stack: [-n n+1]
x♂A Range [-n, n+1). Abs(x) over the range.
╗ Save list to register 0. Let's call it res.
╜ Push res so we can iterate over it.
` Start function (with y from map() at the end)
╝ Save y to register 1.
╜ Push res so we can iterate over it.
" Start function as string (with x from map() at the end)
; Duplicate x.
2@% x mod 2.
2╛%u y mod 2 + 1.
╛(2±&<I If x&-2 < y, then y%2+1, else x%2.
'-' '|++ Push "| -" (We're inside a string right now,
so we need to push each char individually)
E Grab index of "| -"
"£ End string and turn into function.
M Map over res.
Σ. sum() (into a string) and print.
` End function.
M Map over res.
```
Second algorithm
```
u;±ux♂A╗╜ Create res as before.
`;2@%2╛%u╛(2±&<I"| -"E`# The inner function from the first algorithm put into a list.
The only change to the function is the definition of "| -".
"╝╜ £MΣ." Most of the outer function from the first algorithm as a string.
%r % %-formats the list into the outer function.
£M Turns the string into a function, maps over res.
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~19~~ ~~18~~ ~~17~~ 14 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
|╶[ e↷l|*e}╶[↷
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTdDJXUyNTc2JXVGRjNCJTIwJXVGRjQ1JXUyMUI3JXVGRjRDJTdDJXVGRjBBJXVGRjQ1JXVGRjVEJXUyNTc2JXVGRjNCJXUyMUI3,i=Mw__,v=2)
If I were allowed to output every other output rotated 90°, the last 4 characters could be removed.
Explanation (some characters have been changed to look ~monospace):
```
| push "|" - the canvas
╶[ } repeat input times
e encase the canvas in spaces horizontally
↷ rotate the canvas 90°
l|* push "-" repeated the canvas height times vertically
e and encase the canvas if two of those horizontally
╶[ repeat input times
↷ rotate the canvas 90°
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~29~~ 28 bytes
```
„|-S¹>∍ƶćsvy‚˜.Bζ}¹Fζ}»R.∞.∊
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UcO8Gt3gQzvtHnX0Htt2pL24rPJRw6zTc/Sczm2rPbTTDUTuDtJ71DEPiLv@/zcFAA "05AB1E – Try It Online")
-1 thanks to Dzaima...
This is an iterative solution.
---
Essentially This is made by creating the following pattern:
```
['|','--','|||',...]
```
Then, pairwise, transposing each element together and adding the padding.
By transposing after each iteration, we end up creating a single corner of the pattern.
Then, we can use 05AB1E's reflection commands.
---
```
„|-S # Push ['|','-']
¹>∍ # Extended to input length.
ƶ # Each element multiplied by its index.
ćs # Extract head of list, swap remainder to top.
v } # For each element in the '|-' list...
y‚˜ # Wrap current 2D array with new entry, flatten.
.Bζ # Pad and transpose, leaving it transposed for the next addition.
} # End loop.
¹Fζ} # Transpose N times.
»R # Bring it all together into a newline string, reverse.
.∞.∊ # Mirror horizontally, then vertically with overlap.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
âeò↕\┐▄┤╚╬8φ8Δ☺Pä≤δ₧߃
```
[Run and debug it](https://staxlang.xyz/#p=836595125cbfdcb4c8ce38ed38ff015084f3eb9ee19f&i=1%0A2%0A3%0A4&a=1&m=2)
Unpacked, ungolfed, and commented, it looks like this.
```
'| string literal "|"
{ begin block to repeat
. |G push " |", then jump to trailing `}` below
'-z2lG push ["-",[]], then jump to trailing `}` below again
}N repeat block according to number specified in input
m output each row in grid
} goto target - `G` from above jumps to here
i@ modularly index into pair using iteration index
~ push to input stack
{;|Sm surround each row with the extracted element
M transpose grid
```
[Run this one](https://staxlang.xyz/#c=%27%7C++++++%09string+literal+%22%7C%22%0A%7B+++++++%09begin+block+to+repeat%0A++.+%7CG++%09push+%22+%7C%22,+then+jump+to+trailing+%60%7D%60+below+%0A++%27-z2lG%09push+[%22-%22,[]],+then+jump+to+trailing+%60%7D%60+below+again%0A%7DN++++++%09repeat+block+according+to+number+specified+in+input%0Am+++++++%09output+each+row+in+grid%0A++++++++%09%0A%7D+++++++%09goto+target+-+%60G%60+from+above+jumps+to+here%0A++i%40++++%09modularly+index+into+pair+using+iteration+index%0A++~+++++%09push+to+input+stack%0A++%7B%3B%7CSm+%09surround+each+row+with+the+extracted+element%0A++M+++++%09transpose+grid&i=1%0A2%0A3%0A4&a=1&m=2)
[Answer]
# Mathematica, ~~158~~ 164 bytes
```
f[n_]:=Print/@StringJoin/@Map[{{{"|","|", },{ , , }},{{"|", ,"-"},{ ,"-","-"}}}[[##]]&@@#&,Table[{1+i~Mod~2, 1+j~Mod~2, 2+Sign[Abs[i]-Abs[j]]}, {i,-n,n}, {j,-n,n}],{2}]
```
Mathematically calculates the correct symbol at the coordinates (i,j), where both run from -n to n. Human formatted:
```
f[n_]:=Print/@
StringJoin/@
Map[
{{{"|","|", },{ , , }},{{"|", ,"-"},{ ,"-","-"}}[[##]]&@@#&,
Table[{1+i~Mod~2,1+j~Mod~2,2+Sign[Abs[i]-Abs[j]]},{i,-n,n},{j,-n,n}],
{2}]
```
[Answer]
# PHP, 166 bytes
golfed more than 100 bytes off my first approach
and it´s still the longest answer here.
```
function i($n){for($m=['|'];$k++<$n;){array_unshift($m,$m[]=str_repeat(' -'[$f=$k&1],2*$k-1));foreach($m as$i=>&$r)$r=($c='||- '[2*$f+($i&&$i<2*$k)]).$r.$c;}return$m;}
```
**breakdown**
```
function h($n)
{
for($m=['|'];$k++<$n;)
{
array_unshift($m,$m[]=str_repeat(' -'[$f=$k&1],2*$k-1));
foreach($m as$i=>&$r)
$r=($c='||- '[2*$f+($i&&$i<2*$k)]).$r.$c;
}
return$m;
}
```
**ungolfed**
```
function ihih($n)
{
$m=['|']; // iteration 0
for($k=1;$k<=$n;$k++) // loop $k from 1 to $n
{
$f=$k&1; // flag for odd iterations
// add lines:
$r=str_repeat(' -'[$f],2*$k-1); // new line: ' ' for even, '-' for odd iterations
$m[]=$r; // append
array_unshift($m,$r); // prepend
// add columns:
foreach($m as$i=>&$r) // for each line
{
$c='| '[$f]; // '|' for even, ' ' for odd iterations
if($f && (!$i || $i==2*$k)) $c='-'; // '-' in corners for odd iterations
$r=$c.$r.$c; // prepend and append character
}
}
return $m;
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 150 bytes
```
sub h{my$i=pop;my$c=$i%2?$":'|';return(map{"$c$_$c"}h($i-1)),$i%2?'-'x($i*2+1):$c.$"x($i*2-1).$c if$i;()}say for reverse(@q=h<>),$q[0]=~s/---/ | /r,@q
```
[Try it online!](https://tio.run/##JYztCoIwGEZvZcgbm@X8Av9oljfQFUSEjYmDdHPTSNIuvTXq33MOh0dxfc@sNdMNta9uBlEqqQo3WAlikx7By/GCC83HSfekq9XLAwZXYN7aEhA08f3gF2KKn05s013i58BC8P7oihAYEg2IgvirqWfUSI00f3BtOKmGst0f3Mdwji/l20SU0ggtKNJBNVibfaQaheyNpacsjJP4Cw "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 110 bytes
```
f 0=["|"]
f n|odd n=g ' '!n$'-'|1>0=g '|'$id!n$' '
g c=map$(c:).(++[c])
(g!n)c|p<-g.f$n-1=(:p)<>pure$c<$head p
```
[Try it online!](https://tio.run/##FYuxasMwFEV3f8VNEEgiWNilQwmSlxTaoZk6hlCELDum9pOQlULA/@7Gwx3O4dybnX/9OK7DFEPKeLfZqnOgMLQQQjdSoiwRaHyAvPPzbNMDXUj4@Dzhz6d5CASNN/Wq6rVDZS77ZX8tOtAS2hZkenDwHTFe8qVuqo0XzoZ2U@BFD2cmG5lwR6nE4XBxV1mIfkfSLVGXveoYlbURxyh1E@/JM6fZzdsWcZ3sQDB43s8/iPf8ndMXQaF7Lm2J0Rq9z6dA2VOe15fqHw "Haskell – Try It Online")
### Explanation/Ungolfed
The helper function `g` takes a character and a list of strings, it then pre- and appends that character to each string:
```
g c = map (\s-> [c] ++ s ++ [c])
```
Next the operator `(!)` takes a function (`g`), a number (`n`) and a character (`c`). It then computes the output for `n-1`, applies the function `g` to it and adds a string of the same width consisting of `c`s to the beginning and end:
```
(g ! n) c | prev <- g $ f (n-1), ln <- [c | _ <- head p]
= [ln] ++ prev ++ [ln]
```
With these we'r ready to generate the outputs recursively, first we need to cover the base case:
```
f 0 = ["|"]
```
And then the recursion:
```
-- for odd n: the previous output needs a space at the end and beginning and then a string of '-' characters at the top and bottom
f n | odd n = (g ' ' ! n) '-'
-- for even n: the previous output needs a line of spaces at the top and bottom and then each line needs to be enclosed with '|' characters
| otherwise = g '|' $ (id ! n ) ' '
```
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
f=:{&' |-'@*@(-:@=+<-2&|@>.)"{~@:|@i:
```
[TIO](https://tio.run/##y/r/P83WqlpNXaFGV91By0FD18rBVttG10itxsFOT1Opus7BqsYh0wqoTMFUQUFBKV4hNTkjXx3IUwcA "J")
] |
[Question]
[
The [Kolmogorov complexity](http://en.wikipedia.org/wiki/Kolmogorov_complexity) of a string s is defined as the length of the *shortest program* P that outputs s. If the length of P is shorter than the length of s, then s is said to be *compressible*, otherwise s is *incompressible*. Most strings are incompressible ...
Write the shortest program that outputs this string (without spaces and without newlines):
```
d9 a6 b6 33 56 a7 95 4b 29 b0 ac 7f 2a aa 6d 19 b8 4b 4c f8 b6 2a ac 95
a1 4b 4e a5 9d b3 e7 c9 4c 49 59 ec 94 b3 aa 6c 93 8f 11 5a 4d 39 75 82
ec ea 24 cc d3 2d c3 93 38 4e b7 a6 0d d2 b5 37 23 54 ad 1b 79 aa 6e 49
55 52 94 5a a7 3a 6a e9 e4 52 cd 2d 79 ad c6 12 b5 99 5b b4 76 51 17 4e
94 f3 9a a2 e7 15 6a 55 14 4d 4e 4a a3 5c 2f ab 63 cc b5 a6 a4 92 96 8a
2e c3 d8 88 9b 8c a9 16 f5 33 22 5b a2 e2 cc 1b 27 d4 e8 db 17 a4 39 85
ca aa 5b 4f 36 24 d3 c6 f6 94 ad d7 0f 71 24 e1 b1 c5 ef 65 35 6c 8d d7
1a 87 1e 25 df 5d c0 13 b2 6f 5a 57 28 98 bd 41 66 04 ed a2 52 c9 ac 83
b3 6c 56 7e d1 c6 cc 53 4a 62 c5 59 a9 b2 d4 af 22 a5 a9 f4 b2 99 23 32
f8 fb ae 48 6a 8a 9a b5 46 7a 36 59 9f 92 d3 25 b5 19 bd 8a 4a 49 62 a5
e4 59 fb e5 ba a2 35 dd a9 36 1d a9 c9 69 89 77 6a b2 34 2d 1d 22 61 c5
c2 66 1c e2 76 74 52 a5 d9 84 b9 8a a6 b5 14 ec 29 58 b2 bc 96 16 16 48
f5 c5 bd 2f 32 1b 3d 4f 4b 2e b2 6b 9a d9 32 a4 4b 5c bc 92 b7 b3 26 39
fa 42 2d 64 ed 1a 79 49 4c a3 b7 85 b2 a6 e2 8c d9 55 90 e1 a8 87 4b 60
a6 e1 ba c4 bb ec 32 39 76 90 a6 b4 c6 65 79 61 91 aa 3d 54 b7 18 3d 15
4b 06 db 30 8a 4d 4a a1 35 75 5d 3b d9 98 ac 55 5b 10 dd b3 e2 cc f1 5e
b3 2b 53 90 b6 ee 2b ac 8f 88 8d 95 5a 75 df 59 2d 1c 5a 4c e8 f4 ea 48
b9 56 de a0 92 91 a9 15 4c 55 d5 e9 3a 76 8e 04 ba e7 b2 aa e9 ab 2a d6
23 33 45 3d c4 e9 52 e3 6a 47 50 ba af e4 e5 91 a3 14 63 95 26 b3 8b 4c
bc aa 5a 92 7a ab ad a6 db 53 2e 97 06 6d ba 3a 66 49 4d 95 d7 65 c2 aa
c3 1a 92 93 3f ca c2 6c 2b 37 55 13 c9 88 4a 5c 62 6b a6 ae cc de 72 94
```
The output should look like:
```
d9a6b63356a7954b29b0ac7f2aaa6d19b84b4cf8b62aac95a14b4e...7294
```
Note: no user input is allowed, nor web access, nor libraries (except the one required for printing the output).
**Edit I:** the sequence seems random ... but it turns out to be highly compressible handling a *little bit* of prime numbers ...
**Edit II:** Well done! I'll review the answers in the next hours, then assign the bounty.
This is my idea on how it could be solved:
1. If you try to compress the data you don't go far away ...
2. In internet you can find the (well-known?) [On-Line Encyclopedia of Integer Sequences](https://oeis.org/) (OEIS) ;
3. trying the first hexadecimal digits `d9, a6, b6, 33, ...` (or their decimal representation) give no result;
4. but if you convert the numbers to binary (`1,1,0,1,1,0,0,1,1,0,1,0,0,1,1,0`) and searching them on OEIS, [you get this result](https://oeis.org/search?q=1,1,0,1,1,0,0,1,1,0,1,0,0,1,1,0&language=english&go=Search).
5. As noted by Claudiu, I also gave a *little* hint in the question (Edit I above) ... :-)
**The winner is**: Peter Taylor (GolfScript, 50), with a special mention for Claudiu (Python, 92), the first who "solved" it.
[Answer]
# Python, 92 characters
Here it is ladies and gentlemen, the code itself!
```
>>> code = "R=range;print hex(int(''.join(`i/2%2`for i in R(38198)if all(i%x for x in R(2,i))),2))[2:-1]"
>>> len(code)
92
>>> exec code
d9a6b63356a7954b29b0ac7f2aaa6d19b84b4cf8b62aac95a14b4ea59db3e7c94c4959ec94b3aa6c938f115a4d397582ecea24ccd32dc393384eb7a60dd2b5372354ad1b79aa6e495552945aa73a6ae9e452cd2d79adc612b5995bb47651174e94f39aa2e7156a55144d4e4aa35c2fab63ccb5a6a492968a2ec3d8889b8ca916f533225ba2e2cc1b27d4e8db17a43985caaa5b4f3624d3c6f694add70f7124e1b1c5ef65356c8dd71a871e25df5dc013b26f5a572898bd416604eda252c9ac83b36c567ed1c6cc534a62c559a9b2d4af22a5a9f4b2992332f8fbae486a8a9ab5467a36599f92d325b519bd8a4a4962a5e459fbe5baa235dda9361da9c96989776ab2342d1d2261c5c2661ce2767452a5d984b98aa6b514ec2958b2bc96161648f5c5bd2f321b3d4f4b2eb26b9ad932a44b5cbc92b7b32639fa422d64ed1a79494ca3b785b2a6e28cd95590e1a8874b60a6e1bac4bbec32397690a6b4c665796191aa3d54b7183d154b06db308a4d4aa135755d3bd998ac555b10ddb3e2ccf15eb32b5390b6ee2bac8f888d955a75df592d1c5a4ce8f4ea48b956dea09291a9154c55d5e93a768e04bae7b2aae9ab2ad62333453dc4e952e36a4750baafe4e591a314639526b38b4cbcaa5a927aabada6db532e97066dba3a66494d95d765c2aac31a92933fcac26c2b375513c9884a5c626ba6aeccde7294
>>> import hashlib; hashlib.sha256(code).hexdigest()
'60fa293bbe895f752dfe208b7b9e56cae4b0c8e4cdf7c5cf82bf7bab60af3db6'
```
Marzio left a clever hint by saying that "it turns out to be highly compressible handling a *little bit* of prime numbers". I was sure the "little bit" wasn't italicized by accident, so I converted the hex string to bits and tried to find patterns. I thought that at first he was representing all the primes as bits and concatenating them together, but that didn't work out. Then maybe taking only a few digits, or dropping all the zeroes in the bit string - still no. Maybe it's a bitstring of the least-significant-bit of the first few primes? Not quite. But eventually I found the one that worked - it's a bitstring of the second-least-significant bit from the first however-many primes.
So, my code does just that: generate just enough primes, take the second bit of each (`i/2%2`), concatenate them as a binary string, then convert it to base-10 (`int(..., 2)`) and then to base-16 (`hex(...)`).
[Answer]
## GolfScript (50 bytes)
```
$ wc -c codegolf24909.min.gs
50 codegolf24909.min.gs
$ md5sum codegolf24909.min.gs
ce652060039fba071d17333a1199fd72 codegolf24909.min.gs
$ time golfscript.rb codegolf24909.min.gs
d9a6b63356a7954b29b0ac7f2aaa6d19b84b4cf8b62aac95a14b4ea59db3e7c94c4959ec94b3aa6c938f115a4d397582ecea24ccd32dc393384eb7a60dd2b5372354ad1b79aa6e495552945aa73a6ae9e452cd2d79adc612b5995bb47651174e94f39aa2e7156a55144d4e4aa35c2fab63ccb5a6a492968a2ec3d8889b8ca916f533225ba2e2cc1b27d4e8db17a43985caaa5b4f3624d3c6f694add70f7124e1b1c5ef65356c8dd71a871e25df5dc013b26f5a572898bd416604eda252c9ac83b36c567ed1c6cc534a62c559a9b2d4af22a5a9f4b2992332f8fbae486a8a9ab5467a36599f92d325b519bd8a4a4962a5e459fbe5baa235dda9361da9c96989776ab2342d1d2261c5c2661ce2767452a5d984b98aa6b514ec2958b2bc96161648f5c5bd2f321b3d4f4b2eb26b9ad932a44b5cbc92b7b32639fa422d64ed1a79494ca3b785b2a6e28cd95590e1a8874b60a6e1bac4bbec32397690a6b4c665796191aa3d54b7183d154b06db308a4d4aa135755d3bd998ac555b10ddb3e2ccf15eb32b5390b6ee2bac8f888d955a75df592d1c5a4ce8f4ea48b956dea09291a9154c55d5e93a768e04bae7b2aae9ab2ad62333453dc4e952e36a4750baafe4e591a314639526b38b4cbcaa5a927aabada6db532e97066dba3a66494d95d765c2aac31a92933fcac26c2b375513c9884a5c626ba6aeccde7294
real 365m11.938s
user 364m45.620s
sys 0m6.520s
```
Since everyone else is now revealing their code, I will also pre-empt OP's request to unobfuscate:
```
38200,{:x,{)x\%!},,2=},4/{3\{2&!!1$++}/.57>39*+}%+
```
### Overview dissection
* [Compute primes smaller than N](https://codegolf.stackexchange.com/a/5987/194) with N=38200: this gives the first 4032 primes: `38200,{:x,{)x\%!},,2=},`
* We want one bit per prime, with a hex conversion, so split them into groups of 4: `4/`
* For each group, map each prime `p` to `p&2 != 0`, and do a base-2 to base-16 conversion: `{3\{2&!!1$++}/.57>39*+}%` (this is where the interesting tricks are)
* We now have an array of ASCII values, plus the empty string from stdin; concatenate them to get a single string for output: `+`
### More detailed dissection of the base conversion
Given a stack holding an empty string and a list of primes, we need to do two conversions:
1. Convert each prime to a bit indicating whether it's equal to 2 or 3 (mod 4)
2. Convert the bits into hex digits
There are lots of equally long ways to do 1; e.g.
```
{4%1>}%
{4%2/}%
{2/1&}%
{2/2%}%
{2&!!}%
```
or even
```
{2&}% followed by a 2/ after the base conversion
```
For 2, the obvious approach is
```
2base 16base{'0123456789abcdef'=}%+
```
But base is a long word, and since 16 = 24 we can easily save a few chars with
```
4/{2base'0123456789abcdef'=}%+
```
Now the most obvious waste is the 18 chars devoted to that string. We just want a function from digit to ASCII code.
We want to map `0` to `'0' = 48`, ..., `9` to `'9' = 57`, `10` to `'a' = 97`, ... `15` to `'f' = 102`.
```
4/{2base.9>39*+48+}%+
```
But now throw into the mix a ban on `base`. We need to implement it ourselves. The obvious implementation (in this direction, the easy one) is that `k base` is a fold `{\k*+}*`. The slightly longer alternative is a straightforward iteration, which needs a base case: `0\{\k*+}/`. Base 2 is slightly special: `1$++` is equivalent to `\2*+` for the same length, and I've taken that approach.
Both of those are longer than the 5-char `2base`, but since we're now iterating over the values we can pull in part 1 to have a single loop. We replace
```
{2&!!}%4/{2base.9>39*+48+}%+
```
with
```
4/{{2&!!1$++}*.9>39*+48+}%+
```
for a nice 1-char saving, or
```
4/{0\{2&!!1$++}/.9>39*+48+}%+
```
for a 1-char loss.
But although that 1-char loss looks like a step backwards, consider what happens to that 0.
It's multiplied by 16 and added to the base-conversion output. And the final thing we do is to add a multiple of 16 to the output.
So we can combine the two as
```
4/{3\{2&!!1$++}/.57>39*+}%+
```
Joint shortest and the bonus cleverness makes it more interesting.
[Answer]
# Haskell, 105
SHA1 hash: `a24bb0f4f8538c911eee59dfc2d459194ccb969c`
Output:
```
d9a6b63356a7954b29b0ac7f2aaa6d19b84b4cf8b62aac95a14b4ea59db3e7c94c4959ec94b3aa6c938f115a4d397582ecea24ccd32dc393384eb7a60dd2b5372354ad1b79aa6e495552945aa73a6ae9e452cd2d79adc612b5995bb47651174e94f39aa2e7156a55144d4e4aa35c2fab63ccb5a6a492968a2ec3d8889b8ca916f533225ba2e2cc1b27d4e8db17a43985caaa5b4f3624d3c6f694add70f7124e1b1c5ef65356c8dd71a871e25df5dc013b26f5a572898bd416604eda252c9ac83b36c567ed1c6cc534a62c559a9b2d4af22a5a9f4b2992332f8fbae486a8a9ab5467a36599f92d325b519bd8a4a4962a5e459fbe5baa235dda9361da9c96989776ab2342d1d2261c5c2661ce2767452a5d984b98aa6b514ec2958b2bc96161648f5c5bd2f321b3d4f4b2eb26b9ad932a44b5cbc92b7b32639fa422d64ed1a79494ca3b785b2a6e28cd95590e1a8874b60a6e1bac4bbec32397690a6b4c665796191aa3d54b7183d154b06db308a4d4aa135755d3bd998ac555b10ddb3e2ccf15eb32b5390b6ee2bac8f888d955a75df592d1c5a4ce8f4ea48b956dea09291a9154c55d5e93a768e04bae7b2aae9ab2ad62333453dc4e952e36a4750baafe4e591a314639526b38b4cbcaa5a927aabada6db532e97066dba3a66494d95d765c2aac31a92933fcac26c2b375513c9884a5c626ba6aeccde7294
```
Edit: Code:
```
import Numeric;f(x:z)s=f[y|y<-z,0/=mod y x]$s*2+quot(mod x 4)2;f[]s=s;main=putStr$showHex(f[2..38198]0)""
```
I missed the rule about not using any library functions except for printing (putStr). I would assume that mathematical operators, while they're technically functions, are allowed.
[Answer]
# C, ~~136~~ ~~116~~ ~~109~~ 103 characters
OK then, here's my effort:
```
i;p;q;main(n){for(;n++,q<4032;){for(i=1;++i<n&&n%i;);if(i==n)p+=p+(n&2)/2,p=++q&3?p:printf("%x",p)*0;}}
MD5 hash = f638552ef987ca302d1b6ecbf0b50e66
```
[Answer]
## JS, 764
if we consider this string as base64, we can have a smaller version using the un-base-64-ed version:
```
btoa("wÖºo÷离÷ÛÖôiÎßÙ¦éÝ}oÎáÇüoiÏyk^áæ¹õÖ÷{·=áÎ=ç×÷÷i®÷×^ZáÝýï6yÇÛw}swßÎo¶ºÑ×voûÛ~xiÝ[ïÖéî=çv÷Zk½Ú駽{vqÝïÖsvo}å¶øï®u×¾÷÷õ¦¶{½yé®y×áîk~\Ùöëwoºkv÷¯Ùç7wÏ<õ¿kÝz÷Ûn[kg¶qÍ[Û·x{Ç[׶¸ßß9q¦å¾ß¸ww:¯xi×{ÑþõÛµoW9yþ¹ßñ×{Õ¯;Õí¹uþ]sMwonå®{ÛÏ|mÞ5ë8yÖ¶çg=iÏ7o~ç®ÞwW:qÎw᮶s}kÖöwÛf¹k×øoo}Û}öÇÛiî<é¯õ¦ùã®Úß®}õÿvw}¹o}mßá®=ëf¹{}}·¹m¦¶ß]kÝúÕÖ½sÞ½óÞûé¦ößÕݶëW9snºÕǶï®øçf¹wß8oßk¦ù×ÛÞ|ofÜ÷z×®<9mÝßm[ÝÞá½onõ§}ßf¸á¾\mÏvo¶÷Ûý}®6ÙÞ¸yÝZïÞ=áÆ·o¿9ofº{owÞy÷GµkÏ;á¾´k§µm§8m·ßmýï¯tk¦øs®¹ïÞµ÷VÝÞxo½|ÝÝyá½:u½ôñ®á¦µßùåÝÛwß|iÎyå½tuÖ÷{g^^o}çto§Ù¶ñÿ<ñßyå®ùuþ}ÙÝ\å®{Çøy®<oÞzuæ´÷oukÝyáÎyw½Ý®úñí8m§»of{ÖÙ§zÛ}÷ãÝs½çg·é®;çFÚi÷¸{uk}xëyÛ¦÷ñ¾mÆå¯ví¦iÖºu¾wÙï{Ó®mÚë®=áßyw¾¹sfs}Z÷owÝ÷snÙ½ûçwsß<á®\ënk¦qÇ^ïox")
```
But I think that the author wants us to find the logic behind this non-random string instead.
[Answer]
## Mathetmatica - 56
The mystery is already solved, so just implementing the idea
```
⌊.5Prime@Range@4032⌋~Mod~2~FromDigits~2~IntegerString~16
```
[Answer]
# J - 46 char
Don't mind me, just logging the J golf here for posterity. Wasn't clever enough to figure out the trick.
```
4[1!:2&4'0123456789abcdef'{~#.2|<.-:p:i.1007 4
```
Explained:
* `p:i.1007 4` - Create a 1007-row, 4-column matrix of the integers from 0, then take the prime numbers corresponding to those integers. Yes, `p:` is a J builtin. Yes, we're four primes short.
* `2|<.-:` - Halve each number (`-:`), floor it (`<.`), and take that modulo 2 (`2|`). This is the same as taking the next-to-lease significant bit.
* `#.` - Convert each row of the result from base 2 into an integer. This gives us 1007 numbers from 0 to 15 inclusive.
* `'0123456789abcdef'{~#.` - Take each row of this matrix of bits as the binary for a number, and use that number to select from the list of hex digits. This converts every four bits into the hex.
* `1!:2&4` - The J interpreter has a problem with outputting strings longer than 256 chars, so we have to send this data directly to stdout. You win some, you lose some.
* `4[` - Finally, discard the result from `1!:2` and instead output the missing 4 from the output. We do this because it's shorter than including those last four primes and returning an empty result here.
[Answer]
# JS, 503
Following @xem idea:
```
s='Ù¦¶3V§K)°¬*ªm¸KLø¶*¬¡KN¥³çÉLIY쳪lZM9uìê$ÌÓ-Ã8N·¦\nÒµ7#TyªnIURZ§:jéäRÍ-yƵ[´vQNó¢çjUMNJ£\/«c̵¦¤.ÃØ©õ3"[¢âÌ'+"'"+'ÔèÛ¤9ʪ[O6$ÓÆö×q$á±Åïe5l×%ß]À²oZW(½Afí¢Rɬ³lV~ÑÆÌSJbÅY©²Ô¯"¥©ô²#2øû®HjµFz6YÓ%µ½JIb¥äYûåº\n5Ý©6©Éiwj²4-"aÅÂfâvtR¥Ù¹¦µì)X²¼HõŽ/2=OK.²kÙ2¤K\¼·³&9úB-díyIL£·²¦âÙUá¨K`¦áºÄ»ì29v¦´Æeyaª=T·=KÛ0MJ¡5u];Ù¬U[ݳâÌñ^³+S¶î+¬ZußY-ZLèôêH¹VÞ ©LUÕé:vºç²ªé«*Ö#3E=ÄéRãjGPº¯äå£c&³L¼ªZz«¦ÛS.mº:fIM×eªÃ?ÊÂl+7UÉJ\bk¦®ÌÞr'
r=''
for(var i=0;i<s.length;i++) r+=s.charCodeAt(i).toString(16);
console.log(r)
```
[Answer]
# Mathematica, 55
```
Prime~Array~4031~BitAnd~2~FromDigits~2~IntegerString~16
```
Tested on Mathematica 8. This makes use of two observations:
* Mathematica's `FromDigits` doesn't actually check the range of the digits given, so if you apply it to a list of the form `{2,0,2,2,0,...}` you just get twice the result as if applying to `{1,0,1,1,0,...}`. But that's exactly the form generated by `BitAnd`ing the primes with 2.
* The last bit of the number whose hexadecimal representation we want happens to be zero (as evidenced by the string ending in an even digit), so it is just two times the number you'd get with one prime less. But a factor of two is exactly what we get from using the previous observation, so everything perfectly fits together.
] |
[Question]
[
The "Look and say" or "Say what you see" sequence is a series of numbers where each describes the last.
```
1
11 (one one)
21 (two ones)
1211 (one two, one one)
111221 (one one, one two, two ones)
312211 (three ones, two twos, one one)
```
and on and on...
<https://oeis.org/A005150>
Anyway, this is a regular code golf challenge (least byte count wins) to make a program that takes two arguments, an initial number and the amount of iterations. For example if you plugged in "1" and "2" the result would be "21". If you plugged in "2" and "4" the result would be "132112". Have fun!
[Answer]
## Pyth, ~~10~~ 8 bytes
*-2 bytes by @FryAmTheEggman*
```
ussrG8Qz
```
Explanation:
```
Implicit: z=first line as string, Q=second line
u the result of reducing lambda G:
s s rG8 flattened run-length-encoded G
Q Q times
z starting with z
```
Try it [here](http://pyth.herokuapp.com/?code=jkusrG8Q%5DE&input=4%0A2&debug=0).
[Answer]
## CJam, 8 bytes
```
q~{se`}*
```
Input format is the initial number first, iterations second, separated by some whitespace.
[Test it here.](http://cjam.aditsu.net/#code=q~%7Bse%60%7D*&input=2%204)
### Explanation
```
q~ e# Read and evaluate input, dumping both numbers on the stack.
{ e# Run this block once for each iteration...
s e# Convert to string... in the first iteration this just stringifies the input
e# number again. In subsequent iterations it flattens and then stringifies the
e# array we get from the run-length encoding.
e` e# Run-length encode.
}*
```
The array is also flattened before being printed so the result is just the required number.
[Answer]
# JavaScript, 57 bytes
```
F=(a,b)=>b?F(a.replace(/(.)\1*/g,c=>c.length+c[0]),b-1):a
```
Recursion works well for this problem. The first parameter is the initial number as a string, and the second is the number of iterations.
[Answer]
## R, 87 bytes
```
function(a,n){for(i in 1:n){r=rle(el(strsplit(a,"")));a=paste0(r$l,r$v,collapse="")};a}
```
**Ungolfed & explained**
```
f=function(a,n){
for(i in 1:n){ # For 1...n
r=rle(el(strsplit(a,""))) # Run length encoding
a=paste0(r$l,r$v,collapse="") # concatenate length vector and values vector and collapse
};
a # print final result
}
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 9 bytes
```
:"Y'wvX:!
```
Inputs are: number of iterations, initial number.
[**Try it online!**](http://matl.tryitonline.net/#code=OiJZJ3d2WDoh&input=NAoyCg)
```
: % implicit input: number of iterations. Create vector with that size
" % for loop
Y' % RLE. Pushes two arrays: elements and numbers of repetitions.
% First time implicitly asks for input: initial number
w % swap
v % concatenate vertically
X: % linearize to column array
! % transpose to row array
% implicitly end loop
% implicitly display
```
[Answer]
# Ruby, 63 bytes
A full program, since the question seems to ask for that. Takes input as command line arguments.
```
i,n=$*
n.to_i.times{i=i.gsub(/(.)\1*/){"#{$&.size}#$1"}}
puts i
```
No, `gsub!` can't be used, since the strings in `$*` are frozen :/
[Answer]
# [R](https://www.r-project.org/), ~~61~~ 57 bytes
-4 thanks to @JayCe, just when I was sure it couldn't be done any simpler!
```
f=function(a,n)`if`(n,f(t(sapply(rle(c(a)),c)),n-1),c(a))
```
[Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jUSdPMyEzLUEjTydNo0SjOLGgIKdSoygnVSNZI1FTUycZiPN0DYEMEPd/moahjqGB5n8A "R – Try It Online")
[Answer]
# Perl 6, 63 bytes
```
say (@*ARGS[0],*.trans(/(.)$0*/=>{$/.chars~$0})…*)[@*ARGS[1]]
```
This is as short as I could get it for now, there might be some tricky flags that could reduce it, I'm not sure
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~46~~ ~~45~~ 27 bytes
Martin did lots to help golf this.
```
+`(\d)(\1?)*(?=.*_)_?
$#2$1
```
[**Try it online**](http://retina.tryitonline.net/#code=K2AoXGQpKFwxPykqKD89LipfKV8_CiQjMiQx&input=MTIxMV9fXw)
Takes input in the format:
```
<start><count>
```
`<start>` is the initial number.
`<count>` is in unary, all underscores, and is how many iterations are performed.
### Single iteration, ~~20~~ 16 bytes:
```
(\d)(\1?)*
$#2$1
```
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
import Data.List
0%y=y
x%y=do x<-group$(x-1)%y;[length x,x!!0]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuITLQLXStpKrAkim5CtU2OimF@WXFqhoVOgaaqpWWkfnpOall2QoVOhUKCoaxP7PTczMsy0oyswrUTFTjTaM/Q8A "Haskell – Try It Online")
[Answer]
# JavaScript ES6, 71 bytes
```
(m,n)=>[...Array(n)].map(_=>m=m.replace(/(.)\1*/g,x=>x.length+x[0]))&&m
```
Takes input as a string and a number.
[Answer]
# Perl 5, 50 bytes
```
$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say
```
The arguments are in reverse order (number of iterations then seed). Example:
```
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 4 2
132112
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 0 2
2
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 2 0
1110
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 1 10
1110
> perl -E'$_=pop;for$i(1..pop){s/(.)\1*/length($&).$1/ge}say' 11 1
3113112221232112111312211312113211
```
[Answer]
# Python 3.6, ~~100~~ ~~98~~ 93 bytes
```
import re
f=lambda s,n:n and eval("f'"+re.sub(r'((.)\2*)',r'{len("\1")}\2',f(s,n-1))+"'")or s
```
[Try it online!](https://tio.run/##DctBCsMgEADAe1@x2MPuNjagIZdCf@LFEKUBo2G1hVL6dtu5z/Fuj5Kn3rf9KNJAwinek9@X1UPV@ZbB5xXCyydSEdUgYazPhQSJRnb2wqgFPylkUs4o/jqLOtJ/Xg3zoFBxEaj9kC03ioQGNczMcMbJWGsM9h8 "Python 3 – Try It Online")
Note this creates a lambda that takes a string and an integer, and returns a string. Example: `f('1', 5) == '312211'`
Finds all repeated characters (`((.)\2*)` regex), makes a f-string out of their length and the character itself (`r'{len("\1")}\2'`), then evaluates it. Uses recursion on the counter (`n and ...f(s,n-1)... or s`) to avoid having to define a proper function and a loop.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ŒrUFµ¡
```
[Try it online!](https://tio.run/nexus/jelly#@390UlGo26Gthxb@///f6L8JAA "Jelly – TIO Nexus")
```
Implicit input: first argument.
µ¡ Do this to it <second argument> times:
Œr Run-length encode into [value, times] pairs
U Flip them
F Flatten list
```
[Answer]
## Perl, 38 + 2 bytes
```
for$i(1..<>){s/(.)\1*/(length$&).$1/ge}
```
Requires the `-p` flag:
```
$ perl -pe'for$i(1..<>){s/(.)\1*/(length$&).$1/ge}' <<< $'1\n5'
312211
```
Input is a multi line string:
```
input number
numbers of iterations
```
If all the steps are required as well then we can change it to the following, which is 44 + 2 bytes:
```
$ perl -nE'for$i(1..<>){s/(.)\1*/(length$&).$1/ge,print}' <<< $'1\n5'
11
21
1211
111221
312211
```
[Answer]
# Mathematica, ~~81~~ 73 bytes
```
FromDigits@Nest[Flatten[(Tally/@Split@#)~Reverse~3]&,IntegerDigits@#,#2]&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes (Non-competing)
*Corrected due to Emigna's comments, see below/edits.*
```
F.¡vygyÙJ
```
[Try it online!](https://tio.run/nexus/05ab1e#@@@md2hhWWV65eGZXv//G3MZGhqZGBubmJqampkYAwA "05AB1E – TIO Nexus")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Çα▲ì4↔┌j█♀
```
[Run and debug online!](https://staxlang.xyz/#c=DE%7CR%7Brm%3Af%24e&i=1+2%0A2+4&a=1&m=2)
Spent too many bytes on proper IO format ...
## Explanation
Uses the unpacked version to explain.
```
DE|R{rm:f$e
D Do `2nd parameter` times
E Convert number to digits
Starting from the `1st parmeter`
|R Convert to [element, count] pairs for each run
{rm Revert each pair
:f Flatten the array
$ Convert array to string of digits
e Convert string of digits to integer
```
The essential part is `D|R{rm:f`(8 bytes).
If the first input can be taken as an array of digits, the whole program can be written in 9 bytes: [Run and debug online!](https://staxlang.xyz/#p=8d5bc0b76848a0fdc6&i=%5B1%5D+2%0A%5B2%5D+4&a=1&m=2)
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 30 bytes
```
{y{,/{(#x;*x)}'(&~=':x)_x}/,x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqrqyWke/WkO5wlqrQrNWXUOtzlbdqkIzvqJWX6ei9n@IVbVKdGVdkVWagp5ChXVCfra1RkJaYmaOdYV1pXWRZmwtV0i0oYKptbGCoYIREBoqGMYChYwUTKwNFYwhAgpGsf8B "K (ngn/k) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 26 bytes
```
2&([:;](#<@,{.);.1~1,~:/\)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jdQ0oq2sYzWUbRx0qvU0rfUM6wx16qz0YzT/a3JxpSZn5CsYAqGuFZBIUzCEiBhBRIwQIoZgMbCoMbKoIVgGqt4EIWMMFwfLmIJluPyc9BRyE7NTFYpLi1IVMksUyvOLsosV0orycxUS8yoViksSi0oUCvIz80qwGgN2IsLO/wA "J – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
FÅγøí˜
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f7XDruc2Hdxxee3rO//8mXEYA "05AB1E – Try It Online")
```
FÅγøí˜ # full program
F # for N in [0, 1, ...,
# ..., implicit input...
F # ... minus 1]...
˜ # flatten...
ø # zipped...
Åγ # list of chars used in runs of the same char in...
# implicit input...
Åγ # or top of stack if not first iteration...
ø # with...
Åγ # list of lengths of runs of the same char in...
# implicit input...
Åγ # or top of stack if not first iteration...
í # with each element of the list reversed
# (implicit) exit loop
# implicit output
```
`øí` can also be `sø` with no change in functionality. [Try it online!](https://tio.run/##yy9OTMpM/f/f7XDruc3Fh3ecnvP/vwmXEQA "05AB1E – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
!¡(dṁ§eL←gd
```
[Try it online!](https://tio.run/##yygtzv7/X/HQQo2UhzsbDy1P9XnUNiE95f///4b/zQA "Husk – Try It Online")
```
! # get the arg2-th element of
¡ # the infinite list by repeatedly applying
# (starting with arg1):
(d # get the digits of
ṁ # applying to each of
gd # the groups of identical neighbouring digits:
§eL← # combine length + first element
```
[Answer]
# [Go](https://go.dev), 175 bytes
```
import."fmt"
func g(n int,s string)string{for N:=0;N<n;N++{c,o,f,k:=1,"",rune(s[0]),s[1:]+"_"
for _,r:=range k{if r==f{c++}else{o+=Sprintf("%d%c",c,f);f,c=r,1}}
s=o}
return s}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY89asQwFIR7neIhWJDQS7BJE-xVsRcwgZTLshjFMsJryUhyJXSSNCaQLpDz5DbR_lTz4DHfzHx-jW77WXo19eMAc2_s9xr10-vfr5kX5-Mz1XOkRK9WwcgsGBsxQIje2JHfJWnnoWtk1XZ723ZCJIUONU6NrJFS9KsdWDhWJ47hWDcnQc8FWDxn9I30vS3BUzIavJQ6KSHycAlDckK-L4UfNaO7j52iqFDzVqOSHuucSZAuEz_E1VsI-VH7cGt63cE4pFuMgUZC3RbdS3ipyiFEeb1d2RfLDJZhBmlNOSeZPEDbdtd_)
A non-recursive port of [Ogaday's answer](https://codegolf.stackexchange.com/a/71043/77309).
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 41 bytes
Takes curried arguments with number of iterations first.
```
:**&(~(:gsub+:+%[:+@|S,~:[]&0])&/(.)\1*/)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWNzWttLTUNOo0rNKLS5O0rbRVo620HWqCdeqsomPVDGI11fQ19DRjDLX0NSEa1hWUlhQruEWbxEYrGSnFQgQXLIDQAA)
## Non-regex solution, 47 bytes
```
:**&(A|:slice_when+:!=|:*&-[:+@,~:[]&0]|~:*&"")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN_WttLTUNBxrrIpzMpNT48szUvO0rRRta6y01HSjrbQddOqsomPVDGJr6oAiSkqaEG3rCkpLihXcok1io5WMlGIhggsWQGgA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 31 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.875 bytes
```
(øeRf
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiKMO4ZVJmIiwiIiwiNFxuMiJd)
Bitstring:
```
0011010110011001011100101001100
```
inputs are reversed
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÆV=ìÈòÎcÈâ iXÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=xlY97MjyzmPI4iBpWMo&input=NAoy)
[Answer]
# YASEPL, 132 bytes
```
=p'=n'(+`2£s©1`1=q)""=x=l®"p"`3=t$x!h¥t,"p"`4!x+}1,l,5!y¥x,"p"}3,h,4`5!f$x-tſ""!q+f+h!x}2,l,3!n-!p$q<!o$p(!s©o!pſ""!n}!s<!i+}2,n,2
```
prompts you twice. enter starting number and amount of iterations
[Answer]
# Python 3, 138 bytes
I used a recursive approach.
```
def g(a,b):
if b<1:return a
else:
c,n=1,'';f,*a=str(a)+'_'
for i in a:
if i==f:c+=1
else:n+=str(c)+f;f,c=i,1
return g(n,b-1)
```
The function accepts two ints, `a` and `b` as described.
I'm amazed at how terse the entries here are! Maybe someone will come along with a better Python method too.
[Answer]
# [Pylons](https://github.com/morganthrapp/Pylons-lang), 11
```
i:At,{n,A}j
```
How it works:
```
i # Get input from command line.
:A # Initialize A
t # Set A to the top of the stack.
, # Pop the top of the stack.
{ # Start a for loop.
n # Run length encode the stack.
, # Seperate command and iteration
A # Repeat A times.
} # End for loop.
j # Join the stack with '' and print it and then exit.
```
[Answer]
# SmileBASIC, ~~100~~ 98 bytes
```
DEF S N,T?N
WHILE""<N
C=C+1C$=SHIFT(N)IF C$!=(N+@L)[0]THEN O$=O$+STR$(C)+C$C=0
WEND
S O$,T-T/T
END
```
Prints out all the steps.
`T/T` is there to end the program when T is 0.
] |
[Question]
[
An ant walks along the edges (not faces) of a wireframe cube. Each vertex it encounters presents it with a fork from which two new edges branch off. The ant chooses which way to turn -- `left` or `right`. These direction are relative to the ant, who is facing the vertex and is outside the cube. Your goal is to determine, from the sequence of `left`/`right` choices the ant took, whether it ends at the same position that it started.
For example, if the ant turns left four times (`left left left left`), it will have traversed a square counterclockwise and ended at the same place it started. But, if it goes `left left left left right`, it will end on a different spot on the cube. Also, if it goes `left right right right left`, it ends on its starting edge but facing the opposite vertex, which does not count as the same position.
The ant's path might repeat edges, including the edge it started at, but what matters is where it ends after the whole sequence.
Write a *named function* that takes in the ant's sequence of turns and outputs whether the ant is back at its start position after the sequence. Assigning an unnamed function to a variable is enough to make it a named function.
(Edit: If your language can't make a named function, it can instead implement the function with inputs and outputs through STDIN/printing or the stack. If that's not possible, make it a snippet in which the input and output are saved in variables.)
**Input**
A sequence of `left`/`right` decisions of length `0` to `31` inclusive, represented in a format of your choice. This might be a string of letters `R`/`L`, a list of numbers `1`/`-1`, or an array of Booleans. Nothing cheesy like having them be method names or strings useful for your code.
Please post the test cases in your format if it's different from the test cases below.
**Output**
`True`/`False`, `0`/`1`, or the analogues in your language.
**Winning criteria**
Fewest bytes wins. Remember, you need to give a named function. You can have code outside the function, but those bytes count too. Your function should behave correctly if called multiple times.
**Test cases**
`True` cases (one per line, second one is empty list):
```
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 -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
```
`False` cases (one per line):
```
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 -1
```
Here's the same test cases with `L`'s and `R`'s.
`True` cases:
```
RRRR
LLLL
RLRLRL
RRLLRRLL
LRRLLRRL
RRRLLLLR
RLLRLL
RRRRLLLLRLLRLL
LLLRLLRRLRLRRRRRRRRRRRRRRRRR
```
`False` cases:
```
R
RR
RRR
LR
RLLLR
RLLRR
LRLR
RRRRL
LLRLRLLR
RLRRRRLLLRRLLL
```
**Extra credit challenge**
Same thing, but with a [dodecahedron](http://en.wikipedia.org/wiki/Dodecahedron) rather than a cube. See [Hunt the Wumpus](https://codegolf.stackexchange.com/q/26128/194) for ideas.
[Answer]
# GolfScript, 24 chars (19 for function body only)
Math FTW!
```
{3,.@{[+~@\{@}*~]}/=}:f;
```
[Test this solution online.](http://golfscript.apphb.com/?c=IyBmdW5jdGlvbiBkZWZpbml0aW9uOgp7MywuQHtbK35AXHtAfSp%2BXX0vPX06ZjsKCiMgdGVzdCBjYXNlcyAodHJ1ZSkKIjEgMSAxIDEKCjAgMCAwIDAKMSAwIDEgMCAxIDAKMSAxIDAgMCAxIDEgMCAwCjAgMSAxIDAgMCAxIDEgMAoxIDEgMSAwIDAgMCAwIDEKMSAwIDAgMSAwIDAKMSAxIDEgMSAwIDAgMCAwIDEgMCAwIDEgMCAwCjAgMCAwIDEgMCAwIDEgMSAwIDEgMCAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEiCm4ve1t%2BXWZ9JXAKCiN0ZXN0IGNhc2VzIChmYWxzZSkKIjEKMSAxCjEgMSAxCjAgMQoxIDAgMCAwIDEKMSAwIDAgMSAxCjAgMSAwIDEKMSAxIDEgMSAwCjAgMCAxIDAgMSAwIDAgMQoxIDAgMSAxIDEgMSAwIDAgMCAxIDEgMCAwIDAKMCAxIDEgMSIKbi97W35dZn0lcA%3D%3D)
This function takes as input a binary array (0 for left, 1 for right) and returns 1 for true and 0 for false.
Conceptually, it works by rotating the *cube* so that the ant always maintains the same position and orientation, and checking whether the cube finally ends up in the same orientation as it began in.
In particular, we can represent the left and right turns as two linear maps in three dimensions, where a left turn corresponds to a 90° rotation around the *x* axis, i.e. the map (*x*, *y*, *z*) → (*x*, *z*, −*y*), and a right turn corresponds to a 90° rotation around the *y* axis, i.e. the map (*x*, *y*, *z*) → (*z*, *y*, −*x*).
At the beginning of the function, we simply set up a three-element vector containing the distinct positive values (1, 2, 3), apply the sequence of rotation maps to it, and check whether the resulting vector equals the initial one.
(In fact, to save a few chars, I actually transform the coordinates so that the initial vector is (0, 1, 2) and the maps are (*x*, *y*, *z*) → (*x*, *z*, −1−*y*) and (*x*, *y*, *z*) → (*z*, *y*, −1−*x*), but the end result is the same.)
Ps. Thanks to [proud haskeller](https://codegolf.stackexchange.com/users/20370/proud-haskeller) for spotting the bug in the original version of this solution.
---
# Perl, 58 chars
As requested in the comments, here's the same solution ported to Perl. (This version actually uses the untransformed coordinates, since the transformation saves no chars in Perl.)
```
sub f{@a=@b=1..3;@a[$_,2]=($a[2],-$a[$_])for@_;"@a"eq"@b"}
```
[Test this solution online.](http://codepad.org/RuWBoviC)
---
# Bonus: Ant on a Dodecahedron (GolfScript, 26 chars)
```
{5,.@{{2*2%[~\]}*(+}/=}:f;
```
[Test this solution online.](http://golfscript.apphb.com/?c=IyBmdW5jdGlvbiBkZWZpbml0aW9uOgp7NSwuQHt7MioyJVt%2BXF19KigrfS89fTpmOwoKIyB0ZXN0IGNhc2VzICh0cnVlKQoiCjEgMSAxIDEgMQowIDAgMCAwIDAKMSAwIDAgMCAwIDEgMSAwIDAgMCAwIDEKMSAwIDEgMCAxIDAgMSAwIDEgMAoxIDAgMCAwIDEgMCAwIDAKMSAwIDAgMCAxIDEgMSAwIDEgMCAxIDAgMCAwIDEgMSAxIDAgMSAwIgpuL3tbfl1mfSVwCgojdGVzdCBjYXNlcyAoZmFsc2UpCiIxCjEgMQoxIDEgMQoxIDEgMSAxCjAgMSAxIDEgMQoxIDAgMCAwIDAgMQoxIDAgMCAwIDEgMCAxIDEgMSAwIgpuL3tbfl1mfSVwCg%3D%3D)
Like the ant-on-a-cube function above, this function takes as input a binary array (0 for left, 1 for right) and returns 1 if the ant ends up at the same position and orientation as it started in, or 0 otherwise.
This solution uses a slightly more abstract representation than the cube solution above. Specifically, it makes use of the fact that the [rotational symmetry group of the dodecahedron](//en.wikipedia.org/wiki/Icosahedral_symmetry) is isomorphic to the [alternating group](//en.wikipedia.org/wiki/Alternating_group) A5, i.e. the group of even permutations of five elements. Thus, each possible rotation of the dodecahedron (that maps edges to edges and vertices to vertices) can be uniquely represented as a [permutation](//en.wikipedia.org/wiki/Permutation) of a five-element array, with consecutive rotations corresponding to applying the corresponding permutations in sequence.
Thus, all we need to do is find two permutations *L* and *R* that can represent the left and right rotations. Specifically, these permutations need to be 5-cycles (so that applying them five times returns to the original state), they must not be powers of each other (i.e. *R* ≠ *L**n* for any *n*), and they need to satisfy the relation (*LR*)5 = (1), where (1) denotes the identity permutation. (In effect, this criterion states that the path `LRLRLRLRLR` must return to the original position.)
Fixing the *L* permutation to be a simple barrel shift to the left, i.e. mapping (*a*, *b*, *c*, *d*, *e*) → (*b*, *c*, *d*, *e*, *a*), since it can be implemented in GolfScript in just two chars (`(+`), we find that there are five possible choices for the *R* permutation. Out of those, I chose the mapping (*a*, *b*, *c*, *d*, *e*) → (*c*, *e*, *d*, *b*, *a*), since it also has a relatively compact GolfScript implementation. (In fact, I implement it by first interleaving the elements with `2*2%` to obtain (*a*, *c*, *e*, *b*, *d*), then swapping the last two elements with `[~\]`, and finally applying the *L* permutation unconditionally to move *a* to the end.)
The online demo link above includes some test cases of valid paths on a Dodecahedron that return to the origin, such as:
```
# empty path
1 1 1 1 1 # clockwise loop
0 0 0 0 0 # counterclockwise loop
1 0 0 0 0 1 1 0 0 0 0 1 # figure of 8
1 0 1 0 1 0 1 0 1 0 # grand circle
1 0 0 0 1 0 0 0 # loop around two faces
1 0 0 0 1 1 1 0 1 0 1 0 0 0 1 1 1 0 1 0 # Hamilton cycle
```
[Answer]
# Python, 68
Takes a list of 1 and -1. Based on 3D rotations: checks if the point (3,2,1) ends up at the same position after applying a series of rotations. There are two possible rotations, corresponding to 1 and -1. Each one is done by permuting two coordinates and changing the sign of one of them. The exact coordinates to change and which sign to permute is not important.
```
def f(l):
p=[3,2,1]
for d in l:p[d],p[0]=-p[0],p[d]
return[3,2]<p
```
EDIT: this is actually mostly the same solution as "Perl, 58".
[Answer]
# Mathematica
Inspired by Ilmari Karonen's solution. The rotational symmetry group of a cube is isomorphic to S4.
## Cube, 51 bytes
```
Fold[Part,r=Range@4,{{2,3,4,1},{3,4,2,1}}[[#]]]==r&
```
Takes a list of `1`s and `-1`s as input.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6xgq/DfLT8nJTogsahEp8g2KDEvPdXBRKe62kjHWMdEx7BWpxpEGwFZtdHRyrGxsba2RWr/A4oy80qik6OrDXUU4EgXDWNj1sbG/gcA "Wolfram Language (Mathematica) – Try It Online")
## Dodecahedron, 55 bytes
```
Fold[Part,r=Range@5,{{2,3,4,5,1},{3,5,4,2,1}}[[#]]]==r&
```
Takes a list of `1`s and `-1`s as input.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Jgq/DfLT8nJTogsahEp8g2KDEvPdXBVKe62kjHWMdEx1THsFan2hhIm@gYAdm10dHKsbGxtrZFav8DijLzSqJToqsNdRR0kTAc6WJQuJXUxsb@BwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~118~~ ~~116~~ ~~107~~ 105 bytes
-2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
f(char*s){char*p,n[]="@ABCDEFG",y;for(;*s;s++)for(p=n;*p;*p++^=*s^82?y%2+1:4-(y&2))y=*p/2^*p;y=n[2]==66;}
```
[Try it online!](https://tio.run/##XVBda4MwFH2uvyIEHElUxmSUsRD23b3kKfStVhCLVthSMXYQir/dxbTW2JOPe7n33HtPkkdlnvd9gfJ91hCFT9bWodxsGXx9e//4/Fp9w1DT4tAgShRVQYAHv2aSktrsIEgZUelT/KL9OHh4foyQvosx1ozU93FqOJrJTbxlbLmkXf93qHagtOOAmeedvEXdVLItEPR3wFeJhCEokMIhUJh6neeZJPjNKonO5GOrEFw3x3avExkZQENblAgKg9EfLTe45vmwJjbnw7kyLwGn21AspmrusMWYnkUvATvoFpYzyk/kKvtRt/qn5s6YSZ@jZC7L4XAxUzgJE1aZ8xXnB9hriHb9Pw "C (gcc) – Try It Online")
Suppose we gave the cube the following coordinates:
```
(1,1,1) (1,1,0)
G +--------------+ C
/| /|
/ | / |
/ | (0,1,0)/ |
(0,1,1) +--------------+ D |
H | | | |
| | | |
| F +----------|---+ (1,0,0)
| /(1,0,1) | / B x
| / | / y /
|/ |/ |/
E +--------------+ A z ---*
(0,0,1) (0,0,0)
```
If we start on corner D, then moving to C or H can be thought of as rotating the cube around us instead. Moving right would mean rotating counter-clockwise around the Z axis, and moving left would mean rotating clockwise around the X axis. These are the only two rotations we need to care about. Since each rotation is exactly 90 degrees, we can imagine the corners "sliding" along the edges. For moving right, this means A -> B, B -> C, C -> D, D -> A with the other side doing E -> F etc. For moving left, we instead get A -> E, E -> H etc.
Since each corner only slides along an edge, that means only one of the dimensions of each point changes for each rotation. When B moves to C, only its y component changes, and when H moves to D, only its z component changes, and so on. Furthermore, since the coordinates are restricted to 0 and 1, we can think of each point as a binary number, with the appropriate bit flipped upon movement.
We can see that for a movement to the right, A and C flip their x's, while D and B flip their y's. If we change perspective to look on that side of the cube head on, and ignore the z component (which does not change for this rotation anyway) we get:
```
D (0,1) C (1,1)
+-------------+
| |
| |
| |
| |
| |
| |
+-------------+
A (0,0) B (1,0)
```
A pattern emerges: For the points that flip their x, x == y, while the opposite is true for the points flipping their y's. This holds for the other type of rotation, but with z instead of x.
In other words:
```
Right
if (x == y) x = !x
if (x != y) y = !y
Left
if (z == y) z = !z
if (z != y) y = !y
```
Now we can easily go through all the rotations, and at the end see if the final D matches our initial D.
Storing each point as a single number is a given, but in C, assigning a char array is that much more compact than an int array. We take care to choose characters whose lower three bits match 000..111, making it possible to just ignore the rest of the bits. Flipping the coordinates is simply a matter of XOR'ing with the appropriate bitmask.
[Answer]
## Python - 110, 150
Takes in a list of integers with `-1` for turn left, `1` for turn right.
**Cube, 110:**
```
def f(l):
c,p='07'
for d in l:a="100134462634671073525275"[int(c)::8];c,p=a[(a.index(p)+d)%3],c
return'1'>c
```
**Test:**
```
l=map(int,'1 1 1 1'.split())
print f(l)
```
**Dodecahedron, 150:**
```
def f(l):
c,p='0J'
for d in l:a="I5H76E8BBA8F76543100JI0J21D3A5C7E9CJI2132H4GF94C6D98AHGBEDGF"[int(c,36)::20];c,p=a[(a.index(p)+d)%3],c
return'1'>c
```
[Answer]
# [Marbelous](https://github.com/marbelous-lang/marbelous.py) 188
Shameless theft of [Ilmari Karonen](https://codegolf.stackexchange.com/users/3191/ilmari-karonen)'s algorithm for the purpose of showing off a new language.
This script expects a string of 0x00 for left and 0x01 for right on stdin, followed by a 0x0A (newline). It outputs "0" for a failed case and "1" for a success.
```
......@5@3FF
@0@1@2\\]]@5
010203@4=A@4
&0&0&0&0/\
MVMVMVMV..
@0@1@2@3..!!
:MV
}2}2}1}0}1}0}3
&0&1&0&1~~~~<A@P
{0{1{1{0&1&0=0&1
}0}1}2@P{2{2&030
=1=2=3&2FF}3..//
&2&2&231&2{3
\/\/\/&2!!..//
```
example run:
```
# echo -e "\x0\x0\x0\x1\x0\x0\x1\x1\x0\x1\x0\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1" | marbelous.py ant-on-a-cube.mbl
1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
f=lambda l:reduce(lambda n,x:n%4*64+n/4*16**x%63,l,27)<28
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIceqKDWlNDlVA8rP06mwylM10TIz0c7TN9EyNNPSqlA1M9bJ0TEy17QxsvhfnpGZk6pgaFVQlJlXopCmkZlXUFqioan5P9pQRwGKYrmigchARwGKgBxDMAtBQoQMYUoQbIhGLHJwHXAJqDTcdANkQxCuQVOOqRSrHJqDSUMg@6FuQDgF6jNk52JxviE8AAxQdMMDwQAtJNFMwepvFG4sAA "Python 2 – Try It Online")
This uses the permutation representation
```
0: abcd -> dabc
1: abcd -> dcab
```
where left and right (0 and 1) correspond to length-4 cycles on 4 elements. We iterate over the input applying the indicated permutation, and check if the outcome equals the initial value.
We start `a,b,c,d` as the four-element list `0,1,2,3`. We compact them into a single base-4 number `n=abcd`, with initial value `n=27` corresponding to `0123` in base 4. We instantiate each the permutation arithmetically on `n`.
Since both results start with `d`, we can do `n%4` to extract `d`, then `n%4*64` to move it into the right position `d___`. The other digits are `abc`, extracted as `n/4`. We need to insert them into the lower three place values.
For direction `x=0`, we insert `abc` as is, and for `x=1`, we rotate them as `cab`. The rotation can be achieved as `*16%63`, which takes `abc` to `abc00` to `cab`. (The `%63` would go wrong on `a==b==c==3`, but these value aren't possible.) Since just doing `%63` is a no-op, the direction-dependent expression `*16**x%63` gives `abc` or `cab` as required.
---
# [Python 2](https://docs.python.org/2/), 55 bytes
```
f=lambda l:reduce(lambda n,x:n^(n*8%63|7*8**x),l,10)<11
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIceqKDWlNDlVA8rP06mwyovTyNOyUDUzrjHXstDSqtDUydExNNC0MTT8X56RmZOqYGhVUJSZV6KQppGZV1BaoqGp@T/aUEcBimK5ooHIQEcBioAcQzALQUKEDGFKEGyIRixycB1wCag03HQDZEMQrkFTjqkUqxyag0lDIPuhbkA4BeozZOdicb4hPAAMUHTDA8EALSTRTMHqbxRuLAA "Python 2 – Try It Online")
[Answer]
# Haskell, 104 103 ~~99~~ ~~97~~ 96 / ~~67~~ 64 chars
I feel the equivalent of right/left would be a datatype Direction like so:
```
Direction = R | L
```
so I assumed in my answer that they were available.
**edit:** actually realized that booleans would lead to shorter code.
True represents a left turn, and False represents a right turn (although, technically, the code would work the same if it was flipped; it's symmetric)
96 characters:
```
m[p,l,r]b|b=[p%l,7-r-l,r]|0<1=[p%r,l,7-r-l]
p%x|odd$div p x=p-x|0<1=p+x
g l=foldl m[0..2]l<[0,2]
```
g is a function that given a list of Direction would return weather of not the ant got back to its place.
**explanation of representation of position:**
the position of the ant is coded as a three tuple of integers.
the first integer represents the vertex that the ant is heading to.
the first bit represents if the vertex is at the up/down half, the second is the left/right half, and the third is the back/front half. this is done so that moving from a vertex to a neighbor vertex can be done by flipping one bit.
the second integer is the amount that the ant's vertex would change if it would go left. for example, if the ant was at vertex 3, and the second integer was 4, than after turning left the vertex would be 7. note this would always be a power of 2, because exactly one bit is flipped by moving one vertex.
the third integer is the same, but for going right; i know this is can be calculated by the first two, but i don't know how to. if you got an idea, please tell me.
something to note is that when turning left, the third integer would stay the same, and the second would become the one between 1 2 and 4 that wasn't either the second integer or the third, which happens to be the same as 7 - second integer - third integer.
i chose this way of representing position because (as was just stated in the previous paragraph) it was trivial to compute the next position.
**explanation of functions:**
the (%) function is the function that takes the current vertex and the amount to change it, and changes it. it gets to the bit that is going to change and flips it (in a very numeric way).
the m function is a function that takes the position of the ant, and the direction, and returns the new position by using the note we noted earlier.
then the m function is combined using foldl (which is sort of like `reduce` in javascript, but a bit more expressive) to create the function g, the answer to this question.
---
# Haskell, 64 characters
inspired by @alphaalpha's answer, here is it's version ported to haskell:
```
m[a,b,c,d]p|p=[b,c,d,a]|0<1=[b,d,a,c]
g l=foldl m[0..3]l<[0,1,3]
```
---
**edit:** I now feel incredibly stupid because of lmari Karonen's answer. maybe i'll port his answer to haskell.
**another edit:** not feeling as stupid as his answer is was wrong
**edit:** switched from actually using tuples to using lists as their `Ord` instance and the `[ ... ]` syntactic sugar makes it shorter
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
f=(<28).foldl(\n x->mod n 4*64+mod(div n 4*16^x)63)27
```
[Try it online!](https://tio.run/##XY1JDsIwDEX3PoV3JCAqKFVhAZzAK68RUkRbUZGmQMtw@@IMK@wket/Dz9UMt9raaWoOap/vdNb0trLq5PC7PHZ9hQ6LeVksBFXVvoNcl@evLjc6304PnPEMD7gGIfK0AuhM64RaN9ZPcxlRvZxtXT1ghp25oxqu/Ue4SfqhBcKAnlgCgCSAyScwE/kLlEgq7AcYvKagYyHKRGH9P0DSH4a4nky8JI5GQOHf0EnO4YEf "Haskell – Try It Online")
Same logic as my [Python answer](https://codegolf.stackexchange.com/a/157848/20260), even thought `mod` and `div` are longer to write.
---
**[Haskell](https://www.haskell.org/), 58 bytes**
```
r=[1..3]
f=(==r).foldl(\[x,y,z]->(!!)[[x,-z,y],[-z,y,x]])r
```
[Try it online!](https://tio.run/##XY3PDsIgDMbvfQo8CQlbNJ7xCXrqFTkQ3eIiots0br78LIyTLX9@X2k/rn68NSEsy2Dsvq4PDlojjRlU3T7CJciTnfSsv646ys1GWVbVV89O23TpyTk1LL3Y0lYYsQcmTLQDuPsuMnXx1Qz@/BLyHUMXm1HU4u6fQo7Xx4e5LbpXDLlBLcQBgBxAmBKIENMGLMQVSg0ESWPWa2GVhfL4fwBnWgTreDFJEmk1Asz/5pfinA/4AQ "Haskell – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 bytes ([Adám's SBCS](https://github.com/abrudz/SBCS))
```
f←{x∊(-@3∘⌽⌽)/⍵,x←⊂⍳3}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqikcdXRq6DsaPOmY86tkLRJr6j3q36lQA5R51NT3q3Wxc@///o76pQL66U2pOfrlCSUZmsUJOZl6qjkJqWWpRJZCfl65QnJFfmpOikJSqkKhgqKfOBdVyaD31oTpXmoIhBHKlPepdA@QaQCBYwgCGocoMwDxDqLwBqhjcKKgJICPh8gZI8kgqUGRRxRC2E4Cw8IEHFLFha0CHsIV4GuZ1SKDBgwU1iKCycFFDeLAaICICSQ9qYMJZAA "APL (Dyalog Unicode) – Try It Online")
[H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) suggested that reversing the steps doesn't make a difference, and that resulted in -2 bytes.
Well, this is embarrassing, since it was intended to be way shorter than GolfScript. [At least I tried to.](https://chat.stackexchange.com/transcript/message/43331784#43331784)
The function is named `f`, and, in the test cases, `1` represents a left turn (boolean true) and `0` represents a right turn (boolean false). `⍬` represents the empty list.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 21 bytes
```
f←{x≡(↓∪⊢∘⌽)/⍵,x←⊂⍳4}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqikedCzUetU1@1LHqUdeiRx0zHvXs1dR/1LtVpwIo/air6VHvZpPa//8f9U0F8tWdUnPyyxVKMjKLFXIy81J1FFLLUosqgfy8dIXijPzSnBSFpFSFRAVDPXUuqJZD66kP1bnSFIwgkCvtUe8aINcQAsEShjAMVWYI5hlB5Q1RxeBGQU0AGQmXN0SSR1KBIosqhrCdAISFDzygiA1bAzqELcTTMK9DAg0eLKhBBJWFixrBg9UQERFIelADE84CAA "APL (Dyalog) – Try It Online") (Using the testing environment from Erik the Outgolfer's [answer](https://codegolf.stackexchange.com/a/157831/71256))
I take left and right as `1` and `2`. This uses the following permutations of `abcd`:
```
1 : bcda
2 : cdba
```
I apply the permutations corresponding to `1` and `2` to `⍳4 : 1 2 3 4`, and check if it is unchanged
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 71 65 bytes
```
f()(a=1234;for i;{ a=`tr 1-4 4$[$i?123:312]<<<$a`;};((a==1234));)
```
[Try it online!](https://tio.run/##hVDLDoMgELzzFZuGAxyagHoqGnvpF@itaSK2Gk1MTHycjN9OrVSBeigbyLI7s8yQy75SqiSUyIh7fiDKtoNaTCCjbOiAnwMI8B3X8dK8@Nx7hGGIZSZmQRbGSqFUUJXekpRQmBAsqwR8FVA8qxZwLNCM0JqfkqodmxfkBTAgQzcW9ITQhwlch77ok@nY@mzbhsDWAjco5pbt0d9p2xMbirkoC/cLcMtGz584WudAStn0lvddgSVlN2TrPcg3MLvHbfvM/JzLdx3vmXoD "Bash – Try It Online")
Like many previous answers, uses a representation of the group of rotations of the cube generated by 1234->4123 and 1234->4312. Uses numbers instead of letters so that I can use a ternary operator with an arithmetic expansion. Expects its input as 0's and 1's separated by spaces, and outputs via exit code.
6 bytes saved thanks to @manatwork's comment!
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 119 bytes, 137 bytes
Uses the fact that the rotation group of the cube is isomorphic to \$S\_4\$. Brainfuck has no functions at all, named or otherwise, so this is a full program that takes input through STDIN and outputs to STDOUT. (If you insist on a variable, pretend the value of the cell the program ends on is a variable.)
### Cube, 119 bytes
```
++++>+++>++>+>,[+++[->+++<]<<<<[->>>>+<<<<]>[>]<+[[-]<[->+<]<<<[->>>+<<<]>[>]],]<[[<]>[->]<[>>]<]<[>>-<]-[----->+<]>--.
```
[Try it online!](https://tio.run/##NYtRCoAwDEMP1NUTjJ5gX/sN/VBBEMEPwfPXdMNA2keTbs963se7XxFC2bSJFRCheaheKTIliW4wrwKo53kWRi5/6oURkpVVGMdYWl2hqXwz1SWi99bSHw "brainfuck – Try It Online")
```
++++>+++>++>+ Initialize tape as 4 3 2 1
>,[ For each input byte:
+++[->+++<] Add 3 and multiply by 3; if input is R, this will be 255
<<<<[->>>>+<<<<] Move first number to end (BCDA)
>[>]<+[ If input wasn't R:
[-] Zero input cell (which is now negative 18)
<[->+<] Move previously moved number one slot further (BCD_A)
<<<[->>>+<<<] Move first number into vacated slot (CDBA)
>[>]]
,]
<[[<]>[->]<[>>]<] Determine whether tape is still 4 3 2 1
<[>>-<] If not: subtract 1 from output cell
-[----->+<]>--. Create "1" in output cell and output
```
### Dodecahedron, 137 bytes
```
+++++>++++>+++>++>+>,[+++[->+++<]<<<<<[>>>>>+[<]>-]>[>]<+[[-]<<[[->>+<<]<<]>[>>>>>>+[<]<-]>>[>]],]<[[<]>[->]<[>>]<]<[>>-<]-[----->+<]>--.
```
[Try it online!](https://tio.run/##PYxBCoBQCEQP9L@dQDzBX7kVFxUEEbQIOr/NBDWKyvh0ueb93O71qGqUfcWY1gNjCA1NpcKoFpomaWGpLUKwQ4WvxOj/mAIjlz3BcCc4ApD6NtGUEArXeCpTlY8x3H0wvukB "brainfuck – Try It Online")
The only differences between the two programs are the setup and permutations. The left permutation used here is `DCAEB`, which seemed to be the golfiest conjugate available.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr)
Based on [my answer](https://codegolf.stackexchange.com/a/251549/9288) to [Detect round trips on a dodecahedron](https://codegolf.stackexchange.com/q/251538/9288).
## Cube, 35 bytes
```
f(s)=t=x;[t=1/Mod(t+c,3)|c<-s];t==x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN5XTNIo1bUtsK6yjS2wN9X3zUzRKtJN1jDVrkm10i2OtS2xtKyBKbzFJJBYU5FRqFCvo2ikUFGXmlQCZSiCOkgLIFE0dhehoQx0FKIoFcnWBDAQGiUA5yBRUGEkpMg9mDHYVCL0oNkEVIVmoi24mwqFYNOLQg1sNhrdIQ2AHwVyF5Dq459F8gsN3yIGli2YUUoCheQGHmbgCCF0kNlYTkkBgaQoA)
Takes a list of `1`s and `-1`s.
The rotational symmetry group of a cube is isomorphic to \$PSL(2,3)\$ (the [projective special linear group](https://en.wikipedia.org/wiki/Projective_linear_group)). Here `L` and `R` correspond to the rational functions \$\frac{1}{x+1}\$ and \$\frac{1}{x-1}\$ respectively.
---
## Dodecahedron, 37 bytes
```
f(s)=t=x;[t=Mod(t^c+1,5)^c|c<-s];t==x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN1XTNIo1bUtsK6yjS2x981M0SuKStQ11TDXjkmuSbXSLY61LbG0roIrXJBYU5FRqFCvo2ikUFGXmlQCZSiCOkgLIGE0dhehoQx0FBIoFigBpXQgXBwVSpIsqjs4EKYEog5qIYYsusghQWawmxM0wjwIA)
Takes a list of `1`s and `-1`s.
The rotational symmetry group of a dodecahedron is isomorphic to \$PSL(2,5)\$. Here `L` and `R` correspond to the rational functions \$x+1\$ and \$\frac{x}{x+1}\$ respectively.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
3RðW;ṙN1¦ṚƊ/⁼⁸
```
[Try it online!](https://tio.run/##y0rNyan8/9846PCGcOuHO2f6GR5a9nDnrGNd@o8a9zxq3PH///9oQx0FAx0FQyRkAEMo3FgA "Jelly – Try It Online")
`1` = left turn, `0` = right turn. Based on my Dyalog solution.
Unfortunately, Jelly doesn't have named functions. If I can't use an implicit input and need to assume it's in a variable, this same-length version will do:
```
3RµW;®ṙN1¦ṚƊ/⁼
```
It assumes the input is in the register (©/®).
[Answer]
# [Python 3](https://docs.python.org/3/), 111 bytes
```
def f(s):
u,f,r,l,b,d='WGROBY'
for c in s:
if'R'==c:u,f,d,b=b,u,f,d
else:u,l,d,r=l,d,r,u
return'WG'==u+f
```
[Try it online!](https://tio.run/##HUy7CgMhEOz9iu1Usl26A5s0aQIBm5DW0yWCeMeqxX292TsGhmFe@9F/W73PGRMBmWYXBQMJGQsGjE5/nv79@GoFtDGskCs0qUAm7bVz63KWIwYX8FISpdKS2EVsdhfjUMCpD65yJ6txo7lzrt2Q0f51Qls7/w "Python 3 – Try It Online")
There are a few ways I can think to shave off a few bytes, but I'll just leave it like this, since this approach isn't anywhere near competitive anyway. Happy to hear about other tweaks, though!
* -5: Take a boolean array as input, so `if'R'==c:` can be just `if c:`
+ -1: Or just change `if'R'==c:` to `if'L'<c:`
* -1: Change the lettering scheme from `WGROBY` to `ABCDEF` so `'WG'==u+f` can be `'AC'>u+f`
[Answer]
# Perl - 120, 214
Takes an array (list) of booleans.
Cube (120):
```
sub e{$a=$b=0;for$c(@_){$_=(13,62,53,40,57,26,17,'04')[$b];$d=s/$a/($b-1)%8/e;($a,$b)=($b,substr($_,$c^$d,1))}return!$b}
```
Dodecahedron (214):
```
sub e{$a=$b='00';for$c(@_){$_=('01041102090307040500061807160308091502101114121019131714151016081706131819051200'=~/\d{4}/g)[$b];$d=s/$a/sprintf'%02d',($b-1)%20/e;($a,$b)=($b,substr($_,($c^$d)*2,2));}return!($b+0)}
```
] |
[Question]
[
A [quine](/questions/tagged/quine "show questions tagged 'quine'") is a program that produces output that's identical to the program's source code. On this website, we generally only care about [proper quines](https://codegolf.meta.stackexchange.com/q/4877/62131) (at the time of writing, the current definition is "some part of the output is encoded by a different part of the program").
What advice do you have for writing proper quines, or programs with quine-like properties? As usual, each tip should be in a different answer.
[Answer]
## Take advantage of string formatting
One of the easiest ways to create a quine is to define a string, then put the string inside itself with string formatting.
```
s='s=%r;print s%%s';print s%s
```
So in this example Python quine, we declare a string with the first part equal to whatever is before the string `s=`, then we allow for the string to be inserted with formatting with `%r`, and finally we put what comes after the string to print and format it. The trailing newline is because `print` prints a trailing newline.
So the template is really this, in Python:
```
<A>'<A>%r<B>'<B>
```
To expand the existing quine with more code:
```
<more A>s='<more A>s=%r;print s%%s<more B>';print s%s<more B>
```
[Answer]
# Use `eval` to reduce the need to copy code
The majority of quines require two copies of the code; one to be executed, one as data. This can end up doubling the length of the source code, making it harder to maintain, and worsening the score if you're writing the quine for a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition.
Merging the two copies means that one piece of information needs to be used for two purposes. Trying to treat your code as data is often not possible, and is typically considered cheating when it is. Treating data as code, however, can be done in many languages via use of a builtin, typically called `eval`. As such, your quine basically consists of storing the main body of your quine in a variable (so that you can refer to it more than once), then evaluating that variable.
Here's an example of how this works (the example is written in Python, but something similar works in many other languages):
```
d='print("d="+repr(d)+"\\neval(d)")'
eval(d)
```
[Answer]
# Stringified functions
In several languages, function objects (or equivalent constructs) implicitly store their source code, and will return it when converted into a string. This allows compact quines without [using string eval](https://codegolf.stackexchange.com/a/115548). A notable example of such a language is JavaScript:
```
function f(){console.log(f+"f()")}f()
```
This code defines and calls a function `f` that, when called, prints its own source code followed by a call to itself. The only part of the program that needs to be duplicated is the function call `f()`. Of course, the function body can include an arbitrary "payload" of code that will also be executed when the function is called.
---
A more compact version of the same trick works in the golfing languages [GolfScript](https://tio.run/nexus/golfscript#@1@tpFenVKtX9/8/AA):
```
{".~"}.~
```
and [CJam](https://tio.run/nexus/cjam#@1@tFF@nVBtf9/8/AA):
```
{"_~"}_~
```
Each of these quines first defines an anonymous code block (enclosed in braces), which behaves much like a function object in JavaScript: it can be executed, and if stringified, it returns its source code. The rest of the code (`.~` in GolfScript, or `_~` in CJam) then executes the block, while leaving a copy of it on the stack. The code inside the block then pushes a string onto the stack that repeats the code outside the block. When the interpreter exits, it automatically stringifies and prints everything left on the stack. As with the JavaScript example, these code blocks could also be made to carry and execute an arbitrary payload of additional code without having to duplicate it.
[Answer]
# Use string delimiters that nest without escaping
Often, one of the hardest parts about writing a quine is the escaping step. This is needed in almost every quine; the issue is that you're storing data somehow, and you need to replicate the code that stores the data in the quine's output. That code will contain an escaped form of the data, so the program will see an unescaped form, and you'll need to re-escape it.
The easiest way to handle the unescaping step is if the escaped and unescaped forms of the data differ only in the presence or absence of string delimiters. Escaping is thus a simple matter of adding a new pair of string delimiters around the string. Unfortunately, this can clearly only work if the string delimiters themselves can be expressed in the data without escaping.
Perl is a good example of a language where this trick works. Although its usual string delimiters are `"…"` or `'…'`, the less commonly used `q(…)` nests, allowing this sort of quine to be written:
```
$_=q($_=q(0);s/\d/$_/;print);s/\d/$_/;print
```
This is a code+data quine. `s///` is a regex string-replace operation; we use `0` as the marker, and match it within the regex as `\d` ("any digit"), to avoid using the marker more than once (although as another optimization, we could actually just have used `0` again, because Perl's `s///` only replaces the first occurrence by default). Note that there's no explicit escaping step needed here, as the `q(…)` delimiters can just be included literally in the data string.
[Answer]
# Code + data quines
The most general structure for a quine looks something like this pseudocode:
```
data = "*an escaped version of the entire program,
with this string replaced with a marker*"
program = data.replace(
*an expression that evaluates to the marker but doesn't mention it*,
escaped(data))
print program;
```
This structure can be used to write a (fairly naive) quine in most languages. However, it tends to score fairly badly on most scoring systems, because you have to write the entirety of the program twice. However, most quine structures can be considered optimizations of this one.
There are some subtleties to this. In some languages, the hardest part of
performing this operation is to write the escaping code; in many languages, producing the marker without mentioning its name is difficult; and in some esoteric languages, you'll have to invent your own sort of string literal. All three operations tend not to cause too much trouble, though.
For example, we can write a Python quine escaping a string using `repr`, and using the 2-character-sequence `x"` string (which is representable as `"x\""`, i.e. not using the sequence `x"` in the string representation of the string itself) as the marker:
```
d='d=x"\nprint(str.replace(d,"x\\"",repr(d)))'
print(str.replace(d,"x\"",repr(d)))
```
[Answer]
## Remember the Structure of a Quine
I like to think of quines as *three* parts, rather than 2:
* Part 1: Generate a data representation of parts 2 and 3.
* Part 2: Use the data to algorithmically print back part 1.
* Part 3: Decode the representation to print parts 2 and 3.
This can make it easier to think about quines. Here is a Python quine, with each line corresponding to a part:
```
s = "print(\"s = \" + repr(s))\nprint(s)"
print("s = " + repr(s))
print(s)
```
Sometimes, you use an `eval` or similar to remove duplication, but generally I have found that this helps in writing simple quines.
Let's take a look at two different Underload quines. This is the first:
```
(:aSS):aSS
```
The first part is `(:aSS)`, which generates the data representation. The second is `:aS`, which prints `(:aSS)`. The third part is `S`, which prints `:aSS`.
Here is the second quine:
```
(:aS(:^)S):^
```
At first, this doesn't seem to fit. But if you expand the quine, you get:
```
(:aS(:^)S):aS(:^)S
```
Now `(:aS(:^)S)` is part 1, `:aS` is part 2, and `(:^)S` is part 3.
[Answer]
# Exploit wrapping source code
In quite a few languages (mostly 2D languages), the source code can wrap around; under certain circumstances (e.g. in Befunge-98, if your program is a one-liner) going past the end of the program will take you back to the start of the program. This kind of nonlinear behaviour means that you can write code that's inside and outside a string literal at the same time; an unmatched `"` (or whatever the string delimiter is) will effectively give you a string containing the whole of the rest of the program (except for the `"` itself).
One problem with using this trick is that you'll get the string as seen from the point of view of the `"`, rather than from the start of the program (like you'd want). As such, it's likely easiest to rearrange the program so that the `"` appears at the start or end. This often means chopping your program up into multiple pieces and making use of whatever interesting/unusual flow control commands your language has (most languages which let string literals wrap around the program have a good selection of these).
A good example is [@Justin's Befunge-98 quine](https://codegolf.stackexchange.com/a/15841/62131):
```
<@,+1!',k9"
```
The unmatched `"` at the end of the program wraps the whole program in a string literal, so (running right to left due to the `<` at the start) all we have to do is output the program (`9k`), then output the double quote (`'!1+,`) and exit (`@`). This saves needing two copies of the program (one as code, one as data); the two copies are the same piece of code, just interpreted in different ways.
] |
[Question]
[
This idea came to me when I saw my little brother playing with my calculator :D
# The task
Taking a integer as an input, print that many graphical square roots under each other, like this:
```
n = 1
___
\/ 1
n = 3
_______
/ _____
/ / ___
\/\/\/ 3
n = 5
___________
/ _________
/ / _______
/ / / _____
/ / / / ___
\/\/\/\/\/ 5
n = 10
______________________
/ ____________________
/ / __________________
/ / / ________________
/ / / / ______________
/ / / / / ____________
/ / / / / / __________
/ / / / / / / ________
/ / / / / / / / ______
/ / / / / / / / / ____
\/\/\/\/\/\/\/\/\/\/ 10
```
Each root consists of 4 parts, which I'm going to very scientifically name:
(s is the root size on the stack of roots, n is the input number, x is the number of digits)
1. The "tail", which is a single `\`
2. The "wall", which consists of `/` \* s
3. The "roof", which consists of `_` \* 2 \* s + x
4. And the number n under the smallest root, placed in the centre (leaving one empty space under the last `_` in the smallest root)
# Input
You must take input of the number `n`, no hardcoding the `n`
# Output
The ascii roots your program made
This is a code-golf challenge, so lowest byte count for each language wins!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~104~~ ~~94~~ ~~89~~ ~~81~~ 79 bytes
```
s=n=input()
while s:print' '*s,'/ '*(n-s)+'_'*(2*s+len(`n`));s-=1
print'\/'*n,n
```
[Try it online!](https://tio.run/##JY1BCsIwEEX3c4rsJpO21ES6qeQmgoU60ECZBieinj5GXP23eLyfP2U7JNT1uLOJBhGrRolJ8rNYgteWdjY650eSggad9ji2sTIodXhrFJx2O4tdZCG66BA9/O3riE56qa0J/ObV/j7cRNVDgDNM4E9f "Python 2 – Try It Online")
Edit 1: Forgot I switched to python 2 lol
Edit 2: Thanks @ElPedro for the idea of switching to while loop!
Edit 3: Thanks @SurculoseSputum for saving 8 bytes!
Edit 4: Thanks @xnor for saving 2 bytes!
[Answer]
# JavaScript (ES6), ~~104 102~~ 99 bytes
A recursive function starting with the last line and using regular expressions to update each line above.
```
f=(n,s='\\/'.repeat(n)+(e=' ')+n)=>~n?f(n-1,e+s.replace(/\\/g,e).replace(/.(?!.*\/)/g,'_'))+`
`+s:e
```
[Try it online!](https://tio.run/##RY3BDoIwEETvfMV66q4LRa9i5UdIpMGFaMiWUOLF6K/XevI0k5c3mYd/@jis92WrNNwkpdGhltGZrquNXWURv6ESozgDhljJXT7ajqjVsRSOP2X2g2CdB1Mp9AcW253ddzVlbq6GiPui53iSNIYVFRwcG1A45zzkwkzwKgCGoDHMYucwYb4haop3@gI "JavaScript (Node.js) – Try It Online")
## How?
### Initialization
We generate the bottom line with:
```
s = '\\/'.repeat(n) + (e = ' ') + n
```
For instance, this gives `"\/\/\/\/ 4"` for \$n=4\$.
### Recursion
We get rid of the backslashes with:
```
s.replace(/\\/g, e)
```
We create the 'roof' or increase its size with:
```
.replace(/.(?!.*\/)/g, '_')
```
which means: replace with an underscore each character that doesn't have any slash on its right.
This leads to:
```
_________
/ _______
/ / _____
/ / / ___
\/\/\/\/ 4
```
And with a leading space inserted at each iteration:
```
_________
/ _______
/ / _____
/ / / ___
\/\/\/\/ 4
```
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 188 bytes
```
f(0,N)->string:copies("\\/",N)++" "++integer_to_list(N);f(X,N)->string:copies(" ",X+1)++string:copies("/ ",N-X)++string:copies("_",2*X+floor(math:log10(N)+1))++"
"++f(X-1,N).
f(N)->f(N,N).
```
[Try it online!](https://tio.run/##fY3LCoMwEEX3foVkNWkSHy3dWPATXAdqESmJDcREYqCfn46rQi3OYmDu4c5RwY5uEmp9BrPElCUNFe@oaNcYjJuap1@MWoH0fUkwZ4zkhDHjoppUGKIfrFkjdPSmQf7r5YRLVmPvJy8RdELuwUD4@SSZtt4HmMf4aqyf6goV@GbzZ@hHmahRV2QaNinu7UrzaBzcHzQXbZbjGN/odzBRgQZsc7ydBcp38HIEr0ewrr60SB8 "Erlang (escript) – Try It Online")
# Explanation
```
f(N)->f(N,N). % Assign the counter to the input.
f(X,N)-> % While the counter isn't 0:
string:copies(" ",X+1)
% Repeat the space counter + 1 times
++string:copies("/ ",N-X)
% Repeat "/ " input - counter times
++string:copies("_",
% Repeat the "_" that many times:
2*X % The counter doubled
+floor(math:log10(N)+1)
% Plus the length of the digit(s) of the input
++"
" % Join the above, and append a newline
++f(X-1,N). % Decrement the counter by 1
f(0,N)-> % If the counter turns into 0:
string:copies("\\/",N)
% Repeat "\/" input times
++" " % Append a space
++integer_to_list(N);
% Append the number converted into a string
```
```
[Answer]
# Mathematica (Notebook) 30 bytes
Only in Spirit ;-)
```
Nest[Defer@√#&,#,#]&@Input[]
```
produces the nested radicals
[![enter image description here](https://i.stack.imgur.com/sb6iZ.png)](https://i.stack.imgur.com/sb6iZ.png)
in the spirit but not the letter of the problem.
# Explanation
```
Input[] //take input
Nest[f,expr,n] //apply f to expr n times i.e. f[f[f[f[f....[expr]]..]] with n fs
Nest[f,#,#]& //define a lambda that applies f to arg #, # times
Nest[f,#,#]&@Input[] //apply the lambda Nest[f,#,#]& to the value of Input[]
√#& //define a lambda that puts arg # inside √
Defer@√#& //define a lambda that puts arg # inside √ buts keeps the mathematical square root unevaluated
Nest[Defer@√#&,#,#]&@Input[]
//apply the lambda Defer@√#& to Input, Input no of times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes
-4 bytes thanks to Kevin Cruijssen.
```
Lε-„/ ×'_y·¹g+׫y>ú}R„\/¹×¹‚ª»
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f59xW3UcN8/QVDk9Xj688tP3QznTtw9MPra60O7yrNggoE6N/aCdQYOejhlmHVh3a/f@/oQEA "05AB1E – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 34 bytes
```
VQj*N"/ ",*hJ-QNd*+l`QyJ\_;jd,*"\/
```
[Try it online!](https://tio.run/##K6gsyfj/PywwS8tPSV9BSUcrw0s30C9FSzsnIbDSKybeOitFR0spRv//f0MDAA "Pyth – Try It Online")
```
VQ
```
Loop the variable `N` over `0` to `Q` (the input) minus 1
```
j*N"/ "
```
Join the following using `N` instances of `"/ "`:
```
,
```
The two element list of...
```
*hJ-QNd
```
... {`Q` - `N` + `1`} space characters (`d` is the space character in Pyth). Store the value of `Q` minus `N` in the variable `J` so we can use it later.
```
*+l`QyJ\_
```
... {`J` times 2, plus the number of digits of `Q`} instances of the string `"_"`
```
;
```
End of loop
```
jd,*"\/
```
Join the following using a space:
* `Q` instances of the string `"\/"`
* `Q` casted to a string
Conveniently, the string literal is implicitly closed, and the two `Q`s are implicitly appended to the end of the program.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~88~~ 84 bytes
```
param($n)1..$n|%{' '*($m=$n- --$_)+' /'*$_+' '+'_'*(2*$m+"$n".length)}
'\/'*$n+" $n"
```
[Try it online!](https://tio.run/##FYpBCoAgEADvvUJkY1PRsHs/CcSD1EG3qKBD9fbNTgMzs61X2o8l5cy8xT2WDkh554Ce9kaBuoMyAllhLQRlUPSoIVSiwVDroKEYCSRdTjSfi3obnP6HjBRVM7P3Hw "PowerShell – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
NηG↙η←⁺²Lθ↖η_Mη↘Pθ←←Fη«P↗⊕ι←/\
```
[Try it online!](https://tio.run/##XY7LCsIwEEXX7VeErhJI8bGsWzeFKkVwV5Ba0yaQTmpMKiJ@e0xaEXE3mdxz5ja81o2qpXM5DNbsbX9mGnOyiUslH50CnG3VHQrWGoo4Rdk8ldLe8JqigkFnOL4S4r@OwzeWnBKv2KmR4QAFxUF03ISllUYMWoDx2CczWf8frdLIN0HPOPph/JXJRFEOjWY9A8MuWBAPROWcmFski6oKJV7OrZYuHeUb "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nη
```
Input `n` as a number.
```
G↙η←⁺²Lθ↖η_
```
Print the "roof", ensuring that it is long enough to overhang `n`.
```
Mη↘Pθ←←
```
Print `n` as a string in the appropriate place.
```
Fη«
```
Loop `n` times.
```
P↗⊕ι
```
Print the next diagonal line of the "wall".
```
←/\
```
Print the next part of the "tail".
[Answer]
# [MATL](https://github.com/lmendo/MATL), 43 bytes
```
:P"@QZ"47Oh1X@qX"95GVn@E+Y"hh]'\/'1GX"0GVhh
```
[Try it online!](https://tio.run/##y00syfn/3ypAySEwSsnE3D/DMMKhMELJ0tQ9LM/BVTtSKSMjVj1GX93QPULJwD0sI@P/f0MDAA "MATL – Try It Online")
First time I have used `X"`, `Y"`, `Z"` in the same answer!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DLṭ1j+1,-,2×Ɱ$“ “/ “_”ẋ"ⱮṚṄ€ȧ⁾\/ẋ,⁸K
```
A full program which prints the result.
**[Try it online!](https://tio.run/##y0rNyan8/9/F5@HOtYZZ2oY6ujpGh6c/2rhO5VHDHAUg1gcR8Y8a5j7c1a0EFH@4c9bDnS2PmtacWP6ocV@MPlBY51HjDu////8bGgAA "Jelly – Try It Online")**
### How?
```
DLṭ1j+1,-,2×Ɱ$“ “/ “_”ẋ"ⱮṚṄ€ȧ⁾\/ẋ,⁸K - Main Link: integer, n
D - digits (n)
L - length
ṭ1 - tack to one
j - join with (n)
$ - last two links as a monad - f(n):
1,-,2 - [1,-1,2]
Ɱ - map across [1..n] with:
× - multiplication
+ - add (left to each of right, vectorised)
“ “/ “_” - [' ', '/ ', '_']
Ɱ - map across (the list of list of numbers) with:
" - zipped:
ẋ - repetition
Ṛ - reverse
Ṅ€ - print each with trailing newlines
ȧ - logical AND (with n) -> n
⁾\/ - ['\', '/']
ẋ - repeat (n times)
,⁸ - pair with n
K - join with a space
- implicit print
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 32 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
{kî-⌠ *_£(∞k£+'_*û/ ï*\n}û\/k* k
```
[Try it online.](https://tio.run/##AUEAvv9tYXRoZ29sZv//e2vDri3ijKAgKl/CoyjiiJ5rwqMrJ18qw7svIMOvKlxufcO7XC9rKiBr//8xCjMKNQoxMAoxMg)
**Explanation:**
```
{ # Loop the (implicit) input amount of times:
k # Push the input-integer
î- # Subtract the 1-based loop-index
⌠ # + 2
* # And repeat that many spaces
_ # Duplicate this string
£ # Pop and push its length
( # + 1
∞ # * 2
k # Push the input-integer again
£ # Pop and push its length
+ # Add those two integers together
'_* '# And repeat that many "_"
û/ # Push the 2-char string "/ "
ï* # And repeat it the 0-based loop-index amount of times
\ # Then swap the top two strings on the stack
n # And push a newline character
}û\/k* # After the loop: repeat 2-char string "\/" the input amount of times
# Push a space
k # And push the input-integer
# (after which the stack is joined together and output implicitly)
```
[Answer]
# Wolfram Mathematica 120 bytes
```
a=StringRepeat;b=Print;Input[];
b[a[" ",#+1],a["/ ",%-#],a["_",2#+IntegerLength[%]]]&/@Range[%,1,-1];b[a["\/",%]," ",%];
```
[![enter image description here](https://i.stack.imgur.com/OnpRn.png)](https://i.stack.imgur.com/OnpRn.png)
# Explanation
```
StringRepeat[str,n]
//creates a string with str repeated n times
a=StringRepeat
//alias for StringRepeat
Print[expr1,expr2,...]
//prints expr1, expr2,... on a newline without separation
b=Print
//alias for Print
Input[]
//gets user input,
;
//Hide implicit output
%
//last output
IntegerLength[n]
//no of digits in n in base 10
a[" ",#+1]
//Make a lamba StringRepeat with arg #, that prints " ",#+1 times
b[a[" ",#+1],a["/ ",%-#],a["_",2#+IntegerLength[%]]]&
//Make a lambda with arg # that
//prints the appropriate " /_________"
//depending on #
b[....]&/@Range[%,1,-1];
//map the lambda b[....] over {%,%-1,%-2,...,1}
b[a["\/",%]," ",%];
//print the last row "\/\/\/...\/ "
```
[Link to notebook](https://www.wolframcloud.com/obj/310c0ac3-2b2d-40d7-806c-73b82462172c)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~217~~ 154 bytes
```
n=>Join("",Range(0,n).Select(i=>new S(' ',n-i+1)+new S('/',i*2)+new S('_',(n-i)*2-~(n+"").Length)+'\n').Concat(Repeat("\\/",n))).Replace("//", "/ ")+" "+n
```
[Try it online!](https://tio.run/##bZA9T8MwEIZn/CssL7Frx2m7psmCYECdmoElEkqtSzgpvUDsCCEEfz2cEDAgpvfuue8LMQ8R1yUiDTKmLmGQzWtMcPFNmhmW4r/YEenZ39Bygbk7j/CT1Mjqb/XtQuGAlFz8AnVfrVTVdxOSVsqdOhpAbx0Z38AIIWmsaoIX2ehMZo5ytDtjv0GROdzsf92HzGlOMJt9/qHJKmX8EWhIj8ZmLWXGX08UuqRP8AQsqm0LxYOM8UzGLoBWBROpCqmMVVJZWksh@mmWmheWyMfsSpYD65YNa414E1fcNk4j@PsZE/AjQPcajSnF@/oJ "C# (Visual C# Interactive Compiler) – Try It Online")
Edit: Removed 19 bytes thanks to @KevinCruijssen, and used the header better(?)
[Answer]
# [Haskell](https://www.haskell.org/), 129 bytes
```
x%s=[1..x]>>s
0#b=b%"\\/"++' ':show b
x#b=(x+1)%" "++(b-x)%"/ "++(show b>>"_")++x%"__"++'\n':(x-1)#b
f x=x#x
main=interact$f.read
```
[Try it online!](https://tio.run/##JYvRCsIgGEbvfQrRREXmssuBvkiGaDk2tgzmoP/tbdXd4TvfmWJd8rq2Bqzaq9Eabs5VdKbJJka874lSHPOhTq83TgiOXYAykhF8GJE6OLD/8f/iHAlEKgWMhPCNfeGDgM5ImtCIwQIF9IxzsXPZ8xbv@2nUW46P1szlAw "Haskell – Try It Online")
Ties [the existing 129 byte answer](https://codegolf.stackexchange.com/a/204559/56656) but is compliant with the challenge by performing full IO.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 77 bytes
```
^
$.'$*_=$'$*/¶$'$*V
/
=$.%'$*=¶ $.%'$* $`
=
__
(_+)(/+)
$2$1
/
/
V
\/
1A`
```
[Try it online!](https://tio.run/##K0otycxL/P8/jktFT11FK95WBUjqH9oGosIUuPS5bFX0VIFs20PbFBQgTAWVBC5brvh4Lo14bU0NfW1NLhUjFUOgUn0FrjCuGH0uQ8eE//8NDQA "Retina 0.8.2 – Try It Online") Explanation:
```
^
$.'$*_=$'$*/¶$'$*V
```
Insert some working elements: enough `_`s to cover the input, a `/` for each input, then on the next line, a `V` for each input (representing `\/`) and a space.
```
/
=$.%'$*=¶ $.%'$* $`
```
Now expand the `/`s into a bottom right triangle, and also add extra `_`s to overhang on both sides on each line.
```
=
__
```
Expand the `=`s which were placeholders for two `_`s.
```
(_+)(/+)
$2$1
```
Move the input cover next to the rest of the overhang.
```
/
/
```
Space the `/`s apart.
```
V
\/
```
Expand the `V`s on the last line.
```
1A`
```
Delete some left-overs.
[Answer]
# [Haskell](https://www.haskell.org/), 129 bytes
```
r=replicate
c=(concat.).r
f n|s<-show n=unlines$map(\o->r(n-o+1)' '++c o"/ "++r(2*(n-o)+length s)'_')[0..n-1]++[c n"\\/"++" "++s]
```
[Try it online!](https://tio.run/##FYzBDoIwEAXvfMWGmLR1oYjGm/gFevIIhDRNEWLZkhbixX@vcHvJzLxBhY@xNkZfeTPbUavFJLri2tE2pZA@6YF@4ZaHwX2BqpXsSCYcJjXzxuV3zyl3WAoGDFGDSwtIET0/H3cg0Bp6LwMEwTom6pOUlJctYq2B0qYpNjfdg9DGSY0EFSQA2/ezAz6vy2vxDwIJvYC6zC7ZNStPbfwD "Haskell – Try It Online")
[Answer]
# Java 11, ~~137~~ 124 bytes
```
n->{String l="\\/".repeat(n)+" "+n,r=l;for(;n-->0;r=l+"\n"+r)l=" "+l.replace('\\',' ').replaceAll(".(?!.*/)","_");return r;}
```
-13 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/204532/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##NZDBTsMwDIbvewqTSxOaZhuIC1GHeAB24bhOKOsylJG5VZoOoarPXhxWDrZk57fz/T6bqynOx6@p9qbr4M04HBYADqMNJ1Nb2KYS4D0Gh59Qc3oBFJqa44JSF010NWwBoYQJi80wK33JqmrJVLCtNZGjyBmwHGUovT41gWssis1KU5mzClkeBE2QwqcJTz/zrKoymUEm/juv3nOm@Mudul8KJtkHEzrY2AeEoMdJJ562P3jimbGujTvChTzxG9VuD0bcDCWG5MXBM6D9To53@2Et4VHCk4T1iuJhFH9asv/TRXtRTR9VS4uiR46KjiHmS4zTLw)
**Explanation:**
```
n->{ // Method with integer parameter and String return-type
String l= // Temp-String `l` for the current line, starting at:
"\\/".repeat(n) // The input amount of "\/"
+" "+n, // appended with a space and the input
r=l; // Result-String, starting at this (last) line
for(;n-->0 // Loop `n` amount of times:
; // After every iteration:
r=l+"\n"+r) // Prepend the new `l` with newline to the result-String
l= // Change `l` to the new line:
" " // A space
+l // appended with the current line, with the replacements:
.replace('\\',' ') // All '\' replaced with spaces
.replaceAll(".(?!.*/)","_");
// And all characters NOT followed by a '/' with a "_"
return r;} // And return the result-String after the loop
```
[Answer]
# [Julia](https://julialang.org/), 107 bytes
```
n=parse(Int,readline())
println.([[" "^(s+1)*"/ "^(n-s)*"_"^(2s+length("$n")) for s=n:-1:1];"\\/"^n*" $n"])
```
[Try it online!](https://tio.run/##FclLCsIwFAXQuasIDwd5/VjiRKh0AV1DPxIwakq4lrwI7j7G2YGzfYK35pszht1GcXpEaqKz9@DhNPNhjx4p4KSniRStWmrDFXV/opXCW9FZ6uDwTC9NRxCzeryjkgF9a3qzXGmeO1pRkSq7cM6XHw "Julia 1.0 – Try It Online")
## Breakdown
```
n = parse(Int, readline())
println.([ # broadcasting with `.` applies `println` to each element of vector
[
" "^(s + 1)*"/ "^(n - s)*"_"^(2s + length("$n"))
for s ∈ n:-1:1 # array comprehension
]; # semicolon enables blockmatrix-style array syntax...
# ...which unpacks elements in array above into elements of vector
"\\/"^n*" $n" # last element of vector
])
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~100~~, 99 bytes
```
n=int(input())
for i in range(n):print(" "*(n+~i)," /"*i,"_"*(2*n-2*i+len(str(n))))
print("\/"*n,n)
```
[Try it online!](https://tio.run/##LcuxCoNAEITh3qdYtto9L8RoJ/gmAbEwuhDG4zyLNHn18wSn/Pkm/NK6ocsZgyGJIRxJVKvPFsnIQHHCMgu0D/ECTOwE9d/UMz3ZmeexlNbh0TqrvzNkT7H4suq@vIuDh@b8ak4 "Python 3 – Try It Online")
thnx to @KevinCruijssen for -1
[Answer]
# [Perl 5](https://www.perl.org/) `-ap`, 86 bytes
```
$\=$/.'\\/'x$_." $_";$_=$"x($_+1).'_'x(2*$_+y///c);for$a(1.."@F"-1){say;s, /| __,/ ,g}
```
[Try it online!](https://tio.run/##DcfBCgIhEADQXxEZUEtn1sCTLHTq1h8Ig0RFEClrB5fq17Pe7dXzcg9jQJqBUKVEqgOjFMAyAs8guwbeeoOKVde7zT8rEZ1MvJQFsvaIcn@QzptXy2tsVtBbMFsS9voZI3xLfd7Kow13DDj5abhcfw "Perl 5 – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 46 bytes
```
li:A:B;{A)S*"/ "BA-*'_2A*Bs,+*NA(:A}g"\\/"B*SB
```
[Try it online!](https://tio.run/##S85KzP3/PyfTytHKybraUTNYS0lfQcnJUVdLPd7IUcupWEdby89Rw8qxNl0pJkZfyUkr2On/f0MjAA "CJam – Try It Online")
Port of my Python answer
Explanation:
```
li take input as integer
:A:B; assign that to the variables A and B
{ start of while A loop
A)S* push A-1 spaces
"/ "BA-* push B-A strings of "/ "
'_2A*Bs,+* push 2A + the number of digits _
N push a newline
A(:A decrement A
}g end of while loop
"\\/"B* push B \/
SB push B after a space
```
[Answer]
# [Haskell](https://www.haskell.org/), 122 bytes
```
x%y=[1..x]>>y
f x|n<-read x=unlines[(n+1-i)%" "++i%"/ "++(n-i)%"__"++(x>>"_")|i<-[0..n-1]]++n%"\\/"++' ':x
main=interact f
```
[Try it online!](https://tio.run/##HYnRCoMgFEDf@wq5IBWi5etIf8REZDN2mbsP1cCgf3drT@dwzjNur5RzrYUfxmmlirf2aBZWTprkmuKDFfOhjJQ215HQEnsODIRADsPFjv4phMuLtRCgP3GSblSKpPZeCOIwz8Pvt6y9leYdkQzSntZ439lSqx6/ "Haskell – Try It Online")
I've deliberately constrained myself to standard I/O. See my comments on the question.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `So`, 30 bytes
```
ɾṘ›?ʀṪ‛/ *꘍?ɾd?L+\_*Ṙ+⁋,‛\/*$"
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJTbyIsIiIsIsm+4bmY4oC6P8qA4bmq4oCbLyAq6piNP8m+ZD9MK1xcXyrhuZgr4oGLLOKAm1xcLyokXCIiLCIiLCI0Il0=)
This code's sorta backwards to reduce stack operations.
```
?ɾd # (1...input) * 2
?L+ # + log_10(input)
\_* # That many underscores for each
Ṙ+ # Reverse that, and append to...
ɾṘ› # (2...input+1) reversed
꘍ # For each, that many spaces appended to each of...
?ʀṪ # 0...input-2
‛/ * # For each, that many copies of "/ "
⁋, # Print that, joined on newlines
‛\/* # Input * "\/"
$" # Paired with input
# (So flags) print that joined by a space
```
[Answer]
# [Perl 5](https://www.perl.org/), 96 bytes
```
sub f{$n=pop;join"\n",(map' 'x($x=1+$n-$_).'/ 'x$_.'_'x($x*2-2+length$n),0..$n-1),'\/'x$n." $n"}
```
[Try it online!](https://tio.run/##bZDLbsIwEEX38xWWZclJY2xCy4aQ/kF3XVqyihogFUysOEhUiG9P82hCHtib6zlnZiTbJD@tSyjdZUf2N4axzWz0k6VINVLhnb8sJ/zqsWscBgwXzPiSq6rCjOSmAS@rxSo4JXgojgx9sZSy8kJfcK0qDSUlDOm9vLiEfCau2Gw@sjwhRRVd/P4WwT7L6zXECY1MiFw4e0oLpVFjoMR2yyX3b@dfj6Vo/Vjp70AdIpunWFBmaotGqfP2LRfMCIqX8y7JSV2g/h0IMcaAViSEKjev@tRZkS6qNldafclrq/Zy19C39AX1qMD/czx1PLmZvu6mT1fMtk1XPhXUUwOGeC7AiE45jOEYw4QNKUzRA8KMdAzmoEWDTxt8X7gEWf4B "Perl 5 – Try It Online")
[Answer]
# [PHP](https://php.net/), 121 bytes
```
for($x=($i=$j=$argn)/10+1,$f=str_repeat;$i;$c.="/ ")printf("%{$i}s $c%s\n"," ",$f("_",2*$i--+$x));echo$f("\\/",$j)." $j";
```
[Try it online!](https://tio.run/##FYtLCsMgFACvIo8X0MZ87NZIdz2FEILERhcq6iJQevXadDOLGSYdqS2PdNHGTPFUFJ1Cr3DLr8AmMfeCo1Wl5jXvad@qRCfRjAomAixlF6ql0L3RfQpB0xUdgAOBa6KwAr/f0A1DjydjcjdH/Gutp6t7NgJBD7I1MX9jqi6G0obnDw "PHP – Try It Online")
This is not that great maybe, but I came with this.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~54~~ 44 bytes
```
VQ+d++*-QNd*"/ "N*+*2-QNl+""Q"_";++*"\/"hNdQ
```
[Try it online!](https://tio.run/##K6gsyfj/PyxQO0VbW0s30C9FS0lfQclPS1vLCMjL0VZSClSKV7IGSirF6Ctl@KUE/v9vCgA "Pyth – Try It Online")
edit 1: Thanks @mathjunkie for saving 10 bytes!
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 38 bytes
```
Fi,aP[sYsXa-i"/ "Xi'_Ma.y.y]"\/"Xa.s.a
```
[Try it online!](https://tio.run/##K8gs@P/fLVMnMSC6OLI4IlE3U0lfQSkiUz3eN1GvUq8yVilGXykiUa9YL/H///@GBgA "Pip – Try It Online")
### Explanation
This is one of those very rare occasions in Pip when a for loop seems to be the shortest solution.
```
Fi,aP[sYsXa-i"/ "Xi'_Ma.y.y]"\/"Xa.s.a
s is space; a is 1st command-line arg (implicit)
Fi,a For i in range(a):
P Print, with a newline
[ ] the contents of this list, implicitly concatenated:
s A space
sXa-i Space, repeated (a-i) times
Y also, yank that string into the y variable
"/ "Xi "/ ", repeated (i) times
a.y.y Concatenate a with y twice
'_M and replace each character with an underscore,
giving a string of len(a) + 2 * (a-i) underscores
"\/"Xa "\/", repeated (a) times
.s concatenated to space
.a concatenated to a
Autoprint (implicit)
```
[Answer]
# [MAWP](https://esolangs.org/wiki/MAWP), 138 bytes
```
%@![1A~!~]%![!!!1M[84W;1A]%\A[95W2M;84W;1A]%2W1M3A{3M[29W1M5W;1A]25W;%1A}]~!!0/[25WP~1M~]%\1A3M[29W1M5W;1A]25W;%[99W25WM1M;95W2M;1A]%84W;:
```
Works as expected for single digit numbers, but beyond that, the last root will be longer than the others.
[Try it!](https://8dion8.github.io/MAWP/v1.1?code=%25%40!%5B1A%7E!%7E%5D%25!%5B!!!1M%5B84W%3B1A%5D%25%5CA%5B95W2M%3B84W%3B1A%5D%252W1M3A%7B3M%5B29W1M5W%3B1A%5D25W%3B%251A%7D%5D%7E!!0%2F%5B25WP%7E1M%7E%5D%25%5C1A3M%5B29W1M5W%3B1A%5D25W%3B%25%5B99W25WM1M%3B95W2M%3B1A%5D%2584W%3B%3A&input=5)
[Answer]
# [Scala](http://www.scala-lang.org/), 91 bytes
```
n=>print(n.to(1,-1).map{i=>" "*(i+1)+"/ "*(n-i)+"_"*(2*i+1)}:+("\\/"*n+" "+n)mkString "\n")
```
[Try it online!](https://tio.run/##HY6xCoMwGIT3PMWRKTFVSaGLVKFjh06lm1BSqyWt/oqGUhCfPY1O93EcdzdVpjW@f7zryuFiLKH@uZqeE07DgJmxr2nRZDiTQ17gRjaop7wYRktOUOJ6oXexlklnhtnmBQePhFVaKp6uSLENeA@0j1Z7yZTgZZnyiFTIKpLd5@pC2Qu8JC5904@CcIyh4XocZDgBNIJkkG20JbEl2cLY4v8 "Scala – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 46 bytes
```
`:§+*"¦/"o:' s¹z+mR' ṫ¹m§+*" /"(:' R'_+L¹D≠¹)ŀ
```
[Try it online!](https://tio.run/##yygtzv7/P8Hq0HJtLaVDy/SV8q3UFYoP7azSzg1SV3i4c/WhnblgOQV9JQ2gVJB6vLbPoZ0ujzoXHNqpebTh////JgYA "Husk – Try It Online")
] |
[Question]
[
Your task is to calculate the square root of 2 using Newton's Method - with a slight twist. Your program is to calculate an iteration using Newton's Method, and output the source code for the following iteration (which must be able to do the same).
Newton's method is fairly exhaustively described on [Wikipedia](http://en.wikipedia.org/wiki/Newton%27s_Method)
To calculate square root 2 using Newtons method, you:
* Define `f(x) = x^2 - 2`
* Define `f'(x) = 2x`
* Define `x[0]` (the initial guess) `= 1`
* Define `x[n+1] = x[n] - (f[n] / f'[n])`
Each iteration will move x[n] closer to the square root of two. So -
* `x[0] = 1`
* `x[1] = x[0] - f(x[0])/f'(x[0]) = 1 - (1 ^ 2 - 2) / (2 * 1) = 1.5`
* `x[2] = x[1] - f(x[1])/f'(x[1]) = 1.5 - (1.5 ^ 2 - 2) / (2 * 1.5) = 1.416666667`
* `x[3] = x[2] - f(x[2])/f'(x[1]) = 1.416666667 - (1.416666667 ^ 2 - 2) / (2 * 1.416666667) = 1.414215686`
* and so on
Your program will:
* Calculate `x[n]` where `n` is the amount of times the program has been run
* Output the source code to a valid program in the same language which must calculate `x[n+1]` and satisfy the same criteria of this question.
* The first line of the source code must be the calculate result, properly commented. If the source requires something particular (such as a shebang) on the first line, the result may be put on the second line.
Note that
* Your program must use an initial guess of `x[0] = 1`
* The [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply
* Any in-build power, square root or xroot functions are forbidden
* Your program must not accept any input whatsoever. It must be entirely self contained.
Your score is the size of your initial program in UTF-8 bytes. The lowest score wins.
[Answer]
# Common Lisp, 223 95 68 66
```
(#1=(lambda(x p)(format t"~S~%~S"p`(,x',x,(+(/ p 2)(/ p)))))'#1#1)
```
Now that I read the problem statement more carefully (thanks, [primo](https://codegolf.stackexchange.com/users/4098/primo)!) I noticed that the first line must *be* the result of calculation, not that it needs to *contain* the result. Thus, I think my earlier attempts did not quite follow the rules. This one should.
Example use (SBCL 1.1.15):
```
$ sbcl --script nq.lisp | tee nq2.lisp
1
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
'(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 3/2)
$ sbcl --script nq2.lisp | tee nq3.lisp
3/2
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
'(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 17/12)
$ sbcl --script nq3.lisp | tee nq4.lisp
17/12
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
'(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 577/408)
$ sbcl --script nq4.lisp | tee nq5.lisp
577/408
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
'(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
665857/470832)
$ sbcl --script nq5.lisp | tee nq6.lisp
665857/470832
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
'(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
886731088897/627013566048)
$
```
[Answer]
## Python 53 bytes
*Saved 7 bytes due to [@Mukundan](https://codegolf.stackexchange.com/posts/comments/472150?noredirect=1).*
```
x=1.
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o
```
I've simplified the formula slightly, using the following substitutions:
```
x-(x²-2)/(2x)
= (2x²)/(2x)-(x²-2)/(2x)
= (2x²-x²+2)/(2x)
= (x²+2)/(2x)
= (x+2/x)/2
= x/2+1/x
```
I hope that's not an issue.
The program proceeds in the following manner:
```
$ python newton-quine.py
x=1.5
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o
$ python newton-quine.py
x=1.41666666667
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o
$ python newton-quine.py
x=1.41421568627
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o
$ python newton-quine.py
x=1.41421356237
o='print"x=%s\\no=%r;exec o"%(x/2+1/x,o)';exec o
```
etc.
[Answer]
# CJam, 20 bytes
```
1
{\d_2/1@/+p"_~"}_~
```
[Try it online.](http://cjam.aditsu.net/)
### Output
```
$ cjam <(echo -e '1\n{\d_2/1@/+p"_~"}_~'); echo
1.5
{\d_2/1@/+p"_~"}_~
$ cjam <(cjam <(echo -e '1\n{\d_2/1@/+p"_~"}_~')); echo
1.4166666666666665
{\d_2/1@/+p"_~"}_~
$ cjam <(cjam <(cjam <(echo -e '1\n{\d_2/1@/+p"_~"}_~'))); echo
1.4142156862745097
{\d_2/1@/+p"_~"}_~
$ cjam <(cjam <(cjam <(cjam <(echo -e '1\n{\d_2/1@/+p"_~"}_~')))); echo
1.4142135623746899
{\d_2/1@/+p"_~"}_~
```
### How it works
```
1 " Push the initial guess. ";
{ " ";
\d " Swap the code block with the initial guess and cast to Double. ";
_2/ " Duplicate the initial guess and divide the copy by 2. ";
1@/ " Push 1, rotate the initial guess on top and divide. ";
+p " Add the quotients and print. ";
"_~" " Push the string '_~'. ";
} " ";
_~ " Duplicate the code block (to leave a copy on the stack) and execute it. ";
```
[Answer]
# ECMAScript 6, 38 36
```
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1)
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1.5)
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1.4166666666666665)
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1.4142156862745097)
(f=x=>"(f="+f+")("+(x/2+1/x)+")")(1.4142135623746899)
```
---
## JavaScript, 51
```
(function f(x){return "("+f+")("+(x/2+1/x)+")"})(1)
```
This is the same as the above, for older browsers.
[Answer]
# Lua 129
Probably way too long, but the Lua quine sucks because the nested `[[ ]]` is a deprecated feature. But it works regardless:
```
x=1.0;x=x/2.+1./x;l=[[io.write('x=',x,';x=x/2.+1./x;l=[','[',l,']','];',l)]];io.write('x=',x,';x=x/2.+1./x;l=[','[',l,']','];',l)
```
It's a bit nicer to see if you add newlines instead of colons:
```
x=1.0
x=x/2.+1./x
l=[[io.write('x=',x,'\nx=x/2.+1./x\nl=[','[',l,']','];',l)]];io.write('x=',x,'\nx=x/2.+1./x\nl=[','[',l,']','];',l)
```
[Answer]
# J - ~~102~~ 88 bytes
This is as horrible as I'm at making quines (I will probably revise this when I get better ideas). J's floats are limited to 5 decimal places, but by replacing first line with `x=:1x` it would be a fraction with infinite precision.
```
Edit 1: I got better idea. Also added the explanation.
```
---
```
x=:1
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''
```
First few iterations:
```
x=:1.5
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''
x=:1.41667
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''
x=:1.41422
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''
```
### Explanation
```
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'x=:((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:)'''
((3&{.,[:":(x%2)+1%x"_),:3&}.,],{:,{:) The quine-function
3&}.,],{:,{: Build the second row
3&}. Get everything but the first 3 characters from the string
,] Get the whole string and concat
,{: Get the last item (') and concat
,{: -||-
(3&{.,[:":(x%2)+1%x"_) Build the first row
[:":(x%2)+1%x"_ Calculate x/2 + 1/x (stolen from Pythoneer) and stringify
3&{. Take the first 3 characters from the string (x=:)
, Concatenate 'x=:' and the result
,: Concatenate the two rows
```
[Answer]
# Ruby, 65
```
x=1.0
puts"x=#{x/2+1/x}",<<'1'*2,1
puts"x=#{x/2+1/x}",<<'1'*2,1
1
```
As too often happens, this is almost a straight port of the Python solution.
[Answer]
# [Perl 5](https://www.perl.org/), (`-M5.01`) 58 bytes
```
$x=1.;$_=q(say'$x='.($x/2+1/$x).qq(;\$_=q($_);eval));eval
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lwtZQz1ol3rZQozixUh3IVdfTUKnQN9I21Fep0NQrLNSwjgFLq8RrWqeWJeZoQiiu////5ReUZObnFf/X9TXVMzAEAA "Perl 5 – Try It Online")
] |
[Question]
[
Given an [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") road and the time it took me to cross it, tell me if I was speeding.
## Units
Distance is in the arbitrary unit of `d`. Time is in the arbitrary unit of `t`.
## The road
Here is a simple road:
```
10=====
```
The `10` means 10 `d` per `t`. That is the speed limit for the road. The road has 5 `=`s, so its `d` is 5. Therefore, if I cross that road in 0.5 `t`, I went 10 `d` per `t`, because 5/0.5 = 10. The speed limit of that road is 10, so I stayed within the speed limit.
But if I cross that road in **0.25** `t`, I went 20 `d` per `t`, because 5/**0.25** = 20. The speed limit of that road is 10, so I went 10 over the speed limit.
## Examples and calculations
Note that input 1 is the time I took to travel the road, and input 2 is the road itself.
Here is a complex road:
```
Input 1: 1.5
Input 2: 5=====10=====
```
The fastest I could have (legally) gone on the first road (the first 5 `=`s) is 5 `d` per `t`. Since 5 (distance) divided by 5 (speed limit) is 1, the fastest I could have gone on that road is 1 `t`.
On the next road, the speed limit is 10 and the distance is also 5, the fastest I could cross that is 0.5 (5/10). Totaling the minimum times results in 1.5, meaning I went at *exactly the speed limit.*
*Note: I know, I might have been going really fast on one road and really slow on another and still cross in 1.5, but assume the best here.*
A final example:
```
Input 1: 3.2
Input 2: 3.0==========20===
```
The first road is 10 long and has a speed limit of 3, so the minimum time is 3.33333... (10 / 3.)
The second road is 3 long and has a speed limit of 20, so the minimum time is 0.15 (3 / 20.)
Totaling the times results in 3.483333333... I crossed it in 3.2, so I had to be speeding somewhere.
## Notes:
* You must output one distinct value if I am undoubtedly speeding, and another different value if I might not be.
* Your program or function may require input or output to have a trailing newline, but please say so in your submission.
* Your first input will be my speed. It will be a positive float or integer or string.
* Your second input will be the road. It will always match the regex `^(([1-9]+[0-9]*|[0-9]+\.[0-9]+)=+)+\n?$`. [You may test out potential inputs here if you are interested.](https://regex101.com/r/Iq04Ph/4)
* You may take input in 2 parameters of a function or program, in 2 separate files, from STDIN twice, or from a space-separated string passed to STDIN, a function, a file or a command-line parameter.
* If you would like to, you can change the order of the inputs.
* Any questions? Ask below in comments and **happy [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")ing!**
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
m,s=input()
for c in s.split('=')[:-1]:s=float(c or s);m-=1/s
print m<0
```
[Try it online!](https://tio.run/nexus/python2#@5@rU2ybmVdQWqKhyZWWX6SQrJCZp1CsV1yQk1mioW6rrhltpWsYa1Vsm5aTn1iikawAVFOsaZ2ra2uoX8xVUJSZV6KQa2Pw/7@xnomOgpKxnoEtHBiB2EoA "Python 2 – TIO Nexus")
Python's dynamic type system can take quite some abuse.
Splitting the input string `s.split('=')` turns `k` equal signs into `k-1` empty-string list elements (except at the end, where one must be cut off). For example,
```
"3.0===20====".split('=')[:-1] == ['3.0', '', '', '20', '', '', '']
```
The code iterates over these elements, updating the current speed `s` each time it sees a number. The update is done as `s=float(c or s)`, where if `c` is a nonempty string, we get `float(c)`, and otherwise `c or s` evaluates to `s`, where `float(s)` just keeps `s`. Note that `c` is a string and `s` is a number, but Python doesn't require doesn't require consistent input types, and `float` accepts either.
Note also that the variable `s` storing the speed is the same one as taking the input string. The string is evaluated when the loop begins, and changing it within the loop doesn't change what is iterated over. So, the same variable can be reused to save on an initialization. The first loop always has `c` as a number, so `s=float(c or s)` doesn't care about `s`'s initial role as a string.
Each iteration subtracts the current speed from the allowance, which starts as the speed limit. At the end, the speed limit has been violated if this falls below `0`.
[Answer]
# [Python 3](https://docs.python.org/3/), 79 bytes
```
import re;g=re.sub
lambda m,s:eval(g('=','-~',g('([^=]+)',r'0+1/\1*',s))+'0')>m
```
[Try it online!](https://tio.run/nexus/python3#PcZLDsIgEADQvafobmZkRGrTjQYv4iehkTYkpZKBuvTqqBvf6tUQ01NKI/40WfE6r8NmtLOLw8M1kfPRv9yME4IFht0b@Fu83O1NEbCAUe3@2m6BM5ECA3SONUlYCo7Y6Z7DktaCRFQ7bezf4fcP "Python 3 – TIO Nexus")
For example, the input `3.0==========20===` is converted to the string
```
0+1/3.0*-~-~-~-~-~-~-~-~-~-~0+1/20*-~-~-~0
```
and evaluated, and the result is compared to the input speed. Each `-~` increments by `1`. I'm new to regexes, so perhaps there's a better way, like making both substitutions at once. Thanks to Jonathan Allan for pointing out how to match on all but the `=` character.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ 22 bytes
Returns **1** when undoubtedly speeding and **0** otherwise.
Saved 2 bytes thanks to *carusocomputing*.
```
'=¡õK¹S'=Q.¡O0K/O-§'-å
```
[Try it online!](https://tio.run/nexus/05ab1e#@69ue2jh4a3eh3YGq9sG6h1a6G/gre@ve2i5uu7hpf//G@sZ2MKBEYjNZaxnBAA "05AB1E – TIO Nexus")
`-§'-å` shouldn't have to be more than a simple comparison, but for some reason neither `›` nor `‹` seem to work between the calculated value and the second input.
**Explanation**
Using `3.0==========20===, 3.2` as example
```
'=¡ # split first input on "="
õK # remove empty strings
# STACK: ['3.0', '20']
¹S # split first input into a list of chars
'=Q # compare each to "="
.¡O # split into chunks of consecutive equal elements and sum
# STACK: ['3.0', '20'], [0, 10, 0, 3]
0K # remove zeroes
# STACK: ['3.0', '20'], [10, 3]
/ # element-wise division
# STACK: [3.3333333333333335, 0.15]
O # sum
# STACK: 3.4833333333333334
- # subtract from second input
# STACK: -0.2833333333333332
§ # implicitly convert to string
'-å # check if negative
# OUTPUT: 1
```
[Answer]
# Javascript (ES6), 63 bytes
```
a=>b=>eval(b.replace(/([^=]+)(=+)/g,(_,c,d)=>'+'+d.length/c))>a
```
# Usage
Assign this function to a variable and call it using the currying syntax. The first argument is the time, the second is the road.
# Explanation
Matches all consecutive runs of characters that are not equal signs followed by a run of equal signs. Each match is replaced by the result of the inner function, which uses two arguments: the run of equal signs (in variable `d`) and the number (variable `c`). The function returns the length of the road devided by the number, prepended by a +.
The resulting string is then evaluated, and compared against the first input.
# Stack Snippet
```
let f=
a=>b=>eval(b.replace(/([^=]+)(=+)/g,(_,c,d)=>'+'+d.length/c))>a
```
```
<input id="time" placeholder="time" type="number">
<input id="road" placeholder="road">
<button onclick="output.innerHTML=f(time.value)(road.value)">Process</button>
<div id="output"></div>
```
[Answer]
# GNU C, 128 bytes
```
#import<stdlib.h>
f(float t,char*r){float l,s=0;for(;*r;){for(l=atof(r);*(++r)-61;);for(;*r++==61;)s+=1/l;--r;}return t<s-.001;}
```
Handles non-integer speed limits also. `#import<stdlib.h>` is needed for the compiler not to assume that `atof()` returns an `int`.
`t<s-.001` is needed to make the exact speed limit test case to work, otherwise rounding errors cause it to think you were speeding. Of course, now if the time is `1.4999` instead of `1.5`, it doesn't consider that speeding. I hope that's okay.
[Try it online!](https://tio.run/nexus/c-gcc#PY3NDoIwEITvPEVTQ9LSgi0EL2t9Ei8oNjQpP1nqifDsWDA6h92dbybZ7eT6acRwnUPr3aPoboll1o9NIEE@uwYz5MvXezkbBXZEBhlCpPHypgmjZcghY0Igzy8a@K8jhDG7n4XRZw95jrDiK7xxIPFfXiilYd3cEEjfuIHxZElI1IQRWUbT9j6kLZXEsqooJa3MX6WKg/I90kUtaX1QrY5FOYdk3T4)
[Answer]
# [Perl 5](https://www.perl.org/), 43 bytes
42 bytes of code + `-p` flag.
```
s%[^=]+(=+)%$t+=(length$1)/$&%ge;$_=$t<=<>
```
[Try it online!](https://tio.run/nexus/perl5#Pc3NDoIwEATge59ihWIgKPITTrA@CQmpsSJJC01ZjCS8O1oSnctM5vL5ByOtgrNhnDCtwAcrJ0n90MFjtKBnRb1REuRb6G9P2xQ09zjEOAo4xRgqOXT05Fl04cegkxVvkVON9XWrgLewrgjpvhIErxk8J/Ta2PHliHEmM5OTtCCHnnbVSnEXt14tMA5q2bIUXVia5CUr9/27sqRkBf6Tu5sVSf4B "Perl 5 – TIO Nexus")
For each group of digit followed by some equal signs (`[^=]+(=+)`), we calculate how much time is needed to cross it (number of equals divided by the speed: `(length$1)/$&`) and sum those times inside `$t`. At the end, we just need to check that `$t` is less than the time you took to cross it (`$_=$t < <>`). The result will be `1` (true) or *nothing* (false).
[Answer]
# Mathematica, 98 bytes
```
Tr[#2~StringSplit~"="//.{z___,a_,b:Longest@""..,c__}:>{z,(Length@{b}+1)/ToExpression@a,c}]-"
"<=#&
```
Pure function taking two arguments, a number (which can be an integer, fraction, decimal, even `π` or a number in scientific notation) and a newline-terminated string, and returning `True` or `False`. Explanation by way of example, using the inputs `3.2` and `"3==========20===\n"`:
`#2~StringSplit~"="` produces `{"3","","","","","","","","","","20","","","\n"}`. Notice that the number of consecutive `""`s is one fewer than the number of consecutive `=`s in each run.
`//.{z___,a_,b:Longest@""..,c__}:>{z,(Length@{b}+1)/ToExpression@a,c}` is a repeating replacement rule. First it sets `z` to the empty sequence, `a` to `"3"`, `b` to `"","","","","","","","",""` (the longest run of `""`s it could find), and `c` to `"20","","","\n"`; the command `(Length@{b}+1)/ToExpression@a` evaluates to `(9+1)/3`, and so the result of the replacement is the list `{10/3, "20","","","\n"}`.
Next the replacement rule sets `z` to `10/3`, `a` to `"20"`, `b` to `"",""`, and `c` to `"\n"`. Now `(Length@{b}+1)/ToExpression@a` evaluates to `(2+1)/20`, and so the result of the replacement is `{10/3, 3/20, "\n"}`. The replacement rule can't find another match, so it halts.
Finally, `Tr[...]-"\n"` (it saves a byte to use an actual newline between the quotes instead of `"\n"`) adds the elements of the list, obtaining `10/3 + 3/20 + "\n"`, and then subtracts off the `"\n"`, which Mathematica is perfectly happy to do. Finally, `<=#` compares the result to the first input (`3.2` in this case), which yields `False`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ”=V€ḟ0
Œr”=e$ÐfṪ€ż⁸Ǥ÷/€S>
```
**[Try it online!](https://tio.run/nexus/jelly#@/9w5@JHDXNtwx41rXm4Y74B19FJRSB@qsrhCWkPd64CCh/d86hxx@H2Q0sOb9cHcoPt/v//b6xnYAsHRiA2UMgEAA "Jelly – TIO Nexus")**
Note: assumes that the regex given in the question should be such that a speed limit cannot be `0.0`, `0.00`, etc. - just like it cannot be `0` ([confirmed](https://codegolf.stackexchange.com/questions/116050/am-i-over-the-speed-limit/116063#comment283408_116050) as an unintentional property).
### How?
```
ṣ”=V€ḟ0 - Link 1, speed limits: road e.g. "4.0===22=="
ṣ”= - split by '=' [['4','.','0'],[],[],['2','2'],[],[]]
V€ - evaluate €ach as Jelly code [4.0,0,0,22,0,0]
ḟ0 - filter discard zero [4.0,22]
Œr”=e$ÐfṪ€ż⁸Ǥ÷/€S> - Main link: road, time e.g. "4.0===22==", 0.84
Œr - run-length encode [['4',1],['.',1],['0',1],['=',3],['2',2],['=',2]]
Ðf - filter keep:
$ - last two links as a monad:
”= - "="
e - is an element of? [['=',3],['=',2]]
Ṫ€ - tail €ach [3,2]
¤ - nilad followed by link(s) as a nilad:
⁸ - left argument (road)
Ç - last link (1) as a monad [4.0,22]
ż - zip [[3,4.0],[2,22]]
÷/€ - reduce €ach by division [0.75, 0.09090909090909091]
S - sum 0.8409090909090909
> - greater than time? 1 (would be 0 if maybe not speeding)
```
[Answer]
# Python 3, 90 bytes
```
import re
lambda t,r:sum(x.count("=")/eval(x.strip("="))for x in re.findall("\d+\D+",r))>t
```
Outputs `True` if you're speeding, `False` if you might not be. Does not require (but will work with) trailing newline.
Despite it not looking like it would, it correctly handles floats in both input time and speed limits, because the regex is just used to seperate the road segments.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~31~~ 30 bytes
```
t61=TwFhhdfd1wY{1L&)o!oswcU!/s<
```
Inputs are: a string (speed limits and roads), then a number (used speed). Output is `1` if undoubtedly speeding, `0` if not.
[Try it online!](https://tio.run/nexus/matl#@29YaWZoG1LulpGRkpYSWW3oo6aZr5hfXJ4cqqhfbPP/v7qxnoEtHBiB2OpcxnpGAA "MATL – TIO Nexus")
### Explanation with example
Consider inputs `'3.0==========20==='` and `3.2`.
```
1 % Push 1
% STACK: 1
y % Implicitly input string. Duplicate from below
% STACK: '3.0==========20===', 1, '3.0==========20==='
61= % Compare with 61 (ASCII for '=')
% STACK: '3.0==========20===', 1, [0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1]
TwFhh % Prepend true (1) and append false (0)
% STACK: '3.0==========20===', 1, [1 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0]
d % Consecutive differences
% STACK: '3.0==========20===', 1, [-1 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 1 0 0 -1]
f % Find: indices of nonzeros
% STACK: '3.0==========20===', 1, [1 4 14 16 19]
d % Consecutive differences. Gives length of substrings of numbers or roads
% STACK: '3.0==========20===', 1, [3 10 2 3]
Y{ % Split string according to those lenghts. Gives a cell array of strings
% STACK: {'3.0', '==========', '20', '==='}
1L&) % Split into odd- and even-indexed subarrays
% STACK: {'3.0', '20'}, {'==========', '==='}
o % Convert to 2D numeric array. Right-pads with zeros
% STACK: {'3.0', '20'}, [61 61 61 61 61 61 61 61 61 61; 61 61 61 0 0 0 0 0 0 0]
!gs % Number of nonzeros in each row
% STACK: {'3.0', '20'}, [10 3]
w % Swap
% STACK: [10 3], {'3.0', '20'}
c % Convert to 2D char array. Right-pads with spaces
% STACK: [10 3], ['3.0'; '20 ']
U % Convert each row to a number
% STACK: [10 3], [3.0; 20]
! % Transpose
% STACK: [10 3], [3.0 20]
/ % Divide, element-wise
% STACK: [3.3333 0.15]
s % Sum of array
% STACK: 3.4833
< % Implicitly input number. Less than? Implicitly display (true: 1; false: 0)
% STACK: true
```
[Answer]
# APL, 41 bytes
```
{⍺<+/{(≢⍵)÷⍎⍺}/¨Y⊂⍨2|⍳⍴Y←⍵⊂⍨X≠¯1⌽X←⍵='='}
```
This takes the road as a string as its right argument, and the time taken as its left argument, and returns `1` if you were speeding and `0` if not, like so:
```
3.2{⍺<+/{(≢⍵)÷⍎⍺}/¨Y⊂⍨2|⍳⍴Y←⍵⊂⍨X≠¯1⌽X←⍵='='}'3.0==========20==='
1
```
Explanation:
* `X←⍵='='`: store in `X` a bit vector of all positions in `⍵` that are part of the road.
* `X≠¯1⌽X`: mark each position of `X` that is not equal to its right neighbour (wrapping around), giving the positions where numbers and roads start
* `Y←⍵⊂⍨`: split `⍵` at these positions (giving an array of alternating number and road strings), and store it in `Y`.
* `Y⊂⍨2|⍳⍴Y`: split up `Y` in consecutive pairs.
* `{(≢⍵)÷⍎⍺}/¨`: for each pair, divide the length of the road part (`≢⍵`) by the result of evaluating the number part (`⍎⍺`). This gives the minimum time for each segment.
* `+/`: Sum the times for all segments to get the total minimum time.
* `⍺<`: Check whether the given time is less than the minimum or not.
[Answer]
# TI-Basic, ~~168~~ 165 bytes
```
Prompt Str0,T
Str0+"0→Str0
0→I
1→A
While inString(Str0,"=",A
I+1→I
I→dim(L1
I→dim(L2
0→L
inString(Str0,"=",A→B
expr(sub(Str0,A,B–A→L1(I
While 1=expr("9"+sub(Str0,B,1)+"9
L+1→L
B+1→B
If B>length(Str0
Return
End
B→A
L→L2(I
End
T≥sum(seq(L2(X)/L1(X),X,1,I
```
Input is the road as `Str0` and the time as `T`. Make sure to precede the road with a quote, eg `Str0=?"14========3===`.
Output is 0 if speeding, 1 if possibly not speeding.
```
Prompt Str0,T # 6 bytes
Str0+"0→Str0 # 9 bytes
0→I # 4 bytes
1→A # 4 bytes
While inString(Str0,"=",A # 12 bytes
I+1→I # 6 bytes
I→dim(L1 # 6 bytes
I→dim(L2 # 6 bytes
0→L # 4 bytes
inString(Str0,"=",A→B # 13 bytes
expr(sub(Str0,A,B–A→L1(I # 16 bytes
While 1=expr("9"+sub(Str0,B,1)+"9 # 21 bytes
L+1→L # 6 bytes
B+1→B # 6 bytes
If B>length(Str0 # 8 bytes
Return # 2 bytes
End # 2 bytes
B→A # 4 bytes
L→L2(I # 7 bytes
End # 2 bytes
T≥sum(seq(L2(X)/L1(X),X,1,I # 21 bytes
```
[Answer]
# Bash, 151 bytes
Running as (for example) `$ bash golf.sh .5 10=====`:
```
shopt -s extglob
r=$2
while [ -n "$r" ];do
f=${r%%+(=)}
s=`dc<<<"9k$s $[${#r}-${#f}] ${f##*=}/+p"`
r=${f%%+([0-9.])}
done
[[ `dc<<<"$1 $s-p"` != -* ]]
```
## Explanation
```
shopt -s extglob
r=$2
```
Enable bash's [extended pattern-matching operators](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) and assign the road to a variable `r`.
```
while [ -n "$r" ];do
f=${r%%+(=)}
```
Loop until `r` is empty. Set `f` to `r` with all equal signs removed from the end, using the `%%` [parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion) and the `+()` extended globbing operator.
```
s=`dc<<<"9k$s $[${#r}-${#f}] ${f##*=}/+p"`
```
Assign to `s` a running sum of the minimum times for each road segment. This can be re-written (perhaps slightly) more readably as:
```
s=$(dc <<< "9k $s $[${#r}-${#f}] ${f##*=} / + p")
```
Basically what's going on here is we're using a here-string to get the `dc` command to do math for us, since bash can't do floating-point arithmetic by itself. `9k` sets the precision so our division is floating-point, and `p` prints the result when we're done. It's a reverse-polish calculator, so what we're really calculating is `${f##*=}` divided by `$[${#r}-${#f}]`, plus our current sum (or, when we first run through and `s` hasn't been set yet, nothing, which gets us a warning message on stderr about `dc`'s stack being empty, but it still prints the right number because we'd be adding to zero anyway).
As for the actual values we're dividing: `${f##*=}` is `f` with the largest pattern matching `*=` removed from the front. Since `f` is our current road with all the equal signs removed from the end, this means `${f##*=}` is the speed limit for this particular stretch of road. For example, if our road `r` were '10=====5===', then `f` would be '10=====5', and so `${f##*=}` would be '5'.
`$[${#r}-${#f}]` is the number of equal signs at the end of our stretch of road. `${#r}` is the length of `r`; since `f` is just `r` with all the equal signs at the end removed, we can just subtract its length from that of `r` to get the length of this road section.
```
r=${f%%+([0-9.])}
done
```
Remove this section of road's speed limit from the end of `f`, leaving all the other sections of road, and set `r` to that, continuing the loop to process the next bit of road.
```
[[ `dc<<<"$1 $s-p"` != -* ]]
```
Test to see if the time we took to travel the road (provided as `$1`) is less than the minimum allowed by the speed limit. This minimum, `s`, can be a float, so we turn to `dc` again to do the comparison. `dc` does have a comparison operator, but actually using it ended up being 9 more bytes than this, so instead I subtract our travel time from the minimum and check to see if it's negative by checking if it starts with a dash. Perhaps inelegant, but all's fair in love and codegolf.
Since this check is the last command in the script, its return value will be returned by the script as well: 0 if possibly speeding, 1 if definitely speeding:
```
$ bash golf.sh .5 10===== 2>/dev/null && echo maybe || echo definitely
maybe
$ bash golf.sh .4 10===== 2>/dev/null && echo maybe || echo definitely
definitely
```
[Answer]
# Python 3.6, 111 bytes
My first code golf!
```
import re
def f(a,b):
t=0
for c in re.split('(=+)',b)[:-1]:
try:s=float(c)
except:t+=len(c)/s
return a<t
```
[Try it online!](https://tio.run/nexus/python3#PYvBDsIgEETvfMXeWNKKtb2R8iXGAyIkJEgJrIl@Pa4X5zR582akZz0aQQviESJEdPNdGQFkFwHxaOAhFV51rzkRSrSTkqxczelyYw@ofUy3MR@O0CsG4e1DJUOTzaEwOnfBf3q1Am6nUVsqhBE3vc5y04v9Z/11qdT4Ag)
`re.split('(=+)',b)[:-1]`
Splits the road by chunks of `=`.
It then iterates over the result, using `try:s=float(c)` to set the current speed limit if the current item is a number or `except:t+=len(c)/s` to add the time to traverse this section of road to the cumulative total.
Finally it returns the time taken to the fastest possible time.
[Answer]
# PHP5 ~~207~~ 202 bytes
First effort at a code golf answer, please go easy on me. I'm sure one of you geniuses will be able to shorten this significantly, any golfing tips are welcome.
```
function s($c,$d){foreach(array_filter(split("[{$d}/=]",$c)) as $e){$f[]=$e;};return $f;}function x($a,$b){$c=s($b,"^");$d=s($b,"");for($i=0;$i<sizeof($c);$i++){$z+=strlen($c[$i])/$d[$i];}return $a<$b;}
```
Invoke with
```
x("1.5","3.0==========20===")
```
Returns true if you have been under the speed limit, false otherwise
[Answer]
# Dyalog APL, 27 bytes
`<∘(+/(⍎'='⎕r' ')÷⍨'=+'⎕s 1)`
`'=+'⎕s 1` is a function that identifies stretches of `'='` with a regex and returns a vector of their lengths (`⎕s`'s right operand 0 would mean offsets; 1 - lengths; 2 - indices of regexes that matched)
`'='⎕r' '` replaces `'='`s with spaces
`⍎'='⎕r' '` executes it - returns a vector of speeds
`÷⍨` in the middle divides the two vectors (`⍨` swaps the arguments, so it's distance divided by speed)
`+/` is sum
everything so far is a 4-train - a function without an explicit argument
`<∘` composes "less than" in front of that function; so, the function will act only on the right argument and its result will be compared against the left argument
[Answer]
# F# (165 bytes)
```
let rec c t p l=
match l with
|[]->t<0.0
|x::xs->
match x with
|""->c(t-p)p xs
|_->c(t-p)(1.0/float x)xs
let s t (r:string)=r.Split '='|>Seq.toList|>c t 0.0
```
I'm still new to F#, so if I did anything weird or stupid, let me know.
[Answer]
# C# method (137 122 bytes)
Requires `using System.Linq` adding 19 bytes, included in the 122:
```
bool C(float t,string r,float p=0)=>r.Split('=').Aggregate(t,(f,s)=>f-(s==""?p:p=1/float.Parse(s)))<-p;
```
Expanded version:
```
bool Check(float time, string road, float pace=0) =>
road.Split('=')
.Aggregate(time, (f, s) => f - (
s == ""
? pace
: pace = 1 / float.Parse(s)))
< -pace;
```
The `road` string is split on the `=` character. Depending on whether a string is the resulting array is empty, the aggregate function sets the `pace` variable for the segment (denoting the time it takes to travel a single `=`) and subtracts it from the time supplied. This will do one too many substractions (for the final road segment), so instead of comparing to `0`, we compare to `-pace`
[Answer]
# [R](https://www.r-project.org/), 100 bytes
```
function(S,R){s=strsplit(R,"=")[[1]]
s[s==""]=0
S<sum((1+(a=rle(as.double(s)))$l[!a$v])/a$v[a$v>0])}
```
[Try it online!](https://tio.run/##JYnLDoIwEEX3fAVOWMzEWlsIO8aPgGXTBT6akPAwDLgxfntFPMl95N45hrQ6pTGs423pphEbVdNbWJZZnn23YK2AgZyz3ifihBnAs0maStYB0R6x5bl/YCv6Pq3XrQkRZb07tNnL03lzt@liPH1iQKtLBSX/sGYPoCRgoXMFhf4vO7nZv/gF "R – Try It Online")
Returns `TRUE` for unambiguously speeding values, `FALSE` for possibly unspeedy ones.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 71 bytes
```
param($t,$r)$t-lt($r-replace'(.+?)(=+)','+($2)/$1'-replace'=','+1'|iex)
```
[Try it online!](https://tio.run/##PY9RC4IwFIXf/RUXubUNpzmjl0Dqn8TQKwmTbC4Kqt9uc5rn5cI534Fz@9uT7HAlY0ZsoIT32GurO45OohXoUuM42tRSb3RFjGfJSfAyEUyyhGMhdqjYmpaTq9inpZcYv1F05hF4Sa6yg4T4UE5SeTixBGy0GUgszD4rPLPP5jioyBfQ2YfnBHxgA@/Ao2s78hNvupZIr54qR7Xfj5c5tjQ8jPPG1r8VYAhwSGPkC5DSfW2L478WR9/xBw "PowerShell – Try It Online")
Test script:
```
$f = {
param($t,$r)$t-lt($r-replace'(.+?)(=+)','+($2)/$1'-replace'=','+1'|iex)
}
@(
,(1.5, "5=====10=====", $false)
,(3.2, "3.0==========20===", $true)
) | % {
$time,$road,$expected = $_
$result = &$f $time $road
"$($result-eq$expected): $result"
}
```
Output:
```
True: False
True: True
```
Explanation:
1. The script gets the elements of the road `5=====10=====`, swaps elements, adds brackets and operators `+(=====)/5+(=====)/10`
2. Then the script replaces each `=` with `+1`: `+(+1+1+1+1+1)/5+(+1+1+1+1+1)/10`
3. Finally, the script evaluates the string as a Powershell expression and compare it with the first argument.
] |
[Question]
[
You deal cards labeled 0 to 9 from a deck one a time, forming stacks that start at 0 and count up by 1.
* When you deal a 0, you place it on the table to start a new stack.
* When you deal any other card, you stack it atop a card that's exactly
one lower in value, covering it. If there's no such card, the deck isn't stackable.
Given a deck, determine whether it can be stacked when dealt in the order given. Equivalently, given a list of digits, decide whether it can be partitioned into disjoint subsequences each of the form `0,1,..,k`
**Example**
Take the deck `0012312425`. The first two cards are `0`, so they go on the table:
```
Stacks: 00
Deck: 12312425
```
Next, we deal a `1`, which goes on a `0`, doesn't matter which:
```
1
Stacks: 00
Deck: 2312425
```
We then deal a `2` atop the just-placed `1`, and the `3` on top of it.
```
3
2
1
Stacks: 00
Deck: 12425
```
Next, the `1`, `2` and placed atop the first stack and `4` atop the second one.
```
4
3
22
11
Stacks: 00
Deck: 25
```
Now, we need to place a `2`, but there's no `1` atop either stack. So, this deck was not stackable.
**Input:** A nonempty list of digits 0-9, or a string of them. You can't assume that 0 will always be in the input.
**Output**: One of two distinct consistent values, one for stackable sequences and one for non-stackable ones
**Test cases:**
Stackable:
```
0
01
01234
00011122234567890
012031
0120304511627328390
```
Not stackable:
```
1
021
0001111
0012312425
012301210
000112223
```
For convenience, as lists:
```
[0]
[0, 1]
[0, 1, 2, 3, 4]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[0, 1, 2, 0, 3, 1]
[0, 1, 2, 0, 3, 0, 4, 5, 1, 1, 6, 2, 7, 3, 2, 8, 3, 9, 0]
[1]
[0, 2, 1]
[0, 0, 0, 1, 1, 1, 1]
[0, 0, 1, 2, 3, 1, 2, 4, 2, 5]
[0, 1, 2, 3, 0, 1, 2, 1, 0]
[0, 0, 0, 1, 1, 2, 2, 2, 3]
```
Grouped:
```
[[0], [0, 1], [0, 1, 2, 3, 4], [0, 0, 0, 1, 1, 1, 2, 2, 2, 3], [0, 1, 2, 0, 3, 1], [0, 1, 2, 0, 3, 0, 4, 5, 1, 1, 6, 2, 7, 3, 2, 8, 3, 9, 0]]
[[1], [0, 2, 1], [0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 2, 3, 1, 2, 4, 2, 5]]
```
**Leaderboard:**
```
var QUESTION_ID=144201,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/144201/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~45~~ 43 bytes
*-2 bytes thanks to [@TFeld](https://codegolf.stackexchange.com/users/38592/tfeld)*
```
s=[]
for c in input():s+=c,-1;s.remove(c-1)
```
[Try it online!](https://tio.run/##ZU/LboMwELz7K1ZcAuqmws6rpeLYP6hyQRyIu1VQKUbGJM3XU7CDQxNr5H3NjHabizmqWvRSfVIaBEHfplnOvpQGCWU9oOlMGCXtUypxyd/aZ00/6kShXPKoH/jsfCwrgg/dUcIAjL6MYXj0SxJGV1c2uqxNuGhNIb@LQ0WLiI0cSY2BfVF19K610sk/cq0MzAR9FucsixH4NSAIhBXC2tUOfIKYMDIQNghbhB3CC8LrwJx7xJbEH1vxJHWWWzva2ZGwTitvdlUL73O3zq3r93bJ2v6bu5t8zv2uc8Pbcfkf "Python 2 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
Λ¬ḞS:o-→ø
```
[Try it online!](https://tio.run/##yygtzv5/aFuuxqOmxtxMzUPb/p@bfWjNwx3zgq3ydR@1TTq84////wZcBoZAZGRswmVgYGBoaGhkBGSbmplbWIKkjAyMDSGUgYmpoaGZkbmxkYUxUAooamQI1QKigSYYGpkYmYLNAmJDA4gkyDgA "Husk – Try It Online")
Returns `1` for stackable decks and `0` for non-stackable decks.
It looks like Ørjan Johansen in [his Haskell answer](https://codegolf.stackexchange.com/a/144214/62393) already came up with the same algorithm, but in Husk this is obviously much more concise.
### Explanation
We takle the problem from another side: flip the deck and make descending piles. If after going through all the deck all the piles have a 0 on the top, the deck is stackable.
```
Λ¬ḞS:(-→)ø
ø Starting with the empty list (each element of this list will be the top card
of a stack)
ḞS Traverse the input from right to left. For each card:
-→ Remove the successor of this card from our list (if present)
: Add this card to our list
Λ¬ At the end, check if all the cards in our list are zeroes (falsy)
```
[Answer]
# [Haskell](https://www.haskell.org/), 55 bytes
An anonymous function taking a list of integers and returning a `Bool`.
Usage: `(all(<1).foldr(?)[]) [0,1,2,3,4]`.
```
all(<1).foldr(?)[]
m?l|(p,r)<-span(/=m+1)l=m:p++drop 1r
```
[Try it online!](https://tio.run/##ZY9da4MwFIbv8ysO7S4SEp2xX5tUSxmjDMYojF1ZL8LUVhajRMcutv12Z2O1pQsvOd8P5xxE9ZFI2XxbY3hev2ze1ptHeNhuYWz9IpSLTPmZqhMt3uubTyUzlVR2LkqMoH14J62gOhRfICkdgRXAiNJjjFOQhNhYJyL2vNdaZ2pvBeFTS9onOiJmmtgGh1Dq7xohJV5yYqeFjDVekTBC@Ur@4JJpsrSqUih86@eUE@nnXklprIsSuG6a0IlQ6DDgJ8PAZTBhMO3iTryX2@vYwWDGYM5gweCOwX3beclwTBP/n3L60Q45N6WFKbmGNBlgp2l34Fytc84Oe3fO1Pyzq5sGnw@7XgLPx0XoDw "Haskell – Try It Online")
# How it works
* `foldr(?)[]` folds its list argument from right to left using `?`, starting with an empty list. The result is the list of numbers in the list that didn't fit on top of a previous number.
* `all(<1)` tests if the only numbers not fitting on top of a previous number are zeroes.
* `m?l` prepends a number `m` to a list `l` of non-fitting numbers. If `m+1` is already in the list, it can now be removed as it fits on top of `m`.
+ `(p,r)<-span(/=m+1)l` splits the list `l` into two parts `p` and `r` at the first instance of the number `m+1`. If there aren't any, the right part `r` will be empty.
+ `m:p++drop 1r` prepends `m` to the split parts. If `r` is nonempty, then it must start with `m+1`, which is removed by `drop 1`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 11 bytes
```
‘Ṭ€+\I>0FS¬
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4yHO9c8alqjHeNpZ@AWfGjN/8PtQO7//9HRBrE6XNEGOgqGMFpHwUhHwVhHwQQqAEGGMGQEQyAlOgqmOgpmOgrmOgoWOgqWQJUophiAVRliETOAaYYYagaWMgdLGYHNMoYbxxUNM8AIYRaao5CE4e6HMEzApCm65@BsQ4Sbkc1E@DI2FgA "Jelly – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), 42 bytes
```
O$#`(.)(?<=(\1.*?)*)
$#2
.
$*1,
^(,|1\1)+$
```
[Try it online!](https://tio.run/##LYwxDsIwDEV3X6NBckIV@TtJWyRQR0YuUKEyMLAwIEbuHhyKZOt/@cnvdX8/nre64/NaL65bOXqejydeEMPsgyfXKUVyAT1duf9ggd@7WoUENpoyiQgAVetlGKdDQyoJW0guwKBj0ikZsqvi/9LSDNCs5eeyhWyw6b4 "Retina – Try It Online")
### Explanation
```
O$#`(.)(?<=(\1.*?)*)
$#2
```
This sorts the digits, stably, by how often that same digit has occurred before. In effect, this collates the various candidate subsequences together. The resulting string will first have the first occurrence of each digit, and then the second occurrence of each digit and so on. In a stackable input, the result will look something like `0123...0123...0123...`, where each of these substrings may terminate at any point.
It's easiest to determine whether the input has this kind of pattern in unary.
```
.
$*1,
```
We replace each digit **n** by **n** `1`s, followed by a comma to separate individual digits.
```
^(,|1\1)+$
```
Finally we make use of a forward reference to match consecutively increasing runs of digits. We try to match the entire string either by matching a single comma (representing a **0**, which starts a new run) or by matching the previous thing preceded by an additional `1`, which only works if the current digit is the successor of the previous one.
[Answer]
# C (gcc), 74 73 bytes
```
f(int*l){int s[10]={},r=1;for(;~*l;s[*l++]++)r*=!*l||s[*l-1]--;return r;}
```
Requires the input array to mark the end with -1. Example usage:
```
int main(int argc, char** argv) {
int a[] = {0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1};
printf("%d\n", f(a));
return 0;
}
```
[Answer]
# JavaScript (ES6), 39 bytes
*-1 thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
```
a=>a.every(k=>a[a[~k]=-~a[~k],-k]--|!k)
```
[Try it online!](https://tio.run/##fVDLDoIwELz7F3KCZEvKW2Pw6Bd4qz00WF8QagBJSAy/jqVI1FjIpt1mZjqbnRurWZkU13uFcnHk3SnuWLxlNq950ZipfBJG2pTGqFUdUEoRei5Tq0tEXoqM25k4mwbZF4/q0lDD2iy@iZNJMLWsPwwcPQoueOBrub4cVa4qqYMAQohgBWvAk35YKp1ZFiun3jmUSCQRV3p6o@vPR@OQkx3LSu2q@jHuxPjPQlP8EEd/@/IEM5EN3ZmIYZz0Dk5quhc "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~61~~ ~~45~~ 40 bytes
Takes input as a list.
```
a=>a.every(k=>a[~k]=!k|a[-k]--&&-~a[~k])
```
[Try it online!](https://tio.run/##fVDLDoIwELz7F3IgkGxJy1Nj8OgXeKscGgQfEGoASUgMv46lSNRYzKaPzMzOZufKGlbF5eVWo4Ifkz4NexZumZU0SdkamfjSLovCZfZgFGURQrqOOomZfcyLiueJlfOTodF9ea/PbaSZm8UnkRoUR6b5gwFRo2CDA66SG4rIsmUJHXjgQwArWAOe9cNCSf6yWDoNzr5AAoHYwtOZXL8atUNBdyyvlKuqx9gz498LzfFjHMPtiuP9iWx8yUwM06RXcELTPwE "JavaScript (Node.js) – Try It Online")
## How?
For each value ***0...9***, we keep track of the number of available stacks with the preceding card atop. These counters are stored in ***a[-9]*** to ***a[0]***, where ***a[]*** is the original input array. The only counter that collides with the input data is ***a[0]***, but we don't really care about this one because 1) cards labeled ***0*** are always allowed and have to be processed separately anyway and 2) the input value ***a[0]*** is processed before it has a chance to be updated.
```
a => a.every(k => // given the input array a, for each card k in a:
a[~k] = // the card is valid if:
!k | // - it's a 0 or
a[-k]-- && // - there's at least one stack with the card k-1 atop
-~a[~k] // in which case we allow a new card k+1 and go on with the next card
) // otherwise, every() fails immediately
```
[Answer]
# TI-Basic (83 series), 25 bytes (49 characters)
```
:min(seq(min(cumSum(Ans=I)≤cumSum(Ans=I-1)),I,1,9
```
## How it works
Takes input as a list in `Ans`. Outputs `1` for stackable inputs, `0` otherwise.
For each `I`, `cumSum(Ans=I)` computes a list of the number of times `I` has occurred in each initial segment, so `min(cumSum(Ans=I)≤cumSum(Ans=I-1))` is only 1 if, at every position, we've seen `I-1` at least as many times as `I`. The overall expression is `1` whenever this holds for each `I`.
[Answer]
# Nim, 133 bytes
```
proc s(d:seq[int]):int=
var
t= @[0]
r=1
for c in d:(t.add(0);var f=0;for i,s in t.pairs:(if s==c:(t[i]=c+1;f=1;break));r*=f)
r
```
`1` if it works; `0` if it doesn't.
Had to pull some funky business to deal with mutability of variables in for-loops, oh well.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
0*GQ"@yQy=f1)(]a
```
Input is an array of numbers.
The code outputs `1` in STDOUT if input is stackable, or exits with an error and empty output in STDOUT if input is not stackable.
[**Try it online!**](https://tio.run/##y00syfn/30DLPVDJoTKw0jbNUFMjNvH//2gDHQVDHQUjHQUgwxhMmugomIIFgcgMLGUOlgIyLMAMS6CyWAA "MATL – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 110 bytes
```
+`0((.*?)1((.*?)2((.*?)3((.*?)4((.*?)5((.*?)6((.*?)7((.*?)8((.*?)9)?)?)?)?)?)?)?)?)?
$2$4$6$8$10$12$14$16$+
^$
```
[Try it online!](https://tio.run/##Xcy9DsIwDATgPc9hpJRKyHf5aTp15C1QGRhYGBDvH5yaCcXRF/mUez8@z9e9n@J17/OuMV7O2wSHTnKyU5zqLE5z1mn7P0EoWao0gQooyIIqc7hJ7xoUNkw5qCoA0t6lLm0dETXB0VyAyiWxJYtsS/y@DK0BzCxHl12oh6PuCw "Retina – Try It Online") Link includes test cases. I don't often get to use `$16`...
[Answer]
# Mathematica, 80 bytes
```
Catch[Fold[#~Join~{-1}/.{{p___,#2-1,q___}:>{p,#2,q},-1:>Throw[1<0]}&,{},#];1>0]&
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~69~~ ~~61~~ ~~55~~ ~~47~~ 46 bytes
```
s=[]
for c in input():s+=-1,;s[s.index(c-1)]=c
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9g2OpYrLb9IIVkhMw@ICkpLNDStirVtdQ11rIuji/Uy81JSKzSSdQ01Y22T//@PNtBRMNRRMNJRADKMwaSJjoIpWBCIzMBS5mApIMMCzLAEKosFAA "Python 2 – Try It Online")
Output is `error`/ `no error`.
[Answer]
# [R](https://www.r-project.org/), 88 bytes
```
function(d){s={}
for(e in d)if(!e)s=c(s,0)else{k=match(e,s+1)
if(is.na(k))T=F
s[k]=e}
T}
```
[Try it online!](https://tio.run/##NYq7CsMwDAB3f4W6SdQNSR9btOYLspUOwZGpcetAlE7G3@6GQuE4bri1euhP1X@S28KScKasnIvxy4oCIcFMweNBSNmh2pbkpZIjv6fNPVGsHjsy@xG0SRNGopEHo/f4YClmLNWjw9bCTmfhbOHyj@vPN6L6BQ "R – Try It Online")
Function that takes an R vector; returns `TRUE` for stackable and `FALSE` for unstackable.
Explanation:
```
function(d){
s <- {} # initialize the stacks as empty
for(e in d){ # iterate over the deck
if(!e) # if e is zero
s <- c(s,0) # start a new stack
else { # otherwise
k <- match(e,s+1) # find where e should go in s, NA if not there
if(is.na(k)) # if no match (unstackable)
T <- F # set T to F (False)
s[k] <- e # set s[k] to e
}
T # return the value of T, which is TRUE by default and only gets changed in the loop to F.
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ċṪƊƤ⁺⁼
```
[Try it online!](https://tio.run/##y0rNyan8//9I98Odq451HVvyqHHXo8Y9/x/u3Gf9qGGOgq6dwqOGudaH27ke7t5ydFLYo6Y1h9uBROT//0pKStEGsVzRBjoKhlBKR8FIR8FYR8EEwocgQxgygiGQCh0FUx0FMx0Fcx0FCx0FS6BKZDMMwIoMMYUMYFohRpqBpczBUkZgk4zhhkF1G8HNQXMOQhTubgjDBEyaovkJzjaEuxXZQITnYoEBAwA "Jelly – Try It Online")
A monadic link taking a list of integers and returning 1 for stackable and 0 for not. Based on [my answer to @WheatWizard’s near-duplicate puzzle](https://codegolf.stackexchange.com/a/268548/42248).
[Answer]
# [Haskell](https://www.haskell.org), 53 bytes
```
(a:b)#x=sum[1|i<-x,a==i]:b#(a:x)
y#x=y
f x=x#[]#[]==x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN001Eq2SNJUrbItLc6MNazJtdCt0Em1tM2OtkpSBUhWaXJVAyUquNIUK2wrl6FggsrWtgGi-xXgkNzEzT8FWISWfS0GhoCgzr0RBRSFNIdogFo2vo2CIRUhHwUhHwVhHwQRTDoIMYcgIhkCqdRRMdRTMdBTMdRQsdBQsgSpxmW0A1oDTaoi0AcxIiFVmYClzsJQR2AZjmCUgY0pLgkuKfPIUlHR1dZW4UA3GYpERVuvRfIddBTx4IAwTMGmKJxjhbEOsQYJsKSI8Y7kgkQlLEQA)
Inches out [the former best Haskell answer](https://codegolf.stackexchange.com/a/144214/56656) by implementing an algorithm from [my challenge](https://codegolf.stackexchange.com/questions/268543/is-it-stuck-in-a-counting-loop) which turned out to be a duplicate of this.
We implement a function `(#[])` which replaces each value in a list with the number of times that value has already occurred.
If applying this function twice to a list gives back the original list it is stackable.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 5 bytes
```
Oᵐ{x=
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fsv9H26dUF1hu6Q4KbkYKrbgFqNYtEEsV7SBjoIhlNJRMNJRMNZRMIHwIcgQhoxgCKRCR8FUR8FMR8FcR8FCR8ESqBLZDAOwIkNMIQOYVoiRZmApc7CUEdgkY7hhUN1GcHPQnIMQhbsbwjABk6ZofoKzDeFuRTYQ4blYSPgAAA)
```
Oᵐ{x=
O Find a set partition such that:
ᵐ{ For each part:
x= The part is equal to [0,...,length(part)-1]
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~77~~ 75 bytes
```
import Data.List
g[]=1<3
g(x:r)|s<-r\\[x-1]=g r&&(x<1||s/=r&&g s)
g.reverse
```
[Try it online!](https://tio.run/##bU/LasMwELzrK4YcjA2KY9lO0wbr1mN66lHRQRBHNYkfSGrxwf/uGqXqi8CwO8zu7ONN2Ut9vc5z0w69cXhWTqWHxjqiheSsKoiOx71JJlutzfEoxjWTXMNEUTxWbJrshi9cwybkzHVq6o/a2HpuVdOB49QTtGp4QTyYpnNIcU4gRCYpREbBQqbIKQqK8ku4gQXkAcUfQ@Y97I62xJJiG/wPvrTzpYU8evK0tElJMLy7V2cOHVaru8eG@fnPqn/n/ZK/P7mR0setlPMn "Haskell – Try It Online") Usage: `g.reverse $ [0,1,2]`. Returns `True` for stackable inputs and `False` otherwise.
This is a recursive solution which traverses a given list from back to front. It implements the observation that
* the empty list is stackable.
* a non-empty list with prefix `r` and last element `x` is stackable if `r` is stackable and either `x` is zero or both `x-1` appears in `r` and `r` with `x-1` removed is also stackable.
[Answer]
# C, 248 bytes
Note: To print return status, type "echo $status" into the terminal
Return status 0: Not stackable
Return status 1: Stackable
Explanation: Increments array element with the index equivalent to the current-most digit in the stack. Then, the program checks if this just-now-incremented array element is larger than the element preceding it. If so, returns 0. Else if program makes it to the end of the array returns 1.
```
main(int argc, char ** argv)
{
static int stack[10];
while ( *++argv != 0x0 )
{
stack[**argv - 0x30]++;
if ( **argv - 0x30 > 0 )
{
if ( stack[**argv - 0x30] > stack[**argv - 0x30 - 1] )
{
return 0;
}
}
}
return 1;
}
```
[Answer]
# Java 8, ~~168~~ ~~150~~ ~~142~~ 136 bytes
```
a->{int x[]=new int[a.length],s=0,i;A:for(int n:a){if(n<1)s++;else{for(i=s;i-->0;)if(x[i]==n-1){x[i]=n;continue A;}return 0;}}return 1;}
```
-6 bytes thanks to *@ceilingcat*.
Returns `0`/`1` whether it is correctly stackable or not.
**Explanation:**
[Try it here.](https://tio.run/##pVLLboMwELznK/YIikFAXm1cIuUDmkuOiINLnNQpWRA2aSrkb6dgShr1FFJptVp7dsczto/szJws53jcfdRJyqSEVyawGgEIVLzYs4TDpl2aDUisJkcxMJs2e3rUJKmYEglsACGEmjmrqm28RHGI/LMdipibcjyo95jI0COCrpf7rGiJAJfMrsTewhffluMx5anklQFDSYXjrDxqN/AlEnEYouPblSmRJhkqgSWHNdUFV2WB4FHdlz7VNW215eVb2mj7kXjOxA5OjT1rqwqBB@Oj87b9koqf3KxUbt5AKkUL3cTqHcQVeKBtY/quZgL@0H4CAYEJgenAwS78PoI@WioCMwJzAgsCTwSeyXAXhsozbP4/Zr1eTCdybqCFgQKjbXIr784zhgoKhnv4c7kPjF/ftSumJs8e/RzX2h/@lrdefn9JT6JHuv4G)
```
a->{ // Method with integer-array parameter & integer return-type
int x[]=new int[a.length],// Array for the stacks, (max) size equal to input-size
s=0, // Amount of stacks, starting at 0
i; // Index integer
a:for(int n:a){ // Loop A over the input
if(n<1) // If the current item is a zero:
s++; // Increase amount of stacks `s` by 1
else{ // Else:
for(i=s;i-->0;) // Inner loop (2) over the stacks
if(x[i]==n-1){ // If a top item of a stack equals the current item - 1:
x[i]=n; // Set this item in the stacks-array
continue A;} // And go to the next iteration of loop A
return 0;}} // If we haven't encountered a `continue`, return 0
return 1;} // Return 1 if we were able to correctly stack everything
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
‘Ṭ€+\I’Ȧ
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4yHO9c8alqjHeP5qGHmiWX/D7cfnfRw5wzNyP//o6MNYnW4og10FAxhtI6CkY6CsY6CCVQAggxhyAiGQEp0FEx1FMx0FMx1FCx0FCyBKlFMMQCrMsQiZgDTDDHUDCxlDpYyAptlDDeOKxpmgBHCLDRHIQnD3Q9hmIBJU3TPwdmGCDcjm4nwZWwsAA "Jelly – Try It Online")
Essentially a port of [my other answer](https://codegolf.stackexchange.com/a/231388/66833), but with `‘` to handle zero-indexing
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œp@ŒQẎµ0rṀ⁼Qµ¿Ẹ
```
A monadic link taking a list of non-negative integers and returning `0` if stackable or `1` if non-stackable.
**[Try it online!](https://tio.run/##y0rNyan8///o5AKHo5MCH@7qO7TVoOjhzoZHjXsCD209tP/hrh3///@PNtBRACJDHQUjHQVjGMMETJrGAgA "Jelly – Try It Online")**
### How?
```
œp@ŒQẎµ0rṀ⁼Qµ¿Ẹ - Link: list
¿ - while loop:
µ µ - ...condition chain:
0 - literal zero
Ṁ - maximum of current list
r - inclusive range = [0,1,2,...,max(list)]
Q - de-duplicate list (unique values in order of appearance)
⁼ - equal?
- ...do:
ŒQ - distinct sieve (1s at first occurrences 0s elsewhere)
@ - use swapped arguments:
œp - partition (the list) at truthy values (of the distinct sieve)
Ẏ - tighten (makes the list flat again ready for the next loop)
Ẹ - any truthy? 1 if the resulting list has any non-zero integers remaining
- - effectively isNotEmpty for our purposes since a list of only
- zeros gets reduced to an empty list via the loop.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 bytes
```
£=k_¥T©°T}T=0ÃUd
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=oz1rX6VUqbBUfVQ9MMNVZA==&input=WzAsIDEsIDIsIDAsIDMsIDAsIDQsIDUsIDEsIDEsIDYsIDIsIDcsIDMsIDIsIDgsIDMsIDksIDBd) Outputs `false` for stackable, `true` for non-stackable.
### Explanation
```
£ = k_ ¥ T© ° T}T=0Ã Ud
UmX{U=UkZ{Z==T&&++T}T=0} Ud Ungolfed
Implicit: U = input array
UmX{ } For each item X in the array:
T=0 Set T to 0.
UkZ{ } Remove the items Z where
Z==T&&++T Z == T (and if so, increment T).
This has the effect of removing the largest stack.
U= Reset U to the result.
This process is repeated U.length times, which is
evidently enough to handle any U.
Ud Return whether there are any truthy items in U.
Any items not part of a stack are non-zero/truthy,
so this works for every possible case.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηε[DõQ#ZƒDNåiNõ.;Dëˆ#]¯OĀ
```
The challenge doesn't look all that difficult, but it's quite hard in 05AB1E (for me at least..)
Outputs `0` if stackable, and `1` if not stackable.
[Try it online](https://tio.run/##ATcAyP8wNWFiMWX//863zrVbRMO1USNaxpJETsOlaU7DtS47RMOry4YjXcKvT8SA//8wMDEyMzEyNDI1) or [verify all test cases](https://tio.run/##MzBNTDJM/W9o5ObpYq@k8KhtkoKS/f9z289tjXY5vDVQOerYJBe/w0sz/Q5v1bN2Obz6dJtyLRAcWu9/pOG/zqEt/w24DAyByMjYhMvAwMDQ0NDICMg2NTO3sARJGRkYG0IoAxNTQ0MzI3NjIwtjkBRYMVAOpNfQyMTIFGwKEBtCJUEGcQEVGBkCAA).
**Explanation:**
```
η # Prefixes of the (implicit) input
# i.e. '012031' → ['0','01','012','0120','01203','012031']
# i.e. `021` → ['0','02','021']
ε # Map each to:
[ # Start an infinite inner loop
D # Duplicate the current value
õQ# # If it's an empty String, stop the infinite loop
Z # Get the maximum (without popping)
# i.e. '01203' → 3
# i.e. '02' → 2
ƒ # Inner loop `N` in the range [0,max]
D # Duplicate the current value
Nåi # If it contains the current digit `N`
# i.e. '01203' and 1 → 1 (truthy)
# i.e. '02' and 1 → 0 (falsey)
Nõ.; # Remove the first one (by replacing the first `N` with an empty string)
# i.e. '1203' and 1 → '203'
D # And duplicate it again for the next iteration of the inner loop
ë # Else (does not contain the digit `N`):
ˆ # Push `N` to the global stack
# # And break the infinite loop
] # Close the if-else, inner loop, infinite loop, and mapping (short for `}}}}`)
¯ # Push the global stack
O # Take the sum
# i.e. [] → 0
# i.e. ['2'] → 2
Ā # And get the trutified value of that (which we implicitly output as result)
# i.e. 0 → 0
# i.e. 2 → 1
```
[Answer]
# Java 8, 87 bytes
Instead of building the stacks I just calculate if an element is unstackable on the previous elements, and return 0 when an unstackable element is encountered. If I reach the end, the entire string is stackable and 1 is returned:
```
s->{int l[]=new int[10];for(int n:s)if(n!=0&&l[n]>=l[n-1]||l[n]++<0)return 0;return 1;}
```
[Try it online!](https://tio.run/##pVI9b8IwEN3zK64LSoSJ7PDV1oSxUodOjJEHNyTI1DhR4lAhyG9PnUAAdcNYJ@t85/func9bvuejLE/Udv3TiF2eFRq2JuZXWkg/rVSsRab8j4tDnVjysoQvLtTRASg11yKGPr0QSkcMfSqdbJJiCTF1wIG8@pbm0uXuPhNr2Bm8u9KFUJuIAfdaLoghhKYcLY@GBWTEQpX8QstIMKNpVrhtXL2Xnkhd9RLiwUBGii1Ds48IO53a03C4wF6R6KpQgOnFIbRuqNNKMWt1KHWy87NK@7mpr6VyY5/nuTy4fT12BAy159FHAAiIDQZBgGCMYGIBPhvpLeitpUMwRTBDMEfwiuAN2XXU0eGOkTyJx72os9hZl5p3qaDTOL6X@UAdG2GBXT//HtyS4jrzszPp9ukzn@fqE7s53/d1@0U9Ue3UzR8 "Java (OpenJDK 8) – Try It Online")
**Explanation:**
```
s->{
int l[]=new int[10]; # initialise the counts of each digit encountered prefix of element, all initialised to 0
for(int n:s) # Iterate over all entries in input
if(n!=0&&l[n]>=l[n-1]||++l[n]<0) # Check if the element is stackable on the previous elements. Last check is always evaluated and false, but the sideeffect is to add the element to the handled, prefixed element og the next element.
return 0; # Unstackable
return 1; # No unstackable elements, so the result is stackable
}
```
[Answer]
# J, 25 23 bytes
```
{{(-:\:~"1)+/\y=/i.10}}
```
-2 bytes thanks to Bubbler
Note: No TIO for this version as it relies on newer J feater called direct definition `{{...}}`
[Working 24 byte TIO link](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600dK1irOqUDDWjrbT1Y2Jt9TP1HAwN/mty@TnpKaBLaxjq1CmrGWgqaXOlJmfkK6QBjUKwDFHYRgrGCiZIIgZgUUOwjBFU1lTBTMFcwULBEs0cIyBpjGEeSMwArAtkihlQxBwoYgTUbwwxAaJc3S0xp7hSnQumGdkYIxQewkmoohDHg0gTIDbF8BaENkRxNMwsmOf@AwA "J – Try It Online")
Just a port of [caird's great answer](https://codegolf.stackexchange.com/a/231388/15469) to make sure I understood it.
[Answer]
# [Uiua](https://www.uiua.org), 75 bytes
```
=0⋅⋅⋅⧻⍢⍜▽⍜⊢(□⊐⊂:)(((⊙⊙⊙⊙(⊂1)|∘).⊙⊙⊙◌⊃∊≡=:≡⊢,,⊙(-1.⊃⋅⊢↘1)|..0)=0⧻,)▽:□[¯1]⧻.
```
[Test pad](https://uiua.org/pad?src=0_8_0__RiDihpAgPTDii4Xii4Xii4Xip7vijaLijZzilr3ijZziiqIo4pah4oqQ4oqCOikoKCjiipniipniipniipko4oqCMSl84oiYKS7iipniipniipnil4ziioPiiIriiaE9OuKJoeKKoiws4oqZKC0xLuKKg-KLheKKouKGmDEpfC4uMCk9MOKnuywp4pa9OuKWoVvCrzFd4qe7LgojIFRydXRoeQpGIFswXQpGIOKHoTIgIyAwXzEKRiDih6E1ICMgMF8xXzJfM180CkYgMF8wXzBfMV8xXzFfMl8yXzJfM180XzVfNl83XzhfOV8wCkYgMF8xXzJfMF8zXzEKRiAwXzFfMl8wXzNfMF80XzVfMV8xXzZfMl83XzNfMl84XzNfOV8wCiMgRmFsc3kKRiBbMV0KRiAwXzJfMQpGIOKWvTNfNCDih6EyICMgMF8wXzBfMV8xXzFfMQpGIDBfMF8xXzJfM18xXzJfNF8yXzUKRiAwXzFfMl8zXzBfMV8yXzFfMApGIOKWvTNfMl8zXzEg4oehNCAjIDBfMF8wXzFfMV8yXzJfMl8zCg==)
] |
[Question]
[
# The Problem:
You receive a (section of) a Conway's Game of Life grid. Your task is to output whether it represents a still-life (subsequent generations are identical to the current grid), a oscillator of period up to 4 (every nth generation is identical to the current grid), or something else.
The remainder of the infinite grid consists of dead cells.
## Rules of the Game of Life
If a dead cell is next to exactly three living cells, it becomes alive. Otherwise, it remains dead. If a living cell is next to 2 or 3 living cells, it stays alive. Otherwise, it dies.
## Input/Output formats
Input and output can be by any reasonable method - list of locations of living cells, array of bools, one or more strings, etc. You cannot assume that dead cells are stripped from the edge of the input grid. Outputs must be any three consistent values ([still-life: 0, oscillator: 1, other: 2], for instance).
For oscillators of period 5 or greater, output of "Oscillator" or "Other" are both acceptable.
## Examples
(1 is living, 0 is dead)
```
INPUT OUTPUT
0 0 0 0
0 1 1 0 Still-Life
0 1 1 0
0 0 0 0
INPUT OUTPUT
1 1
1 0 Other
INPUT OUTPUT
0 0 0 1 1 0
0 0 0 1 0 1 Still-Life
0 0 0 0 1 0
INPUT OUTPUT
0 1 0
0 0 1 Other
0 1 0
INPUT OUTPUT
0 1
0 1 Oscillator (period 2)
0 1
INPUT OUTPUT
1 1 0 0
1 1 0 0 Oscillator (period 2)
0 0 1 1
0 0 1 1
INPUT OUTPUT
0 1 1 0 0 0 0 0
0 0 0 1 0 0 0 0 Oscillator (period 3)
1 0 0 0 0 0 0 0
1 0 0 0 1 0 0 0
1 0 0 0 1 1 1 1
0 0 1 0 0 0 0 0
INPUT OUTPUT
1 1 0 0 0 1 1
0 1 0 1 0 1 0
0 1 1 0 1 1 0 Oscillator (period 4)
0 1 0 1 0 1 0
1 1 0 0 0 1 1
INPUT OUTPUT
1 1 1
1 0 0 Other (This is a glider - the same shape will repeat, but it will be shifted)
0 1 0
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")- the shortest answer in each language wins.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~61 56 48 40 37 36 35 33~~ 32 bytes
```
6∧+/w∘≢¨⊢∘⌂life\5/⊆w←0,∘⌽∘⍉⍣16⊢⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97b/Zo47l2vrljzpmPOpcdGjFo65FIGZPU05mWmqMqf6jrrbyR20TDHTAontBZG/no97FhmYglX1TQYb8T@MyUTB51LvFQAEGDYEQmQZDLqB6oFnq6lxpXEYKRkANhhAFyBLGCmZwk5B1G0IxnIeqyRisyRBVMaoSI4gSZEGIs7E5FkkMWYOZggVQA7rHkGxFZ6HyMWlDJJuwBpSpgjnIRkMUPQYoGCFmiBJUhijuRPMJJMiQHQAJMi4A "APL (Dyalog Extended) – Try It Online")
Outputs 0 for still-life, 6 for oscillators, and 12 for other.
Expects a binary matrix.
-5 bytes from ovs using a train for the left-most dfn.
-8 bytes from user by omitting `traj` and using `⍣` instead.
-8 more bytes from user.
-3 bytes simplifying user's idea.
-1 more byte from user(how did they do it?!).
-2 more bytes, converting to a full program.
-1 more more byte from user.
## Explanation
```
6∧+/w∘≡¨⊢∘⌂life\5/⊆w←0,∘⌽∘⍉⍣16⊢⎕
⍣16⊢⎕ apply the following to the input 16 times:
0,∘⌽∘⍉ rotate 90 degrees and prepend a column of zeroes
w← store padded input in w
5/⊆ copy it 5 times
⊢∘⌂life\ scan using life function
w∘≡¨ check which ones match w
+/ sum to get number of truthies
6∧ lcm(6,truthies)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~42~~ ~~38~~ ~~31~~ 29 bytes
*2 bytes saved thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!*
```
4thYaXJ4:"3Y6QZ+5:7mtJX=w]xvu
```
Input is a binary matrix. Output is
* Still life: `1`
* Oscillator: `0` *newline*`1`
* Other: `0`.
[Try it online!](https://tio.run/##y00syfn/36QkIzIxwsvESsk40iwwStvUyjy3xCvCtjy2oqz0//9oAwUwtAYShkCIygDDWAA) Or [verify all test cases](https://tio.run/##y00syfmf8N@kJCMyMcLLxErJONIsMErb1Mo8t8QrwrY8tqKs9L@6rq56hEvI/2gDBTC0BhKGQIjKAMNYrmiggDVIDMiECKKoMARhuHK4OrgKQ2tkUWu4CMRgiO1wBtR0OANqlCHceBRrDWC6DZAhQsAQU8AQ2XgDJE8aILxvgHAxVLkhIpAMYgE).
### Explanation
```
4th % Push 4, duplicate, concatenate horizontally. Gives [4 4]
Ya % Implicit input. Padarray. Adds a 2D frame of width 4. This is the
% initial grid state. The padding ensures that results will be correct
% for 4 iterations even if only this finite region is considered
XJ % Copy that into clipboard J
4:" % Push 4, range, for each (this loop runs for 4 iterations)
3Y6 % Push [1 1 1; 1 0 1; 1 1 1] (Moore neighbourhood)
Q % Add 1, element-wise. Gives [2 2 2; 2 1 2; 2 2 2]
Z+ % 2D convolution, maintaining size. Newly active cells correspond to
% values 5 = 1+2*2 (active cell with 2 active neighbours), 6 = 0+2*3
% (inactive cell with 3 active neighours) or 7 = 1+2*3 (active cell
% with 3 active neighours)
5:7 % Push range from 5 to 7, that is, [5 6 7]
m % Ismember. This gives the new grid state
tJX= % Duplicate. Push copy of initial state. Are both arrays equal? Gives
% true (1) or false (0) (*)
w % Swap. This moves the latest grid state to top, for the next iteration
] % End
x % Delete last grid state. The stack contains the results of (*) for each
% iteration
v % Concatenate stack contents vertically. Gives a column vector containing
% true (1) or false (0). The only possibilities are: [1; 1; 1; 1]
% (still life), [0; 1; 0; 1] (period 2), [0; 0; 1; 0] (period 3),
% [0; 0; 0; 1] (period 4) and [0; 0; 0; 0] (other)
u % Unique: removes duplicates, maintaining order. Gives 1, [0; 1] or 0
% Implicit display
```
[Answer]
# JavaScript (ES6), 191 bytes
Expects a binary matrix. Returns `false` for *still-life*, `true` for *oscillator* or `0` for *other*.
```
m=>(M=m=(h=a=>[v,v,v,v,...a,v,v,v,v])(v=m.map(h,v=0),v=v.map(_=>0)),g=k=>(m=m.map((r,y)=>r.map((v,x)=>m.reduce(n=>d?n>>(m[~-(y+--d/3)]||[])[x+d%3-1]:n,v*16+8,d=9)&1)))+''!=M?k&&g(k-1):k<4)(4)
```
[Try it online!](https://tio.run/##lZLbboJAEIbveQp6Udwpu7gbTdOaDr5ATS96SUhDAA/lZIBuNDF9dbpFbBHRaCZL9t/MfPsPs5@e9Ao/X61LlmZBWM2xStAmM0yQLNFD25F0H5Zlec1WukAkJlbircmSSuSgPrKWH2hzALrASFGSJofkdAto53sh6UaJxMrD4MsPSYp2ME1tle18M7I1GQuGI3B3O8cFZ2MG9yMm3ElK5YN4NJ9ogM9gCAAwB4M7nE0jw1iQiAmYRC9jIGOo/Cwtsji04mxB5sTRh0P9vVzFMXtdzUNN1x2d0zp0lzZSqDgvm2TNBdC0HvpbuQzzOlcVHsrExZJeQz3Xit/VcULFlW54lyfaLV5kFL7y55XZH6hVebS9FlH39u@mI5vuT@QNBvfA7mAP/5AfX87b0T0W547FqccW5BavvDOIK6fSfmdHL62XUf0A "JavaScript (Node.js) – Try It Online")
### Commented
The helper function `h` expands an array `a[]` with 4 leading and 4 trailing values `v`:
```
h = a => [v, v, v, v, ...a, v, v, v, v]
```
We use it to expand the original matrix horizontally and vertically. A copy of the updated matrix is saved in `M`:
```
M = m = h(v = m.map(h, v = 0), v = v.map(_ => 0))
```
We then invoke the main recursive function `g` with `k = 4`:
```
g = k => // k = counter
( m = // update m[]:
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each value v at position x in r[]:
m.reduce(n => // for each entry in m[]:
d ? // if d is not equal to 0:
n >> ( // right-shift n if the cell at:
m[~-(y + --d / 3)] // Y = floor(y + --d / 3) - 1
|| [] //
)[x + d % 3 - 1] // X = x + (d mod 3) - 1
// is set
: // else:
n, // leave n unchanged
v * 16 + 8, // starting with n = v * 16 + 8
// (0b1000 if v = 0, or 0b11000 if v = 1)
d = 9 // and d = 9
) // end of reduce()
& 1 // isolate the least significant bit
) // end of inner map()
) // end of outer map()
) + '' != M ? // coerce m[] to a string; if it's not equal to M[]:
k && g(k - 1) // unless k = 0, do a recursive call with k - 1
: // else:
k < 4 // test whether there was at least 2 iterations
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~31~~ ~~27~~ 26 bytes
```
(6∧⌂life⍣(1…4)⍳⊂)(⌽0,⍉)⍣16
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/9OApIbZo47lj3qacjLTUh/1LtYwfNSwzETzUe/mR11NmhqPevYa6Dzq7QQKLDY0@/8/TcFEweRR7xYDBRg0BEJkGgy5gHYAzVZX50pTMFIwAmowhChAljBWMIObhKzbEIrhPFRNxmBNhqiKUZUYQZQgC0Kcjc2xSGLIGswULIAa0D2GZCs6C5WPSRsi2YQ1oEwVzEE2GqLoMUDBCDFDlKAyRHEnmk8gQYbsALAGAA "APL (Dyalog Extended) – Try It Online")
APL has emerged victorious [again](https://codegolf.stackexchange.com/questions/216087/is-it-a-still-life/216575#comment504831_216096). My work here is finally done; now I can rest.
This borrows heavily from Razetime's [answer](https://codegolf.stackexchange.com/a/216096/95792), but I thought it was sufficiently different as to merit its own answer. Also, I wanted to get some rep from this :) **@ngn** also helped on this new train version.
Returns 0 for still-life, 6 for oscillators, and 12 for other. Requires zero-indexing.
`⎕` is niladic and reads from the input.
`(⌽0,⍉)⍣16` pads 4 layers of zeroes on all sides of the input. `⍣`, the power operator, applies `(⌽0,⍉)` 16 times. `0,` adds one row of zeroes, and `⌽⍉` rotates 90 degrees.
`life⍣(1…4)⍳⊂` is a fork. On the right side, `⊂` boxes the padded grid. On the left side, `⌂life⍣(1…4)` makes a range from 1 to 4 (`1…4`) and for every x in that range, it applies the `⌂life` function to the padded matrix x times. Basically, it gives us a vector of the padded matrix over 4 generations. Then, `⍳` finds the index of the padded matrix inside the vector of generations. If it's a still-life, this will be 0, the first element; if it's an oscillator, it will be 1, 2, or 3, and if it's something else, it will be 4 (outside the vector).
`6∧` just bring the different oscillator indices together finding the lcm with 6. Still-life (0) remains 0, oscillator (1,2,3) become 6, and other (4) becomes 12.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ 31 bytes
```
Ż€UZ
Ç⁴¡µÇ4¡+3\Z$⁺_|=3µ4СḊiµ’Ṡ
```
[Try it online!](https://tio.run/##y0rNyan8///o7kdNa0KjuA63P2rccmjhoa2H200OLdQ2jolSedS4K77G1vjQVpPDEw4tfLijK/PQ1kcNMx/uXPAfqLppTeT//9HRBjpgGKsDZBkCIToLIgtkRgPFgJQhlAeRQVVnCMIIXToItQhVhlDz4TIQPpSE2gN1EYIFtQuJBTPXUAdmG6o7DOBmGCBDJBFDLCKGKLYgdKH6ApmGudgQZg6a/9BDCWIqXDXWMIPIIfse4aNYAA "Jelly – Try It Online")
Outputs `0` for still life, `1` for oscillator, and `-1` for other.
```
Ż€UZ Monadic helper link: pad row with zeroes and rotate
Ż€ Prepend a 0 to each row,
U reverse each row,
Z transpose.
Ç⁴¡µÇ4¡+3\Z$⁺_|=3µ4СḊiµ’Ṡ Main link:
Ç⁴¡ Repeat helper 16 times (pad the input four times).
µ µ4С Repeat four times, collecting each result
Ḋ (not including the 0th iteration):
Ç4¡ pad the grid once,
+3\ sum every neighborhood of three elements,
Z transpose,
$⁺ sum and transpose again,
_ subtract the previous grid values,
| bitwise OR with the previous grid values,
=3 is each equal to 3?
i Find the index in the results (or 0 if not found)
Ç4¡µ of the quadruple-padded input,
µ then
’ decrement
Ṡ and take the sign.
```
`µ’` could be `_1`, ~~and `Ż€UZµ4¡` was originally `Ż€UZƊ4¡`~~, but if I'm already using ~~two~~ one `µ`~~s~~ then I may as well use ~~two~~ one more!
`Ç4¡+3\Z$⁺` computes the sum of each Moore neighborhood including the centers, which in the case of a cell which should be alive in the next generation is 3 or 4, but not 4 if the cell is dead, so while `_|` leaves sums for dead cells unchanged, it decrements the sums for alive cells, such that cells which should survive have values 2 or 3, then sets the ones bit so that 2 becomes 3, 3 remains 3, and no other value becomes 3.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes
```
⌊CellularAutomaton["GameOfLife",p=#~ArrayPad~4,4]~Count~p/2⌋&
```
[Try it online!](https://tio.run/##bVBLCsIwEN3nFKLgKmBHuhMhouJGsPvSRdAWC00jJV1IaA@gPWUvUuOn6aTIJGTy5s28xwiurrHgKj3zLll3bfPYxllWZrzYlEqagszD6YGL@JQc0ySe0tt6Vm@Kgt8Dfql96kf1Vpa5qm@LZds8591OhiQo0lwxxsSK7M9XyRImqDaHaO3RT1SUTEwOJv7lX475aG3gDwg98K2O2fC@uJuiBkwFKzeUe8i@vbK1ivOfvJNbIaC9/tidh4Z5OBwM/mIwEhx6sVPHF1B78YJHK3c57hw7GgY3eHmkqqLuBQ "Wolfram Language (Mathematica) – Try It Online")
Returns `2` for still-life, `1` for oscillators, and `0` for other.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
8Fø¾δ.ø}©4FÐ2Fø¾δ.ø}2F€ü3ø}OO·α567såD®Qˆ}¯Ù
```
Inspired by [*@LuisMendo*'s MATL answer](https://codegolf.stackexchange.com/a/216092/52210), just with less convenient builtins.. [matrix](/questions/tagged/matrix "show questions tagged 'matrix'") challenges aren't really 05AB1E's strong suit.
Outputs `[1]` for still-life; `[0,1]` for oscillator; and `[0]` for other.
[Try it online](https://tio.run/##yy9OTMpM/f/fwu3wjkP7zm3RO7yj9tBKEzcXIyQBI7dHTWsO7zEGMv39D20/t9HUzLz48FKXQ@sCT7fVHlp/eOb//9HRBjqGsTpIZCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lotw6Xkn9pCYRvX/nfwu3wjkP7zm3RO7yj9tBKEzcXIyQBI7dHTWsO7zEGMv39D20/t9HUzLz48FKXQ@sCT7fVHlp/eOZ/nUPb7A9t@R8dHW2gA4axOkCWIRCisyCysToK0dFAQaCQIYwLkUNVaQjCCH06SIoRygyhViCkIAJQEmYX1FkIFtQ6JBbcaEMdmI2objGAG2KADJFEDLGIGKJYg9CF7DIktxjqwDEi8FACE1keVT/cSEOYCxCBEwsA).
**Explanation:**
```
# Pad the input with four layers of 0s:
8F # Loop 8 times:
ø # Zip/transpose, swapping rows/columns
# (which uses the implicit input in the first iteration)
δ # Loop over each row:
¾ .ø # And surround it with a leading and trailing 0
}© # After the loop: store the padded input in variable `®` (without popping)
# Now we'll do a Game of Life cycle, four iterations in total:
4F # Loop 4 times:
D # Duplicate the current matrix
2Fø¾δ.ø} # Pad it with a single layer of 0s similar as above
2F # Loop 2 times:
€ # Map over each row:
ü3 # Create overlapping triplets of the current row
ø # Zip/transpose; swapping rows/columns
} # After this loop, we'll have a list of 3x3 blocks
OO # Sum all values in a single 3x3 block together
· # Then double each sum
α # Take the absolute difference (at the same positions) with the current
# matrix we've duplicated earlier
567så # Check for each value in this matrix if it's in the integer 567
# (1 if truthy; 0 if falsey)
D # Duplicate the resulting matrix
®Q # Check if it's equal to matrix `®` (1 if truthy; 0 if falsey)
ˆ # Pop and add this check to the global array
} # After the loop:
# Create the result based on these four iterations:
¯ # Push the global array
Ù # Uniquify it
# (after which the result is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~413~~ \$\cdots\$ ~~375~~ 354 bytes
Saved 13 bytes thanks to [Danis](https://codegolf.stackexchange.com/users/99104/danis)!!!
```
def f(w,t=0,u=[0],R=range):
l=len(w[0])+12;d=len(w);m=[u*l for i in u*6]+[u*6+w[i]+u*6for i in R(d)]+[u*l for i in u*6];n=[u*l for j in m];q=R(-1,2)
while t<6and any(w[r]!=n[r+6][6:-6]for r in R(d)):
for r in R(1,11+d):
for c in R(1,l-1):n[r][c]=sum(m[r+i][c+j]for i in q for j in q)in(3+m[r][c],3)
m=[[*r]for r in n];t+=1
return t>5and 2or t>1
```
[Try it online!](https://tio.run/##bVTbjpswEH3nK6b7gh2cbkxaKiUlX1CpUvrIWqsITEMKJjFG6TbKt29tA8Gg5Tpz5szMsRlxflPHWqzf3zOeQ46uRMUr0sbJipF9LA/iN8cbD8q45AJdNYoDGm6zzsXbKk7aRQl5LaGAQkC7iFigoSi4JgULtPEI7VGGbWxG34qxxsmAFdte4j1aUhJiD67HouSgvkcHkcFBvGkRkn2KRSKDiCXRZhkxkymHFkYtOAgllAaZRS2cDnC5pHijy7AkZXHTVqjSJQvtBSf2EHgZZV1wIdA6qLoMstbaQC8/WchRgGBbFcTUA8lVKwWo3VcjO9RxtaN2i8/XWpYZss9OlW1RFoKbChbvYHOcZSEU8v3Pp1p3b5REKR6XYZIw9hRvVAMxIJuWJCtiT0ZAm3r9H5gdgZE@Q0cMTl2sI81yqLmdEmSW4pDp0HRK6NHh5UoYRDtmL8E1J90oGYTMRK7GYiv3dCH6EUSn/cbEuVJXGSWP29nq6d5PGNMak9L0oWeygdjjf888VTwzX3pFICTQPalzhWTkvaZ1VXGhDN//pYqyXP4ocu4T8H82qXYPqpbWU0cufeylR57@4dLyX9rw25fURI1F1zpsxk4RO6X/ijOyU0dg6NbPcj/eClvPTGU@OKl25tqShnnjnOf@zfxXlPnNPD@Hiyd4ur8sd3Br7oBu6R3DrdeYNHHM2d3H7/8B "Python 3 – Try It Online")
Verbose but it works! :)))
Inputs the grid as a list of lists of \$1\$s and \$0\$s.
Returns `False` if it's a *still-life*, `True` if its an *oscillator*, or \$2\$ if it's an *other*.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 90 bytes
```
≔⁰θ≔⟦⟧ηWS«F⌕Aι1⊞η⟦θκ⟧≦⊕θ»≔ηθF⁴«≔⟦⟧ζF³F³F⊕⌈↔⊖⟦κλ⟧Fθ⊞ζ⊖Eν⁺ξ⎇πλκ≔Φζ∧⁼λ⌕ζκ›²↔⁻⁶№ζκθ⊞υθ»I⌈⟦¹⌕υη
```
[Try it online!](https://tio.run/##VVFNT8MwDD2vv8LayZWC1ALislM1GNqh0iS4VTuELazRsrTNB4whfntx2mwMS1Hs@Pn52dnU3Gwarvq@sFbuNGYMunSWxKhaM6gp/KylEoBL3Xr34ozUO0xT@E4m740BXEi9LZRCyWCaTymx8rbGmkHVMdivqX5S8jZSLvXGiIPQTmzHVj/nZvUYD5T3A/uVilNgGVJ3Kfy7rwix5Ed58Acs3myjvBP4KP6S1Z6BWqfBxsouKj0xuMaRVtQMVspbPDJ4FUZz84UtVdM4oXx2kbaQygkTGAq9xafOc2WRYGEl4ZXgDJ6N4AF1S6izsFJqon9gMG@8dhEabFzCZBDmzxta0codzrl1lxGrPHbx4YvCWLO@z/I8C5bQGbxkjKOTXxyyJEKypL/5UL8 "Charcoal – Try It Online") Link is to verbose version of code. Input is a newline-terminated list of strings and output is `-1` for other, `0` for stable and `1` for oscillator. Explanation:
```
≔⁰θ≔⟦⟧ηWS«F⌕Aι1⊞η⟦θκ⟧≦⊕θ»≔ηθ
```
Input the grid, push the coordinates of all the `1`s to a list, and keep a copy of that list.
```
F⁴«
```
Iterate the game of life 4 times.
```
≔⟦⟧ζF³F³F⊕⌈↔⊖⟦κλ⟧Fθ⊞ζ⊖Eν⁺ξ⎇πλκ
```
Make a new list consisting of all the cells in the original list plus two repetitions for each neighbouring cell.
```
≔Φζ∧⁼λ⌕ζκ›²↔⁻⁶№ζκθ
```
Extract all cells that appear between 5 and 7 times. 5 represents a live cell with 2 neighbours, while 6 and 7 represent cells with 3 neighbours.
```
⊞υθ
```
Save a copy of the new iteration.
```
»I⌈⟦¹⌕υη
```
Print the index of the original position in the list of iterations, limited to 1.
] |
[Question]
[
Given a list of positive integers, output whether every adjacent pair of integers in it shares a prime factor. In other words, output **truthy** if and only if **no** two neighboring integers in the list are co-prime.
In yet other terms: given a list of positive integers **[a1 a2 … an]**, output whether
**gcd(a1, a2) > 1 && gcd(a2, a3) > 1 && … && gcd(an−1, an) > 1.**
The list will always contain at least two elements (n ≥ 2).
## However…
This challenge is also [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'"): the *codepoints* in your answer (whatever codepage it may be in) must satisfy the condition your program checks for.
For example, `print 2` is a valid program. As a list of Unicode codepoints it is **[112 114 105 110 116 32 50]**, which satisfies this condition: **112** and **114** share a factor of **2**; and **114** and **105** share a factor of **3**, etc.
However, `main` can *not* occur in a valid program (sorry!), as the Unicode codepoints of `m` and `a`, namely **109** and **97**, are coprime. (Thankfully, your submission needn’t be a full program!)
Your program isn’t allowed to contain codepoint 0.
## Test cases
Truthy:
```
[6 21] -> 1
[502 230 524 618 996] -> 1
[314 112 938 792 309] -> 1
[666 642 658 642 849 675 910 328 320] -> 1
[922 614 530 660 438 854 861 357 477] -> 1
```
Falsy:
```
[6 7] -> 0
[629 474 502 133 138] -> 0
[420 679 719 475 624] -> 0
[515 850 726 324 764 555 752 888 467] -> 0
[946 423 427 507 899 812 786 576 844] -> 0
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest code in bytes wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
!TM1*Zdl2$Xdl-
```
This outputs a non-empty column vector of nonzero numbers as truthy, or a vector containing at least a zero entry as falsy.
* [Try it online!](https://tio.run/##y00syfn/XzHE11ArKiXHSCUiJUf3//9oSyMjBTNDEwVTYwMFMzMDBRNjCwULUxMFCzNDBWNTcwUTc/NYAA)
* [Verify all test cases](https://tio.run/##XY/BasMwEETv/ooptAQKDdJqtZJOvfTaWw6lIdCA7Vqg2iF2KDn02911oGAqWAmt3syOvo5TmT/wtx5QD9vt9rvLpZnvdq/28b0udP9Wl6f5eUXlttpM58vUXTfL9XQZO4zTOfef1c8Ka8rYVJv2WMaF@wce1mBfVy/rFHk8leO12q16N60ObdAOZ@S@zX2eGpRhOM17AdlDtfeGQM7AE0NsREqiXWcZ1hKSiwiJ4EzSrohAmCA@3s7ICRI8kjVwFLWMUomUUL1XVxEDVo/oGVEsnA/gEBYv3HZKeldWU1jntKJ2mVQZEoJdXj2EeElqvfoYBBKdxAiiOu8RvCaJESyLY2IBk9MK6hoQU0LUn4Qo8EE0Mx/wCw). The footer code contains an `if` branch to test truthyness/falsyness.
* Since MATL uses ASCII, the source code is encoded as
```
[33 84 77 49 42 90 100 108 50 36 88 100 108 45]
```
which [satisfies the requirement](https://tio.run/##y00syfn/XzHE11ArKiXHSCUiJUf3//9oY2MFCxMFc3MFE0sFEyMFSwMFQwMQtlAwNVAwNlOwsIALmJjGAgA).
### Explanation
```
! % Implicit input. Transpose
TM % Push input to latest function again
1* % Multiply by 1 (does nothing, but matches factors)
Zd % Compute gcd with broadcast: matrix of gcd of all pairs
l % Push 1
2$ % The next function will use 2 inputs
Xd % Extract diagonal 1 (i.e. that below the main diagonal) from the matrix
l- % Subtract 1 from each entry. Implicitly display
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~103~~ 100 bytes
EDIT:
* -3 bytes: Used a `d<-fz` guard to merge and shorten the last two lines.
`f` is the main function, which takes a list of integers and returns a `Bool`.
Note that the first two `ԁ`s (only) are Cyrillic (Komi) Unicode characters, and there's a tab character before the first one.
```
f ԁ=zb[ԁ]id
zb[h:p:l]fz=z h p&&zb[p:l]fz
zb l fz=z 0 2
z 0z=z>z^0
z f fz|f<fz=z fz f|d<-fz=z d$f-d
```
[Try it online!](https://tio.run/##LU9tasJAFPxdT7EUEcVEsl9vd0W9iLUQmywJXVNRSyH4xzt6n3ReWgiT2Zn3Znab8vpZpzScyrbbtt2tvpQft@l3l9quvq5O5Xk@f0v57tp8/YgklkvxKvIdAIy1eRRpsVhd6rJarMadIb48H9v@uH8@Dm01AWnW53U6xH7bi0acZzNIfwJMZI5GIdQECLrr3wvQCP0eN6MZ8d2rTT4eqmnMq2HYUyaUPEz2tlBgusiEVSYTJH0mQiA4WuIsJeygIboAposAhwjbZHAm6/@ZNwHMWUxLhGnlGQpMB8WDHGa5hghgONFbaJ4kBq2D5hxno4l/KrDCS3xBqTWDh2MUhzjYTo4zqCRl@CnScihsp4jbse2IIywMZ/mWHr2GuCEYzBilGRzXAHxAoucnOw/XOuKHIfsX "Haskell – Try It Online")
or [test it on itself.](https://tio.run/##y0gszk7Nyfmfm5iZZ5uZV5JalJhcolKckV@ul6aXm1igkFaUn@uaV5r7P43zSqNtVVL0lcbYzBQuICPDqsAqJzatyrZKIUOhQE0NKAQRAEoq5CiAJQwUjLiAJJBpVxVnAGSmAcVr0mzAkmlAVJNiowvmpKik6ab8p4stAA "Haskell – Try It Online")
# How it works
* `f` is the main function. All it does is wrap its argument `ԁ` in a singleton list (because the prime ASCII value of `)` makes parentheses much more awkward to use than square brackets) and call `zb` with that and a dummy argument (the Haskell function `id` happens to have just the right characters to fit here).
+ Getting the same character to fit besides both of `=]` is impossible with plain ASCII, so the argument is named with the 2-byte Unicode character `CYRILLIC SMALL LETTER KOMI DE (ԁ)`, codepoint value `3*7*61=U+0501`, which fits with all of those and `[`.
- Since the codepoint is not even (the smallest option that is a legal identifier and also even uses three bytes), this required using a tab character instead of a space before it.
- A seven bytes longer plain ASCII option is to rename the argument: `f fz|bf<-fz=zb[bf]fz`.
* `zb` takes two arguments, a singleton list whose element is the real list of numbers being recursed on, and a dummy argument `fz` needed only to get a `z` before the function's `=`s.
+ When the inner list has at least two elements, the function `z` is called with the first two (named `h` and `p`), and if that returns `True`, `zb` recurses on the tail `p:l` of the list.
+ If the inner list has fewer than two elements, `zb` returns `True`. Since `=` needs to be followed by the character `z`, the simplest way to do this is to use a call of the `z` function that itself is known to return `True`.
* `z` takes two arguments and recursively calculates their greatest common divisor using subtraction (every other relevant integer division or gcd function is unavailable), returning `True` if it's greater than one.
+ The recursion ends when the first argument is `0`, with the second argument being the gcd. On this line the second argument is also named `z`. The character `1` is awkward here so `z^0` is used to get the number one.
+ Otherwise, if the first argument `f` is smaller than the second `fz`, they are swapped and `z` recurses.
+ Otherwise, the smaller argument is subtracted from the larger, then `z` recurses (also swapping the arguments, although that's just to avoid parentheses.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
### Code
```
ü‚ÒüÃP≠P
```
Uses the [**05AB1E** encoding](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md), which gives us the following list of code points:
```
hex: [0xFC, 0x82, 0xD2, 0xFC, 0xC3, 0x50, 0x16, 0x50]
dec: [252, 130, 210, 252, 195, 80, 22, 80]
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8J5HDbMOTzq853BzwKPOBQH//0ebmZnpKJiZGAEJUwsoy8LEEsgyN9VRsDQ00FEwNrIAEQaxAA "05AB1E – Try It Online") or [Verify the source code!](https://tio.run/##MzBNTDJM/f//8J5HDbMOTzq853BzwKPOBQH//0cbVLg56ygYVFgYgUgXMAkRcTYGkaYGINLQDMKOBQA "05AB1E – Try It Online")
### Explanation
Since the gcd operator (`¿`) has a prime code point I had to look for other ways to check coprimality:
```
ü‚ # Get an array of adjacent pairs of the input
Ò # Factorize both elements of each pair in the array
üà # For each pair, get the intersection of both prime factorization lists
P # Product of each intersection (this leaves 1 when there is no intersection)
≠ # Check for each element whether it does not equal 1
P # Product of the booleans
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
For Truthy inputs it returns a positive integer, for Falsy it returns 0
```
←▼`Ṡt(ż⌋
```
[Try it online!](https://tio.run/##AT8AwP9odXNr///ihpDilrxg4bmgdCjFvOKMi////1s1MTUsODUwLDcyNiwzMjQsNzY0LDU1NSw3NTIsODg4LDQ2N10 "Husk – Try It Online") and [Tested on its own codepoints](https://tio.run/##ATcAyP9odXNr///ihpDilrxg4bmgdCjFvOKMi////1s2LDE4OSw5NiwyMDgsMTE2LDQwLDIzNSwxNDFd)
Uses Husk's [codepage](https://github.com/barbuz/Husk/wiki/Codepage)
```
Source -- [ ← , ▼ , ` , Ṡ , t , ( , ż , ⌋ ]
Hex -- [0x06,0xbd,0x60,0xd0,0x74,0x28,0xeb,0x8d]
Dec -- [6 ,189 ,96 ,208 ,116 ,40 ,235 ,141]
```
### Explanation
```
-- implicit input, e.g [63,36,18,3]
` -- flip the args of the next function
Ṡ -- some combinator (Ṡ f g x = f (g x) x)
t -- tail [36,18,3]
ż -- zipWith (note, keeps trailing elems of longer list) [(63,36),(36,18),(18,3),(3)]
⌋ -- gcd [9,9,3,3]
( -- used just to match restricted source criteria
▼ -- minimum of the list 3
← -- minus 1 2
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~8~~ 7 bytes
```
äj d¹¥Z
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=5GogZLmlWg==&input=WzIyOCwxMDYsMzIsMTAwLDE4NSwxNjUsOTBd)
Code points:
```
Char ä j d ¹ ¥ Z
Hex e4 6a 20 64 b9 a5 5a
Dec 228 106 32 100 185 165 90
```
### Explanation
```
äj d¹ ¥ Z
Uäj d) ==Z
Implicit: U = input array, Z = 0
Uä For each pair of items in the array:
j Return whether the two items are coprime.
d) Return true if any items are truthy, false otherwise.
==Z Return whether this is equal to 0 (false -> true, true -> false).
Implicit: output result of last expression
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes
```
,Pnælð2\P
```
Saved 2 bytes thanks to @[Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
[Try it online!](https://tio.run/##HYwhFgIxDAU9p8gBIppsk6a3WF8qMby@9Wsx3ASF4A69CRcJKeabmfn32xinO@7HfI354evu8/l9vN1bk8QIvCUE4YygZAi1ascLNCFBMAlWWBG2JRSNEQlQJEqz8LOWv58DWdhEMRyUUtBVrY@69NT7Dw)
Jelly has its own [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page) and the codepoints of each character are
```
Chr Hex Dec
, 2c 44
P 50 80
n 6e 110
æ 16 22
l 6c 108
ð 18 24
2 32 50
\ 5c 92
P 50 80
```
This tests for non-coprime numbers by checking if `lcm(a, b) != a*b`. There might be a shorter solution as I just filtered for characters with even codepoints.
## Explanation
```
,Pnælð2\P Input: array A
2\ For each overlapping sublist of size 2
ð Reduce it using this dyad
, Pair
P Product
n Not equals, 1 if true else 0
æl LCM
P Product
```
[Answer]
# TI-BASIC, 38 bytes
```
Input L1:ΔList(cumSum(L1:augment(Ans+V,V+{0:2>sum(AnsL1=lcm(Ans+V,V+L1
```
TI-BASIC is tokenized into one- or two-byte tokens, as listed [here](http://tibasicdev.wikidot.com/tokens).
The trickiest parts of this solution were:
1. The comma token is a prime number (43), forcing me to surround it with multiples of 43 (in this case the V token, which is 86).
2. The gcd( token is a large prime number (47881), which means it couldn't be used at all.
The tokens for this program come out to:
```
token hex dec
Input 0xDC 220
L1 0x5D00 23808
: 0x3E 62
ΔList( 0xBB2C 47916
cumSum( 0xBB29 47913
L1 0x5D00 23808
: 0x3E 62
augment( 0x14 20
Ans 0x72 114
+ 0x70 112
V 0x56 86
, 0x2B 43
V 0x56 86
+ 0x70 112
{ 0x08 8
0 0x30 48
: 0x3E 62
2 0x32 50
> 0x6C 106
sum( 0xB6 182
Ans 0x72 114
L1 0x5D00 23808
= 0x6A 106
lcm( 0xBB08 47880
Ans 0x72 114
+ 0x70 112
V 0x56 86
, 0x2B 43
V 0x56 86
+ 0x70 112
L1 0x5D00 23808
```
# Explanation
```
Input L1: Prompt the user to input L1.
ΔList(cumSum(L1: Take the differences of the prefix sum of L1,
which in effect removes the first element (result in Ans).
augment(Ans+V,V+{0: Append a 0 to the end of Ans.
V defaults to 0, so adding it is a no-op.
Ans now holds L1 shifted to the left by one element,
with a 0 shifted in.
AnsL1=lcm(Ans+V,V+L1 Take the least common multiple of each corresponding element
of Ans and L1, and check if each is equal to their product.
This returns a list of booleans, each 1 corresponding to
a co-prime pair. The last element (having been paired with 0)
will always be 1.
2>sum( Returns 1 if there is at most one 1 in the list, else 0.
Since the last element is always 1, this means
we return 1 only if there are no co-prime pairs.
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 15 bytes
```
&F.bPiFNP.TtBQQ
```
**[Try it here](http://pyth.herokuapp.com/?code=%26F.bPiFNP.TtBQQ&input=%5B38%2C+70%2C+46%2C+98%2C+80%2C+105%2C+70%2C+78%2C+80%2C+46%2C+84%2C+116%2C+66%2C+81%2C+81%5D&debug=0)** or **[Check out Test Suite.](http://pyth.herokuapp.com/?code=%26F.bPiFNP.TtBQQ&input=%5B6%2C21%5D%0A%5B502%2C230%2C524%2C618%2C996%5D%0A%5B314%2C+112%2C938%2C+792%2C+309%5D%0A%5B666%2C+642%2C+658%2C+642%2C+849%2C+675%2C+910%2C+328%2C+320%5D%0A%5B922%2C+614%2C+530%2C+660%2C+438%2C+854%2C+861%2C+357%2C+477%5D&test_suite=1&test_suite_input=%5B6%2C21%5D%0A%5B502%2C230%2C524%2C618%2C996%5D%0A%5B314%2C+112%2C938%2C+792%2C+309%5D%0A%5B666%2C+642%2C+658%2C+642%2C+849%2C+675%2C+910%2C+328%2C+320%5D%0A%5B922%2C+614%2C+530%2C+660%2C+438%2C+854%2C+861%2C+357%2C+477%5D%0A%5B6%2C+7%5D%0A%5B629%2C+474%2C+502%2C+133%2C+138%5D%0A%5B420%2C+679%2C+719%2C+475%2C+624%5D%0A%5B515%2C+850%2C+726%2C+324%2C+764%2C+555%2C+752%2C+888%2C+467%5D%0A%5B946%2C+423%2C+427%2C+507%2C+899%2C+812%2C+786%2C+576%2C+844%5D&debug=0)**
This is a collaborative effort between [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) and [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). Returns an inconsistent value (non-empty list) for truthy, and the empty list for falsy.
---
## ASCII-values
```
[38, 70, 46, 98, 80, 105, 70, 78, 80, 46, 84, 116, 66, 81, 81]
```
Which share the following factors:
```
[2, 2, 2, 2, 5, 35, 2, 2, 2, 2, 4, 2, 3, 81]
```
---
# Explanation
```
&F.bPiFNP.TtBQQ
tBQ Return [Q, Q[1:]] (Q = eval first line of input)
.T Transpose ^ without cropping absences
P Remove last element of ^
.b Q Map in parallel on ^ (N) and Q (Y, ignored)
iFN GCD of N
P Prime factors of ^ (P(1) = [])
&F Left fold (reduce) the result of the map with Logical AND (short-circuiting)
```
---
Without the [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") requirement, this would've been a ~~7~~ 5-byte version accomplishing the same task (-2 thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)):
```
-1iVt
```
---
# Explanation
```
-1iVtQQ Implicit QQ at the end
tQ Return Q[1:]
iV Q Vectorized GCD on ^ and Q
-1 Remove every element of ^ from [1] (implicit singleton)
```
] |