text
stringlengths 180
608k
|
---|
[Question]
[
### Introduction
In the strange world of integer numbers, divisors are like assets and
they use to call "rich" the numbers having more divisors than their reversal, while they call "poor" the ones having less divisors than their reversal.
For example, the number \$2401\$ has five divisors : \$1,7,49,343,2401\$, while its reversal, \$1042\$, has only four : \$1,2,521,1042\$.
So \$2401\$ is called a **rich** number, while \$1042\$ a **poor** number.
Given this definition, we can create the following two integer sequences of rich and poor numbers :
```
(here we list the first 25 elements of the sequences)
Index | Poor | Rich
-------|------|-------
1 | 19 | 10
2 | 21 | 12
3 | 23 | 14
4 | 25 | 16
5 | 27 | 18
6 | 29 | 20
7 | 41 | 28
8 | 43 | 30
9 | 45 | 32
10 | 46 | 34
11 | 47 | 35
12 | 48 | 36
13 | 49 | 38
14 | 53 | 40
15 | 57 | 50
16 | 59 | 52
17 | 61 | 54
18 | 63 | 56
19 | 65 | 60
20 | 67 | 64
21 | 69 | 68
22 | 81 | 70
23 | 82 | 72
24 | 83 | 74
25 | 86 | 75
... | ... | ...
```
**Notes :**
* as "reversal" of a number we mean its *digital reverse*, i.e. having its digits in base-10 reversed. This means that numbers ending with one or more zeros will have a "shorter" reversal : e.g. the reversal of `1900` is `0091` hence `91`
* we intentionally exclude the integer numbers having the same number of divisors as their reversal i.e. the ones belonging to [OEIS:A062895](https://oeis.org/A062895)
### Challenge
Considering the two sequences defined above, your task is to write a program or function that, given an integer `n` (you can choose 0 or 1-indexed), returns the n-th poor and n-th rich number.
### Input
* An integer number (`>= 0` if 0-indexed or `>= 1` if 1-indexed)
### Output
* 2-integers, one for the poor sequence and one for the rich sequence, in the order you prefer as long as it is consistent
### Examples :
```
INPUT | OUTPUT
----------------------------------
n (1-indexed) | poor rich
----------------------------------
1 | 19 10
18 | 63 56
44 | 213 112
95 | 298 208
4542 | 16803 10282
11866 | 36923 25272
17128 | 48453 36466
22867 | 61431 51794
35842 | 99998 81888
```
### 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.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
∞.¡ÂÑgsÑg.S}¦ζsè
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vUMLDzcdnpheDMR6wbWHlp3bVnx4xf//BgA "05AB1E – Try It Online")
---
**0-indexed [rich,poor]:**
```
∞ # Push infinite list.
.¡ } # Split into three lists by...
ÂÑgsÑg.S # 1 if rich, 0 if nothing, -1 if poor.
¦ζ # Remove list of nothings, and zip rich/poor together.
sè # Grab nth element.
```
Maybe someone can explain why this version doesn't seem to terminate, but when I click "cancel execution" on TIO it finishes with the correct answer, or if you wait 60 seconds you get the correct answer. For a version that terminates "correctly" you could use: `T+nL.¡ÂÑgsÑg.S}¦ζsè` +3 bytes
[Answer]
# JavaScript (ES6), ~~121 115 113~~ 111 bytes
Input is 1-indexed. Outputs as `[poor, rich]`.
```
x=>[(s=h=(n,i=x)=>i?h(++n,i-=(g=(n,k=n)=>k&&!(n%k)*~-s+g(n,k-1))(n)>g([...n+''].reverse().join``)):n)``,h(s=2)]
```
[Try it online!](https://tio.run/##Fc3JroJAEIXhvU9RLtQqKTrBeUjhyqcgJBBsBjHVhjbG1X11brM6Od/mf5bf0ldD9/7E6h52rGX8SZqhl1ZQuZMfSdrdWoyi8GLBZuJeNHC/XM5RFz2t/2IfNZPHCREqpQ1mxhiNVqvcDPZrB2@RzNN1WhREF6Wi4DZENpSP1yxh2DBsGXYMe4YDw5HhxHBmSMLsAp/3@czUbriXVYsKkkLl1LuXNS83laEOWaLxHw "JavaScript (Node.js) – Try It Online")
## Commented
### Helper function
```
g = (n, // g is a helper function taking n and returning either the
k = n) => // number of divisors or its opposite; starting with k = n
k && // if k is not equal to 0:
!(n % k) // add either 1 or -1 to the result if k is a divisor of n
* ~-s // use -1 if s = 0, or 1 if s = 2
+ g(n, k - 1) // add the result of a recursive call with k - 1
```
### Main
```
x => [ // x = input
( s = // initialize s to a non-numeric value (coerced to 0)
h = (n, // h is a recursive function taking n
i = x) => // and using i as a counter, initialized to x
i ? // if i is not equal to 0:
h( // do a recursive call ...
++n, // ... with n + 1
i -= // subtract 1 from i if:
g(n) // the number of divisors of n (multiplied by ~-s within g)
> // is greater than
g( // the number of divisors of the reversal of n obtained ...
[...n + ''] // ... by splitting the digits
.reverse() // reversing them
.join`` // and joining back
) // (also multiplied by ~-s within g)
) // end of recursive call
: // else:
n // we have reached the requested term: return n
)``, // first call to h for the poor one, with n = s = 0 (coerced)
h(s = 2) // second call to h for the rich one, with n = s = 2
] // (it's OK to start with any n in [0..9] because these values
// are neither poor nor rich and ignored anyway)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
ṚḌ;⁸Æd
Ç>/$Ɠ©#żÇ</$®#Ṫ
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//4bma4biMO@KBuMOGZArDhz4vJMaTwqkjxbzDhzwvJMKuI@G5qv//OTX/ "Jelly – Try It Online")
A full program taking 1-indexed \$n\$ on stdin and returning a list of the n-th poor and rich integers in that order.
### Explanation
```
ṚḌ;⁸Æd | Helper link: take an integer and return the count of divisors fof its reverse and the original number in that order
Ṛ | Reverse
Ḍ | Convert back from decimal digits to integer
;⁸ | Concatenate to left argument
Æd | Count divisors
Ç>/$Ɠ©#żÇ</$®#Ṫ | Main link
Ɠ© | Read and evaluate a line from stdin and copy to register
$ # | Find this many integers that meet the following criteria, starting at 0 and counting up
Ç | Helper link
>/ | Reduce using greater than (i.e. poor numbers)
ż | zip with
$®# | Find the same number of integers meeting the following criteria
Ç | Helper link
</ | Reduce using less than (i.e. rich numbers)
Ṫ | Finally take the last pair of poor and rich numbers
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 152 bytes
```
(a=b=k=1;m=n={};p=AppendTo;While[a<=#||b<=#,#==#2&@@(s=0~DivisorSigma~#&/@{k,IntegerReverse@k++})||If[#<#2&@@s,m~p~k;a++,n~p~k;b++]];{m[[#]],n[[#]]}-1)&
```
[Try it online!](https://tio.run/##HYtPC4IwHEC/SjAQZYuyPxDMHyzo4i0q6DB2mLV02OZQ8eL0q6/w8t67PCP7ShnZ65cMJYRYQgE1pNSAhXGiDs7OKft@NPRZ6a/iMgPkffEnQQBoFzEWd7CdL3rQXdPedWnkjKING2uS216Vqr2pQbWdYjXGU@J9/uEoW8aOmNnNNZUYE7tUgbEQdDScIyGIXTSt0yQK11bbfsVKvj@eDjsRwg8 "Wolfram Language (Mathematica) – Try It Online")
If the conjecture is true, then this ***140 bytes*** solution also works
```
(a=k=1;m=n={};p=AppendTo;While[a<=#,#==#2&@@(s=0~DivisorSigma~#&/@{k,IntegerReverse@k++})||If[#<#2&@@s,m~p~k;a++,n~p~k]];{m[[#]],n[[#]]}-1)&
```
[Try it online!](https://tio.run/##HctBC4IwGIDhvxIMRNmitIJgfrCgi7eooMPYYdTSYZtjihd1f31Rp/e5vEYOjTJy0E8Za4iphBZyasDCtFAHJ@eUfd07@mj0R3FZAiIIABUJY2kP23DWo@47f9O1kQElGza1pLKDqpW/qlH5XrEW4yWb5@rNUfkfe2KCCy2VGBP7kxB0MpwjIYj9Z1nnWRIvXtthxWq@Oxz3hYjxCw "Wolfram Language (Mathematica) – Try It Online")
Here is ***poor vs rich*** plot
[](https://i.stack.imgur.com/MQEqB.png)
[Answer]
# [Perl 6](http://perl6.org/), 81 bytes
```
{(*>*,* <*).map(->&c {grep
{[[&c]] map {grep $_%%*,1..$_},$_,.flip},1..*})»[$_]}
```
[Try it online!](https://tio.run/##LcvRCoIwFAbgV/mROfSwBgV1U@5FxhoiLgLFsa5knCfrzhebBt1@8MUxTbcyr5ABXckNGVKEB7V67mNzMnJAfqUxIlsrB@dw8F@Er2tSZ62FZyW80mF6R/4Bcbt9rfCOy6dfUQmPziCHo3CFsCQ8L9d72QE "Perl 6 – Try It Online")
* `* > *` is an anonymous function that returns true if its first argument is greater than its second. Similarly for `* < *`. The former will select numbers that belong to the rich sequence, the latter will select those that belong to the poor sequence.
* `(* > *, * < *).map(-> &c { ... })` produces a pair of infinite sequences, each based on one of the comparator functions: the rich sequence and the poor sequence, in that order.
* `»[$_]` indexes into both of those sequences using `$_`, the argument to the top-level function, returning a two-element list containing the `$_`th member of the rich sequence and the `$_`th member of the poor sequence.
* `grep $_ %% *, 1..$_` produces a list of the divisors of `$_`.
* `map { grep $_ %% *, 1..$_ }, $_, .flip` produces a two-element list of the divisors of `$_`, and the divisors of `$_` with its digits reversed ("flipped").
* `[[&c]]` reduces that two-element list with the comparator function `&c` (either greater-than or less-than), producing a boolean value indicating whether this number belongs to the rich sequence of the poor sequence.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~142~~ 141 bytes
```
f=lambda i,n=1,a=[[],[]]:zip(*a)[i:]or f(i,n+1,[a[j]+[n]*(cmp(*[sum(x%y<1for y in range(1,x))for x in int(`n`[::-1]),n])==1|-j)for j in 0,1])
```
[Try it online!](https://tio.run/##Hc3LCsIwEIXhV8lGSNopGHUVzJMMA42XaIqdlrZCIr57TNz@54Mzp@058SFnb19uvNycCMBWg7OIBEhkPmGWjVMYDE2L8LLsrQZ0OFCLTI28jgXg@h5l3KWz9kUlEVgsjh93qSEqVVusLfAme@7RmE6TAiZlrf52w18MVeyhDHleiixnp6PKPw "Python 2 – Try It Online")
---
---
Non-recursive alternative (very similar to the other Python answers)
# [Python 2](https://docs.python.org/2/), 143 bytes
```
i=input()
a=[[],[]];n=1
while~i+len(zip(*a)):([[]]+a)[cmp(*[sum(x%i<1for i in range(1,x))for x in int(`n`[::-1]),n])]+=n,;n+=1
print zip(*a)[i]
```
[Try it online!](https://tio.run/##Lc1BCsIwEIXhfU@RjTBj4iLqqpqTDAMNUu1AOw21xerCq8cU3H7vwZ/eczfqMWcJommZAasYiNgR80WDr16d9O1XbN8qfCTBPiLWUB5sI9JtKELPZYB1J1d/HycjRtRMUR8teLcibrZuJjpDow3V9cEzOmVkG9Rd1JZMmsps/gESzvl8@gE "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~158~~ 153 bytes
-2 bytes thanks to shooqie
```
n=input()
p=[];r=[];c=1
while min(len(p),len(r))<=n:[[],r,p][cmp(*[sum(x%-~i<1for i in range(x))for x in c,int(str(c)[::-1])])]+=[c];c+=1
print p[n],r[n]
```
[Try it online!](https://tio.run/##FY3BCsIwEETvfkUuwq5NDxUv1uZLlhwkVBtot8s2xXrx12PCwAw8hhn5pmnla87sIsueAE/iyD@0WnDd6TPFeTRLZJhHBkFbQxEHxz2Rt2rFU1gELrTtCxzn9heH7rWqiSay0Se/RzgQKzkqCTZygi0pBKS@bzuPRY2jUA6b8ihaCkaIy3ixnO@3Pw "Python 2 – Try It Online")
Input is 0-indexed. Outputs as `poor rich`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 128 bytes
Input is *zero-indexed*. Outputs as [poor, rich].
```
->n,*a{b=[];i=0;d=->z{(1..z).count{|e|z%e<1}};(x=d[i+=1];y=d[i.digits.join.to_i];[[],b,a][x<=>y]<<i)until a[n]&b[n];[a[n],b[n]]}
```
### Explanation
```
->n,*a{ # Anonymous function, initialize poor array
b=[];i=0; # Initialize rich array and counter variable
d=->z{(1..z).count{|e|z%e<1}}; # Helper function to count number of factors
( # Start block for while loop
x=d[i+=1]; # Get factors for next number
y=d[i.digits.join.to_i]; # Factors for its reverse
# (digits returns the ones digit first, so no reversing)
[[],b,a][x<=>y] # Fetch the appropriate array based on
# which number has more factors
<<i # Insert the current number to that array
)until a[n]&b[n]; # End loop, terminate when a[n] and b[n] are defined
[a[n],b[n]] # Array with both poor and rich number (implicit return)
} # End function
```
[Try it online!](https://tio.run/##JczdCoIwGIDhc69C1EJLh1IQNOeNrCHOn/qiNskJ6vTWW0onL8/R@@n5aBpyM1EmwkOhOaEMA4lxRaJs0n6C0BSgUvZC6bmep12dJsuC/YFUFI4kYXjchCq4g@rQU4JASubAMKUs5GHB6JCSbGRpCsE6gZddUMH2fA2mG8ONbDHlQ75bq@1VZzuul19tVzfUy/@3xTGxlVys8@krWwVSdCYSPw "Ruby – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 76 bytes
```
{classify({+(.&h <=>h .flip)},^($_*3+99)){-1,1}[*;$_]}
my&h={grep $_%%*,^$_}
```
[Try it online!](https://tio.run/##DcvRCsIgFADQ5/yK@@BEnUkrCEbZj0TKiDkHRqJPcvHbrfN@0prjtX8q86bjOy6l7L5yHLlmAe7mEUD7uCfRlOXUycs4z0LgcVJTe8obda9G/jkY3PKagLphkMpS17r/ZrDnEyA5lKWCZp60/gM "Perl 6 – Try It Online")
I didn't see [Sean's Perl 6 answer](https://codegolf.stackexchange.com/a/185619/76162), but this works in a different way. Note that I've hardcoded the upperbound as `n*3+99`, which is probably not strictly correct. However, I could replace the `*3` with `³` for no extra bytes, which would make the program far less efficient, if more correct.
[Answer]
# [Python 2](https://docs.python.org/2/), 152 bytes
```
def f(n):
a,b=[],[];i=1
while not(a[n:]and b[n:]):[[],b,a][cmp(*[sum(m%-~i<1for i in range(m))for m in i,int(`i`[::-1])])]+=[i];i+=1
return a[n],b[n]
```
[Try it online!](https://tio.run/##RY5BCsIwEEX3OcVshMSmYIqraE8SAk1tagfMtMQUcePVY7IQGRgen8@82d5pWanLefIzzJyEZuDk2Bsrjb1grxi8Fnx4oDVxZ0hbRxOMFYQ2pTVKZ80tbPxonnvg4dB@8KrmNQICEkRHd8@DEDUJNUGJlPiAg9G6VVaUaXqDRdZUW/RpjwRFVW6XlbdY@uW1k2A/VH/szoLlLw "Python 2 – Try It Online")
Ends up being pretty similar to [Rod's answer](https://codegolf.stackexchange.com/a/185610/69880). Returns zero-indexed `n`th poor, rich tuple.
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~180~~ 175 bytes
```
procedure f(n)
a:=[];b:=[];k:=1
while{s:=t:=0
i:=1to k+(m:=reverse(k))&(k%i=0&s+:=1)|(m%i=0&t+:=1)&\x
s>t&n>*a&push(a,k)
s<t&n>*b&push(b,k)
k+:=1;n>*a|n>*b}
return[!b,!a];end
```
[Try it online!](https://tio.run/##TY7LDoIwEEX3/YpiYjNVFrpwYbH8CLIoMISmUkxbfET8dqW4cRaT3DNnkqvrwX4@VzfU2IwOaQuWEyVkUWbVso2Qe3Lv9AVfXsgg5I4SPbMwULOFXkiHN3QewXDOwKy13DG/nQU@Qb@ksCR2fhCfB2bzjWLX0XegUsOJPy2o@qEqIhP9LHpTvLyJwzA6WyRVmqgyQ9v89e2VtsAJnSf2eNK70wE9JC0cDzylK7riJL58AQ "Icon – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 34 bytes
```
{⍵⌷⍉1↓⊢⌸{×-/{≢∪⍵∨⍳⍵}¨⍵,⍎⌽⍕⍵}¨⍳1e3}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHPdsf9XYaPmqb/Khr0aOeHdWHp@vqVz/qXPSoYxVIumPFo97NQEbtISBjq86j3r5HPXsf9U6FCW02TDWu/Z/2qG0CSKpvqqf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/R72r0g6tMFQwtFAwMVGwNAUA "APL (Dyalog Unicode) – Try It Online")
Thanks to Adám and ngn for helping me golf this monstrosity.
TIO times out for the bigger indices (which require `⍳1e5` or `⍳1e6`) , but given enough time and memory the function will terminate correctly.
[Answer]
# [R](https://www.r-project.org/), ~~152~~ 137 bytes
-12 bytes thanks to Giuseppe
-3 bytes thanks to digEmAll
```
n=scan()
F=i=!1:2
`?`=sum
while(?n>i)if(n==?(i[s]=i[s<-sign((?!(r=?rev((T=T+1)%/%(e=10^(0:log10(T)))%%10)*e)%%1:r)-?!T%%1:T)]+1))F[s]=T
F
```
[Try it online!](https://tio.run/##RcxBCsIwEAXQfU5hF4EZtZjUClocs@sJspOKUtIaqCkkVgvi2WuzcvP@8OGPnxpqBlc/be9gXC9CfXP/Akf8TI5iCchKspTIImNXdaUwPNj7bjsDyp0s2gYckQJ7DhXNHNNgWwegEvCkvHkBaNIriXzDwZAUFxBF17dSgEZEzqXApYlZeExVouOlsZoXWMafmpXTlzUgcSbbRuU@mufRww7Z9AM "R – Try It Online")
`T` is the integer currently being tried; the latest poor and rich numbers are stored in the vector `F`.
The shortest way I could find of reversing an integer was converting it to digits in base 10 with modular arithmetic, then converting back with powers of 10 inverted, but I expect to be outgolfed on this and other fronts.
Explanation (of previous, similar version):
```
n=scan() # input
i=0*1:3 # number of poor, middle class, and rich numbers so far
S=sum
while(S(n>i)){ # continue as long as at least one of the classes has less than n numbers
if((i[s]=i[
s<-2+sign(S(!( # s will be 1 for poor, 2 for middle class, 3 for rich
r=S((T<-T+1)%/%10^(0:( # reverse integer T with modular arithmetic
b=log10(T)%/%1 # b is number of digits
))%%10*10^(b:0))
)%%1:r)- # compute number of divisors of r
S(!T%%1:T)) # computer number of divisors of T
]+1)<=n){ # check we haven't already found n of that class
F[s]=T
}
}
F[-2] # print nth poor and rich numbers
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~190~~ 180 bytes
Outputs as `[poor, rich]`.
```
n=>{let p,r,f=h=i=0;while(f<n){k=d(i),e=d(+(i+"").split``.reverse().join``);if(k<e){p=i;f++}if(k>e&&h<n){r=i;h++}i++}return[p,r]}
d=n=>{c=0;for(j=1;j<=n;j++)if(n%j==0)c++;return c}
```
[Try it online!](https://tio.run/##JU5BasMwELznFSLQoEWKiCGFFnl96ytCwEZeR1KEZGQ3ORi/3ZXpYWeYgZlZ3726yWQ3zueYetoeuEVslkAzG2WWA1p0eNFv6wLxoY6wPLHnDiQVEtyJ4xHUNAY3t63K9KI8EQflk4ttC9oN/FkTLCM6PQix7rqh08nuTbmYdjfLZZp/c7yVzft66HH/wZTdIWXusdK@xqi9EFAK4odHvIARQv@nmFk3faskq74ku14l@/68H1SJ/nTG8siwYSbFKQVSIT14lKwAAGx/ "JavaScript (Node.js) – Try It Online")
## Explanation
### `d(n)` Function
This helper finds the number of factors that a number has.
```
d=n=>{ // Equivalent to `function d(n) {
c=0; // Counter
for(j=1;j<=n;j++) // Check every integer from 1 to n
if(n%j==0)c++; // If the number is a factor, add 1 to the counter
return c
};
```
### Main Function
```
n=>{
let p,r,f=h=i=0; // p -> the poor number, r -> the rich number, f -> the number of poor numbers found, h -> the number of rich numbers found, i -> the current number being checked
while(f<n){ // While it's found less than n poor numbers (assumes that it will always find the rich number first)
k=d(i), // k -> number of factors of i
e=d(+((i+"").split``.reverse().join``)); // e -> number of factors of reversed i
if(k<e){p=i;f++} // If it hasn't found enough poor numbers and i is poor, save it and count it
if(k>e&&h<n){r=i;h++} // If it hasn't found enough rich numbers and i is rich, save it and count it
i++
};
return[p,r]
}
```
[Answer]
## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 221 bytes
```
n=>{int g,h,i,j=9,k,l,m,o,r,p;m=o=r=p=0;while(m<n||o<n){k=g=h=0;l=++j;while(l!=0){k=k*10+l%10;l/=10;}for(i=2;i<j+k;i++){if(j%i<1&&i<j)g++;if(k%i<1&&i<k)h++;}if(g<h&&o<n){o++;p=j;}if(g>h&&m<n){m++;r=j;}}return new{n,p,r};}
```
[Try it online!](https://tio.run/##Nc4/b4MwEIfhvZ@CDkF2faUQKUNlH1syZaoqdSbIwIGxkQFlIHx2avpnueF5h9@V42s50naZbanITuBurS6nPKoi3CzmS7CohgYIWnyHDgz04MDDIHt06HHAVN4bMpr1yj4eTlm@dFhjE9ygEO1fNc@Y7qV7yVJhDlmobxjuWjnPCI@SVCs6SULwhSrWHkhlcRyQ10LIIN2/dLwJsgaqVRPHP4suyIDtr@ZB@137oH7X1etp9jay@r5YGMCvct3k09nOvfbFzejko7C1ZhkcTzz5dFcaJ8aTi/PnomzCe3n05WnSV7KaVYw453L7Bg)
] |
[Question]
[
<https://en.wikipedia.org/wiki/Connect_Four>
Does anyone remember the 2 player game connect 4? For those who don't it was a 6x7 board that stands vertical on a surface. The goal of connect 4 is to, well connect 4! The connection is counted if it is horizontal, diagonal, or vertical. You place your pieces on the board by inserting a piece at the top of a column where it falls to the bottom of that column. Our rules change 3 things in connect 4.
* **Change #1** Winning is defined as the player with the most points. You get points by connecting 4 like in the rules - more on that later.
* **Change #2** You have 3 players each round.
* **Change #3** The board size is 9x9.
### Scoring:
Score is based on how many you get in a row. If you have a 4 in a row group you get 1 point. If you have a 5 in a row group you get 2 points, 6 in a row 3 and so on.
### Examples:
Note `o` and `x` are replaced with `#` and `~` respectively, for better contrast
Example of empty board: (all examples are 2 player standard size board)
```
a b c d e f g
6 | | | | | | | |
5 | | | | | | | |
4 | | | | | | | |
3 | | | | | | | |
2 | | | | | | | |
1 |_|_|_|_|_|_|_|
```
If we drop a piece in coll `d`, it will land in location`1d`.
```
a b c d e f g
6 | | | | | | | |
5 | | | | | | | |
4 | | | | | | | |
3 | | | | | | | |
2 | | | | | | | |
1 |_|_|_|#|_|_|_|
```
If we now drop a piece in coll `d` again, it will land in location `2d`. Here are examples of 4 in a row positions:
```
a b c d e f g
6 | | | | | | | |
5 | | | | | | | |
4 | | | |~| | | |
3 | | |~|#| | | |
2 | |~|#|~| |#| |
1 |~|#|~|#|_|#|_|
```
In this case `x` gets 1 point diagonally (`1a 2b 3c 4d`).
```
a b c d e f g
6 | | | | | | | |
5 | | | | | | | |
4 | | | |#| | | |
3 | | | |#| | | |
2 | | | |#| | | |
1 |_|~|_|#|~|_|~|
```
In this case, `o` gets 1 point vertically (`1d 2d 3d 4d`).
```
a b c d e f g
6 | | | | | | | |
5 | | | | | | | |
4 | | | | | | | |
3 | | | | | | | |
2 | | |#|#|#|#| |
1 |_|_|~|~|~|~|~|
```
In this case `o` gets 2 points horizontally (`1c 1d 1e 1f 1g`) and `x` gets 1 point horizontally (`2c 2d 2e 2f`).
```
a b c d e f g
6 | | |#| | | | |
5 | | |#| | | | |
4 | | |#| | | | |
3 | | |#| | |~| |
2 |~| |#| | |#|~|
1 |~|_|#|~| |~|~|
```
This time `x` gets 3 points for a 6 in a row (`1c 2c 3c 4c 5c 6c`).
### Input / Output
You will have access to the board via a 2d array. Each location will be represented with an `int` representing a player id. You will also have your player id passed to your function. You make your move by returning which coll you want to drop your piece into. Each round 3 players will be chosen to play. At the end of the game, all players will have played an even amount of games.
For the moment 100k rounds will be run (note this takes a *long* time, you may want to reduce it for fast turnaround testing). Overall the winner is the player with the most wins.
The controller can be found here: <https://github.com/JJ-Atkinson/Connect-n/tree/master>.
### Writing a bot:
To write a bot you must extend the `Player` class. `Player` is abstract and has one method to implement, `int makeMove(void)`. In `makeMove` you will decide which coll you would like to drop your piece into. If you chose an invalid coll (e.g. coll does not exist, coll is filled already), **your turn will be skipped**. In the `Player` class you have many useful helper methods. A listing of the most important ones follows:
* `boolean ensureValidMove(int coll)`: Return true *if* the coll is on the board *and* the coll is not filled yet.
* `int[] getBoardSize()`: Return a int array where `[0]` is the number of columns, and `[1]` is the number of rows.
* `int[][] getBoard()`: Return a copy of the board. You should access it like this: `[coll number][row number from bottom]`.
* To find the rest, look at the `Player` class.
* `EMPTY_CELL`: The value of an empty cell
Since this will be multi-threaded, I have also included a `random` function if you need it.
### Debugging your bot:
I have included some things in the controller to make it simpler to debug a bot. The first one is `Runner#SHOW_STATISTICS`. If this is enabled, you will see a printout of player groups played, including a count of bot wins. Example:
```
OnePlayBot, PackingBot, BuggyBot,
OnePlayBot -> 6
PackingBot -> 5
BuggyBot -> 3
Draw -> 1
```
You can also make a custom game with the `connectn.game.CustomGame` class, you can see the scores and winner of each round. You can even add yourself to the mix with `UserBot`.
### Adding your bot:
To add your bot to the lineup, go to the `PlayerFactory` static block and add the following line:
```
playerCreator.put(MyBot.class, MyBot::new);
```
### Other things to note:
* The simulations are multi-threaded. If you want to turn that off, go to `Runner#runGames()` and comment this line (`.parallel()`).
* To change the number of games, set `Runner#MINIMUM_NUMBER_OF_GAMES` to your liking.
### Added later:
* Communication among bots is disallowed.
Related: [Play Connect 4!](https://codegolf.stackexchange.com/questions/5496/play-connect-4)
================================
## Scoreboard: (100 000 games)
```
MaxGayne -> 22662
RowBot -> 17884
OnePlayBot -> 10354
JealousBot -> 10140
Progressive -> 7965
Draw -> 7553
StraightForwardBot -> 7542
RandomBot -> 6700
PackingBot -> 5317
BasicBlockBot -> 1282
BuggyBot -> 1114
FairDiceRoll -> 853
Steve -> 634
```
================================
[Answer]
# MaxGayne
This bot assigns a score to each position, based mainly on the length of connected parts. It looks 3 moves deep inspecting 3 best looking moves at each stage, and chooses the one with the maximum expected score.
```
package connectn.players;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MaxGayne extends Player {
private static final int PLAYERS = 3;
private static class Result {
protected final int[] score;
protected int lastCol;
public Result(int[] score, int lastCol) {
super();
this.score = score;
this.lastCol = lastCol;
}
public Result() {
this(new int[PLAYERS], -1);
}
public Result(Result other) {
this(new int[PLAYERS], other.lastCol);
System.arraycopy(other.score, 0, this.score, 0, PLAYERS);
}
public int getRelativeScore(int player) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < PLAYERS; ++ i) {
if (i != player && score[i] > max) {
max = score[i];
}
}
return score[player] - max;
}
}
private static class Board extends Result {
private final int cols;
private final int rows;
private final int[] data;
private final int[] used;
public Board(int cols, int rows) {
super();
this.cols = cols;
this.rows = rows;
this.data = new int[cols * rows];
Arrays.fill(this.data, -1);
this.used = new int[cols];
}
public Board(Board other) {
super(other);
this.cols = other.cols;
this.rows = other.rows;
this.data = new int[cols * rows];
System.arraycopy(other.data, 0, this.data, 0, this.data.length);
this.used = new int[cols];
System.arraycopy(other.used, 0, this.used, 0, this.used.length);
}
private void updatePartScore(int player, int length, int open, int factor) {
switch (length) {
case 1:
score[player] += factor * open;
break;
case 2:
score[player] += factor * (100 + open * 10);
break;
case 3:
score[player] += factor * (10_000 + open * 1_000);
break;
default:
score[player] += factor * ((length - 3) * 1_000_000 + open * 100_000);
break;
}
}
private void updateLineScore(int col, int row, int colOff, int rowOff, int length, int factor) {
int open = 0;
int player = -1;
int partLength = 0;
for (int i = 0; i < length; ++ i) {
int newPlayer = data[(col + i * colOff) * rows + row + i * rowOff];
if (newPlayer < 0) {
if (player < 0) {
if (i == 0) {
open = 1;
}
} else {
updatePartScore(player, partLength, open + 1, factor);
open = 1;
player = newPlayer;
partLength = 0;
}
} else {
if (newPlayer == player) {
++ partLength;
} else {
if (player >= 0) {
updatePartScore(player, partLength, open, factor);
open = 0;
}
player = newPlayer;
partLength = 1;
}
}
}
if (player >= 0) {
updatePartScore(player, partLength, open, factor);
}
}
private void updateIntersectionScore(int col, int row, int factor) {
updateLineScore(col, 0, 0, 1, rows, factor);
updateLineScore(0, row, 1, 0, cols, factor);
if (row > col) {
updateLineScore(0, row - col, 1, 1, Math.min(rows - row, cols), factor);
} else {
updateLineScore(col - row, 0, 1, 1, Math.min(cols - col, rows), factor);
}
if (row > cols - col - 1) {
updateLineScore(cols - 1, row - (cols - col - 1), -1, 1, Math.min(rows - row, cols), factor);
} else {
updateLineScore(col + row, 0, -1, 1, Math.min(col + 1, rows), factor);
}
}
private void updatePiece(int player, int col, int row) {
updateIntersectionScore(col, row, -1);
data[col * rows + row] = player;
++ used[col];
lastCol = col;
updateIntersectionScore(col, row, 1);
}
public Board updatePiece(int player, int col) {
int row = used[col];
if (row >= rows) {
return null;
} else {
Board result = new Board(this);
result.updatePiece(player, col, row);
return result;
}
}
private void updateBoard(int[][] board) {
for (int col = 0; col < cols; ++ col) {
for (int row = 0; row < rows; ++ row) {
int oldPlayer = data[col * rows + row];
int newPlayer = board[col][row] - 1;
if (newPlayer < 0) {
if (oldPlayer < 0) {
break;
} else {
throw new RuntimeException("[" + col + ", " + row + "] == " + oldPlayer + " >= 0");
}
} else {
if (oldPlayer < 0) {
updatePiece(newPlayer, col, row);
} else if (newPlayer != oldPlayer) {
throw new RuntimeException("[" + col + ", " + row + "] == " + oldPlayer + " >= " + newPlayer);
}
}
}
}
}
private Result bestMove(int depth, int player) {
List<Board> boards = new ArrayList<>();
for (int col = 0; col < cols; ++ col) {
Board board = updatePiece(player, col);
if (board != null) {
boards.add(board);
}
}
if (boards.isEmpty()) {
return null;
}
Collections.sort(boards, (o1, o2) -> Integer.compare(o2.getRelativeScore(player), o1.getRelativeScore(player)));
if (depth <= 1) {
return new Result(boards.get(0).score, boards.get(0).lastCol);
}
List<Result> results = new ArrayList<>();
for (int i = 0; i < 3 && i < boards.size(); ++ i) {
Board board = boards.get(i);
Result result = board.bestMove(depth - 1, (player + 1) % PLAYERS);
if (result == null) {
results.add(new Result(board.score, board.lastCol));
} else {
results.add(new Result(result.score, board.lastCol));
}
}
Collections.sort(results, (o1, o2) -> Integer.compare(o2.getRelativeScore(player), o1.getRelativeScore(player)));
return results.get(0);
}
}
private Board board = null;
@Override
public int makeMove() {
if (board == null) {
int[][] data = getBoard();
board = new Board(data.length, data[0].length);
board.updateBoard(data);
} else {
board.updateBoard(getBoard());
}
Result result = board.bestMove(3, getID() - 1);
return result == null ? -1 : result.lastCol;
}
}
```
[Answer]
# RowBot
Looks in all directions and determines the optimal column. Tries to connect his pieces, while not letting his opponents do the same.
```
package connectn.players;
import connectn.game.Game;
import java.util.ArrayList;
import java.util.List;
public class RowBot extends Player {
@Override
public int makeMove() {
int[][] board = getBoard();
int best = -1;
int bestScore = -10;
for (int col = 0; col < board.length; col++) {
if (ensureValidMove(col)) {
int score = score(board, col, false);
score -= score(board, col, true);
if (score > bestScore) {
bestScore = score;
best = col;
}
}
}
return best;
}
private int score(int[][] board, int col, boolean simulateMode) {
int me = getID();
int row = getLowestEmptyRow(board, col);
List<Score> scores = new ArrayList<>();
if (!simulateMode) {
scores.add(getScoreVertical(board, col, row));
} else {
row += 1;
}
scores.addAll(getScoreHorizontal(board, col, row));
scores.addAll(getScoreDiagonal(board, col, row));
int score = 0;
for (Score s : scores) {
if (s.player == me) {
score += s.points > 2 ? 100 : s.points * 5;
} else if (s.player != Game.EMPTY_CELL) {
score += s.points > 2 ? 50 : 0;
} else {
score += 1;
}
}
return score;
}
private Score getScoreVertical(int[][] board, int col, int row) {
return getScore(board, col, row, 0, -1);
}
private List<Score> getScoreHorizontal(int[][] board, int col, int row) {
List<Score> scores = new ArrayList<>();
Score left = getScore(board, col, row, -1, 0);
Score right = getScore(board, col, row, 1, 0);
if (left.player == right.player) {
left.points += right.points;
scores.add(left);
} else {
scores.add(left);
scores.add(right);
}
return scores;
}
private List<Score> getScoreDiagonal(int[][] board, int col, int row) {
List<Score> scores = new ArrayList<>();
Score leftB = getScore(board, col, row, -1, -1);
Score rightU = getScore(board, col, row, 1, 1);
Score leftBottomToRightUp = leftB;
if (leftB.player == rightU.player) {
leftBottomToRightUp.points += rightU.points;
} else if (leftB.points < rightU.points || leftB.player == Game.EMPTY_CELL) {
leftBottomToRightUp = rightU;
}
Score leftU = getScore(board, col, row, -1, 1);
Score rightB = getScore(board, col, row, 1, -1);
Score rightBottomToLeftUp = leftU;
if (leftU.player == rightB.player) {
rightBottomToLeftUp.points += rightB.points;
} else if (leftU.points < rightB.points || leftU.player == Game.EMPTY_CELL) {
rightBottomToLeftUp = rightB;
}
if (leftBottomToRightUp.player == rightBottomToLeftUp.player) {
leftBottomToRightUp.points += rightBottomToLeftUp.points;
scores.add(leftBottomToRightUp);
} else {
scores.add(leftBottomToRightUp);
scores.add(rightBottomToLeftUp);
}
return scores;
}
private Score getScore(int[][] board, int initCol, int initRow, int colOffset, int rowOffset) {
Score score = new Score();
outerLoop: for (int c = initCol + colOffset;; c += colOffset) {
for (int r = initRow + rowOffset;; r += rowOffset) {
if (outside(c, r) || board[c][r] == Game.EMPTY_CELL) {
break outerLoop;
}
if (score.player == Game.EMPTY_CELL) {
score.player = board[c][r];
}
if (score.player == board[c][r]) {
score.points++;
} else {
break outerLoop;
}
if (rowOffset == 0) {
break;
}
}
if (colOffset == 0) {
break;
}
}
return score;
}
private boolean outside(int col, int row) {
return !boardContains(col, row);
}
private int getLowestEmptyRow(int[][] board, int col) {
int[] rows = board[col];
for (int row = 0; row < rows.length; row++) {
if (rows[row] == Game.EMPTY_CELL){
return row;
}
}
return -1;
}
private class Score {
private int player = Game.EMPTY_CELL;
private int points = 0;
}
}
```
[Answer]
# OnePlayBot
This bot has only one play - place its piece in the leftmost cell that is valid. Oddly enough it does pretty good ;)
```
static class OnePlayBot extends Player {
@Override
int makeMove() {
int attemptedMove = 0;
for (int i = 0; i < getBoardSize()[0]; i++)
if (ensureValidMove(i)) {
attemptedMove = i;
break;
}
return attemptedMove;
}
}
```
[Answer]
# RandomBot
Just put a piece anywhere that is valid.
```
static class RandomBot extends Player {
@Override
int makeMove() {
int attemptedMove = (int)Math.round(random() * getBoardSize()[0]);
while (!ensureValidMove(attemptedMove))
attemptedMove = (int)Math.round(random() * getBoardSize()[0]);
return attemptedMove;
}
}
```
[Answer]
# StraightForwardBot
Similar to the OnePlayBot but takes into account the last move and plays the next column over that is valid.
```
static class StraightForwardBot extends Player {
private int lastMove = 0;
@Override
int makeMove() {
for (int i = lastMove + 1; i < getBoardSize()[0]; i++) {
if (ensureValidMove(i)) {
lastMove = i;
return i;
}
}
for (int i = 0; i < lastMove; i++) {
if (ensureValidMove(i)) {
lastMove = i;
return i;
}
}
return 0;
}
}
```
[Answer]
## JealousBot
This bot hates the other player. And he doesn't like that he drops pieces on the board. So he tries to be the last one who have drop a piece in a column.
```
public class JealousBot extends Player {
@Override
public int makeMove() {
int move = 0;
boolean madeMove = false;
int[] boardSize = getBoardSize();
int id = getID();
int[][] board = getBoard();
if(getTurn()!=0) {
for(int col = 0; col<boardSize[0]; col++) {
for(int row = 0; row<boardSize[1]; row++) {
if(ensureValidMove(col)) {
if(board[col][row]!=EMPTY_CELL && board[col][row]!=id) {
move = col;
madeMove = true;
break;
}
}
}
if(madeMove) break;
}
if(!madeMove) {
int temp = (int)Math.round(random()*boardSize[0]);
while(madeMove!=true) {
temp = (int)Math.round(random()*boardSize[0]);
if(ensureValidMove(temp)) {
madeMove = true;
}
}
move = temp;
}
} else {
move = (int)Math.round(random()*boardSize[0]);
}
return move;
}
}
```
It's my first time on CodeGolf, so I hope this answer will be good enough. I couldn't test it yet, so please excuse me if there are any mistakes.
**EDIT** : Added a line to break the second `for`.
**EDIT 2** : Figured out why the `while` was infinite. It is now complete and can be used!
[Answer]
# BasicBlockBot
A simple (and naive) block bot. He doesn't know you can make a 4 in a row horizontally *or* diagonally!
```
static class BasicBlockBot extends Player {
@Override
int makeMove() {
List<Integer> inARows = detectInARows();
double chanceOfBlock = 0.5;
if (inARows.isEmpty())
chanceOfBlock = 0;
if (random() < chanceOfBlock) {
return inARows.get((int)Math.round(random() * (inARows.size() - 1)));
} else {
return (int)Math.round(random() * getBoardSize()[0]);
}
}
/**
* Very limited - just detects vertical in a rows
*
* @return A list of colls that have 4 in a row vertical
*/
private List<Integer> detectInARows() {
List<Integer> ret = new ArrayList<>();
int[][] board = getBoard();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
int currId = board[i][j];
if (currId != -1 && is4InARowVertical(i, j, board)) {
ret.add(i);
}
}
}
return ret;
}
private boolean is4InARowVertical(int coll, int row, int[][] board) {
int id = board[coll][row];
for (int i = 0; i < 4; i++) {
int y = row + i;
if (!boardContains(coll,y) || board[coll][y] != id)
return false;
}
return true;
}
}
```
[Answer]
# Progressive
Progressive is... progressive. He likes looking at *everything*, and some! (I'm not sure of the methodology of this. It worked against a friend, once.) And, for some reason, it works decently.
```
static class Progressive extends Player{
@Override
int makeMove(){
int move = 0;
boolean statusBroken = false;
for(int n=getBoardSize()[0];n>2;n-=2){
for(int i=0;i<getBoardSize()[0];i+=n){
if(ensureValidMove(i)){
move = i;
statusBroken = true;
break;
}
if(statusBroken) break;
}
}
return move;
}
}
```
[Answer]
# FairDiceRoll
[Always returns 4.](https://xkcd.com/221/)
```
static class FairDiceRoll extends Player {
private int lastMove = 0;
@Override
int makeMove() {
return 4;
}
}
```
[Answer]
# BuggyBot
A sample bot for you to beat (FYI: it's not hard ;)
```
static class BuggyBot extends Player {
@Override
int makeMove() {
return getBoardSize()[1] - 1;
}
}
```
[Answer]
# PackingBot
This bot isn't aiming for points directly. He tries to pack a maximum of tokens until the board is filled. He understood that simply going up again and again is stupid, so he will randomly put tokens around his "domain".
He should be able to get some points in all directions, but will not be the best !
(Not tested)
```
package connectn.players;
static class PackingBot extends Player
{
@Override
int makeMove()
{
int move = 0;
int[] sizes = getBoardSize();
if(getTurn()==0)
return sizes[0]/2+sizes[0]%2;
int[][] board = getBoard();
int[] flatBoard =new int[sizes[0]];
//Creating a flat mapping of my tokens
for(int i=0;i<sizes[0];i++)
for (int j=0;j<sizes[1];j++)
if(board[i][j]!=getID())
flatBoard[i]++;
int max=0;
int range=0;
for(int i=0;i<flatBoard.length;i++)
{
if(flatBoard[i]!=0)
range++;
if(flatBoard[i]>flatBoard[max])
max=i;
}
int sens = (Math.random()>0.5)?1:-1;
move=((int)(Math.random()*(range+1)*sens))+max;
while(!ensureValidMove(move))
{
move=(move+1*sens)%sizes[0];
if(move<0)
move=sizes[0]-1;
}
return move;
}
}
```
[Answer]
# Steve
```
package connectn.players;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import connectn.game.Game;
public class Steve extends Player {
@Override
public int makeMove() {
Random r=ThreadLocalRandom.current();
int attemptedMove = 0;
int[][]board=getBoard();
int ec=Game.EMPTY_CELL;
for(int c=0;c<board.length;c++){
int j=board[c].length-1;
for(;j>=0;j--){
if(board[c][j]!=ec)break;
}
if(j>2+r.nextInt(3)&&r.nextDouble()<0.8)return c;
}
int k=-2+board.length/2+r.nextInt(5);
if(ensureValidMove(k))return k;
for (int i = 0; i < getBoardSize()[0]; i++)
if (ensureValidMove(i)) {
attemptedMove = i;
break;
}
return attemptedMove;
}
}
```
] |
[Question]
[
### Input
Two integers:
* A non-negative integer ***W*** in the range 0 to 2^64-1, specifying the weave.
* A positive integer ***S*** in the range 1 to 255, specifying the side length.
These can be taken in whichever order suits you.
### Output
An ***S*** by ***S*** ASCII representation of the requested weave (***S*** newline separated strings of ***S*** characters with an optional trailing newline). The weave is defined by the weave number ***W*** as follows:
Convert ***W*** to binary and split into 8 bytes. The first (most significant) byte defines the top row, from left (most significant bit) to right. The next byte defines the next row, and so on for 8 rows. The weave number defines an 8 by 8 square which should be tiled over the required area starting from the top left. That is, its top left corner should correspond to the top left corner of the area to be covered.
Every `0` should be displayed as a `|` and every `1` should be displayed as a `-`
### Examples
Input: `0 8`
Ouput:
```
||||||||
||||||||
||||||||
||||||||
||||||||
||||||||
||||||||
||||||||
```
---
Input: `3703872701923249305 8`
Output:
```
||--||--
|--||--|
--||--||
-||--||-
||--||--
|--||--|
--||--||
-||--||-
```
---
Input: `3732582711467756595 10`
Output:
```
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
```
---
Input: `16141147355100479488 3`
Output:
```
---
|||
---
```
---
# Leaderboard Snippet
*(using [Martin's template](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet))*
```
var QUESTION_ID=54123;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><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]
# CJam, ~~33~~ 31 bytes
```
q~:X;2b64Te["|-"f=8/{X*X<z}2*N*
```
[Test it here.](http://cjam.aditsu.net/#code=q~%3AX%3B2b64Te%5B%22%7C-%22f%3D8%2F%7BX*X%3Cz%7D2*N*&input=3732582711467756595%2023)
## Explanation
```
q~ e# Read and eval input.
:X; e# Store the side length in X and discard it.
2b e# Convert to base 2.
64Te[ e# Left-pad to length 64 with zeroes.
"|-"f= e# Select '|' for 0 and '=' for 1.
8/ e# Split into chunks of 8 bits.
{ e# Do the following twice:
X* e# Repeat lines X times (to ensure we have enough of them).
X< e# Truncate them to exactly X lines.
z e# Transpose the grid.
e# The transpose ensures that the second pass tiles the columns, and that the
e# grid is oriented correctly again after both passes are done.
}2*
N* e# Join lines by newline characters.
```
[Answer]
# K, 20
```
{y#y#'"|-"8 8#0b\:x}
```
.
```
0b\:x // convert to binary
8 8# // reshape into an 8x8 boolean matrix
"|-" // index into this char vector using the booleans as indices
y#' // extend horizontally
y# // extend vertically
```
.
```
k){y#y#'"|-"8 8#0b\:x}[3703872701923249305j;10]
"||--||--||"
"|--||--||-"
"--||--||--"
"-||--||--|"
"||--||--||"
"|--||--||-"
"--||--||--"
"-||--||--|"
"||--||--||"
"|--||--||-"
k){y#y#'"|-"8 8#0b\:x}[3703872701923249305j;8]
"||--||--"
"|--||--|"
"--||--||"
"-||--||-"
"||--||--"
"|--||--|"
"--||--||"
"-||--||-"
```
[Answer]
# Java, ~~110~~ ~~109~~ 107 Bytes
My code is in the form of an anonymous lambda function that takes a `long` and an `int` then returns a `String`.
```
(w,s)->{String b="";for(int j,i=s--;i-->0;b+='\n')for(j=s;j>=0;)b+=(w>>8*(i%8)+j--%8)%2<1?'|':45;return b;}
```
Complete testable class
```
import java.util.function.BiFunction;
public class AsciiWeave {
public static void main(String[] args){
BiFunction<Long,Integer,String> weave =
(w,s)->{String b="";for(int j,i=s--;i-->0;b+='\n')for(j=s;j>=0;)b+=(w>>8*(i%8)+j--%8)%2<1?'|':45;return b;}}
;
System.out.println(weave.apply(Long.valueOf(args[0]),Integer.valueOf(args[1])));
}
}
```
[Answer]
# Matlab, ~~86~~ 80 bytes
```
function f(W,S)
a='|-';x=de2bi(typecast(W,'uint8'))+1;s=8-mod(0:S-1,8);a(x(s,s))
```
Thanks to Hoki for his suggestion, which led me to save me 6 bytes.
Example:
```
>> W = uint64(3732582711467756595)
W =
3732582711467756595
>> S = uint8(10)
S =
10
>> f(W,S)
ans =
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
```
[Answer]
# Julia, 145 bytes
```
f(w,s)=(A=map(i->i=="1"?"-":"|",reshape(split(lpad(bin(w),64,0),""),8,8))';for i=1:s A=hcat(A,A)end;for i=1:s println(join(A[i>8?i%8:i,1:s]))end)
```
This creates a function that accepts two integers and prints to stdout.
Ungolfed + explanation:
```
function f(w,s)
# Convert w to binary, left-padded with zeros to length 64
b = lpad(bin(w), 64, 0)
# Create an 8x8 array of | and -
A = transpose(map(i -> i == "1" ? "-" : "|", reshape(split(b, ""), 8, 8)))
# Horizontally concatenate A to itself s times
for i = 1:s
A = hcat(A, A)
end
# Print the rows of A, recycling as necessary
for i = 1:s
println(join(A[i > 8 ? i % 8 : i, 1:s]))
end
end
```
This is pretty long and I'm sure it can be made much shorter. Working on it.
[Answer]
# J, 28 bytes
```
'|-'{~]$"1]$8 8$_64{.#.inv@[
```
Usage:
```
3732582711467756595 ('|-'{~]$"1]$8 8$_64{.#.inv@[) 10
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
--||--||--
||--||--||
||--||--||
--||--||--
```
Explanation (right to left):
```
#.inv@[ binary representation vector of S
_64{. padded with 0-s from the right to length 64
8 8$ reshaped in an 8 by 8 matrix
]$"1]$ tiled to a W by W size
'|-'{~ select | or - based on matrix element values
```
[Try it online here.](http://tryj.tk/)
[Answer]
# CJam, ~~30~~ ~~28~~ 27 bytes
```
q~_2m*W%/ff{8f%8bm>"|-"=}N*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~_2m*W%25%2Fff%7B8f%258bm%3E%22%7C-%22%3D%7DN*&input=3732582711467756595%2010).
[Answer]
## Python, 77
```
lambda w,s:''.join('|-'[w>>~n/s%8*8+~n%s%8&1]+'\n'[~n%s:]for n in range(s*s))
```
For each of the `s*s` values of `n`:
* Compute the coordinates via divmod `(i,j)=(n/s,n%s)`
* Compute the location in the tiling as `(i%8,j%8)`
* Compute the appropriate bit position as `8*(i%8)+(j%8)`
* Extract that bit of `w` by shifting `w` that many spaces with right and take the last bit with `&1`.
* Join one of '|-' at that position
* Add the newline at the end of every row whenever `n%s==0`
Actually, all that ends up getting the tiling backwards, since it reads `w` from the end. We fix this by using `~n` in place of `n`. I tried a recursive approach instead, but it turned out slightly longer.
The expression `w>>~n/s%8*8+~n%s%8&1` is a miracle of operator precedence.
[Answer]
# Python 2, 132 Bytes
Certainly not the most elegant solution, and it's barely shorter than C, but it's a start.. Input is taken comma-separated.
```
k,n=input()
k=[`['|-'[int(x)]for x in'{0:064b}'.format(k)]`[2::5][i*8:i*8+8]*n for i in range(8)]*n
for j in range(n):print k[j][:n]
```
[Answer]
# C, 160 135 bytes
```
i;main(s,v)char**v;{s=atoi(v[2]);for(;i++<s*s+s;)putchar(i%(s+1)?strtoull(v[1],0,10)&1ull<<63-(i/(s+1)*8+(i%(s+1)-1)%8)%64?45:'|':10);}
```
Some more golfing can be done here and need an explanation, but I don't have time at the moment :)
## Ungolfed:
```
i;
main(s,v)
char**v;
{
s=atoi(v[2]);
for(;i++<s*s+s;)
putchar(i%(s+1) ? /* print dash or pipe, unless at end of row, then print newline */
/* Calculating which bit to check based on the position is the tough part */
strtoull(v[1],0,10) & 1ull << 63-(i/(s+1)*8+(i%(s+1)-1)%8)%64 ? /* If bit at correct index is set, print dash, otherwise pipe */
45 /* dash */
: '|' /* pipe */
: 10); /* newline */
}
```
[Answer]
# Pyth, ~~31~~ 30 bytes
```
L<*QbQjbyyMcs@L"|-".[Z64jvz2 8
```
The input should be on two lines, ***W*** then ***S***.
[Try it here](http://pyth.herokuapp.com/?code=L%3C*QbQjbyyMcs%40L%22%7C-%22.%5BZ64jvz2+8&input=3732582711467756595%0A10&debug=0)
## Explanation
```
L # define y(b):
*Qb # b, repeated Q (the second input) times
< Q # cut to length Q
jvz2 # convert the first input to binary
.[Z64 # pad with 0's to length 64
@L"|-" # map the digits to the appropriate character
s # convert the list of characters to a string
c 8 # chop into 8 strings
yM # extend each string to the correct size
y # extend the list of strings to the correct size
jb # join with newlines
```
] |
[Question]
[
## Challenge
>
> In this task you would be given an integer N (less than 106), find the minimum way in which you could sum to N using only Fibonacci numbers - this partition is called [Zeckendorf representation](https://en.wikipedia.org/wiki/Zeckendorf's_theorem).
>
>
>
You could use any Fibonacci number more than once and if there is more than one representation output any.
For example if the input is **67** then one possible output could be using the Fibonacci numbers **1,3,8,55** which is also the minimum number of Fibonacci numbers that could be used to get the sum **67**.
The input N is given on a single line, the inputs are terminated by EOF.
**Examples**
Given in the format `input: output`
```
0: 0
47: 34+13
3788: 2584+987+144+55+13+5
1646: 1597+34+13+2
25347: 17711+6765+610+233+21+5+2
677: 610+55+8+3+1
343: 233+89+21
3434: 2584+610+233+5+2
```
**Constraints**
* The number of inputs would not exceed 106 values.
* Your program should not run more than 5 seconds for all inputs.
* You can use any language of your choice.
* Shortest solution wins!
[Answer]
## Motorola 68000 assembly - 34 bytes
*(GNU assembler syntax)*
```
| short min_fib_partition(long N asm("%d2"), long *out asm("%a0"))
min_fib_partition:
| Generate Fibonacci numbers on the stack (-1, 1, 0, 1, 1, 2, 3, ..., 1134903170).
moveq #-1, %d0 | A = -1
moveq #1, %d1 | B = 1
generate_loop:
move.l %d0, -(%sp) | Push A to the stack.
exg.l %d0, %d1 | A' = B
add.l %d0, %d1 | B' = A + B
bvc.s generate_loop | Stop when signed long overflows.
| Go back up the stack, partitioning N using the greedy algorithm.
moveq #0, %d0 | Initialize return value (number of terms).
subtract_loop:
move.l (%sp)+, %d1 | Pop a Fibonacci number F off the stack.
cmp.l %d1, %d2 | If N < F, continue to smaller Fibonacci number.
blt.s subtract_loop
addq.w #1, %d0 | Increment the term count.
move.l %d1, (%a0)+ | Append F to the output array.
sub.l %d1, %d2 | N -= F
bne.s subtract_loop | Continue if N has not yet reached zero.
| Clear the stack by searching for that -1.
clear_stack_loop:
tst.l (%sp)+
bge clear_stack_loop
done:
rts
```
**36 → 34:** Made Fibonacci generator stop on overflow rather than by counting, and fixed the `0` case so it outputs `[0]` rather than `[]`. However, passing a negative `N` crashes now.
The comment at the top is the C prototype of this function, using a [language extension](http://tigcc.ticalc.org/doc/gnuexts.html#SEC99a) to identify what parameters go where (by default, they go on the stack).
My [TI-89](http://en.wikipedia.org/wiki/TI-89_series), with its 10MHz processor, takes 5 minutes to run this function on 1 – 1,000,000.
Although the machine code is (currently) fewer bytes than the GolfScript solution, it would probably be unfair to accept this as the shortest solution because:
* Machine code is normally not counted as "source code". Unlike source code, machine code usually has high symbol complexity and, more importantly, is unprintable. See "[Should executable binaries be considered a reasonable solution for code-golf?](http://meta.codegolf.stackexchange.com/questions/260/should-executable-binaries-be-considered-a-reasonable-solution-for-code-golf)".
* This solution only takes a single number as input, rather than multiple inputs.
* This solution is a function, not a program.
If you have a TI-89/92/V200, you can download the full project here (outdated):
<https://rapidshare.com/files/154945328/minfib.zip>
Good luck coaxing RapidShare to give you the actual file. Does anyone know of a good host for files this big? 8940 is an awful lot of bytes.
[Answer]
## Javascript (142)
Only handles single input at a time. Because multi-line input is useless for JavaScript.
```
k=n=prompt(f=[a=b=1])|0;while((b=a+(a=b))<n)f.push(b);for(i=f.length,g=[];i--;)if(f[i]<=k)g.push(f[i]),k-=f[i];alert(n+': '+(n?g.join('+'):0))
```
<http://jsfiddle.net/EqMXQ/>
[Answer]
# C, 244 characters
```
#define P printf
int f[30];int main(){f[28]=f[29]=1;int i=28;for(;i>0;--i)f[i-1]=f[i+1]+f[i];int x;while(scanf("%i",&x)!=-1){P(x?"%i: ":"0: 0\n",x);if(x>0){int i=0,a=0;while(x>0){while(f[i]>x)++i;if(a++)P("+");P("%i",f[i]);x-=f[i];}P("\n");}}}
```
With whitespace:
```
#define P printf
int f[30];
int main(){
f[28] = f[29] = 1;
int i = 28;
for(; i > 0; --i) f[i-1] = f[i+1] + f[i];
int x;
while(scanf("%i",&x) != -1) {
P(x ? "%i: " : "0: 0\n",x);
if(x > 0) {
int i = 0, a = 0;
while(x > 0) {
while(f[i] > x) ++i;
if(a++) P("+");
P("%i",f[i]);
x -= f[i];
}
P("\n");
}
}
}
```
This program will read numbers out of standard input and write to standard output.
[Answer]
## Golfscript, 43 chars
```
~]{:|': '[{0 1{|>!}{.@+}/;|1$-:|}do]'+'*n}%
```
I think this can probably be reduced by 3 to 5 chars with more effort. E.g. the unfold to then throw away the array feels wasteful.
[Answer]
## F# - 282 252 241 characters
```
let mutable d=int(stdin.ReadLine())
let q=d
let rec f x=if x<2 then 1 else f(x-2)+f(x-1)
let s x=
d<-d-x
x
printf"%d: %s"q (Core.string.Join("+",[for i in List.filter(fun x->x<d)[for i in 28..-1..0->f i]do if d-i>=0 then yield s i]))
```
[Answer]
## Python - 183 Chars
Majority of the code is handling multiple inputs :(
```
f=lambda a,b,n:b>n and a or f(b,a+b,n)
g=lambda n:n>0and"%d+%s"%(f(0,1,n),g(n-f(0,1,n)))or""
try:
while 1:
n=input()
print "%d: %s"%(n,n<1and"0"or g(n).strip("+"))
except:0
```
[Answer]
# Mathematica 88
```
n = RandomInteger[10000, 10];
Print[k=#,For[i=99;l={},k>0,If[#<=k,k-=#;l~AppendTo~#]&@Fibonacci@i--];":"l~Row~"+"]&/@n
```
Example of output
```
3999: 2584+987+377+34+13+3+1
9226: 6765+1597+610+233+21
7225: 6765+377+55+21+5+2
9641: 6765+2584+233+55+3+1
6306: 4181+1597+377+144+5+2
4507: 4181+233+89+3+1
8848: 6765+1597+377+89+13+5+2
6263: 4181+1597+377+89+13+5+1
2034: 1597+377+55+5
6937: 6765+144+21+5+2
```
[Answer]
EXCEL : 89 chars in unique code:

[Answer]
**Scala - 353 chars** (100 chars for handling multiple inputs)
```
def h(m:Int){lazy val f={def g(a:Int,b:Int):Stream[Int]=a #:: g(b,a+b);g(0,1);};if(m==0)println(m+": "+m)else{var s=0;var t= f.takeWhile(_ <= m);var w="";while(s!= m){s+=t.last;w+=t.last+"+";t=t.takeWhile(_<=m-s);};println(m+": "+w.take(w.length-1))}}
Iterator.continually(Console.readLine).takeWhile(_ != "").foreach(line => h(Integer.parseInt(line)))
```
[Answer]
# Python 3 (170 chars)
```
while 1:
s=input()
if not s:break
s=n=int(s);f=[1];t=[]
while f[-1]<n:f+=[sum(f[-2:])]
for i in f[::-1]:
if s>=i:s-=i;t+=[i]
print(n,'=','+'.join(map(str,t))or 0)
```
Multiline input, stop on empty line
[Answer]
# C, 151 characters
```
main() {int i=1,n,f[30]={1,1};for(;i++<30;)f[i]=f[i-1]+f[i-2];while(scanf("%d",&n))for(i=30;;--i)if(f[i]<=n){printf("%d\n",f[i]);if(!(n-=f[i]))break;}}
```
readable version:
```
main() {
int i=1,n,f[30]={1,1};
for(;i++<30;)f[i]=f[i-1]+f[i-2];
while(scanf("%d",&n))
for(i=30;;--i)
if(f[i]<=n) {
printf("%d\n",f[i]);
if (!(n-=f[i])) break;
}
}
```
[Answer]
# R, 170
```
x=scan();Filter(function(i)cat(unlist(Map(function(d)if(i>=d&&i){i<<-i-d;d},rev(lapply(Reduce(function(f,x)c(f[2],sum(f)),1:94,c(0,1),F,T),head,n=1)))),sep='+',fill=T),x)
```
Handles multiple inputs and cat's the result to STDOUT
```
> x=scan();Filter(function(i)cat(unlist(Map(function(d)if(i>=d&&i){i<<-i-d;d},rev(lapply(Reduce(function(f,x)c(f[2],sum(f)),1:94,c(0,1),F,T),head,n=1)))),sep='+',fill=T),x)
1: 100
2: 200
3: 300
4:
Read 3 items
89+8+3
144+55+1
233+55+8+3+1
numeric(0)
>
```
[Answer]
# R (460 chars)
Another version using R.
Reading from file "input", output to the file "output"
```
d=as.list(as.integer(scan("input","",sep="\n")));n=36;f=rep(1,n);for(i in 3:n){f[i]=f[i-2]+f[i-1]};d2=lapply(d,function(x){a=vector("integer");i=1;while(x>0){id=which(f>=x)[1];if(x==f[id]){x=x-f[id];a[i]=f[id]}else{x=x-f[id-1];a[i]=f[id-1]}i=i+1}a});d=mapply(c,d,d2,SIMPLIFY=0);for(i in 1:length(d)){t=d[[i]];l=length(t);if(l==1){d[[i]]=paste(t[1],t[1],sep=": ")}else{d[[i]]=paste(t[1],": ",paste(t[2:l],collapse="+"),sep="")}}lapply(d,write,"output",append=1)
```
"input" example
```
0
47
3788
1646
25347
677
343
3434
```
"output" example
```
0: 0
47: 34+13
3788: 2584+987+144+55+13+5
1646: 1597+34+13+2
25347: 17711+6765+610+233+21+5+2
677: 610+55+8+3+1
343: 233+89+21
3434: 2584+610+233+5+2
```
More readable version:
```
dt <- as.list(as.integer(scan(file = "input", what = "", sep = "\n")))
n <- 36
fib <- rep(1, n)
for(i in 3:n){fib[i] <- fib[i-2] + fib[i-1]}
dt2 <- lapply(dt, function(x){answ <- vector(mode = "integer")
i <- 1
while(x > 0){
idx <- which(fib>=x)[1]
if(x == fib[idx]){
x <- x - fib[idx]
answ[i] <- fib[idx]
}
else {
x <- x - fib[idx-1]
answ[i] <- fib[idx-1]
}
i <- i + 1
}
answ})
dt <- mapply(FUN = c, dt, dt2, SIMPLIFY = FALSE)
for(i in 1:length(dt)){
t1 <- dt[[i]]
t1.len <- length(t1)
if(t1.len == 1){
dt[[i]] <- paste(t1[1], t1[1], sep=": ")
} else {
dt[[i]] <- paste(t1[1], ": ", paste(t1[2:t1.len], collapse = "+"), sep="")
}
}
lapply(dt, write, "output", append=TRUE)
```
[Answer]
## D (196 chars)
Run with `rdmd --eval=…`. This conveniently hides the boilerplate of `import x, y, z;` and `void main() {…}`:
```
int f(int i){return i-->1?f(i--)+f(i):i+2;}int n;foreach(x;std.stdio.stdin.byLine.map!(to!int))writeln(x,": ",x?n=x,reduce!((r,i)=>f(i)<=n?n-=f(i),r~="+"~f(i).text:r)("",29.iota.retro)[1..$]:"0")
```
[Answer]
**Using Java**
```
package org.mindcraft;
import java.util.Scanner;
public class Fibbo {
public static void main(String[] args) {
String number = null;
int tmp, sum;
int i = 1, j = 1;
Scanner in = new Scanner(System.in);
number = in.nextLine();
String[] arr = number.split(" ");
for (int it = 0; it < arr.length; it++) {
tmp = Integer.parseInt(arr[it]);
String value = tmp+" : ";
while (tmp > 0) {
i = 1;
j = 1;
for (int k = 0; k < 10000; k++) {
sum = i + j;
if (sum > tmp) {
//if (value == null) {
char ch=value.charAt(value.length()-2);
if(ch==':')
{
value = value+" "+ j + "";
} else {
value = value + " + " + j;
}
tmp = tmp - j;
break;
}
i = j;
j = sum;
}
}
System.out.println(value);
}
}
}
```
] |
[Question]
[
Two or more positive integers are said to be "[friendly](https://en.wikipedia.org/wiki/Friendly_number)" if they have the same "abundancy". The abundancy of an positive integer \$n\$ is defined as $$\frac {\sigma(n)} n,$$ where [\$\sigma(n)\$](https://en.wikipedia.org/wiki/Divisor_function) is the sum of \$n\$'s divsors. For example, the abundancy of \$30\$ is \$\frac {12} 5\$ as
$$\frac {\sigma(30)} {30} = \frac {1 + 2 + 3 + 5 + 6 + 10 + 15 + 30} {30} = \frac {72} {30} = \frac {12} 5$$
Because \$140\$ has the same abundancy (\$\frac {12} 5\$), we know that \$30\$ and \$140\$ are "friendly". If a number does not have the same abundancy of any other numbers, it is termed a "solitary" number. For example, \$3\$'s abundancy is \$\frac 4 3\$ and it can be shown that no other number has an abundancy of \$\frac 4 3\$, so \$3\$ is solitary.
We can partition the positive integers into "clubs" of friendly numbers. For example, the [perfect numbers](https://en.wikipedia.org/wiki/Perfect_numbers) form a club, as they all have abundancy \$2\$, and solitary numbers each form a club by themselves. It is currently unknown whether or not infinitely large clubs exist, or if every club is finite.
---
You are to take two positive integers \$n\$ and \$k\$, and output \$k\$ numbers in \$n\$'s club. You may assume that \$k\$ will never exceed the size of the club (so \$k\$ will always be \$1\$ for solitary numbers etc.). You may output any \$k\$ numbers, so long as they all belong to \$n\$'s club (note that this means you do not always have to output \$n\$). You may input and output in any [reasonable format and manner](https://codegolf.meta.stackexchange.com/q/2447) - keep your golfing in your code, not your I/O.
**A few remarks**
* You may assume that \$n\$ is known to be either friendly or solitary - you will never get e.g. \$n = 10\$.
* It [has been shown](https://oeis.org/A014567) that if \$\sigma(n)\$ and \$n\$ are co-prime, \$n\$ is solitary, and so, in this case, \$k = 1\$.
* Your answers may fail if values would exceed the limit of integers in your language, but only if that is the *only* reason for failing (i.e. if your language's integers were unbounded, your algorithm would never fail).
* I am willing to offer a bounty for answers that also include a program that aims to be quick, as well as correct. A good benchmark to test against is \$n = 24, k = 2\$ as the smallest friendly number to \$24\$ is \$91963648\$
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code in each language wins.
---
## Test cases
Note that the outputs provided are, in some cases, sample outputs, and do not have to match your outputs
```
n, k -> output
3, 1 -> 3
6, 4 -> 6, 28, 496, 8128
8, 1 -> 8
24, 2 -> 24, 91963648
84, 5 -> 84, 270, 1488, 1638, 24384
140, 2 -> 30, 140
17360, 3 -> 210, 17360, 43400
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes
*-1 thanks to @Jonathan Allan.*
```
1,Æs×ṭʋE¥#
```
[Try it online!](https://tio.run/##y0rNyan8/99Q53Bb8eHpD3euPdXtemip8n@gkInBf2MA "Jelly – Try It Online")
### Explanation
Jelly's `#` parsing is *really* confusing. `#` doesn't consume the first link `1`, since it's a nilad. (This, as it turns out, works really weirdly if you use chain separators; the equivalent code would be `ø1ð,,Æs$ÆḊ¬ð#`.)
The code is essentially parsed from postfix notation to the following, where `[]` represent chains:
```
[1 #(filter=¥[ʋ[, Æs × ṭ] E])]
```
This chain is then applied to the arguments `(n, k)`. The value is first initialized to `n`.
The `#` operation is then used as a dyad, as if it's the `+` in `1+`. It receives `(1, n)` as arguments and starts passing those to its `filter` chain, incrementing the `1` until `k` matches are found. (Since `#` only consumed one link, the last command-line argument is used as the count.)
The filter chain then does this, where `x` is the candidate number:
* `,`: make pair `[x, n]`.
* `Æs`: compute `[sigma(x), sigma(n)]`.
* `ṭ`: make pair `[n, x]`.
* `×`: elementwise multiply, i.e. `[sigma(x)*n, sigma(n)*x]`.
* `E`: see if the values equal. This is pretty clearly true iff `x/sigma(x)=n/sigma(n)`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes
```
↑f¤=oṁ\Ḋ⁰N
```
[Try it online!](https://tio.run/##ASEA3v9odXNr///ihpFmwqQ9b@G5gVzhuIrigbBO////MTQw/zI "Husk – Try It Online")
```
↑f¤=S/oΣḊ⁰N
f N # filter the natural numbers by
¤ # combin: '¤fgxy' means 'f(g x)(g y)', where
= # f is '=' equals
oṁ\Ḋ # g is 'oṁ\Ḋ', which parses as:
o # compose
ṁ # map this & sum the results:
\ # reciprocal
Ḋ # over each divisor of argument
⁰ # x is the last input argument
# y is the number being filtered (so, each of the natural numbers)
↑ # finally, from the filtered numbers, take
# the first n equal to the other input argument.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~90~~ 79 bytes
```
->n,k{w=0;g=->w{(1..w).sum{|x|w%x<1?x:0}};k.times{g[w+=1]*n==g[n]*w||redo;p w}}
```
[Try it online!](https://tio.run/##BcHdDkAgGADQV3Fj89uKO/l4kNaNoZmJhX1Z9ew5x7zTF1eI9aCr3SFQrqAe0GWMEMzJ/R7OW4@p7dloOxoC38mzHcvtlMASmCw0gBJaFui9WeaTXwmGEFfR0qqR8Qc "Ruby – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~91 89 88~~ 85 bytes
*Saved 3 bytes thanks to @tsh*
Expects `(n)(k)`. Prints the numbers.
```
n=>k=>{for(g=x=>{for(q=d=x;--d;)x%d?0:q+=d},i=0;k;q*++i+~g(i)*q*n||print(i)|k--)g(n)}
```
[Try it online!](https://tio.run/##RZDdaoMwFMfvfYpzsUFS4xqTzGYLcVd7ChEqFa0LuOpKEdS9ujtW63Jx@P0/Qjj5ym7Zz6mtLtfgpqfCTrWNnY374rslpe1WamxuOxMEuaHdc/7B3xvf5iOrLDfONDvfr/zfklR01@zqYbi0VX1FNbggoCWp6TiZxANIYD6SQQgpg/0e5GZGDNRqIgqN8g1Bh0JvHf1/cTO1YvD6MJHFgWNL6bkbSZxCSa3WdqgwFI@370V@j8KDjFBKSGGORDhni6ek4txLvRf8hs/sdCYkgZqBg5SCjaGHZdljAk99PTKcboT0SA0UuDhxCEsDYaTTHw "JavaScript (V8) – Try It Online")
### Commented
```
n => // n = positive integer
k => { // k = required number of solutions
for( // main loop:
g = x => { // g is a helper function loading sigma(x) in q
for( // loop:
q = d = x; // start with q = d = x
--d; // decrement d and stop when d = 0
) x % d ? 0 // add d to q if d is a divisor of x
: q += d //
}, // end
i = 0; // start with i = 0
k; // stop when k = 0
q * ++i + // increment i and test whether:
~g(i) * q * n || // sigma(n) * i = sigma(i) * n
print(i) | k-- // if so, print i and decrement k
) g(n) // load sigma(n) in q
} // end
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
µN‚ÂÑO*ËD–
```
Inputs in the order \$k,n\$, outputs the results on separated newlines to STDOUT.
Port of [*@PurkkaKoodari*'s Jelly answer](https://codegolf.stackexchange.com/a/246135/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//0Fa/Rw2zDjcdnuivdbjb5VHD5P//TbjMAA) or [verify almost all test cases](https://tio.run/##yy9OTMpM/V9WGZSg5JlXUFpSbKWQbXt4v04ekFBQ0uFS8i8tgQgr6VQmhP4/tNUv4lHDrMNNhyf6ax3udnnUMPl/7aFt9nqHtv6PjjbUMY7ViTbRMQOShjoWQNJUx8IESBnpGJoYAGljHUNzYzMDsIiRSWwsAA) (times out for `2,24`).
**Explanation:**
```
µ # Loop while `¾` is not equal to the first (implicit) input-integer:
# (`¾` is 0 by default)
N‚ # Pair the loop-index with the second (implicit) input-integer
 # Bifurcate it; short for Duplicate & Reverse copy
Ñ # Map both values in the reversed copy to a list of its divisors
O # Sum those inner lists of divisors
* # Multiply it to the pair
Ë # Check if both values in the pair are the same
D # Duplicate this check
– # Pop, and if this is truthy: print `N` with trailing newline
# (implicit - Pop, and if this is truthy: increase `¾` by 1)
```
[Answer]
# [R](https://www.r-project.org), ~~74~~ 72 bytes
```
\(n,k,s=\(m,l=1:m)mean(l*!m%%l))while(k)s(F<-F+1)==s(n)&&{show(F);k=k-1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGGtKLM1LyUnMr45JzSJAUb3aWlJWm6Fjc9YjTydLJ1im1jNHJ1cmwNrXI1c1MT8zRytBRzVVVzNDXLMzJzUjWyNYs13Gx03bQNNW1tizXyNNXUqosz8ss13DSts22zdQ1rIeZtRrFGw8JEx1QTIrNgAYQGAA)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 55 bytes
```
f(n,k,i)=while(k,sigma(n)/n-sigma(i++)/i||k-=!print(i))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN83TNPJ0snUyNW3LMzJzUjWydYoz03MTNfI09fN0IcxMbW1N_cyammxdW8WCosy8Eo1MTU2o9vLEgoKcSo1EBV07BbBcmoaSZ55VTJ5qio6CakpMnn9pCZCnpKOQGG0YCyKNYjWtFdI0kLg6CtHRxjogbrSZjgmIsoDwLEx0TEG0oYmBjhGYYW5sZqBjHBsLtR7mCwA)
This is slow. It tries every positive integer one by one until it finds `k` answers. It takes 3 minutes to calculate `f(24, 2)` on my computer.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
NθNη≔⁰ζW‹ⅉη«≦⊕ζ¿⁼×ζΣΦ⊕θ∧κ¬﹪θκ×θΣΦ⊕ζ∧κ¬﹪ζκ⟦Iζ
```
[Try it online!](https://tio.run/##dY6xCsIwFEVn@xVvfIEIKm5OIgqCLYIuIg6xjTY0TZomUaj47TGoiIO@7cC95928ZG2umQxhqRrvMl8feYuGTJJvLiNPrRVnhQMKXaRrKSQHXHFrcYeEQkkI3JJeypp3cKnyltdcOV68Kj1xApwbz6TFrai5xY7Cxte4ENLFJ1@FOIDCVBVYUci0w1QXXmo0FCryPAovg/lr6H4auo8hzl23Qjncz5h1MX6IE@8hDMeDZBT6F/kA "Charcoal – Try It Online") Link is to verbose version of code. Don't try any of the other test cases on TIO because it's too slow. Explanation:
```
NθNη
```
Input `n` and `k`.
```
≔⁰ζ
```
Start enumerating the club.
```
W‹ⅉη«
```
Repeat until `k` numbers have been output.
```
≦⊕ζ
```
Increment the number to be tested.
```
¿⁼×ζΣΦ⊕θ∧κ¬﹪θκ×θΣΦ⊕ζ∧κ¬﹪ζκ
```
If it's in the club, then...
```
⟦Iζ
```
... output it on its own line.
Save 2 bytes by dropping support for `n=1`:
```
NθNη≔¹ζW‹ⅉη«≦⊕ζ¿⁼×ζΣΦθ∧κ¬﹪θκ×θΣΦζ∧κ¬﹪ζκ⟦Iζ
```
[Try it online!](https://tio.run/##bY7LCsIwEEXX9itmOYEIKu5ciSgUrAi6EXER22iCafpIohDx22NrRRS8u3OZw9xUsDotmAoh1qWzK5cfeY0VmUTfLBqeGiPPGocUfEM3IRUHXHJjcIeEgiAE7lEvYeX7MNZpzXOuLc86pSdPgPPKMWVwK3Nu0FPYuBwXUtn2KYWpzvBCYVVYTIrMqaItL@QVCp1U/Uj@n@Q/UjNqXUttcT9jxqInh2bII4TheBCNQv@qng "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Desmos](https://desmos.com/calculator), 122 bytes
```
o->join(o,a),T->T+sign(k-o.length)
n=\ans_0
k=\ans_1
o=[]
T=0
a=\{f(T)=f(n):[T],[]\}
f(K)=\sum_{N=1}^K\{\mod(K,N)=0,0\}N/K
```
Input in the first two lines of the graph (`n` on the first line, `k` on the second)
Output is the value of `o` after the program has completely ran (which is when `T` stops incrementing)
[Try It On Desmos!](https://www.desmos.com/calculator/tn8dbf3sl8)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/yoankvixma)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
µN‚ÑzOËD–
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0Fa/Rw2zDk@s8j/c7fKoYfL//yZcZgA "05AB1E – Try It Online")
Uses that simplification that the "sum of divisors of x, divided by x" is just equal to "sum of reciprocals of divisors of x".
Apart from this, the rest of the [05AB1E](https://github.com/Adriandmen/05AB1E) nuts & bolts are shamefully stolen from [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/246148/95126).
[Answer]
# [Factor](https://factorcode.org/) + `lists.lazy math.primes.factors math.unicode`, 78 bytes
```
[ [ dup divisors Σ swap / ] tuck call '[ @ _ = ] 1 lfrom swap lfilter ltake ]
```
[Try it online!](https://tio.run/##PZBBS8QwFITv/RVz87TVbOu6KIo38eJFPJVFQprQ0Ncm5KVKXfbX@H/8SzXdLn2nb4ZhGJ6RKrowfby/vr3cQzI7xWh16DWhk7HJfbCd5tycc7x4Q2@Vq/VZgJvBGNIwYQRZjpyT/LkgfNAxjqmjj3jIsmOGdEcIFDhduMRuZYH9yrfYl6vYQpQ3qyog7ordrE/ZVKFCPXjU9svyPPHvF/wtPa5xQBxUCyWJcFXhGZ94TKYAmeC6JUXGUtQBFGWrcUh18/InGYIckae0cp13rJffbLRUzfQP "Factor – Try It Online")
## Explanation
Naive algorithm. Takes input as `k n` and returns a `k`-long lazy list containing numbers in the same club as `n`.
```
! 4 6
[ dup divisors Σ swap / ] ! 4 6 [ dup divisors Σ swap / ] (push abundancy function)
tuck ! 4 [ dup divisors Σ swap / ] 6 [ dup divisors Σ swap / ]
call ! 4 [ dup divisors Σ swap / ] 2
'[ @ _ = ] ! 4 [ dup divisors Σ swap / 2 = ]
1 lfrom ! 4 [ dup divisors Σ swap / 2 = ] L{ 1 2 3 ... }
swap ! 4 L{ 1 2 3 ... } [ dup divisors Σ swap / 2 = ]
lfilter ! 4 L{ 6 28 496 8128 ... }
ltake ! L{ 6 28 496 8128 }
```
[Answer]
# Python, 116 bytes
```
def f(n,k):
x=lambda n:sum([i for i in range(1,n+1)if n%i==0])/n;i=1
while k:
if x(i)==x(n):print(i);k-=1
i+=1
```
Pretty basic but painfully slow. Calculates the abundancy of each integer from 1 to `n` using the `x` function until the chosen number of matches have been found.
[Answer]
# [Python 3](https://docs.python.org/3/), 109 bytes
```
a=lambda n:sum(-~i*(n%-~i<1)for i in range(n))/n
def f(n,k,i=1):
if a(n)==a(i):print(i);k-=1
f(n,k*k/k,i+1)
```
[Try it online!](https://tio.run/##JYoxDoMwDAD3vMJLJZuCUMSW1o9xBWmtgEGBDl369RCJ6U66237HZ7WhFOFZltcoYGH/Ltj9tUG7VTw9xTWDghpksfeERtSbG6cIEa1NrbKn4EAjSG3Mgkphy2pHlUfq2LvrbFJf77unUk4 "Python 3 – Try It Online")
A little longer one-liner,
```
def f(n,k,i=1,a=lambda n:sum(-~i*(n%-~i<1)for i in range(n))/n):print(end=(f"{[i,k:=k-1][0]}\n"if a(n)==a(i)else""));f(n,k*k/k,i+1)
```
Both functions always ends in a error(division by 0) after printing the answers.
[Answer]
# [Haskell](https://www.haskell.org), 85 bytes
```
f=fromIntegral
a n=f(sum[y|y<-[1..n],n`mod`y==0])/f n
n!k=take k[x|x<-[1..],a n==a x]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bU_LCoJAFN37FXeghQNN-epBNO2DoEW0EsGBnAp1DB1JwT9p4yb6ir6gL-hv8oGrZnW453U5j9eFZWEQRfWbENARhtUKtkIC2QzgNug9c8nJ8nvklKdJ3DDBOWWRxkBQrmd57JZVuSauOZkIbyz8ODn5JaWGh6cchCZQSCULAwjdoip6nzduw5RBMZR_YnYV3f896FjrLgqnRAO45fIg052AEWSX5A66jUys4ufIUfLL1t8s_FcsB1nqiINmSsF0jDaibDMX9txANu4n1XWPPw)
`!` is the infix function that implements the friendly club function.
Some testcases are commented out because this is very slow.
-3 bytes from caird.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 99 bytes
```
d;c;s(n){for(d=c=n;--d;)c+=n%d?0:d;d=c;}i;f(n,k){for(i=1;k;++i)s(n)*i-n*s(i)?:printf("%d ",i,--k);}
```
[Try it online!](https://tio.run/##bZThjqIwEMe/71NMSEyolizQAmqX88Nln2I1G1Nwl3BXFyE5c4ZXP28qFXCLURxnfjPzZ@govQ8pr9dMSFG7ilwOx5ObpTJVwvMyQeQiVbNs468zgV7RFuLgKlp2XJEGohSLRUF06rzw1Lx2C7JZf50K1RxcZ5aBQwvqeSUR7RV98HtfKJfA5QnwpR1NXjfv6m0HKVwYhZjCEt@cQsB9vCQsxq@Qt@Ixo@wyAgoapRAhRAELhCMyP3/lssmzwJSfCIVdCNuG2JevdP8gXE6QrCOnQtyEUEqYaNV8icWCmC21dLbkEzmR0XTD/Qkg7oAwGMbAGfen0MSg2H8VrGIW85HKeY91VD8UOgxhMNlg8sGMBjMezGRCyv1R1sXf/Hhw@2bk2Xjmg4vCNyq0qdCmmE0xm@I2xW0qsqnIpmKbim0qsamEmBHJo6obkJ/70xyvuSzzUzcnZ3t@Dbfn1U/8RA6F8W/mmGzcNXD1lAuV5WdM84UxX76LsDUQ8CAQgFuqM8itYLd@92ensKJZwxuzEw/h8h4urfCw5xRw170fuO6gKOC694z@v3hw3I7Lu246OjQTjfHgjhiL6IdSdQOpcBhYVt9pRUZ3@KCznmWosNroSa@drXo11ddaeP5W7UY6W@s2t8ox8fapvf6Th1/7j/rq/fkP "C (gcc) – Try It Online")
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 112 bytes
Golfed version. [Try it online!](https://tio.run/##XctLC4JAFIbhfb/CZekB85JFNlDQJigICloMg4x5O5ijTNZG9K9PuhCk5fec9xS8zuKC1/jkKqEiAC0P2JaoSxl9XjFtOISAxAJJmrYFTo74xXcpb5gWnFogmCn8R4Z9eo5FWmd7ucsh/M@QmeifEsoJCUF2h6qKRXQvO2Q@GgbzJVOzhDqgWcw0rxJF3U8PNHcyN9PrXE@o7YJmj6IvhqSX1eTFcpeTZIC14/XkjKR@)
```
Module[{a,b,i=1,r={}},a=DivisorSigma[1,n]/n;While[Length@r<k,b=DivisorSigma[1,i]/i;If[a==b,r~AppendTo~i];i++];r]
```
Ungolfed version. [Try it online!](https://tio.run/##bY27asNAEEX7/YpbJvKCLEt@EEdFwI3BgUAMKZbFrKPXoGhl1koao29XZgUJKlzNzD1zZhrTVXljOvo0w1Aoe5KoTxpPKV7b7PsrVzcjcZYgpIgkHJdb30sBGG539EPX1r1T2RjF2OrQbpl9VMTqIbdlVymn8YzaKzjfcUiH5B3sC8U3U//t5XLJbXZslfNcj5hmMy5j74QWQhQqloh0GL45sh2PK4lkMm6m9CEo1CKRWPwlwaNf4WQ5UaJkPlnxwTpecRT/R2IYfgE)
```
f[n_, k_] := Module[{a, b, i = 1, r = {}},
a = DivisorSigma[1, n]/n;
While[Length[r] < k,
b = DivisorSigma[1, i]/i;
If[a == b, AppendTo[r, i]];
i++
];
r
]
f[3, 1]//Print
f[6, 4]//Print
f[8, 1]//Print
(*f[24, 2]//Print*)
f[84, 5]//Print
f[140, 2]//Print
f[17360, 3]//Print
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@â x÷U ¶Xâ x÷X}jV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=QOIgePdVILZY4iB491h9alY&input=NiA0)
] |
[Question]
[
Let's consider the following sequence:
$$9,8,7,6,5,4,3,2,1,0,89,88,87,86,85,84,83,82,81,80,79,78,77,76,75,74,73,72,71...$$
This is the sequence of \$9\$'s complement of a number: that is, \$ a(x) = 10^d - 1 - x \$ where \$ d \$ is the number of digits in \$ x \$. ([A061601](https://oeis.org/A061601) in the OEIS).Your task is to add the first \$n\$ elements.
### Input
A number \$n∈[0,10000]\$.
### Output
The sum of the first \$n\$ elements of the sequence.
### Test cases
```
0 -> 0
1 -> 9
10 -> 45
100 -> 4050
1000 -> 408600
10000 -> 40904100
```
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
f=function(n)sum(10^nchar(1:n-1)-1:n)
```
[Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jT7O4NFfD0CAuLzkjsUjD0CpP11BTF0hp/k/TMNTkAhIGEBJGwWkDzf8A "R – Try It Online")
**note**
I left out the check for 0 as I do not think it is part of the sequence as refered to A061601 in the OEIS reference. Adding the check would result in the exact same answer of Giuseppe, which would surely be preferable including the correct answer including 0.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
FromDigits[9-IntegerDigits@--n]~Sum~{n,#}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277360oP9clMz2zpDjaUtczryQ1PbUIwnfQ1c2LrQsuza2rztNRrlX7H1CUmVeioO@Qru9QbaBjqGMIJAzAGEIY1P7/DwA "Wolfram Language (Mathematica) – Try It Online")
-2 bytes from att
[Answer]
# [Julia 1.0](http://julialang.org/), ~~43~~ ~~38~~ 30 bytes
```
!n=n>0&&10^ndigits(~-n)-n+!~-n
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPNs/OQE3N0CAuLyUzPbOkWKNON09TN09bEUj/L0ktLolPTixOLVawVYg20DHUMQQSBmAMIQxiuTT0FBHq9GxtgeosdUxMdUwMTA2AhIWZAYiyNDABqo/V1KuxKyjKzCvJyfsPAA "Julia 1.0 – Try It Online")
-5 dingledooper, -8 MarcMush
[Answer]
# [R](https://www.r-project.org/), 39 bytes
```
function(n)sum(10^nchar(1:n-1)-1:n)*!!n
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPs7g0V8PQIC4vOSOxSMPQKk/XUFMXSGlqKSrm/S9OLCjIqdQwsDI00EnT5EoDqjQwgNEGmv8B "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
FNg°<N-O
```
[Try it online](https://tio.run/##yy9OTMpM/f/fzS/90AYbP13///8NDQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVLfKZL7X83v/RDG2z8dP3/1@r8jzbQMdQxBBIGYAwhDGIB).
**Explanation:**
```
F # Loop `N` in the range [0, (implicit) input):
Ng # Push the length of `N`
° # Take 10 to the power this length
< # Decrease it by 1
N- # Decrease it by `N`
O # Take the sum of the values on the stack
# (after which the last sum is output implicitly as result -
# or the implicit input if it was 0 and we never entered the loop)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 8 bytes
No, I'm not Jo King. I found another use for the `r` flag!!!
>
> It happens once in a blue moon on average
>
>
>
Okay, yes, I said that
```
ʁƛL↵-‹;∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwiyoHGm0zihrUt4oC5O+KIkSIsIiIsIjEwIl0=)
[Flagless 9 bytes](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgcabTOKGtW4t4oC5O+KIkSIsIiIsIjEwIl0=)
## Explanation
So the `r` flag is basically a reverser, which reverses the order of the arguments. That makes it hard to use for long programs, but for short ones like this, it's useful sometimes.
```
ʁƛL↵-‹;∑
ʁ create list with range(0, n)
ƛ open mapping lambda (with loop item n)
L↵ push 10 to the length of n
- n - the latter (because it's reversed)
‹; decrement by 1 and close lambda
∑ sum list
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
’æċ⁵_)S
```
A monadic Link accepting a non-negative integer that yields a non-negative integer.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw8zDy450P2rcGq8Z/P//f0NDAA "Jelly – Try It Online")**
### How?
```
’æċ⁵_)S - Link: non-negative integer, n
) - for each i in [1..n] (if n is 0 this will yield []):
’ - decrement -> i-1
⁵ - 10
æċ - ceil i-1 to the nearest (positive integer) power of 10
_ - subtract i
S - sum
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~50~~ 44 bytes
Gave a fun recursive solution a go :)
edit: -6 bytes thanks to solid.py
```
f=lambda n:n and f(m:=n-1)-n+10**len(str(m))
```
[Try it online!](https://tio.run/##FcVBCsMgEAXQfU/xd5lJE1C6KYInKV1YjFSIP2Ld5PS2hQevnv198HavbYzk91BeMYCOCIxIUpznanXl1Zp53jfKpzcpqiMdDRmZeJgF9uefMU93AWrL7JIk64KN0U@YdHwB "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 79 bytes
```
g(n,t,s){t=--n/10;s=n%10+1;n=t*45+s*(19-s)/2+10*(t?s*g(t+1)+(10-s)*g(t)-90:0);}
```
[Try it online!](https://tio.run/##LU5BTsQwDDyTV1grVbKbRLUXOCwh8BDYA8rSKgeyaJMTVd9eHMHB4xmPxnbyS0r7vmBxzVVaW/S@TMKhxjIIWwkltvHh0dYR5eQrTUcrPGJ7reOCzQpZFNZ5V@RP/MQUtv3rIxek1eTSoKW3M0RYzR07caKgeHRyr5x7/QE7swUzX2@APZUjB8jwDDX/fF5nbImmf6o2qWct9aXfN9UzHoYL@BcYLu/l4PRkPjv9qHeiYDaz7b8 "C (gcc) – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 35 bytes
```
for ((x=$1;x--;s+=1e$#x+~x)):
<<<$s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3ldPyixQ0NCpsVQytK3R1rYu1bQ1TVZQrtOsqNDWtuGxsbFSKIUqhOpZGGxoYxEI5AA)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 57 49 bytes
-8 bytes thanks to @mazzy!
```
0.."$args"-gt0|%{$s-=$_---("1e"+"$_".length)}
+$s
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPT0klsSi9WEk3vcSgRrVapVjXViVeV1dXQ8kwVUlbSSVeSS8nNS@9JEOzlktbpfj///@GBgYA "PowerShell – Try It Online")
[Answer]
# [Behaviour](https://github.com/FabricioLince/BehaviourExolang), ~~36~~ 29 bytes
```
f=&#(a*&10^#(""+a)-1-a;>&a+b)
```
My own recently made esolang, so bear with me.
ungolfed and commented
```
f=&
#( // deal with 0 case, convert nil into 0
a * & // generate array for n nine complements
10^#(""+a)-1-a; // nine complements logic
>&a+b // reduce array by adding its items
)
```
Test with:
```
f:0
f:1
f:10
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~8.5~~ 6.5 bytes
```
+.,$-^~,`p-$~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWa7X1dFR04-p0Egp0VeogYlCpBVsNuAy5DIGEARhDCAOIJAA)
*-2 bytes thanks to Dominic van Essen*
```
+.,$-^~,`p-$~
+ Sum
. for n in
, range from 1 to
$ input
- subtract
^~ 10 to the power of
, length of
`p convert to string
- ~ subtract 1 from
$ n
n
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
+1 byte to work around a bug in Japt.
```
aÓApUs l
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=YdNBcFVzIGw&input=MTAw)
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
*-1 byte thanks to user `friddo`*
```
lambda n:sum(~i+10**len(str(i))for i in range(n))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqrg0V6MuU9vQQEsrJzVPo7ikSCNTUzMtv0ghUyEzT6EoMS89VSNPU/M/XCjaQEfBEIhAlAGEgJIGsVZcCkBQUJSZV6KRBjRIRyE1L8VWXUFd8z8A "Python 3 – Try It Online")
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 17 bytes
```
+/⍳-⍨1-⍨10*≢∘⍕¨∘⍳
```
`⎕IO←0`.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/04Cktv6j3s26j3pXGIIJA61HnYsedcx41Dv10Aowvfn//7RDKwwUDBUMgYQBGEMIAwA)
[Answer]
# JavaScript, 47 bytes
```
f=n=>(t=10**`${n}`.length)*n+n*~n/2+~-t*~t/11+9
```
[Try it online!](https://tio.run/##LYxNDoIwFAav8i1c0PKAFn9Z1IsYEwhS0DSvBho2Rq5eJbqZWUwyj2Zupna8P0PG/tbFaA2bcxKMVlLWmxe/69x13IdBSE5ZLlyU6ZIFuYRC67SK1o9I5sbBW1wUQRNKwpawI@wJB8IRdCJU37Rm9cOf6irQep6863Ln@3VEsKuEiB8 "JavaScript (Node.js) – Try It Online")
There isn't any non-recursive implementation here. So maybe it is worth to include one. But it is longer than current answers...
If your language trunk divide result to int automatically, `+~-t*~t/11` could be changed into `-t*t/11`.
$$ t = 10^{1+\lfloor\log\_{10}n\rfloor} $$
$$ t\cdot n-\frac{n\cdot (n+1)}2-\frac{t^2-100}{11} $$
with special case where \$n=0\$
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
:q"10@Vn^q@-vs
```
[Try it online!](https://tio.run/##y00syfn/36pQydDAISwvrtBBt6z4/39DAwA "MATL – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 49 bytes
```
f(k)=∑_{n=2}^k(10^{1+floor(log(n-1))}-n)+9-0^k9
```
Would be 44 bytes if we didn't have to deal with 0...
[Try It On Desmos!](https://www.desmos.com/calculator/hx3t6kc5n5)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/hogm4nge2i)
## 48 bytes, port of [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)'s [answer](https://codegolf.stackexchange.com/a/243275/96039)
```
t=10^{log(n+0^n)}10
f(n)=tn-(nn+n)/2-(tt-100)/11
```
[Try It On Desmos!](https://www.desmos.com/calculator/epcgwgznbc)
[Answer]
# [Raku](https://raku.org/), 32 bytes
```
0,|[\+] {{S:g/./9/-$_}($++)}...*
```
[Try it online!](https://tio.run/##K0gtyjH7n1up4FCsYPvfQKcmOkY7VqG6OtgqXV9P31JfVyW@VkNFW1uzVk9PT@u/tUJxYqWCkkq8gq0dUEu0SnyskkJafpGCjYGCoYIhkDAAYwhhYPcfAA "Perl 6 – Try It Online")
This is an expression for the infinite sequence of sums.
* `{ ... } ... *` is a lazy, infinite sequence, where the brackets enclose an expression that generates each sequence element.
* `$++` postincrements an anonymous state variable each time the generating function is called, producing the numbers 0, 1, 2, .... Each time, that number is passed to the anonymous function enclosed in the inner brackets. (That saves us having to declare a variable to hold the counter value.)
* `S:g/./9/` converts every digit in the counter to `9`.
* `- $_` subtracts the counter from the previous value.
* `[\+]` produces the sequence of partial sums from the original sequence.
* `0, |` pastes a zero onto the front of the sequence.
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 32 bytes
```
:*|:sum+(-[S|:+@|:**&10,:~]|+:+)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWNxWstGqsiktztTV0o4NrrLQdaqy0tNQMDXSs6mJrtK20NaHqNAoU3KINYrlAlCGUgnENEAyDWIj6BQsgNAA)
## Explanation
```
:* | :sum + ( -[ S | :+@ | :** & 10, :~ ] | +:+ )
:* | # 0...input
:sum + ( ) # Sum by
-[ , ] | +:+ # Sum of
S | :+@ | :** & 10 # 10 to the power of the number of digits
:~ # and two's complement
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 11 \log\_{256}(96)\approx \$ 9.05 bytes
```
eDL10@1-_ES
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuharU118DA0cDHXjXYMhIlCJBYsNDQwgTAA)
#### Explanation
```
# Implicit input
e # Map over range(input):
DL # Duplicate and push the length
10 # Push ten
@ # Push 10 ** length
1- # Subtract one
_ # Subtract the loop variable
ES # After the map, sum
# Implicit output
```
[Answer]
# [FunStack](https://github.com/dloscutoff/funstack) alpha, 60 bytes
```
Cons 9 Reverse From0 over flatmap Times 9 Pow 10 #N Sum Take
```
Try it at [Replit](https://replit.com/@dloscutoff/funstack)!
### Explanation
First, we construct the infinite list `[9,8,7,6,5,4,3,2,1,0,89,88,87,...]`:
```
#N
```
Natural numbers starting from 0.
```
Times 9 Pow 10
```
Take 10 to the power of each number, then multiply by 9.
```
Reverse From0 over flatmap
```
Create a function that takes a number, generates the range from 0 to that number (exclusive), and reverses it. Then map that function to each number in the above list and flatten the resulting list of lists.
(What we're doing here is really just function composition, but `over` is fewer bytes than `compose` and does the same thing in this case.)
```
Cons 9
```
Stick a 9 on the front of the list.
Now this value gets appended to the program's argument list (which previously contained the input number, N), and we apply the following functions:
```
Take
```
Take the first N values from the infinite list.
```
Sum
```
Sum them.
[Answer]
# JavaScript, 35 bytes
```
f=n=>n&&f(--n)+10**`${n}`.length+~n
```
[Try it online!](https://tio.run/##FcsxCoAgFADQq/whQhPDoCEwO4sRaYZ8I8Ul6upW05vePuc5Lqc7Es9DKUahmrCuDeEcKetE0@jqwlu3fkWbNvZgMeEE4kCBkOBgVNB/MkZhCRiDX1sfLDHkv45SWV4 "JavaScript (V8) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
+/@((10&^@#@":->:)"0@i.)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfUdNDQMDdTiHJQdlKx07aw0lQwcMvU0/2tycaUmZ@QrpCkYwBiGcAZCyACZicI24PoPAA "J – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
```
f=lambda n:n and-~~n+10**len(`n-1`)+f(n-1)
```
[Try it online!](https://tio.run/##FcVNCoAgFEbReat4Q38StGHQSiLQMEmoT5EmTdy62eXCye9zJkytheVy9@4dYQY5eFUrpNFCXAeYhTKWy8C6vIVUKFIErXok0//RepsH6uUS8bDAIuftAw "Python 2 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->n{n.times.sum{|x|10**x.to_s.size+~x}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vJDM3tVivuDS3uqaixtBAS6tCryQ/HiiSWZWqXVdRW/u/QCEt2iCWC0QZQikY1wDBMIj9DwA "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
I↨¹EN⁻I×Lι9ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXDUEfBN7FAwzOvoLTErzQ3KbVIQxMolJlXWgxRFZKZm1qs4ZOal16SoZEJlFOyVNIEUpmaIGD9/7@hgYHBf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
N Input as a number
E Map over implicit range
9 Literal string `9`
× Repeated by
ι Current value
L Length (of string representation)
I Cast to integer
⁻ Subtract
ι Current value
↨¹ Take the sum
I Cast to string
Implicitly print
```
(`Sum()` won't work for an input of `0`.)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 19 bytes
```
-.{Jln'9j.*j|-}GZ++
```
[Try it online!](https://tio.run/##SyotykktLixN/V@tpGunZG2tG1uU@V9Xr9orJ0/dMktPK6tGt9Y9Slv7f214zn8DBV07BQMuQxBlyWUI5pqYAhkQloGpAYgN5ViYGUC4UL6lgQmQBwA "Burlesque – Try It Online")
```
-. # Decrement (Burlesque runs 0..N inclusive, need to exclude)
{
J # Duplicate
ln # Number of digits
'9 # Character 9
j # Reorder stack
.* # Repeat 9 n_digits times as string
j # Reorder stack
|- # String subtract (parse and subtract)
}GZ # Generate for range
++ # Sum
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 30 bytes
```
n->sum(i=0,n-1,10^#Str(i)-1-i)
```
[Try it online!](https://tio.run/##LYdBCoAwDAS/EuqlgQbSB9hPeBQFL0pAQ6j14OurRWGY2bUlC21WV@irUjqvw0vPQSmGyHM3lOwFKZJgXcz22ytQAsui5Z2uHQerV8QAIweILy386TdPWB8 "Pari/GP – Try It Online")
] |
[Question]
[
## Background
The number of values for a given type is called the *cardinality* of that type, and that of type T is written as `|T|`.
Haskell and a few other languages have a certain set of enum types, each of which has a small finite number of values (the exact names vary, so this challenge uses some arbitrarily chosen names).
```
Name | Cardinality
------+-------------
Never | 0
Unit | 1
Bool | 2 (true or false)
Order | 3 (LT, EQ, or GT)
```
And they also have some derived types which have one or more *type parameters*. Their cardinality depends on which types they get as parameters (written as `T` and `U` in the table below). `Func(T,U)` represents the function commonly written as `T -> U`, i.e. a function that takes a parameter of type T and returns a value of type U.
```
Name(Params) | Cardinality
-------------+-------------
Option(T) | |T| + 1 (some value from T, or absence)
Either(T,U) | |T| + |U| (some value from T or some value from U)
Pair(T,U) | |T| * |U| (any combination of values from T and U)
Func(T,U) | |U| ** |T| (any combination of U for every value of T)
```
Note: A "function" here is to be understood as a mathematical concept rather than a programming one. A mathematical function `Func(T,U)` maps every possible value of T to some value of U, disregarding the "how". For programmers, it is OK to think of it as functions of the form of (in Haskell-like pseudocode):
```
\(x :: T) -> case x of
value1OfT -> someValue1OfU
value2OfT -> someValue2OfU
...
valueXOfT -> someValueXOfU
```
with all cases provided.
For example, `Option(Never)` has cardinality 1, and `Func(Bool,Order)` has cardinality `3**2 = 9`. `Func(Never,Never)` has cardinality 1; `0**0` is defined to be 1 in this system.
A type parameter can itself be a derived type, so `Pair(Func(Never,Never),Pair(Either(Bool,Bool),Option(Order)))` is also a valid type, which has cardinality of `(0**0) * ((2+2) * (3+1)) = 16`.
For this challenge, assume that no types other than the 8 presented above are available.
## Challenge
Given a string that represents a valid type in this system, output its cardinality. You can assume the input does not contain spaces.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
Never -> 0
Unit -> 1
Bool -> 2
Order -> 3
Func(Never,Never) -> 1
Func(Unit,Never) -> 0
Option(Unit) -> 2
Option(Order) -> 4
Either(Bool,Bool) -> 4
Either(Bool,Order) -> 5
Pair(Bool,Order) -> 6
Pair(Func(Never,Never),Pair(Either(Bool,Bool),Option(Order))) -> 16
Func(Func(Order,Order),Order) -> 7625597484987
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 80 bytes
```
Never,Unit,Bool,Order=0..4
Option=(1+)
Either=(+)
Pair=(*)
Func=(x,y)=>y**x
eval
```
[Try it online!](https://tio.run/##ZZDNTsMwEITP3aewevIGEyUlP@3BPVQqR8qFBwhgqZYi2zLunxDPnsbrSC1wWY0@b2Zn4rwN1gzDizoqL96MDmJjbS92/lN5WeR5BTsXtDWSlw8IWx32I@ejfO30KDKE54P5kPwsLijXlyw7gzp2/XDa616xkn3DrBPsnUmmjTsEjvmX63Xgc/a4ZnOEmfPaBB53BItf8g4RflKguFNATBVVCTFaVAugfFE@0X2e8tPEtEuYCt1oMZUhjpNTImRIqJpa8tuPIF5T5b@0SfRfCEH43ikOFL/OYcrapLA06GHyvzvTNou6XrXVslot2ys "Proton – Try It Online")
This solution is a whole lot shorter in Proton. Original Python solution included below.
# [Python 3](https://docs.python.org/3/), 106 bytes
```
Never=0
Unit=1
Bool=2
Order=3
Option=1 .__add__
Either=int.__add__
Pair=int.__mul__
Func=int.__rpow__
eval
```
[Try it online!](https://tio.run/##ZZBNTwMhEIbP5VeQniBZm7b71ZrgwUSP1oOeN9QlWRIEwrJt/PUrDKirXibDMzPvvIP98IPR5Tw/iYtwbItetfRsh@6NUWyPTq4PtEQn66XRbIc3Xcf7vuvQg/RDKEntv9Ezl1/gfVIBPE76LQNnzTUQceFqvg5SCfziJnGLVrzAZ8yw1HbyhG5Gq6Qna3xzh9cUrawL4yT2hAcfR@E8jhqEU8zilCdnmrzHkWQ/ZumCmOUjYlqCIwLtBUSaegHH0QXd5qOB06yUCAgCqvI/kLit@OE1fMZf2iT6z0QBeKkUAy1@raPJa5PMQoBC1l@saZt9XR/b6lAdD@0n "Python 3 – Try It Online")
-3 bytes thanks to dingledooper
`__rpow__` exists so I don't even have to do `lambda x,y:y**x` so this is even more boring :D
trivial solution and I'm sure there's something both better and smarter
[Answer]
# [JavaScript (V8)](https://v8.dev/), 98 bytes
```
Never=0
Unit=1
Bool=2
Order=3
Option=x=>1+x
Either=(x,y)=>x+y
Pair=Math.imul
Func=(x,y)=>y**x
eval
```
[Try it online!](https://tio.run/##NY2xDsIgFEX39xmdoK2N1cXldTDRTeviBxAklgahoZTA12NLdDk3Ofcmd2SezdzKye38KaW78MLiHp5aOmzhbIzCA/T2tdoj9JOTRmPArq0CXKQbVk1CHSl2oYrwYNLijbmhkZ9FwXXR/F/HsgwgPFOJGz0bJRpl3mQTpNh2JCMf1Zn0FwWl6Qs "JavaScript (V8) – Try It Online")
Same idea as @hyper-neutrino, though its shorter in js
-1 byte thanks to @Arnauld
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~77~~ ~~31~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Rv"0123>+*m ""NUBdpEPF"ykè.V
```
Byte-count more than halved and sped up a lot by porting [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/236277/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f8/qEzJwNDI2E5bK1dBSckv1CmlwDXATaky@/AKvbD//wMSM4s03ErzkjX8UstSi3TApKYOWNg1syQjtUjDKT8/RwdEaOr4F5Rk5udp@BelABVpagIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/6AyJQNDI2M7ba1cBSUlv1CnlALXADelyuzDK/TC/tfq/PdLLUst4grNyyzhcsrPz@HyL0oB8t1K85I1wFI6YFITIgJSBhPwLyjJzM8DC8E5YM2aXK6ZJRmpRRog83RABKoIVFFAYiYWAQyLdcDCGCbqoNioCXUfmAALQQ2FUgA).
**Explanation:**
```
R # Reverse the (implicit) input-string
v # Loop over each of its characters `y`:
"NUBdpEPF"yk # Get the index of `y` in "NUBdpEPF"
# (which will result in -1 if it isn't present)
"0123>+*m " è # Use it to (0-base modulair) index into "0123>+*m "
.V # Execute it as 05AB1E code:
# `>`: Increment the top value by 1
# `+`: Add the top two values together
# `*`: Multiply the top two values
# `m`: Take the exponent of the top two values
# The digits 0-3 remain the same
# ` `: No-op for not found characters / index -1
# (after which the result is output implicitly)
```
### Original (77 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) answer:
```
”†™‰¿ëĂє#ā<:Δ”íŽ‰‡¥Öˆ¦c”#vD.γd}þàÝ©NĀiã©',ý}€…(ÿ)yì®N_i>ëíðý…m+*Nè«}øvy`.V:
```
Because 05AB1E lacks both regexes and functions, this uses a brute-force replacement method wrapped in a loop. It's therefore also extremely slow the larger the integer becomes, and will fail to complete the final test cases as is.
[Try it online](https://tio.run/##yy9OTMpM/f//UcPcRw0LHrUsetSw4dD@w6sPtzxqmHV4IlBY@UijjdW5KUDW4bVH9wKlHzUsPLT08LTTbYeWJYPky1z0zm1OqT287/CCw3MPrfQ70pB5ePGhleo6h/fWPmpa86hhmcbh/ZqVh9ccWucXn2kHNHvt4Q2HgSYty9XW8ju84tDq2sM7yioT9MKs/v8PSMws0nArzUvW8EstSy3SAZOaOmBh18ySjNQiDaf8/BwdEKGp419Qkpmfp@FflAJUpKkJAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0cNcx81LHjUsuhRw4ZD@w@vPtzyqGHW4YlAYeUjjTZW0S4pykD24bVH9wIVPGpYeGjp4Wmn2w4tSwapKHPRO7c5pfbwvsMLDs89tNLvSEPm4cWHVqrrHN5b@6hpzaOGZRqH92tWHl5zaJ1ffKYd0PS1hzccBpq0LFdby@/wikOraw/vKKtM0Auz@l9bW6vz3y@1LLWIKzQvs4TLKT8/h8u/KAXIdyvNS9YAS@mASU2ICEgZTMC/oCQzPw8sBOeANWtyuWaWZKQWaYDM0wERqCJQRQGJmVgEMCzWAQtjmKiDYqMm1H1gAiwENRRKAQA) (the `Δ` is replaced with `[Dd#` in the test suite to speed it up slightly, so we can also verify the last test case).
**Explanation:**
```
”†™‰¿ëĂє # Push dictionary string "Never Unit Bool Order"
# # Split it on spaces: ["Never","Unit","Bool","Order"]
ā # Push a list in the range [1,length] (without popping): [1,2,3,4]
< # Decrease each to the range [0,length): [0,1,2,3]
: # Replace all "Never" with 0; "Unit" with 1; etc. in the (implicit)
# input-string
Δ # Loop until the result no longer changes:
[Dd# # (slightly faster alternative, so we'll have one iteration less:)
[ # Start an infinite loop
D # Duplicate the current string
d # If it's a non-negative (>=0) integer:
# # Stop the infinite loop
”펉‡¥Öˆ¦c” # Push dictionary string "Option Either Pair Func"
# # Split it on spaces: ["Option","Either","Pair","Func"]
v # Loop over each string `y` in this list:
D.γd}þà # Get the current maximum integer in the string:
D # Duplicate the string
.γ # Group this string into substrings by:
d # If it's a non-negative (>=0) integer
}þ # After the group-by, only leave these integers
à # And pop and push the maximum
Ý # Pop and push a list in the range [0,max]
© # Store it in variable `®`
NĀi # If the index is NOT 0 (thus not "Option"):
ã # Take the cartesian product of this list
© # Store that in variable `®` instead
',ý '# And join each inner pair with "," delimiter
}€…(ÿ) # After the if-statement: wrap each integer/string into parenthesis
yì # And prepend the current string `y`
® # Push list `®` again
N_i # If the index is 0 (thus "Option"):
> # Simply increase the value by 1
ë # Else:
í # Reverse each pair in the list
ðý # Join each pair with space delimiter
…m+* # Push string "m+*"
Nè # Index the loop-index into it (0-based modulair)
« # Append it to each string
}ø # After the if-else statement: zip to create pairs of the two lists
v # Loop over each pair `y` in this list:
y # Push the pair `y`
` # Pop and push both values separated to the stack
.V # Execute the second string as 05AB1E code, resulting in an integer
: # Replace the first string to this integer
# (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 `"Never Unit Bool Order"` and `”펉‡¥Öˆ¦c”` is `"Option Either Pair Func"`.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 129 bytes
```
Or
Q
{T`NUBQ)(l`0-3;_
O(\d+);
$.(_$1*
E(\d+),(\d+);
$.($1*_$2*
P(\d+),(\d+);
$.($1*$2*
F(\d+)
F$1*
(F_*)_(,\d+;)
P$1$2$2
F,\d+;
1
```
[Try it online!](https://tio.run/##bY4xD4IwEIX3@x0dWqxGcGQjoSOFRDaTQqSJTQiYprr447E9UUNgeZf33d27s9qZoY2nSVqo4HVuijqrGO2b4/6UKpD00u1YCuRAFYkjyNHzP/VQkSSCcqMRuEACIixToSKmKPckZVCSmCQkAYEe/AuFfmoL9WAcZOPYg7Sd9@IxXCm2OCr7kDD2BfLuzDgg@hlcZpAbd9OWhjweZEnmobI1G2B1mCNeJfLFRTb/h4JoDp3LGw "Retina – Try It Online") Link includes test cases. Explanation:
```
Or
Q
```
Change `Order` to `Qder` to avoid confusion with `Option`, and also because `O` has special meaning for Transliterate.
```
{
```
Repeat the remaining transformations until the desired result is obtained. (The transliteration does not need to be repeated but it's golfer to share the ```.)
```
T`NUBQ)(l`0-3;_
```
Transliterate the `Never`, `Unit`, `Bool` and `Qder` to `0` to `3` respectively, transliterate the `)` to `;` for ease of matching, and delete the lower case letters and `(`.
```
O(\d+);
$.(_$1*
```
Handle `Option` by incrementing the value.
```
E(\d+),(\d+);
$.($1*_$2*
```
Handle `Either` by taking the sum of the values.
```
P(\d+),(\d+);
$.($1*$2*
```
Handle `Pair` by taking the product of the values.
```
F(\d+)
F$1*
```
Convert the first parameter of `Func` to unary.
```
(F_*)_(,\d+;)
P$1$2$2
```
Compute `Func(n+1,m)` as `Func(n,m)*m` using `P` to do the multiplication.
```
F,\d+;
1
```
`Func(0,m)` is just `1`.
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 111 bytes
```
Op.{5}
EU,
T`NUB\O)(l`0-3;_
\d
$*
E(1*),(1*);
$1$2
(P1*)1(,1*;)
E$1$2$2
P,1*;
(F1*)1(,1*;)
P$1$2$2
}`F,1*;
1
1
```
[Try it online!](https://tio.run/##bY69CsIwFIX3@xwVbkoUozh1K7RuTQa7FUzRgIGSlhBdpM9em1jFUpfDPd@5f1Y5bephhXiUA@82z0MPWUnhJIsyrTjBRm7X@@QM1RWiGDJkMaFeEohYtAMUY82QsjghkHk0QuEtAOY/mZiyXuYhZcCGoVAPZaE02kHatg1wex19fjcXDBENSt7Et30A75xuTUBfE4bHJ7S7KYt@H/UyJ1OTqPUfsDhMA15spLOLhLwA "Retina 0.8.2 – Try It Online") Link includes reduced test cases, as Retina 0.8.2 has to calculate in unary, which limits the magnitude of the result. Explanation:
```
Op.{5}
EU,
```
Change `Option(` to `Either(Unit,` (except preabbreviated).
```
T`NUB\O)(l`0-3;_
```
Transliterate the `Never`, `Unit`, `Bool` and `Order` to `0` to `3` respectively, transliterate the `)` to `;` for ease of matching, and delete the lower case letters and `(`.
```
\d
$*
```
Convert to unary.
```
E(1*),(1*);
$1$2
```
Handle `Either` by taking the sum of the values.
```
(P1*)1(,1*;)
E$1$2$2
```
Compute `Pair(n+1,m)` as `Pair(n,m)+m` using `E` to do the addition.
```
P,1*;
```
`Pair(0,m)` is just `0`.
```
(F1*)1(,1*;)
P$1$2$2
```
Compute `Func(n+1,m)` as `Func(n,m)*m` using `P` to do the multiplication.
```
F,1*;
1
```
`Func(0,m)` is just `1`.
```
}`
```
Repeat the above transformations until the desired result is obtained.
```
1
```
Convert to decimal.
[Answer]
# JavaScript (ES7), 103 bytes
A regex-based solution. This is longer than using @hyper-neutrino's [method](https://codegolf.stackexchange.com/a/236251/58563), but not as much longer as I was expecting.
```
s=>eval(s.replace(/\w+/g,s=>(i="enorpiau".search(s[1]))<4?i:`((x,y)=>y${['|1+','+','*','**'][i&3]}x)`))
```
[Try it online!](https://tio.run/##pdJNT4MwGAfwu59iIUbarYJsvGxGZmKiR@fFE5KsYd1WQyhpGW7RfXak1YsdMVkh6XMA8uvTf593XGORcVpW1wVbkWYdNyKekxrnQDiclDnOCHDfPkbuBrUfAI0tUjBeUryzHEEwz7ZAJF4K4Z1/T2@XAOzRAcbzw@VnYn95IxvZcg3lGtppQq8m6XEPlxA2GSsEy4mTsw1YA@uZ1IRbEA5MH9cd3Fxo6GtBqz6mRD0dfWAs74uOdXTBV72PP9HRp12RARUsUhWeu0HX8RUqgzU0Oy9qUVaUFYqFRil0ZvqDqmiN1Bb1dfSRVlvCgRwCJItJpv@iRu22aKCjL5j2IRUadqInc4XU65No0J8bgKoDOVJh50ypon79bfiMvls1CsdBMIv8qT@bRs03 "JavaScript (Node.js) – Try It Online")
### How?
All keywords can be unambiguously identified by looking at the second character. Hence the lookup string `"enorpiau"` and an index `i` into this string. We use the pattern `((x,y)=>y…x)` for all operations.
```
i | keyword | translation
---+----------+----------------
0 | N[**e**]ver | 0
1 | U[**n**]it | 1
2 | B[**o**]ol | 2
3 | O[**r**]der | 3
4 | O[**p**]tion | ((x,y)=>y|1+x)
5 | E[**i**]ther | ((x,y)=>y+x)
6 | P[**a**]ir | ((x,y)=>y*x)
7 | F[**u**]nc | ((x,y)=>y**x)
```
[Answer]
# [Julia 1.0](http://julialang.org/), 87 bytes
```
eval∘Meta.parse
Never,Unit,Bool,Order=0:3
Option,Pair,Either=x->x+1,*,+
Func(x,y)=y^x
```
[Try it online!](https://tio.run/##bZHPTsMwDMbveQozcUhYNu1/N6TugAQSB9guXEHV6oqgKq1Sb@regEfg@XiR0jiVNhiVark/O46/rx/73CTjusniBg9J/v359YSUDMvEVSie8YBOv1hD@q4ocr1xKbp4dDsVm5JMYfU2MU7fG3pvcT1Y1/2xvtF98bC3O1nro4qPr3VDWFEFMVRlbmgoHSZpbixWUikhssKBJP2mUYGxwL0C2qd0xlJuJUG8hkxS2@yxyfgDrmLgHeWjpfYs186P9bAucUeYwjX2QhltKtq3YVUwWMNIeGk@Gwuvz2cTwSJ9Og06ggkcVehlzK6c6KizhLnqJgXCAxnNRPBKsps@/INP7XPh/f1LF4Fe7MY/Q15coH9toYKERdDAgQvd/LNrosVkPl9Fs@VstYx@AA "Julia 1.0 – Try It Online")
Same idea as the other answers
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~66~~ ~~61~~ 60 bytes
```
F⮌S«≡ιd⊞υ³B⊞υ²U⊞υ¹N⊞υ⁰p⊞υ⊕⊟υE⊞υ⁺⊟υ⊟υP⊞υ×⊟υ⊟υF«≔⊟υθ⊞υX⊟υθ»»Iυ
```
[Try it online!](https://tio.run/##fZDNigIxDIDP41MUTyl0YX9u60lFwYsWd/cBSic6hbGd7Y8eFp@9tsM6UzwIIZAvH2kT2QgrjWhjPBhLYI9ntA5ho7vgv7xV@giUUvI3qdxFedkQUH0lhUMyraefhAfXQGDkg87ueFHg9xH/FPhtxNsCv464K/BGS4sn1B5r4KaDkP40iKtC5G1w/0YqHk1emN/qhE/UdVLTmtXcOXXUg/ebjWp4zVzQFr3cvOa4Tng6nYelcD7PncXIhbKwDlrCNt@Y9ZmyHq@Ub9KghTEty4myXeeV0bCzdZIojS/n9gY "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 5 bytes thanks to @KevinCruijssen pointing out that `d` and `p` uniquely identify `Order` and `Option`. Saved 1 byte by finding a slightly shorter way to exponentiate. Explanation:
```
F⮌S«
```
Loop over the characters of the input string in reverse order.
```
≡ι
```
Switch on the current character.
```
d⊞υ³
```
For `(Or)d(er)` push `3` to the predefined empty list.
```
B⊞υ²
```
For `B(ool)` push `2` to the predefined empty list.
```
U⊞υ¹
```
For `U(nit)` push `1` to the predefined empty list.
```
N⊞υ⁰
```
For `N(ull)` push `0` to the predefined empty list.
```
O⊞υ⊕⊟υ
```
For `(O)p(tion)` increment the top of the list.
```
E⊞υ⁺⊟υ⊟υ
```
For `E(ither)` sum the top two elements of the list.
```
P⊞υ×⊟υ⊟υ
```
For `P(air)` multiply the top two elements of the list.
```
F«≔⊟υθ⊞υX⊟υθ»
```
For `F(unc)` exponentiate the top two elements of the list. (Unfortunately the elements are in the wrong order, complicating the code. I tried processing the string from left to right which avoids that issue but that then requires an operator stack which ends up making the code much longer.)
```
»
```
Ignore any other characters.
```
Iυ
```
Output the final result.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~120~~ 95 bytes
```
p=i=->x,y=1{x+y}
a=->x,y{x*y}
u=->x,y{y**x}
f=->s{eval s.gsub(/\w+/){$&[1]}.tr'enor()','0-3[]'}
```
[Try it online!](https://tio.run/##nZLJboMwEIbvPIWVVGWJE3ZIDuRQqT02ufSU5kBS0iIhQCwpCPnZKdiWTNgOvVjMP/98M2OT5JeyrmPHd9b7ApaOWhWrEnEuCatCaoKcBqUkFYi7NVFaeXc3AOnmO80vgvz5u5LF6un5pJ7RJkt4L4wSQeQhr6z105lHdZxnqbB49@5eApw9WFbgtrm6QUC1hQgQkOVGV1DzvQQKRyo@Qj/rFbQS86vEr1L/SxQFPX8rMb9G/Br1H5KvwURYYxU6qdBpxVseXgU8NMSn2Kse5Cdnxc52mxlQJz15R4c486MQW/uMbmr6DogJrz0BIDlGMAjBoIRXP/vxEqG9aTiKGRoYyyQsk7KOrj9H6qcZxyIcq8sZPAbEcnec9hDhw57iaNP/sjrvT0dUre4fgA9spiuNLz7rZT1sSzPNnW1sjd3WJu0eJK7@Aw "Ruby – Try It Online")
* Thanks to @Dingus for the 25 Bytes saved!
[Answer]
# [R](https://www.r-project.org/), 121 bytes
Or **[R](https://www.r-project.org/)>=4.1, 100 bytes** by replacing the three `function` appearances with `\`s.
```
function(s,Never=0,Unit=1,Bool=2,Order=3,Option=function(x)x+1,Either=`+`,Pair=`*`,Func=function(a,b)b^a)eval(parse(t=s))
```
[Try it online!](https://tio.run/##dZBPb8IwDMXvfArELvHwJFr6hxyyAxI7jl12nRpYqkVCbdUUxLcvsdt1i9guVf1@dt6z275UfXmujp2tK@Hw1VxMq1b4XtlORbit65OKcd9@enWN@4ba1NR/hesywp3tvjwulgW@aet/Hgt88S0/fRoPcPjQYC76JBrdOiM65QD6UizYcQEP86fn@WrmBbIe64hqyjDWMdUcZhTWJJCX4GeG@PB7miE9GTJ2GtZhCoHDoLPRN0gIDJsKSsSn@RcGoylRuswfLJvY3RZ8THFniUE6mJbNZjUDJ9zRNqZSUkqYLsAfHhn9wxh5FqepzJNNIjd5fwM "R – Try It Online")
[R](https://www.r-project.org/) doesn't have a simple `eval`, you need to `parse` the string first.
[Answer]
# [Haskell](https://www.haskell.org/), 206 bytes
```
f.read
data T=Never|Unit|Bool|Order|Option T|Either(T,T)|Pair(T,T)|Func(T,T)deriving Read
f(Option a)=f a+1
f(Either(a,b))=f a+f b
f(Pair(a,b))=f a*f b
f(Func(a,b))=f b^f a
f Never=0
f Unit=1
f Bool=2
f _=3
```
[Try it online!](https://tio.run/##PY9Nj8IgEIbv/oqJ8VCUNX6cuZisx3Vj6m2jmbZQyXZpQ7EnfrssTKuXycsD8@Tljv2vbJpQi5@g1lZiNavQIeTiSw7S@ovRzh/atvEnW8XzqXO6NZD7T@3u0mY5z5n/Rj2l48OUlOJbPWhTwzkpVTbtIRMKcLWNZBIgL9gIFRQRk@sNlyMk7QsW13gxU0AFxSamVFJEJ6SiYhfDTezDH2oDAjqrjYMF1DAnN7lol9NknPBUJxl4GoyPlTP6N2NsHp6larDuw0fZdf8 "Haskell – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 92 bytes
```
Never=0
Unit=1
Bool=2
Order=3
Option(x)=1+x
Either(x,y)=x+y
Pair(x,y)=x*y
Func(x,y)=y^x
eval
```
[Try it online!](https://tio.run/##K0gsytRNL/j/3y@1LLXI1oArNC@zxNaQyyk/P8fWiMu/KAUoaszlX1CSmZ@nUaFpa6hdweWaWZKRWqRRoVOpaVuhXckVkJgJ42lVcrmV5iVDeJVxFVypZYk5/wuKMvNKNEBMDSWwNJgAG64DJjWhlJKm5n8A "Pari/GP – Try It Online")
The same as [@hyper-neutrino's](https://codegolf.stackexchange.com/a/236251/9288) and [@wasif's](https://codegolf.stackexchange.com/a/236256/9288) answers.
[Answer]
# [Perl 5](https://www.perl.org/), 105 bytes
```
s/\w(.)\w+/$1/g;y/enor/0123/;1while s|([piau]).(\d+)(,(\d+))?\)|($4//1).({a,'*',u,'**'}->{$1}//'+').$2|ee
```
[Try it online!](https://tio.run/##bY5Bb4JAEIXv/AoPJLsjC9PF9kTSJk3qUXvxJB6IbuomhCULlBjxr3cLI5oQvbzJfPPmzZTK5m/OVZi2PIK0DdCX@JOcUBXG4ouMF5jI9qhzNas6vi111uwg4ukhAC6owEcKHfdfEWU/OGeCzZloep2zS/h@9uUFkQUMIj/ulHJupX6V9TaFrr1PY3JvbQ99v2yKPaeRIIUrGWw3sC5rbQpC94aWwfvS9VFZPuSJQaZkNH1n@gl4OCwIPySKyUUY/yMhNIaO5c@Qu3Jh@Q8 "Perl 5 – Try It Online")
] |
[Question]
[
## Challenge
Write a program or a function that returns or prints a square-random-symmetrical matrix.
---
## Input
**N**: The size of the matrix i.e `6 x 6`
---
## Output
The matrix. You can either print it, return it as string (with the newlines) or as a list/array of lists/arrays.
---
## Rules
1. You need to use at least `N` different characters, where `N` is the size of the square matrix (input). Since we 're using only letter [a, z][A, Z] and digits [0, 9] (and only 1 digit at the time) you can assume that `N < 27` and `N > 2`, that is because at `N <= 2` you can't have both letters and digits. Last but not least, every letter/digit must have non-zero probability of occurring (uniform distribution is not a necessity). However, the result must have at least `N` different letter/digits.
2. The matrix has to be both horizontally and vertically symmetrical.
3. Exactly 2 rows and 2 columns must contain strictly one single-digit number (it's position should be random as well). The rest of rows/cols will contain only letters. Consider letters as [a, z] and [A, Z] and of course single-digit numbers as [0, 9].
4. Just to be easier, you can assume that the case of the letters doesn't matter, as long as the cases are symmetrical which means: `a=A, b=B, etc`.
5. Every possible output must have a non-zero probability of occurring. The random distribution doesn't need to be uniform.
---
## Example
**Input**: 8
**Output**:
```
c r p s s p r c
r k o z z o k r
u t 2 a a 2 t u
y n q z z q n y
y n q z z q n y
u t 2 a a 2 t u
r k o z z o k r
c r p s s p r c
```
[Answer]
# [R](https://www.r-project.org/), ~~124~~ 118 bytes
```
function(n,i=(n+1)/2,j=n%/%2,m="[<-"(matrix(-letters,i,i),j-1,j-1,0:9-1))cbind(y<-rbind(m,m[j:1,]),y[,j:1])
`-`=sample
```
[Try it online!](https://tio.run/##HcbRCoIwFIDhe58iBOEcOgebFJFsTzIEzTbYcCvmgnz6VV78P18q9iC52Hecs3tGiOQUxKPAtiOvYtM2HQVVa8k1hCkn9wFeTM4mreTIIXkWe6f@xgJxvrv4gE1y2hEoaN8LGpA2TT8NWI08qnUKr8UUC2esLFz@u2L5Ag "R – Try It Online")
In R, things that look like operators are just functions that get special treatment from the parser.
If you redefine an operator (like `-`) to be some other function, it keeps the special treatment from the parser. Since `-` is both prefix and infix, and I need to call the `sample` function with both one and two arguments, I can use
```
`-`=sample
```
to get what I want.
So the code `-letters` is translated to `sample(letters)`, which randomly shuffles the `letters` built-in. But `j-1` is translated to `sample(j,1)`, which randomly samples `1` item from the vector `1:j`.
(This behaviour of the `sample` function depending on the number of parameters and what the first parameter is, is a huge pain in the butt in production code, so I'm happy to find a great use of its perverse nature here!)
Otherwise the code just makes the top left quadrant of the required result, replaces a random element (the `j-1`,`j-1` bit) with a random digit (the `0:9-1` bit), and folds it out for the required symmetry. The `i` and the `j` are needed to deal with the even and odd cases.
[Answer]
# Python3, 287 bytes
My first try at golfing something here; I'm sure someone can do far better:
```
import random as rn, math as m
n=int(input())
x,o=m.ceil(n/2),n%2
c=x-1-o
f=lambda l,n: l.extend((l[::-1], l[:-1][::-1])[o])
q=[rn.sample([chr(i) for i in range(97, 123)],x) for y in range(x)]
q[rn.randint(0,c)][rn.randint(0,c)] = rn.randint(0,9)
for r in q:
f(r, n)
f(q, n)
print(q)
```
[Try it Online!](https://tio.run/##ZU7LasMwELzrK/ZS0ILs1g6lxKAvMTqotlwLpNUjCihf71rNoZTuZV7LMPFR9kCX47A@hlwga1qDB32DTAK8LnvjnpG0VLileC8ckVURpO8XYx2n1xEFvYxskbUbusA26bT/XDU4QRO43tRiaOXczdPUDUrASU58KpyDQpbknKm/aR@d4fOyZ24RtpDBgqW26cvw64eAYbygEvWZPX6zioqlVtHmt6FvYkH1zwAJf6wrslaUW1GaGJy38SyATp@nH4y5vSY8jvdv)
Thanks to HyperNeurtrino, Ourous and Heiteria this shrunk down to 193 bytes (see comments). However, TFeld correctly pointed out that multiple calls to `sample` aren't guaranteeing at least `N` different characters.
That stuff in mind, try this new version that should guarantee at least `N` different characters per run.
# Python3, ~~265~~ 260 bytes, at least `N` distinct characters
```
from random import *
n=int(input())
x=-(-n//2)
o=n%2
c=x+~o
i=randint
u=[chr(j+97)for j in range(26)]
z,q=u[:],[]
for y in [1]*x:
shuffle(z)
q+=[z[:x]]
z=z[x:] if len(z[x:])>=x else u[:]
q[i(0,c)][i(0,c)]=i(0,9)
for r in[q]+q:r.extend(r[~o::-1])
print(q)
```
[Try it online!](https://tio.run/##NY/BasMwEETv@xW6FLSx3TRuaYlg8yNCh@LItYIjWYoMig75dUcK9PQYZneGWe5xcvZz28bgriz82nOBuS4uRLYDS8ZGbuyyRo4IiTre2f2@R3Bk33oYKDUPB4bqYzmFleQwBX5pjj84usAuzNia@qd5/40KcutplUK1UkH179WXB7VLAhi7Tes4zppnLMI3JLMUSakiMmWZhGJmZLO2/CXwRInp@aZZTQQvDf9oB1T/pMojvnpC6ZFeNV6Ed52itmce5MMJ0R0UwhLqTI/b9vUE)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
NθE⊘⊕θ⭆⊘⊕θ‽βJ‽⊘θ‽⊘θI‽χ‖OO→↓﹪θ²
```
[Try it online!](https://tio.run/##fY3LCsIwEEX3/YosJxBB3QjtUhdWqEr1B6ZpbAt5NSb182OQ@lg5mxnunMPlPTpuUMZYahv8MahGOBhpkZ3doD1UaGGPchItlJo7oYT26R4pZeTiE9L9I2rUrVHQ0DRFdgjKXg3M4ez8ct/o07/Fu38bq@XrUYubFNyfJuEk2nlBXg9d7xnJd@ahGalMG6SBkZF1cmLcxMUknw "Charcoal – Try It Online") Link is to verbose version of code. If `n` is always even, then for 23 bytes:
```
NθE⊘θ⭆⊘θ‽βJ‽⊘θ‽⊘θI‽χ‖C¬
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDN7FAwyMxpyw1BSiooxBcAhRNRxMMSsxLyc/VSNIEAmsur9LcgpB8DaggXBlCHUIIbotzYnEJTIehAVgiKDUtJzW5xDm/oFLD6tAaTev//y3@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input \$ n \$.
```
E⊘θ⭆⊘θ‽β
```
Create an \$ \frac n 2 \$ by \$ \frac n 2 \$ array of random lowercase letters. This prints implicitly as a square.
```
J‽⊘θ‽⊘θ
```
Jump to a random position in the square.
```
I‽χ
```
Print a random digit.
```
‖C¬
```
Reflect horizontally and vertically to complete the matrix.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~45~~ ~~44~~ ~~43~~ 40 bytes
thanks @Adám for -1 byte
```
26{(⎕a,⍺⍴⎕d)[⌈∘⊖⍨⌈∘⌽⍨⍺+@(?⊂⌊⍵÷2)?⍵⍴⍺]},⍨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04CkkVm1BlAkUedR765HvVuAzBTN6Ec9HY86ZjzqmvaodwWU3bMXxO7dpe2gYf@oq@lRT9ej3q2Htxtp2gNpkMbeXbG1QENW/P@fpmABAA "APL (Dyalog Classic) – Try It Online")
uses `⌈` (max) of the matrix with its reflections to make it symmetric, so it's biased towards the latter part of the alphabet
the digit is chosen uniformly from 0...25 mod 10, so it has a small bias to lower values
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 31 bytes (Fixed digit position)
```
;
/2 c
VÆVÆBö}ÃgT0@Mq9îêUvÃêUv
```
[Try it online!](https://tio.run/##y0osKPn/35pL30ghmSvscBsQOR3eVnu4OT3EwMG30PJw86F1h1eFlh1uBpH//1so6AYBAA "Japt – Try It Online")
---
# [Japt](https://github.com/ETHproductions/japt), 41 bytes (Random digit position)
```
;
/2 c
VÆVÆBö}ÃgMq´VÉ ,MqVÉ @Mq9îêUvÃêUv
```
[Try it online!](https://tio.run/##y0osKPn/35pL30ghmSvscBsQOR3eVnu4Od238NCWsMOdCjq@hSDKwbfQ8nDzoXWHV4WWHW4Gkf//WyjoBgEA "Japt – Try It Online")
---
**Explanation**
```
; Change to new vars
/2 c set implicit var V equal to implicit var U / 2 rounded up
VÆVÆBö}ÃgT0@Mq9îêUvÃêUv Main function
VÆ Range from 0 to V and map
VÆ Range from 0 to V and map
Bö}Ã return random char from alphabet
gT0@ map upper-left corner
Mq9Ã return random number
®êUv horizontal mirror
êUv vertical mirror
```
[Answer]
# [Python 2](https://docs.python.org/2/), 259 bytes
```
from random import*
n=input();c=choice;r=range
w,W=n/2,-~n/2
o=n%2
A=map(chr,r(97,123))
l=[c(r(10))]+sample(A,n)+[c(A)for _ in' '*w*w]
l,e=l[:w*w],l[w*w:W*W]
shuffle(l)
l=[l[w*i:w*-~i]+e[i:i+1]for i in range(w)]+[e[-W:]]
for r in l+l[~o::-1]:print r+r[~o::-1]
```
[Try it online!](https://tio.run/##NU4xbsQgEOx5BU10YLASO8XpOFH4FS4QiiyC45UwoD2frDT@ugMnpdlZzczObP7dlhT785wxrRSn@F0A1pxwa0jUEPNzY/zutFsSOH9HXTw/nuxy1PG9l@1RJkk6vvVk0OuUmVtQIrtdZdd/ck6CNo4h6z44t@IxrTl4NsjIRaEHPiekXxTihV6avdktCdLrYFTdZTAF1NiMljyW5zyXy/AKrAIUT3uAFd6AAtHZGgUlir4eZHupM960o7KWVA2rFkQwR1Kq7azKCHGjKPCfOc/rHw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ ~~40~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands)
```
A.rs;ò©n∍9ÝΩ®DnαLʒ®%Ā}<Ωǝ®ô»¹Éi.º.∊ëº∊
```
+11 bytes to fix the digit being at a random position while still keeping rule 3 in mind for odd inputs..
-2 bytes thanks to *@MagicOctopusUrn*, changing `îï` to `ò` and changing the position of the `»`.
[Try it online](https://tio.run/##AUoAtf9vc2FiaWX//0EucnM7w7LCqW7iiI05w53OqcKuRG7OsUzKksKuJcSAfTzOqcedwq7DtMK7wrnDiWkuwrou4oiKw6vCuuKIiv//Nw) of [verify some more test cases](https://tio.run/##AVsApP9vc2FiaWX/MjVMw4x2eSc6wqssef9BLnJzO8Oywqlu4oiNOcOdzqnCrkRuzrFMypLCriXEgH08zqnHncKuw7TCu3nDiWkuwrou4oiKw6vCuuKIiv99LMK2P/83).
Old (**~~29~~ 27 bytes**) answer where the digit positions where always in the corners:
```
A.rs;ò©n∍¦9ÝΩì®ô»¹Éi.º.∊ëº∊
```
[Try it online](https://tio.run/##AToAxf9vc2FiaWX//0EucnM7w7LCqW7iiI3CpjnDnc6pw6zCrsO0wrvCucOJaS7Cui7iiIrDq8K64oiK//83) or [verify some more test cases](https://tio.run/##AUoAtf9vc2FiaWX/MjVMw4x2eSc6wqssef9BLnJzO8Oywqlu4oiNwqY5w53OqcOswq7DtMK7ecOJaS7Cui7iiIrDq8K64oiK/30swrY//w).
**Explanation:**
```
A # Take the lowercase alphabet
.r # Randomly shuffle it
# i.e. "abcdefghijklmnopqrstuvwxyz" → "uovqxrcijfgyzlbpmhatnkwsed"
s # Swap so the (implicit) input is at the top of the stack
; # Halve the input
# i.e. 7 → 3.5
ò # Bankers rounding to the nearest integer
# i.e. 3.5 → 4
© # And save this number in the register
n # Take its square
# i.e. 4 → 16
∍ # Shorten the shuffled alphabet to that length
# i.e. "uovqxrcijfgyzlbpmhatnkwsed" and 16 → "uovqxrcijfgyzlbp"
9ÝΩ # Take a random digit in the range [0,9]
# i.e. 3
®Dnα # Take the difference between the saved number and its square:
# i.e. 4 and 16 → 12
L # Create a list in the range [1,n]
# i.e. 12 → [1,2,3,4,5,6,7,8,9,10,11,12]
ʒ } # Filter this list by:
®%Ā # Remove any number that's divisible by the number we've saved
# i.e. [1,2,3,4,5,6,7,8,9,10,11,12] and 4 → [1,2,3,5,6,7,9,10,11]
< # Decrease each by 1 (to make it 0-indexed)
# i.e. [1,2,3,5,6,7,9,10,11] → [0,1,2,3,5,6,7,9,10]
Ω # Take a random item from this list
# i.e. [0,1,2,3,5,6,7,9,10] → 6
ǝ # Replace the character at this (0-indexed) position with the digit
# i.e. "uovqxrcijfgyzlbp" and 3 and 6 → "uovqxr3ijfgyzlbp"
®ô # Split the string into parts of length equal to the number we've saved
# i.e. "uovqxr3ijfgyzlbp" and 4 → ["uovq","xr3i","jfgy","zlbp"]
» # Join them by new-lines (this is done implicitly in the legacy version)
# i.e. ["uovq","xr3i","jfgy","zlbp"] → "uovq\nxr3i\njfgy\nzlbp"
¹Éi # If the input is odd:
# i.e. 7 → 1 (truthy)
.º # Intersect mirror the individual items
# i.e. "uovq\nxr3i\njfgy\nzlbp"
# → "uovqvou\nxr3i3rx\njfgygfj\nzlbpblz"
.∊ # And intersect vertically mirror the whole thing
# i.e. "uovqvou\nxr3i3rx\njfgygfj\nzlbpblz"
# → "uovqvou\nxr3i3rx\njfgygfj\nzlbpblz\njfgygfj\nxr3i3rx\nuovqvou"
ë # Else (input was even):
º∊ # Do the same, but with non-intersecting mirrors
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~198~~ ~~197~~ 196 bytes
Saved 2 bytes thanks to ceilingcat.
```
#define A(x)(x<n/2?x:n-1-x)
#define R rand()
S(n,x,y){int s[x=n*n];for(srand(s),y=R;x;)s[x]=97+(--x*31+y)%71%26;y=n/2;for(s[R%y+n*(R%y)]=48+R%10;x<n*n;++x%n||puts(""))putchar(s[A(x%n)+A(x/n)*n]);}
```
[Try it online!](https://tio.run/##NU7LCsIwELz3K0olsNs01FbxFYP4C@1Reijx1YOr2Aob1G@vqeJpZpgZZqw6Wdv3o/3h2NAh3AIj8JrSfMMrUpliDP5eEd5r2gMGJVDCicNnQ13Y7thQTJU@Xu/QfhMtJs4UmjV6szLLuQSlOJ5k0qGYZyKfaWf8xK@yK4STFIMHrMx0IQuRjbX/EJOWkgW9XrdH10IUIXpiz/VQ8kcFofSQEvp51O/@UjcE@Cwhnw3yAw "C (gcc) – Try It Online")
Explanation:
```
// Coordinate conversion for symmetry
#define A (x) (x < n / 2 ? x : n - 1 - x)
// Get a random and seed
#define R rand()
S (n, x, y)
{
// the array to store matrix values (x is the array size)
// Note that we do not need the whole array, only its first quarter
int s[x = n * n];
// iterate n*n-1 times until x is zero
for (srand(s), y = R; x;)
// and fill the array with pseudo-random sequence of letters
s[x] = 97 + (--x * 31 + y) % 71 % 26;
// this is the max. coordinate of the matrix element where a digit may occur
y = n / 2;
// drop a random digit there
s[R % y + n * (R % y)] = 48 + R % 10;
// Now we output the result. Note that x is zero here
for (;
x < n * n; // iterate n*n times
++x % n || puts ("") // on each step increase x and output newline if needed
)
// output the character from the array
putchar (s[A (x % n) + A (x / n) * n]);
}
```
[Answer]
# JavaScript (ES6), ~~213~~ ~~209~~ 206 bytes
```
n=>(a=[],F=(x=y=d=c=0,R=k=>Math.random()*k|0,g=y=>(r=a[y]=a[y]||[])[x]=r[n+~x]=v.toString(36))=>y<n/2?F(g(y,R[v=R(m=~-n/2)<!d&x<m&y<m?R(d=10):R(26)+10]=R[v]||++c,g(n+~y))&&++x<n/2?x:+!++y,R):!d|c<n?F():a)()
```
[Try it online!](https://tio.run/##LYxPb4JAEEfvforxAjMdpKiJB8rgzVt7oEfKYQNC/cOuWYmBlPrV6Wp6mffL5OUd1U1dS3u4dAttqv1Uy6QlRSV5EewEexmkklKiIJOTpO@q@w6t0pVpkV5OYxQ0TkjRisqH4nnGMS8o7wuxuea74y3szGdnD7rB9YZI0iHRr6vtDhscgiy/SYat3BfuR8m88vqk9Yak3WZYyTKiOMPVhngZFeJcV2cugwZdeiDyPOb@WetjnjO7HsXzaiwT7foUK0KaamNRg8D6DTQksIwcmQl@ZgCl0Vdz3odn06D/4SQf2FkMfvylH7tGTWGrLmhBUrDh0Rw0@uAT/U@n0cN/cPY7/QE "JavaScript (Node.js) – Try It Online")
### Commented
```
n => ( // n = input
a = [], // a[][] = output matrix
F = ( // F = main recursive function taking:
x = y = // (x, y) = current coordinates
d = c = 0, // d = digit flag; c = distinct character counter
R = k => // R() = helper function to get a random value in [0,k[
Math.random() * k | 0, // also used to store characters
g = y => // g() = helper function to update the matrix
(r = a[y] = a[y] || [])[x] // with horizontal symmetry
= r[n + ~x] = v.toString(36) // using the base-36 representation of v
) => //
y < n / 2 ? // if we haven't reached the middle row(s) of the matrix:
F( // do a recursive call to F():
g( // invoke g() ...
y, // ... on the current row
R[v = // compute v = next value to be inserted
R(m = ~-n/2) < !d & // we may insert a digit if no digit has been
x < m & // inserted so far and the current coordinates are
y < m ? // compatible: 2 distinct rows / 2 distinct columns
R(d = 10) // if so, pick v in [0, 9] and update d
: // else:
R(26) + 10 // pick v in [10, 35] for a letter
] = R[v] || ++c, // set this character as used; update c accordingly
g(n + ~y) // invoke g() on the mirror row
) && // end of outer call to g()
++x < n / 2 ? // if we haven't reached the middle column(s):
x // use x + 1
: // else
+!++y, // increment y and reset x to 0
R // explicitly pass R, as it is used for storage
) // end of recursive call to F()
: // else:
!d | c < n ? F() : a // either return the matrix or try again if it's invalid
)() // initial call to F()
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~346~~ 312 bytes
*will golf more tomorrow*
```
import StdEnv,Data.List,Math.Random,System.Time,System._Unsafe
$n#q=twice(transpose o\q=zipWith((++)o reverse o drop(n-n/2*2))q q)[[(['a'..'z']++['0'..'9'])!!(c rem 36)\\c<-genRandInt(toInt(accUnsafe(time)))]%(i*n/2,i*n/2+(n-1)/2)\\i<-[1..(n+1)/2]]
|length(nub(flatten q))>=n&&sum[1\\c<-q|any isDigit c]==2=q= $n
```
[Try it online!](https://tio.run/##PY7RT8IwEMbf@StKQNYyNmRGExPqEz6QYGJE48NYTCndaLJe2XpgIPztzg6iL5fv7rvv7idLJaAxdrMvFTFCQ6PNztZIlrh5hsNoJlDEC@1w9CJwG78J2FgzWh4dKhO/a6P@9NcHOJGrTh96FcdvLRXFWoDbWaeIXVX8pHefGreUhiGzpFYHVbcO2dR2RyGCcTJMGKtIxdKUpoEI4jg4BVkYpsFtqx@DjHW7VPqoIXcPbLWS06hQ0CLNASnatgopryAUPRxjLLuheuiPjy419J8mbJz4tJ5G6SSOKYTtIMs651JB4QFhv6Z5KRAVeBj2xGEwcHuTTi4fq7OAI9FupguNRGacJ7zipA/NEkWNnR5x@qQIJ/de5nuQqC34tt/hpL1aalCO0H@n3WbNj/Re4ZpovmhmRxBGy2vz6iO5rU0TrX8B "Clean – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 197 bytes
**As mentioned by @Emigna, doesn't work for odd values of `N` (I didn't understand the question properly)**
```
from random import*
def m(N):M=N//2;E=reversed;R=range;B=[randint(48,57),*(sample(R(97,123),N)*N)][:M*M];shuffle(B);r=R(M);m=[k+[*E(k)]for k in[[chr(B.pop())for i in r]for j in r]];m+=E(m);return m
```
[Try it online!](https://tio.run/##XU9Nb4MgGL7zK94jWLKuH1s7CRcTj3rwSjw0EydVkIAu2a93FG2WjAvwfOV57M/Ujea0LK0bNbibacKltB3dlKBGtqBxSdKCl/v9keXcyW/pvGxYxYP2S7KMi4dJmQmfr/TtQmiC/U3bQeIKf1zo4XgitCRJSWqRFklRM9/NbRvojDDHK1wQprnodyLJcU/qdnTQgzJCfHYOZy92tJiQB6oCCi4K7uuzZnrHc6xDkJxmZ0AvCMUd1rrQaNux/QL1TDlTeKdwpXB4TRGE46Sfhwl4WKtIRG7ey2AdpMErSYBzUJH7qxCZNeKf6b7pI7cWeAYhtPwC "Python 3 – Try It Online")
I do think the calls to `randint()` + `sample()` + `shuffle()` are too much, and getting rid of in-place shuffling would be great :)
I'm pretty sure this part (that selects the letters & digit) could be golfed a bit more.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~275~~ 266 bytes
```
from random import*
def f(n):
R=range;C=choice;A=map(chr,R(97,123));b=N=n-n/2;c=`C(R(10))`;s=[c]+sample(A,n-1)+[C(A)for i in R(N*N-n)]
while b:shuffle(s);i=s.index(c);b=n%2>(i<N*N-N>N-1>i%N)
a=[r+r[~(n%2)::-1]for r in[s[i::N]for i in R(N)]];return a+a[~(n%2)::-1]
```
[Try it online!](https://tio.run/##TZDBboMwEETP5St8ifAGkxbSKqpdI0W5@8DVtRRCTHEVFmSI2l766xSrrZTTjjRvdqQZvqa2x3yeG993xFd4Xo7rht5P6@hsG9JQBB6RUi7emxUHWbe9q63Yy64aaN16VtLnHcvyLYA4SSUxxftc1PJ4oCXNHgCOYpS6NslYdcPF0j3DNINEH@gemt4TRxySkqq1ShFMRD5ad7HkxMf22jQLP4Jwctw4PNtPWocOXOUFdS8hoQqVZoVbKYhIJbVPvP6miw@cp5kJ75cC1KN2nCtzWwfGCG@nq0dSJdVtag4YBkxv2SN7YvnO8Ohu8A4ngv8ifsV48947pGGH@FezsBbAHzPPPw "Python 2 – Try It Online")
Returns the array as a list of lists of characters. To satisfy Rule 1, we set up a pool of characters:
```
s = [c] # the unique digit...
+ sample(A,n-1) # then sample without replacement `n-1` chars in a-z,
# so we have `n` distinct chars
+ [C(A)for i in R(N*N-n)] # and fill out the rest with any in a-z
```
The next tricky bit is rule 3: there must be *exactly 2* columns and rows having a digit; this means for `n` odd, that the chosen digit may not appear in the middle column or middle row. Since we construct the array using a twice reflected square sub array `s`, that is accomplished here by using:
```
while b: # to save a couple bytes, `b` is initialized
# to `N`, which is greater than 0.
shuffle(s) # shuffle at least once...
i = s.index(c) # c is the unique digit used
b = n%2
> # if n is even, 0>(any boolean) will be false,
# so exit the loop; otherwise n odd, and we are
# evaluating '1 > some boolean', which is equivalent
# to 'not (some boolean)'
(i<N*N-N # i is not the last column of s...
> # shortcut for ' and ', since N*N-N is always > N-1
N-1>i%N) # is not the last row of s
```
i.e., shuffle at least once; and then, if `n` is odd, keep looping if the digit is in the last column or the last row of `s`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 48 bytes
```
L+b_<b/Q2JmO/Q2 2jy.eyXWqhJkbeJOT<csm.SGQK.EcQ2K
```
Try it out online [here](https://pyth.herokuapp.com/?code=L%2Bb_%3Cb%2FQ2JmO%2FQ2%202jy.eyXWqhJkbeJOT%3Ccsm.SGQK.EcQ2K&input=8&debug=0).
The program is in 3 parts - definition of palindromisation function, choosing location of numeric, and main function.
```
Implicit: Q=eval(input()), T=10, G=lower case alphabet
L+b_<b/Q2 Palindromisation function
L Define a function, y(b)
/Q2 Half input number, rounding down
<b Take that many elements from the start of the sequence
_ Reverse them
+b Prepend the unaltered sequence
JmO/Q2 2 Choose numeric location
O/Q2 Choose a random number between 0 and half input number
m 2 Do the above twice, wrap in array
J Assign to variable J
jy.eyXWqhJkbeJOT<csm.SGQK.EcQ2K Main function
cQ2 Divide input number by 2
.E Round up
K Assign the above to K
.SG Shuffle the alphabet
sm Q Do the above Q times, concatenate
c K Chop the above into segments of length K
< K Take the first K of the above
.e Map (element, index) as (b,k) using:
qhJk Does k equal first element of J?
W If so...
X b Replace in b...
eJ ...at position <last element of J>...
OT ...a random int less than 10
Otherwise, b without replacement
y Apply palindromisation to the result of the above
y Palindromise the set of lines
j Join on newlines, implicit print
```
Using several shuffled alphabets should ensure that the number of unique characters is always more then the input number.
[Answer]
# **Python 2/Python 3, 227 bytes**
```
from random import*
def m(N):n=N-N//2;r=range;C=choice;c=n*[chr(i+97)for i in r(26)];shuffle(c);c[C([i for i in r(n*(N-n))if(i+1)%n+1-N%2])]=`C(r(10))`;R=[c[i*n:i*n+n]+c[i*n:i*n+n-N%2][::-1]for i in r(n)];return R+R[::-1][N%2:]
```
ungolfing a bit:
```
from random import * # get 'choice' and 'shuffle'
def matrix(N):
n = ceil(N/2) # get the size of the base block
# get a shuffleable lowercase alphabet
c = [chr(i+97)for i in range(26)]
c = n*c # make it large enough to fill the base-block
shuffle(c) # randomize it
digit = choice('1234567890') # get random digit string
## this is only needed as to prevent uneven side-length matrices
# from having centerline digits.
allowed_indices = [i for i in range( # get all allowed indices
n*(N-n)) # skip those, that are in an unmirrored center-line
if(i+1)%n # only use those that are not in the center column
+1-N%2] # exept if there is no center column
index = choice(allowed_indices) # get random index
c[index]=digit # replace one field at random with a random digit
##
R=[]
for i in range(n):
r = c[i*n:i*n+n] # chop to chunks sized fit for the base block
R.append(r+r[::-1][N%2:]) # mirror skipping the center line
return R+R[::-1][N%2:] # mirror skipping the center line and return
```
Older, *almost* correct versions below:
**Python2, Python3, 161 bytes**
```
from random import *
N=26
n=N-N//2
c=[chr(i+97)for i in range(26)]
R=[ r+r[::-1][N%2:]for r in[(shuffle(c),c[:n])[1]for i in range(n)]]
R+=R[::-1][N%2:]
print(R)
```
It seems N differing elements is only *almost* guarranteed.
**Python 2/Python 3, 170 bytes**
```
from random import*
def m(N):n=N-N//2;r=range;c=n*[chr(i+97)for i in r(26)][:n*n];shuffle(c);R=[_+_[::-1][N%2:]for _ in[c[i*n:i*n+n]for i in r(n)]];return R+R[::-1][N%2:]
```
It seems I forgot rule 3. Also somehow the [:n\*n] slipped in.
] |
[Question]
[
# We are searching for a sequence
Take the **natural numbers**
`1,2,3,4,5,6,7,8,9,10,11,12,13,14...`
Convert to **base-2**
`1,10,11,100,101,110,111,1000,1001,1010,1011,1100,1101,1110...`
**Concatenate** the above numbers
`110111001011101111000100110101011110011011110...`
**Partition** this number in **Prime-Chunks**
(chunks containing a prime number of digits)
Primes are taken in asceding order `2,3,5,7,11,13,17...`
`[11][011][10010][1110111][10001001101][0101111001101][1110...]`
and find the **Sum of the digits of each chunk**
`Primes 2 3 5 7 11 13 17`
`Chunks [11][011][10010][1110111][10001001101][0101111001101][1110...]`
`SumOfDigits 2 2 2 6 5 8`
# The Sequence
>
> 2, 2, 2, 6, 5, 8, 9, 10, 14, 22, 11, 18, 25, 27, 32, 21, 28, 32, 40, 40, 49, 49, 32, 41, 49, 53, 63, 55, 63, 70, 87, 73, 51, 63, 71, 78, 78, 90, 107, 86, 96, 108, 115, 128, 138, 92, 83, 95, 102, 110, 130, 106, 122, 141, 149, 163, 130, 140, 151, 165, 181, 165, 204, 200, 234, 100, 130, 138, 167, 149, 169, 180, 209, 166, 189, 194, 222, 205, 234, 260, 216, 206, 217, 241, 240, 267, 289, 242, 274, 308, 286, 329, 338, 155, 189, 225, 197, 240, 272, 217, 254, 282, 287, 317, 281, 256, 299, 286, 331, 337, 316, 350, 354, 391, 367, 282, 327, 313, 364, 358, 348, 397, 406, 466...
>
>
>
# The Challenge
Find the `nth` term of the above sequence
# Input
An integer `n>0`
# Test Cases
```
1->2
3->2
6->8
36->78
60->165
160->581
260->1099
350->1345
```
This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'").Shortest answer in bytes wins!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
Σ!CİpṁḋN
```
[Try it online!](https://tio.run/##yygtzv7//9xiRecjGwoe7mx8uKPb7////4YGAA "Husk – Try It Online")
## Explanation
```
Σ!CİpṁḋN
N Start with the infinite list of natural numbers.
ṁḋ Convert each to its binary representation and join them all together. (A)
İp Get the infinite list of primes. (B)
C Split (A) into chunks of lengths (B).
! Retrieve the nth chunk (where n is the input).
Σ Sum the bits in this chunk.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
RÆNµSRBFṁRṪS
```
[Try it online!](https://tio.run/##ATcAyP9qZWxsef//UsOGTsK1U1JCRuG5gVLhuapT/8W8w4figqxH//9bKnJhbmdlKDEsIDM3KSwgNjBd "Jelly – Try It Online")
### How it works
```
RÆNµSRBFṁRṪS Main link. Argument: n
R Range; yield [1, ..., n].
ÆN N-th prime; yield P := [p(1), ..., p(n)].
µ Begin a new, monadic chain with argument P.
S Take the sum of P, yielding s := p(1) + ... + p(n).
R Range; yield [1, ..., s].
B Binary; convert all integers from 1 to s to base 2.
F Flatten the resulting array.
R Range; yield [[1, ..., p(1)], ..., [1, ..., p(n)]].
ṁ Mold; reshape the result to the left like the result to the right.
Ṫ Tail; take the last chunk.
S Take the sum, counting the set digits.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
### Code
Can get pretty slow for large numbers:
```
ÅpDOLbJs£`SO
```
Uses the **05AB1E**-encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//cGuBi79PklfxocUJwf7//xubGgAA "05AB1E – Try It Online")
### Explanation
```
Åp # Get a list of the first <input> primes
DO # Duplicate and sum the primes
L # Create the list [1, .., <sum>]
bJ # Convert to binary and join into a single string
s£ # Get the slices [a[0:2], a[2:2+3], a[2+3:2+3+5], a[2+3+5:2+3+5+7], ...]
corresponding to the list of primes
`SO # Get the last one and sum up it's digits
```
[Answer]
# Mathematica, 71 bytes
```
(Tr/@TakeList[Join@@IntegerDigits[Range[#^2+1],2],Prime~Array~#])[[#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/BfI6RI3yEkMTvVJ7O4JNorPzPPwcEzryQ1PbXIJTM9s6Q4OigxLz01WjnOSNswVscoViegKDM3tc6xqCixsk45VjM6Wjk2Vu0/UDSvRMEhLdrY1CD2PwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
RÆNSRBF
RÆN+\‘ṬœṗÇ⁸ịS
```
[Try it online!](https://tio.run/##y0rNyan8/z/ocJtfcJCTGxeIoR3zqGHGw51rjk5@uHP64fZHjTse7u4O/v//v5kBAA "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
RBFṁ
RÆNSÇṫÆNC$S
```
[Try it online!](https://tio.run/##y0rNyan8/z/Iye3hzkauoMNtfsGH2x/uXA1kOKsE/z/c/qhpzf//hgYA "Jelly – Try It Online")
## Explanation
```
RBFṁ Helper link. Input: integer k
R Range, [1, 2, ..., k]
B Convert each to a list of its binary digits
F Flatten
ṁ Shape it to length k
RÆNSÇṫÆNC$S Main link. Input: integer n
R Range, [1, 2, ..., n]
ÆN Get i'th prime for each
S Sum
Ç Call helper link
$ Monadic chain
ÆN Get n'th prime
C Complement, 1 - n'th prime
ṫ Tail, take the last n'th prime digits
S Sum
```
[Answer]
# [R](https://www.r-project.org/), ~~206~~ 200 bytes
```
function(n){a=p=j=y=2
for(i in 2:n-1){while(sum(y)<4*a){x=as.double(rev(intToBits(j)))
y=c(y,x[cumsum(x)>0])
j=j+1}
b=1:a
y=y[-b]
z=outer(k<-b+a,p,'%%')
p=c(a<-k[!apply(z<1,1,sum)][1],p)}
sum(y[1:a])}
```
[Try it online!](https://tio.run/##HY/BboMwEETv/gqKFGW3WSqcVBwQ7qHf0BvlYFxQTRJjgWlxEN9OTa@jmac3w9aKrZ2Mcro3YHCRwopOeHFmbT@AjrSJzrlJOC6/3/rWwDjdwWPx@ixxmYUcX776qQ750PyANu6jf9duhA4RmRcKPM2lmu77asa3tELWie7EV1YLnstQ8WVSV@wh@sk1A1yLpD5JsnQ8HI7IbCDIIrmWT9Lam4dHwYlTgGFV8oosruzfpwysCtdtVza7sgJOF8roklGWEs9SxIVFSjowFOcxteEqxZ8mRrZufw "R – Try It Online")
The algorithm tries also to "save" on space by iteratively removing bits as it cycles through the primes. I feel that the decimal to bit conversion could probably be shorter, but I could not figure out other alternatives.
Saved 6 bytes thanks to Jonathan French.
[Answer]
# JavaScript (ES6), 144 bytes
```
n=>eval("s=o=j=0;for(i=p=1;n;d>p&&(n--,s+=p))for(p++,d=2;p%d++;);while(b=Math.log2(++j)+1|0,i<=s)for(x=0;x++<b&i<=s;)o+=i++>s-p&&j<<x&1<<b?1:0")
```
## Ungolfed
```
n=>{
s=o=j=0;
for(i=p=1;n;d>p&&(n--,s+=p))
for(p++,d=2;p%d++;);
while(b=Math.log2(++j)+1|0,i<=s)
for(x=0;x++<b&i<=s;)
o+=i++>s-p&&j<<x&1<<b?1:0
return o
}
```
## Test Cases
```
f=
n=>eval("s=o=j=0;for(i=p=1;n;d>p&&(n--,s+=p))for(p++,d=2;p%d++;);while(b=Math.log2(++j)+1|0,i<=s)for(x=0;x++<b&i<=s;)o+=i++>s-p&&j<<x&1<<b?1:0")
;[1,3,6,36,60,160,260,350].forEach(t=>console.log(t,"->",f(t)))
```
```
.as-console-wrapper{max-height:100%!important}
```
[Answer]
# [Perl 6](https://perl6.org), 67 bytes
```
{(1..*).map(|*.base(2).comb).rotor(grep *.is-prime,2..*)[$_-1].sum}
```
[Test it](https://tio.run/##TU7BSsQwFLznKx5LkaQ26Sa1tUtp8LoXT95ckW4bpbBpQpKCsu6XefPHaru7oJdh3sy8Yaxyh2LSn3DTmk5BPR0xZywmTDcWf8Vs33iFBWGt0XvCnAnG4XenLMSs99S6XqtELA/P0SvlL8yP@jSNXsGT8qFCc/FDmBnUEMXbx3MNTnfdbUp@vtl2mCP20AzXUAqiQm/GXU8qIeoHO4YEIvVhVRtUB0cE0HtY1uKLS/7ZCawuItTyT11V6DRxKgXKFiioLFE2432JijWVvMgRX0heciTOynqzQVm@sOwu/wU "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
(
1 .. * # Range of all numbers starting with 1
).map(
# WhateverCode lambda
| # Slip each of these values into the outer list individually
* # this is the parameter
.base(2) # convert base
.comb # split into digits
).rotor( # split into chunks
grep *.is-prime, 2..* # the sequence of prime numbers
)[ $_ - 1] # index into it using 1 based indexing
.sum # find the sum
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 114 bytes
```
n=input();k=m=1;p=[0];s=''
exec's+=bin(k)[2:];p+=m%k*[k+p[-1]];m*=k*k;k+=1;'*n*n*2
print s[p[n-1]:p[n]].count('1')
```
[Try it online!](https://tio.run/##JY9JDoMwDEXX5BTeVGYIFaESCyL3IlEWTFVRiokYpPb0NLT6sv/Gw/v@sz1nLo9u7gcgQMSDaWS/b3GiHU2ktCdTWL0SohjeQ4drRu3IsUtMWVvtM5ouLjUu8yZX1uopJZc67bKwiikHlcIvI2@wGm84zNTBrL12885bjAqTI7wV4jEvwDAyKAk3CVXooapCgqqKWkT/IywB8ztKEf0oA/Ormdq@qYFFdPLBGeX4Ag "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), ~~138~~ ~~132~~ 123 bytes
```
N=>(n=k=1,g=s=>N?g((P=n=>n%--x?P(n):x<2)(x=++n)?s[n]?s.slice(--N&&n,n/!N):s+(n--,k++).toString(2):s):s.split`1`.length-1)``
```
### Test cases
[Try it online!](https://tio.run/##dc3faoMwGAXw@z2Fu1hJiJ8mdto/LPoGUtjlKNO61GaGL6UJQ/bymZR5MWFwrs6Pw/lsv1rX3fTVw6k9KQNoP1Q4RzLUsiQoByniXjpZ1lVPyEGiLPEJYKwOBOl@fMkoGSVjSCv3hsfKJc7oThGAerXCGNPHmu4dIwgQD4zRxNtXf9PYk2zqpyTuarRvRJMYhb2/gKBNEzqLzhqVGNuTMxGURlGUplH28BfW/0Exw3a5uMsEm6UU/FdEkS9I3G2ifCsWlM0k@G63/MpnWz/nIQA433bDu9PfSmac8x8)
### Demo
*NB: Only 'safe' test cases are included here (guaranteed to work on Chrome, Firefox and Edge). You may have to increase the call stack size of your engine to pass the other ones.*
```
let f =
N=>(n=k=1,g=s=>N?g((P=n=>n%--x?P(n):x<2)(x=++n)?s[n]?s.slice(--N&&n,n/!N):s+(n--,k++).toString(2):s):s.split`1`.length-1)``
console.log(f(1)) // 2
console.log(f(3)) // 2
console.log(f(6)) // 8
console.log(f(36)) // 78
console.log(f(60)) // 165
```
### Formatted and commented
```
N => ( // given N = index of the expected term
n = k = 1, // n = current prime, k = current natural number
g = s => // g = recursive function taking s = binary string
N ? // if we haven't reached the correct chunk yet:
g( // do a recursive call to g():
(P = n => // P() returns: true for prime
n % --x ? P(n) : x < 2) // false for composite
(x = ++n) ? // increment n; if n is prime:
s[n] ? // if s is long enough:
s.slice(--N && n, // either remove this chunk (if N > 0)
n / !N) // or truncate it to the correct size (if N = 0)
: // else:
s + (n--, k++) // append the next natural number to s
.toString(2) // in binary format
: // else:
s // just look for the next prime
) // end of recursive call
: // else:
s.split`1`.length - 1 // return the number of 1's in the last chunk
)`` // initial call to g() with an empty string
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~143~~ ~~139~~ 133 bytes
*-4 bytes thanks to @ErikTheOutgolfer*
```
s='1';i=x=1
exec"s=s[i:];i+=1\nwhile~-all(i%x for x in range(2,i)):i+=1\nexec's+=bin(x)[2:];x+=1;'*i;"*input()
print s[:i].count('1')
```
[Try it online!](https://tio.run/##JY7dDoIgHMXveQrW1gCtJrhck/Ek5oUZ5X9z4AAX3fTqhHVxrs7H7yzvMFkj0mjvWjlCSPKKcCJBRcWRjnrceeU7aHsJpeJX85pg1p/jMM8U9hE/rMMRg8FuME9NxQEYa//JrUx8qW5gaGSdyBMxG5IUIHcFmGUNlKHFgQnYdy30p9GuJtCMZyk/@dHxdqy4JI5q1KC6QU2FeJbIqs/VFw "Python 2 – Try It Online")
[Answer]
# J, 48 bytes
```
([:+/-@{:{.+/{.[:}:[:(#:@[,])/1+[:i.1++/)@:p:@i.
```
## explained
```
( )@:p:@i. the first n primes, passed to...
-@{: {. ... take "nth prime" elements from the tail of...
+/ sum the first n primes and...
{. take that number of elements from...
[: }: all but the last element of... <----------------<
1 + [: i. 1 + +/ sum first n primes, add 1 (so we have enough |
for case n=1) -- make that many natural numbers |
[: (#:@[ , ])/ reduce them by turning into lists of binary |
digits and catting, however the rightmost number |
won't get reduced, hence the need for ------------^
([: +/ and sum those digits
```
[Try it online!](https://tio.run/##DcNBCsMgEAXQvaf4pIsok47a5YeA9xi6KpGYTQpZSs5u@@Ado15YiYT/4Y0Sn6Wzq8SuxptG/2Cx5R1iFmPTLBJD4Zel6QhuUsx15YwFN1Ev57bPfsLXKQVkCJq@0vgB "J – Try It Online")
[Answer]
# JavaScript 1+ + substr, 135 bytes
```
for(n=prompt(s=P=0),i=n*n*n*8;--i;)s=i.toString(2)+s;for(p=1;n;e=j?s:--n?P+=p:s.substr(P,p))for(j=p++;p%j--;);eval([].join.call(e,'+'))
```
] |
[Question]
[
Given a real number, convert it to a list of lists, with the negative sign (if any) becoming an empty list, the integer part becoming a list of digits, and the fractional part (if any) becoming a list of digits. The digits must be actual numbers, not strings.
### Examples
`0` ‚Üí `[[0]]`
`123` ‚Üí `[[1,2,3]]`
`-123` ‚Üí `[[],[1,2,3]]`
`123.45` ‚Üí `[[1,2,3],[4,5]]`
`0.45` ‚Üí `[[0],[4,5]]`
`-0.45` ‚Üí `[[],[0],[4,5]]`
`-123.45` ‚Üí `[[],[1,2,3],[4,5]]`
[Answer]
# C#, ~~60~~ 66 bytes
```
using System.Linq;s=>s.Split('-','.').Select(p=>p.Select(c=>c-48))
```
[Try it online!](https://tio.run/##jVBNSwMxEL3nVwy5bEKzoWoFod1cioqiIPTQQ@khplMNbJO6kxWk9Lev6ad68/Lmg3mPec9RuYohdi358AaTL0q4GrLfk37y4WPImKstEbywDaNkk3fwGf0Cnq0PQublXRvciFKTiepIHMe6Rpd8DKTvMWDjnX64De0KG/ta4@ifZz4kYwwsoYKOKkN6sq59EkVZqEIXUk9wRxfryqxPvauMKwc3Unb58UVss8xsDgkpjS0hZaUN9BVcXF4pKPeYQQ@uFfT3WB7LYQvbIVvGBq17B3FQO2uBDz@6ko2ziVijnjY@YQ4OBZ9x6MEhmGw1OJvEUpzpPeD8bMFCZeAP4THmeLniCqzc3c65PNXsbMu23Tc "C# (Mono) – Try It Online")
[Answer]
# JavaScript (ES6), ~~33~~ ~~44~~ ~~43~~ 41 bytes
Takes input as a string. Sacrificed ~~11~~ 10 bytes converting the elements in the output to numbers after the challenge spec was updated.
```
s=>s.split(/\D/).map(a=>[...a].map(eval))
```
* Saved a byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s suggestion of using `eval`.
---
## Test it
```
console.log((
s=>s.split(/\D/).map(a=>[...a].map(eval))
)("-123.45"))
```
---
## Explanation
```
s=>
```
Anonymous function taking the string as an argument via parameter `s`.
`"-123.45"`
```
s.split(/\D/)
```
Use RegEx to split the string to an array on all non-digit characters - i.e., `-` and `.`
`["","123","45"]`
```
.map(a=>)
```
Map over the array, passing each string to a function via parameter `a`.
```
[...a]
```
Split to an array of individual character strings.
`[[],["1","2","3"],["4","5"]]`
```
.map(eval)
```
Map over the subarray and `eval` each string, which converts it to an integer.
`[[],[1,2,3],[4,5]]`
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
lambda x:[map(int,i)for i in`x`.replace(*'-.').split('.')]
```
[Try it online!](https://tio.run/##DctBCoAgEEDRq7hzJkooaBN0kgqyUhpQG8ygTm/u/uJ9/tJ5hS7bcc5O@@3Q4h0mrxkopJrQXlGQoLC@q4qGnd4NVLJREtXNjhLIkkvmWDjYMvGTABFz06r@Bw "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒṘµ<”/œpV€
```
A monadic link taking a number and returning the resulting list of lists of numbers.
**[Try it online!](https://tio.run/##y0rNyan8///opIc7ZxzaavOoYa7@0ckFYY@a1vw/3A4W/f9fV8/EFAA "Jelly – Try It Online")** (the footer just prints the python representation to show all the actual lists)
...or see the [test suite](https://tio.run/##y0rNyan8///opIc7ZxzaavOoYa7@0ckFYY@a1vw/uudwO1hcBcjLAuJHDXMUdO0UgGoi//@PNtBRMDQy1lHQBZNAQs/EVEcBTOhCSIhYLAA "Jelly – Try It Online").
### How?
```
ŒṘµ<”/œpV€ - Link: number
ŒṘ - Python representation (yields a string representation of the number)
µ - monadic chain separation (call that s)
”/ - literal '/' character
< - less than? (vectorises) ('.' and '-' are, digit characters are not)
œp - partition s at truthy indexes of the resulting list discarding the borders
V€ - evaluate €ach (list of characters) as Jelly code (vectorises)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
Thanks to *Riley* for saving a byte. Code:
```
'-'.:'.¡εSï
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f9fXVddz0pd79DCc1uDD6///1/X0MhYz8QUAA "05AB1E – Try It Online")
Explanation:
```
'-'.: # Replace "-" by "."
'.¬° # Split on "."
ε # Apply to each element..
S # Split into a list of characters
ï # Convert back to int
```
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
lambda a:[[]]*(a<0)+[map(int,n)for n in`abs(a)`.split('.')]
```
[Try it online!](https://tio.run/##JYzBDoIwEETvfsXe2FVsFOVC9EtKE5ZoYxNYGroXv74UvbzM5E0mfvWzSJP9s88Tz@OLgTtrnTsiPy50sjNHDKK1kF9WEAgy8JiQaTApTkGxMhW5vEt9Jy0e8Nrcajj/WGDu7b@VQN0BIK7lED3ue6K8AQ "Python 2 – Try It Online")
-5 bytes from Felipe Nardi Batista
[Answer]
# [Actually](https://github.com/Mego/Seriously), 23 bytes
```
'.@;)A$s⌠♂≈⌡M[[]]+@s~@t
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/19dz8Fa01Gl@FHPgkczmx51djzqWegbHR0bq@1QXOdQ8v@/rqGRsZ6JqRkA "Actually – Try It Online")
Explanation:
```
'.@;)A$s⌠♂≈⌡M[[]]+@s~@t
'. push "."
@;) make a copy of the input and move it to the bottom of the stack
A$s absolute value of input, stringify, split on periods
⌠♂≈⌡M convert integer and fractional parts to lists of digits
[[]]+ prepend an empty list
@s~ bitwise negation of sign of input (1 -> -2, 0 -> -1, -1 -> 0)
@t elements in the list starting at that 0-based index (drops the leading empty list if the input was positive)
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 11 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
Ζ-.ŗ .Θ⌡č¹r
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMzk2LS4ldTAxNTclMjAuJXUwMzk4JXUyMzIxJXUwMTBEJUI5cg__,inputs=LTEyMy40NTY_)
Outputs to the top of the stack (because SOGL converts it to a multiline string because it is made for ascii-art). To view the result, look in the console after ``r`@10:` (the outer brackets are the stack arrays) or just append `οø∑` after the code
```
Ζ-.ŗ replace "-" with "."
.Θ split on "."s
‚å° for each
č chop into characters (casts to strings :/)
¬π wrap in array (this + for each is like map())
r reverse types, vectorizing
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/) (v2.0a0), ~~12~~ ~~10~~ 8 bytes
Takes input as a string.
```
q\D ®¬®n
```
[Test it](http://ethproductions.github.io/japt/?v=2.0a0&code=cVxEIK6srm4=&input=Ii0xMjMuNDUiCi1R) (`-Q` flag for visualisation purposes only.)
* 2 bytes saved thanks to [Justin](https://codegolf.stackexchange.com/users/69583/justin-mariner).
* 2 bytes saved thanks to ETH.
---
## Explanation
Implicit input of string `U`.
```
q\D
```
Use RegEx to split (`q`) to an array on all non-digit characters.
```
®
```
Map over the array.
```
¬
```
Split each string to an array of individual characters.
```
®
```
Map over the array.
```
n
```
Convert to integer.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 54 bytes
```
@(x)cellfun(@(c){c-48},strsplit(num2str(x),{'-' '.'}))
```
Anonymous function that takes a number as input and produces a cell array of numeric vectors.
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330GjQjM5NScnrTRPw0EjWbM6WdfEolanuKSouCAns0QjrzTXCMgBqtKpVtdVV1DXU6/V1PyfpqFraGSsZ2Kq@R8A "Octave – Try It Online")
### Explanation
```
@(x)cellfun(@(c){c-48},strsplit(num2str(x),{'-' '.'}))
@(x) % Function with input x
num2str(x) % Convert x to string
strsplit( ,{'-' '.'}) % Split at '-' or '.'. Gives a
% cell array of substrings
cellfun( , ) % To each substring apply
% the following function
@(c){c-48} % Subtract 48 from each char
% and pack into a cell
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~170~~ ~~164~~ ~~152~~ ~~146~~ 144 bytes
Should be able to golf this down a bit...
```
#define P printf
#define V *v[1]
main(c,v)char**v;{for(V^45?P("[[%c",V++):P("[[],[%c",V++,V++);V;V^46?P(",%c",V++):P("],[%c",V++,V++));P("]]");}
```
[Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIUChoCgzrySNCyYQpqBVFm0Yy5WbmJmnkaxTppmckVikpVVmXZ2WX6QRFmdiah@goRQdrZqspBOmra1pBebF6sAEwILWYdZAlWYglTrICtGUaVqDxGKVNK1r////r2toZKxnYgoA "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ŒṘ⁾-.yṣ”.V€€
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7Zzxq3KerV/lw5@JHDXP1wh41rQGi/4fbwXL//@sa6pkCAA "Jelly – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 16 bytes
```
$'.'-(Æ'.@s⌠♂≈⌡M
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/19FXU9dV@Nwm7qeQ/GjngWPZjY96ux41LPQ9/9/XQM9E1MA "Actually – Try It Online")
Explanation:
```
$'.'-(Æ'.@s⌠♂≈⌡M Implicit eval'd input
$ Convert to str
'. Push '.'
'- Push '-'
( Rotate stack left
Æ Pop a, b, c; push c.replace(b, a)
'. Push '.'
@ Pop a, b; push b, a (swap)
⌠♂≈⌡ Push function ♂≈
‚ôÇ Map
≈ Convert to int
M Map
```
[Answer]
## R, ~~51~~ ~~47~~ 72 bytes
```
x=RG::s(strtoi(s(gsub('-','.',scan()),on='\\.')))
x[is.na(x)]=list(NULL)
```
I'm loving the `RG` library.
Had to add 26 bytes to make sure the empty list was actually empty.
```
gsub('-','.',scan()) # replace - with . in input; also converts to string
s( ,on='\\.') # split string on '.'
strtoi( ) # convert to numeric
RG::s( ) # convert to lists of digits
x[is.na(x)]=list(NULL) # converts list of `NA` to empty list
```
Example output:
```
> x=RG::s(strtoi(s(gsub('-','.',-123.45),on='\\.')))
> x[is.na(x)]=list(NULL)
> x
[[1]]
NULL
[[2]]
[1] 1 2 3
[[3]]
[1] 4 5
```
[Answer]
# [Perl 5](https://www.perl.org/), 56 54 + 1 (-p) = 55 bytes
```
$_="[[$_]]";s/\D\K\./0./;s/\d(?=\d)/$&,/g;s/-|\./],[/g
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lYpOlolPjZWybpYP8YlxjtGT99ATx/ESdGwt41J0dRXUdPRTwcK6NYA5WJ1ovXT///XNTQy1jMx/ZdfUJKZn1f8X7cAAA "Perl 5 – Try It Online")
*Saved two bytes due to Dom reminding me about $&*
**Explanation:**
```
$_="[[$_]]"; # Add opening and closing to ends of strings
s/\D\K\./0./; # handle the case of .45 or -.45 by inserting 0 before
# the decimal. Otherwise, .45 & 45 would be ambiguous.
s/\d(?=\d)/$&,/g; # Put a comma between numbers.
s/-|\./],[/g # Turn - and . into separators between lists
```
[Answer]
# [Perl 6](https://perl6.org), 23 bytes
```
+«*.split(/\D/)».comb
```
[Test it](https://tio.run/##VZFNbsIwEIX3PsUItcUGx4R/CSuoiy677C5kkSaDFOEQizioUdUT9QjdcbHU@SHAbvy9p2e/scaTWlVFjnBeiUiStISXKIsRvGp8@R2JXKvE0MnubcIufyLK0s@qMb0azA14QAmAC94WfN8NeMDtcTqbt2DKZ3zeQaenAe@Eq1kslg9@f8GXrej2knuPnRu3@FG6z@tv6g1Mkrrqh327JFqFRxg3RSTZZ6euk7MFCpsDlvQpOerCMA6bc6gKpI3OgMG3vcnuYIdfGiODsd1Do4k01HQk3hM7JgZT1ozSupPciRG1KqFe7i35msBhANBSsU8NHT6v8yGra7TB2n4TZQPyU/0D "Perl 6 – Try It Online")
## Expanded
```
+¬´\ # numify each of the following (possibly in parallel)
*\ # WhateverCode lambda (this is the input)
.split(/\D/)\ # split on non-digits ( . and - )
».comb # split each of those into individual characters
```
Note that `…».comb` is a higher precedence than `+«…`
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
lambda x:(x<0)*[[]]+[map(int,i)for i in`abs(x)`.split('.')]
```
[Try it online!](https://tio.run/##LY3BDoMgEAXv@xV7E1ok1NaLqV9CScQ0pJsoEuVAvx7R9jKTvMO88I2fxTfZ9a882Xl8W0wdS0/FL1obc9WzDYx8FMTdsiIh@cGOG0t8kFuYKLJKVtxk6rUScGvuAuqTBfLRClAn679@q4GjlUoLqQMMazlAV5qIeQc "Python 2 – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 13 bytes
```
r'-'.er'./::~
```
[Try it online!](https://tio.run/##S85KzP3/v0hdV10vtUhdT9/Kqu5/wn9dAz0TUwA "CJam – Try It Online")
[Answer]
# Pyth, 12 bytes
```
sMMcXz\-\.\.
```
[Try it here.](http://pyth.herokuapp.com/?code=sMMcXz%5C-%5C.%5C.&input=-0.45&debug=0)
[Answer]
# [Perl 6](http://perl6.org/), 22 bytes
```
{m:g/^\d*|\d+/».comb}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtcqXT8uJkWrJiZFW//Qbr3k/Nyk2v/WCsWJlQpKKvEKtnYK1WkaKvGaeumZxSW1Sgpp@UUKNgYKhkbGCrogAoj1TEwVDECELoSECNlZ/wcA "Perl 6 – Try It Online")
The elements in the returned list are strings, but as is normal for Perl, they can be used as numbers and will be converted implicitly; they are "actual numbers" for all practical purposes. To force them to be numbers in their most immediate representation, one need only prefix the contents of the code block with "+¬´" for three more bytes.
[Answer]
# RUBY, 75 bytes
```
->(x){(x<0?[[]]:[])+x.abs.to_s.split('.').map{|y|y.chars.map{|z|z.to_i}}}
```
[Try it online!](https://tio.run/##vYzLCgIhGIX3PkW7UWJ@7LaJLg8iEo5MJVjJ6IDO6LNb5itEi/PBuXCGsQs562N7wp7M2B/omTHO94yTpQfRWXCviwVrtHK4gYbAQ5g5hhhA3sVgq53iVHYqpZTN6OxCgxRa41vvvgeKgHpa00uHfl9f/1NnilbrDWoLPoLtDtGCtrJGbw "Ruby – Try It Online")
] |
[Question]
[
This is a very very simple algorithm, that I am sure can be solved in many many different languages. In Spain ID cards (known as [*DNI*](https://en.wikipedia.org/wiki/Documento_Nacional_de_Identidad_(Spain))) consist of 8 numbers and a control character. The control character is calculated with the following algorithm: divide the number by 23, take the remainder of the operation and replace it with a character according to this table:
```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
T R W A G M Y F P D X B N J Z S Q V H L C K E
```
If the DNI belongs to a foreign person living in Spain, the first digit is changed to `X`, `Y` or `Z` and it is called an [*NIE*](https://en.wikipedia.org/wiki/NIE_number). In this case, the following substitutions are made before calculating the control character:
```
X Y Z
0 1 2
```
There are a lot of calculators online that help you get the control character, but, how short can you write that code? Write an algorithm (program or function) that receives a `string` with the DNI number (that will always consist of 8 alphanumeric characters) and returns just the single control character calculated and nothing more (a trailing newline is accepted).
Notes:
* The DNI is always written in uppercase, but in your algorithm you can choose the input and output to be upper- or lowercase, just be consistent.
* In real life, some NIEs issued before 2008 have 8 digits after the `X`, `Y` or `Z`, but for the purposes of this game, you can consider they have 7 digits as they have nowadays.
* You can consider that the input string will always have 8 characters, but if they are not in the "8 digits" format nor the "[XYZ] plus 7 digits" format, you must return an error (of your choice) or just throw an exception.
### Test cases:
```
00000010 -> X (HRM Juan Carlos I's DNI number)
01234567 -> L
98765432 -> M
69696969 -> T
42424242 -> Y
Z5555555 -> W (Z=2)
Y0000369 -> S (Y=1)
A1234567 -> <Error code or exception>
1231XX12 -> <Error code or exception>
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
[Answer]
# [Python 3](https://docs.python.org/3/), 83 bytes
```
lambda n:'TRWAGMYFPDXBNJZSQVHLCKE'[int([n,str(ord(n[0])%4)+n[1:]][n[0]in'XYZ'])%23]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSj0kKNzR3TfSLcAlwsnPKyo4MMzDx9nbVT06M69EIzpPp7ikSCO/KEUjL9ogVlPVRFM7L9rQKjY2GsTPzFOPiIxSB4obGcf@LygCaUnTyMwrKC3R0NTU/G9iBIEA "Python 3 – Try It Online")
-5 thanks to [AlixEinsenhardt](https://codegolf.stackexchange.com/users/70489/alix-eisenhardt) (from 99 to 94). -1 thanks to [JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
[Answer]
# [Haskell](https://www.haskell.org/), 107 93 92 bytes
```
c(x:y)="TRWAGMYFPDXBNJZSQVHLCKE"!!mod(read(("X0Y1Z2"!x):y))23
(a:b:c)!x|x==a=b|2>1=c!x
_!x=x
```
[Try it online!](https://tio.run/##TdHra4MwEADw7/krTr80ATeq9rEK6ei67ln3sqzarhRrw5TVB@o2B/3fXaJj5AKCv0u8eBf6xQc7HOo43X8eGNh@lMB3yHKGUBRnaV7CNE3KPD2czqqAZWWUJggFluWUeZS8w8kYpqGf1wGurB9C1cXLcnJte1dPl@7Fw93KeX69mU/vZ6qi8AI4Z/4eY9XtevrKUJWK8DPEMBH2rZ0VEKU6VpT6dHc0xjoNlAptlYpWdcmKsgDLgjVuy2pNUbJBbYYi4LEGrHab0LuqBh23QxrXhOuG2esPhsLnko/OhoN@zzSE25IPRu0SvpC8Z7RLuCf5qt@G8KXknriO2X7HkXwi3edccs666@qG7BuEYjEV/v@3j4BJ@0Yh9jN7C6IDzaPgm9vBiUMN40KDL8K3Bn4ZhIAz3juuAfCWUZ4hgN@YGOFfgokaThqz/1ETgupf "Haskell – Try It Online")
[Answer]
# Pyth, ~~35~~ 34 bytes
The code contains some unprintable characters, so here is a reversible `xxd` hexdump.
```
00000000: 402e 5043 22fc eeff 1ffc adc7 e614 9451 @.PC"..........Q
00000010: 2247 2573 7358 637a 5d31 3e33 4755 3320 "G%ssXcz]1>3GU3
00000020: 3233 23
```
Uses **lowercase** characters.
[Try it online.](http://pyth.herokuapp.com/?code=%40.PC%22%C3%BC%C3%AE%C3%BF%1F%C3%BC%C2%AD%C3%87%C3%A6%14%C2%94Q%22G%25ssXcz%5D1%3E3GU3+23&input=y0000369&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=%40.PC%22%C3%BC%C3%AE%C3%BF%1F%C3%BC%C2%AD%C3%87%C3%A6%14%C2%94Q%22G%25ssXcz%5D1%3E3GU3+23&test_suite=1&test_suite_input=00000010%0A01234567%0A98765432%0A69696969%0A42424242%0Az5555555%0Ay0000369%0Aa1234567%0A1231xx12&debug=0)
### Printable version
```
@.P305777935990456506899534929G%ssXcz]1>3GU3 23
```
### Explanation
* `cz]1` splits the input at position 1, e.g. `"y0000369"` to `["y", "0000369"]`.
* `>3G` gets the last 3 characters of the alphabet, `"xyz"`.
* `U3` gets the range **[0, 3[**, `[0, 1, 2]`.
* `X` maps `xyz` to `[0, 1, 2]` in the split array, e.g. `["y", "0000369"]` to `[1, "0000369"]`. This replaces the first character if it is one of `xyz`, while leaving the tail of 7 characters untouched since any 7 character string can't be equal to a single character.
* `s` joins the array with the empty string, e.g. `[1, "0000369"]` to `"10000369"`.
* `s` casts this string to integer, e.g. `"10000369"` to `10000369`. This throws an error if any extra non-digit characters are left in the string.
* `%`…`23` gets the value modulo 23, e.g. `10000369` to `15`.
* `C"`…`"` converts the binary string from base 256 to integer (about 3.06 × 1026).
* `.P`…`G` gets the permutation of the alphabet with that index.
* `@` gets the correct character from the permutation.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~62~~ 59 bytes
```
'RWAGMYFPDXBNJZSQVHLCKET'j'[\dXYZ]\d{7}'XXg'XYZ'I:47+XEU1))
```
The error for not valid input is `A(I): index out of bounds` (compiler running in Octave) or `Index exceeds matrix dimensions` (compiler running in Matlab).
[**Try it online!**](https://tio.run/##y00syfn/Xz0o3NHdN9ItwCXCyc8rKjgwzMPH2ds1RD1LPTomJSIyKjYmpdq8Vj0iIl0dyFP3tDIx145wDTXU1Pz/3wAMDA0A "MATL – Try It Online")
### Explanation
```
'RWAGMYFPDXBNJZSQVHLCKET' % Push this string (output letters circularly shifted by 1)
j % Unevaluated input
'[\dXYZ]\d{7}' % Push this string (regexp pattern)
XX % Regexp. Returns cell arary with matching string, or empty
g % Convert to standard array. Will be empty if non-valid input
'XYZ' % Push this string
I:47+ % Push [47 48 49] (ASCII codes of '012')
XE % Transliterate
U % Convert to number
1) % Get first entry. Gives an error if empty
) % Index (modular, 1-based) into initial string
% Implicitly display
```
[Answer]
# ES6, 83 82 81 bytes
```
i=>'TRWAGMYFPDXBNJZSQVHLCKE'[(/^[XYZ]/.test(i)?i.charCodeAt()%4+i.slice(1):i)%23]
```
[In action!](https://jsfiddle.net/2ndAttmt/ngwvz8w0/2/)
Uppercase only, the error code for invalid numbers is `undefined`.
One byte saved thanks to Jonathan Allan.
Another byte saved thanks to Shaggy.
[Answer]
# Java 8, ~~154~~ ~~145~~ 104 bytes
```
s->{s[0]-=s[0]<88|s[0]>90?0:40;return"TRWAGMYFPDXBNJZSQVHLCKE".charAt(new Integer(new String(s))%23);}
```
-9 bytes thanks to *@OliverGrégoire*.
-41 bytes thanks to *@OliverGrégoire* again, by taking the input as a char-array (`char[]`).
If the input is invalid, it will either fail with a `java.lang.NumberFormatException` or `java.lang.StringIndexOutOfBoundsException`.
**Explanation:**
[Try it here.](https://tio.run/##zZHZTsJAFIbvfYqTJiZtDE0X9goGEXeIilEWuRiHEYowbaYDQrAJ9/qUvEidUm5p7A1htjPbf@Y7Z0ZohlKOS@io/xngMfI8qCObLo8AbMoJ@0CYQCNcAuAhYoDl0HR74CmW2PVFF83jiNsYGkChBIGXKi@9rtZLlcLxNJ//Dm25oJ1pxbRmMcKnjErPT6@Vq3r78uGidd647TQfX67vq3c1SQ0fqKxXv@vVD5cp@YIbQTIgbDNvcmbTgewpyrFhKpYfWBGBO30fC4ItyMyx@zARgcjRfcGLlCiK5sLjZKI6U6664oiPqUxVLEvapuiapHKnGhIwhhayomzCjJHphpnOZHMJZYV8LptJm0ZCWbYQ1YSytBHVhLJOJioJZe0wkeZOSM4W0U/s9lCJT6oPGHE8lGtzTFxuOxTIXInxKdUYc1gRJDgJb26d/BdGsOitlm4cBEwx/kv2C9M9JJi3PcH4R37wBw) (Invalid test cases are surrounded by try-catch so it doesn't stop at the first error.)
```
s->{ // Method with char[] parameter and char return-type
s[0]-=s[0]<88|s[0]>90? // If the first character is not XYZ:
0 // Leave the first character as is
: // Else:
40; // Subtract 40 to convert it to 012
return"TRWAGMYFPDXBNJZSQVHLCKE".charAt(
// Get the char from the String
new Integer( // by converting the following String to an integer:
new String(s) // by converting the char-array to a String
)%23); // And take modulo-23 of that integer
} // End of method
```
[Answer]
# [PHP](https://php.net/), 88 bytes
prints 1 for an error
```
$a[0]=strtr(($a=$argn)[0],ZYX,210);echo!ctype_digit($a)?:TRWAGMYFPDXBNJZSQVHLCKE[$a%23];
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6sUZQoBStb/VRKjDWJti0uKSoo0NFQSbcEqNIFiOlGRETpGhgaa1qnJGfmKySWVBanxKZnpmSVAZZr2ViFB4Y7uvpFuAS4RTn5eUcGBYR4@zt6u0SqJqkbGsdb//wMA "PHP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 42 bytes
```
“X0Y1Z2”⁸y@1¦RṪ€V%23ị“Ñ×ⱮEɼiʋ}'uƒẹsø’ṃØA$¤
```
[Try it online!](https://tio.run/##AV0Aov9qZWxsef//4oCcWDBZMVoy4oCd4oG4eUAxwqZS4bmq4oKsViUyM@G7i@KAnMORw5fisa5Fybxpyot9J3XGkuG6uXPDuOKAmeG5g8OYQSTCpP///yI5ODc2NTQzMiI "Jelly – Try It Online")
Too long, Jelly! Dennis is disappointed of you![citation-needed]
[Answer]
# q/kdb+, 68 bytes
**Solution:**
```
{"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}
```
**Examples:**
```
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"00000010"
"X"
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"01234567"
"L"
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"98765432"
"M"
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"69696969"
"T"
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"42424242"
"Y"
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"Z5555555"
"W"
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"Y0000369"
"S"
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"A1234567"
" "
q){"TRWAGMYFPDXBNJZSQVHLCKE"mod["J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x;23]}"1231XX12"
" "
```
**Explanation:**
If the first character, `x 0`, is in the string `"XYZ"` then `a` will be `0`, `1` or `2`. If the first character is not in the string, then `a` will be `3`. If `a` is less than 3, we switch out the first character for the string of a (`0`, `1` or `2`), otherwise we switch out for the first character (thus effectively doing nothing).
This string is cast to a long (`"J"$`), which is then `mod`'d with 23 to give the remainder.
This remainder is used to index into the lookup table.
```
{ "TRWAGMYFPDXBNJZSQVHLCKE" mod["J"$$[3>a:"XYZ"?x 0;string a;x 0],1_x;23] } / ungolfed solution
{ } / lambda function
mod[ ;23] / performds mod 23 of the stuff in the gap
1_x / 1 drop input, drops the first character
, / concatenation
$[ ; ; ] / if COND then TRUE else FALSE - $[COND;TRUE;FALSE]
a:"XYZ"?x 0 / "XYZ" find x[0], save result in a
3> / is this result smaller than 3
string a / if so, then string a, e.g. 0 -> "0"
x 0 / if not, just return first character x[0]
"J"$ / cast to long
"TRWAGMYFPDXBNJZSQVHLCKE" / the lookup table
```
**Notes:**
`" "` is returned in the error scenarios, this is because the cast returns a null, and indexing into a string at index null is an empty char. I could add 4 bytes at the beginning (`"!"^`) to make it more obvious that an error had occurred:
```
q){"!"^"TRWAGMYFPDXBNJZSQVHLCKE"("J"$$[3>a:"XYZ"?x 0;($)a;x 0],1_x)mod 23}"1231XX12"
"!"
```
[Answer]
# JavaScript(ES6), 121 byte
```
f=i=>{c=+i[0];a=3;while(a--){i[0]=="XYZ"[a]&&(c=a)}b=7;while(b--){c= +i[7-b]+c*10}return "TRWAGMYFPDXBNJZSQVHLCKE"[c%23]}
console.log([f("00000010"),f("01234567"),f("98765432"),f("69696969"),f("42424242"),f("Z5555555"),f("Y0000369"),f("A1234567"),f("1231XX12")])
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 50 bytes
Similar to most of the other approaches.
Input and output is lowercase, outputs `undefined` for invalid input.
```
`tr°gmyfpdxbnjzsqvhlcke`g("xyz"øUg)?Uc %4+UÅ:U %23
```
[Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=YHRysGdteWZwZHhibmp6c3F2aGxja2VgZygieHl6IvhVZyk/VWMgJTQrVcU6VSAlMjM=&input=ImExMjM0NTY3Ig==)
[Test all valid test cases](http://ethproductions.github.io/japt/?v=1.4.5&code=o2B0crBnbXlmcGR4Ym5qenNxdmhsY2tlYGcoInh5eiL4WGcpP1hjICU0K1jFOlggJTIz&input=WyIwMDAwMDAxMCIsIjAxMjM0NTY3IiwiOTg3NjU0MzIiLCI2OTY5Njk2OSIsIjQyNDI0MjQyIiwiejU1NTU1NTUiLCJ5MDAwMDM2OSJd)
[Answer]
# Rust, 206 bytes
I don't think rust is well suited for code golfing -\_-
```
let b=|s:&str|{s.chars().enumerate().map(|(i,c)|match i{0=>match c{'X'=>'0','Y'=>'1','Z'=>'2',_=>c},_=>c}).collect::<String>().parse::<usize>().ok().and_then(|x|"TRWAGMYFPDXBNJZSQVHLCKE".chars().nth(x%23))};
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~41~~ ~~40~~ 39 bytes
```
ć…xyz2ÝJ‡ìDd_i.ǝ}23%.•Xk¦fΣT(:ˆ.Îðv5•sè
```
Takes the input in lowercase (to save 1 byte *yay*)
[Try it online!](https://tio.run/##MzBNTDJM/f//SPujhmUVlVVGh@d6PWpYeHiNS0p8pt7xubVGxqp6jxoWRWQfWpZ2bnGIhtXpNr3DfYc3lJkCRYsPr/j/v9IACIzNLAE "05AB1E – Try It Online")
Prints the input to STDERR if it is malformed
### Explanation
```
ć…xyz2ÝJ‡ìDd_i.ǝ}23%.•Xk¦fΣT(:ˆ.Îðv5•sè
ć # Get head of input and put the rest of the input under it on the stack
…xyz # Push xyz
2ÝJ # Push 012
‡ # Transliterate
ì # Prepend to the rest of the input
Dd_ # Does the result contain something other than numbers?
i.ǝ} # If so print input to STDERR
23% # Modulo 23
.•Xk¦fΣT(:ˆ.Îðv5• # Pushes the character list
sè # Get the char at the index of the modulo
```
[Answer]
## Dyalog APL, 95 bytes
`{'TRWAGMYFPDXBNJZSQVHLCKE'[1+23|(10⊥¯1+'0123456789'⍳{(⍕{('XYZ'⍳⍵)<4:('XYZ'⍳⍵)-1⋄⍵} ⊃⍵),1↓⍵}⍵)]}`
This is a monadic operator that accepts a character string as its operand and returns its result.
**FIXME** it doesn't check its input. It's not properly golfed.
Usage:
```
OP ← {'TRWAGMYFPDXBNJZSQVHLCKE'[1+23|(10⊥¯1+'0123456789'⍳{(⍕{('XYZ'⍳⍵)<4:('XYZ'⍳⍵)-1⋄⍵} ⊃⍵),1↓⍵}⍵)]}
OP '01234567'
L
OP '00000010'
X
```
] |
[Question]
[
# Code Golf
*Totally real* backstory: I'm a contractor working on a website www.**Sky.Net** and one of our tasks it to create some self-aware program or something, I don't know I wasn't really listening to the boss. Anyways in an effort to make our code more self-aware we need *IT* to be able to know what code is on each line-number.
---
# Challenge
Create a program or function that takes an input `n` and returns the code of said program or function on line `n`.
---
# Rules
➊ Your program or function must be at least 4 lines long. Each line must be unique.
➋ You may assume the input will always be a positive integer greater than or equal to 1 and less than or equal to the number of lines in your program/function.
➌ The first line in your program/function is line 1, not line 0.
➍ You can not access the file that your program is on. (If someone has to ask "Isn't this technically breaking rule #4"; it probably is)
➎ Lines can-not be empty *(this includes a space if spaces don't do anything in your language)*
➏ Lines can-not be //comments (/\* of any <!--style)
---
This is a [quine](/questions/tagged/quine "show questions tagged 'quine'")-like challenge
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the fewest bytes wins!
[Answer]
# Vim, 7 bytes
```
1
2
3
4
```
[Try it online!](https://tio.run/nexus/v#@2/IZcRlzGXy/78xAA "V – TIO Nexus")
As far as I can tell, this complies with all of the rules. In vim by default, the empty program prints out all of the input. Since
```
<N><CR>
```
Is a noop, nothing changes the input text, and since each input matches the desired output, this same approach works with any number of lines.
[Answer]
# Ruby, ~~71~~ ~~70~~ 66 bytes
[Try it online!](https://repl.it/FylY/4)
```
->n{
k=["}", "k[-n]%%k.inspect", "k=%s", "->n{"]
k[-n]%k.inspect
}
```
**"Cheating" Mode: 7+1 = 8 bytes**
Requires the `-p` flag for +1 byte. Literally a copy of [the V answer](https://codegolf.stackexchange.com/a/111446/52194). Prints the number that is inputted; the entire program is effectively just no-ops.
```
1
2
3
4
```
[Answer]
## Haskell, ~~69~~ 59 bytes
```
(lines(s++show
s)
!!)
s="\n(lines(s++show\n s)\n !!)\ns="
```
Based on the standard Haskell quine. The first expression (spread over the first three lines) is an unnamed function that picks the nth line from the quinified string `s` (`s++show s`). +2 bytes for making indexing 1-based (imho an unnecessary rule).
For a [Try it online!](https://tio.run/nexus/haskell#@59mq5GTmZdarFGsrV2ckV/OpVCsyaWgqKjJVWyrFJOHLh2TB5QHEkAFMXlAFf9zEzPzFGwVchMLfBU0CkpLgkuKfPL00jQVog319ExiFf4DAA "Haskell – TIO Nexus") version I have to name the function which adds 4 bytes.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~184~~ 172 bytes
```
$v=0,
'$v=0,',
"'`$v=0',",(($q='"{0}`$v=0{0},",(($q={0}{1}{0})-f([char]39),$q)')-f([char]39),$q),
(($z='(($z={0}{1}{0})-f([char]39),$z;$v[$args]')-f([char]39),$z);$v[$args]
```
[Try it online!](https://tio.run/nexus/powershell#M9TTM1GoUVBVqObiDC/KLEnV9cgvLlFQ8snMS1VQqY6vtVJS0PXL90stzwGKoKhR0VBQU6j@r1Jma6DDpQ6m1HW4lNQTQEx1HSUdDQ2VQlt1pWqDWrAQkIYJApnVhrVAUlM3TSM6OSOxKNbYUlNHpVBTHUNEhwuopcpWHUzi0lhlrVIWrZJYlF4ci25ClSZC7j9nrYJKvIImV@1/AA "PowerShell – TIO Nexus")
## Explanation
Starts by creating an array `$v` on the first line. On that same line, the first (`0`th) element is set to `0`, and a comma `,` continues its definition.
The next line sets the next element (`1`) of the array to a string representing the content of the first line of the script, so that `$v[1]` returns the first line.
The 3rd line first sets the 3rd element of the array (index `2`) to a string representing the 2nd line of the script, then on the same line sets the 4th element (index `3`) using a quine snippet that uses the format operator (`-f`) to replace certain instances of single quotes (`[char]39`) and the format template string, into itself, to reproduce the entirety of the 3rd line.
Line 4 basically does the same thing, but also ends the creation of the array and then indexes into it using the supplied argument.
[Answer]
# Python 2, 104 73 67 bytes
Thanks to Jonathan Allan for saving 6 bytes!
```
s=\
['print s[input()]or s', 's=\\', 0, 'exec s[', '0]']
exec s[
0]
```
**Edit:** Same byte count, but I like this solution better
[Try it online!](https://tio.run/nexus/python2#@19sG8MVrV5QlJlXolAcnZlXUFqioRmbX6RQrK6joA6UjQHSBkBmakVqMlAFSNQgVj2WC8rnMoj9/98IAA)
Python version of Value Ink's [Ruby answer](https://codegolf.stackexchange.com/questions/111439/input-number-output-line-number/111444#111444).
Older answer (67 bytes):
```
1
s=\
['print s[-input()]or s', 0, 's=\\', 1]
print s[-input()]or s
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), ~~19~~ ~~18~~ 17 bytes
```
1
{'_'~]ri(=}
_
~
```
[Try it online!](https://tio.run/nexus/cjam#@2/IVa0er14XW5SpYVvLFc9V9/@/EQA "CJam – TIO Nexus")
Based on the standard CJam-quine. The `{...}_~` runs the `...` with the block itself on the stack (and in this case, also `1` below that). Then we do:
```
'_'~ e# Push the third and fourth line.
] e# Wrap all four lines in a list.
ri e# Read input and convert to integer.
(= e# Use as index into the lines.
```
[Answer]
# PHP, 261 bytes
```
<?php function f($l){
$a="aWYoJGw9PTEpJG09Ijw/cGhwIGZ1bmN0aW9uIGYoXCRsKXsiO2lmKCRsPT0yKSRtPSJcJGE9XCIkYVwiOyI7aWYoJGw9PTMpJG09IlwkYj1cIiR";
$b="iXCI7IjtpZigkbD09NCkkbT0iZXZhbChiYXNlNjRfZGVjb2RlKFwkYS5cJGIpKTt9Pz4iO2VjaG8gJG07";
eval(base64_decode($a.$b));}?>
```
[Try it online !!](https://tio.run/#IJOXD)
The encoded string is:
```
if($l==1)$m="<?php function f(\$l){";
if($l==2)$m="\$a=\"$a\";
if($l==3)$m="\$b=\"$b\";
if($l==4)$m="eval(base64_decode(\$a.\$b));}?>";
echo $m;
```
[Answer]
# Perl, 52 bytes
```
$_=q{print+(split/
/,"\$_=q{$_};
eval")[<>-1]};
eval
```
This is a simple variation on the classic quine
```
$_=q{print"\$_=q{$_};eval"};eval
```
The "payload" is `split` on newlines and the correct line is selected by indexing into the resulting list.
# Perl, ~~49~~ 48 bytes (non-competing)
```
#!/usr/bin/perl -d:A
sub DB'DB{
print${"_<$0"}[<>]}
1
```
38 bytes for the code (excluding the shebang but including `-d:A`) plus 10 bytes for the filename, which must be `Devel/A.pm`. The `Devel` directory must be in `@INC`.
Technically, this violates Rule #4 because `-d:A` causes the file to be parsed twice, so it's a non-competing solution.
It uses a [debugger hook](http://perldoc.perl.org/perldebguts.html#Debugger-Internals) to access the lines of the file, which perl stores in the `@{"_<$filename"}` array at compile time.
] |
[Question]
[
What general tips do you have for golfing in [dc](https://en.wikipedia.org/wiki/Dc_(computer_program))?
dc is a calculator utility for UNIX/Linux that predates the C language. I am interested in how to make my dc programs (calculations?) shorter. I'm looking for ideas that can be applied to general [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") that are at least a little bit specific to dc (eg. removing comments is not a helpful answer)
Please post one tip per answer.
[Answer]
# Arrays
Although they're a headache for beginners, `dc` offers arrays. They work like this:
```
value index :a # store `value' in array linked to top of stack `a', with index `index'
index ;a # push a[index] on (main) stack
```
As usual, the first element has the index 0. Arrays can be useful when working with sequences, like in the [SUDSI sequence](https://codegolf.stackexchange.com/questions/48155/generate-the-sudsi-sequence/81164#81164 "Generate the SUDSI sequence"), especially in combination with counters. Arrays can reduce the amount of number-shuffling you need to do (and the number of counters and comparisons) if you want to select a particular element without destroying your environment. For example, if you want to move a stackful of numbers into an array, you could write a recursive function that uses `z` (stack depth) or `z 1-` as the index, stores the element, and checks whether `z == 0` to terminate itself.
```
[z 1- :a z 0 !=F]dsFx # or I could just write such a function for you :)
```
Be aware of the following:
* Arrays are associated with instances on named stacks. If you push a new value on a stack that has an array associated with it, that array will also be "pushed back", and a "new" array will take its place. The old array won't be usable until the corresponding value on the named stack is also usable (i.e., on top of its stack). This is a complicated concept that would be better explained with a good animation, which is beyond me.
* You **can** store stuff in a named array without actually pushing a value into the corresponding named register. However, if you do this, you **cannot** access the stack/register with that name for the rest of the session. `dc` will crash.
* If you pop a value off a named stack, any values in the corresponding array will be lost—no warnings, no safeguards, nothing. Just gone (which can also be useful).
[Answer]
# If-then-else statements
Suppose we want to check the condition `a==b` (let `a` and `b` be stored in their respectively-named registers).
edit:
```
[ # Everything is wrapped in one big macro
[ # An inner macro for our *then* part
# <-- Stuff to execute if a==b here
2Q # Then quit the inner and outer macro
]sE # `E' is for Execution register ;)
la lb =E # if a==b, execute E
# if E is executed, it will quit the whole macro, so the rest is never reached:
# <-- Stuff to execute if a!=b here
]x # End macro; Execute
```
Let `(foo)` be a placeholder, for the purpose of condensing:
```
[[(then)2Q]sE(condition)E(else)]x
```
Pretty sure this is the most compact if statement possible (also featured [here](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/57145#57145)).
[Answer]
# You can save input with `d`
By using `d`, which duplicates the ToS (top of stack) you can move the input out of the way for later use, while still being able to use it.
[Answer]
# 0 to the nth power instead of conditionals/macros
Sometimes you might need something like [c](/questions/tagged/c "show questions tagged 'c'") ternary conditional:
```
A == B ? C : D;
```
A nice way to handle this is described in [@Joe's answer](https://codegolf.stackexchange.com/a/84327/11259). However we can do better:
```
0AB-^E*C+
```
where E is D - C.
This tests for equality by raising 0 to the power of the difference of the two values. This results in 1 if equal and 0 otherwise. The rest just scales the 1 or 0 to the values C or D. This works because `dc` gives 00 = 1 and 0n = 0 for n != 1.
[Answer]
Sometimes it is necessary to discard a number from the stack. One way to do this is to simply pop it into an unused variable, i.e. `st`. However in some situations, you can pop it to a couple of other places, e.g. the input base when you have no more numerical input or to the precision specifier if you don't have any more operations to do where precision would make a difference. In the former case, use `i`. In the latter case, use `k`.
[Answer]
# Length Calculation: `Z`, `X`, and `z`
`Z` pops the ToS and pushes the number of digits (decimal) if it's a number or the number of characters if it's a string. This can be useful for detecting the length of a result (for buffering output) or computing string length. Note that for numbers, `Z` pushes the combined length of the integer part and the fraction part.
`X` pops the ToS and pushes the number of digits in the fraction part of the number. If the ToS was a string, `0` is pushed.
To find the number of digits in the integer part of the number, one might use `dZrX-`. If you haven't changed the precision from the default `k==0`, using `1/Z` is shorter, but suppose you need to maintain a particular non-zero precision after the operation: `Kr0k1/Zrk` is rather an eyesore.
`z` pushes the number of items on the stack. One of my favourite commands, it does not actually pop any values! It could be used to generate a sequence of numbers or increment a counter. Using `zd` repeatedly (say, at the start of a macro) could let one [test a calculation](https://codegolf.stackexchange.com/a/90618/54071) on each natural or whole number in ascending order.
[Answer]
Digits `A` to `F` may be used in substitution for the numbers 10 to 15. However they must still be treated effectively as base 10 digits (assuming input base is 10) when in different places. In other words, with input base 10 `FF` would not represent 255, it would represent `(15 * 10) + 15` or 165.
In fact this works for all digits `0` to `F` in any input base `2` to `16`. So if the input base is 5, then `26E` would be `(2 * 5^2) + (6 * 5) + 14`, or 94.
Note this behaviour is in effect for the unmodified GNU sources. However, as @SophiaLechner points out, RedHat-based distros appear to use [bc-1.06-dc\_ibase.patch](https://src.fedoraproject.org/rpms/bc/blob/f8/f/bc-1.06-dc_ibase.patch) which changes this behaviour so digits >= ibase are treated as `ibase - 1`, regardless of their actual value. Note the TIO `dc` [appears not to have bc-1.06-dc\_ibase.patch](https://tio.run/##S0oszvj/PzmxREE/tSRZPy01Jb8oUbcoNSc1sTiVKyVZQTdV3c2tQP3/fwA) (even though its Fedora 28 ¯\_(ツ)\_/¯ ).
[Answer]
# If an operator is restricted from source, make a new one with `a`
Something that has come in handy for me a couple of times now is to avoid using a specific operator by pushing the ASCII value of the operator, using `a` to convert it to a string, and `s`toring this in a register to be executed as a macro later on. For example, I need to do division, but am either disallowed from or trying to avoid using the character `/`. I can, instead do `47asd` and then in the future when I need to divide 16 by 4, `16 4 ldx`.
* This will only work for single-character operators (can't build up a string), and will not work for commands like `s` that need to be postfixed by something.
* This adds quite a few bytes, and is therefore only suitable when avoiding the specific character is necessary or somehow affords a score bonus.
[Answer]
When initialising a ~~function~~ macro (we'll use `F`) that you want to run immediately, use something like `dsFx` rather than `sFlFx`. The same works for variables: `dsa` rather than `sala`.
If you need to do other stuff in between the storing and the loading (e.g., `sa[other stuff]la`), still consider whether the above is viable: If you leave a value on the stack before the other operations, will it be back at the top by the end of those operations?
[Answer]
Just discovered this by accident. Yet another way to generate a zero: `_`.
`_` is a signal to dc that the following digits are a negative number. Example:
```
_3 # pushes -3
```
But what if we don't follow it with a number?
```
_ # pushes 0...sometimes
```
This works when the next non-blank character following the underscore is not a digit. If a digit follows it, even after a newline, it is interpreted as a negative sign.
```
c4 5_6 # -6,5,4
c4 5_ 6 # -6,5,4
c4 5_
6 # -6,5,4 # still a negative sign since the next thing it sees is a digit
c4 5_z # 3,0,5,4 # if it's followed by a non-digit, it's a 0
c4 5_p6 # 6,0,5,4
c4 _* # 0 # 4*0=0
```
[Answer]
If the contents of the entire stack needs printing at the end of a program, a recursive macro loop could be used to achieve this. However, it is much shorter to simply use the `f` command.
[Answer]
`dc` reads input a line at a time. If you need to read in multiple items, doing it one-per line either requires a `?` for every line to be read, or a cumbersome macro loop. Instead, if all input items can be put on one space-separated line, then a single `?` will read all the input items, pushing each one onto the stack.
For example in `seq 10 | dc -e'?f'`, `seq` outputs integers 1-10, one per line. the `?` will just read the first `1` which will be output when `f` dumps the whole stack. However in `seq 10 | tr '\n' ' ' | dc -e'?f'`, the `tr` makes the input integers all space separated. In this case the `?` will read all the integers from the line in one go, and `f` will output them all.
[Answer]
# Avoiding whitespace
Avoiding whitespace comes up in quite a few challenges, and is generally easy in `dc`. Aside from strings, the one very specific time that whitespace becomes necessary is when pushing multiple numbers in a row: `1 2 3`. If this must be avoided:
* Execute an empty macro in between: `1[]x2[]x3[]x`.
* If brackets are off the table, store a NOP of a macro ahead of time: `35asn` and execute *it* in between: `1lnx2lnx3lnx`.
] |
[Question]
[
What general tips do you have for golfing in [Racket](http://racket-lang.org) / [Scheme](http://scheme.com)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Racket / Scheme (e.g. "remove comments" is not an answer).
---
I'm aware [Scheme](http://scheme.com) and [Racket](http://racket-lang.org) (formerly PLT Scheme) are technically different languages but are quite similar in many ways and much code (I suspect) will run mostly as intended in either. If your tip only applies to one of the aforementioned languages, note as such.
[Answer]
In **Racket**, `λ` and `lambda` are synonymous keywords for constructing anonymous functions, but `λ` is 2 bytes where `lambda` is 6.
In **Scheme**, there's no such keyword `λ` and you're stuck with `lambda`.
[Answer]
Use `~a` to convert numbers and symbols to strings.
[Answer]
# Use shorter synonyms
There's a number of procedures in Racket that have mostly-equivalent shorter versions. (They are usually not equivalent: for example, `(car (cons 1 2))` works where `(first (cons 1 2))` fails. But you can make the substitution if you know they are synonyms in your case.)
This list is probably incomplete: I probably don't know about most of the things that could go in this list yet.
* `(= a b)` instead of `(equal? a b)` when comparing numbers.
* `'(1 2)` instead of `(list 1 2)`.
* `car`, `cadr`, `cdr` for `first`, `second`, and `rest`.
* `null?` instead of `empty?`
* `modulo` instead of `remainder` when the modulus is positive.
* `floor` instead of `truncate` when its argument is positive.
[Answer]
When using **Racket**, bind variables using `λ` to shave off a few bytes. In **Scheme**, `lambda` makes this trick not applicable, unless one is binding four or more variables.
Example: One variable saves 2 bytes over `let`/`define`
```
(define n 55)(* n n) ; 20 bytes
(let([n 55])(* n n)) ; 20 bytes
((λ(n)(* n n))55) ; 18 bytes
```
[Answer]
In **Racket**, `require` forms can have multiple arguments.
```
(require net/url net/uri-codec)
```
Is way shorter than
```
(require net/url)(require net/uri-codec)
```
I don't know much about **Scheme**, but it doesn't seem to have a `require` builtin.
[Answer]
# Omit needless spaces
This can be considered a "trivial" tip, but it has to be pointed out somewhere.
Any time you read Racket code written by *normal* people (e.g. in [the Racket documentation](https://docs.racket-lang.org/reference/index.html)) it will have all the spaces put in: for example,
```
(append (list 1 2) (list 3 4) (list 5 6) (list 7 8))
```
In fact, since `(` and `)` can't be part of variable names, we can delete all the spaces around them and not lose any ambiguity (and, more importantly, still get valid code). So the above expression can instead be:
```
(append(list 1 2)(list 3 4)(list 5 6)(list 7 8))
```
[Answer]
The following tips are for **Racket**:
### Default arguments
Especially useful for creating aliases for long function names that are used often.
Assume the golf allows you to write a function that consumes the argument, and assume you need to use `reverse` a lot.
You'll start with something like:
```
(λ(x) ... reverse ... reverse ... reverse ...
```
You can instead take in an additional argument, with a shorter name than `reverse`, and set its default value to `reverse`:
```
(λ(x[r reverse]) ... r ... r ... r ...
```
Furthermore, it's useful if you have a helper function that you use in many places with some of the same arguments. Remember to reorder the arguments to the function as needed, so you can use as many default arguments as possible, and remove the arguments from multiple callsites.
### `match`
This one is a little harder to summarize in a small post, so read up on the [Racket Docs](https://docs.racket-lang.org/reference/match.html) for this one.
In a nutshell, `match` allows you extract elements and sequences of elements in a certain order from a list, and the quasiquote syntax lets you stitch the mutilated list back together:
```
(match (range 10)
[`(,xs ... 3 ,ys ... 6 ,zs ...)
`(,@(map f xs) 3 ,@(map f ys) 6 ,@(map f sz))]
...
```
It also gives you an easy way to work with regular expressions and do additional computation on the resulting groups afterwards,
### Named `let`
See the named `let *proc-id* ...` syntax [here](https://docs.racket-lang.org/reference/let.html).
This allows you to write recursive functions that are called immediately without `define` or actually calling the function after you've defined it.
Something like:
```
(define (fib i)
(if (< i 2) i
(+ (fib (- i 1)) (fib (- i 2)))))
(fib 10)
```
can be shortened to:
```
(let fib {[i 10]}
(if (< i 2) i
(+ (fib (- i 1)) (fib (- i 2)))))
```
This last one is silly, but I haven't been able to use this little trick anywhere so far:
`(apply map list matrix)` takes a transpose of `matrix`, where `matrix` is some rectangular list of lists, like `'((1 2 3) (a b c))`.
Let me know if this does prove to be useful.
[Answer]
The expressions `'x`, ``x`, `,x`, an `,@x` automatically expand to `(quote x)`, `(quasiquote x)`, `(unquote x)`, and `(unquote-splicing x)`, respectively. This is purely a syntactic transformation, and can be applied anywhere. This gives a convenient notation for one-variable functions:
```
; Defining a function:
(define ,x (+ x x))
; Calling a function:
(display ,2)
```
which expands to
```
; Defining a function:
(define (unquote x) (+ x x))
; Calling a function:
(display (unquote 2))
```
I'm not sure what the semantics for shadowing a syntactic keyword such as `quote` or `quasiquote` with a bound variable, although code like the above worked in the interpreters I tested it on, and `unquote-splicing` is less than ideal since it has a two-character abbreviation, but `unquote` is an auxillary syntax with a one-character abbreviation and so is ideal for this hack.
[Answer]
As [Winny pointed out](https://codegolf.stackexchange.com/a/119537/38603), `#!` can usually be used instead of `#lang`, saving four bytes.
```
#lang racket ;12 bytes
#!racket ;8 bytes
```
] |
[Question]
[
In this challenge you will need to determine whether it's Pi Day, Pi Minute, or Pi Second.
Because Pi is irrational, it wants your code to be as short as possible.
# Examples
**No input is provided**, your program should use the system time. I've just added it for clarity
```
March 14, 2016 0:00:00
Pi Day
December 25, 2015 3:14:45
Pi Minute
December 29, 2015 0:03:14
Pi Second
January 1, 2016 0:00:00
<No Output>
```
## What is Pi Day / Minute / Second
* `Pi Day` is when the month is March, and the date is the 14th
* `Pi Minute` is when the hour is 3, and the minute is 14
* `Pi Second` is when the minute is 3, and the second is 14
* `Pi Day` should be preferred instead of `Pi Minute` or `Pi Second`, and `Pi Minute` should be preferred instead of `Pi Second`.
* For this challenge you should use 12-hour time (15:14 == 3:14). The date/time used to determine the `Pi Day/Minute/Second` should be based on **system time**.
## Scoring & Bonus
**-15 byte Bonus:** If you print `"No Pi Time"` when it's not Pi time.
---
As always, [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") shortest code in bytes wins!
[Answer]
# Javascript (ES6), 114 112 - 15 = 97 bytes
```
x=>['Pi Day','Pi Minute','Pi Second'].find((x,i)=>[/ar 14/,/(03|15):14:/,/03:14/][i].test(Date()))||'No Pi Time'
```
**Ungolfed:**
```
x=>
['Pi Day', 'Pi Minute', 'Pi Second'] // array of outputs
.find( // find first element in the array
(x, i)=> // which returns truthy for this function
[/ar 14/, /(03|15):14:/, /03:14/] // array of regex patterns
[i] // get corresponding regex based on index
.test(Date()) // test it against current date, date is automatically cast to string
) || 'No Pi Time' // if no result, then return "No Pi Time"
```
Thanks for -2 bytes [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)
[Answer]
## Ruby, ~~125~~ 124 chars
```
i=[*[(t=Time.new).month,t.day,t.hour,t.min,t.sec].each_cons(2)].index [3,14];i&&$><<['Pi Day','','Pi Minute','Pi Second'][i]
```
Alas, the cleverer `%i[month day hour min sec].map{|x|Time.new.send x}` is longer.
The key here is the use of `each_cons` to avoid repetition (see the last few lines of the explanation below).
```
i= # send i (index) to...
[* # convert to array (splat)...
[
(t=Time.new).month, # the current month...
t.day,t.hour,t.min,t.sec # etc... (duh)
]
.each_cons(2) # each consecutive two elements
] # [[month, day], [day, hour], [hour, min], etc]
.index [3,14]; # first occurrence of [3, 14]
i&& # shorthand for "if i"...
$><< # output...
[
'Pi Day', # [month=3, day=14] is Pi Day
'', # [day=3, hour=14] isn't anything
'Pi Minute', # [hour=3, min=14] is Pi Minute
'Pi Second' # [min=3, sec=14] is Pi Second
][i] # index by index (obviously)
```
[Answer]
## CJam, 41 bytes
```
et[3E]#"
Pi Day
Pi Minute
Pi Second
"N/=
```
[Test it here.](http://cjam.aditsu.net/#code=et%5B3E%5D%23%22%0APi%20Day%0A%0APi%20Minute%0APi%20Second%0A%22N%2F%3D) Alternatively [use this link](http://cjam.aditsu.net/#code=%5B2016%203%2014%2017%2045%2013%20458%201%20-3600000%5D%0A%5B3E%5D%23%22%0APi%20Day%0A%0APi%20Minute%0APi%20Second%0A%22N%2F%3D) to stub the result of `et` for easier testing.
### Explanation
```
et e# Get the current datetime as an array with the following elements:
e# - Year
e# - Month
e# - Day
e# - Hour
e# - Minute
e# - Second
e# - Millisecond
e# - Weekday
e# - Tickrate or something.
[3E] e# Push the array [3 14].
# e# Find the position of this subarray in the current datetime array. Let's see
e# what results we can get:
e# - Year 3 is in the past and there is no 14th month, so we can't get 0.
e# - Pi day will give result 1.
e# - Day 3, hour 14 would give 2.
e# - Pi minute will give result 3.
e# - Pi second will give result 4.
e# - Second 3, millisecond 14 would give 5.
e# - Weekday and tickrate won't be 14, so we'll never get 6 or 7.
e# - If [3 14] isn't found at all we get -1.
"\Pi Day\\Pi Minute\Pi Second\"
e# Push this string (with linefeeds instead of backslashes.
N/ e# Split into lines.
= e# Select the corresponding element. The non-existent "pi hour" and "pi millisecond"
e# would map to empty strings as well as the -1.
```
[Answer]
## Python 2, ~~219~~ ~~186~~ 183 Bytes (198-15)
I tried
Ungolfed:
```
from datetime import datetime
now = datetime.now()
output = ['Pi Day', 'Pi Minute', 'Pi Second', 'No Pi Time']
if now.month == 3 and now.day == 14:
print output[0]
elif now.hour == 2 and now.minute == 13:
print output[1]
elif now.minute = 2 and now.second == 13:
print output[2]
else:
print output[3]
```
Golfed:
```
from datetime import *
n=datetime.now()
a=n.minute
if n.month==3and n.day==14:print'Pi Day'
elif n.hour==2and a==13:print'Pi Minute'
elif a==2and n.second==13:print'Pi Second'
else:print'No Pi Time'
```
[Answer]
## Japt, 78 - 15 = 63 bytes
```
D=Ð)g ¥3©Df ¥E?"Pi Day":Dd %C¥3©Dc ¥E?`Pi M©e`:Dc ¥3©Db ¥E?`Pi SeÖ:No Pi Te
```
Pretty straightforward - just checks the date for every case.
Explanation:
* `D=Ð)g` get the current date (`Ð`), store it in the variable `D` and get the month (`g`). Why store it in the variable, if it's already one-letter? Because since then you can dress any part of date with `Da`, where `a` is the function, returning year, month, date, etc. But otherwise you'd have to do `Ð a`, see the space.
* `¥3` is `==3`, checking if the month is March.
* `©` is `&&`, i.e. "and".
* `Df` is the day of the month.
* `E` is 14
* `?...:...` - typical sets of ternary operators
* `Dd %C` the reminder of dividing the hour (`Dd`) by 12 (`C`)
* `Dc` is the minutes
* `Db` are seconds
[Try it online!](http://ethproductions.github.io/japt?v=master&code=RD3QKWcgpTOpRGYgpUU/IlBpIERheSI6RGQgJUOlM6lEYyClRT9gUGkgTYipZWA6RGMgpTOpRGIgpUU/YFBpIFNl1gg6Tm8gUGkgVItl&input=ImFiYyIgMTMgWzkgInp5eCJd)
---
[To emulate Pi Day:](http://ethproductions.github.io/japt?v=master&code=RD3QIjMvMTQvMTEgMTE6MTE6MTEiOwpEZyClMqlEZiClRT8iUGkgRGF5IjpEZCAlQ6UzqURjIKVFP2BQaSBNiKllYDpEYyClM6lEYiClRT9gUGkgU2XWCDpObyBQaSBUi2U=&input=ImFiYyIgMTMgWzkgInp5eCJd)
```
D=Ð"3/14/11 11:11:11";
Dg ¥2©Df ¥E?"Pi Day":Dd %C¥3©Dc ¥E?`Pi M©e`:Dc ¥3©Db ¥E?`Pi SeÖ:No Pi Te
```
[To emulate Pi Minute](http://ethproductions.github.io/japt?v=master&code=RD3QIjExLzExLzExIDM6MTQ6MTEiOwpEZyClMqlEZiClRT8iUGkgRGF5IjpEZCAlQ6UzqURjIKVFP2BQaSBNiKllYDpEYyClM6lEYiClRT9gUGkgU2XWCDpObyBQaSBUi2U=&input=ImFiYyIgMTMgWzkgInp5eCJd):
```
D=Ð"11/11/11 3:14:11";
Dg ¥2©Df ¥E?"Pi Day":Dd %C¥3©Dc ¥E?`Pi M©e`:Dc ¥3©Db ¥E?`Pi SeÖ:No Pi Te
```
[To emulate Pi Second](http://ethproductions.github.io/japt?v=master&code=RD3QIjExLzExLzExIDAwOjM6MTQiOwpEZyClMqlEZiClRT8iUGkgRGF5IjpEZCAlQ6UzqURjIKVFP2BQaSBNiKllYDpEYyClM6lEYiClRT9gUGkgU2XWCDpObyBQaSBUi2U=&input=ImFiYyIgMTMgWzkgInp5eCJd):
```
D=Ð"11/11/11 00:3:14";
Dg ¥2©Df ¥E?"Pi Day":Dd %C¥3©Dc ¥E?`Pi M©e`:Dc ¥3©Db ¥E?`Pi SeÖ:No Pi Te
```
[Answer]
# TI-BASIC, 124 bytes
Thanks to FlagAsSpam for shaving a few bytes.
```
"→Str1
getTime
If min({3,14}={Ans(2),Ans(3
"Pi Second→Str1
getTime
If Ans(2)=14 and max(Ans(1)={3,14
"Pi Minute→Str1
getDate
If min({3,14}={Ans(2),Ans(3)
"Pi Day→Str1
Str1
```
[Answer]
# Perl, 80 - 15 = 65 bytes
```
print'No 'x localtime!~/(ar | 15:|03:)14/,'Pi ',(Time,Day,Minute,Second)["@-"/4]
```
Take 2, parsing the string representation of `localtime`. At present, this looks something like this:
```
Sun Jan 3 15:14:15 2016
```
The position of the matched string is used to determine the correct Pi Time.
---
### Perl, 100 bytes
```
@t=localtime;$t[2]%=12;3-/3/^{@t[$_,$_+1]}->{14}||exit!print'Pi ',(Second,Minute,_,Day)[$_]for 3,1,0
```
`localtime` returns the months zero indexed, hence the need for `3-/3/`.
[Answer]
# [05AB1e](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 31 (46 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 15 bonus)
```
žfžeža12%žbDžc)2ôJƵÖk”€º‚Ž™Ù…Þ”#…Pi ìć…No ìªsè
```
[Try it online](https://tio.run/##yy9OTMpM/f//6L60o/tSj@5LNDRSPbovyeXovmRNo8NbvI5tPTwt@1HD3EdNaw7tetQw6@jeRy2LDs981LDs8DygsDKQEZCpcHjNkXYgyy8fyDq0qvjwiv//AQ) or [try it online with emulated datetime](https://tio.run/##yy9OTMpM/W@qoKCglJufV5KhFMNlaALkpCRWApkmIPGM/NKiYqUYFy5jsKrMvNKS1GKYuuLU5Py8FCD3v6bR4S1ex7Yenpb9qGHuo6Y1h3Y9aph1dO@jlkWHZz5qWHZ4HlBYGcgIyFQ4vOZIO5Dllw9kHVpVfHjF//8A).
Adding the `No Pi Time` bonus costed 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage), so it's worth the -15. Here it is without the bonus:
`žfžeža12%žbDžc)2ôJƵÖk”‚Ž™Ù…Þ ”#„Pirèðý` - [Try it online](https://tio.run/##AUoAtf9vc2FiaWX//8W@ZsW@ZcW@YTEyJcW@YkTFvmMpMsO0Ssa1w5Zr4oCd4oCaxb3ihKLDmeKApsOeIOKAnSPigJ5QaXLDqMOww73//w) or [try it online with emulated datetime](https://tio.run/##yy9OTMpM/W@qoKCglJufV5KhFMNlaALkpCRWApkmIPGM/NKiYqUYFy5jsKrMvNKS1GKYuuLU5Py8FCD3v6bR4S1ex7Yenpb9qGHuo4ZZR/c@all0eOajhmWH5ykAhZQfNcwLyCw6vOLwhsN7//8HAA).
**Explanation:**
```
žf # Push the current month
že # Push the current day
ža # Push the current hours (24-hours format)
12% # Modulo-12 to make it a 12-hours format
žb # Push the current minutes
D # Duplicate the current minutes
žc # Push the current seconds
) # Wrap all values on the stack into a list
2ô # Split it into pairs
J # Join each pair together
ƵÖ # Push compressed integer 314
k # Get the first 0-based index of 314 in this list (or -1 if none are)
”€º‚Ž™Ù…Þ” # Push dictionary string "Time Day Minute Second"
# # Split it on spaces: ["Time","Day","Minute","Second"]
…Pi ì # Prepend "Pi " in front of each:
# ["Pi Time","Pi Day","Pi Minute","Pi Second"]
ć # Extract head; pop and push remainder-list and first item separately
…No ì # Prepend "No " in front of it: "No Pi Time"
ª # Append it to the remainder-list:
# ["Pi Day","Pi Minute","Pi Second","No Pi Time"]
s # Swap so the earlier index of 314 is at the top
è # Use it to index into the list of strings,
# where -1 would get the last item
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”€º‚Ž™Ù…Þ”` is `"Time Day Minute Second"` and `ƵÖ` is `314`.
[Answer]
# Python 3, 137 - 15 = 122 bytes
```
import time
T=list(time.localtime())
T[3]%=12
print({1:'Pi Day',3:'Pi Minute',4:'Pi Second'}.get(bytes(T[1:6]).find(b'\x03\x0e'),'No Pi Time'))
```
The 12-hour requirement was unfortunate, as this would've been 118-15=103 bytes without it:
```
import time
print({1:'Pi Day',3:'Pi Minute',4:'Pi Second'}.get(bytes(time.localtime()[1:6]).find(b'\x03\x0e'),'No Pi Time'))
```
[Answer]
# AppleScript, ~~202~~ ~~190~~ ~~187~~ ~~183~~ 181 bytes
Hey, this isn't so bad after all.
```
set n to current date
set b to n's time string
if n's date string contains"March 14"
log"Pi Day"
else if b contains"3:14:"
log"Pi Minute"
else if b contains"3:14"
log"Pi Second"
end
```
~~I actually found a use for AppleScript's method calling. Go figure.~~ Nope. Just turns out that `I'm an idiot`. Setting a variable is shorter.
(for those wondering, current date command returns a date-type with the contents `"Saturday, January 2, 2016 at 2:46:01 PM"` or the like)
[Answer]
# PHP, 85 - 15 = 70 bytes
```
<?=['No Pi Time','Pi Day','Pi Minute','Pi Second'][strpos(@date(Ymdhi_is),'0314')/4];
```
---
The main trick use here is the `Ymdhi_is` [date format](http://php.net/manual/en/function.date.php), at the time of writing, `date('Ymdhi_is')` returns `201501030258_5828`.
* `md`, `hi` and `is` are the values who will be replaced by `0314` if it's Pi-something. Note that all those strings will be always be replaced by a 4-character long string.
* They are put in that specific order since `strpos` will stop searching at the first occurrence of the needle, so we put them in the order of priority.
* A separator between `hi` and `is` is necessary because we don't want `strpos` to match a value that would overlap both (thanks to [primo](https://codegolf.stackexchange.com/questions/68371/pi-day-pi-minute-or-pi-second/68460#comment166273_68460) for saving bytes here).
* The needle is `0314` because `314` would wrongly match 10:31:42 as Pi-Second.
The Y part is the trickiest. We need a prefix to to offset the first occurrence of Pi-something, allowing us to distinguish `strpos`'s return values between `false` (not found, Pi-nothing) and `0` (found at index 0, Pi-day).
And we want this prefix to be either 4 or 5-character long, since we are planning to divide `strpos`'s return value by 4.
Y is 4-character long, but:
* it will be 5-character long someday, and this will break the program (think about year 10314): [the PHP documentation](http://php.net/manual/en/function.date.php#refsect1-function.date-parameters) says that `Y` will be replaced by 4 digits, but [it's not true](https://3v4l.org/N9MlD).
* if you come back in time, at year 314, it will break the program.
Since PHP didn't exist in year 314, and will likely not exist anymore in year 10314, I guess these bugs can be safely ignored.
Note that `0314` can overlap `Ymd` since:
* `Ymmd` configuration: there's no 31st month.
* `YYmm` configuration: there's no 14th month.
* `YYYm` configuration: there are less than 40 months.
---
Also, there's a version without the bugs related to the year, which is **86 - 15 = 71 bytes**:
```
<?=['No Pi Time','Pi Day','Pi Minute','Pi Second'][strpos(@date(D_mdhi_is),'0314')/4];
```
[Answer]
# [Go](https://go.dev), 211 - 15 = 196 bytes
```
import."time"
func f(){N,s:=Now(),"Pi "
M:=N.Minute()
if _,m,d:=N.Date();m==3&&d==14{s+="Day"}else if N.Hour()%12==3&&M==14{s+="Minute"}else if M==3&&N.Second()==14{s+="Second"}else{s="No "+s+"Time"}
println(s)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY_BisIwEIbveYowoCS0FtQ9LEpuHrw0CLt3CW0qQZOUJkWk9Em8lAVv3vZRPPk2ts3inob5_49hvuvPwXb3UmRHcZBYC2VutS9mn8-H0qWtfAJeaQmoqE2GC0IbHrsV4_ZMaAw7hQGl_ZqkytReEopUgfexjvMh3IghWmvGltNpztj8o3ERg424QCtPTuIe5snW1hWhk_lixNI3Fk7-k-nY8-RLZtbkhL7BEASwcQy4xRC5CL6Hx1tUVsr4kyGOtkHtd3QZVAnFDeql0F_TdWG-AA)
Prints to STDERR.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~48~~ ~~47~~ 45 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
:\ I can *definitely* do better than this! Outputs `undefined` if it's not a Pi date/time. Second line include a trailing space.
```
`DÃÕsMÔSSeÖ`qÅæÏgKs6 f"%d+" ã2)e#;ìF
©i"Pi
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YETD1XNNiNRTU2XWCGBxxebPZ0tzNiBmIiVkKyIg4zIpZSM77EYKqWkiUGkg), or test:
* [Pi Day](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=Sz3QS2kgMkUzRUU&code=YETD1XNNiNRTU2XWCGBxxebPZ0tzNiBmIiVkKyIg4zIpZSM77EYKVqlpIlBpIA)
* [Pi Minute](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=Sz3QS2kgMkQzRUU&code=YETD1XNNiNRTU2XWCGBxxebPZ0tzNiBmIiVkKyIg4zIpZSM77EYKVqlpIlBpIA)
* [Pi Second](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=Sz3QS2kgMkRBM0U&code=YETD1XNNiNRTU2XWCGBxxebPZ0tzNiBmIiVkKyIg4zIpZSM77EYKVqlpIlBpIA)
```
`...`qÅæÏgKs6 f"%d+" ã2)e#;ìF\n©i"Pi
`...` :Compressed string "DaysssMinutesSecond"
q :Split on
Å : "s"
æ :Get first element to return true
Ï :When its index is passed through the following function
g : Index into
K : Date
s6 : To locale string (M/D/Y, h:m:s A/PM)
f : Match
"%d+" : RegEx /\d+/
ã2 : Sub-arrays of length 2
) : End indexing
e : Is equal to
#; : 59
ì : Converted to digit array in base
F : 15
\n :Assign to variable U
© :Logical AND with
i"Pi : U prepended with "Pi "
```
[Answer]
## Pascal, 226 Bytes
See also [FreePascal](/a/259162).
This `program` requires a processor complying to ISO standard 10206 “Extended Pascal”.
```
program p(output);var t:timeStamp;begin getTimeStamp(t);with t do write(subStr('Pi Day ',1,9*ord(month=3))+subStr('Pi Minute',1,9*ord(hour in[3,15]))+subStr('Pi Second',1,9*ord(minute=3)):9*ord(14 in[day,minute,second]))end.
```
Ungolfed:
```
program piDMS(output);
var
ts: timeStamp;
begin
getTimeStamp(ts);
{ `with t do ` is two characters shorter than six times `t.` }
with ts do
begin
writeLn(
{ subStr(string, firstCharacterIndex, length) }
subStr('Pi Day ', 1, 9 * ord(month = 3)) +
subStr('Pi Minute', 1, 9 * ord(hour in [3,15])) +
subStr('Pi Second', 1, 9 * ord(minute = 3))
: 9 * ord(14 in [day, minute, second])
);
end;
end.
```
---
**216 characters** if
* the *implementation-defined* value of `maxChar` has an ordinal value ≥ 59 and
* neither `chr(3)` or `chr(14)` of the *implementation-defined* set of `char` values indicate an end of line (Pascal does not permit multiline strings).
```
program p(output);var t:timeStamp;begin getTimeStamp(t);with t do year:=index(chr(month)+chr(day)+chr(hour mod 12)+chr(minute)+chr(second),'');write(subStr('Pi SecondPi Minute Pi Day ',37-9*t.year):9)end.
```
NB:
The `string` literal `''` is `chr(3) + chr(14)`.
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~263~~ 229 bytes
```
uses sysutils,RegExpr;var x:array[0..2]of string=('.*:03:14','.* 03:14.*','14-3.*');y:array[0..2]of string=('Second','Minute','Day');i:word;begin
for i:=0to 2do if ExecRegExpr(x[i],DateTimeToStr(Now))then writeln('Pi ',y[i]);end.
```
[Try it online!](https://tio.run/##dY69DoIwFEZ3n@JugMEGf6YSNxg1Rt2MQ4UL3gRbcluEPj02xtXtfMk5ydcrW6lu1fTVPA8WLVhvB0edTc/YllPP@VsxTFIxK3/LhNjcTQPWMel2H0diKbOtXO@iNCB8USzDWO9W2wBJ7v@VF6yMroN6ID04DFAoHwKSo@E6f2BLetEYBpL7zBnY1AaogXLC6vcsnm50Twvl8EovvJqL4/hoxiRxT9QwMjnsdBydCKLUBzXJUddinj8)
~~[263b](https://tio.run/##dY49b8IwFEX3/oq3xUbBCh@TrTDBWFQVNsTgJi/hSalt2Q6Jf31q0a7dztW9R7pOh0YP6841yzIGDBBSGCMNofzE/jQ7r57awyy19zrdKiG2d9tBiJ5MX7NCrGS1k5t9UWaEF4pVDpv9epeBq/SfecHGmjZP38mMETMcdcqCk78TRXKyvlVf2JN566wHknUVLWxbC9TBacbm7yKbb3Qvjzrilb7xai/Rs7OdOI8PNOBknXKvsjOg6eODOX6o4NVNniIOhhUfBEXpuELTimX5AQ "Pascal (FPC) – Try It Online")~~
Might be shortened by using `if..then..elseif..` instead of complicated arrays & loops.
[Answer]
# Python 3, 179 bytes
```
import functools as F,datetime as D
T,G=D.datetime.now(),getattr
F.reduce(lambda i,j:print("Pi "+i.title())if G(T,i)/G(T,j)==3/14else j,"month day hour minute second".split(" "))
```
[Answer]
# [Zsh](https://www.zsh.org/)\*, ~~93~~ ~~88~~ 83 (98-15) bytes
```
case `date` in *Mar\ 14*)t=Day;;*\ 03:14*)t=Minute;;*03:14\ *)t=Second;esac
<<<Pi\ ${t?No Pi Time}
```
[Try it online!](https://tio.run/##Zc5LC4JAFIbhvb/ioG1y5aULeKFFbQ0ho40LJ@dQAzlGc4Qs@u02aouo3cfLA@c81LlTSPWVAO@EkiM/XeqjYViEioCz1gLgsZk1CAm7gTsDdxH4y0CPfbYGz/F884MrIUd8QD7iOTi@loEev1hh@YddNxj8F@5KphAKzggLEBJsTXP9hT2leMPaMLTz8UYfEiEbQt2GkkPfdljWkoeoWGlEUZSKHCZPWm1rSAVkosJX170B) (98-15 bytes)
~~[103-15 bytes](https://tio.run/##Zc5NS8NAEAbge37FS1MoRoQm8QPygQe9eKgWTPGSQ9fsaBfMrs1O0Cr@9rjZeBA9zfDOM8x82N1gic0rg96ZtCT5/GIeAymYgiAEk2XszBuqmzs8ma4VbOGHoS84kVgcx4kzfWcXbsVvSHEIAVnOqp6wEh3iU8TnWXqRuWZTXSFZJunsB7dKT/iB5ITPsEydzFzzF1tq/uE4zrz/hYdGWMJ2fHELpRE5WrsvoiMur8Uhz6N6ujEGK6V7Jpf5pMaY3VNjtMzJiibYl2tVY/7Jl7cGa4VKtfSVF0Ux3w/DNw)~~
~~[93 bytes](https://tio.run/##Zc5NS8NAEAbge37FS1MoRoRu4gfkgx704qEomOIlh67ZaRuwu212glbxt8fNxoPoaYZ3nmHmw@56S2wODHpn0orU9tW8BEoyBUEIJsvYmTeU9w/YmHYv2cIPQ19woTA7F7EzXWtnbsVvKHkKAVVMyo6wlC3EJcR1mtykrlmVt4jncTL5wftGj/iZ1IivME@cTF3zF1uq/2EhUu9/4b6WlrAeXlyj0YgcrdwX0RkXd/KUZVE13hiCZaM7Jpf5pMKQPVFttMrIyjo4Fo9NheknL76yPM@nx77/Bg "Zsh – Try It Online")~~
~~[107-15 bytes, using associative array](https://tio.run/##dY5Na8JAEIbv@RXDmoMGAonRCmtCKfWqCEY8WME1O9ilmoRkFD/wt8elK6IGb@8Mz/txKn@rEinLCfBAmEqU6022sqwGYUkgxbEBUEQs3iEMRQF@B/wPHvS4FtP4G9peO2A3eKtSA89QGrgLXqBJrsUrXGJSg32f//M1WM9w9@49/2HMLf@d5d7yYnluqSQmG1EguF@QR03mGNJhMBBHYI5p0edQpTtC/TEz9WeCSZbKlkWRfc7nzb/WUgrC5eLSD8NwrH7APhP/HGUwVhCrLV6q6go)~~
Used `extendedglob` for matching the `case` patterns. If `$t` wasn't set (`${t?}`), then it prints "No Pi Time" to stderr.
] |
[Question]
[
From Wikipedia [Set-theoretic definition of natural numbers](http://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers)
>
> The set N of natural numbers is defined as the smallest set containing
> 0 and closed under the successor function S defined by S(n) = n ∪ {n}.
>
>
> The first few numbers defined this way are 0 = {}, 1 = {0} = {{}}, 2 = {0,1} = {{},{{}}}, 3 = {0,1,2} = {{},{{}},{{},{{}}}}.
>
>
>
Using this definition of natural numbers count the length of a string.
**Input** a string of characters from a-zA-Z of any length
**Output** the length of the string in set notation without separators
**Examples**
**Input** Empty string
**Output** {}
**Input** a
**Output** {{}}
**Input** aaaa
**Output** {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}
For readability output for 'aaaa' with separators is
```
{
{}
{{}}
{{} {{}} }
{{} {{}} {{} {{} } } }
}
```
Conditions
1. No digits 0 to 9 to appear in the code;
2. No use of character code conversion to generate numbers;
3. No use of +-\*/ for arithmetic calculations including increment and decrement;
4. No mathematical operations other than Boolean Logic;
5. Input string does not count in determining byte length;
**Winner** Shortest code length in bytes.
As this is my first question I hope I have made it clear and rigorous enough. Friendly advice accepted.
[Answer]
# Haskell function, ~~35~~ 34 characters
```
f[]="{}";f(_:x)='{':f x++tail(f x)
```
# Haskell program with hardcoded input, ~~48 or 49~~ 47 or 48 characters
```
f[]="{}";f(_:x)='{':f x++tail(f x);main=print$f"aaaa"
```
(47 characters if you don't mind extra quotes around the output; if you do, use `putStr` instead of `print` for a total of 48 characters)
# Haskell program, ~~51~~ 50 characters
```
f[]="{}";f(_:x)='{':f x++tail(f x);main=interact f
```
[Answer]
## GolfScript (18 17 bytes)
```
'{'\{;.'}'++}/'}'
```
Takes input on the stack (so if run as a program, via stdin). Leaves the output as two strings on the stack (so if run as a program, the correct output is sent to stdout).
To leave a single string on the stack, either append `+` to concat, or use the alternative
```
'{}'\{;.);\'}'++}/
```
### Dissection
```
# Stack: input-str
'{'\
# Stack: <0< input-str where <0< means the string representing 0 without its final }
# Loop over each character of the input string
{
# Stack: <n< char
# Discard the input character
;
# Concatenate two copies of <n< and a }
.'}'++
}/
# Push the final } to the stack
'}'
```
Alternative:
```
# Stack: input-str
'{}'\
# Stack: <0> input-str (where <0> means the string representing 0)
# Loop over each character of the input string
{
# Stack: <n> char
# Discard the input character
;
# Duplicate <n> and remove the final '}'
.);
# Stack manipulations
\'}'
# Stack: <n>-less-final-'}' <n> '}'
# Concatenate the three strings to get <n+1>
++
}/
```
### Impact of the restrictions
If decrement were allowed, it would permit the 15-byte solution
```
'{}'\{;..,(/*}/
```
[Answer]
# Python 3 - 64
```
o=['{}']
for a in input():o+=['{'+''.join(o)+'}']
print(o.pop())
```
If inlining the input is allowed:
# Python 2 - 54
```
o=['{}']
for a in'whatever':o+=['{'+''.join(o)+'}']
print o.pop()
```
[Answer]
# Javascript 70 (chars)
```
s='';c=prompt().split('');while(c.pop()){s+='{'+s+'}'}alert('{'+s+'}')
```
This was my effort before setting the question. I would assume someone with more knowledge of Javascript than me can probably beat it.
Thank you Jan Dvorak and Peter Taylor for further reductions
# now 62
```
s='{';c=prompt().split('');while(c.pop())s+=s+'}';alert(s+'}')
```
# and now 61
```
s='{';for(c=prompt().split('');c.pop();)s+=s+'}';alert(s+'}')
```
**Explanation of Original Code**
set s to be empty
input string into c and split into an array
while it is possible to pop() a character from c do so and reset s=s{s} as successor
output current s but need to surround with set brackets.
[Answer]
# J - ~~22~~ 20 char
```
'{','}' '{'&(,,~)~#
```
How this can be derived:
```
#'123' NB. string length
3
'Left' (,,~) 'Right' NB. dyad to concat L,R,R
LeftRightRight
'{' (,,~) '}' NB. using braces
{}}
'{'&(,,~) '}' NB. bind left argument, now it's a monad
{}}
'{'&(,,~) '{'&(,,~) '}' NB. twice
{{}}{}}
'{'&(,,~)^:2 '}' NB. ^: is monad functional power
{{}}{}}
'{'&(,,~)^:3 '}' NB. any integer
{{{}}{}}{{}}{}}
3 '{'&(,,~) '}' NB. convenient feature of dyadic &
{{{}}{}}{{}}{}}
'}' '{'&(,,~)~ 3 NB. swap argument order
{{{}}{}}{{}}{}}
'}' '{'&(,,~)~ #'123' NB. using string length
{{{}}{}}{{}}{}}
'{', '}' '{'&(,,~)~ #'123' NB. add final brace
{{{{}}{}}{{}}{}}
('{','}' '{'&(,,~)~#) '123' NB. works as a verb
{{{{}}{}}{{}}{}}
```
Alternatively, this can be written `'{','{'&(,,~)&'}'@#`, meaning the same thing.
Usage:
```
'{','}' '{'&(,,~)~# 'aaaa'
{{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}
f =: '{','}' '{'&(,,~)~# NB. can be assigned to a function
f 'VeryBig'
{{{{{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}{{{{}}{}}{{}}{}}{{{}}{}}{{}}{}}
```
[Answer]
**Haskell - 35 charactes**
```
g[]="{}";g(_:x)=(init.g)x++g x++"}"
```
Solution is influenced by Jan Dvorak's one, but without reversing the order.
[Answer]
# Scala, 64 characters
```
def f(s:String):String=s"{${s.tails.toSeq.tail.map(f)mkString}}"
```
Note the dual roles that both the braces and `s` play in this code.
EDIT: removed a digit
[Answer]
# Python 3 (44)
```
s='{'
for _ in input():s+=s+'}'
print(s+'}')
```
At each step, `s` is the string representing the set with the final `}` removed. We create the set representing `n+1` from the set representing `n` via the relationship f(n+1) = f(n) ∪ {f(n)}. To implement the union with strings, we append the string for {f(n)}, which is exactly `s` but with the final `}` returned, and neglect to include the final `}` in the result. Finally, we add back a final `'}'` before printing.
If I may hardcode the string, the character count cuts down to 35 character, switching to Python 2 to save parantheses on the `print`.
```
s='{'
for _ in'string':s+=s+'}'
print s+'}'
```
There might be a way to save the space after the `print` by doing something like `print'{'+s` with a reversed `s`, but this messes up with the `+=` appending on the right.
[Answer]
# gs2, 12 bytes
```
7b 7d 05 27 a0 42 30 30 e4 43 2e 32
```
mnemonics:
```
"{}"
right-uncons @0 swap + + b5
rot length times
```
[Answer]
# Mathematica, 115 characters
```
StringReplace[ToString@Function[s,NestWhile[#~Append~#&,{},(s~Read~Character//StringQ)&]]@StringToStream@"test",", "->""]
```
The complete code as shown has 121 characters, but 6 of them are used for the input string (`"test"`) which, according to the rules, doesn't count.
Without the requirement that there are no delimiters, the code length could be reduced further by 24 characters; without explicit conversion to string then another 9 characters could be removed.
[Answer]
# Ruby, 27, kind of cheating
```
a=*a
gets.chars{a=*a,a}
p a
```
Questionable things:
1. Output looks like `[[], [[]], [[], [[]]], [[], [[]], [[], [[]]]]]`
2. Most methods of input to ruby will include a trailing newline, which inflates the count by 1.
[Answer]
# Pure Bash, 54
```
f()([ $@ ]&&(a=`f ${@%?}`
echo $a{$a}))
echo {`f $@`}
```
Output:
```
$ ./strlenset.sh
{}
$ ./strlenset.sh a
{{}}
$ ./strlenset.sh aa
{{}{{}}}
$ ./strlenset.sh aaa
{{}{{}}{{}{{}}}}
$ ./strlenset.sh aaaa
{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}
$
```
[Answer]
# Julia 43
```
f(z)="{"foldl((x,y)->"$x{$x}","",{z...})"}"
```
The construct **{z...}** expands the string z into an array. Fold loops over all elements of the array ignoring the contents and instead building up from the empty string. The function **foldl** is available in Julia 0.30.
Sample Output
```
julia> f("")
"{}"
julia> f("aa")
"{{}{{}}}"
julia> f("aaaa")
"{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}"
julia> f("aaaaaa")
"{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}"
```
[Answer]
# Haskell, 31 bytes
```
foldl(\s _->init s++s++"}")"{}"
```
[Answer]
# Mathematica, ~~45~~ ~~57~~ 48 bytes
```
"{"~~Fold[#~~"{"~~#~~"}"&,"",Characters@#]~~"}"&
```
---
A 36 bytes solution:
```
Fold[{##{##}}&@@#&,{},Characters@#]&
```
However, it uses some arithmetic calculations.
[Answer]
# Delphi XE3 (264)
Ok I dont even come close to the other but it was fun to do :)
Probably overthinking it. Going to see if there is a better way to do this.
### Golfed
```
uses System.SysUtils;var s,f:string;a:TArray<char>;b:TArray<string>;i,x:integer;begin readln(s);a:=s.ToCharArray;f:='{';setlength(b,Length(a));for I:=Low(a)to High(a) do begin s:='{';for x:=Low(b)to High(b)do s:=s+b[x];b[i]:=s+'}';f:=f+b[i];end;writeln(f+'}');end.
```
### Ungolfed
```
uses
System.SysUtils;
var
s,f:string;
a:TArray<char>;
b:TArray<string>;
i,x:integer;
begin
readln(s);
a:=s.ToCharArray;
f:='{';
setlength(b,Length(a));
for I:=Low(a)to High(a) do
begin
s:='{';
for x:=Low(b)to High(b)do
s:=s+b[x];
b[i]:=s+'}';
f:=f+b[i];
end;
writeln(f+'}');
end.
```
### Testing results
Tested strings with length 0..10
```
{}
{{} }
{{} {{}} }
{{} {{}} {{}{{}}} }
{{} {{}} {{}{{}}} {{}{{}}{{}{{}}}} }
{{} {{}} {{}{{}}} {{}{{}}{{}{{}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}} }
{{} {{}} {{}{{}}} {{}{{}}{{}{{}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}} }
{{} {{}} {{}{{}}} {{}{{}}{{}{{}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}} }
{{} {{}} {{}{{}}} {{}{{}}{{}{{}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}} }
{{} {{}} {{}{{}}} {{}{{}}{{}{{}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}}} }
{{} {{}} {{}{{}}} {{}{{}}{{}{{}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}}} {{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}{{}{{}}{{}{{}}}{{}{{}}{{}{{}}}}}}}}}} }
```
[Answer]
**Perl 5: 33 characters**
It's not quite clear which characters I should count as part of the solution. Probably not the `echo ... |` part because that's just used to feed a line in to stdin. Probably not the name of the perl binary, because you could rename that whatever you wanted.
So I've counted the command-line switches passed to perl, the quote marks wrapped around the Perl code, and the Perl code itself.
```
# 1 2 3
# 12 3456789012345678901234567890123
$ echo "aaaa" | perl -ple'$s.="{$s}"while s/.//;$_="{$s}"'
```
Also, [related](https://metacpan.org/pod/Number%3a%3aNatural%3a%3aSetTheory).
[Answer]
# Perl 6: 37 characters
```
say ({"\{@_.join()\}"}...*)["(input string)".chars]
```
or from STDIN:
```
say ({"\{@_.join()\}"}...*)[get.chars]
```
`{"\{@_.join()\}"}...*` makes a lazy list of the set forms of the natural numbers, and we just grab the one we need with `get.chars`.
The lazy list might be more readably written:
```
-> *@prev { '{'~ @prev.join ~'}' } ... *
```
Which reads pretty similarly to the definition.
[Answer]
## Dart: 85 characters
```
a(p,i)=>(--i).isNegative?p:a("$p{$p}",i);
main(s){print("{${a("",s.first.length)}}");}
```
(with extra newline for readability).
The requirement of not using "0" really bites, otherwise `.first` would be `[0]` and `(..).isNegative` would be `..<0`.
[Answer]
# Pyth, 13 bytes
```
+u++GG\}z\{\}
```
This is the golfed Pyth equivalent of @xnor's Python answer. Note that Pyth is newer than this question, so this answer is not eligible to win this challenge.
[Demonstration.](https://pyth.herokuapp.com/?code=%2Bu%2B%2BGG%5C%7Dz%5C%7B%5C%7D&input=aaaa&debug=0)
[Answer]
# Javascript, ~~171~~ ~~149~~ ~~147~~ 142 bytes
(Will likely be golfed further later)
```
n=prompt().split("");for(a=[];n.pop();)a.push(a.slice());alert(JSON.stringify({a:a})[R="replace"](/[^\[\]]/g,"")[R](/\[/g,"{")[R](/\]/g,"}"));
```
] |
[Question]
[
In [my previous code challenge](https://codegolf.stackexchange.com/questions/16349), I asked you to write a function that tells you which of its lines has been removed.
The instructions were:
>
> Write a function that contains five lines.
>
>
> If you run the function as-is, it should return 0.
>
>
> If you remove any one of the five lines and run the function, it
> should tell you which of the lines has been removed (e.g., if you
> remove the final line it should return 5).
>
>
>
Now, let's try something a teensy bit more difficult.
Follow the same rules as above, but this time, the function should return an array telling you which TWO lines have been removed.
So, for instance, if I remove lines 1 and 5, the return value should be [1,5], and if I remove lines 3 and 4, the return value should be [3,4].
Again, if no lines are removed, the function should return 0. Bonus points if you can also handle the one-line-removed case, but it's not strictly necessary that you do so.
Can you make use of helper functions? Yes, but only if you have to. A single self-contained function that pulls this off is the ideal.
As with the last challenge, the highest upvoted solution wins. I'll pick the winner in a week, or sooner if no new submissions have been received in 24 hours.
[Answer]
# Perl
```
sub foo {
@a = (2..5);
@a = grep $_ != 2, (@a ? @a : (1..5));
@a = grep $_ != 3, (@a ? @a : (1..5));
@a = grep $_ != 4, (@a ? @a : (1..5));
@a = grep $_ != 5, (@a ? @a : (1..5));
}
```
This actually works for any number of lines removed (as long as it's not *all* the lines, that is), and can be trivially extended to more than 5 lines. No helper functions are used, and it even uses only one statement per line. It relies on the fact that, in the absence of an explicit `return` statement, the return value of a Perl function is the value of the last statement in it.
Note that (in list context) this code returns an empty list rather than the number 0 if no lines have been deleted. This could be fixed (e.g. by appending "`@a ? @a : 0;`" to the last line), but would make the code uglier. In any case, in *scalar* context it *does* return the number of deleted lines, which will be 0 if no lines have been removed. ;-)
[Answer]
# Ruby
Similar to the Perl version, but in Ruby. I return 0 if no lines are deleted as requested, but I agree it makes the code uglier and doesn't quite make sense as a return value.
```
def which_lines_removed(arr = [*1..5])
arr -= [1]
arr -= [2]
arr -= [3]
arr -= [4]
(arr -= [5]).empty? ? 0 : arr
end
```
If an empty array is acceptable as the return value when no lines are deleted, the code looks like this:
```
def which_lines_removed(arr = [*1..5])
arr -= [1]
arr -= [2]
arr -= [3]
arr -= [4]
arr -= [5]
end
```
Both methods work for any number of lines deleted between 0 and 5.
[Answer]
# JavaScript, 152 characters golfed
```
function t() {
var fa = (f + '').match(/\d/g)
var ra = []
for (var i = 0; i < 5; i++) {
if (fa.indexOf(i + '') < 0) ra.push(i + 1)
}
return ra
}
function f() {
0; return t()
1; return t()
2; return t()
3; return t()
4; return t()
}
```
Golfed:
```
function t(){for(a=[],i=0;++i<5;)if((f+'').indexOf(i)<0)a.push(i+1);return a}function f(){
return t(0)
return t(1)
return t(2)
return t(3)
return t(4)
}
```
Self contained (but ugly):
```
function f() {
0; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
1; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
2; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
3; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
4; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
}
```
Basically exploits function `toString` by numbering each line. Note that you actually have to remove the line because of this (commenting it out will not work).
This actually works for **any number of lines removed**! It will return an array of the lines removed, or an empty array if none have been removed. (I could easily change that to return zero (by replacing `return ra` with `return ra || 0`), but I like the empty array solution since it would be more useful in the real world.)
For example, removing the first line returns `[1]`, and removing everything but the first line returns `[2,3,4,5]`. (Of course, it doesn't work if you remove all lines `;-)`)
[Answer]
## Ruby
```
def f
a = [ 2, 3, 4, 5 ]
defined?(a) ? a = a.select { |num| num != 2 } : a = [ 1, 3, 4, 5 ]
defined?(a) ? a = a.select { |num| num != 3 } : a = [ 1, 2, 4, 5 ]
a = a.select { |num| num != 4 }
(a = a.select { |num| num != 5 }) == [] ? a = 0 : a
end
```
How this works: my idea was: create an array, and on each line, remove a specific value. So, on the first line, I actually have the array `[ 1, 2, 3, 4, 5]`, with the element `1` removed. At the second line, if `a` is already defined, remove the element `2`. Otherwise, create a new array with the element `2` removed. Do the same for line 3. At line 4, you can be sure that there is already an array created, so just remove element `4`. At line 5, first remove element `5`, and if `a` is then an empty array, return `0`. Otherwise, return `a`.
[Answer]
# Python
```
f=lambda:{1,2,3,4,5}-{
1,
2,
3,
4,
5,
} or 0
```
Returns 0 if no line is removed, otherwise returns the removed lines. You can remove 1 to 5 lines, except the 0th and 6th line ;-).
[Answer]
## JavaScript, self-contained, works for 0, 1, 2 removed lines (~~607~~ ~~315~~ 186 chars)
## → [live demo](http://xem.github.io/miniCodeEditor/1.1/#w=%0Afunction%28r%29%7B%0A%20%20r.shift%28%29;%0A%20%20r.splice%28r.indexOf%282%29,1%29%0A%20%20r.splice%28r.indexOf%283%29,1%29;a=b=1;if%28this.a&&this.b%29return%20r%0A%20%20var%20a;r.splice%28r.indexOf%284%29,1%29;b=1;if%28this.b%29return%20r%0A%20%20var%20b;r.pop%28%29;return%20r%5B0%5D?r:0%0A%7D%0A%0Adocument.write%28w%28%5B1,2,3,4,5%5D%29%29%7F%7F%3Ch2%3ERemove%201%20or%202%20lines%20of%20the%20function%20w,%20it%20will%20return%20the%20number%20of%20the%20removed%20line%28s%29%3C/h2%3E%0A%0ARemoved%20lines%3a%201) ←
Abusing JS variable hoisting and global leaking, like in the other challenge :)
```
function(r){
r.shift();
r.splice(r.indexOf(2),1)
r.splice(r.indexOf(3),1);a=b=1;if(this.a&&this.b)return r
var a;r.splice(r.indexOf(4),1);b=1;if(this.b)return r
var b;r.pop();return r[0]?r:0
}
```
to be called with the array [1,2,3,4,5] as parameter.
**315 chars**
```
function(r){
var a;
var b;
var c;a=1;b=2;d=4;e=5;for(i in(z="abde".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
var d;a=1;b=2;c=3;e=5;for(i in(z="abce".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
var e;a=1;b=2;c=3;d=4;for(i in(z="abcd".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
}
```
to be called with an empty array as parameter.
**non-golfed version**
(also works for 3 and 4 lines removed):
```
function(r){
var a;b=c=d=e=1;if(this.b)r.push(2);if(this.c)r.push(3);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var b;a=c=d=e=1;if(this.a)r.push(1);if(this.c)r.push(3);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var c;a=b=d=e=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var d;a=b=c=e=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.c)r.push(3);if(this.e)r.push(5);return r.length?r:0;
var e;a=b=c=d=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.c)r.push(3);if(this.d)r.push(4);return r.length?r:0;
}
```
to be called with an empty array as parameter.
[Answer]
**JavaScript:**
```
var f = function(){
1
2
a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;3
a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;4
a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;5
}
```
[fiddle](http://jsfiddle.net/briguy37/64ySU/)
[Answer]
# Javascript
```
(function (i){
i += .1; // line 1
i += .02; // line 2
i += .003; // line 3
i += .0004; // line 4
i += .00005; // line 5
return (Math.round((.12345-i)*100000)/100000+'').match(/([1-5])/g) || 0 })(0)
```
Call it what you like, but I think it's *pretty*.
Lets you know which lines were removed (1 or more), or 0 if no lines are removed. All 5 lines **can** be removed.
**EDIT:**
Because it was brought to my attention that my code might actually consists of 6 lines, and is in violation of the rules, I adjusted it to the following:
```
(Math.round((.12345 - (new (function(){
this.i = isFinite(this.i) ? this.i + .1 : .1 ;
this.i = isFinite(this.i) ? this.i + .02 : .02;
this.i = isFinite(this.i) ? this.i + .003 : .003;
this.i = isFinite(this.i) ? this.i + .0004 : .0004;
this.i = isFinite(this.i) ? this.i + .00005 : .00005;
})().i || 0) )*100000)/100000+'').match(/([1-5])/g) || 0
```
The same applies -- it will return an array of removed lines ranging from 1-**All** or 0 if none.
[Answer]
# Common Lisp
```
(defun which-lines-are-removed (&aux (x (list 1 2 3 4 5)))
(setq x (remove-if #'(lambda (x) (eql x 1)) x))
(setq x (remove-if #'(lambda (x) (eql x 2)) x))
(setq x (remove-if #'(lambda (x) (eql x 3)) x))
(setq x (remove-if #'(lambda (x) (eql x 4)) x))
(setq x (remove-if #'(lambda (x) (eql x 5)) x))
)
```
It works for removal of 1-4 lines. If you remove all lines it will return the same as if you remove none.
NB: Having ending parenthesis on it's own line is considered bad style, but since other languages has `end` and `}` I assume it is allowed.
[Answer]
# Python
```
def function(a = [1,2,3,4,5]):
delete(a, len(a)-5)#1
delete(a, len(a)-4)#2
delete(a, len(a)-3);print a if len(a)==2 else '',#3
delete(a, len(a)-2);print a if len(a)==2 else '',#4
delete(a, len(a)-1);print a if len(a)==2 else '',#5
def delete(a, i):
del a[i]
return a
```
It works for all lines - but only if two are deleted. If only one line is deleted then it will print the deleted line and line 5. If too many lines are deleted it won't print anything.
This uses a helper function because the del keyword can't be used in a line with a ;(as far as I know)
Basically, each line deletes itself in the array that is declared in the constructor, then if enough lines have been deleted the array is printed.
This function misses the spec in two ways:
1. it doesn't print 0 if it is run as-is(it assumes the last two lines have been commented and so prints 4, 5
2. It assumes that `print` and `return` are interchangeable
[Answer]
# [Déjà Vu](https://github.com/gvx/deja)
Works for removing any number of lines (as long as you leave at least one line)
```
local line n:
try:
dup
catch stack-empty:
dup set{ 1 2 3 4 5 }
delete-from swap n
func which-gone:
line 1
line 2
line 3
line 4
line 5
```
[Answer]
# R
I have another version in R which I think is better (but uses a helper function):
```
trick <- function(sym, value) {
assign(sym, value, envir=parent.frame())
values <- unlist(as.list(parent.frame()))
if(length(values)==5) 0 else which(!1:5 %in% values)
}
reportRemovedLines <- function(){
trick("a", 1)
trick("b", 2)
trick("c", 3)
trick("d", 4)
trick("e", 5)
}
```
Or one can avoid using the helper function by defining it as a default argument (works identically but is less readable -- however, it does not use a "separately defined" helper function):
```
funnyVersion <- function(trick = function(sym, value) {
assign(sym, value, envir=parent.frame())
values <- unlist(as.list(parent.frame()))
if(length(values)==5) 0 else which(!1:5 %in% values)
}){
trick("a", 1)
trick("b", 2)
trick("c", 3)
trick("d", 4)
trick("e", 5)
}
```
Both `reportRemovedLines()` and `funnyVersion()` work with any number of lines removed - except if you remove all lines (in that case, they will return `NULL`). They actually *return* the line numbers, not just print them - as in R, the value of the last expression evaluated within a function will automatically be returned.
How does it work? The trick is in the `trick` function which takes all objects from its "parent environment" (i.e., environment of the function that calls it), puts their values together in a vector, and returns, which values from 1 to 5 are not represented.
[Answer]
## JavaScript (136/166 chars)
A smaller version with some values declared at the beginning:
```
function(){b=[1,2,3,4,5],i=0
b.splice(0,1);i++
b.splice(1-i,1);i++
b.splice(2-i,1);i++
b.splice(3-i,1);i++
b.splice(4-i,1);i++
return b}
```
A self-contained version (you don't need to pass anything - the b argument is there so I can check if b is defined with `||`)
```
function(b){
b=[2,3,4,5],i=1
b=b||[1,2,3,4,5],i=i||0,b.splice(1-i,1);i++
b=b||[1,2,3,4,5],i=i||0,b.splice(2-i,1);i++
b.splice(3-i,1);i++
b.splice(4-i,1);i++
return b}
```
Yes, both have `return` statements, but that is only fair if I am competing with languages with implicit return.
[Answer]
# R
A simple version (not foolproof as you will get an error if you remove line 5):
```
doit <- function() setdiff(1:5, c(
1,
2,
3,
4,
5
))
```
And a foolproof version:
```
doit<-function() setdiff(1:5, scan(text="
1
2
3
4
5
"))
```
It works with any number of lines removed (except if you remove all the lines), and can easily be extended to more than 5 lines. Running it "as is" will return `integer(0)` which is conceptually similar to returning just `0`. Returning an actual 0 would make it uglier and longer but would not be complicated.
Finally, a version using magic:
Helper function:
```
dysfunction <- function(E){
FUN <- function(){}
e <- substitute(E)
e[[1]] <- as.name("list")
nb <- quote(setdiff(as.list(1:5), x))
nb[[3]] <- e
body(FUN) <- nb
FUN
}
```
The actual function:
```
df <- dysfunction({
1
2
3
4
5
})
```
[Answer]
**C++**
```
void function(int & i)
{
i=i|1;
i=i|2;
i=(i|4);
i=(i|8);
i=(i|16);
}
int[] func2(int i)
{
int arr[]={0,0};
int k=0,l=1;
for(int j=1;j<=16;j*=2,l++)
{
if((i&j)==0)
{
arr[k++]=l;
}
}
return arr;
}
```
How to use: call the function with i and use func2 for understanding that what function is telling.
If you change the line int arr[]={0,0} to int arr[]={0,0,0,0,0} it will also work for all five lines, it is also handline one line remove test case automatically, what i am doing is simply using a bits of a variable as a flag for each line....
] |
[Question]
[
Yesterday I asked [this](https://codegolf.stackexchange.com/q/152281/56656) question about riffle shuffles. It seems that yesterdays question was a bit too hard so this question is a related but much easier task.
Today you are asked to determine if a permutation is in fact a riffle shuffle. Our definition of riffle shuffle is adapted from our last question:
The first part of the shuffle is the divide. In the divide partition the deck of cards in two. The two subsections must be continuous, mutually exclusive and exhaustive. In the real world want to make your partition as close to even as possible, however in this challenge this is not a consideration, all partitions including ones that are degenerate (one partition is empty) are of equal consideration.
After they have been partitioned, the cards are spliced together in such a way that cards maintain their relative order *within the partition they are a member of*. For example, if card **A** is before card **B** in the deck and cards **A** and **B** are in the same partition, card **A** must be before card **B** in the final result, even if the number of cards between them has increased. If **A** and **B** are in different partitions, they can be in any order, regardless of their starting order, in the final result.
Each riffle shuffle can then be viewed as a permutation of the original deck of cards. For example the permutation
```
1,2,3 -> 1,3,2
```
is a riffle shuffle. If you split the deck like so
```
1, 2 | 3
```
we see that every card in `1,3,2` has the same relative order to every other card in it's partition. `2` is still after `1`.
On the other hand the following permutation is *not* a riffle shuffle.
```
1,2,3 -> 3,2,1
```
We can see this because for all the two (non-trivial) partitions
```
1, 2 | 3
1 | 2, 3
```
there is a pair of cards that do not maintain their relative orderings. In the first partition `1` and `2` change their ordering, while in the second partition `2` and `3` change their ordering.
## Task
Given a permutation via any reasonable method, determine if it represents a valid riffle shuffle. You should output two distinct constant values one for "Yes, this is a riffle shuffle" and one for "No, this is not a riffle shuffle".
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better.
## Test Cases
```
1,3,2 -> True
3,2,1 -> False
3,1,2,4 -> True
2,3,4,1 -> True
4,3,2,1 -> False
1,2,3,4,5 -> True
1,2,5,4,3 -> False
5,1,4,2,3 -> False
3,1,4,2,5 -> True
2,3,6,1,4,5 -> False
```
[Answer]
# JavaScript (ES6), 47 bytes
Takes input as an array of integers. Returns a boolean.
```
([x,...a],y)=>a.every(z=>z+~x?y?z==++y:y=z:++x)
```
### Test cases
```
let f =
([x,...a],y)=>a.every(z=>z+~x?y?z==++y:y=z:++x)
;[
[1,3,2 ], // -> True
[3,2,1 ], // -> False
[3,1,2,4 ], // -> True
[2,3,4,1 ], // -> True
[4,3,2,1 ], // -> False
[1,2,3,4,5 ], // -> True
[1,2,5,4,3 ], // -> False
[3,1,4,2,5 ], // -> True
[2,3,6,1,4,5] // -> False
]
.forEach(a => console.log(JSON.stringify(a) + ' -> ' + f(a)))
```
### How?
The input array **A** is a valid riffle shuffle if it consists of at most two distinct interlaced sequences of consecutive integers.
The challenge rules specify that we're given a *permutation* of **[1...N]**. So we don't need to additionally check that the sorted union of these sequences actually results in such a range.
We use a counter **x** initialized to **A[0]** and a counter **y** initially undefined.
For each entry **z** in **A**, starting with the 2nd one:
* We check whether **z** is equal to either **x+1** or **y+1**. If yes, we increment the corresponding counter.
* Else: if **y** is still undefined, we initialize it to **z**.
* Else: we make the test fail.
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
n%h=n+0^(n-h)^2
f l=elem(foldl(%)0$l++l)l
```
[Try it online!](https://tio.run/##PY5BCsMgEEX3OcUsEjBowUS79CRiQKjB0NGGtPe31qGuZt78x2eifz8DYil5iiZzubF8i/O2DjugCRgS21/4QDbNckTOccaCxlopYBWwOGF/Q4CkTTZQFZYmKEoU2QTkUKg768ZrZd1qFFm9llj35vv/qp0bkj8yGIDzOvIHRkj@hPp/@QI "Haskell – Try It Online")
Checks if the list concatenated to itself contains the numbers `0..n-1` in order as a subsequence.
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
`s` takes a list of integers as in the OP examples and returns a `Bool`.
```
s p=or[f(<x)p++f(>=x)p<[1..]|x<-p]
f=filter
```
[Try it online!](https://tio.run/##NY1BDoMgEEX3noI0XUBAEhR34kUoC9JCJEUlYlMXvTsdTbuZefnvT2a0@eliLJMNswrz5lZ7366vOYbZZT7ZhG@pHhKlF1QP6EJpHpc3znh19oESIYSfzZJRUsuqPe53Am2PBwXQa8G5@ex9nUzllQ8RHpSiBWtZYyoNk4lzCyAJ1ICRZybZ3x7uSLsfd8AtcAdX8nCm@gI "Haskell – Try It Online")
# How it works
* The list comprehension tries each element `x` of `p` in turn and checks if it can be the first element of the second partition of the shuffle. Then `or` returns `True` if any of the checks were `True`.
* The comprehension does this by partitioning (with `filter`) `p` into elements smaller and larger than (or equal to) `x`, concatenating, and checking if the resulting list is `[1..length p]`, i.e. the elements in order.
* The check for whether the resulting list is `[1..length p]` is done by seeing if the result is strictly smaller than the infinite list `[1..] == [1,2,3,etc.]`, which gives the same result for any permutation.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 6 bytes
```
ỤIṢḊRẠ
```
[Try it online!](https://tio.run/##y0rNyan8///h7iWeD3cuerijK@jhrgX/D7c/aloT@f9/dLShjoKxjoJRrA6XQjSIoaNgCGMbgrkmYK4RWJkJTNYEogvGhaiEKDBFEjEFixiDRUzBBppAVCJZARExRbLFDCZuGhsLAA "Jelly – Try It Online")
### Alternate version, postdates challenge, 5 bytes
```
Ụ>ƝSỊ
```
[Try it online!](https://tio.run/##y0rNyan8///h7iV2x@YGP9zd9f9w@6OmNZH//0dHG@ooGOsoGMXqcClEgxg6CoYwtiGYawLmGoGVmcBkTSC6YFyISogCUyQRU7CIMVjEFGygCUQlkhUQEVMkW8xg4qaxsQA "Jelly – Try It Online")
### How it works
```
ỤIṢḊRẠ Main link. Argument: A (permutation of [1, ..., n])
Ụ Grade up; sort the indices of A by their respective values.
For shuffles, the result is the concatenation of up to two increasing
sequences of indices.
I Compute the forward differences.
In a shuffle, only one difference may be negative.
Ṣ Sort the differences.
Ḋ Dequeue; remove the first (smallest) difference.
R Range; map each k to [1, ..., k].
This yields an empty array for non-positive values of k.
Ạ All; check if all resulting ranges are non-empty.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
l=input()
n=0
for x in l*2:n+=n==x
l[n]
```
[Try it online!](https://tio.run/##TYw9C8MgEEB3f8WRqR8ZjNol4NhC924hQ0ksEeQUa6j59WlUGjrdvbvHc0uYLLJ1sKOSVVWtRmp0czgcCUpKXtZDBI1gTqzFs0QpIzEd9uvmks@kjYKHn1VLAIJf0gBQUQ2Qgpmc1xjg9jTvxCoOygW446ji1Xvr2z8pldaO1sBqaHrSpVEDLRvNwDdossDLhxe7QHHKU@wsMrONRc7wYu3ZwmIvX35X0X8B "Python 2 – Try It Online")
Takes the list 0-indexed and outputs via exit code.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
o~cĊ⟨⊆⊇⟩?
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlWpArLTEnOJUpdqHWyeU/8@vSz7S9Wj@ikddbY@62h/NX2n//390tKGOsY5RrE40kNQxBNOGQJYJkGUElDEBi5nowGRBciBRUyjbFMg2BrJNgbpMQHJQE0BsU6gZZmC@aWwsAA "Brachylog – Try It Online")
The predicate succeeds if the input represents a riffle shuffle and fails if it does not, meaning among other things that if the predicate is run as an entire program success will print `true.` and failure will print `false.`. Input is taken as a list of any sorts of items and interprets it as representing a permutation of itself sorted.
```
Ċ Some length-two list
~c which concatenated
o is the input sorted
⟨ satisfies the condition that its first element
⊆ is an ordered not-necessarily-contiguous sublist
? of the input
⊇ which is an ordered superlist of
⟩ the list's second element.
```
I feel like there's something in the spirit of `⊆ᵐ` which should work in the place of the four-byte "sandwich" construct `⟨⊆⊇⟩`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~75~~ ~~60~~ 47 bytes
thanks to Dennis for -13 bytes
```
x={0}
for v in input():x=x-{v-1}|{v}
len(x)<3>q
```
[Try it online!](https://tio.run/##TYzNDoIwEITvfYoNJ0lqIj/1QMSbHvXizXhAXCMRaa0Fa5Bnxy3BaNJ0v9mZHfUyF1mFfS5PmHqe19u0nXXsLDU0UFT0VG0mfmJTO22badC926ZjJVYT6y@i5b2nG/a8FCXCTteYMACjX24AoMUcXPGglC4qA@usfDiNNkdlYJPdcKW11MlfxhX9Iqvt@i9x1Jhd@33AIx4e2J5@HgwzIIqJQnLiYRfzr@s8txUjC@KIWNBV7LyxwbEYO@aDFocP "Python 2 – Try It Online")
Output is via exit code.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->l{l.any?{|a|l&[*1..a]|l==l.sort}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkcvMa/SvromsSZHLVrLUE8vMbYmx9Y2R684v6iktvZ/QWlJsUJadLShjrGOUWwsF4wP5OkYovANgSImSCJGQB0mKGpMdNB1gfSAVJmiiZkCxYyRxEyBppuA1KLZCBIzRbPTDCwOFP0PAA "Ruby – Try It Online")
## How?
* `l & [*1..a] | l` applies an intersection and then an union: first get the elements of `l` that are `<=a` and then add the remaining elements of `l` without changing the order. If a is the number we are looking for, then this operation is the same as sorting `l`.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~56~~ 55 bytes
```
import StdEnv
?l=any(\e=sortBy(\a b=a<e&&b>=e)l<[1..])l
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4zLPsc2Ma9SIybVthgo6gRkJSok2SbapKqpJdnZpmrm2EQb6unFaub8Dy5JBGqzVbCPNtIx1jHTMdQx0TGN/f8vOS0nMb34v66nz3@XyrzE3MzkYgA "Clean – Try It Online")
[Answer]
## Pyth, 5 bytes
```
}SQy+
```
**[Test suite](https://pyth.herokuapp.com/?code=%7DSQy%2B&test_suite=1&test_suite_input=%5B1%2C3%2C2%5D%0A%5B3%2C2%2C1%5D%0A%5B3%2C1%2C2%2C4%5D%0A%5B2%2C3%2C4%2C1%5D%0A%5B4%2C3%2C2%2C1%5D%0A%5B1%2C2%2C3%2C4%2C5%5D%0A%5B1%2C2%2C5%2C4%2C3%5D%0A%5B5%2C1%2C4%2C2%2C3%5D%0A%5B3%2C1%2C4%2C2%2C5%5D%0A%5B2%2C3%2C6%2C1%2C4%2C5%5D&debug=1)**
```
}SQy+
+QQ concatenated two copies of the (implicit) input
y all subsequences of it
} contain an element equaling
SQ the input list sorted
```
Checks whether the doubled input list contains a sorted version of itself as a subsequence.
Thanks to Erik the Outgolfer for 1 byte taking better advantage of implicit input with `+QQ` rather than `*2Q`.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 9 bytes
```
!t-.+xLQS
```
**[Test suite.](https://pyth.herokuapp.com/?code=%21t-.%2BxLQS&test_suite=1&test_suite_input=%5B1%2C3%2C2%5D%0A%5B3%2C2%2C1%5D%0A%5B3%2C1%2C2%2C4%5D%0A%5B2%2C3%2C4%2C1%5D%0A%5B4%2C3%2C2%2C1%5D%0A%5B1%2C2%2C3%2C4%2C5%5D%0A%5B1%2C2%2C5%2C4%2C3%5D%0A%5B5%2C1%2C4%2C2%2C3%5D%0A%5B3%2C1%2C4%2C2%2C5%5D%0A%5B2%2C3%2C6%2C1%2C4%2C5%5D&debug=0)**
Saved 3 bytes thanks to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg).
# [Pyth](https://pyth.readthedocs.io), 14 bytes
```
}SQm.nS.Tcd2./
```
**[Try it here!](https://pyth.herokuapp.com/?code=%7DSQm.nS.Tcd2.%2F&input=%5B2%2C3%2C6%2C1%2C4%2C5%5D&debug=0)** or **[Verify all the test cases.](https://pyth.herokuapp.com/?code=%7DSQm.nS.Tcd2.%2F&test_suite=1&test_suite_input=%5B1%2C3%2C2%5D%0A%5B3%2C2%2C1%5D%0A%5B3%2C1%2C2%2C4%5D%0A%5B2%2C3%2C4%2C1%5D%0A%5B4%2C3%2C2%2C1%5D%0A%5B1%2C2%2C3%2C4%2C5%5D%0A%5B1%2C2%2C5%2C4%2C3%5D%0A%5B5%2C1%2C4%2C2%2C3%5D%0A%5B3%2C1%2C4%2C2%2C5%5D%0A%5B2%2C3%2C6%2C1%2C4%2C5%5D&debug=0)**
Outputs `True` and `False` for riffle-shuffle and non-riffle-shuffle respectively.
### How?
```
}SQm.nS.Tcd2./ ~ Full program. Reads input from STDIN and outputs to STDOUT.
./ ~ Return all divisions of the input into disjoint substrings (partition).
m ~ Map over the above using a variable d.
cd2 ~ Chop d into two-element lists.
.T ~ Justified transpose, ignoring absences.
S ~ Sort (lexicographically).
.n ~ Deep-flatten.
} ~ Check if the above contains...
SQ ~ The sorted input.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
±§#OoṖD
```
**[Test suite!](https://tio.run/##yygtzv6f@6ip8f@hjYeWK/vnP9w5zeX////R0YY6xjpGsTrRQFLHEEwbAlkmQJYRUMYELGaiA5MFyYFETaFsUyDbGMg2BeoyAclBTQCxTaFmmIH5prGxAA "Husk – Try It Online")**
[Answer]
# Perl, 28 bytes
Includes `+1` for `a`
Input on STDIN, 1 based
```
perl -aE '$.+=$_==$.for@F,@F;say$.>@F' <<< "3 1 2 4"
```
Uses [xnor's algorithm](https://codegolf.stackexchange.com/a/152432/51507)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 61 bytes
```
a,b,B;f(int*A){for(a=b=B=1;*A;A++)a-*A?B*=*A>b,b=*A:++a;b=B;}
```
[Try it online!](https://tio.run/##jdC9CsIwFIbhWa9CCkJ@TqGpqUNDlPQ21CGpRDpYpbiVXnvMKYigHTJlefLmI21@a9sQLDholCdd/2KGjv4xEKudbrRQzCjDObU5M8eGaWYODlw8as6tikRN4W67ntBxvXoOMeBJJjZ1vdlez30GnmD0dKGjgB2UUEyUqq8sliQ68SvFshTRyiRbxvflf3dxgYT0DbgAy1VSGXUF2E/RVdwg537qb8i5n9LG6n6@8fFTeAM "C (gcc) – Try It Online")
] |
[Question]
[
**In:** a string without line breaks\*
**Allow the user to edit and submit the line**
**Out:** the modified string (optionally with a trailing linebreak)
The line editor must at minimum allow the user to:
1. move a visible cursor left and right
2. insert and/or overwrite characters at the cursor position
3. remove characters at the cursor position
4. submit the new string, i.e. cease editing cause the modified string to be returned/printed/displayed/saved… (with no other text)
Appreciated, but not required:
* explanation of your code.
* link to an online testing site that can demonstrate your program/function
* an animated image demonstrating usage (TIO, for instance, does not allow interactivity)
Note:
* key-bindings are suggestions only
* GUI or visual styling is not required
### Examples
In the following, the cursor is illustrated with `_`.
**In:** `Just some text`
**Allow the user to edit:**
``Just some text_`` User presses `←` (left arrow key) nine times
``Just ̲some text`` User presses **`Del`** four times
``Just ̲ text`` User presses **`a``n``y`**
``Just any_text`` User presses **`Enter`**
**Out:** `Just any text`
**In:** `Remove me`
**Allow the user to edit:**
---
\* To prevent trivial editor solutions, this must either be supplied via a different input method than the editing commands, or must be separated from them by a newline or similar.
[Answer]
# JavaScript (ES6), ~~15~~ 14 bytes
I don't understand why this is getting so many upvotes!
```
s=>prompt(s,s)
```
Saved a byte thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m)'s suggestion that I display the original input in the `prompt`.
---
## Try It
```
f=
s=>prompt(s,s)
console.log(f("Edit this ..."))
```
[Answer]
# Bash 4.x, 25 characters
```
read -ei "$*" t
echo "$t"
```
Sample run:
```
bash-4.3$ bash interactive.sh hello world
hello golfing world
hello golfing world
```
(Line 2 above was the interactive editing, line 3 the output of resulted text.)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 5 bytes
```
⍞←⍞⋄⍞
```
This is a tradfn, so to use it, do
```
∇a
⍞←⍞⋄⍞
∇
```
And then call it by using `a`, after which you supply the starting string, and then you can edit the string.
[Answer]
# C + NCURSES, 573 bytes
```
#include <curses.h>
i;j;k;s;c;p;int main(a,b)char**b;{char*q;char t[999];if(a&&(q=b[1]))while(*q)t[s++]=*q++;i=s;initscr();noecho();keypad(stdscr,1);do{for(j=0;j<i;j++)addch(t[j]);addch('|');for(j=i;t[j];j++)addch(t[j]);c=getch();switch(c){case KEY_LEFT:if(i)i--;break;case KEY_RIGHT:if(i<s)i++;break;case 8:case 127:case KEY_BACKSPACE:if(i){for(k=i-1;k<s;k++)t[k]=t[k+1];i--;s--;}break;case KEY_DC:if(i<s){for(k=i;k<s;k++)t[k]=t[k+1];s--;}break;default:if(c>31&c<127){for(k=s;k>i;k--)t[k]=t[k-1];t[i]=c;i++;s++;}}clear();}while(c!=10);printw(t);getch();endwin();return 0;}
```
**Test**
* Compile & Run with input `Just some text`.
[](https://i.stack.imgur.com/upjX5m.png)
[](https://i.stack.imgur.com/Sdrhgt.png)
* Press Left-Arrow button nine times.
[](https://i.stack.imgur.com/YqJCnt.png)
* Press Delete button four times.
[](https://i.stack.imgur.com/ynZ6Wt.png)
* Press `a` then `n` then `y`.
[](https://i.stack.imgur.com/h7CLdt.png)
* Press `Enter` to terminate.
[](https://i.stack.imgur.com/1ERsvt.png)
**Detailed**
```
#include <curses.h>
int main(int argc, char ** argv)
{
char*q = 0;
char t[999] = {0};
int j = 0, k = 0;
int i = 0; // cursor before first char
int s = 0; // current size
int c = 0; // current input
int p = 0;
// copy first command-line argument
if(argc>0 && (q=argv[1]))while(*q)t[s++]=*q++; i=s;
initscr(); // initiate NCURSES
noecho(); // input does not echo on entry
keypad(stdscr,TRUE); // handle all input
do
{
// print current content with cursor
for(j=0;j<i;j++) addch(t[j]);
addch('|'); for(j=i;t[j];j++) addch(t[j]);
// printw("\n\n> key %d pressed",c); // debug
c = getch(); // read next char
switch(c)
{
case KEY_LEFT: // left arrow; cursor left
if(i > 0) i--;
break;
case KEY_RIGHT: // right arrow; cursor right
if(i < s) i++;
break;
case 8: // backspace; remove previous char
case 127:
case KEY_BACKSPACE:
if(i > 0)
{
for(k=i-1; k<s; k++) t[k]=t[k+1];
i--;s--;
}
break;
case KEY_DC: // delete; remove next char
if(i < s)
{
for(k=i; k<s; k++) t[k]=t[k+1];
s--;
}
break;
default: // none of the above
if(c > 31 && c < 127) // printable char
{
for(k=s; k>i; k--) t[k]=t[k-1];
t[i] = c;i++;s++;
}
}
clear(); // clear screen
if(c == 10) break;
}
while(c);
addch('\n');
printw(t); // print final result
getch(); // wait for any input
endwin();
return 0;
}
```
[Answer]
# Bash + Vi/Vim, 14 bytes
```
echo $1>a;vi a
```
`vi` is aliased to `vim` on macOS, I don't know about other OSes.
[Answer]
# HTML + JavaScript (ES6), 77 66 64 bytes
**HTML**
```
<input id=t
```
**JavaScript**
```
onkeyup=e=>e.which-13||alert(t.value);f=a=>t.value=a;
```
Saved 10 bytes thanks to Jörg Hülsermann and 2 bytes thanks to Luke.
```
onkeyup=e=>e.which-13||alert(t.value);f=a=>t.value=a;
f("Remove Me");
```
```
<input id=t>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~275~~ 200 bytes
Not a winner, but here it is:
```
from msvcrt import*
s=list(input())[::-1]
c=i=0
def p(a):print''.join(a)[::-1]
while'\r'!=c:p(s[:i]+['<']+s[i:]);c=getch();x=c!='\b';exec["s[i:i+1-x]=c*x","i=(i-1+2*(c<'\\t'))%-~len(s)"][x*' '>c]
p(s)
```
## Explanation:
It works by reversing the input (with `[::-1]`), and excluding and inserting characters in that reversed input so that the cursor does not have to move. Reverses it again when printing.
## Usage:
[Tab] key to move Right
[Ctrl+C] to move Left
[Backspace] to erase
[Return] to finish editing
Any other key, will be inserted into text
## Example:
Using OP's example
**In:** `Just some text`
``Just some text>``
``Just some> text`` User presses **`Ctrl+C`** five times
``Just > text`` User presses **`Backspace`** four times
``Just any> text`` User presses **`a``n``y`**
``Just any> text`` User presses **`Enter`**
**Out:** `Just any text`
## Inline editor version:
If you want the text to be editted inline, append `,'\r',` at the end of the `print` statement:
```
def p(a):print''.join(a)[::-1],'\r',
```
[Answer]
## VBScript, ~~23~~ 40 bytes
```
MsgBox InputBox("",,Wscript.Arguments(0))
```
[](https://i.stack.imgur.com/pBf9W.png)
[Answer]
# C#, 53 bytes
```
s=>{SendKeys.SendWait(s);return Console.ReadLine();};
```
Where `s` is a string to modify and the output is the new value.
[SendKeys.SendWait](https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.sendwait(v=vs.110).aspx): Sends the given keys to the active application, and then waits for the messages to be processed.
or 74 bytes if we are not in a Windows Forms context:
```
s=>{System.Windows.Forms.SendKeys.SendWait(s);return Console.ReadLine();};
```

[Answer]
## Ruby, ~~9~~ ~~19~~ ~~22~~ 84 bytes
```
->s{r=Readline;r.pre_input_hook=->{r.insert_text s;r.redisplay};r.readline}
```
This creates a Readline pre input hook that inserts the text s and then redisplays. After this, irb gets messed up so make sure to run this from a file. Run as a lambda, it takes the input string as an argument and returns the output string.
```
puts Readline.readline
```
This uses the Readline library to perform line editing. My previous answer only allowed backspaces.
```
puts gets
```
This is really, *really* self explanatory.
Edit: I have been asked for an explanation. This is equivalent to `puts(gets)`. `gets` inputs a string with a line editor. `puts` outputs it.
[Answer]
# PHP + HTML, 26 Bytes
```
<input value=<?=$_GET[0]?>
```
The Browser adds automatically the closing tag
[$\_GET](http://php.net/manual/en/reserved.variables.get.php) Using a url like `http://example.com?0=input` as Input
Creates in a HTML `<input value=input`
And this is the output for the string input
```
<input value=input
```
[Answer]
# Tcl, 17
```
puts [gets stdin]
```
Online interpreters just suck to demonstrate it, then I showcase some images from a Windows command shell:
# Test case 1

# Test case 2
[](https://i.stack.imgur.com/iLC2p.png) 
[Answer]
# [AHK](https://autohotkey.com/), 32 bytes
```
InputBox,s,,,,,,,,,,%1%
Send,%s%
```
`InputBox` stores whatever is typed as the variable `s` and gives a starting prompt of the variable `1` which is the first passed parameter.
`Send` sends keystrokes to the current window. In this case, it'll be the contents of `s`.
`MsgBox` was an option but, for golfing, `Send` is 2 bytes shorter.
[](https://i.stack.imgur.com/bmm6d.gif)
[Answer]
## Excel VBA Immediate Window Command - 22 bytes
```
[a1]=inputbox(0,,[a1])
```
[](https://i.stack.imgur.com/vNjdQ.png)
[Answer]
# SmileBASIC, 138 bytes
```
DEF E S@L
WAIT
B=BUTTON(1)C=C-(B==4&&C)+(B>7&&C<LEN(S))I$=INKEY$()IF"\u0008"<I$THEN B=I$<"\u000E"S=SUBST$(S,C,B,I$*!B)?S?" "*C;1IF"\u0008"!=I$GOTO@L
END
```
Creates a function `E` with 1 argument and 0 outputs. (Output is displayed in the console)
The escaped characters should be the actual symbols, but they wouldn't show up here.
Controls:
```
Normal keys: Insert a character before the cursor.
Enter: Delete the character at the cursor.
Backspace: Submit.
D-pad left: Move cursor left.
All buttons except up, down, and left on the d-pad: Move cursor right.
```
Inserting/deleting characters is backwards so it's very annoying to use (but should still fulfill the requirements).
```
Just some text
1
'(press right 5 times)
Just some text
1
'(press enter 4 times)
Just text
1
'(press a)
Just a text
1
'(press right)
Just a text
1
'(...)
Just any text
1
'(press backspace)
```
[Answer]
# ZX Spectrum BASIC, 7 bytes
Trivial, included for completeness (`INPUT` and `PRINT` are one byte tokens each).
```
INPUT a$: PRINT a$
```
[Answer]
## Windows command interpreter, 16 bytes
```
set/pa=
echo %a%
```
This is very trivial; the command interpreter is trivially a "line editor".
[Answer]
# Commodore BASIC (C64Mini, C64/128, VIC-20 etc...) 179 tokenized BASIC bytes
This should be typed in business mode (upper/lower case characters)
```
0a$="Just some text":?"{SHIFT+CLR/HOME}"a$"_":fOi=0to1step0:getk$:on-(k$<>"")goS2:goS1:nE
1?"{CTRL+N}{CLR/HOME}"a$"_ ";:return
2ifasc(k$)<>20thena$=a$+k$:on-(asc(k$)=13)goS4:return
3if-(len(a$))thena$=leF(a$,len(a$)-1):goS4:return
4?"{ARROW LEFT}{ARROW LEFT}{ARROW LEFT} ":return
```
Allows basic text editing + delete + new line. Maximum size of `a$` like all strings in Commodore BASIC is 255 characters, so any more than that will crash the program. I will find a way to do > 255 characters if that is necessary.
[](https://i.stack.imgur.com/peD2O.png)
[](https://i.stack.imgur.com/sHfRG.png)
] |
[Question]
[
The challenge here is to accurately depict the flower of life (which is a sacred geometrical figure according to some) in the language of your choice.

The design consists an arrangement of circles and partial circles of radius 1 as shown whose centres arranged on a triangular grid of pitch 1, plus one larger circle of radius 3 surrounding them.
The design can be scaled as you like, but a max error of 2% from mathematically correct is permitted. If using raster graphics, this effectively limits the diameter of the small circles to at least about 100 pixels.
Since this is code-golf, shortest code (bytes) wins.
[Answer]
## Mathematica, ~~177~~ ~~173~~ ~~128~~ ~~124~~ 120 bytes
```
c=Circle;Graphics@{{0,0}~c~3,Rotate[Table[If[-3<x-y<4,c[{√3x,-x+2y}/2,1,Pi/{6,2}]],{x,-3,2},{y,-4,2}],Pi/3#]&~Array~6}
```
[](https://i.stack.imgur.com/1Ybiy.png)
The main idea is to compose the result from six rotated versions of this:
[](https://i.stack.imgur.com/rqH0L.png)
This in turn is a rectangular table of identical circle arcs with two corners cut off. If we remove the shearing and represent each circle center with a `#`, we basically want to distribute the circles in this pattern:
```
####
#####
######
######
#####
####
```
These edges are cut off by imposing the condition `-3 < x-y < 4` on the 2D indices (since the value of `x-y` is constant along diagonals) and the shearing comes from multiplying these `x` and `y` by non-orthogonal basis vectors which span the grid we're looking for.
This particular orientation of the unrotated arcs turns out to be the shortest since both ends of the arc evenly divide `Pi` so that the arc can be expressed as `Pi/{6,2}` (all other arcs would either require and additional minus sign or integers in the numerator).
[Answer]
# OpenSCAD, 228 bytes
```
$fn=99;module o(a=9){difference(){circle(a);circle(a-1);}}function x(n)=9*[sin(n*60),cos(n*60)];module q(g){for(i=[1:6])if(g>0){translate(x(i))union(){o();q(g-1);}}else{intersection(){translate(x(i))o();circle(9);}}}q(2);o(27);
```
The below is a version allowing someone to set parameters r (radius) and w (width of rings).
```
r=1;w=.1;$fn=99;module o(n){difference(){circle(n);circle(n-w);}}function x(n)=(r-w/2)*[sin(n*60),cos(n*60)];module q(g){for(i=[1:6])if(g>0){translate(x(i))union(){o(r);q(g-1);}}else{intersection(){translate(x(i))o(r);circle(r);}}}q(2);o(3*r-w);
```
This version is xactly 246 characters.
Some of this code is technically unnecessary but makes it look more like the picture.
[Answer]
# Mathematica, 263 bytes
Not really competitive with @MartinEnder's submission but I had fun with this nonetheless. I let the petals do a random walk! The petal walks by rotating 60 degrees randomly about one of the endpoints which is also randomly chosen. I test to see if the rotating end of the petal falls outside the large disk, and if so, the rotation goes the other way.
```
c=Circle;a=√3;v={e=0{,},{0,2}};f=RandomChoice;Graphics@{e~c~6,Table[q=f@{1,2};t=f@{p=Pi/3,-p};r=RotationTransform[#,v[[q]]]&;v=r[If[r[t]@v[[-q]]∈e~Disk~6,t,-t]]@v;Translate[Rotate[{c[{1,a},2,p{4,5}],c[{1,-a},2,p{1,2}]},ArcTan@@(#-#2)&@@v,e],v[[2]]],{5^5}]}
```
Here is the subsequent code I used for the animation.
```
Export[NotebookDirectory[]<>"flower.gif", Table[Graphics[Join[{c[e,6]},(List@@%)[[1,2,1;;n-1]],{Thick,Red,(List@@%)[[1,2,n]]}]],{n,1,3^4,1}]]
```
[](https://i.stack.imgur.com/F89fX.gif)
I read somewhere that 2-dimensional random walks must eventually return to the origin. It seems like a few thousand steps guarantee filling the large disk.
[Answer]
## JavaScript (ES6)/SVG, 299 bytes
```
with(document){write(`<svg height=250 width=250><circle${b=` fill=none stroke=black `}cx=125 cy=125 r=120 />`);for(i=0;i<24;i++)write(`<path${b}d=M5,125${`${a=`a60,60,0,0,1,`}40,0`.repeat(i%4+3)+`${a}-40,0`.repeat(i%4+3)} transform=${`rotate(60,125,125)`.repeat(i>>2)}rotate(-60,${i%4*4}5,125) />`)}
```
Works by generating multiple arc pairs of various lengths then rotating them into place.
] |
[Question]
[
>
> This challenge is inspired from [this](https://askubuntu.com/a/699587) answer at the Ask Ubuntu Stack Exchange.
>
>
>
# Intro
Remember the [Windows ME screensaver with the pipes](https://www.youtube.com/watch?v=Uzx9ArZ7MUU)? Time to bring the nostalgia back!
[](https://i.stack.imgur.com/U5PrJ.gif)
# Challenge
You should write a program or function which will output an ASCII representation of the screensaver. In the screensaver there should be a single pipe which will grow in semi-random directions.
The start of the pipe will be randomly placed at any of the borders of the screen and the pipe piece should be perpendicular to the border (corner first-pipes can either be horizontal or vertical). Each tick the pipe will grow in the direction it is facing (horizontal/vertical) at an `80%` chance or take a corner at a `20%` chance.
# Pipe representation
To create the pipe, 6 unicode characters will be used
```
─ \u2500 horizontal pipe
│ \u2502 vertical pipe
┌ \u250C upper left corner pipe
┐ \u2510 upper right corner pipe
└ \u2514 lower left corner pipe
┘ \u2518 lower right corner pipe
```
# Input
The program / function will take 3 values of input, which can be gathered through function parameters or prompted to the user.
* Amount of ticks
* Screen width
* Screen height
### Amount of ticks
For every tick, a piece of pipe will be added to the screen. Pipes will overwrite old pipe pieces if they spawn at the same position.
For example, take a screen of size 3x3
```
ticks == 3
─┐
┘
ticks == 4
─┐
└┘
ticks == 5
│┐
└┘
```
Whenever a pipe exits the screen, as in the last example at 5 ticks, then a new pipe will spawn at a random border. For example:
```
ticks == 6
│┐
└┘
─
```
The new pipe should have a 50% chance of being horizontal or vertical.
### Screen width/height
The screen width and height can be combined into a single value if that's preferrable in your language of choice. The screen width and height will always have a minimum value of 1 and a maximum value of 255. If your language of choice supports a console or output screen which is smaller than a 255x255 grid of characters then you may assume that the width and height will never exceed the boundaries of your console. (Example: Windows 80x25 cmd window)
# Output
The output of your program/function should be printed to the screen, or returned from a function. For every run of your program, a different set of pipes should be generated.
# Test cases
The following test cases are all random examples of valid outputs
```
f(4, 3, 3)
│
─┘
│
f(5, 3, 3)
│
─┘┌
│
f(6, 3, 3)
─│
─┘┌
│
f(7, 3, 3)
──
─┘┌
│
```
Obviously, the more ticks that have occured, the harder it becomes to prove the validity of your program. Hence, posting a gif of your output running will be preferred. If this is not possible, please post a version of your code which includes printing the output. Obviously, this will not count towards your score.
# Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest amount of bytes wins
* Standard loopholes apply
* If you use the unicode pipe characters in your source code, you may count them as a single byte
This is quite a hard challenge that can possibly be solved in many creative ways, you are encouraged to write an answer in a more verbose language even though there are already answers in short esolangs. This will create a catalog of shortest answers per language. Bonus upvotes for fancy coloured gifs ;)
Happy golfing!
Disclaimer: I am aware that Unicode characters aren't ASCII, but in lack of a better name I just call it ASCII art. Suggestions are welcome :)
[Answer]
Nothing says nostalgia quite like...
## QBasic, 332 bytes
```
INPUT t,w,h
RANDOMIZE
CLS
1b=INT(RND*4)
d=b
IF b MOD 2THEN c=(b-1)/2*(w-1)+1:r=1+INT(RND*h)ELSE c=1+INT(RND*w):r=b/2*(h-1)+1
WHILE t
LOCATE r,c
m=(b+d)MOD 4
IF b=d THEN x=8.5*m ELSE x=13*m+(1<((b MOD m*3)+m)MOD 5)
?CHR$(179+x);
r=r-(d-1)MOD 2
c=c-(d-2)MOD 2
b=d
d=(4+d+INT(RND*1.25-.125))MOD 4
t=t-1
IF(r<=h)*(c<=w)*r*c=0GOTO 1
WEND
```
QBasic is the right language for the task because:
* Its encoding includes box drawing characters--no need for Unicode
* `LOCATE` allows you to print to any location on the screen, overwriting what was there previously
* Microsoft®
### Specifics
This is golfed QBasic, written and tested on [QB64](http://qb64.net) with autoformatting turned off. If you type/paste it into the actual QBasic IDE, it will add a bunch of spaces and expand `?` into `PRINT`, but it should run exactly the same.
The program inputs three comma-separated values: ticks, width, and height. It then asks for a random-number seed. (If this behavior isn't acceptable, change the second line to `RANDOMIZE TIMER` for +6 bytes.) Finally, it draws the pipes to the screen.
The maximum dimensions that can be entered are 80 (width) by 25 (height). Giving a height of 25 will result in the bottom row getting cut off when QBasic says "Press any key to continue."
### How?
TL;DR: A lot of math.
The current row and column are `r` and `c`; the current direction is `d` and the previous direction is `b`. Direction values 0-3 are down, right, up, left. Arithmetic translates those into the correct step values for `r` and `c`, as well as the correct edge coordinates to start on.
The box drawing characters `│┐└─┘┌` are code points 179, 191, 192, 196, 217, and 218 in QBasic. Those appear pretty random, but it still used fewer characters to generate the numbers with some (pretty convoluted, I'm-not-sure-even-I-understand-it) math than to do a bunch of conditional statements.
The code for changing direction generates a random number between -0.125 and 1.125 and takes its floor. This gives `-1` 10% of the time, `0` 80% of the time, and `1` 10% of the time. We then add this to the current value of `d`, mod 4. Adding 0 keeps the current direction; adding +/-1 makes a turn.
As for control flow, the `WHILE t ... WEND` is the main loop; the section before it, starting with line number `1` (`1b=INT(RND*4)`), restarts the pipe at a random edge. Whenever `r` and `c` are outside the window, we `GOTO 1`.
### Show me the GIF!
Here you go:
[](https://i.stack.imgur.com/Ir5gg.gif)
This was generated by a somewhat ungolfed version with animation, color, and an automatic random seed:
```
INPUT t, w, h
RANDOMIZE TIMER
CLS
restart:
' Calculate an edge to start from
b = INT(RND * 4)
'0: top edge (moving down)
'1: left edge (moving right)
'2: bottom edge (moving up)
'3: right edge (moving left)
d = b
' Calculate column and row for a random point on that edge
IF b MOD 2 THEN
c = (b - 1) / 2 * (w - 1) + 1
r = 1 + INT(RND * h)
ELSE
c = 1 + INT(RND * w)
r = b / 2 * (h - 1) + 1
END IF
COLOR INT(RND * 15) + 1
WHILE t
' Mathemagic to generate the correct box-drawing character
m = (b + d) MOD 4
IF b = d THEN
x = 17 * m / 2
ELSE
x = 13 * m + (1 < ((b MOD m * 3) + m) MOD 5)
END IF
LOCATE r, c
PRINT CHR$(179 + x);
' Update row and column
r = r - (d - 1) MOD 2
c = c - (d - 2) MOD 2
' Generate new direction (10% turn one way, 10% turn the other way,
' 80% go straight)
b = d
d = (4 + d + INT(RND * 1.25 - .125)) MOD 4
' Pause
z = TIMER
WHILE TIMER < z + 0.01
IF z > TIMER THEN z = z - 86400
WEND
t = t - 1
IF r > h OR c > w OR r = 0 OR c = 0 THEN GOTO restart
WEND
```
[Answer]
# JavaScript (ES6), 264 ~~266 274 281~~
```
(t,w,h,r=n=>Math.random()*n|0,g=[...Array(h)].map(x=>Array(w).fill` `))=>((y=>{for(x=y;t--;d&1?y+=d-2:x+=d-1)x<w&y<h&&~x*~y?0:(d=r(4))&1?x=r(w,y=d&2?0:h-1):y=r(h,x=d?0:w-1),e=d,d=r(5)?d:2*r(2)-~d&3,g[y][x]="─└ ┌┐│┌ ┘─┐┘ └│"[e*4|d]})(w),g.map(x=>x.join``).join`
`)
```
Counting unicode drawing characters as 1 byte each. (As specified by OP)
*Less golfed*
```
(t,w,h)=>{
r=n=>Math.random()*n|0; // integer range random function
g=[...Array(h)].map(x=>Array(w).fill(' ')); // display grid
for (x=y=w;t--;)
x<w & y<h && ~x*~y||( // if passed boundary
d = r(4), // select random direction
d & 1? (x=r(w), y=d&2?0:h-1) : (y=r(h), x=d?0:w-1) // choose start position
),
e=d, d=r(5)?d:2*r(2)-~d&3, // change direction 20% of times
g[y][x]="─└ ┌┐│┌ ┘─┐┘ └│"[e*4|d], // use char based on current+prev direction
d&1 ? y+=d-2 : x+=d-1 // change x,y position based on direction
return g.map(x=>x.join``).join`\n`
}
```
**Animated test**
Note: trying to keep the animation time under 30 sec,more thicks make animation pace faster
```
f=(t,w,h,r=n=>Math.random()*n|0,g=[...Array(h)].map(x=>Array(w).fill` `))=>
{
z=[]
for(x=y=w;t--;d&1?y+=d-2:x+=d-1)
x<w&y<h&&~x*~y?0:(d=r(4))&1?x=r(w,y=d&2?0:h-1):y=r(h,x=d?0:w-1),
e=d,d=r(5)?d:2*r(2)-~d&3,g[y][x]="─└ ┌┐│┌ ┘─┐┘ └│"[e*4|d],
z.push(g.map(x=>x.join``).join`\n`)
return z
}
function go() {
B.disabled=true
var [t,w,h]=I.value.match(/\d+/g)
var r=f(+t,+w,+h)
O.style.width = w+'ch';
var step=0
var animate =_=>{
S.textContent = step
var frame= r[step++]
if (frame) O.textContent = frame,setTimeout(animate, 30000/t);
else B.disabled=false
}
animate()
}
go()
```
```
#O { border: 1px solid #000 }
```
```
Input - ticks,width,height
<input value='600,70,10' id=I><button id=B onclick='go()'>GO</button>
<span id=S></span>
<pre id=O></pre>
```
[Answer]
### Python 2.7, ~~624~~ ~~616~~ ~~569~~ ~~548~~ 552 bytes
```
from random import*
from time import*
i=randint
z=lambda a,b:dict(zip(a,b))
c={'u':z('lur',u'┐│┌'),'d':z('ldr',u'┘│└'),'l':z('uld',u'└─┌'),'r':z('urd',u'┘─┐')}
m=z('udlr',[[0,-1],[0,1],[-1,0],[1,0]])
def f(e,t,w,h):
seed(e);s=[w*[' ',]for _ in' '*h]
while t>0:
_=i(0,1);x,y=((i(0,w-1),i(0,1)*(h-1)),(i(0,1)*(w-1),i(0,h-1)))[_];o=('du'[y>0],'rl'[x>0])[_]
while t>0:
d=c[o].keys()[i(7,16)//8];s[y][x]=c[o][d];x+=m[d][0];y+=m[d][1];t-=1;sleep(.5);print'\n'.join([''.join(k)for k in s]);o=d
if(x*y<0)+(x>=w)+(y>=h):break
```
The first parameter is a seed, same seeds will generate the same output, printing each step with a 500 ms delay.
* **-10 bytes** thanks to @TuukkaX
[repl it](https://repl.it/Dbai/1)
Example run
```
f(5,6,3,3)
```
will output
```
┐
```
```
─┐
```
```
──┐
```
```
┘─┐
```
```
┐
┘─┐
```
verbose version
```
import random as r
from time import *
char={
'u':{'u':'│','l':'┐','r':'┌'},
'd':{'d':'│','l':'┘','r':'└'},
'l':{'u':'└','d':'┌','l':'─'},
'r':{'u':'┘','d':'┐','r':'─'}
}
move={'u':[0,-1],'d':[0,1],'l':[-1,0],'r':[1,0]}
def f(seed,steps,w,h):
r.seed(seed)
screen=[[' ',]*w for _ in ' '*h]
while steps > 0:
if r.randint(0,1):
x,y=r.randint(0,w-1),r.randint(0,1)*(h-1)
origin='du'[y>0]
else:
x,y=r.randint(0,1)*(w-1),r.randint(0,h-1)
origin = 'rl'[x>0]
while steps > 0:
direction = char[origin].keys()[r.randint(0,2)]
screen[y][x]=char[origin][direction]
x+=move[direction][0]
y+=move[direction][1]
steps-=1
sleep(0.5)
print '\n'.join([''.join(k) for k in screen]),''
if x<0 or y<0 or x>=w or y>=h:
break
origin=direction
```
[Answer]
# C (GCC/linux), 402 353 352 302 300 298 296 288 bytes
```
#define R rand()%
x,y,w,h,r;main(c){srand(time(0));scanf(
"%d%d",&w,&h);for(printf("\e[2J");x%~w*
(y%~h)||(c=R 8,(r=R 4)&1?x=1+R w,y=r&2
?1:h:(y=1+R h,x=r&2?1:w));usleep('??'))
printf("\e[%dm\e[%d;%dH\342\224%c\e[H\n",
30+c,y,x,2*"@J_FHAF__L@HL_JA"[r*4|(r^=R 5
?0:1|R 4)]),x+=--r%2,y+=~-r++%2;}
```
Credit to edc65 for storing the direction in a single 4-bit number.
Reads a width/height on stdin before looping the screensaver forever. E.g.:
```
gcc -w golf.c && echo "25 25" | ./a.out
```
Or for a full-screen screensaver:
```
gcc -w golf.c && resize | sed 's/[^0-9]*//g' | ./a.out
```
For readability I added newlines. Requires a linux machine with a terminal respecting ANSI codes. Has colors! If you remove color support it costs 17 bytes less.
[](https://i.stack.imgur.com/0oHTf.png)
[Answer]
# Ruby, ~~413~~ ~~403~~ 396 bytes

A function that takes a number of ticks and a width as input and returns the final screen as a string. Could no doubt be golfed more.
```
->t,w{k=[-1,0,1,0,-1]
b=(" "*w+$/)*w
f=->t,a=[[0,m=rand(w),2],[w-1,m,0],[m,0,1],[m,w-1,3]].sample{n,m,i=a
d=k[i,2]
q=->n,m,i{_,g,j=rand>0.2?[[1,0],[3,0],[0,1],[2,1]].assoc(i):"021322033132243140251350".chars.map(&:to_i).each_slice(3).select{|c,|c==i}.sample
v,u=k[j||=i,2]
y=n+v
x=m+u
[g,y,x,j]}
g,y,x,j=q[n,m,i]
b[n*w+n+m]="─│┌┐┘└"[g]
y>=0&&y<w&&x>=0&&x<w ?t>1?f[t-1,[y,x,j]]:b:f[t]}
f[t]}
```
See it on repl.it: <https://repl.it/Db5h/4>
In order to see it in action, insert the following after the line that begins `b[n*w+n+m]=`:
```
puts b; sleep 0.2
```
...then assign the lambda to a variable e.g. `pipes=->...` and call it like `pipes[100,20]` (for 100 ticks and a 20x20 screen).
## Ungolfed & explanation
```
# Anonymous function
# t - Number of ticks
# w - Screen width
->t,w{
# The cardinal directions ([y,x] vectors)
# Up = k[0..1], Right = k[1..2] etc.
k = [-1, 0, 1, 0, -1]
# An empty screen as a string
b = (" " * w + $/) * w
# Main tick function (recursive)
# t - The number of ticks remaining
# a - The current position and vector index; if not given is generated randomly
f = ->t,a=[[0,m=rand(w),2], [w-1,m,0], [m,0,1], [m,w-1,3]].sample{
# Current row, column, and vector index
n, m, i = a
d = k[i,2] # Get vector by index
# Function to get the next move based on the previous position (n,m) and direction (d)
q = ->n,m,i{
# Choose the next pipe (`g` for glyph) and get the subsequent vector index (j)
_, g, j = (
rand > 0.2 ?
[[1,0], [3,0], [0,1], [2,1]].assoc(i) : # 80% of the time go straight
"021322033132243140251350".chars.map(&:to_i).each_slice(3)
.select{|c,|c==i}.sample
)
# Next vector (`v` for vertical, `u` for horizontal)
# If straight, `j` will be nil so previous index `i` is used
v, u = k[j||=i, 2]
# Calculate next position
y = n + v
x = m + u
# Return next glyph, position and vector index
[g, y, x, j]
}
# Get next glyph, and subsequent position and vector index
g, y, x, j = q[n, m, i]
# Draw the glyph
b[n * w + n + m] = "─│┌┐┘└"[g]
# Check for out-of-bounds
y >= 0 && y < w && x >=0 && x < w ?
# In bounds; check number of ticks remaining
t > 1 ?
f[t-1, [y,x,j]] : # Ticks remain; start next iteration
b : # No more ticks; return final screen
# Out of bounds; repeat tick with new random start position
f[t]
}
f[t]
}
```
] |
[Question]
[
Convert a large int (e. g. 1234567890) into a string containing the usual decimal prefixes k, M, G, T, etc. for kilo, mega, giga, tera, etc. The result shall be groups of three digits, interspersed by the prefixes (e. g. `1G234M567k890`), so that it is easy to glance the order of magnitude of the number without counting the digits.
It shall work for numbers of all digit counts up to 15. Only non-negative numbers are allowed as input.
More test cases:
```
0 → 0
123 → 123
1234 → 1k234
1000 → 1k000
1000000000 → 1G000M000k000
```
[Answer]
# JavaScript (ES6), 64 bytes
Takes input as a string.
```
f=(n,i=0,[d,t]=n.split(/(...)$/))=>t?f(d,i+1)+['kMGT'[d&&i]]+t:d
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfT1kAnOkWnJNY2T6@4ICezRENfQ09PT1NFX1PT1q7EPk0jRSdT21BTO1o929c9RD06RU0tMzZWu8Qq5X9yfl5xfk6qXk5@ukaahpKhkZKmJheGoDF2URMcwqa4xM1wSphbWBrglQQDoIr/AA "JavaScript (Node.js) – Try It Online")
### How?
The regular expression `/(...)/$` matches the last three digits of the integer, or nothing at all if there are less than 3 digits remaining.
Because there's a capturing group, these digits -- if present -- are included in the output of the `.split()` method.
*Examples:*
```
'123456789'.split(/(...)$/) // --> [ '123456', '789' '' ]
'123'.split(/(...)$/)) // --> [ '', '123' ]
'12'.split(/(...)$/)) // --> [ '12' ]
''.split(/(...)$/)) // --> [ '' ]
```
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
i = 0, // i = index of next prefix
[d, t] = // d = either the leading digits without the last 3 ones,
// or all remaining digits if there are less than 3
n.split(/(...)$/) // t = last three digits (or undefined)
) => //
t ? // if t is defined:
f(d, i + 1) + // append the result of a recursive call with d and i + 1
['kMGT'[d && i]] // append the prefix if d is defined, or an empty string otherwise
+ t // append the last 3 digits
: // else:
d // stop recursion and return the remaining digits
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes
```
R3ô"kMGTP"øSR¦
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yPjwFqVsX/eQAKXDO4KDDi37/9/QyNjE1MzcwtIAzAIA "05AB1E – Try It Online")
Thanks to Kevin Cruijssen for -1 byte
```
R reverse input
3ô split it into groups of 3 digits
"kMGTP" push the prefixes
ø zip the groups of numbers with them
S split to a list of characters
R reverse again
¦ drop the first element
implicitly print
```
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
f=lambda s,p="":s and f(s[:-3],p[1:]+"kMGT")+s[-3:]+p[:1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoVinwFZJyapYITEvRSFNozjaStc4Vqcg2tAqVlsp29c9RElTuzha1xjILYi2Moz9n5ZfpBCvkJmnUJSYl56qYWiqacXFWVCUmVcC1J6ZV1BaoqGp@V/J0EiJC0gYQ0gTKGUKo83gDHMEywKJaYnMNkDhoPHQuRh8TAEDJQA "Python 2 – Try It Online")
Takes input as a string. If the output may have a trailing space, we can avoid some workarounds and save 3 bytes.
**54 bytes**
```
f=lambda s,p=" kMGT":s and f(s[:-3],p[1:])+s[-3:]+p[0]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoVinwFZJIdvXPUTJqlghMS9FIU2jONpK1zhWpyDa0CpWU7s4WtfYKla7INog9n9afpFCvEJmnkJRYl56qoahqaYVF2dBUWZeCVBbZl5BaYmGpuZ/JUMjJS4gYQwhTaCUKYw2gzPMESwLJKYlMtsAhYPGQ@di8DEFDJQA "Python 2 – Try It Online")
One potentially-useful observation is that the string format `'{:,}'.format` puts commas in the places we want to insert letters:
```
'{:,}'.format(1234567) == "1,234,567"
```
However, I haven't found a short enough way to use this.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
```
↔ġ₃;"
kMGT"↔z₀cc↔
```
Input as a string, returns through output the result, with a trailing newline :)
Explanation:
```
More or less a translation of Jelly answer:
↔ Reverse input string
ġ₃ Group into triples, excluding last group with length in range (0,3]
; Pair those groups with:
"
kMGT" A string containing a newline followed by the symbols in reverse order
↔ Reverse the pair so the string comes before the list of digit triplets
z₀ Zip the pair until the smallest list is depleted
cc Concatenate the zipped lists together, then concatenate the strings together
↔ Reverse the result
```
[Try it online](https://tio.run/##SypKTM6ozMlPN/r//1HblCMLHzU1WytxZfu6hygB@VWPmhqSk4GM//@VDI2MTUzNzC0sDZT@h3kGhzr6eAa7uviF@jq5BgEA)
[Answer]
# [Perl 5](https://www.perl.org/) (-p), 40 bytes
```
y/ kMG/kMGT/while s/\d\K((\d{3})+$)/ $1/
```
[Try it online!](https://tio.run/##K0gtyjH9/79SXyHb110fiEP0yzMyc1IVivVjUmK8NTRiUqqNazW1VTT1FVQM9f//NzTiMjQyBmETMGEKIc2glLmFpQESEwz@5ReUZObnFf/XLcgBAA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
**13** if input formatted as a string is acceptable for languages which *can* handle large integers (remove `Ṿ` and quote the argument)
```
ṾṚs3żFtṚʋ“kMGT
```
A full program accepting the non-negative number as a command line argument which prints the result
**[Try it online!](https://tio.run/##y0rNyan8///hzn0Pd84qNj66x60EyDjV/ahhTrave8j///8NjYxNTM3MLSwNwCwA "Jelly – Try It Online")**
### How?
```
ṾṚs3żFtṚʋ“kMGT - Main Link: integer e.g. 12345
Ṿ - un-evaluate the integer ['1', '2', '3', '4', '5']
Ṛ - reverse ['5', '4', '3', '2', '1']
s3 - split into chunks of three [['5', '4', '3'], ['2', '1']]
“kMGT - literal list of characters ['k', 'M', 'G', 'T']
ʋ - last four links as a dyad i.e. f([['5', '4', '3'], ['2', '1']], ['k', 'M', 'G', 'T'])
ż - zip [[['5', '4', '3'], 'k'], [['2', '1'],'M'], ['G'], ['T']]
F - flatten ['5', '4', '3', 'k', '2', '1','M', 'G', 'T']
t - trim (from either side) ['5', '4', '3', 'k', '2', '1']
Ṛ - reverse ['1', '2', 'k', '3', '4', '5']
- implicit (smashing) print 12k345
```
[Answer]
# [PHP](https://php.net/), ~~67~~ 65 bytes
```
for(;''<$d=$argn[-++$i];)$r=$d.' kMGT'[$i%3==1?$i/3:5].$r;echo$r;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKzV1W1UUmxVEovS86J1tbVVMmOtNVWKbFVS9NQVsn3dQ9SjVTJVjW1tDe1VMvWNrUxj9VSKrFOTM/KB1H8QraAUk6dkXZpXnFqioZKpCWMVaVr/NzQy5gJiE1MIaQalzC0sESwDLktU8C@/oCQzP6/4v64bAA "PHP – Try It Online")
Loops on input digits from right to left and concatenates each digit to `$r` variable in reversed order. When we are on 4th, 7th, etc... digit, the respective prefix is concatenated to `$r` as well. Output has a trailing space.
```
for(;''<$d=$argn[-++$i];) // loop on input digits from right to left, $d is current digit and $i is incremental (1, 2, ...)
$r=$d // concatenate current digit to beginning of $r
.' kMGT' // string of prefixes, first item is space for first digit and causes a trailing space in output
[$i%3==1?$i/3:5] // if $i is 1, 4, 7, etc... concatenate letter at index of $i/3 (1/3=0.33, 4/3=1.33, 7/3=2.33, etc...)
// PHP uses integer part of decimal indexes, so 1.33 will return the letter at index 1
// for any other $i, use index 5 which doesn't exist and is equal to an empty string
.$r; // concatenate $r itself to the end, so everything will be in reversed order of reading (which itself is in reversed order of input)
echo$r; // output $r when the loop is finished
```
A schematic example for how an output is created for input of `1234`:
```
| Current Digit | Concatenation | $r |
|---------------|---------------|-------|
| 4 | 4 | 4 |
| 3 | 3 | 34 |
| 2 | 2 | 234 |
| 1 | 1k | 1k234 |
```
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~76~~ 71 bytes
```
procedure f(s)
k:=0
s[i:=*s-2to 2by-3:i]:="kMGT"[k+:=1]&\z
return s
end
```
[Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSFNo1iTK9vK1oCrODrTylarWNeoJF/BKKlS19gqM9bKVinb1z1EKTpb28rWMFYtpoqrKLWktChPoZgrNS8FyZzcxMw8DU0uBQWF8qLMklSNNA0lQyNjE1MzcwtLAyVNVBlLC3N0IaBiqEKQuQA "Icon – Try It Online")
Takes input as a string.
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/), 485 bytes
```
honestly
i lived my life
i faced a boatload of brutal challenges
i desire a day of bliss-i want badly to forget a day where things backfire
i desire a day-i covet a week-and of course i want solitude around everyone
i desire a day-i crave a year-finding no faults i seem to create everyday
i desire a day-i plead,i pray-for an answer i need,i should deserve
fea-r-s,smea-r-s
really,i have a stupid aim
oh world,why was i on earth
o,i suggest venus
o,i deserve a way i go to space
by-by
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?bZFhboMwDIX/cwofoEjdOnXqcQxxSFQTV3ECyuk7h/bXNgmJGN77/OwESaSF2xCB40YO1mYHT1Z7nK1GmAQLCzoQD1OuBRnmgMyUFlLTOdKYyYQO26HhqDpG2DEVmNBxgyLgJS9U3qo9kDlKiGlRk8x3b4RfKCPMsh2Wneg@YjoSzFKzErzxKhxLdWbJUk1AG@VmI/3Dyrj1qhHm0cfkrDcky4WVixpPidYedM6EhV4ks/4lPZjQneydrbSxAJM9ulM2SiLq/zRIZdedlDcaPOGYRz3p@joM1oO5mTC8Ummpj2jLjusgAXbJ7E57sEVhjyYJLHUJg3R0XWzvBTZKVY8v7y59UbbbCIv0OfRh9zdMbZza83r7@jxfbx@Xy/ftfP542q38AA)
Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.
The point of the language is to allow for programs to be written in free-verse poetry. It was fun to write this one (though usually two consecutive ones would be written as 11-letter words; it was hard to golf this poem and make it sound interesting!).
This poem is equivalent to the following brainfuck program, which others are more than welcome to golf:
```
,[>>->,]<<<<<<<<<<[<++>-----]<+++++<<<<<<<<[<+>---]<--------<<<<<<<<[<+>-------]<--<<<<<<<<[<+>---]<-<<<<<<<-[+[<+<<<]>>>-]>[.>[.[+]]>>]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 55 bytes
```
f=(n,i=0)=>n.replace(/.+(?=...)/,d=>f(d,i+1)+'kMGT'[i])
```
[Try it online!](https://tio.run/##BcE7DgIhEADQ0xhmAs4uhRXOWlrZ2RkLwseMEtiA8fr43tv//Ahd9u@xtpjmzAzVCK/IW6We9uJDgoU0XJiIcDGRtwzRiLao1ed2vauHPHHm1kHYmsFKOTmzPTnRGkOro5VEpb0gw9AsB7siuvkH "JavaScript (Node.js) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 85 bytes
```
func[n][p: copy"kMGT"parse reverse n[any[3 skip ahead skip insert(take p)]]reverse n]
```
[Try it online!](https://tio.run/##TYq7CgIxEAD7@4plK@3U85X7AatrxC6kCJcNhsDesskJ9/UREcRqhmGUQrtTsK6LQ4sLT5adlQGmWVbM4@2B4rUQKL3oQ7aeV9tDyUnAP8mHryYupHVTfSaQrXO/3zXRxBUi4P7QH0/ny9XssPuPxhhsbw "Red – Try It Online")
Takes the input as a string.
[Answer]
# APL+WIN, 46 bytes
Prompts for integer as a string
```
∊(n/m),¨(n←3>+/¨' '=¨m←((3/⍳5)⊂¯15↑⎕))/'TGMk '
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6ujSyNPP1dQ5tEIjDyRsp61/aIW6grrtoRW5QL6GhrH@o97NppqPupoOrTc0fdQ2EWiCpqa@eoi7b7aCOtCA9v9pXOqG6lwg0sgYRpvAGaZm5shsC0sDNC6yLriIiak6AA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Gema](http://gema.sourceforge.net/), 88 characters
```
\A=@subst{?=\@push\{p\;?\};TGMk }
*=@reverse{@subst{<d3>=\$p\$1\@pop\{p\};@reverse{$0}}}
```
Boring double reverse approach, but looping in Gema would be painfully long.
Sample run:
```
bash-5.0$ echo -n '1234567890' | gema '\A=@subst{?=\@push\{p\;?\};TGMk };*=@reverse{@subst{<d3>=\$p\$1\@pop\{p\};@reverse{$0}}}'
1G234M567k890
```
[Try it online!](https://tio.run/##S0/NTfz/P8bR1qG4NKm4pNreNsahoLQ4I6a6IMbaPqbWOsTdN1uhlkvL1qEotSy1qDi1GqrSJsXYzjZGpSBGxRCoJb8ApKPWGq5KxaC2tvb/f0MjYxNTM3MLSwMA "Gema – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), [~~65~~](https://tio.run/##ZYvBC4IwFIfv/hXjgbDpk2Yzy3bo2Klbt@gg0kqqJUsvE//2NaEg9Du8Bx@/r0qqR6mvzila3UoTabSsVy9DpU0SyRpT61ZRG4odhBVs/fEPIx3HCOR@2B/hZBfizOTgAj8lz7LWlJE@UBQ4YMpk07VvCsDkqNKlABRzmQFmf5b89CpfbwrAYlrwEcB81vAvk4Z4zKXtjCZcBoP7AA "C (clang) – Try It Online") 62 bytes
```
f(char*n,z){for(;z--;z%3||printf(L" kMGT"+z/3))putchar(*n++);}
```
[Try it online!](https://tio.run/##ZYvRCoIwFEDf/YpxIbhXJ81mluwDeqm3fkCklVRLlr5M/falUBB6Hg/nlHH5KMzVe43lrbCh4Y46/bKoXBwrt5J9X9vKNBqPwO6nwxkit5ZEddtMPYYmikgNPhgb9iwqg8S6QCMI4AmpMXsjAKlJJRsJXC5lCjz9s@ynt9lunwPP54eYAJ4tHvFl9rARe2laa5hQweA/ "C (clang) – Try It Online")
Taking a char array as input.
Saved 3 thanks to @ceilingcat
# [C (clang)](http://clang.llvm.org/), 68 bytes
```
f(n,s){!s|n&&f(n/10,s+1)+printf(s%3?"%d":"%d%c",n%10," kMGT"[s/3]);}
```
[Try it online!](https://tio.run/##S9ZNzknMS///P00jT6dYs1qxuCZPTQ3I0Tc00CnWNtTULijKzCtJ0yhWNbZXUk1RsgISqslKOnmqQAVKCtm@7iFK0cX6xrGa1rX/uYBKFXITM/M0NBWqudI0DHQMNK0LSkuKNZSUNK2BAoZGxliETFDEFKCCpmbmFpYYqg1AAFO9AQygalAAgqLUktKiPAUDa67a/wA "C (clang) – Try It Online")
Taking an int as input
Recursive function which first call itself and outputs after.
```
f(n,s) // Idk if it's acceptable or if I have to wrap with a g(n){f(n,0);}
{
!s| // to allow 0 value calls
n&& // when n=0 exit recursion
f(n/10,s+1)+printf(
s%3?"%d":"%d%c" // select format string
,n%10, // digit to print
" kMGT"[s/3]);} // if second format selected add character
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~81~~ ~~73~~ ~~71~~ ~~69~~ 64 bytes
```
($a=$args)|%{$r=$a[--$i]+' kMGT'[$j+5*!$k]+$r;$j+=$k=!($i%3)}
$r
```
[Try it online!](https://tio.run/##bc/JCsIwEAbge54ilalJbAvuK4XeeurNm4iIxi3FJVUUap@9TuKGYA7D/F9mDnM8XKXONjJNS1jRkOYlh3kIc73OxN3NQWM/CQLYTj1GVRKP2QR2XqfmgJp6oEcYQlChw2HrtkRBQJcFIREnFJ/PWaPJfGqq@EqrbU2Z5oc73V5/ULefMcYEszLwZ8h2zDcyRorREkRlVBBB79SluV2DvQ/ydpSLs1zigTB7qpbZJT0jVPHuaG@xAvzlwUKePlti@B6vkKJ8AA "PowerShell – Try It Online")
Takes argument as a splatted string.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 83 bytes
```
a=('' k M G T)
s=
(($1>99))&&s=${1: -3}
echo `$0 ${1:0:-3} $[$2+1]`${s:-$1}${a[$2]}
```
[Try it online!](https://tio.run/##FcixCoMwFAXQ/X3FHR6aUIQ8XUwgXZ3c3EQwFYPg0CFjyLen9oznE9JVo9K5Bq/aFjdmTFg0JU9Ksbyt1bppkucsDt1Q6DyuL/aIfxj3DHjl/iXbzjm5jqVwDs9spRaiCDGjHYz09Qc "Bash – Try It Online") (link shows 82 bytes, but uses function recursion instead of `$0`-recursion)
Nice little recursive solution.
Bash doesn't like invalid string indexing, which both helps (gives us our exit condition for free) and hurts (we have to have separate logic for when our number has n != 0 mod 3 digits).
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 39 bytes
```
{flip [~] <<''k M G T>>Z~.flip.comb(3)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi0ns0Ahui5WwcZGXT1bwVfBXSHEzi6qTg8koZecn5ukYaxZ@784sVIhTUMlXlMhLb9IwUBHwdDIGEyYAEkDAwMICQEQcVMzcwtLAzDrPwA "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~84~~ 74 bytes
```
i=input();o=""
for x in"kMGT ":o=(i,x+i[-3:])[len(i)>3]+o;i=i[:-3]
print o
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SqmCroK6u/j/TNjOvoLREQ9M631ZJiSstv0ihQiEzTynb1z1EQckq31YjU6dCOzNa19gqVjM6JzVPI1PTzjhWO98aqDPaStc4lqugKDOvRCH/P9A4rtSK1GQNkPGaWoam/5UMjZS4gIQxhDSBUqYw2gzOMEewLJCYlshsAxQOGg@di8HHFDBQAgA "Python 2 – Try It Online")
Previous version for 84 bytes
```
i=input()[::-1];o=""
for x in"kMGT ":o+=(i,i[0:3]+x)[len(i)>3];i=i[3:]
print o[::-1]
```
[Try it online!](https://tio.run/##ZY3LDoIwEEX3/YpmNrSiCVDxUVK3rty5a7rCGiealhBM8OsrBh8Im3vPmWRmqkdz8S4LpT9ZqmgURQEVuureMK6lXKSm8AqAnH1NW4oOrof9kYL0sWI4R51IYeKW65t1DPlOmKJb10IaUtXoGur7I6E7TGxrS/Z6xGdpHiDNgHQh@ly@K//06gvrH20GuB1y8icjG@vEp4MEng "Python 2 – Try It Online")
* ~~Reverse the input~~
* Step ~~through~~ backwards in threes ~~appending~~ prepending the next letter
* ~~Reverse and print~~
Not sure that this is the most efficient approach but it's the best I can come up with at the moment.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 71 bytes
Takes input as number
```
b=(a,l=10e11,x=0,c=a/l|0)=>(l-1)?(c?c+'TGMk'[x]:'')+b(a%l,l/1000,x+1):c
```
[Try it online!](https://tio.run/##fcmxCsIwFEDR3f@QJCS176nVWokdndzcxCEJRdSHESslg/8e6Sgk3vHcmxlM717X57sY6hit5kaRRugQVdCgnDYlfUDoHacCRctd6yQ77g93dgrnhjEhLTdTUlQiAKggUTQuOv/oPXUz8hduOQixnfwSJmieskUSl2mtMrzK@To76vzZ/FkwNv74BQ "JavaScript (V8) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes
```
r`\B...
,$.'$&
T`9630,`TGMk_`,.
```
[Try it online!](https://tio.run/##K0otycxL/P@/KCHGSU9Pj0tHRU9dRY0rJMHSzNhAJyHE3Tc7PkFH7/9/QyNjE1MzcwtLAwA "Retina 0.8.2 – Try It Online") Explanation:
```
r`\B...
```
Match groups of three digits starting from the end but ensure that there is at least one more digit before the match.
```
,$.'$&
```
Prefix each match with a marker comma and the number of digits after the match (`0` for the last match, then `3`, `6` and `9` respectively).
```
T`9630,`TGMk_`,.
```
Replace the marker and following number with the appropriate suffix.
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
f=lambda n,p=' kMGT':(n>M and f(n/M,p[1:])or'')+`n%M+M`[-3:]+p[0]
M=1000
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU@nwFZdIdvXPUTdSiPPzlchMS9FIU0jT99XpyDa0CpWM79IXV1TOyFP1VfbNyFa19gqVrsg2iCWy9fW0MDA4H9BUWZeCVCDoZGxiamZuYWlgeZ/AA "Python 2 – Try It Online")
[Answer]
# Python3, ~~89~~ ~~83 bytes~~ 65 chars
(or 65 bytes, if you use just ASCII, but I fancy the Unicode superscript small letters)
```
f=lambda n,p='ᵏᴹᴳᵀ':len(n)<4 and n or f(n[:-3],p[1:])+p[0]+n[-3:]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIU@nwFb94db@h1t2Ptyy@eHWBnWrnNQ8jTxNGxOFxLwUhTyF/CKFNI28aCtd41idgmhDq1hN7YJog1jtvGhdY6vY/wVFmXklGmka6oZGxiamZuYWlgZglrqm5n8A)
Python3, 89 bytes:
```
import re;print(''.join(sum(zip(re.findall('..?.?',str(x)[::-1]),'kMGT.'),()))[::-1][1:])
```
[Try it online!](https://tio.run/##K6gsycjPM/5foWCrYGhkbGJqZm5haQBm/c/MLcgvKlEoSrUuKMrMK9FQV9fLys/M0yguzdWoyizQKErVS8vMS0nMydFQ19Oz17NX1ykuKdKo0Iy2stI1jNXUUc/2dQ/RU9fU0dDUhApGG1rFav7/DwA)
I didn't try to shorten this dramatically. See it as an incentive to beat me :) This is my first challenge in this forum; by now I understand the asker isn't supposed to post an answer right away. Next time I will wait a little longer before doing it. But since I couldn't really undo the post (deleting the post leaves it visible to too many people anyway), I saw no use in even trying to.
[Answer]
# [Zsh](https://www.zsh.org/), 53 bytes
```
a=kMGT
for z y x (${(Oas::)1})s=$x$y$z$a[i++]$s
<<<$s
```
[Try it online!](https://tio.run/##qyrO@J@moanxP9E229c9hCstv0ihSqFSoUJBQ6Vawz@x2MpK07BWs9hWpUKlUqVKJTE6U1s7VqWYy8bGRqX4vyZXmoKhgYmpgaGBhaWxgaHRfwA "Zsh – Try It Online")
`(s::)` splits the stirng, `Oa` reverses the characters. Zsh arrays and strings are 1-indexed, so `$a[0]` on the first iteration substitutes nothing.
[Answer]
# [Haskell](https://www.haskell.org/), 99 bytes
```
f n=concatMap(\(a,b)->a++b)$reverse$zip(reverse<$>chunksOf 3(reverse$show n))(["","k","M","G","T"])
```
[Try it online!](https://tio.run/##Nci9CsIwFEDh3ae4hAwJrUWtv2A7CS4Wh7qpw21IaWibhiRV8OVjBx0@OJwGXSu7LqjeDNbDCT0mF@V8UppO@VmPSkMGZvSlt8BqWK7S9WKz3e0PPNSgMzFogb5Awx4M44rPc4yiilMrX9I6ST/KsF8faS6aUbfuWkP6n9Q1wxs05@xOSEzaSTE5T27kyUP4Ag "Haskell – Try It Online")
The function `f` takes a number, converts it into a string and splits it backwards into chunks of 3 characters, e.g.
```
reverse<$>chunksOf 3(reverse$show 1234) == ["234","1"]
```
it then zips the list of chunks with the list of magnitue identifieres `["","k","M","G","T"]`.
Then the list is reversed and with `concatMap` converted to one string.
It uses the function `chunksOf` from the package [`Data.List.Split`](https://hackage.haskell.org/package/split-0.2.3.3/docs/Data-List-Split.html)
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 84 bytes
```
: f s" kMGT" bounds <# do
1000 /mod tuck if
0 # # # d. i c@ hold then loop
0 #s #> ;
```
[Try it online!](https://tio.run/##hZLNcoIwFIX3PMUZnQ52HDHaf22d7ly5c9kNkgAZIGFC1OnT2ySCYLWWLHLDPTn3y01iqXQ6SmI7HWZIMEAQBBC494AJIQTjQlLobZSBx0127DLizk1WCRD03fgCK7iGThVjoDzhukKsZFGrnXZKlSxR7cMSqcxpu4ehCFXGlFMpFm1VxUy2ifZcp3VxozBygXmNZDFmsIACoxFCShVyh7ZQ8Nfwl/BX8DOoBd775pyGt0J/gbnd9pdswxIuHMyvVuxTnrPuuV1Mh51DKVayUHu4qBT1kK2W695R21Qx5A5a1P28VvCkudF/w3Cuqu1QDCF3TCH6/Ievavg2citoZQmpdI29SkY@7MPIWbhjxysZ3OYL3JKfOHIpyy7FwV7jVQbv4j16rWvH0VE429aUGFP9XTJEyptMH85Xj0/PL90/pPNdKl/fiIvazOEH "Forth (gforth) – Try It Online")
A function that takes a number from the stack, and returns a string as (address, length) pair, which is the standard representation for a string in Forth. Produces lots of garbage under the returned string, and a few zeros on stdout.
Forth has a [dedicated set of facilities for customized number-to-string formatting](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Formatted-numeric-output.html#Formatted-numeric-output), and this challenge seemed to be the right place to showcase it.
On the golfing perspective, I found that `do .. if .. then loop` (test and ignore the rest of the body) is shorter than `begin .. while .. repeat` (test and break simple loop) or `do .. if leave then .. loop` (test and break counted loop).
### How it works
```
: f ( n -- addr len )
s" kMGT" \ Create a local string "kMGT"; gives its address and length
bounds \ Convert (addr, len) to (addr+8*len, addr)
<# \ Initialize the buffer for number-to-string conversion
do \ Loop; i = addr .. addr+8*len; stack=(n)
1000 /mod \ Calculate n%1000 and n/1000
tuck if \ Stack=(n/1000 n%1000); if n/1000 is nonzero...
0 # # # d. \ emit three digits from n%1000 and discard it
i c@ hold \ emit the next char of "kMGT"
then \ End if
loop \ End loop
0 #s \ Emit all the remaining digits
#> \ Finish conversion; push addr/len of the result string
; \ End function
```
] |
[Question]
[
### 0. DEFINITIONS
A *sequence* is a list of numbers.
A *series* is the sum of a list of numbers.
The set of *natural numbers* contains all "non-negative integers greater than zero".
A *divisor* (in this context) of a natural number *j* is a natural number *i*, such that *j*÷*i* is also a natural number.
### 1. PREAMBLE
A couple of other questions on this site mention the concept of the aliquot, or the sequence of divisors of a natural number *a* which are less than *a*. [Determining amicable numbers](https://codegolf.stackexchange.com/questions/2291/) involves computing the sum of these divisors, called an aliquot sum or aliquot series. Every natural number has its own aliquot sum, although the value of a number's aliquot sum is not necessarily unique to that number. (*Exempli gratia*, every prime number has an aliquot sum of 1.)
### 2. CHALLENGE
Given a natural number `n`, return the `n`th digit of the sequence of aliquot sums. The first several series in the sequence, starting with the series for 1, are:
```
{0, 1, 1, 3, 1, 6, 1, 7, 4, 8, 1, 16, 1, 10, 9, 15, 1, 21, 1, 22, 11, 14, 1, 36, 6, 16, 13}
```
Concatenated, these look like:
```
0113161748116110915121122111413661613
```
Input may be zero-indexed or one-indexed, according to your preference. Solutions must be programs or functions capable of returning the 10,000th digit (input up to `9999` or `10000`). The shortest working solution wins.
### 3. TEST CASES
Correct input-output pairs should include, but are not limited to, the following:
```
0 or 1 -> 0
4 or 5 -> 1
12 or 13 -> 6
9999 or 10000 -> 7
```
The number preceding the "or" is 0-indexed; the number following is 1-indexed.
Additional test cases may be provided upon request.
### 4. REFERENCES
OEIS has a [list](http://oeis.org/A001065/b001065.txt) of numbers and their aliquot sums.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~14~~ ~~11~~ 10 bytes
Compute n = 9999 in about 15 seconds. Code:
```
ÌL€Ñ€¨OJ¹è
```
Explanation:
```
Ì # Increment implicit input by 2
L # Generate the list [1 .. input + 2]
ۄ # For each, get the divisors
۬ # For each, pop the last one out
O # Sum all the arrays in the array
J # Join them all together
¹è # Get the nth element
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w47DjEdOw5HCqE99SsK5w6g&input=MTI).
[Answer]
## Mathematica, 51 bytes
```
Array[##&@@IntegerDigits[Tr@Divisors@#-#]&,#][[#]]&
```
An unnamed function which takes and returns an integer and uses 1-based indexing. Handles input `10000` instantly.
### Explanation
This is a very straight-forward implementation of the definition, making use of the fact that the first `n` divisor sums are always enough to determine the `n`th digit. As usual, the reading order of golfed Mathematica is a bit funny though:
```
Array[...&,#]...&
```
This generates a list with all the results of applying the unnamed function on the left to all the values `i` from `1` to `n` inclusive.
```
...Tr@Divisors@#-#...
```
We start by computing the divisors of `i`, summing them with `Tr` and subtracting `i` itself so that it's just the sum of divisors less than `i`.
```
...IntegerDigits[...]...
```
This turns the result into a list of its decimal digits.
```
##&@@...
```
And this removes the "list" head, so that all the digit lists are automatically concatenated in the result of `Array`. For more details on how `##` works, see the "Sequences of arguments" section [in this post](https://codegolf.stackexchange.com/a/45188/8478).
```
...[[#]]
```
Finally, we select the `n`th digit from the result.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 40 bytes
```
:2-I,?:?:1yrc:Im.;0.
:1e:2f+.
>.>0,?:.%0
```
This is 1-indexed, takes about 0.15 seconds for `N = 100`, 15 seconds for `N = 1000`. I'm currently running for `N = 10000`, I'll report the run time once it ends (If my estimation is correct, it should take about 8 hours)
**Edit**: by fixing premature constraints propagation in Brachylog, it now (on a 3 bytes longer code) takes about `2.5` minutes for `10000` but returns an `out of global stack` error.
### Explanation
* Main Predicate: `Input = N`
```
:2-I, I = N - 2
?:?:1y Find the N first valid outputs of predicate 1 with input N
rc Reverse and concatenate into a single number
:Im. Output is the Ith digit of that number
; Or (I strictly less than 0)
0. Output is 0
```
* Predicate 1: computes the sum of the divisors
```
:1e Get a number between N and 1
:2f Find all valid outputs of predicate 2 with that number as input
+. Output is the sum of those outputs
```
* Predicate 2: unifies output with a divisor of the input
```
>.>0, Output is a number between Input and 0
?:.%0 Input is divisible by Output
```
[Answer]
# Pyth, ~~26~~ ~~21~~ ~~20~~ 15 bytes
```
@sm`sf!%dTtUdSh
```
[Try it online.](http://pyth.herokuapp.com/?code=%40sm%60sf!%25dTtUdSh&input=9999&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=%40sm%60sf!%25dTtUdSh&test_suite=1&test_suite_input=0%0A4%0A12%0A9999&debug=0)
Uses 0-based indexing. The program is O(n²) and completes for *n* = 9999 in about 14 minutes on my 2008 machine.
[Answer]
# Jelly, ~~13~~ ~~11~~ 10 bytes
*2 bytes thanks to @Adnan and 1 more thanks to @Dennis.*
```
ÆDṖSDµ€Fị@
```
[Try it online!](http://jelly.tryitonline.net/#code=w4ZE4bmWU0TCteKCrEbhu4tA&input=&args=MTAwMDA)
Uses 1-based indexing. Completes for *n* = 10000 in under 2 seconds online.
[Answer]
# PHP, 90 bytes
0 indexed
```
<?php for(;strlen($s)<=$a=$argv[1];$s.=$n)for($n=0,$j=++$i;--$j;)$i%$j||$n+=$j;echo$s[$a];
```
Absolutely not subtle or with a clever way of approaching it at all.
Also, as usual, produces three notices which are ignored.
[Answer]
# [J](http://jsoftware.com), 34 bytes
```
{[:;1<@":@(-~>:@#.~/.~&.q:)@+i.@>:
```
This is zero-indexed and uses the formula below to calculate the divisor sums.

## Explanation
```
{[:;1<@":@(-~>:@#.~/.~&.q:)@+i.@>: Input: n
>: Increment n
i.@ Create the range [0, 1, ..., n]
1 + Add one to each to get [1, 2, ..., n+1]
( )@ For each value
q: Get the prime factors
/.~&. For each group of equal prime factors
#.~ Raise the first to the first power, the second
squared and so on, and sum them
>:@ Increment that sum
&.q: Reduce the groups using multiplication
-~ Subtract the initial value from that sum
":@ Convert each to a string
<@ Box each
[:; Unbox each and concatenate the strings
{ Select the character from that string at index n
and return it
```
[Answer]
# [MATL](http://matl.tryitonline.net/#code=OiJAQDohXH5mc0AtVl12Ryk&input=MTM), ~~16~~ 15 bytes
```
:"@@q:\~fsV]vG)
```
Indexing is 1-based.
The last test case times out in the online compiler, but it does give the correct result with the offline compiler, in about 15 seconds.
[**Try it online!**](http://matl.tryitonline.net/#code=OiJAQHE6XH5mc1Zddkcp&input=MTM)
```
: % Take input n. Push [1 2 ... n]
" % For each k in [1 2 ... n]
@ % Push k
@q: % Push [1 2 ... k-1]
\ % Modulo. Zero values correspond to divisors
~f % Indices of zeros. These are the divisors
s % Sum
V % Convert to string
] % End for each
v % Concatenate all stack contents vertically
G) % Take n-th digit. Implicitly display
```
[Answer]
## Haskell, 52 bytes
```
(([1..]>>= \n->show$sum[m|m<-[1..n-1],mod n m<1])!!)
```
Usage example: `(([1..]>>= \n->show$sum[m|m<-[1..n-1],mod n m<1])!!) 12`-> `6`.
It's a direct implementation of the definition: foreach `n` sum it's divisors and convert it into a string. Concatenate all such strings and pick the element at the requested index. Haskell's laziness takes only as much `n`s from the infinite list `[1..]` as needed.
[Answer]
# Python 3.5, ~~103~~ ~~93~~ 92 bytes:
```
R=range;A=lambda f:''.join([str(sum([j for j in R(1,i)if i/j%1==0]))for i in R(1,f+1)])[f-1]
```
Pretty straightforward implementation of method described in post.
[Try It Online! (Ideone)](http://ideone.com/mk7guu)
Does not quite finish within the allotted 5 seconds in the online compiler for input `10000`, but it does finish on my machine for the same input within about 8.5 seconds.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
!ṁödΣhḊN
```
[Try it online!](https://tio.run/##yygtzv7/X/HhzsbD21LOLc54uKPL7////4amAA "Husk – Try It Online")
[Answer]
## Octave, 71 bytes
This one is Octave only. It won't work in MATLAB. A virtual function is created which works on 1-indexed numbers. It can probably be simplified a bit further. Will have a look this evening.
```
@(x)c((c=num2str(arrayfun(@(n)sum(b(~rem(n,b=(1:n-1)))),1:x)))~=' ')(x)
```
You can try online [here](http://octave-online.net/).
Simply run the command above, prefixed with `a=` or whatever (just so that you can use it multiple times), and then do `a(10000)` or whatever. It takes about 7 seconds to calculated that the 10000th digit is a 7.
[Answer]
## Java 8, 220 bytes
```
import java.util.stream.IntStream;
char a(int n){return IntStream.range(1,n+2).map(i->IntStream.range(1,i).filter(k->i%k==0).sum()).mapToObj(Integer::toString).collect(java.util.stream.Collectors.joining("")).charAt(n);}
```
Well, it's fast at least. It averages 0.3 seconds to get the 9999/10000th element on my machine. It generates only as many aliquot sums as the index you specified. This means the string will be slightly longer than your index in most cases, since some aliquot sums have 2 or more digits, but for the most part, it only generates as long of a string as we need.
Usage:
```
public static void main(String[] args) {
System.out.println(a(0));
System.out.println(a(4));
System.out.println(a(12));
System.out.println(a(9999));
}
```
Ungolfed:
```
public static void main(String[] args) {
System.out.println(all(0));
System.out.println(all(4));
System.out.println(all(12));
System.out.println(all(9999));
}
static int aliquotSum(int n) {
return IntStream.range(1, n).filter(k -> n % k == 0).sum();
}
static IntStream sums(int n) {
return IntStream.range(1, n + 2).map(i -> aliquotSum(i));
}
static String arraycat(IntStream a) {
return a.mapToObj(Integer::toString).collect(java.util.stream.Collectors.joining(""));
}
static char all(int index) {
return arraycat(sums(index)).charAt(index);
}
```
] |
[Question]
[
There have of course been challenges to render ASCII art fonts [here](https://codegolf.stackexchange.com/q/99913/72726) and [there](https://codegolf.stackexchange.com/q/80940/72726). This challenge doesn't add anything to those. In contrary, it subtracts from them for a good reason. If you allow all characters,
1. it's a lot of boring work
2. the task is mainly about clever compression of the font and short extraction
This one shall be different, because it is restricted to only five letters to be rendered: `BDIOP`
```
#### # ### #### ####
# # # # # # # # #
#### # # # #### # #
# # # # # # # #
#### # ### # ####
```
Those are obviously chosen for a reason, they share some symmetry, some common elements, but not all of them:
* They are vertically symmetrical, except for the `P`
* The start with a vertical bar, except for the `O`
* The second line is the same, except for the `I`
I think these subtile differences open the field for a lot of possible golfing improvements.
**The input** is a sequence of up to 13 uppercase characters out of those five (put as extended regex `[BDIOP]{,13}`) in a form that fits your language.
**The output** is the ASCII art output of the string with the given 5\*x variable width font, using a whitespace for the background and a character of your choice for the letters, with two whitespaces between the letters. Trailing whitespaces on the lines are allowed, as well as one trailing newline.
**The shortest code** for each language wins.
[Answer]
# JavaScript (ES6), 110 bytes
Expects an array of ASCII codes.
```
a=>[759,4,55,5,757].map(p=>a.map(c=>"# ## ### #### ".substr((p>>c%31%9&3)*5,4>>c-9^5)).join` `).join`
`
```
[Try it online!](https://tio.run/##LU7dCoIwGL3vKT4cxhZzFDpEYoN@brqqeylcS0sxN5z1@kurA@fv6pxGvZXTfW2HqDO30lfCKyHzlGc0oZxTTlOentlTWWyFVN@ghQwQAKBJJkMTEQTMva5u6DG2UuowXoXZPCYLTpOxRtmFE8IaU3cFQPFPs8Jr0znTlqw1d1zhnDEWbA@n4z74rWoQEjTTD9XvxoObAS/JiLX/AA "JavaScript (Node.js) – Try It Online")
Or **[102 bytes](https://tio.run/##JU7dCoIwGH2VsWFsMT8KHSKxQT83XdW9FK6lpZgbznr9pXXg/F2d0@qP9mZo3Bj39l6FWgYtVZGJnKdcCC54JrILvLSjTir9C0YqTBBCZJbZyEyCMPj3zY8DpU4pEyXrKF8kbCl4OtU4vwrGoLVNXyJUsmBs721XQWcftKYFAODd8Xw64P@aQVIhA@aph/10bDvSFZuwCV8)** if we can output an array of strings.
### Method
Only 4 distinct patterns are needed to build all letters. We store them into a single lookup string.
```
0: #...# #...##.....###.####.
1: #.... \___/\___/\___/\___/
2: .###. 0 1 2 3
3: ####.
```
The letters are encoded per row, using 2 bits per pattern. By converting from base 4 to base 10, we eventually get the array `[759, 4, 55, 5, 757]`.
```
2: .###. | 3: ####. | 3: ####. | 1: #.... | 3: ####. -> 23313 -> **759**
0: #...# | 0: #...# | 0: #...# | 1: #.... | 0: #...# -> 00010 -> **4**
0: #...# | 0: #...# | 3: ####. | 1: #.... | 3: ####. -> 00313 -> **55**
0: #...# | 0: #...# | 0: #...# | 1: #.... | 1: #.... -> 00011 -> **5**
2: .###. | 3: ####. | 3: ####. | 1: #.... | 1: #.... -> 23311 -> **757**
```
By reducing each ASCII code modulo \$31\$ and modulo \$9\$, we get the shift amount that must be applied to extract the relevant bits from the above values. (This formula is the reason why the letters are encoded in the order `ODBIP`.)
| Letter | ASCII code | modulo 31 | modulo 9 |
| --- | --- | --- | --- |
| **O** | 79 | 17 | **8** |
| **D** | 68 | 6 | **6** |
| **B** | 66 | 4 | **4** |
| **I** | 73 | 11 | **2** |
| **P** | 80 | 18 | **0** |
Finally, we have to adjust to the correct character width. The expression `4 >> c - 9 ^ 5` used as the 2nd parameter of `substr()` gives \$1\$ for `I` and \$5\$ for all other letters. (The simpler `c - 73 ? 5 : 1` is just as long ... but not as cool. ^^)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•1b§…£U(γ°xāxK²•„# Åв5ô5ôIÇH<è€øJøð«»
```
[Try it online.](https://tio.run/##AVYAqf9vc2FiaWX//@KAojFiwqfigKbCo1UozrPCsHjEgXhLwrLigKLigJ4jIMOF0LI1w7Q1w7RJw4dIPMOo4oKsw7hKw7jDsMKrwrv//0JPRERJUE9QSURPQg)
Just uses `#` and spaces like the challenge description, and has a single trailing column of spaces. Using a different character (`0`) would be the same byte-count, by replacing `„# Åв` with `b1ð:S`:
[try it online](https://tio.run/##AVMArP9vc2FiaWX//@KAojFiwqfigKbCo1UozrPCsHjEgXhLwrLigKJiMcOwOlM1w7Q1w7RJw4dIPMOo4oKsw7hKw7jDsMKrwrv//0JPRERJUE9QSURPQg).
**Explanation:**
```
•1b§…£U(γ°xāxK²• # Push compressed integer 22122550664723003622970748254752
„# # Push string "# "
√Ö–≤ # Convert the large integer to a base-2 list, and index it into "# "
5ô # Split the list of characters into parts of size 5
5ô # Split the list of quintuplets into parts of (up to) size 5 as well
I # Push the input-string
Ç # Convert it to a list of codepoint-integers
H # Convert them from hexadecimal to base-10
< # Decrease each by 1
è # Modular 0-based index each into the earlier list of matrices
€ # Map over each matrix:
√∏ # Zip/transpose; swapping rows/columns
J # Join each inner list together to a string
√∏ # Zip/transpose; swapping rows/columns
ð« # Append a space to each line
» # Join each inner list by a space, and then each string by newlines
# (after which the result is output implicitly)
```
| letter | `Ç` | `H` | `<` | modular 0-based index |
| --- | --- | --- | --- | --- |
| B | 66 | 102 | 101 | 1 |
| D | 68 | 104 | 103 | 3 |
| I | 73 | 115 | 114 | 4 |
| O | 79 | 121 | 120 | 0 |
| P | 80 | 128 | 127 | 2 |
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1b§…£U(γ°xāxK²•` is `22122550664723003622970748254752`.
This number has been generated by [the program in this ASCII-art tip](https://codegolf.stackexchange.com/a/120966/52210) using the transposed flattened rendered letters as input-string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes
```
OD§ị“¡x%ẸȥpFẠẊẓ~ọØ¢’Bs5$⁺¤jØ1z1a⁶Y
```
[Try it online!](https://tio.run/##AVAAr/9qZWxsef//T0TCp@G7i@KAnMKheCXhurjIpXBG4bqg4bqK4bqTfuG7jcOYwqLigJlCczUk4oG6wqRqw5gxejFh4oG2Wf///0JJUE9ET1BJQg "Jelly – Try It Online")
A full program taking a string argument and printing the desired output, using 0 and space to make up the letters. In the end, a simple binary encoding of the five letters was most the shortest I could come up with.
## Explanation
```
O # Convert to codepoints
D # Convert to decimal digits
§ # Sum inner lists
ị ¤ # (Modular) index into the following:
“¡x%ẸȥpFẠẊẓ~ọØ¢’ # - Base-250 integer 22122550664723003622970748254752
B # - ‎⁢Convert to binary
s5$⁺ # - ‎⁣Split into lists of length 5 twice (last one will only have length 1 - corresponds to I)
jØ0 # ‎⁢⁣Join with two ones between each list of lists
z1 # ‎⁢⁤Zip, filling with ones
a⁶ # ‎⁣⁡And with a space (replaces 1 with space)
Y # ‎⁣⁢Join with newlines
üíé
```
# [Jelly](https://github.com/DennisMitchell/jelly), previous version, 35 bytes
```
“¢ḄẸẏ߯¦ṠAi;$ƈƬ’Bs5s5⁽æ£,ḥⱮjØ0z0o⁶Y
```
[Try it online!](https://tio.run/##AVMArP9qZWxsef//4oCcwqLhuIThurjhuo/Dn8W7wqbhuaBBaTskxojGrOKAmUJzNXM14oG9w6bCoyzhuKXisa5qw5gwejBv4oG2Wf///0JJUE9ET1BJQg "Jelly – Try It Online")
A full program taking a string argument and printing the desired output, using 1 and space to make up the letters.
## Explanation
```
“¢ḄẸẏ߯¦ṠAi;$ƈƬ’Bs5s5⁽æ£,ḥⱮjØ0z0o⁶Y­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁣⁡⁡‏⁠‎⁡⁠⁣⁡⁢‏⁠‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁣⁡⁣‏‏​⁡⁠⁡‌­
“¢ḄẸẏ߯¦ṠAi;$ƈƬ’ # ‎⁡Base-250 integer 40155886737228810123461877351903
B # ‎⁢Convert to binary
s5 # ‎⁣Split into lists of length 5
s5 # ‎⁤Split into lists of length 5 (last one will only have length 1 - corresponds to I)
⁽æ£, # ‎⁢⁡Pair 6503 with this
ḥⱮ # ‎⁢⁢Use 6503 as the salt for the Jelly hash function for each of the input letters (will return the first list of lists for B, the second for P, the third for O, the fourth for D and the fifth for I)
jØ0 # ‎⁢⁣Join with two zeros between each list of lists
z0 # ‎⁢⁤Zip, filling with zeros
o⁶ # ‎⁣⁡Or with a space (replaces 0 with space)
Y # ‎⁣⁢Join with newlines
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~41~~ ~~39~~ ~~36~~ ~~35~~ 33 bytes
```
↑ES⟦⪪§⪪”{∨'N4T≕⊞|"³üUr⁸mI”²⁴⊖Σ℅ι⁵
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtEBHwTexQMMzr6C0JLgEKJiuoamjEB1ckJNZouFY4pmXklqhAeEpKSgrKysoKygAaTgBEoMAMBtOwGXAapAJmA4c5ijpKBiZAJ3gkppclJqbmleSmqIRXJqr4V@UkpmXmKORqQkEOgqmmrGamtb//zt5Bvi7/NctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Mainly clever compression of the font and short extraction.
```
S Input string
E Map over letters
”...” Compressed rotated font
⪪ ²⁴ Split into letters
§ Indexed by
ι Current character
‚ÑÖ Ordinal
Σ Digital sum
‚äñ Decremented
⪪ ⁵ Split into columns
‚ü¶ Doubly nest the list
‚Üë Output rotated
```
The mapping of the characters to the font index is as follows (note that the modulo 5 is automatic due to the use of cyclic indexing):
| Character | Ordinal | Digital Sum | Decremented | Modulo 5 |
| --- | --- | --- | --- | --- |
| O | 79 | 16 | 15 | 0 |
| B | 66 | 12 | 11 | 1 |
| P | 80 | 8 | 7 | 2 |
| D | 68 | 14 | 13 | 3 |
| I | 73 | 10 | 9 | 4 |
The nested map would normally result in a list of lists so the extra list wrapper makes a doubly nested list which results in the desired output spacing.
[Answer]
# GNU [sed](https://www.gnu.org/software/sed/) `-E`, 218 bytes
There are only four or five different lines to compose the characters, but seems expensive to use this knowledge in `sed`, so I a column-based approach. First, replace each character by a lower letter representing the type of column, from `a` for `a`ll set to `z` for `z`ero set. The I build row after row, inheriting the type of column. Simple for `a` and `z`, slightly more complicated for `e`very `o`ther row set and really long logical chains for others.
```
s/./a&zz/g
s/^/xy:kl:ghia:zzoe \
fglmnzaawxyzeo#\n_/
s/I//g
s/B/eeo/g
s/P/wwx/g
s/D/ffk/g
s/aO/kffk/g
G
:1
s/_([ #]*\n)(.*)/\1_\2\n/
s/((.)([a-z])\S*(.)\n.*_[ #]*)\2(.*)/\1\4\5\3/
#x;p;x
/.*#\n((.*\n){5})_.*/!b1
s//\1/
```
Who can beat that one with `sed` with a different approach?
[Try it online!](https://tio.run/##LY5BasMwEEX3OkWKoUgCa0jabJxdcSlZ2ZBlJhEKld1gVzK4xYpKrh5FVrN7M7z/Z0b9mbfmN4QRBKhn76ElIxzBXYquL9qvsyq8t3qBpGn7b@OVmtzFa5uhkRDNLaTAG2htE9UwTS5RCU3TJVIVdP/8QYplXEi6X2QHjoZRwRngUuIKzdxHqWB0r3J/YLjjcUAjuEw2w9XDxldc4wuQzG2GjSMgeHwnJufCv/WVScHh6TQfijKEUFdlua2rmx1@ztaMIX@/Aw "sed – Try It Online")
[And easily scalable](https://tio.run/##Pc5BS8MwFAfwez7FpCBJoHlsukt3c@1kpw7cbW@GiGkdncmgStOIX92YxuHtl8f//156/Zq35jOEHgSoW@@hJT08gxuL7ly0bydVeG/1DEnTnt@NV2pwo9c2QyMhJreQCmoPoxoTH0Brm1RF6aQdDINL2kQNSSU0TfdXrqH793pyE/1IinkcSHqYZUeOhlHBGeBc4gLNdJpSwehB5f7I8InHBxrBZUozXFzTeI9LvAOSudVl5QgIHn8em9PCr@U3k4LDzct0KIYhhF1dbuuy2lTr/Y@9fJys6UNe/QI "sed – Try It Online")
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), ~~45~~ 37 bytes
```
OṠv"ᵇVOᶠ4ZG%|∵₁ιf†“b5Ẇ5Ẇ$ið5Y2YjTð∧Ṅṅ
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJP4bmgdlwi4bWHVk/htqA0WkclfOKIteKCgc65ZuKAoOKAnGI14bqGNeG6hiRpw7A1WTJZalTDsOKIp+G5hOG5hSIsIiIsIkJJUE9ET1BJQiIsIjMuMS4wIl0=)
This is a translation of my [Jelly answer](https://codegolf.stackexchange.com/a/266960/42248) to Vyxal 3, mainly as an exercise in learning an alternative language. It’s ~~11~~ 3 bytes longer, partly reflecting my inexperience with the language.
The lost bytes reflect two bytes to manually output as ASCII art rather than a representation of lists, 0-indexing (so one byte for decrementing the index).
*Thanks to @lyxal for saving eight bytes, including by fixing some bugs in the language!*
[Answer]
# APL+WIN, 80 bytes
Prompts for character string. Can be any length:
```
' #'[(5⍴2)⊤∊(¯9+(⊂⎕av)⍳¨('xnnnc' 'xjjjg' 'x' 'gjjjg' 'hmmma')['BDIOP'⍳⎕]),¨⊂0 0]
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv7qCsnq0humj3i1Gmo@6ljzq6NI4tN5SW@NRVxNQZWKZ5qPezYdWaKhX5OXlJasrqFdkZWWlg2ggToeyM3JzcxPVNaPVnVw8/QPUgTqAWmM1dQ6tAJpioGAQ@x9oFdf/NC51oLSLk5Onp6e/f0CAOhcA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Python](https://www.python.org), 118 bytes
```
s=input()
*z,=b"|b|b||bbb|\\bbb\``|b|"
for z[:0]in[[6]]*5:print(*(bin(z[ord(c)%9//2*5])[3:].replace(*'0 ')for c in s))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3y4ptM_MKSks0NLm0qnRsk5RqkoCwJikpqSYmBkjGJCQA-UpcaflFClXRVgaxmXnR0WaxsVqmVgVFmXklGloaSZl5GlXR-UUpGsmaqpb6-kZaprGa0cZWsXpFqQU5icmpGlrqBgrqmiAjkhUy8xSKNTUhtkMdsWBNgKeTi7-_p5O_Z0AARAwA)
Uses spaces and `1`s for output.
Encodes the font in binary. Lookup uses `%9//2` which maps the code points to `0...4`, in particular, sending `I` to `0` which allows us to abuse the simple structure of `I`.
[Answer]
# [Uiua](https://uiua.org) 0.3.1, 62 [bytes](https://codegolf.stackexchange.com/questions/247669/i-want-8-bits-for-every-character/265917#265917)
```
/⊐≡(⊂⊂:" ")⊐≡(+@ ×3⋯)⊏:[±.⍜↘±3.⍜⊙⊡-.2.⊃+∘+14×3¬.⋯17]⊗:"IPBDO"
```
## Explanation
```
Rndr ‚Üê ( # Define a function
‚äó:"IPBDO" # Convert letters to indices
[±.⍜↘±3.⍜⊙⊡-.2.⊃+∘+14×3¬.⋯17] # Encode bit masks for letters as integer arrays
‚äè: # Convert indices to masks
≡(□+@ ×3⋯) # Render each row as a letter,
# box them to accommodate for different width
/⊐≡(⊂⊂:" ") # Join letters together, add spaces between them
# ≡&p # Uncomment to print to stdout
)
Rndr "IDBIPOPD" # Call the function on a value
```
[Try it out!](https://uiua.org/pad?src=0_3_1__Um5kciDihpAgKAogIOKKlzoiSVBCRE8iCiAgW8KxLuKNnOKGmMKxMy7ijZziipniiqEtLjIu4oqDK-KImCsxNMOXM8KsLuKLrzE3XQogIOKKjzoKICDiiaEo4pahK0Agw5cz4ouvKQogIC_iipDiiaEo4oqC4oqCOiIgICIpCiAgIyDiiaEmcCAjIFVuY29tbWVudCB0byBwcmludCB0byBzdGRvdXQKKQpSbmRyICJJREJJUE9QRCIK)
] |
[Question]
[
In this challenge you will write a function that takes a list (ordered set) containing real numbers (the empty list is an exception, as it has nothing) and calculates
$$f(x)=\begin{cases}1 & \text{if } |x|=0 \\ x\_1+1 & \text{if } |x|=1 \\
\log\_{|x|}\sum\_{n=1}^{|x|}{|x|}^{x\_n} & \text{otherwise}
\end{cases}$$
where \$|x|\$ is the length of list \$x\$ and \$x\_n\$ is the \$n^\text{th}\$ item in the list \$x\$ using 1-based indexing. But why is this called “logarithmic ***incrementation***”? Because there is an interesting property of the function:
$$f(\{n,n\})=n+1$$
Amazing, right? Anyways, let’s not go off on a tangent. Just remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! Oh, right, I forgot the legal stuff:
* Standard loopholes apply.
* In a tie, the oldest answer wins.
* Only numbers that your language can handle will be input.
### Test cases:
```
[] -> 1
[157] -> 158
[2,2] -> 3
[1,2,3] -> 3.3347175194727926933796024072445284958617665867248313464392241749...
[1,3,3,7] -> 7.0057883515880885509228954531888253495843595526169049621144740667...
[4,2] -> 4.3219280948873623478703194294893901758648313930245806120547563958...
[3,1,4] -> 4.2867991282182728445287736670302516740729127673749694153124324335...
[0,0,0,0] -> 1
[3.14,-2.718] -> 3.1646617321198729888284171456748891928500222706838871308414469486...
```
Output only needs to be as precise as your language can reasonably do.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~22~~ 15 bytes
Anonymous tacit prefix function implementing $$f(x)=x\_1\cdot\big[1=\lvert x\rvert\big]+\log\_{\lvert x \rvert} \sum\_{n=1}^{\lvert x\rvert}1^{\lvert x\rvert-n}\cdot\lvert x\rvert^{x\_n}$$
```
(⊃×1=≢)+≢⍟1⊥≢*⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NRV/Ph6Ya2jzoXaWoDiUe98w0fdS0FsrQedS36n/aobcKj3j6goke9ax71bjm03vhR28RHfVODg5yBZIiHZ/D/NAWgHFeago6hqTmQMtIxApKGOkY6xmDaGAhB4iZgcWMdQx0TIG2gA4YgET1DEx1dIz1zQwsA "APL (Dyalog Unicode) – Try It Online")
`(`
`⊃` the first element
`×` times
`1=` whether (1) or not (0) one equals
`≢` the length of the argument
`)+` plus
`≢⍟` the length-logarithm of
`1⊥` the sum (lit. the base-one evaluation) of
`≢` the length
`*` raised to the power of (each element in)
`⊢` the argument
### Old solution: [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 22 bytes
Anonymous prefix lambda.
```
{0::1+⊃⍵⋄+/⍢((≢⍵)∘*)⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v9rAyspQ@1FX86PerY@6W7T1H/Uu0tB41LkIyNd81DFDSxPIqP2f9qhtwqPePrC6NY96txxab/yobeKjvqnBQc5AMsTDM/h/mgJQjitNQcfQ1BxIGekYAUlDHSMdYzBtDIQgcROwuLGOoY4JkDbQAUOQiJ6hiY6ukZ65oQUA "APL (Dyalog Extended) – Try It Online")
`{`…`}` "dfn"; argument is `⍵`
`0::` if any error happens:
`1+` increment
`⊃⍵` the first element of the argument
`+/⍢(`…`)⍵` the sum of the argument, under the influence of:
`(`…`)∘*` raising to the power of:
`≢⍵` the tally of elements (length of the argument)
[Answer]
# JavaScript (ES7), 62 bytes
```
a=>a.map(v=>t+=n**v,t=0,n=a.length)&&(L=Math.log)(t)/L(n)||++a
```
[Try it online!](https://tio.run/##ZdBLDsIgEIDhvadwZcBOp4VBqQs8gZ7AuCDa@kiljZKujFevVhOthVnyZf7A2Tb2trueah@7ap@3hWmtWVq82Jo1Zukj46bTBrxJwRmLZe4O/sgnE7Yya@uPWFYHzjxPVszx@z2KbLur3K0q8@6GFWyz5XzcO0kyFqMBETPdVx2ZZUMkQQ4QBXtAAv3QizwIiZQOIb3mG@2gxjQNoyqIPhSSFIshJBCg/tMKZTYPNqbwnl46@A5CoSCWqEXWsc8zxFzp9gk "JavaScript (Node.js) – Try It Online")
### How?
Given the input list \$a\$ and its length \$n\$, we compute:
$$t=\sum\_{i=0}^{n-1}n^{a\_i}$$
We then try to compute \$log\_n(t)=log(t)/log(n)\$.
If the result is `NaN`, we return `++a` instead.
This will happen if:
* \$n=0\$ : we try to compute \$\log(0)/\log(0)\$
* \$n=1\$ : we try to compute \$\log(1)/\log(1) = 0/0\$
This gives the correct answer in both cases because:
* if \$n=0\$, we increment the empty array, which gives \$1\$.
* if \$n=1\$, there's a single atom \$x\$ in \$a\$ which is coerced to a number and incremented.
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
f[]=1
f[x]=1+x
f x|n<-sum$1<$x=logBase n$sum$map(n**)x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py061taQKy26AkhpV3ClKVTU5NnoFpfmqhjaqFTY5uSnOyUWpyrkqYCEchMLNPK0tDQr/ucmZubZFhRl5pWopEUb6xjH/gcA "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 56 bytes
```
f[]=1
f[x]=1+x
f x|n<-sum$x>>[1]=logBase n$sum$map(n**)x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py061taQKy26AkhpV3ClKVTU5NnoFpfmqlTY2UUbxtrm5Kc7JRanKuSpgARzEws08rS0NCv@5yZm5tkWFGXmlaikRRvrGMf@BwA "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 70 bytes
```
f[]=1;f[x]=1+x;f x|let n=fromIntegral$length x=logBase n$sum$map(n**)x
```
[Try it online!](https://tio.run/##DcU7DoAgDADQqzAw@FuMo2Fx8wzEoUOLxlINYNLBu6NveTvkE5lrJb@5cSavf73OZPRlLEYcpSuuUjAkYMsooexGHV9hgYxGbH6ijXA30nWt1giHuDsdUiz5aZi2@gE "Haskell – Try It Online")
[Answer]
# [Python](https://www.python.org) NumPy, 81 bytes
```
lambda l:[sum(l)+1,w(l*(x:=w(l*0)))/x][x>0]
from numpy import*
w=logaddexp.reduce
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NZFNjptAEIWV5XAKxAommHT9dHe1JfsOkbJzvGDGOIOEDcIwts8ym5Gi5C45QnKaFNijRmqq6P7ee8Xb7-46vLTH95_71fdf47BfyN-vTXl42pVxs9ycxkPaZJ8hP6fNY3pZrqbdZFn25bLdXNZmG-379hAfx0N3jetD1_bDY3ReNe2PcrerLl3RV7vxubqDT-eXuqnib_1YLaOHJl7F9bEbhzSLHtI6bzNtNMWpa-ohTRbrRNu1tqrXsklrLdqPolVs15TPVZoURZHkSZLp566vj8PEyfdp2fflVS9l2U36_d-nP5ttvFjHEG3A-turlWiDOc4FaT_HnG5FQcQevIXAHn1AF4h8cAbZeGS2KBysOPDO6aYtISB2TAGRwXNQXxOQdN3EfGGM9SJkVVaMiLVGD0uwbAlEBC1NTCYbrEUHLhgODgGYPRvn_Izku10uCCGgmMAinhyqX_GG1DBqK1Awal_cbCyQGrdiHKCx7K0jFZpxlEPOdyBqkBAABUHQa8Ipple2U65BC85P6fWEd540owsM6h2Z9CE7A00-r49RUwGcL7DwIPfBgmOnc1P3EERpU3LRkQFb5YuEKZU1BhG9cUKaDsjoCWbVE6cqt1_6Hw)
Takes a numpy array for input.
Test harness nicked from @AnttiP.
#### How?
Uses the almost-builtin: `numpy.logaddexp.reduce` Shame it's such a mouthful.
[Answer]
# [R](https://www.r-project.org), ~~50~~ 44 bytes
*Edit: -1 byte thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
\(x,`?`=sum,l=?x|1)`if`(l<2,x?1,log(?l^x,l))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZJdSitBEIXx1VUE7ssMdIb6_wFjNiISECLCiKA3kIe7k_sSBRelm9GaxCRIDzRzqD6nvur-__q8e1sv3jd_1_P4aDfdtq2Wq8XL5rGNi-X2H_arh_WqG6-obZfYxqf7bjnebtvY94cznxdf6-6u6_vZn9n8eoaX0x-qnwSNvUSNjhIfaho1PkkDszi6YoqTJ1kyexqQgJOIUkhqGLpZbSUFI4sJJ5GgSw7D8GPLtU7xPgCoR7BWIwERqlBHIlWUMSJIeXIW1lQlQ0uQNEIUcQEzPxrLGUAGJkwKSIlwNqrew4GreSopOaFQwvZNJheEBhgSqLgaV9zRlBs2OdtSoWUiBWGQF_ME7pVg5Q6kaD7NoyrcnIvaUrA4SLg-1qMttP36fSk8oLQ5DY5xHjuaWE21eDCjnKeJRA0URSsrIidOBSAiBwsuXmSoCpHKDqvEwzvY7Q77Nw)
[Answer]
# Excel, 57 bytes
```
=LET(x,A1#,y,ROWS(x),IF(y-1,LOG(SUM(y^x),y),IFNA(x+1,1)))
```
Input is vertical spilled range `A1#`.
[Answer]
# [Python](https://www.python.org) NumPy, 70 bytes
```
lambda l:math.log(sum(L**l),L)if(L:=len(l))>1else sum(l)+1
import math
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVFLjptAEFWWwykQK5hg1PXp7mpL9jIrL7NzsmASHCM1BmE8I58hR8hmpCi5S46QnCYF9qiRoF5Vv0_x4_dwnY796fXnYfPp12U6rOTvh1h3T1_rNK67ejpWsf-Wny9dvnt8jEW5K9pDvltvYnPKY1FsoYnnJp37sXgPSdsN_Til88U72_fD2Hfp6dIN1_TercexviYvxzY26cfx0qyTh5hu0vY0XKa8SB7ytuwLBWJ1HmI75dlqmyncKtQ81zFvtejfir4amyHWX5o8q6oqK7Os0PYwtqdp5ikP-SKnl4riZun137s_-8_paptCsgfrb59Wkj2WuBSkeIkl3YqKiD14C4E9-oAuEPngDLLxyGxROFhx4J3Tl0JCQOyYAiKD56C-ZkLScxPzlTHWi5BVWTEi1hodlmDZEogIWpo5mWywFh24YDg4BGD2bJzzCyXf7XJFCAHFBBbx5FD9ijekhlGhQMGofXGLsUBq3IpxgMayt45UaKGjEkq-E6IGCQFQEAS9JpxjeuV2ymvQgvNzep3wzpNmdIFBvSOTPmQXQlMu523VVAGXK6w8yH2x4Njp3tQ9BFG2ObnoyoCt8ouEOZU1BhG9cUKaDsjoBLPqiVOV2y_9Dw)
A rather dirty mix which expects a numpy array as input to take advantage of vectorised arithmetic but later uses the log from std lib math because it allows to specify the base.
Test harness from @AnttiP via @loopywalt.
[Answer]
# [Python](https://www.python.org), 85 76 bytes
Essentially by @Albert.Lang
```
lambda l:math.log(sum(map(pow,[L:=len(l[2:])+2]*L,l+l+[0,0])),L)
import math
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NVDLbtswEESP0VcIOpE1TZDLxy4NOF_gY26qD0or1wIoS3DkBPmWXgIUyT-lX9OV5WAvnOHOzO7--Rhfp-Nwevt72P54v0yHNX3uctM__mrKvOmb6ajz8Fs8XXrRN6MYhxdV7zbb3J5ErmGzlyvYf9-pvMqr2iizl1LtZNH143Ceyll-88wvxy635cP50m6Ku1xuy-40XiYhizvRqUEykfXTmLtJVOv7iumOqfa5yaJjMHyBQZ_bMTc_W1FprStVVZK_x3N3mmYfdeB2uWS-_fsm6325vi9tUduAyzNQUYOCK3DMK1BuAdo5jxaDTR4BE8TkHKZowBsE7wNw4CxwXIsZamMCErnAtmSIQjAJgFLwwVkiWiT-Fue1A5uATPJE6CJwHqFxHAhMJZeu7U5Z5W8CoIgpWSCwBAg0j0HI2sg6A-Eq4LvP9bWq09arNWi0dFvMRh-jRU63iRDSPBl5i9aHiDwLuywn-w8)
[Answer]
# [Go](https://go.dev), 160 bytes
```
import."math"
type F=float32
func f(N[]F)F{L,s:=F(len(N)),0.0
if L<1{return 1}
if L<2{return N[0]+1}
for i:=0;i<int(L);i++{s+=Pow(L,N[i])}
return Log(s)/Log(L)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZHNasMwDMfZ1ac9ggkUbKJm-dpa2mbHnEzoPQsjlLgza5ySOB0j5El2CYM9xB5lfZo5acuWooOsnyzxl_TxuS267326eU23Gc5TIZHI90WpLIPnyviqFZ_Of7oLy1P1YiD1vs9wGPBdkSrPRbyWG8xJFCchDRsG1SIIyS6TJKIUbMtGgmO2cpoyU3UpsdOegHsBUWwnpqa8KLFYBPZSrIRUhNGlMM2mMoN18UYYRLFIaIvORazYkore9Y7R9qTzeHM7aOnHIBQ3SNY5E5XCiwDHSZwMgh_8Bv09W_gXOPezUeyCO86DC94V8bSNq_yrKg8c8EfEhsHGvyzHh6lrzZy55i0atvEMeoKql1-mUt_nMk-D1qVeESfG5ICDRzw5PEkD-nQF-hK9p7Rvcl5M1538Lw)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~57~~ 53 bytes
```
->x{k=x.size;k>1?Math::log(x.sum{|c|k**c},k):x.sum+1}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166iOtu2Qq84syrVOtvO0N43sSTDyionP10DKFiaW12TXJOtpZVcq5OtaQUW0Tas/V@gkBYdHRvLBaYNTc1hTCMdI7iojpGOcWzsfwA "Ruby – Try It Online")
[Answer]
# Vyxal, 24 Bytes
```
□L2<[?1+,]□L:ẋ□e∑∆l□L∆l/
```
### My first Vyxal answer!
[Try it online! (List is given as input of numbers separated by newlines. This will not work if there is a trailing or leading newline in the input.)](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLilqFMMjxbPzErLF3ilqFMOuG6i%20KWoWXiiJHiiIZs4pahTOKIhmwvIiwiIiwiMy4xNFxuMi43MTgiXQ==)
If you want the output as a decimal instead of a fraction, use the `ḋ` flag.
If the length is `2` or above, it applies the general formula and implicitly prints the result. If the length is `1` or `0`, it adds `1` to the number. With a list of length `1`, this just increments the number and prints it. With a list of length `0`, it increments it to get `1` and prints it, but then throws an error. Luckily, `STDERR` is ignored by default.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
I⎇Φθκ▷math.log⟦ΣXLθθLθ⟧⊕↨θ¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcrAooy80o0nBOLSzRCUovyEosqNdwyc0pSizQKdRSyNXUUXMsSc8ISizSUchNLMvRy8tOVdBSig0tzNQLyy4GqfFLz0ksyNAqBKgs1gQScHwvkeOYlF6XmpuaVpKZoOCUWp4LMNNAEAeslxUnJxVBXLI9W0i3LUYpdER1tpKNgFBsLEQYA)\*\* Link is to verbose version of code. Explanation: Port of @AnttiP's Python answer.
```
θ Input array
Φ Filtered where
κ Index is not zero
⎇ If still not empty then
θ Input array
L Length
X Vectorised raise to power
θ Input array
Σ Summed
▷math.log⟦ ⟧ Logarithm to base
θ Input array
L Length
θ Otherwise input array
↨ ¹ Summed via "base 1" conversion*
⊕ Incremented
I Cast to string
Implicitly print
```
\*Base 1 conversion returns `0` for an empty list, which `Sum` does not.
\*\*I'm using ATO instead of TIO because the version of Charcoal on TIO incorrectly prints floats whose value is just below that of an integer.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 48 bytes
```
x->if(1<n=#x,log(vecsum(n^x))/log(n),n,x[1]+1,1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LU3dCoIwFH6VYTcbnZlnGnqRvoiskGgi2BqmsZ6lGyGiZ-pt2qZ8cL4_Ps7ra5qhO7VmfitSfqZR8eKXWF51iuJBlxsL_a2lj8v5Pl2pPlrGdj7QDDTYGuUWAdm6Gxpj-ie1hFfEDJ0enYy8iYiibgmkrqU7uM89CRDBgYB0EalDqLKlSgEh8yKBgJDFmAEXcY6FlOvneV74Dw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g©ImO®.n®_+®i+`
```
[Try it online](https://tio.run/##yy9OTMpM/f8//dBKz1z/Q@v08g6ti9c@tC5TO@H//2gTHaNYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL//RDKytz/Q@t08s7tC5e@9C6TO2E/7U6/6OjY3WiDU3NgaSRjhGIrWOkYwymjYEQJG4CFjfWMdQxAdIGOmAIEtEzNNHRNdIzN7SIjQUA).
**Explanation:**
```
g©ImO®.n # Otherwise portion of the formula:
g # Push the length of the (implicit) input-list
© # Store it in variable `®` (without popping)
I # Push the input-list
m # Take the length to the power of each element
O # Sum them together
®.n # Take the base-`®` logarithm of that sum
®_+ # n=0 case of the formula:
®_ # Push length `®` again, and check whether it's 0 (1 if 0; 0 otherwise)
+ # Add that to the value
®i+` # n=1 case of the formula:
®i # If length `®` is 1:
+ # Add the current value to the wrapped value of the input-list
` # And unwrap it by popping and pushing its value to the stack
# (after which the result is output implicitly)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
.x.ls^lQQlQhe+Z
```
[Try it online!](https://tio.run/##K6gsyfj/X69CL6c4LicwMCcwI1U76v//aEMdYyA0jwUA "Pyth – Try It Online")
### Explanation
```
.x.ls^lQQlQhe+ZQ # implicitly add Q
# implicitly assign Q = eval(input())
.x # try:
^lQQ # length(Q) to the power of each element of Q
s # sum all elements
.l lQ # take the log base length Q
# except: (log will error if length is 0 or 1)
+ZQ # prepend 0 to Q
e # take the last element
h # and increment it
```
[Answer]
# [Desmos](https://desmos.com/calculator), 68 67 ~~65~~ 53 Bytes
Thanks to [AidenChow](https://codegolf.stackexchange.com/users/96039/aiden-chow%5D) for -12 Bytes!
```
l=a.length
f(a)=\{l=0,l=1:a[1]+1,\log_l(l^a.\total)\}
```
Now needs a keypress before it works
Without needing keypress (and visible) (~~66~~ 65 Bytes):
-1 from AidenChow
```
f(a)=\left\{l=0,l=1:a[1]+1,log_l(l^a.total)\right\}withl=a.length
```
[Link](https://www.desmos.com/calculator/vwkm9hv9cg)
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 105 bytes
```
[H|T]*L*S:-T*L*N,S is N+L^H,!.
_*0.
A-K:-A=[B],K is B+1,!;length(A,L),L>1,A*L*S,K is log(S)/log(L),!;K=1.
```
[Try it online!](https://tio.run/##JYxNC4JAGITv/oq8rTq7tWoUisF2EpQuehC2LQikBD/Cgi79d9vdGHifYeZlnvPUT3f6@nTLIvNvrfzSrxJaa5xQrbrX6hSUlxwuc67@hjmCFgkVmTwqFKY9Bhxu2rfj/f0gAqWH8sAhzMr/Qa@Tylsb6NJNi4yzxU5IBcm3O31DhMYjRGQZaZk8tnkEjlhzAyuTMB6DhmzH90phaIdbO5MGwkNDa5yDz9y9234ktceWHw "Prolog (SWI) – Try It Online")
Defines a predicate `A-K` which matches the ordered list `A` to its logarithmic incrementation `K`.
[Answer]
# [Scala](https://www.scala-lang.org/), 95 bytes
Golfed version. [Try it online!](https://tio.run/##JU5Nb8IwDL33V/gYayiAditKJaQdYRfECaEqdGnJ5CZdEj6r/vbiDh@s9yH7vVhp0qNtOx8SxInIVqezLLPMn35NlWCrrYM@u2qCOt/YmA5f/nIic1TFG4AaSRUEfFed@0pHA9@WlSX84535E3dk@nF/C6Uq@umbUySjfZoV@UYQx3ai8zfhZiWijJcW55PhcBhGgB9Tc4B1Qocm5rAOQT8OuxSsa46Yw97ZBIprAk/HaiInajHVFZ9yMQNeiMj2kA3jCw)
```
l=>l match{case Nil=>1 case Seq(x)=>1+x case _=>{val n=l.size;log(l.map(pow(n,_)).sum)/log(n)}}
```
Ungolfed version. [Try it online!](https://tio.run/##TU9BasMwELzrFXOUaFBSejOkUMix6aX0FIpRVNlRWUtGktuU4re7shqHXJbdmWF2JmpFapps1/uQEOdLdiqdZM2YP34anbBX1uGXAR@mQcOpwrON6bDzw5HMu6jwv2FbRAAhG@jT5QK0igYvlrB9xL3c3KKzET@LwuAO51uuntHFA/hSBJd/kNR@cIkXOoXBiKuEfMspp@9577@5W6EWQsahE1gXzi3SkS1zZJdeXS7JVWhjhacQ1M/hNQXr2rnem7PpWq7PaCLHG16yP8jNCnkIIYrbyKbpDw)
```
import scala.math._
object Main {
def f(l: List[Double]): Double = {
l match {
case Nil => 1.0
case List(x) => 1 + x
case _ => {
val n = l.count(_ => true)
log(l.map(pow(n, _)).sum) / log(n)
}
}
}
def main(args: Array[String]): Unit = {
println(f(List(3.0, 3.0)))
}
}
```
[Answer]
# [Perl 5](https://www.perl.org/) List::Util, 43 bytes
```
sub{@_>1?log(sum map@_**$_,@_)/log@_:1+pop}
```
[Try it online!](https://tio.run/##VZBRT4MwFIWf5VfckE222SG3LbRAtvGucS/6pIaogYXIBg5INMt@O7YDlo2@0HO@cy7cMtnnbttUCTxmVR0EL3WWg1U1Wys0tn8wShdt1XweoniJq7zYTJQD248yimezUUyieHqv1CgO8K4symMbGmmxBx3MVR1MDIBXuH7wnWgVXXGWFktAV3Y6JfRSZz1NKGEXqs0YFyhc9Lmgwh8gpo4YIGE7jiukZK4ql04P8et@bjOKPlU2l1Iwr4MYQcIvISo94ftIJUVJRQc55HTOf9BHbeRkTm2BsvtS9LjnoVBj0Jc6Oj0YOqKXlPyWyVddwQLU9qLTzsKzuSlqZdyO0knnTDur3Ge7OjXHc68CyHZlUwcwniNVN@j7tEAdLagOdanediYxbkxdaULyA@Yw2YQVWMW3BQFYT@tnWD9YGuwG6swA6leVDo1j@w8 "Perl 5 – Try It Online")
] |
[Question]
[
You know those letterboards outside old-style cinemas which show upcoming films - perhaps you have a miniature one in your home?
[](https://i.stack.imgur.com/E5cdlm.png)
If you've operated one, you'll know that you can normally add letters from either side of a row. But the slots (in which you slide letters) are thin, so it's impossible to swap the order of two letters once you've put them on.
Thus, you can't just go putting the letters on in any order - there's a restricted set of orders which actually work...
---
## More formally:
Given a string \$ S \$, an ordered list \$ \sigma= (\sigma\_i)\_{i=0}^k \$ of characters, we will say \$ S \$ is \$\sigma\$-*writable* if it is possible to write \$ S \$ on a (initially empty) row of a letterboard, by adding (all) the characters from \$ \sigma \$, in order. Characters can be inserted on either side of the row, but can **not** pass over existing characters.
For example, **ABBA** is **(B,A,B,A)**-writable, by the following process:
```
(empty row)
--> B (insert B from left)
--> AB (insert A from left)
ABB <-- (insert B from right)
ABBA <-- (insert A from right)
```
But it is *not* **(A,A,B,B)**-writable, since after inserting the initial two **A**s, there is no way to put a **B** in between them.
Trivially, every \$ S \$ is *not* \$\sigma\$-writable if \$ \sigma \$ is not a permutation of the characters of \$ S \$.
---
## The Challenge
Your task is to write a program which, given a string \$ S \$ of ASCII uppercase letters, and list \$\sigma\$, determines whether \$ S \$ is \$\sigma\$-writable. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!
You may assume \$ \sigma \$ has the same length as \$ S \$, although you may not assume it is a permutation of \$ S \$.
---
## Test Cases
In the format \$ S \$, \$ \sigma \$ (as a string).
Truthy inputs:
```
ORATOR, OTRARO
SEWER, EWSER
COOL, COOL
CHESS, SEHSC
AWAXAYAZ, AXYAWAZA
SERENE, ERENES
```
Falsy inputs:
```
SEWER, EWSRE
BOX, BOY
ABACUS, ACABUS
SSSASSS, SSSSASS
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŒPUṚ;"Ɗi
```
[Try it online!](https://tio.run/##y0rNyan8///opIDQhztnWSsd68r8f3i5g/6jpjX//0dHK/kHOYb4BynpKCj5hwQ5BvkrxXLpRCsFu4a7ggVdw4OBDLCYs7@/D0gITENEPFyDg0FCwa4ewc4QMcdwxwjHSMcokLBjRCSQG@WIaWaQK0TMyT8CJOLkHwnV7eToHAo20tHZ0QnIgugMDnYMhtoEYQPFYwE "Jelly – Try It Online")
Takes the letter-list \$\sigma\$ on the left and the target word \$S\$ on the right, returning a non-negative integer (truthy) if the word can be formed and 0 (falsy) otherwise.
Inspired by [a brief exchange with caird coinheringaahing](https://chat.stackexchange.com/transcript/message/62244870#62244870).
```
ŒP Powerset of σ: list of all sublists of σ, not necessarily contiguous.
U Reverse each, then
·πö reverse the entire list,
;"Ɗ and concatenate corresponding elements of the unmodified powerset:
ŒPUṚ;"Ɗ it's ordered so that each sublist's complement is at the complementary index.
i Find the first index of S in that result, or 0 if not found.
```
[Answer]
# [J](http://jsoftware.com/), 22 18 bytes
```
e.((,.~,,.),.)/@|.
```
[Try it online!](https://tio.run/##bY5LC8IwEITv@RXRyyrUqBfBgOAmpHgQAtlKH@BBpCIiCD4OBfGv15A2noRdmPkGdvbSLgdyvl8M5BKADQWc@Epy4Amfcel3Irh227StxWiUiE@SiLGf6fot2jGrj@cbh@z@ep4b6J11mFkH/ORl5tDZGJDJTcdNTl71WFu7DTSICDeGKFAyG9IRY44FlliFBIvS@wqB9Wl6uD6av23ORKxsEaCy5e@oQr3rylCj8jKeIEKKb3QGWPsF "J – Try It Online")
This builds up all possibilities recursively using a single reduction.
* `@|.` Since J evaluates from right to left, first we reverse our candidate list.
* `((,.~,,.) )/` This simply left-zips the next left element in the reduction with the results so far `,.` and cats that `,` with the right-zip `,.~` of the results so far, thereby giving us all possibilities (since the only way to proceed is to left-append or right-append each next element to what we already have).
+ `(( ),.)/` You might wonder about this *extra* `,.`. This is a J technicality that arises because the zips require the right side to be a table. But in the first step of the reduction, the right side is an atom, and this extra `,.` table-izes that atom. In later steps, when the right side is already a table, table-ize has no effect.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 64 bytes
```
[ all-subsets dup [ reverse ] map reverse [ prepend ] 2map in? ]
```
Port of Unrelated String's [Jelly answer](https://codegolf.stackexchange.com/a/253679/97916).
[Try it online!](https://tio.run/##ZVBBasMwELz7FfuB5tBjCy1rI5pCiUBKsB2Tg@Io1MSRZUluKCFvd9c1pIIKtBrN7I7EHFUdOjdu5Pvq7QmU913t4aSd0S143Q/a1NoTCh76C1inQ/i2rjEBzip8LuruvG@MIouG5p6T5JoArf5yBS5wzQXwtUDB4XbnJcuZAJZLqn9sxvnHXCJuyaSk/qXMIhZzLLDELWBREt4iaf/NBYtGUl7QLmOTFLONBMwwpSP6nJQop0dnQMotGStQbfvgh/1vDIfBQgVOf2nnNewoB3u/VVNCVpsD8Y@T0JhX2I3HOdiXiVmMPw "Factor – Try It Online")
And my original answer:
---
# [Factor](https://factorcode.org/), ~~74~~ 69 bytes
```
[ { ""} swap [ '[ _ prefix dup reverse 2array ] map-flat ] each in? ]
```
[Try it online!](https://tio.run/##ZZBPS8QwEMXv/RSPvXhyDx4VlLQUVxADzS5ttywS6hSD3f5JUmsp/ew1a0ELBjJ5/N7MJJlC5rbW80E8vTzeQhpT5wYfpCsqUegBhtqOqpwMpNZyMCiVJS1Lg7w@N6okve2sclC5FEPWoO3RaLJ2aLSqLO48b/TgVtuP4BHb8wh8H7GIY/rlIozDCGEsXPyjAefPS1ixXSiEy9@JYEVZzBKWsiNYkjp9ZM773zwKVyU@T9xO1018FhwEWMB8d6weJwQTl0sX4ZzJmzOM2GwmmF42yHCV4fXy7UJ94a1roOmTtCHc/EwNJ5xlc12U0jpJMn@Hqh5wmotl4vfOxXb@Bg "Factor – Try It Online")
Iterative approach. Works roughly like this:
```
EWSER
^
E
----------------------
EWSER
^
WE EW
----------------------
EWSER
^
SWE WES SEW EWS
----------------------
EWSER
^
ESWE SWEE EWES WESE ESEW SEWE EEWS EWSE
----------------------
EWSER
^
RESWE ESWER RSWEE SWEER REWES EWESR RWESE WESER RESEW ESEWR RSEWE SEWER REEWS EEWSR REWSE EWSER
```
Then check if the first input is in this final list.
[Answer]
# [Python 3](https://docs.python.org/3.8/), ~~68~~ 65 bytes
```
f=lambda s,x,a="":x and f(s,y:=x[1:],x[0]+a)|f(s,y,a+x[0])or a==s
```
[Try it online!](https://tio.run/##VZDBasMwDIbveQrhU0x92NhlBHxQgqGHgcHuSNKQg0cXVujSEGfgwt49sx2PrSf/@iTrlzTdlo/r@PQ8zes68Iv5fDsZsMwxwwkpHJjxBENu2a3grnsseua6h35n6HeEzOxCTK8zGM7tusxf7xY4dBnkRCo8SEUYEHlQqCShLGAtahGpqLUXG6ykfAksvgnthdaBabHXVYJYY4MtHgPHpvXhEQnN@iwbzMX@ef83USJ9LmUTUCnb324lVq/RAyssvUoTao06eW86Wfg1/WngPEJctJjm87jk4RKO0rv8Ns19wfoD "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~12~~ 10 bytes
*-2 bytes thanks to [Fatalize](https://codegolf.stackexchange.com/users/41723/fatalize)*
```
Ė|k↰;?tᵗpc
```
A predicate that takes the list of characters \$\sigma\$ as its input parameter and the string \$S\$ as its output parameter, succeeding if \$S\$ is \$\sigma\$-writable and failing if it is not. (Both \$\sigma\$ and \$S\$ are taken as Brachylog strings.) [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//8i0muxHbRus7Usebp1ekPz/f7RSopKOUhIQQ@jY/0qJSUmJSgA "Brachylog – Try It Online")
### Explanation
The predicate is recursive:
```
Ė|k↰;?tᵗpc
·∫∏ Base case: input and output are both the empty string
| Or (recursive case):
↰ Call this predicate recursively on
k The input with its last character removed
;?t·µó Put the result in a list with the original input's last character
p Try both permutations of that list
c Concatenate the elements into a single string
which must match the output parameter
```
[Answer]
# JavaScript (ES6), 45 bytes
Expects two strings as `(S)(sigma)`. Same recursive approach as [97.100.97.109](https://codegolf.stackexchange.com/a/253669/58563).
```
S=>g=([c,...b],o)=>c?g(b,[o]+c)|g(b,c+o):o==S
```
[Try it online!](https://tio.run/##fY/NCoJAFEb3PkXMykHzAYIxrjLQIhiYa/iXC51UinCiolXvbo62Smk1Z/gO9373Ur7Kh7qfb891p09137Aemd8yO1eu53lV4WrKfLVt7crNdeEo@jaoHE03mjHsle4e@lp7V93ajU2EhEhIQgeKJEhBKLV@FOQxHw0eo4GZEAqxN/n0zuMdRzQ58h2GCwLEkEAKmXEgSYdvBoSunBU5doRa//pIvjAvEImJA5EuLQsgPIx1IITA0PxgRMBv5YkHqf8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Employs the inverse test of a post by [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger) - [here](https://codegolf.stackexchange.com/a/243174/53748).
```
JŒ!<ƝṢƑ$Ƈịċ⁸
```
A dyadic Link that accepts the sign, \$S\$, on the left and the deck of letters, \$\sigma\$, on the right and yields a positive integer (truthy) if possible or \$0\$ (falsey) if not.
**[Try it online!](https://tio.run/##ATQAy/9qZWxsef//SsWSITzGneG5osaRJMaH4buLxIvigbj///8iU1RBVElPTiL/IklPVEFOVFMi "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/r6CRFm2NzH@5cdGyiyrH2h7u7j3Q/atzx//By/UdNa/7/j45W8g9yDPEPUtJRUPIPCXIM8leK5dKJVgp2DXcFC7qGBwMZYDFnf38fkBCYhoh4uAYHg4SCXT2CnSFijuGOEY6RjlEgYceISCA3yhHTzCBXiJiTfwRIxMk/EqrbydE5FGyko7OjE5AF0Rkc7BgMtQnCBorHAgA "Jelly – Try It Online").
### How?
First, this constructs a list of all permutations of the indices of \$S\$ which do not decrease after their first increase.
e.g. for \$S\$ of length four:
```
[1, 2, 3, 4]
[2, 1, 3, 4]
[3, 1, 2, 4]
[3, 2, 1, 4]
[4, 1, 2, 3]
[4, 2, 1, 3]
[4, 3, 1, 2]
[4, 3, 2, 1]
```
It then uses these to index into the deck, \$\sigma\$, to construct all the possible signs and counts the occurrences of the sign, \$S\$.
```
JŒ!<ƝṢƑ$Ƈịċ⁸ - Link: list of characters S, list of characters D (sigma)
J - range of length (S) -> [1,2,3,...,length(S)]
Œ! - all permutations
Ƈ - filter keep those for which:
$ - last two links as a monad:
∆ù - for neighbouring pairs:
< - less than?
Ƒ - is invariant under?:
·π¢ - sort
ị - index into (D) (vectorises)
⁸ - chain's left argument = S
ċ - count occurrences
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 33 bytes
```
[]![]=1
(x:s?s++[x])!(t++[x])=s!t
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z86VjE61taQS6PCqti@WFs7uiJWU1GjBMKwLVYs@Z@bmJmnYKug5B/kGOIfpKSgCGSGBDkG@Sv9BwA "Curry (PAKCS) – Try It Online")
Returns `1` for truthy, and nothing otherwise. It might return the same `1` multiple times for truthy result.
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 26 bytes
```
^set"__ _`"Q rev"++"dip :?
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Port of Unrelated String's clever answer.
For testing purposes (use `-i` flag if running locally):
```
"ORATOR""OTRARO", "SEWER""EWSER", "COOL""COOL", "CHESS""SEHSC", "AWAXAYAZ""AXYAWAZA",.
"SEWER""EWSRE", "BOX""BOY", "ABACUS""ACABUS", "SSSASSS""SSSSASS",.
,` ( ,_. ) map
^set"__ _`"Q rev"++"dip :?
```
## Explanation
Prettified version:
```
^set ( __ _` ) Q rev \++ dip :?
```
Assuming inputs *S*, *σ*:
* `^set` powerset of *σ*
* `( __ _` ) Q` duplicate, reverse each, reverse
* `rev \++ dip` prepend to powerset
* `:?` whether *S* is in resulting array
---
# [sclin](https://github.com/molarmanful/sclin), 38 bytes
```
1<>: _` ,_"\++ Q rev ++ +`"fold rev :?
```
[Try it here!](https://replit.com/@molarmanful/try-sclin)
For testing purposes (use `-i` flag if running locally):
```
"ORATOR""OTRARO", "SEWER""EWSER", "COOL""COOL", "CHESS""SEHSC", "AWAXAYAZ""AXYAWAZA",.
"SEWER""EWSRE", "BOX""BOY", "ABACUS""ACABUS", "SSSASSS""SSSSASS",.
,` ( ,_. ) map
1<>: _` ,_ "\++ Q rev ++ +`"fold rev :?
```
## Explanation
Prettified version:
```
1<>: _` ,_ ( \++ Q rev ++ +` ) fold rev :?
```
Assuming inputs *S*, *σ*:
* `1<>:` split *σ* into head and tail
* `_` ,_ (...) fold` fold over tail with head as initial accumulator...
+ `\++ Q` vectorized suffix
+ `rev ++` vectorized prefix
+ `+`` concat prefixes and suffixes, thereby preserving flatness of accumulator
* `rev :?` whether *S* exists in resulting array of prefixes/suffixes
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
æÂís+Iå
```
Port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/253679/52210), so make sure to upvote him/her as well!
Inputs in the order \$\sigma,S\$. Outputs `1`/`0` for truthy/falsey respectively.
[Try it online](https://tio.run/##MzBNTDJM/f//8LLDTYfXFmt7Hl76/7@To5Mjl6OTkyMA) or [verify all test cases](https://tio.run/##Vc1BCsIwEAXQq0i2dqEL1@UnBLoQBjItSVsKKngCQejWhQfwDrrzFLmJF4nTZKPZTOYx82ezO56253Sda7X63B8rVc@HLsVXvMX3ZR3iM1VpHJWGhqoUtJSpGhW1Do5EyKEll816tk6IrbdFDNFeIJelZ9uwWaCxzFkQengMOdsjoMdQXC793pNsZ/@yNfXSawpl3kB3nDdgupLN8sALlo/o9AU).
**Explanation:**
```
æ # Get the powerset of the (first) implicit input `σ`
 # Bifurcate it; short for Duplicate & Reverse copy
í # Reverse each string in this reversed copy
s # Swap so the unmodified powerset-list is at the top of the stack
+ # †Concatenate the strings at the same positions in the list together
Iå # Check if the second input `S` is in this list
# (after which the result is output implicitly)
```
*†*: The `+` is the reason for the [legacy version of 05AB1E](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) (built in Python), which allows concatenation of strings and vectorizes. In the [new version of 05AB1E](https://github.com/Adriandmen/05AB1E) (build in Elixir), the `s+` should have been `øíJ` instead: [try it online](https://tio.run/##ASEA3v9vc2FiaWX//8Omw4LDrcO4w61KScOl//9CQUJBCkFCQkE).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes `σ` as the first input.
```
à
íiUmÔÔ øV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4ArtaVVt1NQg%2bFY&input=Ik9UUkFSTyIKIk9SQVRPUiI)
```
à\níiUmÔÔ øV :Implicit input of strings U=σ & V=S
à :Combinations of U
\n :Reassign to U
í :Interleave U with
Um : Map U
Ô : Reverse
Ô : Reverse
i :Reduce each pair by prepending
√∏V :Does the resulting array contain V
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~134~~ ~~132~~ 131 bytes
-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!
```
o;*t;f(*r,a,b,s){r?t=r,s="",*t=0:0;*t|=!strcmp(a,s);for(int v=2,c=*(char*)b;v--&&c;f(0,a,b+1,o))asprintf(&o,"%s%s",v?s:&c,v?&c:s);}
```
[Try it online!](https://tio.run/##dVHLboMwELzzFa4lEBAjkRxjocggpBwqIeFUebQ5EDekSAlEtpseUn691Iak0EN82d2Z2Vlrl3nsmJWHpqmwK3FuuxxlaIeEc@UzGXAkAgiRKwN/6ivBd/AkJGens50pCc4rbhelBJdggljg2uwj466zwxfPsyym3HxtNhqjynEyceZKm9tWhaApTAHRZSamFlPBYlPlVjfa65QVpe0YVwOo1xoCuRfydQsC0IH6wSQliySFSGWLlKQJRD1H42XcUvGS6qRnoiR51kQXB/g8plQTNJ7TaMiQJVmRNdlokqzWqtyQR7PSeMiEyUrjYbL@5xeS6KUdRSIS6mzgRSmht390@YD1EfDbosZGG9XyQbv9Qm3Gx92Wii1W9SgAE6cV9RvTSr4Xn0cJ8B@ortFh6N5@T8AIjFXhO734dj91PARMoYaa728lfNTZ@d7aa6Nuflh@zA6i8b5@AQ "C (clang) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
⊞υωFS≔⁺⁺ιυ⁺υιυ№υS
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1RHoVzTmistv0hBwzOvoLQkuKQoMy9dQ1NTwbG4ODM9TyMgp7QYQmTqKJRq6iiA2UB9mZqaIAFrrgCgjhIN5/xSIAkURzVG0/r//2BXj2BnLmcP1@Dg/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Takes the list as the first argument and the string as the second argument and outputs a `-` for each order of insertions that writes the string (this is always even because the first character can be inserted from either side). Explanation:
```
⊞υω
```
Start with an empty board.
```
FS
```
Loop over the list of characters.
```
≔⁺⁺ιυ⁺υιυ
```
Prefix and suffix the character to all of the strings found so far.
```
№υS
```
Output the number of occurrences of the desired string.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 7 bytes (14 nibbles)
```
?!.\;`_0$\$@:
```
[Nibbles](http://golfscript.com/nibbles/index.html) port of [Unrelated String's Jelly answer](https://codegolf.stackexchange.com/a/253679/95126): upvote that one!
```
?!.\;`_0$\$@:
`_0$ # all subsequences of arg1
; # (save that for later)
\ # reverse the list
. \$ # and map over it reversing each subsequence
! # now zip this together with
@ # the saved of subsequences
: # by concatenation
? # and find the index of arg2
# (or 0 if not found)
```
[](https://i.stack.imgur.com/2d4TY.jpg)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 88 bytes
```
f=lambda a,b,s={}:f(a,b[1:],{b[0]+t for t in s}|{t+b[0]for t in s}|{b[0]})if b else{a}&s
```
[Try it online!](https://tio.run/##VdDBaoQwEADQu18RPBRlc2jppQgeRgnsoTSQ2UVd8aCsocLWFZNCi/XbbeJmaT1l8pLJTGb41u/X/vllGJdFxpf6oznXpKYNVfE0RzIwYfkUVXRqysdqp4m8jkSTridq/pn0zuqGLMxhJ0lD2otqp3p@UIseP1tFYlJ6JPCRCfbGfEr8NUA/pJa5gAMXlvlBgOCOkWVsVZaZRIcp56/W1tXRniFaQ7bH1CFkkEMBJ@uQF2Z7Aj/0Ks@TtWnuX0t/RQRzyQnPLSW8uL@WQHpca0AKyfHeOCICutq32JUwY1H0yw5m/X80jF2vAxkYDMPN@a2b7YXlFw "Python 3.8 (pre-release) – Try It Online")
I rewrote it using sets and recursion, empty set is falsy, builds up a set of increasing string that get appended and prepended by the next character.
] |
[Question]
[
## Content
You count numbers every day (I think), and most of you know how to count properly, the one next to `1` is `2`, and the next is `3`, so go on, no matter what number you receive, you can easily know what next number is.
Anyway, the program doesn't know, they are incredibly stupid, if I make a program shaped like `1`, it doesn't count to `2` for me. We need to solve that asap.
## Task
Write a program shaped `1` that produces a program shaped `2`, which chains and produces the next number, until the program failed and produces a number other than it should be.
## Shapes
your number should shaped like:
```
# ### ### # # ### ### ### ### ### ###
# # # # # # # # # # # # # #
# ### ### ### ### ### # ### ### # #
# # # # # # # # # # # # #
# ### ### # ### ### # ### # ###
```
It can be enlarged, twisted, be longer or shorter, as long as it Resembles the shape:
```
Acceptable:
##### ###### ### resembles 9
## # # # # #
## # ###### ###
##### # ###
# # #
# # #
#
Not acceptable:
### ##### ### ####
### # # # # # ##
# ### ### ###
# # # #
# # #
Those does NOT resembles 9
```
```
Acceptable reshape:
Original shape:
### ####
# # widen # #
### -------> ####
# #
# #
extend ### shorten ###
-------> # # or # #
### ###
# #
#
#
lengthen ###
-------> # #
# #
###
#
#
enlarge line ### #### #### ### ###
-------> ### or # ## or ## # or # # but not # # (this is
# # #### #### ### ### not 9
### ## # ### ### but a 0)
# ## # # ###
#
```
You can do 1 or more of those actions on the same digit for any amount of units, for example:
```
#####
# ##
# ##
#####
##
##
##
##
```
Is Widened, extended, enlarged, and lengthened.
The original number should be obtained if you repeatedly removing one out of two consecutive identical rows or columns.
For digits that contain a hole in it (6, 8, 9, 0), the hole should exist (length, wide does not matter).
For U-shaped holes (2, 3, 4, 5, 6), those should have at least one empty byte that resembles a hole:
```
### is done by shortening, and then enlarge line.
##
### Acceptable.
##
###
```
For numbers that have more than one digit, digits should have at least one spacing between them, and they should not be connected in any way:
```
# ###
# #
# ###
# #
###
```
In case someone built a super large program, I am limiting first number's (1) byte count to be under 10k.
## Rules
* No standard loopholes
* Takes no input and outputs a program.
* You should output in the very same language you used on the previous number.
## Scoring
Your score is the highest number you chained until break.
For example, your code failed to generate 21, your score will be 20. In this case, the `20` program could be anything as long as it fits number rules, may also be non-program.
If there is infinity score exist, it counts as an infinity score.
for tie breaker, It would be the lowest total bytes count until the number 1000.
Whoever gets the largest number is the overall winner. (Grand prize)
And also individual winners for each language too. (individual prize)
[Answer]
# [Python 3](https://docs.python.org/3/), infinity points
```
exec('exec("N=2%F=@@@%Q=chr'
'(39)*3%def?magic(s,N,W,H=N'
'one):%?if?H?is?None:%??H?='
'?W//2%?L=[%?@###,#,###,###'
',#?#,###,###,###,###,###@.'
'split(@,@),%?@#?#,#,??#,??'
'#,#?#,#??,#??,??#,#?#,#?#@'
'.split(@,@),%?@#?#,#,###,#'
'##,###,###,###,??#,###,###'
'@.split(@,@),%?@#?#,#,#??,'
'??#,??#,??#,#?#,??#,#?#,??'
'#@.split(@,@),%?@###,#,###'
',###,??#,###,###,??#,###,?'
'?#@.split(@,@)]%?Z=@@%?s=s'
'.replace(chr(32),chr(63)).'
'replace(chr(34),chr(33)).r'
'eplace(chr(39),chr(64)).re'
'place(chr(10),chr(37))%?s='
'f@exec({chr(39)}exec(!{s}!'
'.replace(chr(63),chr(32)).'
'replace(chr(33),chr(34)).r'
'eplace(chr(64),chr(39)).re'
'place(chr(37),chr(10))){ch'
'r(39)})@%?I=0%?done=False%'
'?for?i?in?range(5):%??for?'
'_?in?range(H):%???z=@[[email protected]](/cdn-cgi/l/email-protection)'
'in(L[i][int(j)]for?j?in?st'
'r(N))+@?@%???k=0%???for?j?'
'in?z:%????if?j==@#@:%?????'
'k+=1%????else:%?????if?k:%'
'??????k*=W%??????if?I==0:%'
'???????Z+=s[:k-1]+!@!%????'
'???I=k-1%??????else:%?????'
'??z=s[I:I+k-2]%???????if?l'
'en(z)?==?0:%????????Z+=@#@'
'*k%???????elif?len(z)?<?k-'
'2:%????????Z+=(!@!+z).ljus'
't(k,@#@)%????????I+=k%????'
'????done=True%???????else:'
'%????????if?z[-1]==!@!:%??'
'???????Z+=!@!+z+@)@%??????'
'???I+=k%?????????done=True'
'%????????elif?z[-2]==!@!:%'
'?????????Z+=!@!+z+@#@%????'
'?????I+=k%?????????done=Tr'
'ue%????????else:%?????????'
'Z+=!@!+z+!@!%?????????I+=k'
'-2%?????Z+=@?@*W%?????k=0%'
'???Z+=chr(10)%?if?done:?re'
'turn?Z[:-1]%def?f(s):%?fro'
'm?itertools?import?count%?'
'print(next(filter(None,(ma'
'gic(s,N,w)?for?w?in?count('
'7)))))%@@@%exec(F)%templat'
'e=@@@N={}%F={}{}{}%exec(F)'
'%template={}{}{}%S=templat'
'e.format(N+1,Q,F,Q,Q,templ'
'ate,Q)%f(S)@@@%S=template.'
'format(N+1,Q,F,Q,Q,templat'
'e,Q)%f(S)".replace(chr(63)'
',chr(32)).replace(chr(33),'
'chr(34)).replace(chr(64),c'
'hr(39)).replace(chr(37),ch'
'r(10)))')##################
############################
############################
############################
############################
############################
############################
```
[Try it online!](https://tio.run/##7ZdrS@NAFIa/769YDaEzZqy1dV0sO5z5VCxIQVwQLGUpdaJp0rQkEd0Wf7t7ZnLpRdeT7udNGetInnnfc@Z2XPzOHudx5@1Nv@gJa9ifhwPZdntSKeVey8lj0vj6yfOlwToX/Kjj3msfZuOHYMJSMRC34lIOCHAea951IfDhEoIUBtjHLnYkAcLtyUnbhSs5dEE5jiPw49hGgMKB6tXNppoEmC6iIGNKKC6MpBlFAJhGgE4uCWAbQNl3FAE2P5K0dinF7egA6iZHfSyJtqnpgDIZeXTrb8rqO8lyLsl53I6s@p1ShC3JkQt3uMxdSGVKTUeiF9F4ohnuB9Zpc2G@zzucUytnizvLuY7hqG21yV0UemeG0wS45k5bhd53zk2QBOgru/1XheSr7R2s0teDfZKDSRFFkvZLTsmd7Zec8zKpF/slB5MiiiRxjjFTVm1KOC6Wvmy5cI@HleyNo1S71JLz5wkEEMSQjOMHzb6ZM8/@kQB/rZlLy8BSKlDN6ZwAg5hdDYPRMIgzNuUjIzU1Y6UZGeOAcw81jFhowsyNToFUhKV1aA7zqZTKUXmXAkNPntoXNWayQHCIsEtm1T7hkbzNIUP1pWzVBOHOk@mwGx6fjrwDdeDWsIpv9CUChd6GYRJcola/2/fC4/aowI3fiFrkMVtykBJa3ZIyvhV5dxyF5fs6Mjr5QD8gPCbA9pYQw8x4S96Mpk/U8ZixUKAvXuF9T4Y1s5rvpZ/Jk167xtwSYKWEAS6HOI9Sol3jv/YCsOF5iqtirBoLoIwKtnzXtWpnA822S7P1rG6adVTdrH5slgDXc7C5wGsoVg7L3VRZIMDjtlstbFBHxXY2hw8dIzLFCW6rSBNiF8grIHtKYrgbdnHN2KLVZ6k5Xv2EOldnEGQ6yebzKIVgtpgnGUzmT3HmUslZJOYojvVLxvwgwjGYqXUFm40JsKymn7k9h5/NKW4lGQHihY@Pa0p4e4v3uJvpGV5@1BWgTdk/kKtX/Adg9Wo@5QDUIi/G1yV2I2sqNjG02ThjA@9UXIsetmthUQJELXHNXZ/dcBNnpaepquNverTVUu9wt@Kh6tWqINqteAhwXRDtVjwEuC6IdisesgawBVGDO@@eT0Hnk@c/@A/g29sf "Python 3 – Try It Online")
[Here's the code that generates the 1](https://tio.run/##lVRRa@JAEH7fXzHow@6a1VbttVRuX6VCEaQHgkEOsZs2JiaSrLSn@Nu92c3GRL0r1LBk55v5vpldJ7P5o9/TpH88jmWXDCWllEzk8j1j/Ufe6pNXFcB68RYuWS7GYiqe5DhNFB8QCAN4gjAHY6OJhoTpzU2PwLP0CdBmsynwaboFtX21aCffxKFmVFAuDMmECYBiWQvArsr@D@kf6gXpq0ylcj1j7X1FOjtTTf20vyDNCczwTgnkMu9kahMvlorZ2@1xYd73fc7PHXeFo3/leHSMuwtH99YxHjg3iQKqPtWS7R3pYK3GPj80zmiYWbhKLhKVjstE92Vpj5eMh8KBlXB@ysvx2CN5S@AVO0QOF3GuCARpBiGECWSL5E2xH6aTLPi7Ap8sCDtJgXZWaZiwZz@c@2Gi2YrPTfDKBOc6Y2POPYwy4ZFJVWhZ986KmDZdSUmbtDAh8rDPzUZhPQ7DmMhtIWrJqdsiPJLytvTAzJO5P4ja3bnXoI0SHUlEnFHTNPXn/mgw8qJ2b15iKBmrhO04SAmVspHGEltRCai4ivwJqHAWyjC9t@OdeLXNNYsEUvnJP/LkSaa4@l/ZVlXCtQpNOTsfzyMlKlawyWFTeJTTCj1TvpYuika93hd6zW/p1WutRGqXX4i0e@R0i0Bb7v9zDYGg6007s0yaAWRKb7MEZv4AT2@HXMBy03ZBlq4h1CrTaRrnEK43aaZhmW4TTWCTmR5M1KdmQRhjEDPDT7BqQH5w24AfpgEtieFHiT9i5qr9EIecaLXGb0crM2zHcn/Asbs/mOc6wuEvskQ6KL9eaDb2umIihrgmovSJCScBe@Em1/cYx@Nf "Python 3 – Try It Online")
The total length of the first 1000 programs (including 1) is 3961370 bytes
The main function of interest takes any string without `!`, `?`, `@`, or `%` and uses those to escape (space), `\n`, `'`, `"`. That makes it easy to split up the big exec string, since it has nothing annoying anymore.
Here's the number 1234567890 as generated by the program. (At the TIO link, you can see how it has to increase the size of 1234567891 because it couldn't fit)
```
exec('' 'exec("N=1234567891%' 'F=@@@%Q=chr(39)*3%d' 'ef?ma' 'gic(s' ',N,W,H=None):%?if?H' '?is?None:%??H?=?W//' '2%?L=[%?@###,#,###,' '###,#?#,###,###,###' ',###,###@.split(@,@' '),%?@#?#,#,??#,??#,'
'#?#,#' '??,#??,??#,#?#,#?#@' '.split(@,@),%?@#?#,' '#,###' ',###,' '###,###,###,??#,###' ',###@.split(@,@),%?' '@#?#,#,#??,??#,??#,' '??#,#?#,??#,#?#,??#' '@.split(@,@),%?@###' ',#,###,###,??#,###,'
'###,?' '?#,###,??#@.split(@' ',@)]%?Z=@@%?s=s.rep' 'lace(' 'chr(3' '2),chr(63)).replace' '(chr(34),chr(33)).r' 'eplace(chr(39),chr(' '64)).replace(chr(10' '),chr(37))%?s=f@exe' 'c({chr(39)}exec(!{s'
'}!.re' 'place' '(chr(' '63),c' 'hr(32' ')).re' 'place' '(chr(' '33),c' 'hr(34' ')).re' 'place' '(chr(' '64),c'
'hr(39' ')).re' 'place' '(chr(' '37),c' 'hr(10' '))){c' 'hr(39' ')})@%' '?I=0%' '?done' '=Fals' 'e%?fo' 'r?i?i'
'n?ran' 'ge(5)' ':%??f' 'or?_?' 'in?ra' 'nge(H' '):%??' '?z=@?' '@.joi' 'n(L[i' '][int' '(j)]f' 'or?j?' 'in?st'
'r(N))' '+@?@%???k=0%???for?' 'j?in?z:%????if?j==@' '#@:%?????k+=1%????e' 'lse:%?????if?k:%???' '???k*=W%??????if?I=' '=0:%?' '??????Z+=s[:k-1]+!@' '!%???????I=k-1%????' '??els' 'e:%??'
'?????' 'z=s[I:I+k-2]%??????' '?if?len(z)?==?0:%??' '??????Z+=@#@*k%????' '???elif?len(z)?<?k-' '2:%????????Z+=(!@!+' 'z).lj' 'ust(k,@#@)%????????' 'I+=k%????????done=T' 'rue%?' '?????'
'?else' ':%????????if?z[-1]=' '=!@!:%?????????Z+=!' '@!+z+@)@%?????????I' '+=k%?????????done=T' 'rue%????????elif?z[' '-2]==' '!@!:%?????????Z+=!@' '!+z+@#@%?????????I+' '=k%??' '?????'
'??don' 'e=Tru' 'e%???' '?????' 'else:' '%????' '?????' 'Z+=!@' '!+z+!' '@!%??' '?????' '??I+=' 'k-2%?'
'????Z' '+=@?@' '*W%??' '???k=' '0%???' 'Z+=ch' 'r(10)' '%?if?' 'done:' '?retu' 'rn?Z[' ':-1]%' 'def?f'
'(s):%' '?from' '?iter' 'tools' '?impo' 'rt?co' 'unt%?' 'print' '(next' '(filt' 'er(No' 'ne,(m' 'agic('
's,N,w' ')?for?w?in?count(7)' '))))%@@@%exec(F)%te' 'mplat' 'e=@@@N={}%F={}{}{}%' 'exec(F)%template={}' '{}{}%' 'S=template.format(N' '+1,Q,' 'F,Q,Q,template,Q)%f'
'(S)@@' '@%S=template.format' '(N+1,Q,F,Q,Q,templa' 'te,Q)' '%f(S)".replace(chr(' '63),chr(32)).replac' 'e(chr' '(33),chr(34)).repla' 'ce(ch' 'r(64),chr(39)).repl'
'ace(c' 'hr(37),chr(10)))')## ##################### ####### ##################### ##################### ####### ##################### ####### #####################
```
[Try it online!](https://tio.run/##tVdha@JMEP7eX/F6ISTbpJ7WXn0r7zL7SSocQrmDQkUOsck1RqMkKdez9Lf3Zte4szFukYM3EnV2dmaePDs7O9n8Lp/WWe/9PXqJ5r7n/bO7PCV@GvPuZe/qy3X/35uuq3VDLoRw7/j8Kfd7N@y85z6SXQyrmZZ@JnO/0FI4Du/DWz5eZxEbuJDEcKt1kBQgFTgOt8Dh/vNnrbt04SufuCAcxwnxg99ap4ZgN1jdFK8aEO1is0xKX4RC61go/UnDEGB373VnnhonaIARQE1xdje5Ic/aIUFrgqnDrm6A5kxRd6x1FeQ9HhO2twdo/JLdIdBavEMoJhVylELoadohuRFs6sID5oYLBS/aebTRuuVsHvlaUnlDq8tCOXDdY0zayKla56upV7sZPTWDMk1N9askVDO07vqKnKkZ3Y6x8sqkz5jEGQvMdELmv1b@3tQGaL0WRMVbC13uxfrl1WAf6Pw6tB4C0JIMdknQ2F9F@DBerxHv6ng87wj1JqHk5Uy5ubEAPfkhDoH2D4DSmjUisNf5SVTUcHrsjQmqYjDiHUN6xOKjJT6cLaluRS7Eay3lkEBCVGSQzzIL0J@R/4VZdLLQxdrpOocftM0S6VRLGbq5tVEh3ZxEBWy5MOpIe7FOKIL/dULSdJJkJS3Sgk1rOBc1nEVJVOT@mOnH9QIBWAkAUqQZf2I01boFoOlWYgd5DCw4pzriiN04pAHvqn@0LssiqpRolaq/RvmD9Jzf79RSP@IW0nhn4Nbs8HoIeDEZpBfdadAiLK3KG/pClRIMu8jMEXMhznZOtXKLvkeDUZBeXE4rj8bBF8MyyvwtA86hY7ohaMIR5@lheIxPtv9BekEldbDHLY39lmgFFiq2rL1caLvnovTTEIMxba91o4CnelRuFv6dtsRzdEioQQXSRCtIyBD7doJ8c9p1CJT0EnqLErYVbAPBBKlHlGkGsqPQqkvxtZ1YqMC14YSlCcXICgnFMaEE9AxpYwHNrEB0lDL8e/580t6NzEQ/3Ndg10nmBzpeI3@sds3HNRfCPQ2LJ3khQjH33YMN8mCsIBaLk6g4v/8wfGrb851arcAHnD9RjuBRYyvTqk3VM2VyEaGQR6VlAb08g4cJZT3mOZ01j9gkx0SFX2AVJ6dxvl6dVtGTMsot4cv1mopTw261MY6zEuYkPWela6N3k9fOhSx6MaQ4WZa2LMRzgSJkUejr5/Nm8g2BqCjwFeEXndfq0Pglz4r5GpH5fWa0Lti/ydcQ1acNmVvaeo4VNh2lsenQaMxf39whfsmPW3/nUa6UTYQTLD7rdt/43qKNgFez0h9b7IJueEcN@xCFu3BvG94x18yKb0zQHhRuIwhxP1ZuTW@2rJBBqB7EGONTrU2ud6mqOdWNtG11pSFh6e0NdQdusVMRjS14ve/ybypDokKhq7Ww/d1c3LbYcDDHqXTOseto@LruI7v/w@ff2r2//wE "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score infinity, ~~134~~ 111 bytes for 1, [597940 bytes for 1..1000](https://tio.run/##NUrLCgFRGH4ZSzJG1DQ2CnU0ZTXKcpSNlJ2w0Ay7sbFCLothRrkumZPL4h8mHuM/L3Kckvr67vVao9HhvKwoSjACp6Bxzpm5CKZFpPtYMpg@J0jH4EZFmcPrkMCKgPu@IBW6ZtZdgLy9qgjouxWxZZh1JbnYz90JOL3AJy8TfTuP/iCdEiTnjRLSeV3qSm3WP0iwKYAnjIp0l40gfYS2SmBb7oDXCo/xkh7an5sGrm4kYAMnpDO9yaxzhZlLFbby//cF)
```
“ØJṫ-3ØėṖ¤,“DịI¢I¤ȷṢI£⁽⁽IȥbI£ḤYI¤<⁻ID-I¤<⁽I¡~øIŀḊEḃ65ḃ2EaOṛj0z0x€0¦F¥€;ṪA$ṾƊ;I©Vy¥vƭ/OUƊɼL¤Ua1¦®ṚUo⁶Y”;©2Vy¥vƭ/
```
[Try it online!](https://tio.run/##NUpNC8FgHP8yjpaZuMxFoR6pnaZ2pFyk3ISDNm5zZ3k5YFNejzxPzOE/1nyM//NF5impX7/3VrPd7scxN5eBU0F2lDKB85ohm4KbFGUR7xMCGwJudEMmdMstX4BEXkMEpK4htjy37qQo/ZxPYD0MKHmbSO0S0nEuK0gp1TVki5Y8kHt8dJJhVwZPGBXZoZBA9gxtlcC@1gevG55Tmh7an0cVXL2ehh1ckM31DreuBjdXKuyV/y@Ovw "Jelly – Try It Online")
A full program that takes no arguments and prints the next program. Should work for any integer - to try a different output, just change the number 2 after the `©︎` to something else. This uses something similar to the minimum possible shapes for each number as suggested by @Bubbler but I’ve added a zero. The left-hand most digit has its right-hand column widened to accommodate the program, which is then placed in the bottom row. All other non-spaces are replaced by the right link, `ṛ`.
## Example program for 9876543210
```
ṛṛṛ ṛṛṛ ṛṛṛ ṛṛṛ ṛṛṛ
ṛṛṛ ṛ ṛ ṛ ṛ ṛ ṛ
ṛ ṛ ṛṛṛ ṛṛṛ ṛṛṛ ṛ ṛ ṛṛṛ ṛṛṛ ṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛ
ṛṛṛ ṛ ṛ ṛṛṛ ṛ ṛ ṛ ṛṛṛ ṛ ṛ ṛ ṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛṛ
ṛ ṛṛṛ ṛṛ ṛṛṛ ṛṛṛ ṛ ṛṛṛ ṛṛṛ ṛ ṛṛ“ØJṫ-3ØėṖ¤,”,“DịI¢I¤ȷṢI£⁽⁽IȥbI£ḤYI¤<⁻ID-I¤<⁽I¡~øIŀḊEḃ65ḃ2EaOṛj0z0x€0¦F¥€;ṪA$ṾƊ;I©Vy¥vƭ/OUƊɼL¤Ua1¦®ṚUo⁶Y”,9876543211©Vy¥vƭ/
```
[Try it online!](https://tio.run/##y0rNyan8/18BCB7unA1BCqg84sQHDnChOEkByaFwUgGHyMA5WIG4kMVUiawHzh5FdENcBCIHKZWhRRVKyhwNSLpGGkaEYMtp6JGFKzcC0aOGOYdneD3cuVrX@PCMI9Mf7px2aInOo4a5QDzH5eHubs9DizwPLTmx/eFOIL34UeNeIPI8sTQJyHm4Y0kkUM7mUeNuTxddCGuv56GFdYd3eB5teLijy/XhjmYzUyBh5JroD7Qry6DKoOJR0xqDQ8vcDi0FMqwf7lzlqPJw575jXdaeh1aGVR5aWnZsrb5/6LGuk3t8Di0JTTQ8tOzQuoc7Z4XmP2rcFglyl6WFuZmpibGRoSFCw///AA "Jelly – Try It Online")
## Explanation (outdated)
```
[“&<-”,[”“,”’,””]],“D…Y”,2 | Literal list of [["&<-","“’”"],"D…Y",2]
© | Copy this list to the register
ƭ/ | Reduce using:
y | 1. translate (so the D…Y item has "&" replaced by "“", "<" by "’" and "-" by "”")
v | 2. Eval (so the translated string is evaluated as a program using 2 as its argument
```
## Explanation of the program that’s built by the main program (also outdated)
This is split into parts to make it easier to read; these are all a single link, though. It takes an integer argument and also expects the original list of three items in the main program to be in the register.
```
“œ…’ ¤ | Starting with [7814, 233918, 203174, 39260, 210860, 241612, 15754, 241614, 86334, 54574]
Ɗ | - Do the following as a monad:
ḃ62 | - Convert to bijective base 62
ḃ2 | - Convert to bijective base 2
’ | - Subtract 1
Dị | Now, index into this list of binary digits using the digits of the link’s argument
j0 | Join with zeroes
z0 | Transpose, filling with zeros
Ʋ | Starting with the link’s argument:
+1 | - Add 1
D | - Convert to decimal digits
L | - Length
Ʋ | - Following as a monad:
132+ | - Add 132
1; | - Prepend 1 (call this y)
¥€ | For each row of the output from the first part:
x" | - Repeat the number of times indicated by y, with arguments zipped
F | - Flatten
ḷ ɗɼ$ | Do the following to the register, but preserve the existing working value of the link (output from previous part):
Ʋ | - Following as a monad:
Ṫ | - Tail
+1 | - Add 1
;@ | - Append to the end of the list
Ṿ | - Uneval
Ż Ɗ}¡ | - Prepend a zero if the following is true when applied to the output from the previous part:
¬ | - Not
Ḣ | - Head
Ḣ | - Head
aⱮ”¹ | And with "¹"
a1¦®;“©yvƭ/”¤ | And the first row with the register after appending "©︎yvƭ/" to it
Ṛ | Reverse
o⁶ | Or with space
Y | Join with newlines
```
] |
[Question]
[
Let \$R, C\$ be positive integers and let \$0 < s \leq 1\$. Consider the \$R \times C\$ **matrix** \$\mathbf M\$ defined as
\begin{equation}
M(i,j) = \frac{\mathrm{mod}\,(j, i^s)}{R^s}, \quad i = 1, \ldots, R, \quad j = 1, \ldots, C
\end{equation}
where \$\,\mathrm{mod}\,\$ denotes the [modulo operation](https://en.wikipedia.org/wiki/Modulo_operation): for \$a,b > 0\$ not necessarily integer, \$\mathrm{mod}\,(a,b) = c\$ if and only if \$0 \leq c < b\$ and \$a = b\cdot k + c\$ with \$k\$ integer.
Note that \$0 \leq M(i,j) < 1\$.
The matrix \$\mathbf M \$ can be displayed as an image, where the value of each entry determines the color of a pixel, using a **colormap** to translate numbers between \$0\$ and \$1\$ into colors. The simplest colormap is to directly consider each number as grey intensity, with \$0\$ corresponding to black and \$1\$ to white.
As an example, \$R=500\$, \$C=800\$, \$s=0.8\$ with the grey colormap give the following image:

# The challenge
Given two positive integers \$100 \leq R, C \leq 2000 \$ and a number \$0 < s \leq 1\$, display the above defined matrix \$\mathbf M\$ as an image. You can use any colormap of your choice, not necessarily consistent across images, as long as it satisfies the very lax requirements described next.
# Colormap requirements
1. At least \$16\$ different colours.
2. Reasonably gradual changes between adjacent colours.
3. The first and last colours should be clearly different.
Although the terms *reasonably gradual* and *clearly different* are somewhat subjective, this is not likely to be a contentious point. The sole purpose of these requirements is to prevent abuse. If your programming language offers a default colormap, it is most likely fine. If it doesn't, using grey is probably the shortest option.
# Additional rules
* **Graphical output** is required, with output being [flexible](https://codegolf.meta.stackexchange.com/questions/9093/default-acceptable-image-i-o-methods-for-image-related-challenges) as usual.
* The image should have the correct **orientation**, with \$M(1,1)\$ corresponding to the upper-left corner.
* The image should have the **aspect ratio** given by \$R\$ and \$C\$. That is, each entry of \$\mathbf M\$ should correspond to a square pixel.
* If the image is output by displaying it on the screen, it is not necessary that each screen pixel corresponds to an image pixel. That is, the **display scaling is flexible** (but the aspect ratio should be kept).
* **Auxiliary elements** such as axis labels, grid lines or a white frame are not required, but are allowed.
* [Programs or functions](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) are accepted. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Shortest code in bytes wins.
# Test cases
Each of the following uses a different colormap, to illustrate some possibilities (and not incidentally to produce lively pictures).
| Inputs: `R`, `C`, `s` | Output |
| --- | --- |
| `500`, `800`, `0.8` | |
| `600`, `1000`, `0.7` | |
| `800`, `800`, `0.9` | |
| `500`, `900`, `1` | |
| `700`, `1200`, `0.6` | |
| `200`, `250`, `0.3` | |
[Answer]
# [Haskell](https://www.haskell.org/), 131 bytes
```
f=fromIntegral
u=unwords.map show
a%b|a>b=(a-b)%b|1<2=a
(r#c)s="P2":u[c,r,99]:[u[round$f j%(f i**s)/f r**s*99|j<-[1..c]]|i<-[1..r]]
```
[Try it online!](https://tio.run/##Jc27CoMwGEDh3acIXiARTVUoqJjuhRYKHSVDvKRqNcofg4vvboVO59tOJ/S3HcfjkEzCPN3V2n5AjJZhRm0zNJpOYkG6mzdLeNUubhXDIqzI6bhImLAwODXRzH4ldm7KOoAgy3hemhJmoxpXosHDEvW@r8lFIjjrZ9k@FGEZU1pzvvd/AufHJHrFzt8TLWZ9r/BQyEX4GjlpRCKaHj8 "Haskell – Try It Online")
`(r#c)s` returns the lines of a PGM file.
After writing it like this, I learned I could probably just return a matrix of float values but I don't think that's very interesting.
[](https://i.stack.imgur.com/gHlbo.png)
[Answer]
# [J](http://jsoftware.com/), 51 bytes
```
load'viewmat'
1 :'[:viewmat(|~^&u)"0~/&(1+i.)%u^~['
```
[Try it online!](https://tio.run/##y/r/Pyc/MUW9LDO1PDexRJ3LUMFKPdoKytWoqYtTK9VUMqjTV9Mw1M7U01QtjauLVv//HwA "J – Try It Online")
A J adverb, which uses the library function `viewmat` to do all the heavy lifting -- we merely need to construct the matrix values.
Assuming the adverb has been assigned to `f`, called like:
```
500 (0.8 f) 800
```
## 500 800 0.8
[](https://i.stack.imgur.com/x8dqZ.jpg)
## 200 250 0.3
[](https://i.stack.imgur.com/JcHKg.jpg)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
```
sImage@Array[Mod[#2,#^s]&,{##}]/#^s&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v/j9pIWeuYnpqQ6ORUWJldG@@SnRykY6ynHFsWo61crKtbH6QLba/4CizLwSh7RoAz2L2GhTAwMdCwOD2P8A "Wolfram Language (Mathematica) – Try It Online")
Input `[s][R, C]`.
[](https://i.stack.imgur.com/XQRf5.png)
[Answer]
# [K (oK) + `iKe`](https://github.com/JohnEarnest/ok), 61 bytes
```
{w::y;h::x;p::pow[;z];,(;gray;+_255*((p 1+!h)!\:/:1+!w)%p w)}
```
[Try it online!](https://johnearnest.github.io/ok/ike/ike.html?key=xhQWqes_)
Shortened heavily and made to work with the help of JohnE and coltim at [the k tree.](https://chat.stackexchange.com/rooms/90748/the-k-tree)
A function which takes input as `R, C, s`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~116~~ ~~114~~118 bytes
-2 thanks to some basic pointers from hyper-neutrino
+4 to correct an off-by-one error, thanks Tipping Octopus
```
from matplotlib.pylab import*
def M(R,C,s):
imshow([[j%i**s/R**s for j in range(1,C+1)]for i in range(1,R+1)]);show()
```
Fairly straightforward, my first code golf attempt so I may be missing something easily golfable. Executes nested list comprehension inside the imshow() to immediately create image. Needs the show() to actually display the image.
## 700, 1200, 0.6
[](https://i.stack.imgur.com/RVkqV.png)
[Answer]
# JavaScript + HTML, 156 bytes
```
(R,C,s)=>{for((w=x=>document.write(x))`<table cellspacing=0>`,i=0;i++<R;)for(w`<tr>`,j=0;j<C;)w(`<td bgcolor=#${((++j%i**s*16/R**s|0)*273).toString(16)}>`)}
```
* -7 bytes by Shaggy
```
; (function run() {
f=
(R,C,s)=>{for((w=x=>document.write(x))`<table cellspacing=0>`,i=0;i++<R;)for(w`<tr>`,j=0;j<C;)w(`<td bgcolor=#${((++j%i**s*16/R**s|0)*273).toString(16)}>`)}
R = /*R{*/500/*}*/;
C = /*C{*/800/*}*/;
s = /*s{*/0.8/*}*/;
document.write(`
<div style="margin-bottom: 10px;">
<label> R = <input id="inputR" type="number" step="1" value="${R}" oninput="UpdateJS()" /></label><br />
<label> C = <input id="inputC" type="number" step="1" value="${C}" oninput="UpdateJS()" /></label><br />
<label> s = <input id="inputS" type="number" step="0.01" value="${s}" oninput="UpdateJS()" /></label><br />
<form action="${location.href}" method="post">
<input id="inputJs" type="hidden" name="js" />
<input type="hidden" name="css" />
<input type="hidden" name="html" />
<input type="hidden" name="console" value="false" />
<input type="hidden" name="babel" value="false" />
<button type="submit">Draw</button>
</form>
</div>
`)
f(R, C, s);
UpdateJS = function () {
R = inputR.value;
C = inputC.value;
s = inputS.value;
js = `; (${run}());`
.replace(/\/\*R\{\*\/.*?\/\*\}\*\//, `/*R{*/${R}/*}*/`)
.replace(/\/\*C\{\*\/.*?\/\*\}\*\//, `/*C{*/${C}/*}*/`)
.replace(/\/\*s\{\*\/.*?\/\*\}\*\//, `/*s{*/${s}/*}*/`);
inputJs.value = js;
};
UpdateJS();
}());
```
[Answer]
# [R](https://www.r-project.org/), 66 bytes
```
function(R,C,s)cat('P2',C,R,99,(99*outer(1:C,(1:R)^s,`%%`))%/%R^s)
```
[Try it online!](https://tio.run/##K/pfkJNfmp6RmhKflpmak2L7P600L7kkMz9PI0jHWadYMzmxREM9wEgdyAnSsbTU0bC01MovLUkt0jC0ctYBEkGaccU6CaqqCZqaqvqqQXHFmmhGapgaGOhYALGeheZ/AA "R – Try It Online")
I kinda think that [pajonk's answer](https://codegolf.stackexchange.com/a/231106/95126) is close to the shortest possible using [R](https://www.r-project.org/)'s built-in graphics... so here's a completely different approach, which actually turns-out to be 4 bytes shorter...
Outputs the contents of a greyscale [PGM file](https://en.wikipedia.org/wiki/Netpbm#PGM_example). At least on my laptop using Apple's 'Preview' program, the newline characters separating lines appear to be superfluous.
Here's Preview's display of the the output of `ploughed_field(500,800,.8)`:
[](https://i.stack.imgur.com/cGvef.png)
[Answer]
# Python 3, 90 73 bytes
```
from pylab import*;ion()
def M(R,C,s):imshow(-~r_[:C]%c_[1:R+1]**s/R**s)
```
Heavily based on Danica's answer, I would have commented but I have 0 reputation.
Shorter import statement
`ion()` to show instead of `;show()`
`arange` (from `numpy.arange`) array approach for faster performance and fewer bytes
remove def function indent
```
from pylab import*
ion()
def M(R,C,s):imshow((arange(C)+1)%(arange(R)+1)[:,None]**s/R**s)
```
Thanks to ovs this shortens to 74 bytes
And a `-~` trick removes 1 byte from `r_[1:C+1]`
[Answer]
# [R](https://www.r-project.org/), ~~84~~ 70 bytes
*-14 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*
```
function(R,C,s)image(outer(1:C,(R:1)^s,`%%`)/R^s,c=rainbow(64),as=R/C)
```
[Try it online!](https://tio.run/##DcZLCoAgEADQ0wgzMKRCRQiuvIEHiEwyXKTgh45vLR68MoIeoSffYk5gyVDF@Lj7gtzbVUAqQ2CVxL3SwdiB3P7zuriYzvzCOiO5qi03OAIsQtD2E9OG4wM "R – Try It Online")
[Try it on rdrr.io with graphical output](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(R%2CC%2Cs)image(outer(1%3AC%2C(R%3A1)%5Es%2C%60%25%25%60)%2FR%5Es%2Cc%3Drainbow(64)%2Cas%3DR%2FC)%0Af(500%2C800%2C0.8))
[Answer]
# [Red](http://www.red-lang.org), 137 bytes
```
func[r c s][i: make image! to[]as-pair c r k: 0
repeat y r[repeat x c[i/(k: k + 1): to 1.1.1 to[](to 1 x %(y ** s)/(r ** s)* 255)]]?(i)]
```
`f 500 800 0.8`
[](https://i.stack.imgur.com/JFB48.png)
] |
[Question]
[
Output either the text below, or a list of lists of integers (more details below).
```
0
10 1
20 11 2
30 21 12 3
40 31 22 13 4
50 41 32 23 14 5
60 51 42 33 24 15 6
70 61 52 43 34 25 16 7
80 71 62 53 44 35 26 17 8
90 81 72 63 54 45 36 27 18 9
91 82 73 64 55 46 37 28 19
92 83 74 65 56 47 38 29
93 84 75 66 57 48 39
94 85 76 67 58 49
95 86 77 68 59
96 87 78 69
97 88 79
98 89
99
```
## Rules
* If you wish, you may "one index" and replace each `n` with `n+1`. In this case the output will contain the numbers 1 to 100 inclusive.
### If output is text
* The single digits are right aligned in each column in the text provided, but it is fine if you wish to left align. Additionally, alignment is not required to be consistent between columns.
* Leading/trailing whitespace is permitted. Trailing spaces on each line are also permitted.
* Returning a list of lines is acceptable.
### If output is numerical
* Output can be a list of lists of integers (or 2D array): `[[1], [11, 2], [21...`
* Floats are fine.
* If it is not possible to have nonrectangular array in the language used, then the elements in the array that aren't within the triangle can take any value and will be ignored.
If you prefer another format, feel free to ask.
Shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12 10~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-4 thanks to Dennis, yes FOUR! (use of group indices and Cartesian product)
```
⁵pḅ1ĠU
```
Uses 1-indexing and the list option for output.
**[Try it online!](https://tio.run/##ARsA5P9qZWxsef//4oG1cOG4hTHEoFX/wqLFkuG5mP8 "Jelly – Try It Online")** (The footer formats the output in Python representation)
...or see a [0-indexed, formatted version](https://tio.run/##y0rNyan8//9R49aChztaDY8sCP1/aNGjhpnu/wE "Jelly – Try It Online").
### How?
```
⁵pḅ1ĠU - Main link: no arguments
⁵ - literal 10
p - Cartesian product (with the leading constant of 10 and implicit ranges)
- = [[1,1],[1,2],[1,3],...,[10,8],[10,9],[10,10]]
ḅ1 - to base one (proxy for sum each without the monad)
- = [2,3,4,5,6,7,8,9,10,11,3,4,5,6,7,8,9,10,11,12,4,...,18,19,20]
Ġ - group indices by value
- = [[1],[2,11],[3,12,21],...,[90,99],[100]]
U - upend = [[1],[11,2],[21,12,3],...,[99,90],[100]]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
k=1
exec"print range(k,0,-9)[:101-k];k+=10-k/91*9;"*19
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9vWkCu1IjVZqaAoM69EoSgxLz1VI1vHQEfXUjPaytDAUDc71jpb29bQQDdb39JQy9JaScvQ8v9/AA "Python 2 – Try It Online")
(1-indexed, because `range(k,0,-9)` is shorter than `range(k,-1,-9)`.)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 20 bytes
```
E¹⁹⪫I⮌Φ¹⁰⁰⁼ι⁺÷λχ﹪λχ
```
[Try it online!](https://tio.run/##LcdJCgJBDEDRq4ReRYhQtRSXDqDQ0HiD0B0wEKq0putHBf/m8dcnlzWzuS9FU8OZXxgPBPesCU9cGz5kSKmCV7UmBWMIBJd3Z6uoBIv1irfUzjp0EzSCGHYEc9665f/@Iphg@np09/2wDw "Charcoal – Try It Online") Link is to verbose version of code. Note: trailing space. Explanation:
```
¹⁹ Literal 19
E Map over implicit range
¹⁰⁰ Literal 100
Φ Filter over implicit range
λ λ Inner index
χ χ Predefined variable 10
﹪ Modulo
÷ Integer divide
⁺ Sum
ι Outer index
⁼ Equals
⮌ Reverse
I Cast to string
⪫ Join with spaces
Implicitly print each string on its own line
```
[Answer]
# JavaScript (ES6), 61 bytes
0-based. Returns a string.
```
f=(k=n=0)=>k>98?k:k+((k-=9)%10>0?' '+f(k):`
`+f(n+=n>89||10))
```
[Try it online!](https://tio.run/##DchBDkAwEADAu1e4SHfTkLqpZOsrFVRY2YqKk7@X22T28RnTdG3nXUucl5wDAZOQQXLsbDdwzxqAa7JYtcaZQZVKB2DsfeF/iCZxnX3f1iDmKUqKx9IccYUAf3w "JavaScript (Node.js) – Try It Online")
### How?
We start with **k = n = 0** and stop when **k = 99**. We subtract **9** from **k** at each iteration.
End of rows are detected with `k % 10 <= 0`. This condition is fulfilled if:
* **k** is negative (upper part of the pyramid) because the sign of the modulo in JS is that of the dividend.
```
0 (-9)
10 1 (-8)
20 11 2 (-7)
```
* *or* **k % 10 == 0** (lower part of the pyramid)
```
90 81 72 63 54 45 36 27 18 9 (0)
91 82 73 64 55 46 37 28 19 (10)
92 83 74 65 56 47 38 29 (20)
```
At the beginning of the next row, we add either **1** or **10** to **n** and restart from there.
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
r=range
for a in r(0,90,10)+r(90,100):print r(a,a/10+a%10*10-1,-9)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPZUrLb9IIVEhM0@hSMNAx9JAx9BAU7tIA8ww0LQqKMrMKwFKJeok6hsaaCeqGhpoGRroGuroWmr@/w8A "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
,.<@|./.i.,~10
```
[Try it online!](https://tio.run/##y/pflFiuYGulYKAAwrp6Cs5BPm7/dfRsHGr09PUy9XTqDA3@a3KlJmfkKyjpARX/BwA "J – Try It Online")
## Note:
This solution uses boxed output - I'm not sure if it's allowed (I hope it is, because lists of integers are also allowed)
## Alternative:
# [J](http://jsoftware.com/), 10 bytes
```
|./.i.,~10
```
In this solution the numbers outside the triangular area are displayed as `0`
[Try it online!](https://tio.run/##y/pflFiuYGulYKAAwrp6Cs5BPm7/a/T09TL1dOoMDf5rcqUmZ@QrKOkBFf4HAA "J – Try It Online")
## Explanation:
`i.,~10` creates a matrix 10x10 of the numbers 0..99 `,~10` is short for `10 10`
```
i.,~10
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
```
`/.` finds the oblique diagonals (antidiagonals) of the matrix
```
]/.i.,~10
0 0 0 0 0 0 0 0 0 0
1 10 0 0 0 0 0 0 0 0
2 11 20 0 0 0 0 0 0 0
3 12 21 30 0 0 0 0 0 0
4 13 22 31 40 0 0 0 0 0
5 14 23 32 41 50 0 0 0 0
6 15 24 33 42 51 60 0 0 0
7 16 25 34 43 52 61 70 0 0
8 17 26 35 44 53 62 71 80 0
9 18 27 36 45 54 63 72 81 90
19 28 37 46 55 64 73 82 91 0
29 38 47 56 65 74 83 92 0 0
39 48 57 66 75 84 93 0 0 0
49 58 67 76 85 94 0 0 0 0
59 68 77 86 95 0 0 0 0 0
69 78 87 96 0 0 0 0 0 0
79 88 97 0 0 0 0 0 0 0
89 98 0 0 0 0 0 0 0 0
99 0 0 0 0 0 0 0 0 0
```
Using `]` (same) pads all lines with `0`s. Each line is reversed. In order to get rid of the zeroes I box the lines `<` after they are reversed `|.`
```
<@|./.i.,~10
┌─┬────┬───────┬──────────┬─────────────┬────────────────┬
│0│10 1│20 11 2│30 21 12 3│40 31 22 13 4│50 41 32 23 14 5│. . .
└─┴────┴───────┴──────────┴─────────────┴────────────────┴
```
Boxing makes the list of lists to be flatten. I finally ravel `,.` the list so that the lines are ordered in a column.
```
,.<@|./.i.,~10
┌────────────────────────────┐
│0 │
├────────────────────────────┤
│10 1 │
├────────────────────────────┤
│20 11 2 │
├────────────────────────────┤
│30 21 12 3 │
├────────────────────────────┤
│40 31 22 13 4 │
├────────────────────────────┤
│50 41 32 23 14 5 │
├────────────────────────────┤
│60 51 42 33 24 15 6 │
├────────────────────────────┤
│70 61 52 43 34 25 16 7 │
├────────────────────────────┤
│80 71 62 53 44 35 26 17 8 │
├────────────────────────────┤
│90 81 72 63 54 45 36 27 18 9│
├────────────────────────────┤
│91 82 73 64 55 46 37 28 19 │
├────────────────────────────┤
│92 83 74 65 56 47 38 29 │
├────────────────────────────┤
│93 84 75 66 57 48 39 │
├────────────────────────────┤
│94 85 76 67 58 49 │
├────────────────────────────┤
│95 86 77 68 59 │
├────────────────────────────┤
│96 87 78 69 │
├────────────────────────────┤
│97 88 79 │
├────────────────────────────┤
│98 89 │
├────────────────────────────┤
│99 │
└────────────────────────────┘
```
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/) (no external utilities), 66
```
eval a={{9..1},}\;b={9..0}';c[a+b]+=$a$b\ '
printf %s\\n "${c[@]}"
```
[Try it online!](https://tio.run/##S0oszvj/P7UsMUch0ba62lJPz7BWpzbGOskWxDaoVbdOjk7UTorVtlVJVEmKUVDnKijKzCtJU1AtjonJU1BSqU6OdoitVfr/HwA "Bash – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
V19fqssM`TN_U100
```
[Try it online!](https://tio.run/##K6gsyfj/P8zQMq2wuNg3IcQvPtTQwOD/fwA)
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 24 bytes
```
0D9FlF{a+|lD|9F~lF{P|D|;
```
[Try it online!](https://tio.run/##S8/PScsszvj/38DF0i3HrTpRuybHpcbSrQ7IDqhxqbH@/x8A "Gol><> – Try It Online")
The output looks like this:
```
[0]
[10 1]
[20 11 2]
[30 21 12 3]
[40 31 22 13 4]
[50 41 32 23 14 5]
[60 51 42 33 24 15 6]
[70 61 52 43 34 25 16 7]
[80 71 62 53 44 35 26 17 8]
[90 81 72 63 54 45 36 27 18 9]
[91 82 73 64 55 46 37 28 19]
[92 83 74 65 56 47 38 29]
[93 84 75 66 57 48 39]
[94 85 76 67 58 49]
[95 86 77 68 59]
[96 87 78 69]
[97 88 79]
[98 89]
[99]
```
### How it works
```
0D9FlF{a+|lD|9F~lF{P|D|;
0D Push 0 and print stack
9F | Repeat 9 times...
lF{a+| Add 10 to all numbers on the stack
l Push stack length (the last one-digit number)
D Print stack
9F | Repeat 9 times...
~ Discard the top
lF{P| Increment all numbers on the stack
D Print stack
; Halt
```
[Answer]
# [R](https://www.r-project.org/), ~~50~~ 48 bytes
```
split(y<-rev(order(x<-outer(0:9,0:9,"+"))),x[y])
```
[Try it online!](https://tio.run/##K/r/v7ggJ7NEo9JGtyi1TCO/KCW1SKPCRje/tATIMLCy1AFhJW0lTU1NnYroyljN//8B "R – Try It Online")
1-indexed. Follows the same logic as Jonathan Allan's [Jelly answer](https://codegolf.stackexchange.com/a/163515/78274), so make sure to upvote him.
As a bonus, here is also an implementation of standard looping approach (0-indexed). Here, I at least tried to make the output prettier (thus, didn't even save bytes for `print` instead of `cat(...,"\n")` to get rid of annoying `[1]`s in the console.
# [R](https://www.r-project.org/), ~~66~~ 59 bytes
```
for(i in c(0:8*10,90:99))cat(seq(i,i/10+i%%10*10-1,-9),"
")
```
[Try it online!](https://tio.run/##K/r/Py2/SCNTITNPIVnDwMpCy9BAx9LAytJSUzM5sUSjOLVQI1MnU9/QQDtTVdXQACita6ija6mpo8SlpPn/PwA "R – Try It Online")
Edit: -2 and -7 both thanks to Giuseppe.
[Answer]
# [R](https://www.r-project.org/), ~~137 86 73~~ 69 bytes
```
for(u in 0:18)cat("if"(u>9,seq(81+u,10*u-81,-9),seq(10*u,u,-9)),"\n")
```
[Try it online!](https://tio.run/##K/r/Py2/SKNUITNPwcDK0EIzObFEQykzTUmj1M5Spzi1UMPCULtUx9BAq1TXwlBH11ITLAji65SCuJo6SjF5Spr//wMA "R – Try It Online")
Previous golfed version, %100 credits to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).
```
S=sapply
c(S(1:10,function(u)1:u-1+10*(u-1:u)),S(9:1,function(y)1:y+9-y+10*(y:1+9-y)))
```
[Try it online!](https://tio.run/##K/r/P9i2OLGgIKeSK1kjWMPQytBAJ600L7kkMz9Po1TT0KpU11Db0EBLA0hblWpq6gRrWFoZIpRUApVUalvqVoIVVVoZgtiampr//wMA "R – Try It Online")
Below my first attempt at Codegolf keeping it just for the record.
```
x<-c(1:10)
z<- c(9:1)
c(sapply(x,function(u) seq_len(u)-1+10*(u-seq_len(u))),sapply(z,function(y) seq_len(y)+9-y+10*rev(seq_len(y)+9-y)))
```
[Try it online!](https://tio.run/##VctNCoAgEEDhfadoOVMNOEuju0SIQSBmP0Z6eUsIpN3jwbendA@kgHsWWMWBagWyZ6wUHJNzJsDdzd6qc1kteKwPvY1G5yRuWTTgqSzE7kOxoFBQwFZSyGzXF/zvi1N6AA "R – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~67~~ ~~66~~ ~~65~~ 64 bytes
```
for i=0:8disp(10*i:-9:0)end,for i=0:9disp(90+i:-9:11*i+(i<1))end
```
[Try it online!](https://tio.run/##y08uSSxL/f8/Lb9IIdPWwMoiJbO4QMPQQCvTStfSykAzNS9FByZnCZazNNAGyxkaamVqa2TaGGqCFP3/DwA "Octave – Try It Online")
Those missing semicolons hurt my eyes!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
TLûvTLD>T*«NèyGD9+})R,
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/xOfw7rIQHxe7EK1Dq/0Or6h0d7HUrtUM0vn/HwA "05AB1E – Try It Online")
---
Super Naive Approach: [Try it online!](https://tio.run/##MzBNTDJM/f8/xMfl8KL//wE "05AB1E – Try It Online") may be a better solution but I can't figure out how to get from A to B.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 77 bytes
```
(0..90|?{!($_%10)})+91..99|%{"$(for($i=$_;$i-gt$_/10+$_%10*10-1;$i-=9){$i})"}
```
[Try it online!](https://tio.run/##HcpLCoAgEADQsyQjOEU1s5SQjuLKShAMC1qYZ7fP9vH2eLl0bC6EWhUNg6Z7zo0CK5mwYKf5NX3LLEAtMSnwBuwEvl9PsCNT98@WqedPjcYMvqAotT4 "PowerShell – Try It Online")
Outputs as ASCII-art with the single-digits left-aligned. Exploits the fact that stringifying an array inserts spaces between elements by default.
Very similar to Rod's Python answer, apparently, but developed independently.
[Answer]
# JavaScript, 69 bytes
```
f=(i=e=[])=>e[i<19&&(e[+i]=[]),i/10+i%10|0].unshift(+i)*i++-99?f(i):e
```
[Try it online!](https://tio.run/##FchBDsIgEAXQ09jMOLbCEiP2IIRFUwf9poFGalfeHeNbvte0T3V@Y936XO7aWvIErz5E9jcNuFrXdaRBEP93wtkawcGar4nDJ9cn0kYCPkKkd25MBL5om0uuZdFhKQ9KxNx@ "JavaScript (Node.js) – Try It Online")
# JavaScript REPL, 77 bytes
```
[...Array(100)].map((_,i)=>e[i<19&&(e[i]=[]),i/10+i%10|0].unshift(i),e=[])&&e
```
[Answer]
# [Perl 5](https://www.perl.org/), 62 bytes
```
$,=$";say@,=map$_+=10,@,,$_ for-9..0;say map++$_,@,while pop@,
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybo4sdJBxzY3sUAlXtvW0EDHQUdHJV4hLb9I11JPzwAkrQCU1NZWiQdKlWdk5qQqFOQXOOj8//8vv6AkMz@v@L@ur6megaEBAA "Perl 5 – Try It Online")
1-indexed to save a couple bytes
[Answer]
# [Ruby](https://www.ruby-lang.org/), 58 bytes
```
0.step(180,10){|x|p x.step(0,-9).select{|y|y<100&&y>x-90}}
```
[Try it online!](https://tio.run/##KypNqvz/30CvuCS1QMPQwkDH0ECzuqaipkChAiJmoKNrqalXnJqTmlxSXVNZU2ljaGCgplZpV6FraVBb@/8/AA "Ruby – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 105, 95 91 bytes
```
v: make vector! 0
loop 10[alter v + 10 length? v print v]loop 9[alter v last v print 1 + v]
```
[Try it online!](https://tio.run/##PYsxDoAgDAB3X1FnFxh18Q@uhIFIo8YKBJt@vxIHxsvdVYy6YXReZYEn3AiCO@c6ghko5wLWuECMFQSmBkCYDj7XhqVeiUH8n829ovByt7ZN4lU/ "Red – Try It Online")
## Explanation:
```
v: make vector! 0 ; start with a vector with one element: -10
loop 10[alter v + 10 length? v print v] ; Ten times print the vector after adding 10
; to its elements and appending the length
loop 9[alter v last v print 1 + v] ; Nine times print the vector after adding 1
; to its elements and removing the last one
; `alter` appends the item if it's not
; in the list, otherwise removes it
```
[Answer]
# [JavaScript](https://nodejs.org), 112 bytes
Not that optimal, but I wanted to try a different approach.
```
[...Array(19)].map((x,y)=>y>9?81+y:y?y+'0':y).map(x=>(f=(n,a=[n])=>!n|a[n+='']|n[1]>8?a:f(n-=9,a.concat(n)))(x))
```
[Try it online!](https://tio.run/##NYxBCoMwEEX3PUW7ygxqqDsVEunGS4SAg9VisRNRKQl491RauvuP9/hPetPaLeO8ZezufWxUNFLK27JQgLxEK180A/g0oNJBl3WRJ6EKdUjEVVQBv9orDYMCTkkZtkd44Z0MJ0oIu7PJrS5qqgbgTJUpyc5xRxswIoJHjAevburl5B7Q/A@9fLqR23OLv3FqMX4A "JavaScript (Node.js) – Try It Online")
Old Solution:
```
[...Array(19)].map((x,y)=>y>9?y-9+'9':y).map((x,y)=>(f=(n,a=[n])=>a[n/10]|!n?a.reverse():a.push(n+=9)&&f(n,a))(x*1).slice(y-19))
```
[Try it online!](https://tio.run/##TY3BDoIwEAXvfoVeYFdglWNJCvHCTxASGqwKwZa0StrEf6@oF2/zMnmZUSzC9maYH5nSZxlqHhoiOhkjPOQMW7qLGcClHnnpS1b5jCUxiwuP/wYuHFQqeKPadYlGHfJj@9qpSpCRizRWAhaC5qe9gUo4wyi6fA6I4PY5kp2GXoLP1iKGXiurJ0mTvkL9rTheOhr1oLpthz/YdBje "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
тL<ΣTLãOsè}TLû£í
```
[Try it online!](https://tio.run/##MzBNTDJM/f//YpOPzbnFIT6HF/sXH15RC2TsPrT48Nr//wE "05AB1E – Try It Online")
**Explanation**
```
тL<Σ } # sort the values in [0 ... 99] by
sè # the value at that index in
O # the sum of
ã # the cartesian product of
TL # the range [1 ... 10]
£ # split the result into pieces of sizes
TLû # [1,2,...,9,10,9,...2,1]
í # and reverse each
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~43~~ 40 bytes
```
{map {[R,] grep :k,$_,(^10 X+ ^10)},^19}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjexQKE6OkgnViG9KLVAwSpbRyVeRyPO0EAhQlsBSGnW6sQZWtb@L06sVEjT0LT@DwA "Perl 6 – Try It Online")
-3 bytes thanks to Brad Gilbert b2gills.
] |
[Question]
[
# Definitions
* A subsequence may not be contiguous, e.g. `[1, 1, 1]` is a subsequence of `[1, 2, 1, 2, 1]`.
* An equal subsequence is a subsequence in which every element is equal.
* The longest equal subsequence may not be unique, e.g. `[1, 1]` and `[2, 2]` are both longest equal subsequences of `[2, 1, 1, 2]`.
# Input
A non-empty list of positive integers in one of the format below:
* as the native implementation of an array of positive integers in your language
* as a string of newline-separated integers in decimal
* as a string of newline-separated integers in unary
* any other reasonable formats
# Output
All of the longest equal subsequences in any order in one of the formats below:
* as a 2D nested array in your language (if the input is an array)
* as a flattened array with the equal elements being contiguous
* any other reasonable format
# Scoring
Although we are looking for something long, the code used should be as short as possible in terms of number of bytes, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
# Testcases
Inputs:
```
[1, 2, 3]
[1, 2, 2, 1]
[1, 2, 3, 2, 1]
[1, 2, 1, 2, 3, 4, 1]
```
Outputs:
```
[[1], [2], [3]]
[[1, 1], [2, 2]]
[[1, 1], [2, 2]]
[[1, 1, 1]]
```
Note that for the outputs above, any order is valid.
A flattened array is also valid, as long as the equal elements are contiguous.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ĠLÐṀị
```
[Try it online!](https://tio.run/nexus/jelly#@39kgc/hCQ93Njzc3f3/cPujpjVHJz3cOQNIR/7/H82lEG2oo2Cko2AcqwNnA5EhEtcYQwQubgIS54oFAA "Jelly – TIO Nexus")
### How it works
```
ĠLÐṀị Main link. Argument: A (array)
Ġ Group; partition the indices of A by their corresponding values.
LÐṀ Select all index arrays with maximal length.
ị Unindex; retrieve the items of A at the specified indices.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
⊇ᶠ=ˢlᵍh
```
[Try it online!](https://tio.run/nexus/brachylog2#@/@oq/3htgW2pxflPNzam/H/f7ShjoKJjoIRmDQGMwxj/0cBAA "Brachylog – TIO Nexus")
## Explanation
```
⊇ᶠ=ˢlᵍh
⊇ᶠ Find all subsequences
=ˢ Keeping only those for which all elements are equal
lᵍ Group by length
h Take the first group
```
`⊇`'s natural order generates the longest subsequences first, so those are the ones that end up in the first group.
[Answer]
# Pyth, 5 bytes
```
S.M/Q
```
[Test suite](https://pyth.herokuapp.com/?code=S.M%2FQ&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%5D%0A%5B1%2C+2%2C+2%2C+1%5D%0A%5B1%2C+2%2C+3%2C+2%2C+1%5D%0A%5B1%2C+2%2C+1%2C+2%2C+3%2C+4%2C+1%5D&debug=0)
Explanation:
This is implicitly `S.M/QZQ`. `.M` is the maximal function, so `.M/QZQ` selects all elements where the value of `/QZ`, count the number of occurrences of the element in the input, is maximal. `S` then sorts the list so that identical elements are contiguous.
[Answer]
## bash, 66 bytes
```
sort|uniq -c|sort -rn|awk 'NR==1{a=$1}$1==a{for(i=a;i--;)print$2}'
```
This seems like it should be way shorter, but I can't figure out how.
```
sort # sort the input
|uniq -c # group runs of identical lines and prefix with count
|sort -rn # sort by count, with largest at top
|awk ' # pipe to awk...
NR==1{a=$1} # on the first line, set the variable "a" to field 1
$1==a{ # on any line, if first field is a (max count)...
for(i=a;i--;) # a times...
print$2 # print the second field
}
'
```
[Try it online!](https://tio.run/nexus/bash#@1@cX1RSU5qXWaigm1wD4ijoFuXVJJZnK6j7BdnaGlYn2qoY1qoY2tomVqflF2lk2iZaZ@rqWmsWFGXmlagY1ar//2/IZcRlDMSGAA)
Thanks to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) for 3 bytes!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~68~~ 63 bytes
```
lambda x:sorted(n for n in x if x.count(n)/max(map(x.count,x)))
```
[Try it online!](https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqFBhVZxfVJKaopGnkJZfpJCnkJmnUKGQmaZQoZecX5pXopGnqZ@bWKGRm1igARXSqdDU1PxfUJSZV6KQphFtqKNgpKNgHKvJhSYERIaYosa4JODSJmDp/wA "Python 2 – TIO Nexus")
[Answer]
# Mathematica, ~~42~~ ~~31~~ 25 bytes
*Thanks @GregMartin for 5 bytes and @MartinEnder for another byte!*
```
MaximalBy[Length]@*Gather
```
## Explanation
```
MaximalBy[Length]@*Gather (* {1, 2, 3, 2, 1} *)
Gather (* Gather same numbers: {{1, 1}, {2, 2}, {3}} *)
@* (* Function composition *)
MaximalBy[Length] (* Find longest: {{1, 1}, {2, 2}} *)
```
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), ~~55~~ ~~52~~ 43 bytes
```
sorted rle toarr:[1#]map MAX@K[1#K=]YES rld
```
[Try it online!](https://tio.run/nexus/stacked#09AwVDBSMNZUANNGCoZQljESG8I3AfI1FaoV8/4X5xeVpKYoFOWkKpTkJxYVWUUbKsfmJhYo@DpGOHgDOd62sZGuwUAFKf/zFIpSC4oUCkpLFNQVbO2ABIgJFssHMmoVgPr@AwA "Stacked – TIO Nexus")
Works by run-length encoding the input, sorting by occurrences, keeping occurances for which the number of occurrences is maximal, and run length decoding. Outputs through a flat list, as is acceptable by the challenge.
[Answer]
# [Actually](https://github.com/Mego/Seriously), 23 bytes
```
;╗⌠;╜ck⌡M;♂NM╗⌠N╜=⌡░♂FS
```
[Try it online](https://tio.run/nexus/actually#@2/9aOr0Rz0LgNSc5OxHPQt9rR/NbPLzhYj6AUVtgYKPpk0EiroFA7kOj6au@v8/2lBHwUhHwRhMGsYCAA "Actually – TIO Nexus"), or [run all test cases](https://tio.run/nexus/actually#e9Sz4L/1o6nTH/UsAFJzkrMf9Sz0tX40s8nPFyLqBxS1BQo@mjYRKOoW/B@kIPN/dLShjoKRjoJxrI4ClAlEhgieMboAXNgEJBwLAA "Actually - TIO Nexus")!
Thanks to Leaky Nun for pointing out a one-byte improvement that really should've been obvious to me
-3 bytes from relaxed output format
Explanation:
```
;╗⌠;╜ck⌡M;♂NM╗⌠N╜=⌡░♂FS
;╗ save a copy of the input to register 0
⌠;╜ck⌡M for each value in the input list:
; make a copy on the stack
╜c count the occurrences in the input list (from register 0)
k make a list: [value, count]
;♂N make a copy, take last value of each list in the 2D list
M╗ store the maximum count in register 0
⌠N╜=⌡░ filter the other copy of the list of [value, count] lists:
N╜= take items where the count equals the maximum count
♂FS take first items (values) and sort them
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 18 bytes
```
{x{b=|/b:#'x}#.=x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6quqE6yrdFPslJWr6hV1rOtqOXi0khLyLLXVFdQiskDYqVoQx0FIx0F41guBSgTiAwRPGN0AbiwCUhYCQD8oxYl)
[Answer]
# Python 2, 138 bytes
```
lambda l:[[x[0]]*x[1] for x in next(__import__('itertools').groupby(__import__('collections').Counter(l).most_common(),lambda x:x[1]))[1]]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
3#XMg1bX"&
```
[Try it online!](https://tio.run/nexus/matl#@2@sHOGbbpgUoaT2/3@0oYGOghEQG0NpQ4NYAA "MATL – TIO Nexus")
### Explanation
Similar to my Octave answer. Consider input `[10, 20, 30, 20, 10]` as an example.
```
3#XM % Three-output version of mode function. Gives the first mode, the
% number of repetitions, and a cell array with all modes
% STACK: 10, 2, {10; 20}
g % Convert from cell array to matrix
% STACK: 10, 2, [10; 20]
1 % Push 1
% STACK: 10, 2, [10; 20], 1
b % Bubble up in the stack
% STACK: 10, [10; 20], 1, 2
X" % Repeat those number of times vertically and horizontally
% STACK: 10, [10, 10; 20, 20]
& % Specify that implicit display will show only the top of the stack.
% Since this is singleton cell array that contains a matrix, that
% matrix is directly displayed
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 47 bytes
```
[~,b,c]=mode(input(0));disp([repmat(c,1,b){:}])
```
[Try it online!](https://tio.run/nexus/octave#@x9dp5Okkxxrm5ufkqqRmVdQWqJhoKlpnZJZXKARXZRakJtYopGsY6iTpFltVRur@f9/tKGOgpGOgjGYNIwFAA "Octave – TIO Nexus")
### Explanation
The second and third outputs of `mode` (obtained as `[~,b,c]=mode(...)`) respectively give the number of repetitions (`b`) and a column cell array (`c`) of the most repeated elements in the input (`input(0)`) . The cell array `c` is then repeated horizontally `b` times (`repmat(c,1,b)`), converted to a comma-separated list (`{:}`) and contatenated horizontally (`[...]`) to give a numeric matrix, which is displayed (`disp(...)`).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 5 bytes
Outputs a flat list in order
```
.M¹Ã{
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@6/ne2jn4ebq//@jDXUUjHQUIKSxjoIJkB0LAA "05AB1E – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 22 bytes
```
{$e`z~\__:e>f=.*\]ze~}
```
This is an anonymous block (function) that takes the input from the top of the stack and repaces it with the output. The output is a flattened array withequal elements being contiguous.
[Try it online!](https://tio.run/nexus/cjam#izZUMFIwBmLD2P/VKqkJVXUx8fFWqXZptnpaMbFVqXW1/@sK/gMA "CJam – TIO Nexus")
### Explanation
Consider input `[10 20 30 20 10 ]` as an example.
```
{ e# Begin block
e# STACK: [10 20 30 20 10]
$ e# Sort
e# STACK: [10 10 20 20 30]
e` e# Run-length encoding
e# STACK: [[2 10] [2 20] [1 30]]
z e# Zip
e# STACK: [[2 2 1] [10 20 30]]
~ e# Dump array contents onto the stack
e# STACK: [2 2 1] [10 20 30]
\ e# Swap
e# STACK: [10 20 30] [2 2 1]
__ e# Duplicate twice
e# STACK: [10 20 30] [2 2 1] [2 2 1] [2 2 1]
:e> e# Fold maximum over array. Gives the maximum of the array
e# STACK: [10 20 30] [2 2 1] [2 2 1] 2
f= e# Map "is equal" with number (2) over the array ([2 2 1])
e# STACK: [10 20 30] [2 2 1] [1 1 0]
.* e# Vectorized multiplication
e# STACK: [10 20 30] [2 2 0]
\ e# Swap
e# STACK: [2 2 0] [10 20 30]
] e# Pack into array
e# STACK: [[2 2 0] [10 20 30]]
z e# Zip
e# STACK: [[2 10] [2 20] [0 30]]
e~ e# Run-length decoding
e# STACK: [10 10 20 20]
} e# End block
```
[Answer]
# Perl 5, 58 bytes
```
sub{sort grep$x{$_}>$m,grep{$/=$x{$_}++;$m=$/if$m<$/;1}@_}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
→kLk=
```
[Try it online!](https://tio.run/##yygtzv7//1HbpGyfbNv///9HG@oY6RgDsWEsAA "Husk – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ü üÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=/CD8yg&input=WzEsIDIsIDMsIDIsIDFdCi1R)
```
ü üÊ :Implicit input of array
ü :Group & sort by value
üÊ :Group & sort by length
:Implicit output of last element
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5 bytes (10 nibbles)
```
/=~=~$$,$@
```
```
/=~=~$$,$@
=~ # group
$ # the input
$ # by its own values,
=~ # now group each of these groups
,$ # by their lengths
# (group of longest groups comes last),
/ # fold over this list-of-lists from right
@ # always returning the second argument
# (so this fold just returns the last item,
# which is the list of the longest groups
# of values)
```
[](https://i.stack.imgur.com/OfzYp.png)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 22 bytes
Requires `⎕ML←3` which is default on many systems.
### Program: `s/⍨(⌈/=⊢)≢¨s←⊂⍨(⍋⊃¨⊂)⎕`
`⎕` get numeric (evaluated) input
`(`…`)` tacit function
`⍋` the indices of ascending items
`⊃¨` each pick from
`⊂` the entire array
`⊂⍨` partition by cutting at its increases
`s←` store as *s*
`≢¨` tally each
`(`…`)` tacit function
`⌈/` the maximum (tally)
`=` equals
`⊢` the argument (the tallies)
`s/⍨` filter *s* with that
### Function: `{s/⍨(⌈/=⊢)≢¨s←⊂⍨⍵[⍋⍵]}`
`{`…`}` anonymous function where argument is `⍵`
`⍵[⍋⍵]` sort (lit. index with indices of ascending items)
`⊂⍨` partition by cutting at its increases
`s←` store as *s*
`≢¨` tally each
`(`…`)` tacit function
`⌈/` the maximum (tally)
`=` equals
`⊢` the argument (the tallies)
`s/⍨` filter *s* with that
[Try it online!](https://tio.run/nexus/apl-dyalog#U9Z71DfV1@dR2wRjrkcd7Wn/i/Uf9a7QeNTToW/7qGuR5qPORYdWFAOlH3U1gSV6ux91NR9aAeRqAnX@B@rhSgdKV@PX96h3azRIa@/W2Nr/aVyGOgpGOgrGXDAWEBnCOcZofLioCUiUKx0mAGeBVacroOqG8VF1AwA "APL (Dyalog Unicode) – TIO Nexus")
[Answer]
# PHP, 69 Bytes
```
<?print_r(preg_grep("#".max($r=array_count_values($_GET))."#",$r));
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/d4708cb38ce9cd4c658637033dbd5d755d584cc3)
## Output Format
key = value , value = count
```
Array
(
[1] => 2
[2] => 2
)
```
## PHP, 96 Bytes
```
<?foreach($_GET as$v)$r[$m[]=count($l=preg_grep("#^{$v}$#",$_GET))][$v]=$l;print_r($r[max($m)]);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/afbc1269ed2cdc2da52e73ce655e42ad924c8bec)
## Output Format
1D Key= value
2D Key = position in the input array for each value
```
Array
(
[1] => Array
(
[0] => 1
[4] => 1
)
[2] => Array
(
[1] => 2
[3] => 2
)
)
```
## PHP, 97 Bytes
```
<?foreach($_GET as$v)$r[count($l=preg_grep("#^{$v}$#",$_GET))][$v]=$l;ksort($r);print_r(end($r));
```
[Answer]
## JavaScript (ES6), ~~84~~ 83 bytes
Returns a sorted flattened array.
```
a=>a.sort().filter((_,i)=>b[i]==Math.min(...b),b=a.map(i=>a.filter(j=>i-j).length))
```
### Test cases
```
let f =
a=>a.sort().filter((_,i)=>b[i]==Math.min(...b),b=a.map(i=>a.filter(j=>i-j).length))
console.log(JSON.stringify(f([1, 2, 3])))
console.log(JSON.stringify(f([1, 2, 2, 1])))
console.log(JSON.stringify(f([1, 2, 3, 2, 1])))
console.log(JSON.stringify(f([1, 2, 1, 2, 3, 4, 1])))
```
[Answer]
## CJam, 24 bytes
```
{$e`_$W=0=\{0=1$=},e~\;}
```
I wanted to do this in 05ab1e, but I gave up :P
This is a block. Input and output are arrays on the stack.
[Try it online!](https://tio.run/nexus/cjam#izZUMFIwBmLD2P/VKqkJ8Qa2BrYx1Qa2hiq2tTpWiVapdTHWtf/rEv4DAA "CJam – TIO Nexus")
Explanation:
```
{ e# Stack: | [1 2 3 2 1]
$ e# Sort: | [1 1 2 2 3]
e` e# RLE encode: | [[2 1] [2 2] [1 3]]
_$W= e# Copy elements: | [[2 1] [2 2] [1 3]] [2 1]
0= e# First element: | [[2 1] [2 2] [1 3]] 2
\ e# Swap: | 2 [[2 1] [2 2] [1 3]]
{0=1$=}, e# Filter where x[0]==2: | 2 [[2 1] [2 2]]
e~ e# RLE decode: | 2 [1 1 2 2]
\; e# Delete back: | [1 1 2 2]
}
```
[Answer]
## Clojure, 65 bytes
```
#(let[P partition-by C count](last(P C(sort-by C(P +(sort %))))))
```
Ungolfed:
```
(def f #(->> %
(sort-by identity) ; sort so that identical values are one after another, same as sort
(partition-by identity) ; partition by identity (duh!)
(sort-by count) ; sort by item count
(partition-by count) ; partition by item count
last)) ; get the last partition
```
[Answer]
# C#, 145 Bytes
```
l=>{var t=Enumerable.Range(0,l.Max()+1).Select(i=>l.Count(a=>a==i));return t.Select((a,i)=>Enumerable.Repeat(i,a)).Where(d=>d.Count()==t.Max());}
```
This must be possible better as well, however I'm kind of stuck.
**Explanation**
```
l => //Takes the list
{ //...
var t = Enumerable.Range(0, l.Max() + 1) //Makes a range till the count, so that the items together with their indices are double defined (i.e. the items are 0,1,2,3... and the indices are the same)
.Select(i => //Takes the items
l.Count(a => a == i)); //And replaces them with the count of themselves in the list (so the item has the index with its old value and the count as it's actual value)
return t.Select((a, i) => //Then it takes this list and selects the items together with the indices
Enumerable.Repeat(i, a)) //Repeats them as often as they appeared in the list
.Where(d => d.Count() == t.Max()); //And just keeps those which appear the maximum amount of times
}; //...
```
Probably a totally different approach would be much shorter, so the C# challenge is still open :)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 57 bytes
```
->a{a.reject{|i|a.map{|j|a.count j}.max>a.count(i)}.sort}
```
[Try it online!](https://tio.run/nexus/ruby#S7ON@a9rl1idqFeUmpWaXFJdk1mTqJebWFBdkwVkJOeX5pUoZNUCRSrsoFyNTM1aveL8opLa/@UZmTmpCumpJcVcCgoFCml6yYk5OQqpZYk5GirxmlypeSn/ow11FIx0FIxjuaAsIDKEc4zR@HBRE5AoAA "Ruby – TIO Nexus")
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 46 bytes
```
[ all-subsets [ all-eq? ] filter all-longest ]
```
[Try it online!](https://tio.run/##Xck7DsIwEATQ3qeYCxCJTwUFJaKhQVQohWNtgiXHdrwbCRTl7CZKCj5bjGbe1tpISPl2PV9Oe7RaHoUJbWW9ntgaRpNCH61vwNT15A3xpxX0lKQZMZHIKybrBQelBoXpBqyxwRbj19pMOf58/2XR3ayjyndo51bcV0zCWBZ1R5SorRNKM7jgG2JBmVsdUeQ3 "Factor – Try It Online")
* `all-subsets` Get all the subsets of the input
* `[ all-eq? ] filter` Get the ones where all the elements are the same
* `all-longest` Get all the longest of these
] |
[Question]
[
A perfect power is a number of the form \$a^b\$, where \$a>0\$ and \$b>1\$.
For example, \$125\$ is a perfect power because it can be expressed as \$5^3\$.
# Goal
Your task is to write a program/function that finds the \$n\$-th perfect power, given a positive integer \$n\$.
# Specs
* The first perfect power is \$1\$ (which is \$1^2\$).
* Input/output in any reasonable format.
* Built-ins are **allowed**.
# Further information
* [OEIS A001597](http://oeis.org/A001597)
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins.
# Testcases
```
input output
1 1
2 4
3 8
4 9
5 16
6 25
7 27
8 32
9 36
10 49
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
µÆE;¬g/’µ#Ṫ
```
[Try it online!](http://jelly.tryitonline.net/#code=wrXDhkU7wqxnL-KAmcK1I-G5qg&input=MTA).
### Background
Every positive integer \$k\$ can be factorized uniquely as the product of powers of the first \$m\$ primes, i.e., \$k=p\_1^{\alpha\_1}\cdots p\_m^{\alpha\_m}\$, where \$\alpha\_m>0\$.
We have that \$a^b\$ (\$b>1\$) for some positive integer \$a\$ if and only if \$b\$ is a divisor of all exponents \$\alpha\_j\$.
Thus, an integer \$k > 1\$ is a perfect power if and only if \$\gcd(α\_1, ⋯, α\_m) ≠ 1\$.
### How it works
```
µÆE;¬g/’µ#Ṫ Main link. No arguments.
µ Make the chain monadic, setting the left argument to 0.
µ# Find the first n integers k, greater or equal to 0, for which the
preceding chain returns a truthy value.
In the absence of CLAs, n is read implicitly from STDIN.
ÆE Compute the exponents of the prime factorization of k.
;¬ Append the logical NOT of k, i.e., 0 if k > 0 and 1 otherwise.
This maps 1 -> [0] and [0] -> [1].
g/ Reduce the list of exponents by GCD.
In particular, we achieved that 1 -> 0 and 0 -> 1.
’ Decrement; subtract 1 from the GCD.
This maps 1 to 0 (falsy) and all other integers to a truthy value.
Ṫ Tail; extract the last k.
```
[Answer]
# Mathematica, 34 bytes
```
(Union@@Array[#^#2#&,{#,#}])[[#]]&
```
Generates an \$n\times n\$ array \$A\_{ij} = i^{1+j}\$, flattens it, and returns the \$n\$th element.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
Code:
```
LD>m€`{Ú`¹<@
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=TEQ-beKCrGB7w5pgwrk8QA&input=MTA).
[Answer]
## CJam, 16 bytes
```
ri_),_2f+ff#:|$=
```
[Test it here.](http://cjam.aditsu.net/#code=ri_)%2C_2f%2Bff%23%3A%7C%24%3D&input=8)
### Explanation
This uses a similar idea to LegionMammal's Mathematica answer.
```
ri e# Read input and convert to integer N.
_), e# Duplicate, increment and turn into range [0 1 ... N].
_2f+ e# Duplicate and add two to each element to get [2 3 ... N+2].
ff# e# Compute the outer product between both lists over exponentiation.
e# This gives a bunch of perfect powers a^b for a ≥ 0, b > 1.
:| e# Fold set union over the list, getting all unique powers generated this way.
$ e# Sort them.
= e# Retrieve the N+1'th power (because input is 1-based, but CJam's array access
e# is 0-based, which is why we included 0 in the list of perfect powers.
```
[Answer]
# Octave, ~~57~~ ~~31~~ 30 bytes
```
@(n)unique((1:n)'.^(2:n+1))(n)
```
I just noticed again that Octave does not need `ndgrid` (while Matlab does)=)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
*þḊFQṢị@o
```
[Try it online!](https://tio.run/##ASMA3P9qZWxsef//KsO@4biKRlHhuaLhu4tAb/8xMDvDhyTigqxH/w "Jelly – Try It Online")
As far as I can tell, only the `þ` quick didn't exist when the challenge was posted, but [this](https://tio.run/##y0rNyan8/7/g4Y4uLf1HTWsCH@5c9HB3t0P@f0MD68PtKkAh9/8A) 10 byter would've worked back then as well as now.
## How it works
```
*þḊFQṢị@o - Main link. Takes n on the left
Ḋ - Yield [2, 3, ..., n]
þ - Create an n×(n-1) matrix then
for each entry (i,j) (i = 1,2,...,n and j = 2,3,...n),
fill it with the following:
* - i*j
F - Flatten the matrix
Q - Remove duplicates
Ṣ - Sort
For all n > 1, this yields an ordered list of perfect powers below n*n
For n = 1, this yields an empty list
ị@ - Take the nth item in this list. n = 1 yields 0
o - Replace 0 with n, to handle n = 1
```
[Answer]
# Sage (version 6.4, probably also others): ~~64~~ 63
```
lambda n:[k for k in range(1+n^2)if(0+k).is_perfect_power()][n]
```
Creates a lambda function that returns `n`th perfect power. We rely on the fact that it is found within the first `n^2` integers. (The `1+n^2` is necessary for `n=1,2`. The `0+k` bit is necessary to convert `int(k)` to `Integer(k)`.)
Byte off for `xrange`->`range`, thanks Dennis.
Just a fun fact: `0` is a perfect power by Sage's standards, fortunately, because then `1` is the 1st element of the list, not 0th :)
[Answer]
# Pyth - ~~12~~ 11 bytes
Obvious approach, just goes through and checks all numbers.
```
e.ffsI@ZTr2
```
[Test Suite](http://pyth.herokuapp.com/?code=e.ffsI%40ZTr2&input=4&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0).
[Answer]
# J, 29 bytes
Based on the @LegionMammal978's [method](https://codegolf.stackexchange.com/questions/78985/find-the-n-th-perfect-power/78992#78992).
```
<:{[:/:~@~.[:,/[:(^/>:)~>:@i.
```
## Usage
```
f =: <:{[:/:~@~.[:,/[:(^/>:)~>:@i.
f " 0 (1 2 3 4 5 6 7 8 9 10)
1 4 8 9 16 25 27 32 36 49
```
## Explanation
```
<:{[:/:~@~.[:,/[:(^/>:)~>:@i.
i. Create range from 0 to n-1
>: Increments each in that range, now is 1 to n
[: Cap, Ignores input n
>: New range, increment from previous range to be 2 to n+1 now
^/ Forms table using exponentation between 1..n and 2..n+1
,/ Flattens table to a list
~. Takes only distinct items
/:~ Sorts the list
<: Decrements the input n (since list is zero-based index)
{ Selects value from resulting list at index n-1
```
[Answer]
# MATL, 9 bytes
```
:tQ!^uSG)
```
[Try it online](http://matl.tryitonline.net/#code=OnRRIV51U0cp&input=Nw)
This is a port of Flawr's Octave solution to MATL, make the matrix of powers up to `n^(n+1)`, and get the `n`-th one.
[Answer]
# Julia, ~~64~~ 32 bytes
```
n->sort(∪([1:n]'.^[2:n+1]))[n]
```
This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable.
The idea here is the same as in LegionMammal's Mathematica [answer](https://codegolf.stackexchange.com/a/78992/20469): We take the outer product of the integers 1 to *n* with 2 to *n* + 1, collapse the resulting matrix column-wise, take unique elements, sort, and get the *n*th element.
[Try it online!](http://julia.tryitonline.net/#code=Zj1uLT5zb3J0KOKIqihbMTpuXScuXlsyOm4rMV0pKVtuXQoKZm9yIGkgPSAxOjEwCiAgICBwcmludGxuKGksICI6ICIsIGYoaSkpCmVuZA&input=) (includes all test cases)
[Answer]
# JavaScript (ES6), 87
```
n=>(b=>{for(l=[i=0,1];b<n*n;++b)for(v=b;v<n*n;)l[v*=b]=v;l.some(x=>n==i++?v=x:0)})(2)|v
```
*Less golfed*
```
f=n=>{
for(b=2, l=[0,1]; b < n*n; ++b)
for(v = b; v < n*n;)
l[v*=b] = v;
i = 0;
l.some(x => n == i++ ? v=x : 0);
return v;
// shorter alternative, but too much memory used even for small inputs
// return l.filter(x=>x) [n-1];
}
```
**Test**
```
f=n=>(b=>{for(l=[i=0,1];b<n*n;++b)for(v=b;v<n*n;)l[v*=b]=v;l.some(x=>n==i++?v=x:0)})(2)|v
function test(){
var v=+I.value
O.textContent=f(v)
}
test()
```
```
<input type=number id=I value=10><button onclick='test()'>-></button>
<span id=O></span>
```
[Answer]
# ><>, 108 bytes
```
:1)?v >n;
$:@@\&31+2>2$:@@:@
:1=?\@$:@*@@1-
:~$~<.1b+1v!?(}:{:~~v?(}:{:v?=}:{
1-:&1=?v~~>~61. >~1+b1.>&
```
This program requires the input number to be present on the stack before running.
It took quite a lot to reduce the number of wasted bytes down to 7!
After a check to see if the input is `1`, the program checks each number, `n`, from 4 in turn to see if it's a perfect power. It does this by starting with `a=b=2`. If `a^b == n`, we've found a perfect power, so decrement the number of perfect powers left to find - if we've already found the right number, output.
If `a^b < n`, `b` is incremented. If `a^b > n`, `a` is incremented. Then, if `a == n`, we've found that `n` isn't a perfect power, so increment `n`, resetting `a` and `b`.
[Answer]
## Actually, 18 bytes
```
;;u@ⁿr;`;√≈²=`M@░E
```
[Try it online!](http://actually.tryitonline.net/#code=Ozt1QOKBv3I7YDviiJriiYjCsj1gTUDilpFF&input=MTA) (may not work due to needing an update)
Explanation:
```
;;u@ⁿr;`;√≈²=`M@░E
;;u@ⁿr push range(n**(n+1))
;`;√≈²=`M@░ filter: take if
;√≈²= int(sqrt(x))**2 == x
E get nth element
```
[Answer]
# [R](https://www.r-project.org/), 44 bytes
```
n=scan();unique(sort(outer(1:n,2:n,`^`)))[n]
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujQvs7A0VaM4v6hEI7@0JLVIw9AqT8cIiBPiEjQ1NaPzYv8bGvwHAA "R – Try It Online")
Same approach as the [Mathematica answer](https://codegolf.stackexchange.com/a/78992/95126).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
!¹OuṠ×^tḣ→
```
[Try it online!](https://tio.run/##ARwA4/9odXNr//8hwrlPdeG5oMOXXnThuKPihpL///8y "Husk – Try It Online")
## Explanation
```
!¹OuṠ×^tḣ→ Range 1..n+1 (ḣ called with 1 given an empty list)
Ṡ hookf: Ṡ f g x = f (g x) x
×^ f: apply power to all possible pairs from two lists
t g: tail (1..n → 2..n)
u all unique powers
O sort in ascending order
!¹ element at index n
```
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
!¹uO§×^…2ḣ
```
[Try it online!](https://tio.run/##ARsA5P9odXNr//8hwrl1T8Knw5de4oCmMuG4o////zE "Husk – Try It Online")
Dominic Van Essen's solution.
## Explanation
```
!¹uO§×^…2ḣ
§ fork: § f g h x = f (g x) (h x)
×^ f: apply power to all possible pairs from two lists
…2 g: inclusive range from 2..n (works for n<2)
ḣ h: range from 1..n
O sort in ascending order
u all unique powers
!¹ element at index n
```
[Answer]
## JavaScript (ES7), 104 bytes
```
n=>(a=[...Array(n)]).map(_=>a.every(_=>(p=i**++j)>n*n?0:r[p]=p,i+=j=1),r=[i=1])&&r.sort((a,b)=>a-b)[n-1]
```
Works by computing all powers not greater than n², sorting the resulting list and taking the nth element.
[Answer]
# Java, 126
```
r->{int n,i,k;if(r==1)return r;for(n=i=2,r--;;){for(k=i*i;k<=n;k*=i)if(k==n){i=--r>0?++n:n;if(r<1)return n;}if(--i<2)i=++n;}}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 82 bytes
```
f=lambda n,i=0:n and f(n-any(a**b==i for a in range(i)for b in range(i)),i+1)or~-i
```
[Try it online!](https://tio.run/##TcyxCoMwFIXhvU9xxlwboaHgIORhbrBpL9QTCS4uffWoU13/D/5lWz@Fz9Zy/OqcJgW9xcdIKCdkx165Oe26FKMhlwqFEVX5fjmTM6RrEG/3IKX@emsn8o/Bh0HGG7BU4@qOt0jbAQ "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
µNDÓ2šθ2@
```
[Try it online](https://tio.run/##yy9OTMpM/f//0FY/l8OTjY4uPLfDyOH/f1MA) or [verify a few more test cases](https://tio.run/##ASoA1f9vc2FiaWX/MjVFTj8iIOKGkiAiP07/wrVORMOTMsWhzrgyQP99LC7Ctf8).
**Explanation:**
```
µ # Loop until the counter_variable (0 by default) equals the (implicit) input:
ND # Push the current 0-based loop-index `N` twice
Ó # Pop one, and push all its exponents of prime factorization [a,b,c,d,...] in
# [2^a,3^b,5^c,7^d,...]
# (for N=0 and N=1, this will results in an empty list)
2š # Prepend a 2 (for the edge cases N=0 and N=1)
θ # Pop the list, and leave just the last value
2@ # Check if this is larger than or equal to 2
# (if it is: implicitly increase the counter_variable by 1)
# (after the loop, implicitly output the last `N` that's still on the stack)
```
Minor note: the `@` in my answer using the latest 05AB1E version is a builtin for `>=`, whereas the `@` used in [*@Adnan*'s existing 05AB1E answer](https://codegolf.stackexchange.com/a/79043/52210) using the legacy 05AB1E version is a builtin to push the \$n^{th}\$ item on the stack.
] |
[Question]
[
Let's take a grid of 16x16 printable ASCII characters (code points 0x20 to 0x7E). There are 30-choose-15 paths from the top left to the bottom right corner, making only orthogonal moves, like the following example:
```
##..............
.#..............
.######.........
......##........
.......##.......
........#.......
........#.......
........#.......
........###.....
..........###...
............#...
............####
...............#
...............#
...............#
```
Each such path consists of exactly 31 characters. Note that each of those characters is on a different of the 31 anti-diagonals:
```
0123456789ABCDEF
123456789ABCDEFG
23456789ABCDEFGH
3456789ABCDEFGHI
456789ABCDEFGHIJ
56789ABCDEFGHIJK
6789ABCDEFGHIJKL
789ABCDEFGHIJKLM
89ABCDEFGHIJKLMN
9ABCDEFGHIJKLMNO
ABCDEFGHIJKLMNOP
BCDEFGHIJKLMNOPQ
CDEFGHIJKLMNOPQR
DEFGHIJKLMNOPQRS
EFGHIJKLMNOPQRST
FGHIJKLMNOPQRSTU
```
This is not an example grid. This is a visualisation of the 31 anti-diagonals.
We'll call a grid *diagonally unique* if no anti-diagonal contains the same character twice. If the grid has this property, no two paths will contain the same string. (Just to clarify, the visualisation itself is basically the *opposite* of diagonally unique.)
## The Challenge
Design a diagonally unique 16x16 grid, such that as many paths as possible are valid code which prints `Jabberwocky` to STDOUT (with optional trailing line break) in as many languages as possible. Each code may either be a full program, or the body of a parameterless function without return statement (this is in order not to discourage languages that *need* to have their code in some boilerplate function/class/namespace).
**Note:** For simplicity you can use some reserved character for unused cells [like Ypnypn](https://codegolf.stackexchange.com/a/40466/8478) did.
For each valid path, please clearly state *one* programming language it is valid in.
The winner is the submission with the largest number of languages covered by the above list. (Alternatively, for each language you want to count, show one path which is valid in that language, but make sure not to count any path for two languages.)
In the event of a tie, count the grid cells which are *not* covered by any valid path. Fewer unused cells win. If there is *still* a tie, I'll accept the answer with the most (net) votes.
## Validation Script
I just quickly put together a little CJam snippet you can use to validate that a grid is diagonally unique.
1. Go to [the online CJam interpreter](http://cjam.aditsu.net/).
2. Paste the following code
```
l:A;
qN/W%A16**33/z{A-__|=}%:*"D""Not d"?"iagonally unique"
```
3. In the input field, put you reserved character on the first line (use an unused character if you don't make sue of a reserved character), and then your grid in line 2 to 17. E.g., for Ypnypn's answer:
```
~
pr~~~~~~~~~~~~~
tin~~~~~~~~~~~~
~ypt(~~~~~~~~~~~
~~ef(~~~~~~~~~~~
~~ "J~~~~~~~~~~
~~~~~ab~~~~~~~~~
~~~~~~be~~~~~~~~
~~~~~~~rwo~~~~~~
~~~~~~~~~ck~~~~~
~~~~~~~~~~y~~~~~
~~~~~~~~~~\n~~~~
~~~~~~~~~~~")) ~
~~~~~~~~~~~ ;
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~
```
4. Run.
Let me know if you think it has a bug.
[Answer]
## ~~30 33~~ 35 Languages
Reserved character: `~`
```
println!~~~~~~~
puts (1,~~~~
echo '~~~~
"cWprintfn"Ja~~~
Eork~~~;'Jabbe~~
\ui)K00~~~~~br~~
]tteL~0~~~~~ew~~
]<~ln(0~~~~~ro~~
`<~~~ 0~~~~~wc~~
m"~~~ "~~~~~ok~~
rJ~~~'J~~~~~cy~~
j"<< "a~~~~~k'..
^~~~~~bberwoy");
f~~~~~~~~~~c' ;
t~~~~~~~~~~ky"
XX");); 5f+');
```
**Languages:**
```
01. Rust | println! ( "Jabberwocky") ; |
02. Groovy | println "Jabberwocky" |
03. E | println ( "Jabberwocky") |
04. Swift | println ( "Jabberwocky") ; |
05. Julia | println ( "Jabberwocky");; |
06. Processing | println ( "Jabberwocky") ; |
07. Falcon | printl ( "Jabberwocky") |
08. ALGOL 68 | print ( "Jabberwocky") |
09. Vala | print ( "Jabberwocky") ; |
10. Pawn | print ( "Jabberwocky");; |
11. Batsh | print ( "Jabberwocky") ; |
12. freeBASIC | print "Jabberwocky" |
13. Rebol | print "Jabberwocky" ; |
14. Red | print "Jabberwocky" ; |
15. AWK | print 'Jabberwocky' |
16. Perl | print 'Jabberwocky' ; |
17. bc | print 'Jabberwocky' ; |
18. Euphoria | puts (1,"Jabberwocky") |
19. C | puts ( "Jabberwocky") ; |
20. Tcl | puts "Jabberwocky" |
21. Ruby | puts 'Jabberwocky' |
22. Zsh | echo "Jabberwocky" |
23. Bash | echo "Jabberwocky" ; |
24. tcsh | echo "Jabberwocky" ; |
25. PHP | echo 'Jabberwocky' |
26. Fish | echo 'Jabberwocky' ; |
27. Dash | echo 'Jabberwocky' ; |
28. F# | printfn"Jabberwocky" ; |
29. C++ | cout<<"J"<< "abberwocky" ; |
30. D | Writeln( 'Jabberwocky'); |
31. Pascal | WriteLn( 'Jabberwocky'); |
32. Delphi | Writeln( "Jabberwocky"); |
33. GolfScript | print;'Jabberwocky'..;; |
34. CJam | "E\]]`mrj^ftXX");); 5f+'); |
35. Pyth | pk)K00000"Jabberwocky" |
```
*(Pyth and CJam thanks to user23013)*
[Answer]
## 17 languages
Here's the grid, with `.` as the reserved character:
```
prin...........
utstln!........
(1,......
<?echo ".....
.........'Jab...
............b...
............e...
............r...
............w...
............o...
............c...
............k...
............y"..
............' ).
............. ;
..............
```
And here are the languages and their paths (ignore the vertical bars):
```
01. Rust | println!( "Jabberwocky" ) ; |
02. Swift | println ( "Jabberwocky" ) ; |
03. Scala | println ( "Jabberwocky" ) |
04. Falcon | printl ( "Jabberwocky" ) |
05. Vala | print ( "Jabberwocky" ) ; |
06. Lua | print ( 'Jabberwocky' ) ; |
07. ALGOL 68 | print ( "Jabberwocky" ) |
08. Dart | print ( 'Jabberwocky' ) |
09. Rebol | print "Jabberwocky" ; |
10. Perl | print 'Jabberwocky' ; |
11. AWK | print "Jabberwocky" |
12. Euphoria | puts (1, "Jabberwocky" ) |
13. C | puts ( "Jabberwocky" ) ; |
14. Tcl | puts "Jabberwocky" |
15. Ruby | puts 'Jabberwocky' |
16. Bash | echo "Jabberwocky" |
17. PHP | echo "Jabberwocky" ; |
```
I haven't been able to test all of them, so let me know if something doesn't work.
[Answer]
# 18 languages and more
Reserved character: `~`.
```
"~~~~~~
12345678 "~~~~~~
12345678 "~~~~~~
12345678 "~~~~~~
1234567: ea~~~~~
1234567: c;~~~~~
1234567: hL~~~~~
1234567: o'~~~~~
1234567: Jab~~~
1234567:?""""~~~
~~~~~~~~~Jabberw
~~~~~~~~~~~~~~~o
~~~~~~~~~~~~~~~c
~~~~~~~~~~~~~~~k
~~~~~~~~~~~~~~~y
~~~~~~~~~~~~~~~"
```
Languages:
```
CJam | ea;L'J"abberwocky"|
GolfScript | cho "Jabberwocky"|
Bc | "Jabberwocky"|
Bash | """"echo J"abberwocky"|
Zsh | ""echo J"abberwocky"|
Fish | echo J"abberwocky"|
Tcsh | """"echo Ja"bberwocky"|
Dash | ""echo Ja"bberwocky"|
Ksh | echo Ja"bberwocky"|
Mksh | """"echo Jab"berwocky"|
Yash | ""echo Jab"berwocky"|
Sash | echo Jab"berwocky"|
Posh | """"echo "Jabberwocky"|
Csh | ""echo "Jabberwocky"|
PHP | echo "Jabberwocky"|
```
and...
```
FreeBasic | ?"Jabberwocky"|
QBasic | 12345678 ?"Jabberwocky"|
QB64 | 123456788 ?"Jabberwocky"|
```
There should be many [more Basic dialects](http://en.wikipedia.org/wiki/List_of_BASIC_dialects) that works. But I don't have time to test all of them yet.
] |
[Question]
[
First attempt at a question.
---
# Calculating Transitive Closure

According to [Wikipedia](https://en.wikipedia.org/wiki/Transitive_closure), "the transitive closure \$R^\*\$ of a homogeneous binary relation \$R\$ on a set \$X\$ is the smallest relation on \$X\$ that contains \$R\$ and is transitive."
Also, "a relation \$R\$ on a set \$X\$ is transitive if, for all \$x, y, z \in X\$, whenever \$x R y\$ and \$y R z\$ then \$x R z\$."
If that jargon did not make much sense, just remember the transitive law:
>
> If \$a = b\$ and \$b = c\$, then \$a = c\$.
>
>
>
We can use this law for relations on sets.
Basically, transitive closure provides reachability information about a graph. If there is a path from \$a\$ to \$b\$ (\$a\$ "reaches" \$b\$), then in a transitively closed graph, \$a\$ would relate to \$b\$.
[Here](https://www.techiedelight.com/transitive-closure-graph/) is another resource about transitive closure if you still do not fully understand the topic.
---
# Challenge
Given a 2D Array (representing the graph \$R\$) where each inner array contains only positive integers and represents a vertex, **determine the number of additional edges required to create the transitively closed graph \$R^\*\$.**
---
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āεFè]øε˜ÙINèK}˜g
```
0-based indexing.
[Try it online](https://tio.run/##yy9OTMpM/f//SOO5rW6HV8Qe3nFu6@k5h2d6@h1e4V17ek76///R0YY6RrE60SBsDMSxsQA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKSvdL/I43ntrodXhF7eMe5rafnHJ7p6Xd4hXft6Tnp/5X0wnS4QKq5yjMyc1IVilITUxQy87hS8rkUFPTzC0r0IYZCKTR7bBRUwGrzUv9HRxvqGMXqRIOwMRDHxnJFR4NoKNMQyDBAYiELgzWCuUYQHYY6BmCjwCp0jHRABkJIY2SNMLtMgNgUaj4A) or [see what it does step-by-step](https://tio.run/##VVHNSsNAEL77FENOCilFvSmSW6WIIh4tOYzJNFnY7MbsbGsPPfgYQh@gL6B4Nt4KvlK6P0rxMMsyzPcz32iDT4KGIZmq1vIFJOnV10d2lNxbUwOCFIZBKOCaoENVEcxOU9dwsyNJquI695jv14i6xRb0gjogLGpYoLSUAqoSFBmm0gFLenEv68AYeNwPGRpUK2DRkPF8P@@TfptHzkfRjtlpm1YbugSzxLYVqoJOL8240NI2KmD6zzg/kchMKshaJZ6tmK@iH6GUs@ZXihq7Tf@2jqAHapzvg6lR8G7gOMmmWXIC8043keQAn97125v1f1G3WEUceEJ0eg5YloKFVijlCoqO0AdRaOel8O3gfbeJNNd/2BCtR3MtTArLWnj/BrTtoCNjJfsItOXfo1XZMMzcac7ydObr3FWe7wE).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
ε # Map over each value:
F # Loop that many times:
è # Index the inner-most values of the current list into the (implicit)
# input-list,
# which will use the (implicit) input-list in the first iteration
] # Close both the loop and map
ø # Zip/transpose; swapping rows/columns
ε # Map over each inner nested list:
˜ # Flatten it
Ù # Uniquify its values
INè # Push the map-index'th list of the input
K # Remove those values from the current list
}˜ # After the map: flatten it to get all additionally created connections
g # Pop and push the length
# (after which this amount is output implicitly as result)
```
Initially I used `.Γè}` instead of `āεFè]`, and although it worked for the [example test case](https://tio.run/##yy9OTMpM/f9f79zkwytqD@84t/X0nMMzPf0Or/CuPT0n/f//6GhDHaNYnWgQNgbi2FgA), it didn't for any test cases that have reflexive vertices (like test case `[[1],[0]]` for example). Hence the use of `āεFè]` to loop a fixed amount of times based on the amount of input-vertices.
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 11 bytes *(non competing)*
`#µÍ®ääe*¿<S`
Reads zero-indexed array from standard input, prints the solution to standard output
[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I7XNruTkZSq_PFM=&in=W1sxLDJdLFsyXSxbM10sW11d)
# Explanation
The solution is based on the observation that an entry `i,j` of the `k`-th power of the adjacency matrix of a graph taken is nonzero iff there is a walk of length `k` in the graph connecting the vertices `i` and `j`.
So the adjacency matrix of the transitive closure has ones in all entries that are non-zero in at least one positive power of the adjacency matrix of the original graph.
```
# ; read the array from standard input
µÍ® ; compute adjacency matrix of graph
µ ; apply to all elements
Í ; convert array to array with ones at the indices given by the values of the array
® ; convert nested array to matrix
ää ; duplicate matrix twice
e ; compute matrix exponential (sum of all powers of matrix)
* ; multiply with original matrix (sum of all positive powers of matrix)
¿ ; replace all non-zero entries with one
< ; point-wise comparison keeps only the entries that appear in A*e^A but not in A
S ; sum up all entries (as all entries are zero or one, this give the number of nonzero entries)
; solution is implicitly printed
```
## Disclaimer
*This language was created after I saw the sandbox version of this challenge.
While the [general consensus](https://codegolf.meta.stackexchange.com/questions/12877/lets-allow-newer-languages-versions-for-older-challenges) seems to be that new languages without built-ins designed specifically for a challenge are allowed,
I will still mark this solution as non-competing as this challenge heavily influenced the design process
(for instance built-in matrix operations and the `Í` operator were introduced to simplify writing this solution)*
---
# Itr, [12 bytes](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I7XNruRMuV5TvzxT&in=W1sxLDJdLFsyXSxbM10sW11d) (no floating point operations)
`#µÍ®äL¹^S¿<S`
`L¹^S` directly computes the sum of the first n powers
```
^ ; the matrix to the power of
L¹ ; the range from 1 to the number of rows (does not consume the array)
S ; sum up all results (taking to the power of a vector will give a vector containing all the powers)
```
[Answer]
# JavaScript (ES6), 74 bytes
Uses 0-based indexing. Returns `false` for `0`.
```
f=a=>a.some(b=>b.some(i=>a[i].some(v=>!b.includes(v)&&b.push(v))))&&1+f(a)
```
[Try it online!](https://tio.run/##dZDBcoMgEIbvPsX24sDUkChJLw7e@hSOh8VoY8aIExounT67XSBt0zbdGZaf5eOH5YgObXse5tfVZPbdsvQKVYXCmlPHtKp0VAPV6qGJC6eqBy2GqR0v@84yx9NUi/liDyQp0jR/7BnypawTgLpuMoiD0t9Yr2ETsMIz@X0oYMUt9o/fLywDeZckTAZMfj6uyCCYyluWsF10I6MMtgG4zttv458tyK/dnU9P17bipZukSURvzs/YHhiCquCNTpIAFCecmfYlHaTz0sEKcs5LglozWTN2YjQvzH8vFd95uXwA "JavaScript (Node.js) – Try It Online")
### How?
We look for some sub-list `b` in the main list `a` and some `i` in `b` such that there's at least one value `v` in the sub-list `a[i]` that does not yet exist in `b`. If `v` is found, we add it to `b` and increment the final result. This process is repeated until there's nothing to update anymore.
### Commented
```
f = // f is a recursive function taking ...
a => // ... the main list a[]
a.some(b => // for each sub-list b[] in a[]:
b.some(i => // for each value i in b[]:
a[i].some(v => // for each value v in a[i]:
!b.includes(v) // if v is not already in b[],
&& b.push(v) // append v to b[] and trigger all some()'s
) // end of some()
) // end of some()
) // end of some()
&& 1 + // if truthy, increment the final result
f(a) // and do a recursive call with the updated list
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
ls-Vum{sam@G
```
[Try it online!](https://tio.run/##K6gsyfj/P6dYN6w0t7o4MdfB/f//6GijWB2FaBA21FEwANFGsbEA "Pyth – Try It Online")
Takes zero-indexed input.
### Explanation
This may be the most implicitly added variables I've ever had in a Pyth golf.
```
ls-Vum{sam@GkddGQQ # implicitly add kddGQQ
# implicitly assign Q = eval(input())
u Q # find fixed point, repeatedly apply lambda G, H to the previous value, iteration number until we get a result that has occurred before, begin with Q
m G # map lambda d over G
m d # map lambda k over d
@Gk # value of G at index k
a d # append d
s # flatten
{ # deduplicate
-V Q # remove any elements originally present in Q, vectorized
s # flatten
l # output the length
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;ịFQʋ€ÐLḟ"⁸FL
```
A monadic Link that accepts \$R\$ as a one-indexed adjacency list and yields the required number of edges to add to make a transitive closure, \$R\*\$, containing \$R\$.
**[Try it online!](https://tio.run/##y0rNyan8/9/64e5ut8BT3Y@a1hye4PNwx3ylR4073Hz@//8fHW0Uq6MQbQwiTECEKYgwAxGGsbEA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/64e5ut8BT3Y@a1hye4PNwx3ylR4073Hz@H530cOcMncPtWY8a5ijY2ik8apirGfn/f3R0dKyOAgTH6nApREcbgdiGqBx0WR0FYyQxY5gJRjoKYLXGMMVAdToKJmAhKG2CbpYxXNQURJjBbY8FAA "Jelly – Try It Online").
### How?
Repeatedly add edges that do not yet exist for all traversable pairs of edges, then count the number of new edges.
```
;ịFQʋ€ÐLḟ"⁸FL - Link: adjacency list, A
ÐL - start with X=A and loop until a fixed point applying:
€ - for each {node in X}:
ʋ - last four links as a dyad - F(node, X)
ị - {node} index into {X} (vectorises)
; - {node} concatenate {that}
F - flatten
Q - deduplicate -> updated node
⁸ - chain's left argument -> A
" - zip with:
ḟ - {final node} filter discard {original node from A}
F - flatten
L - length
```
---
The end, `ḟ"⁸FL`, seems long, is there something better than this or `;ịFQʋ€ÐLn>0SS` etc.?
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 110 bytes
```
f=lambda a,o=0,c=0:a!=(m:=[[*(s:={*sum([a[i]for i in n],n)},c:=c+len(s-{*n}))[0]]for n in a])and c+f(m,o or a)
```
A recursive function that accepts the adjacency list, `a`, and returns the number of required edges (with `False` [quacking like](https://codegolf.meta.stackexchange.com/a/9067/53748 "meta") `0`).
**[Try it online!](https://tio.run/##bZDRasMwDEXf9xVan@xEBbduxzBoP2LM8NKaGRolJNnDCPn2LHa70LEabKOro4uk9nv4bFi/tt08B7r4@uPkwWNDCitSxj@TqA1ZW4je0Fj0X7Ww3kYXmg4iRAZ2yHLCylBVXs4s@u1Y8CSlVS5DnCDvpOcTVGUQNTawyF7OKTuc@yEB4gmWY61DuF6HN2Wfwt2/@AGDoP/K@tdtj5Ar9F3JQiMcsnr7Dw9M9Zo4pudlbUaajKX@3xXQwsftDu62AuvwiXGZbrvIgwibMUkT0BuMQVwtZKmmjZx/AA "Python 3.8 (pre-release) – Try It Online")**
[Answer]
# Python3, 240 bytes:
```
E=enumerate
T=lambda K,g:[(v,l)for i,v in E(K)for _,l in E(K[i+1:])if l not in g[v-1]]
def e(g,n,c=[]):
for i in g[n-1]:
yield from T(c+[n,i],g)
if i not in c:yield from e(g,i,c+[n])
f=lambda g:len({j for i,_ in E(g)for j in e(g,i+1)})
```
[Try it online!](https://tio.run/##dU@7bsMgFN35ijuCfDs4pFVlyWOmrNkQilwbKBHGluVaiqp@uwvY7jMZAN3zuof@Or52nj/3wzwfSuXfWjVUoyKn0lXtS1PBEU0h6ISO6W4AixNYDwd6TOMZ3ToKm@WFZFaDA9@NETViesilJI3SoKhBj3UpJCsIpKRF4oMkIHC1yjWgh66FE60z4dFKNCwwIdJukXXxQxczLUatZERvfU3hlKfvl2UJnpd@JtW9xCHZspx9sLkfrB@ppkJIhOVIxsg3vItY@APcQu/JEfgNjm8rdgjJy/@agw9hn6j13d/bwb/Yx3g9rTX/5f3WRsH8CQ)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
FθFιF⁻§θκι«⊞ιλ→»Iⅈ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BTAUxnQmjfzLzSYg3HEs@8lNQKjUIdhWxNHQWgXDUXZ0BpcYZGpo5CjqY1F6dvflmqhlVQZnpGCZBbyxVQlJlXouGcWFyiEaGhqalp/f9/dHS0UayOQjQIG@ooGIBoo9jY2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. `0`-indexed. Explanation:
```
Fθ
```
Loop over each vertex.
```
Fι
```
Loop over the list of target indices for this vertex. Note that this list can be extended by the innermost loop in which case the additional indices will also be considered.
```
F⁻§θκι«
```
Loop over the list of target indices for the target vertex, but exclude indices already present in the list of target indices for the source vertex.
```
⊞ιλ
```
Add this index to the list of target indices for the source vertex.
```
→
```
Increment a counter.
```
»Iⅈ
```
Output the final count.
Bonus: Reflexive closure, 8 bytes:
```
IΣEθ¬№ικ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUCjUEfBLx8oll8KlMnUUcjWBAPr//@jo6MNYnUUokEYzDCMjY39r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code.
Bonus 2: Symmetric closure, 14 bytes:
```
IΣEθ↨¹Eι¬№§θλκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUCjUEfBKbE4VcNQRwHEzdRR8MsHKskvBSp0LPHMS0mtAKnJ0dRRyNaEAuv//6Ojo41idRSiQRio1QBEG8XGxv7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 16 bytes
```
~ᵉ{$#ᵑ{ˣ@j,u}}∕~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FtvrHm7trFZRfrh1YvXpxQ5ZOqW1tY86ptYtKU5KLoaqWXCzJDo6VgeMYrmiow2BDAMkFrKwjhGMawTRYagDUmAEUaFjpGMM4oFJY2SNRlABEyA2hZgPsRwA)
[Answer]
# [Scala](https://www.scala-lang.org/), 102 bytes
Port of [@CursorCoercer's Python answer](https://codegolf.stackexchange.com/a/263589/110802) in Scala.
---
Golfed version. [Try it online!](https://tio.run/##jVFNa8MwDL3nV4jSg0WdkDXdDksd2HGwnXYcJbiZ02XEThabMhb82zM7JaXrPujB0rPe00OWdcFrPjTbN1EYeOSVAvFhhHrRcNe20AfBntdQ3pIn8f7sz70ymw3LXEJgA2dZv@cdkVQjcxoz8gRpjGnZdEStQ469ZCoyjWPHWu5q6W4dSuw52WHkaoIXr0QuWI42lWHIVKoXTEa6@hQ21XYIAPwYRmijgcFDpQ1xNTigMSCF7xnpmWI5UVf/chf0U0j@liXnkywpHF2TX2ydG4XVUXGCVxcMk/wQX0/g5uTBrh0DF8YVHlfub8Ay983efVpx7FbscyR5S5Tn1QhzCOFgBdB2lTK1Ino2n0zmfTkaxmhnXmQxsMMX)
```
a=>{var(m,s)=(Set[Int](),0);for(n<-a){m=n.toSet;for(_<-a;g<-m){a(g).foreach(m+=_)};m--=n;s+=m.size};s}
```
Ungolfed version. [Try it online!](https://tio.run/##jZJdT4MwFIbv@RVvll20EQiO6cUUEy9N9MpLs5COlYmBQmhjjAu/HdsC3Zwf2U3P13PenJ5WZqxkfV9v3nim8MQKAf6huNhK3DcN9h6w5TlywlZ4LKR6sceDUOs1XUFbJBYC3lmLSkfPfKgT6tJSpyMb5XULInAbgNGxD7ZLhKrWnWPGYqnFbrAztjrgACM7GmqGs@yVVLhIkNKx2DnNINCqYyQNU4Wy@OTegZKe8TwzYwnFpTJzmvsRW7aePaiP75b6J8RiKl3@Wzuj30f8NxafTrLw4VTjX2S1mo@lI4785RnDxD/gq8m5PrqwbqdmjXaF7l1MhOTO/Y5hxZFesbFhxRr9EXRdWDdFgEEKaNpCqFIQOZtPIvN9bgUj2s0M1FGv8/r@Cw)
```
object Main extends App {
def f(a: List[List[Int]]): Int = {
var m = Set[Int]()
var s = 0
for (n <- a) {
m = n.toSet
for (_ <- a; g <- m) {
a(g).foreach(m += _)
}
m --= n
s += m.size
}
s
}
val tests = List(
List(List(), List(), List()),
List(List(2), List(1)),
List(List(2), List(1), List()),
List(List(2), List(1, 3), List()),
List(List(3), List(), List(2, 1), List(3)),
List(List(2, 3, 4), List(3, 4), List(4), List()),
List(List(2), List(3), List(4), List(5), List(6), List(1))
)
tests.foreach(test => {
val test0 = test.map(n => n.map(_ - 1))
println(s"$test => ${f(test0)}")
})
}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 18 bytes
```
Fi"TX@@g&(]tYezwz-
```
The input is a cell array of numerical vectors, 1-based. [Try it online!](https://tio.run/##y00syfn/3y1TKSTCwSFdTSO2JDK1qrxK9///6mijWB2FaGMQYQIiTEGEGYgwjK0FAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8N8tUykkwsEhXU0jtiQytaq8Sve/S8j/6uhYHQUIruWqjjYCsQyRmagyOgrGcBFjmE4jHQWwOmOIQqAaHQUTsACUNkE1xRguZgoizKB2AgA).
### Explanation
The first 11 bytes are used for computing the adjacency matrix from the specified input format. The rest of the code is essentially comparing the matrix before and after matrix exponentiation.
```
F % Push false, that is, a 1x1 logical matrix containing false
i % Push input: cell array of numerical vectors
" % For each entry in the cell array
T % Push true (*)
X@ % Push current iteration index, starting at 1 (**)
@g % Push current numerical vector (***)
&( % Write true (*) at specified row (**) and column indieces (***)
% in the logical matrix. This may increase the matrix size
] % End. The stack now contains the adjacency matrix
t % Duplicate adjacency matrix
Ye % Compute the logical version of the adjacency matrix of the power
% of the graph with increasing exponent until the result no longer
% This is the same as logical(M*expm(M)), where M is the original
% adjacency matrix and expm is matrix exponeitial, but numerical
% precision issues are avoided
z % Number of nonzeros
w % Swap. Moves copy of original adjacency matrix to top
z % Number of nonzeros
- % Subtract. Implicit display
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 84 bytes
```
lambda a:sum(len((m:={*n},[m:=m|{*a[g]}for f in a for g in m])and m-{*n})for n in a)
```
[Try it online!](https://tio.run/##bY9hC4IwEIa/9ysOP20yIZ1FCPZHbMRCZ4KbovYhzN9u3jQpcrDtvfeeO@7qZ3evDD/Vzajiy1hKfUslyKh9aFJmhhAdxb1rBpZMQr96Vya5GFTVgILCgASUOUotqDQpaA9xiraxBB1Rd1nbYUh2MJ0kEQzmK9jiBBj6f/EGw4D/2vzTLWBgK/hXyUQzCK27/OFGU74mDvgc12FoZDGc/7qHeOILz7dbF7iPEbCuioywdN0UpiPK6dEaID5Dr8jcgg4OHd8 "Python 3.8 (pre-release) – Try It Online")
Takes 0-indexed input. Essentially a port of my [Pyth answer](https://codegolf.stackexchange.com/a/263579/73054) with some swapping of loop order.
[Answer]
# [J](http://jsoftware.com/), 36 bytes
```
[:+/@,@((+/ .*+.])^:_~-])<@i.@#e.&>]
```
[Try it online!](https://tio.run/##VY3BCsIwEETv/Yqhim1Muk1TvSStBARPnrxK9CAp6sU/8NdjQi20LLvLPmZm3yGnYkCvUUBAQseuCMfL@RSumtdW2LLkNWjLybGbvn8rxzr7IrvytDm4wDLfk1zLzD@eHwzwJtZ0lKJhMHFJNqEGKgE18pYZLNQm/lcLppIk4cZAKGAWhDaGjDNFYebrrMj5X7PDHjL8AA "J – Try It Online")
Uses 0 indexing.
* `<@i.@#e.&>]` Convert adjacency list to adjacency matrix
* `(+/ .*+.])^:_~` Take transitive closure of matrix multiplication, but any cell that becomes 1 also remains 1 `+.]`.
* `-]` Subtract original adj matrix
* `+/@,@` Count the ones
] |
[Question]
[
Given a set of substrings, such as `[ca, ar, car, rd]`, it's possible to create infinitely many strings by concatting them together. Some examples of this for the given substrings could be:
```
ca
caar
card
rdca
carrd
rdrd
...
```
One interesting property of this set of substrings is that any string can only be constructed in one way using them; there is no string where it's ambiguous which combination was used. As a counterexample, take the set `[foo, bar, obar, fo, baz]`. The string `foobar` could either be `foo + bar` or `fo + obar`.
**Task:**
Given a set of substrings, which will not contain duplicates, determine if the above property holds; that is, if for any concatenated ordering of any number of the substrings, it is unambiguously possible to determine the original order of the substrings that it was constructed out of.
In place of substrings you may use lists, with any reasonable data type in place of characters. You may also restrict the characters used in the substrings within reason, such as only using lowercase letters. Your chosen representation of the substrings must be able to represent at least a dozen "characters".
You may produce output using any of the following:
* A truthy/falsy value, with truthy representing either ambiguous or unambiguous (your choice)
* Two consistent values representing ambiguous and unambiguous
* One consistent value representing either ambiguous or unambiguous, and any other value representing the other
**Test cases:**
```
[ca, ar, car, rd] unambiguous
[foo, bar, obar, fo, baz] ambiguous
[a, b, c] unambiguous
[a, ab] unambiguous
[ab, bc, c] unambiguous
[b, ab, ba] ambiguous
[b, ab, ba, aa] ambiguous
[a, aa] ambiguous
[abc, bcd, cda, dab, abcd] ambiguous
[nn, no, on, oo] unambiguous
[atombomb, at, omb] ambiguous
[abc, dx, yz, ab, cd, xyz] ambiguous
[xxx, xxxxx] ambiguous
[a, ax, xx] unambiguous
[baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac, w, wb, acx, xba, aacy, ybaa, aaacz, zbaaa, aaaacd, d] ambiguous
```
(Thanks to @Arnauld, @CursorCoercer, and @loopywalt for the last three test cases)
**Scoring:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes, per language) wins.
[Answer]
# JavaScript (ES6), 110 bytes
Returns *false* for unambiguous or *true* for ambiguous.
```
f=(a,p='',q=p)=>p>q?f(a,q,p):p&&p==q||q.match(p)&&!p[a.map(s=>n*=s.length,n=1)|n]&&a.some(s=>s!=q&&f(a,p+s,q))
```
[Try it online!](https://tio.run/##jVHbboQgEH3vV3RfQFpq0tcmuB9ifeCi7jbKgGjDbvx3K2jSNlXThAww5zAz5/DBP7mT3dX0LxpUOU0VSzg1DGNqmSEsM5k9V3PKUkPeDEKGMTuONm15Ly@JIQidTM7nq0kcy/QTc2lT6rq/UM1eyagLhHjqoC0D7E7MIhTKmWdHLSGTBO2gKdMG6gTng@atuNYDDK7A5OEnWCU5lhzTR8y7EOWydQoX5C8zEkXk7eNcbGPxnZD7r7UOmIYQIZ4BDtr4EL2PjF8U/K7zQ8EVxB5i0QrrXq3J@2ZPsUqLlH8wwpkfTL@DLf4IqaJNKnIVX0vLnV/poRXziqQ@SmrFUXkVrbvdvwde@vnbtnbvV6/9Yvf0BQ "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = list of substrings
p = '', // p = first string, initially empty
q = p // q = second string, initially empty
) => //
p > q ? // if p is lexicographically greater than q:
f(a, q, p) // swap p and q
: // else:
p && p == q || // stop as successful if p is non empty and p = q
q.match(p) && // stop as failed if p cannot be found in q
!p[ // stop as failed if p is too long:
a.map(s => // for the upper bound, we use the product n
n *= // of all substring lengths
s.length, // (e.g. for two substrings whose lengths x and y
n = 1 // are co-prime, we may need to build strings of
) | n // length x * y to get a match)
] && //
a.some(s => // for each substring s in a[]:
s != q && // provided that s is not equal to q,
f(a, p + s, q) // do a recursive call where s is appended to p
) // end of some()
```
### 98 bytes, much slower
```
f=(a,p='',q=p)=>p>q?f(a,q,p):p&&p==q||!p[a.map(s=>n*=s.length,n=1)|n]&&a.some(s=>s!=q&&f(a,p+s,q))
```
[Try it online!](https://tio.run/##fY/BboMwDIbve4r1kpA1Q9p1UuiDMA5OCqwT2A4pVQ68O1vSHjat5fLbyvfbv/MFFwhuOvH5FenYrmtnCtBspNTesDIVV/7Q/Tx5zeqdhWBj/LLsuIZyBC6CqfDFhHJosT9/ajRvasFGCCgDjW3CYWe8EGkF74P2Sq2OMNDQlgP1haxnhNGe@pnm0Ej19Bt2RS0dSP0sYUrqrmU6ykb9d2ajzb7HHOx9luesezyNmBhSUso90UZMTBpjdvyxyA@sNz9sb2eme2Aj4T6L8ZYcr@HrNw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), 104 bytes
```
f=lambda l,x=set():l>l-(y:={a[len(b):]for a in l|x for b in[l,l|x][{a}<l]if b+"~">a>b})or y-x and f(l,y)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=tZOxjtQwEIYLun2KkSnOBu8KOrSQlWh5hSiF7STEt44dJY4u2ePo6CgokQBpG3gnKLfhNRhnI9jkIlGdZdmy_fubmd_Jlx9V7wtnj8fvrc_XL34WeWREKVMBhndRk3nKtmZn1rTfRrciNpmlkm2T3NUgQFsw7zoIC4mL2HBcJvGtuHtlEp2DfErek53YyTuGkn7dgbAp5NTwno3xfofLRtsswFyF-GdsuwLNHUTD_qZuKqM9JQCEP2d4hAf0Cb3eNL7WFSVxAoQFynVA6M0o57jLOHuJmUVgnQeHF0TtmxvtC0paS5BV1dp6isFGGONXp28fT18_XMXSOUNzGhzQjLEokgmDx5ALqzJQRab2UIp6D1arfYZF1a6EN84KXwgLr40RdnWmk9PnT2Qs9_jr0TpWgoOoOagw1GkC_1pr0Xv9tnVts4pz5zjIIHLDmA_LQ9BfqBAmkXVJWaSFoHJJNdchTapF4kQnAy8kdF-3pMJ5ppzltsCZq0JaUqWYW4o3UjHAVTDwQmUtx-dGz3B2bgKd1uldKbEjw6OyvPBmHjPtOPSHcyUhfNcfpjG7DhVdaPeKmFU56P7nrHjwFvx-8IbO3WAPDqtQ9_kjUD2aKccUFLp6kH8TCuZOn_P82_wB)
Takes a set of strings (ASCII characters < "~"); returns the empty set for unambiguous and True for ambiguous.
#### How?
Alongside the set of given "syllables" we keep a set of "tips" which are generated by building two words from the syllables such that one is a prefix of the other (and they do not start with the same syllable). The tip is the longer word with the prefix removed.
At each iteration we try generating new tips by finding syllables which are prefixed by or do prefix a previously found tip. The new tip will be the difference. If no new tips are found output unambiguous, if a syllable was created as a new tip output ambiguous, otherwise rinse and repeat.
[Answer]
# [Python 3](https://docs.python.org/3.8/), ~~140 133~~ 129 bytes
This is my golf of [Ajax 1234](https://codegolf.stackexchange.com/users/74571/ajax1234)'s method (it was 197 at the time) - go upvote [that answer](https://codegolf.stackexchange.com/a/254204/53748)!
-7 Thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) (use `for j,k in q` loop in place of `while q` loop to remove the need for `j,k=q.pop()`.)
-4 Thanks to [Sʨɠɠan](https://codegolf.stackexchange.com/users/92689/s%ca%a8%c9%a0%c9%a0an) (function rather than full-program.)
```
def f(a):
d={};q=[(i,[i])for i in a]
for j,k in q:q+=[(j+i,k+[i])for i in a if''.join(a)[:1-len(j+i):k in d.setdefault(j,[k])]]
```
A function that accepts a list of strings and identifies ambiguity by success/failure:
* Errors when ambiguous (raises a ValueError "slice step cannot be zero") or
* Succeeding when unambiguous (returns `None`).
**[Try it online!](https://tio.run/##VY1BCsMgEEX3OcXsdIgNlG6KJScRF5YoHZNqTE2hlJ7daneFYZgH7/9ZX/kWw@m8bqVM1oHjBmUH0/j@XNKoOAlFGl3cgIACGN1BAy/mhkmmvkq@JzH3/yKQY2zwkUJtVPJ4WGxoIspfchoeNteHZl8y90LNGrUujtunWTiFdc8cEYtiJsf7tQ4TUO@2G@gv "Python 3.8 (pre-release) – Try It Online")** Or see the [test-suite](https://tio.run/##dZKxTsMwEIbn5ilOWZJQUwmxoKK@Ai8QPDixDW5TO3WckhYxsjEwMsDL9UXKORVtUlLLsnXx5/9@X67cuGejb@9Ku99zIUHGLJkGwGevb/erWRorkiqaSGNBgdLAaAA@mJOFD1fT1Rih@ViRxbgPgpJRNJkbpVExnd5cF0J7MJm2N/mkEg4Tsrpw8ZykC5pQulfL0lgHVgSBE5WrYAZhGAZpzggwSyD3i@UUTqPWbJmpp9rUVZBKYwhkHjLtKttw6/kOhWIZanVVBtV80myIOudQLcsHFXtc5vW8of/cEIX7GXnmjQ176znLvTWO3jje4KwVz30BO5TWBDRWyuBuDL38TmeWGU7UcEguO7U5z8kbApvt4SU@fbPZ9nM2fuD3pqEX/ftff2woqQonbPxgtCDQNsekKgvl4uhRRwn27OhqTUA0pcid4Ng4Vkyk0pwVBSIv44iASoKRsxtERzJeYyCaXJTOxyx3NSt8u52y43lRif5ppx54XlqlXYxpDwCBaPfzsft@j9K/G7OjI5oEBzzcfX2Gyf4X "Python 3.8 (pre-release) – Try It Online").
[Answer]
# Python3, 277 bytes:
```
def F(a):
q,s=[(j,k)for j in a for k in a if j!=k and j[:len(k)]==k],[]
for j,k in q:
if j==k:return 0
j,k=sorted([j,k],key=len)
if k[len(j):]in s:continue
for i in a:
if all(J==K for J,K in zip(i[:len(k)-len(j)],k[len(j):])):q+=[(j+i,k)];s+=[k[len(j):]]
return 1
```
[Try it online!](https://tio.run/##tVNNc5swED2HX7H1BalWM@30kiGjaw7JTP8A4SBAtAIsYRAx8OfdXUgd26HtKRqNPtjH27cPthn9L2e/3zXt8ZjrAh6Y4lEAe9HJmJWi4oVroQRjQQEdq@VoCig/yQqUzaGMo1pbVvFEyioRcRLMSHyZsHtkm@EYjFrt@9bCV3yEYdm51uucxXhORKVHiTx8gVcxcZY8SpCjizJnvbG9xiBxm1kFMRNW1TV7lPJpDj2KJwpOpmHmj7AvCxfmOLFyHu23VOLWYJHJfYeXtyiW8Cr129HsGpSJ98DrzncgYbPZBHGmBKhWQEZLmyfwNnqrdqn52bu@C@LCOQEpgdy8FvN1IvwZCslS5DpnWWWjpOka6hqHbGm2yniBS4mPBL3HraFwv0JeaVPr2i6UZSQtR205vpGrmTwjA89Q1gqw6JTD3bnk73V6t0txIodH5O7Mm@uc@SBgnJZKKP0wTpc5hwERA43kX/qRYcb9z1n14YP8/vCBzh1wksMZ1b38BNmIZqavEjJ0dUpPgsjci89J/XLq2sLUXrfsh7NawNxRt11TG8/CZxtiVwY3n18wH7ZZq28LY3Pq7vD5sA0FGB7cqK7T2I4P7IWDlMAOtIZn1of8@Bs)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
WS⊞υι¹≔⮌υθFθFυ¿№θ⁺ικ⎚¿‹LιL⪫υω⊞θ⁺ικ
```
[Try it online!](https://tio.run/##VY69DsIwDIT3PIVHWwoDcyfUCcRQwRNUVWgsIpvmp338ECoYWHynk/2dJz/GScdQ6@Y5OMCzvEq@58gyIxEMJXksFpg6M7Qw47G5U0o8C97c6mJyWMjC0uKHRsCFYNdCwA/AXks7WiwMoSRkC09q2D64MSJ14EJy@97VpdSGzNkjN97XXpTl078R/b75Z3W1ihhRo2JUTT2s4Q0 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings and outputs a Charcoal boolean, i.e. `1` for unambiguous, nothing for ambiguous. Explanation: Originally another port of @Ajax1234's answer, but since heavily simplified (see my comment on his answer), but it still seems to work, so...
```
WS⊞υι
```
Input the substrings.
```
¹
```
Assume they are unambiguous.
```
≔⮌υθFθ
```
Start a breadth-first search with a clone of the list of substrings.
```
Fυ¿№θ⁺ικ⎚
```
Loop over all of the substrings and if an ambiguous concatenation is found then clear the canvas.
```
¿‹LιL⪫υω⊞θ⁺ικ
```
Otherwise if the current string is not too long then add the concatenation to the search.
[Answer]
# [Python 3](https://docs.python.org/3/), 219 bytes
```
lambda x:any(t!=s and t==s[:len(t)]and c(s,t,x) for s in x for t in x)
def c(m,n,e,t=[]):d=m[len(n):];return d not in t and(d in e or any(s==d[:len(s)]and c(m,n+s,e,t+[d])or d==s[:len(d)]and c(n+s,m,e,t+[d])for s in e))
```
[Try it online!](https://tio.run/##fVDBboMwDL33K7JTiMptN6Z8CeOQ4LAhFaciQQr9eZo4wCqKJkW2Zb@89@z77H8tfi6d/F5uatCgWKgUzoX/kI4pBOaldHV1M1h40aRGW7jSl0Gwzo7MsR5ZoNJTKS5guogZSixN6WXdiArkUCcCFFXzNRo/jciAoaUfPqkUkErDIk0Sd1JC1nSbZuS7usR4raEREQe7L9gwCTHsmN2eEWK5jz36gk8Yd@x/Jjs5Li652RU1bxUvGVdjim1OI/BGvGIIoglxNlH62CWsbs9@IKYu2hQt1daekoYUQ3iZbZmfb9JZItV5Cbvmbm0@DiJ6dU7Df2epVqcW37p5Zd0CbQ6EArXStW9n9XbQ8dHYk@lBn1MCXWN@/BnLGmE@7hXCeriQb7c8AQ "Python 3 – Try It Online")
Takes a list of strings as input, returns False for unambiguous and True for ambiguous
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā€ãJ˜DÙQ
```
-6 bytes by checking if the flattened list contains only unique strings (taken from [*@lyxal*'s Vyxal answer](https://codegolf.stackexchange.com/a/254298/52210))
Outputs `0` if ambiguous and `1` if unambiguous.
[Try it online](https://tio.run/##yy9OTMpM/f//SOOjpjWHF3udnuNyeGbg///RSokl@blJQKSkA2QCCRAzFgA) or [verify all test cases with \$\leq4\$ items](https://tio.run/##ZU09CsIwFN5zikdwLHqBYhd1cBHn4vDyAy3YPGkLdtXBA7gJbq7eom7eoheJSSMtaAjvfX/5IrDKrMQa5iBJ6SlVKHINcQzLzYolHLrLFXhiX6fu/Gwf6/d90d62NmLeZscs32soNSrIDVPEAGZ0qGeh5bt@imOY9Fmjbcol8ohj6YbsZ6n4jqXcq8KLA0MRoFeFHCwRLKfhH3cIx/cBGuOwITfII6IQqKkQ7vpc7eUi/NY0jWONP2NRkBz/AA).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
€ # Map over each integer:
ã # Get the value'th cartesian power of the (implicit) input-list
J # Join each inner-most lists together to a string
˜ # Flatten the list of lists of strings
DÙQ # Verify the list doesn't contain any duplicated strings:
D # Duplicate this list
Ù # Uniquify the copy
Q # Check if the two lists are still the same
# (after which the result is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, ~~11~~ ~~8~~ 7 bytes
```
żvÞẊfÞu
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBciIsIiIsIsW8dsOe4bqKZsOedSIsIiIsIltcImNhXCIsIFwiYXJcIiwgXCJjYXJcIiwgXCJyZFwiXVxuW1wiZm9vXCIsIFwiYmFyXCIsIFwib2JhclwiLCBcImZvXCIsIFwiYmF6XCJdXG5bXCJiXCIsIFwiYWJcIiwgXCJiYVwiLCBcImFhXCJdXG5bXCJhYmNcIiwgXCJiY2RcIiwgXCJjZGFcIiwgXCJkYWJcIiwgXCJhYmNkXCJdXG5bXCJhYlwiLCBcImJjXCIsIFwiY1wiXVxuW1wieHh4XCIsIFwieHh4eHhcIl1cbltcImFcIiwgXCJheFwiLCBcInh4XCJdIl0=)
Two can play at the porting game, Kevin! -3 bytes by using cartesian products (taken from [*@KevinCruijssen*'s 05AB1E answer](https://codegolf.stackexchange.com/a/254291/78850)). And another -1 by using the `r` flag to get rid of a `$` that was needed for some weird reason (bug, probably).
Outputs `1` for unambiguous, `0` for ambiguous.
## Explained
```
żvÞẊfÞu
ż # The range [1, len(input)]
vÞẊ # nth cartesian power of the input for each number in that range
fÞu # are all the items unique?
```
[Answer]
# T-SQL, 156 bytes
Returns 1 when ambiguous, 0 when unambiguous
```
WITH C(z,y)AS(SELECT*,*FROM @
UNION ALL SELECT','+z+','+x+',',+x
FROM C,@ D WHERE z not
like'%,'+x+',%')SELECT
top 1~(-1/sum(1))FROM
C GROUP BY y ORDER BY 1
```
**[Try it online](https://dbfiddle.uk/q3MSfFmI)**
] |
[Question]
[
Given two strings `a` and `b`, count how many times `b` occurs as a substring in `a`, but only when it overlaps with another instance of `b`.
(This means that `1` will never be a valid output, because in order for the substring to be strictly overlapping, there must be at least one other instance for it to overlap with.)
## Test cases
```
input a input b output
trololololol trol 0
trololololol ol 0
trololololol lol 4
trololololol LOL 0
HAAAAHAAAAA A 0
HAAAAHAAAAA AA 7
Teeheeee ee 3
123123123123123123 12312312 4
(empty string) whatever 0
```
`b` will never be an empty string.
## Rules
* Matching must be case-sensitive
* You may use [any sensible IO format](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) apply
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# [J](http://jsoftware.com/), 35 33 31 24 bytes
```
1#.1<1#.#@[>|@-//~@I.@E.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1DG2AhLJDtF2Ng66@fp2Dp56Dq95/Ta7U5Ix8BXVHR3WFNAV1D0cgABOO6lAZXV1ddS4I20DBVkG9pCg/B6wWxIBBdSQFuKVNQNI5BLT7@PvglcflUHOwJC5ZY5BsaipYNiQ1NSMVCJBdZWhkDEZgBTAOAiE7oKICrEj9PwA "J – Try It Online")
*-7 bytes after reading [Luis Mendo's idea](https://codegolf.stackexchange.com/a/218985/15469) and realizing I could adapt it to J*
* `I.@E.` Indexes of matches
* `|@-//~@` Table of pairwise absolute differences
* `#@[>` Is it less than the substring length? (produces 0-1 table)
* `1#.` Sum rows
* `1<` Greater than 1? (produces 0-1 list)
* `1#.` Sum
[Answer]
# JavaScript (ES6), 69 bytes
Expects `(a)(b)`.
```
a=>g=(b,i=(t=0)-.1,p)=>~i?g(b,a.indexOf(b,i+1),i,q=b[i-p]?t-=~!q:0):t
```
[Try it online!](https://tio.run/##ldA7C4MwEADgvb/CZkqo8VELBSGKWwfBpVvp4CPaFDE@QunkX7c@qlKHopcQ7o77CMnTf/lVWLJc4IxHtIlJ4xMrITCQGYGCaAgrupwjYtXMTtqur7Asom8v7iYOOpKZXJDgxnB@twUm9b4wNWSKJuRZxVOqpDyBMQSi5Om4gNQHGrp9hZCkqpK2W6XmfIuaikGd1inXc8G/uy5OG/3hfFGn5nyTcn7edV6qK6UP2sZIBjXVgzKWSj8aiw3Q3AXf32g@ "JavaScript (Node.js) – Try It Online")
### How?
Given the last position **i** of **b** in **a**, we use `a.indexOf(b, i + 1)` to get the position of the next occurrence. We keep track of the previous position in **p** and figure out whether they overlap by testing if `b[i - p]` is defined.
At the very beginning of the process, we initialize **i** to **-0.1** so that it's neither **-1** (that would stop the recursion) nor **0** that would mean that there's a match at position **0**, while still being interpreted as **0** by `.indexOf()`.
Exemple for `a = "XABABA"` and `b = "ABA"`:
```
iteration | 1 | 2 | 3 | 4
-----------+-----------+----------+------+-----
i | -0.1 | 1 | 3 | -1
p | undefined | -0.1 | 1 | 3
i - p | NaN | 1.1 | 2 | n/a
match | "X**ABA**BA" | "XAB**ABA**" | none | n/a
^ ^
```
### Commented
```
a => // outer function taking the haystack a
g = ( // inner recursive function g taking:
b, // b = needle
i = (t = 0) - .1, // i = pointer in a, initialized to -0.1
// t = output, initialized to 0
p // p = position of the previous occurrence
) => //
~i ? // if i is not equal to -1:
g( // do a recursive call:
b, // pass b unchanged
a.indexOf( // set i = position of the next occurrence
b, // of b in a
i + 1 // starting at i + 1 (for the first iteration,
), // this gives -0.1 + 1 = 0.9, rounded to 0)
i, // set p = i
q = // the flag q is set to 0 if this is the first
// occurrence in a chain of valid matches:
b[i - p] ? // if i - p is less than the length of b:
t -= ~!q // add 2 to t if q = 0, or only 1 otherwise
// either way, set q to a non-zero value
: // else:
0 // set q to 0
) // end of recursive call
: // else:
t // stop the recursion and return t
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
yXf&-|wn<s1>s
```
Inputs are in reverse order: `b`, then `a`.
[Try it online!](https://tio.run/##y00syfn/vzIiTU23pjzPptjQrvj/f/Wc/Bx1LvWSovwcGFQHAA) Or [verify all test cases](https://tio.run/##y00syfmf8L8yIk1Nt6Y8z6bY0K74v0vIf/WSovwcdS4wBYNALjaxHGyCPv4@mIKOQOzhCARgAsRzxBRKTQUSIampGampYKahkTEYITERCCiYmJQMJNUB).
### Explanation
Consider inputs `'lol'` and `'trololololol'` as an example.
```
y % Implicit inputs: b, a. Duplicate second-top element in stack
% STACK: 'lol', 'trololololol', 'lol'
Xf % Find second string in first string. Produces a row vector (possibly
% empty) with the indices of all occurrences of b in a
% STACK: 'lol', [4 6 8 10]
&- % Square matrix of pairwise differences
% STACK: 'lol', [0 2 4 6; -2 0 2 4; -4 -2 0 2; -6 -4 -2 0]
| % Absolute value, element-wise
% STACK: 'lol', [0 2 4 6; 2 0 2 4; 4 2 0 2; 6 4 2 0]
w % Swap
% STACK: [0 2 4 6; 2 0 2 4; 4 2 0 2; 6 4 2 0], 'lol'
n % Number of elements
% STACK: [0 2 4 6; 2 0 2 4; 4 2 0 2; 6 4 2 0], 3
< % Less than? Element-wise
% STACK: [1 1 0 0; 1 1 1 0; 0 1 1 1; 0 0 1 1]
s % Sum of each column. For each ocurrence, this gives the number of
% occurrences, including itself, that are close enough to overlap.
% If there are no occurrences this gives 0
% STACK: [2 3 3 2]
1> % Greater than 1? Element-wise. For each occurrence, this gives 1 (true)
% if there is a different occurrence that is close enough to overlap
% STACK: [1 1 1 1]
s % Sum. Implicit display
% STACK: 4
```
(Note that the code `1>s` cannot be replaced by `qz` because when there are no occurrences of `b` in `a` that would give `1` instead of `0`, due to the behaviour of the previous `s`).
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 102 bytes
```
lambda a,b:sum(b==a[i-1:i+(T:=len(b)-1)]*(b in a[i+~T:i+T-1]or b in a[i:i+T*2])for
i in range(len(a)))
```
[Try it online!](https://tio.run/##tZK7boMwGEZ3P4UbFhuMEkKlVlQMbB0idfFGGezENEgEkCFDl7469QUiaEim1KDf8newDxg3392xrsLXRvbO05oX1boxCcjjz75kJ35gkBEetecT4nHM0sIPosJDNIpLUSGO/QBnLuKwqKCC3g9VlPpBVks4hjpxtxnOVVboTLLqSyA9n2GMe2fRM7NMHT71gmuJzdytSm@JwFQ0WdvdeDMtfbgsvcjI401ZGmTAOYgc5kjJcEQH15sU3VlW8J8/bra8NU8dNjGLjifmymbBfSXQgBHICdxrjABadbIux2tFoBmrfoPJAryDbPe8yHYfu8u890Q1UxKNkptA1xdDqBBHoZqOTQ1NHGzDP7d@YBwML4MjyNpWyM78WchxHO8JRHYThkjtBgb9Lw "Python 3.8 (pre-release) – Try It Online")
Explanation: it's pretty readable already. Just that `i+~T` == `i-T-1`, and the `:=` is equivalent to an assignment but can be inserted in a lambda (to make the code shorter)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
wÐƤẹ1ạ€`<L}S>1S
```
A dyadic Link accepting `a` on the left and `b` on the right which yields the count.
**[Try it online!](https://tio.run/##y0rNyan8/7/88IRjSx7u2mn4cNfCR01rEmx8aoPtDIP///@vVFKUnwODSv@VQCQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/7/88IRjSx7u2mn4cNfCR01rEmx8aoPtDIP/H16uD@T@/x8drVRSlJ8Dg0o6CmC@UiyXDqYMLvEcXBI@/j4QCQ9HIAATjiBxR@yiUOGQ1NSMVCAAiQFJsJihkTEaAsnCOBA1IJHyjMSS1LLUIqBILAA "Jelly – Try It Online").
### How?
```
wÐƤẹ1ạ€`<L}S>1S - Link: a, b
ÐƤ - for postfixes (of a):
w - first 1-indexed index (of b)
ẹ1 - indices of 1 (i.e. X = a list of starts of b in a)
` - use (X) as both arguments of:
€ - for each (v in X):
ạ - (v) absolute difference (across each of X)
-> list of lists of distances between starts
L} - length (of b)
< - less than
S - sum
>1 - greater than 1 (i.e. not just overlapping itself)
S - sum
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes
```
(?=(.+)(.*¶)\1$)(.(?!\2))+?((?=\1)|(?<=\1))
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZyg81/D3lZDT1tTQ0/r0DbNGEMVIEvDXjHGSFNT214DKBljqFmjYW8DojX//y8pys@BQR0QhwtFBJ2fgy7g4@/D5eEIBGDCUccRlefIFZKampEKBDqpqVyGRsZoSAfG4irPSCxJLUstAgA "Retina 0.8.2 – Try It Online") Takes input on separate lines but link includes test suite that splits on comma for convenience. Explanation: The program consists of a single match stage that outputs the count of matches of the pattern within the string `a`. For each match:
```
(?=(.+)(.*¶)\1$)
```
The remainder of the string `a` is split into two parts, the first of which must equal string `b` (which is therefore effectively captured into `$1`). The part of the string `a` after this match of the string `b` is captured into `$2`.
```
(.(?!\2))+?
```
Advance as few characters as possible, and definitely without reaching the end of this particular match of string `b` in string `a`.
```
((?=\1)|(?<=\1))
```
Find an overlapping match of string `b`. Note that in the case of a forward overlap, the lazy quantifier ensures that this match will always stop on or before the next match of string `b`.
[Answer]
# [R](https://www.r-project.org/), ~~90~~ 89 bytes
```
function(x,y,z=rle(diff(el(gregexpr(paste0("(?=",y,")"),x,,T)))<nchar(y)))sum(z$l[z$v]+1)
```
A byte saved by Dominic van Essen.
[Try it online!](https://tio.run/##dcqxDoJADADQ3a8wDUMvnonoCjFsDiQubMaBYA9ITiDHgcDPYwOyqLRN077WjGrr7UfVFInNywI72cvBN5rwkSuFpDE1lFJXGazi2tIBAc8@8BcIELKTMhJCeEWSxQZ7HuvmiYOjb4PT3neuGBWCNaVeEuS0gtj8HlZYr3h4DWe/BBxTC5iDv/jRiCgjDiZuE7nH01fxcZnnF4ZXFltqyYAY3w "R – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 117 bytes
```
sub f{($a,$b,$f,%s,$c)=@_;!$s{$x=1+index$a,$b,$_}++&&$x&&($w=$f&&$x-$f<length$b,$f=$x,$c+=$j*$w,$j=2-$w)for 0..99;$c}
```
[Try it online!](https://tio.run/##jZJbT4NAEIXf/RXTzUgKbJteNKbWjfbNxEZe@qaGQF16sdIKKDQNvx2X5VK2ibEDWThnvzkZwu54sLnOsvDbBe/QRoeiS9GjlyHFuc4e7HELwwMmrG@u/HeelICdmqamYaJpbYwZevl7B727DfcX0VJGMExEhMlwbWBMcc0GHYx1bxtAr9sdjcY4TzOh2i8kCrab6iIUqpL@Uffe6EX@/JtX1Bm8Kq/@5afWtCGP@Y8TUXKZNAcgijqHV@RNzc84X3JRSpzgVWdY8/3B8OSWXO0XXcfvPcmt8@OlE/EfHhT7@fz6QbZ87quDwpOdOCRoj0sfcLGNWM/0CkAv/F2w8iO5BfwL8ia4F7/rg8AtEMMwnq0ZWE8t0qRJOYWAmeyAPFlmgMPQAXAZuq@@aEqzXw "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
I↨E⌕Aθη⊙↔⁻⌕Aθηι∧λ‹λLη¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXDN7FAwy0zL8UxJ0ejUEchQ1NHwTGvUsMxqTg/p7QEKJ@ZV1qMriJTE6wsRSNHR8EntbgYQuell2RoZGiCgI6CIZC0/v/f0MgYDXHBWP91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Conveniently, Charcoal's `FindAll` command also includes overlapping matches.
```
θ First input
η Second input
⌕A Find all matches
E Map over positions
⌕Aθη All matches
↔⁻ Absolute difference with
ι Current match
⊙ Does any difference satisfy
λ Current difference
∧ Non-zero and
λ Current difference
‹ Less than
L Length of
η Second string
↨ ¹ Take the sum
I Cast to string
Implicitly print
```
I don't use `Sum` here because it doesn't output `0` for an empty list.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.sIÅ?ƶ0KDδαIg‹O1›O
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/218990/52210).
[Try it online](https://tio.run/##yy9OTMpM/f9fr9jzcKv9sW0G3i7ntpzb6Jn@qGGnv@Gjhl3@//@XFOXnwCAXEAMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H@94ojDrfbHthl4u5zbcm5jRPqjhp3@ho8advn/1/kfHa1UUpSfA4NKOmCuUqwOhjh20Rzswj7@PmBhD0cgABOOQFFHbGIQwZDU1IxUIACKAAmQiKGRMRoCysHYYBVAfnlGYklqWWqRUmwsAA).
**Explanation:**
```
.s # Get all suffices of the (implicit) input-string
IÅ? # Check for each if they start with the second input-string
# (1 if truthy; 0 if falsey)
ƶ # Multiply each value by their 1-based index
0K # Remove all 0s
δ # Apply double-vectorized,
D # with a copy of itself:
α # Get the absolute different between the values
Ig‹ # Check for each that it's lower than the length of the second input
O # Sum the checks of each row together
1› # Check for each whether it's larger than 1
O # And sum those checks together again
# (after which the result is output implicitly)
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 20 bytes [SBCS](https://github.com/abrudz/SBCS)
```
+/1<1⊥≢⍤⊣>∘|∘.-⍨⍤⍸⍤⍷
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=09Y3tDF81LX0UeeiR71LHnUttnvUMaMGiPV0H/WuAAn17gCT2wE&f=U8/Jz1FXSFNQLynKz4FBdS4wF1McAA&i=AwA&r=tryAPL&l=apl-dyalog&m=train&n=f)
A train submission which takes `b` on the left, and `a` on the right.
-2 bytes from Adám(helped trainify the function)
## Explanation
```
⍷ boolean array where b occurs in a
⍸⍤ indices of 1s in it
∘.-⍨⍤ all pairwise differences
| take the absolute value of it(vectorized)
≢⍤⊣ length of b
> greater than the absolute values?(vectorizes)
1⊥ sum the columns of that result
1< are they >1?
+/ sum the result
```
[Answer]
# [Perl 5](https://www.perl.org/) (`-00p`), 54 bytes
```
$_=/
(.+)(.*\1)$/?()=/(?=$1$2$2)|(?<=$1)$2$2(?!$2)/g:0
```
[Try it online!](https://tio.run/##ZY@xCsIwEIb3ewqFDDnFXltxUUvo5lBwcSyIw2ELsQ1pUASf3ZgKCm3/@znu@7YzbPXGd1RKvhn3nHXO1s21RKKdF@eMQEZLlNGiTFCQkpiRVJlIRCpSfEm1Dzf2INU8GLpuY@@dbfVvoAeAgZoIPTHFsQA45CHflUM@wsAn5opDIBSSdD3qXwEMfkN4VBfHd7bv1ri6bTq/imNtPg "Perl 5 – Try It Online")
[Answer]
# [Japt](https://ethproductions.github.io/japt/?v=1.4.6&code=8FYK5M8tWDxWbAro&input=InRyb2xvbG9sb2xvbCIKImxvbCI=), 12 bytes
Been quite a while since I've done any Japt, probably has some room for improvement.
```
ðV
äÏ-X<Vl
è
```
[Try it out here.](https://ethproductions.github.io/japt/?v=1.4.6&code=8FYK5M8tWDxWbAro&input=InRyb2xvbG9sb2xvbCIKImxvbCI=)
Explanation:
```
ðV # Get all indices of needle in input
äÏ-X<Vl # For every consecutive pair in the result, check if their distance is small enough that they overlap
è # Return the number of items that were true
```
] |
[Question]
[
*Inspired by [this](https://codegolf.stackexchange.com/questions/135417/reverse-array-sum)*
In the linked challenge, we are asked to apply addition to the elements of the original and the reverse of the input array. In this challenge, we are going to make it slightly more difficult, by introducing the other basic math operations.
Given an array of integers, cycle through `+, *, -, //, %, ^`, where `//` is integer division and `^` is exponent, while applying it to the reverse of the array. Or, in other words, apply one of the above functions to each element of an array, with the second argument being the reverse of the array, with the function applied cycling through the above list. This may still be confusing, so lets work through an example.
```
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9]
Operand: + * - / % ^ + * -
[ 9, 8, 7, 6, 5, 4, 3, 2, 1]
Result: [10, 16, -4, 0, 0, 1296, 10, 16, 8]
```
so the output for `[1, 2, 3, 4, 5, 6, 7, 8, 9]` would be `[10, 16, -4, 0, 0, 1296, 10, 16, 8]`
To cover the corner cases, the input will never contain a 0, but may contain any other integer in the range from negative infinity to positive infinity. You may take input as a list of strings representing digits if you want.
## Test cases
```
input => output
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [10, 16, -4, 0, 0, 1296, 10, 16, 8]
[5, 3, 6, 1, 1] => [6, 3, 0, 0, 1]
[2, 1, 8] => [10, 1, 6]
[11, 4, -17, 15, 2, 361, 5, 28] => [39, 20, -378, 7, 2, 3.32948887119979e-44, 9, 308]
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code (in bytes) wins!
[Answer]
# Jelly, 10 bytes ([fork](https://github.com/miles-cg/jelly/tree/tie))
```
+×_:%*6ƭ"Ṛ
```
I was just working on implementing a quick for this the other day, so it's quite surprising to see a use for it so soon. It still only exists as a fork, so you cannot try it online.
## Sample output
```
$ ./jelly eun '+×_:%*6ƭ"Ṛ' '[1,2,3,4,5,6,7,8,9]'
[10, 16, -4, 0, 0, 1296, 10, 16, 8]
$ ./jelly eun '+×_:%*6ƭ"Ṛ' '[5,3,6,1,1]'
[6, 3, 0, 0, 1]
$ ./jelly eun '+×_:%*6ƭ"Ṛ' '[2,1,8]'
[10, 1, 6]
$ ./jelly eun '+×_:%*6ƭ"Ṛ' '[11,4,-17,15,2,361,5,28]'
[39, 20, -378, 7, 2, 3.32948887119979e-44, 9, 308]
```
## Explanation
```
+×_:%*6ƭ"Ṛ Input: array
6ƭ Tie 6 dyads
+ Addition
× Multiplication
_ Subtraction
: Integer division
% Modulo
* Power
" Vectorize with
Ṛ Reverse
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
~~This challenge favours languages that can create infinite lists of functions.~~ Maybe not, `eval` FTW
```
zF¢+ë+*-÷e%^Ṡze↔
```
[Try it online!](https://tio.run/##ATMAzP9odXNr//96RsKiK8OrKyotw7dlJV7huaB6ZeKGlP///1sxLDIsMyw0LDUsNiw3LDgsOV0 "Husk – Try It Online")
### How?
```
¢+ë+*-÷e%^ The infinite list [+,*,-,÷,%,^,+,*,-,...
ë+*-÷ The list [+,*,-,÷]
e%^ The list [%,^]
+ Concatenated
¢ Then repeated infinitely
↔ The input reversed e.g [9,8,7,6,5,4,3,2,1]
Ṡze Zipped with itself [[9,1],[8,2],[7,3],[6,4],[5,5],[4,6],[3,7],[2,8],[1,9]]
zF Zipwith reduce, the list of functions and the list of lists.
[F+[9,1],F*[8,2],F-[7,3],F÷[6,4],F%[5,5],F^[4,6],F+[3,7],F*[2,8],F-[1,9]]
[10 ,16 ,-4 ,0 ,0 ,1296 ,10 ,16 ,8 ]
```
Alternative 17 byte solution:
```
ṠozIzI¢+ë+*-÷e%^↔
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
Â"+*-÷%m"Ig×)øε`.V
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cJOStpbu4e2quUqe6Yenax7ecW5rgl7Y///RhoY6CiY6CrqG5joKhqY6CkY6CsZmQDEQ0yIWAA "05AB1E – Try It Online")
**Explanation**
```
 # push a reversed copy of the input
"+*-÷%m" # push the list of operators
Ig× # repeat it input times
)ø # zip together
ε # apply to each triplet
` # push separately to stack
.V # evaluate
```
[Answer]
# Bash + GNU utilities, 53
```
tac $1|paste -d, $1 -|tr ',
' '
;'|paste -sd+*-/%^|bc
```
This script takes a filename as a command-line parameter.
[Try it online](https://tio.run/##Rck7CoQwFEbh/l/FLZSAekd8Owy4FCFGQRsJkytYZO/RRizPdybt1mC00EDbbg/5yClwixDzC0G0oajwVjtZiOfsDmIvf1IZFCn81PPcnCacx6OfTAgFSlSo0aBFhx5fXA).
The nice thing here is that `paste -d` allows a list of separators to be given, which are used cyclically. The rest it just getting the input into the right format to do this.
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
*-3 bytes thanks to ovs.*
```
lambda l:[eval(j+'*+*-/%*'[-~i%6::6]+l[~i])for i,j in enumerate(l)]
```
[Try it online!](https://tio.run/##RY/LDoIwEEX3/YrZmPKMaRXEJnxJ7QJjiSXlEagmbvh1ZNCUWZzFPO69M3zcs@/4Upe3xVbt/VGBFVK/Kxs0MY3iKD0eIirT2RxyIXIVWzkbFdb9CCZpwHSgu1erx8rpwIZqcXpyE5QgCawlKaMJUI44Ic6IDJEjLogCcaUq@Z9kfnvbYT/4MffNYm8y5tVTtqmybHfOmbfl6xFRhGwPYPwtsIBhNJ2DOjDh8gU "Python 2 – Try It Online")
## [Python 2](https://docs.python.org/2/), 95 bytes
```
lambda l:[[add,mul,sub,div,mod,pow][i%6](v,l[~i])for i,v in enumerate(l)]
from operator import*
```
[Try it online!](https://tio.run/##Fcq9CsIwGAXQ3ae4i9DKXaz/gk8SM6SkwUCSL8S04uKrR7oeTv7Wl6ShucezBRNHaxDuShlrGefA9zzS@oVRLLN8tPLbs@4WBvXzundS4LnAJ0xpjlMxdepCrzeuSITkFdYSs5S6a7n4VOE6tScG4kAciRNxJi7Elbjpvv0B "Python 2 – Try It Online")
`eval` is evil... but perhaps more golfy. :P
[Answer]
# [Haskell](https://www.haskell.org/), ~~74~~ ~~117~~ 105 bytes
```
x#y=fromIntegral.floor$x/y
x%y=x-x#y
f u=[o a b|(o,a,b)<-zip3(cycle[(+),(*),(-),(#),(%),(**)])u(reverse u)]
```
[Try it online!](https://tio.run/##VYtBDoIwEEXXcopJgKTFgkEUMZEDeAbSRdGixEJJAQPGu9fBHcm8ZOb9P0/Rv6RS1k7unFdGN9d2kA8jVFQprY037WZn8ud8CrHgVDDmhQYB5ZdoJlhJL@Gn7hJym29KFmRLGQmQEHERf7kDyulIjHxL00sYKbeNqFvI4a7B2XSmbgfwoIIijqIzX5kjg4RByiDGWUf7v8zWMkZ1YBDGJ0zxGUtJim5ZM25/ "Haskell – Try It Online")
*Saved 12 bytes thanks to @nimi*
There is certainly a better way to achieve this.
**EDIT** 1. Fixed exponent for integers; 2. There's definitely a better way, see comment below: ~~95~~ 91 bytes
```
x#y=fromIntegral.floor$x/y
x%y=x-x#y
f=zipWith3($)(cycle[(+),(*),(-),(#),(%),(**)])<*>reverse
```
[Try it online!](https://tio.run/##VYtBDoIwEEXXcopJgIRiwSCKmFj3nsCFYUGwlcZCSSGmePk6uCOZl8y8/6etxzdXyjnrz0wY3d36ib9MrVKhtDaB3c2eDWdmEyx4gn3lcJdTm0cBiZq5UfwRbQmNYiRBfCRc7phU5BJfDf9wM3LX1bIHBk8N3mYwsp8gAAGPLE3P1cocKeQUCgoZzjra/2W5lhmqA4UkO2GKz1jKC3TLWlbuBw "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
żṚj"“+×_:%*”ṁ$V
```
**[Try it online!](https://tio.run/##AT4Awf9qZWxsef//xbzhuZpqIuKAnCvDl186JSrigJ3huYEkVv///1sxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5XQ "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8///onoc7Z2UpPWqYo314eryVqtajhrkPdzaqhAFlDrc/alpzdNLDnTOANBBlgaiGOQq2dgpAVZH//0dHG@ooGOkoGOsomOgomOoomOkomOsoWOgoWMbqcClEm4KlgIJAZYZgESMw2wLMNjQEa9M1BGoxNIUYZGYINsfIIjYWAA "Jelly – Try It Online").
### How?
```
żṚj"“+×_:%*”ṁ$V - Link: list of numbers, a e.g. [5, 3, 6, 1, 1]
Ṛ - reverse a [1, 1, 6, 3, 5]
ż - interleave [[5,1],[3,1],[6,6],[1,3],[1,5]]
$ - last two links as a monad:
“+×_:%*” - literal list of characters ['+','×','_',':','%','*']
ṁ - mould like a ['+','×','_',':','%']
" - zip with the dyad:
j - join ["5+1","3×1","6_6","1:3","1%5"]
V - evaluate as Jelly code (vectorises) [6, 3, 0, 0, 1]
```
[Answer]
# JavaScript (ES7), ~~68~~ 67 bytes
```
a=>[...a].map((v,i)=>(x=a.pop(),o='+*-/%'[i%6])?eval(v+o+x)|0:v**x)
```
```
let f =
a=>[...a].map((v,i)=>(x=a.pop(),o='+*-/%'[i%6])?eval(v+o+x)|0:v**x)
console.log(JSON.stringify(f([1, 2, 3, 4, 5, 6, 7, 8, 9] ))) // [10, 16, -4, 0, 0, 1296, 10, 16, 8]
console.log(JSON.stringify(f([5, 3, 6, 1, 1] ))) // [6, 3, 0, 0, 1]
console.log(JSON.stringify(f([2, 1, 8] ))) // [10, 1, 6]
console.log(JSON.stringify(f([11, 4, -17, 15, 2, 361, 5, 28]))) // [39, 20, -378, 7, 2, 3.32948887119979e-44, 9, 308]
```
[Answer]
# [Perl 6](https://perl6.org), ~~67~~ 66 bytes
*Saved 1 byte thanks to @nwellnhof.*
```
{map {EVAL ".[0] {<+ * - div % **>[$++%6]} .[1]"},zip $_,.reverse}
```
[Try it online!](https://tio.run/##FcxNC4IwHAfgu5/ihyjo/G9kL1ZYQYedKj0EQQwJoQVCgmwklPjZF16fw9Np887cx2pcyuIk7/wqJS9KLm/Hc@61XwQv7N3Q1h2GyeALNasw7BIwcDybHiEYO6ggScKsGiFUWvkj/ZoOwYOE0b02Vo8u92w9bVGUEuaEBWFJWBEywpqwIWzjOHd/ "Perl 6 – Try It Online")
Very unimaginative (and probably bad) solution. Zips the argument with itself reversed. The resulting list is then mapped with the block that `EVAL`s the string `a (operator) b`. The operator is chosen from the list of strings `<+ * - div % **>` using the free `state` (think `static` in C — the value persists across the calls of the block) variable `$`. This is created for each block separately and set to 0. You can do anything you like with it, but you may reference it only once (each occurence of `$` refers to another variable, actually). So `$++%6` is actually 0 during the first call, 1 during the second, ... 5 during the 6th, 0 during the 7th and so on.
I at first tried to do without an `EVAL`. The operators are in fact just subs (= functions), but their names are so extremely ungolfy (`&infix:<+>` and so on) that I had to forgo that approach.
[Answer]
# [Desmos](https://desmos.com/calculator), ~~107~~ 104 bytes
```
k=l.length
L=mod([1...k],6)
R=l[k...1]
f(l)=\{L=1:l+R,L=2:lR,L=3:l-R,L=4:\floor(l/R),L=5:\mod(l,L),l^R\}
```
Very straightforward implementation of the challenge, can probably be golfed further.
[Try It On Desmos!](https://www.desmos.com/calculator/owt7vdmr2i)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/mfgbvpqvcc)
[Answer]
# [Factor](https://factorcode.org/) + `sequences.repeating`, 69 bytes
```
[ dup reverse { + * - /i mod ^ } over length cycle [ execute ] 3map ]
```
[Try it online!](https://tio.run/##Rc27DoIwGEDhnac4s0aM4t0HMC4uxolo0tQfJJZSSzES4rOjcXE5yzecTOlQ@f503B92G@7irRhqeTRitdSUKtx@ibPG6lBUtv5r7MWJCoXNcV5CaJ0vbGAbRR0TpiTMmLNgyYo17z7l2ji8PMXXQseQASPGBWV15cKb6isYsfl3qltthBR5iW6CcCYplePca2UMcf8B "Factor – Try It Online")
## How?
```
! { 1 2 3 4 5 6 7 8 9 }
dup ! { 1 2 3 4 5 6 7 8 9 } { 1 2 3 4 5 6 7 8 9 }
reverse ! { 1 2 3 4 5 6 7 8 9 } { 9 8 7 6 5 4 3 2 1 }
{ + * - /i mod ^ } ! { 1 2 3 4 5 6 7 8 9 } { 9 8 7 6 5 4 3 2 1 } { + * - /i mod ^ }
over ! { 1 2 3 4 5 6 7 8 9 } { 9 8 7 6 5 4 3 2 1 } { + * - /i mod ^ } { 9 8 7 6 5 4 3 2 1 }
length ! { 1 2 3 4 5 6 7 8 9 } { 9 8 7 6 5 4 3 2 1 } { + * - /i mod ^ } 9
cycle ! { 1 2 3 4 5 6 7 8 9 } { 9 8 7 6 5 4 3 2 1 } { + * - /i mod ^ + * - }
[ execute ] 3map ! { 10 16 -4 0 0 1296 10 16 8 }
```
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
lambda l:[eval(y+'+*-/%*'[x%6]*-~(x%6>4)+l[~x])for x,y in enumerate(l)]
```
[Try it online!](https://tio.run/##FcXdCoIwGADQV/kYiPtRIjPLoF5k7WLRRsKcMmZsN7766rs5Z83xs/iu2PuzOD2/3hrcTZqvdjSLWvD2UPFapmpQvN3p/0fPhJN7UswuAVKTYfJg/DaboKOhjqmyhslHaqkkR9IA6ZAT0iNnZEAuyBUZiWKs/AA "Python 2 – Try It Online")
Saved 2 bytes thanks to ovs!
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~63~~ 57 bytes
```
->a{t=0;a.map{|x|eval [x,a[t-=1]]*%w(** % / - * +)[t%6]}}
```
Nothing fancy, really. Just iterate on the array, use an index as reverse iterator, join into a string using the right operator, evaluate, rinse and repeat.
[Try it online!](https://tio.run/##NU5LCsIwFNz3FLMpaHxRXzWxIvUi4S0i2JVCkaiVtmePIaWzmy/zet9@sW2ivvohNPuL3z59N4z9eP/4B1xP3gXdsIgqvyulUGIHDYXN2oXSyjRFVyDBMaEiHAhHgiFYwolQE85Cc8BkN@kpyYtYZVovlDn3Nacum3nRch6sailkPhfGDq0LMsU/ "Ruby – Try It Online")
[Answer]
# [k](https://en.wikipedia.org/wiki/K_(programming_language)), 40 bytes
```
{_((#x)#(+;*;-;%;{y!x};{*/y#x})).'x,'|x}
```
[Try it online!](https://tio.run/##FYpBDoMgFAWv8hpiAJU2nwpi/2G6Y8Oi22@Qs1PcTDKZKe5Xes@f@jVGiVVm4ZkdT1zPhzSu8@tU0qx9aln1Ja1nbQgeb2wIiNiRcHAYHkEg9oOJiUZ2tIPC/UYar0@2/wE "K (oK) – Try It Online")
```
{ } /function(x)
|x /reverse x
x,' /zip concat with x
( ; ; ; ; ; ) /list of operations
+ * - % /add, mult, sub, div
{y!x} /mod (arguments need to be reversed)
{*/y#x} /pow (repeat and fold multiply)
((#x)# ) /resize operations to length of x
.' /zip apply
_ /floor result
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~27~~ 23 bytes
-4 bytes thanks to @LuisMendo
```
tP+1M*1M-IM&\w1M^v"@X@)
```
[Try it online!](https://tio.run/##y00syfn/vyRA29BXy9BX19NXLabc0DeuTMkhwkHz//9oQ0MdBRMdBV1Dcx0FQ1MdBSMdBWMzoBiIaRELAA "MATL – Try It Online")
### Explanation:
```
tP % duplicate and flip elements
+ % push array of sums (element-wise)
1M* % push array of products (element-wise)
1M- % push array of subtractions (element-wise)
IM&\w % push array of divisions and modulo (element-wise)
1M^ % push array of power (element-wise)
v % vertically concatenate all arrays
"@X@) % push to stack values with the correct index based on operator
% (implicit) convert to string and display
```
[Answer]
# J, ~~44~~ 42 bytes
Crossed out 44, yada yada...
-2 bytes thanks to @ConorO'Brien
```
_2+/`(*/)`(-/)`(<.@%/)`(|~/)`(^/)\[:,],.|.
```
[Try it online!](https://tio.run/##y/r/P03BVk8h3khbP0FDS18zQUMXRNjoOaiC6Jo6EBmnrxkTbaUTq6NXo8eVmpyRr5CmYGelkKlnCeMZGuoomOgoxBua6ygYmuooGOkoGJsBxUBMi///AQ)
So many parens and inserts... Surely there's a better way to do this (maybe using insert rather than infix?)
# Explanation
```
_2(+/)`(*/)`(-/)`(<.@%/)`(|~/)`(^/)\[:,],.|. Input: a
],.|. Join a with reverse(a)
, Ravel (zip a with reverse(a))
_2 \ To non-overlapping intervals of 2
(+/)`(*/)`(-/)`(<.@%/)`(|~/)`(^/) Apply the cyclic gerund
+/ Insert addition
*/ Insert multiplication
-/ Insert subtraction
<.@%/ Insert integer division
|~/ Insert mod
^/ Insert exponentiation
```
Some notes:
J doesn't have integer division, so we compose `%`-division with `>.`-floor. J's mod (`|`) does the reverse order of what we'd expect, so we have to invert its order using `~`-reflexive.
Even though we're moving over intervals of 2, we have to use `/`-insert to insert the verbs to have them be used dyadically since that's how `\`-infix works.
[Answer]
# [Perl 5](https://www.perl.org/), 68 + 1 (-p) = 69 bytes
```
print$",eval'int 'x($i%6==3).$_.qw|+ ** % / - *|[$i--%6].$F[$i]for@F
```
[Try it online!](https://tio.run/##DcZBCsIwEAXQq3wkoRqd2LE2uim46s4TSJEuKgRKE2NRFz27Y1bvxSGNtUhMfprVaje8@7HIRfFdK69d01Qbq@72@Vm2MAYaexDMclOeSLvOqja3e4R0aUWYcQTxCVzjgMoxsudfiLMP00voWtuSS6H@Dw "Perl 5 – Try It Online")
Takes input as space separated list of numbers.
[Answer]
# [R](https://www.r-project.org/), 74 bytes
```
function(l)Map(Map,c(`+`, `*`, `-`, `%/%`, `%%`,`^`),l,rev(l))[1:sum(l|1)]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNH0zexQAOIdZI1ErQTdBQStECELohQ1VcFU0AyIS5BUydHpyi1DKhDM9rQqrg0VyOnxlAz9n@aRrKGkY6hjoWm5n8A "R – Try It Online")
This is the final answer I came up with. It returns a list of length `length(l)` where each element is a list containing the corresponding element. Kinda crappy but they're all there. If that's unacceptable, either of the `Map` can be replaced with `mapply` for +3 bytes.
Since R operators are all functions (the infix notation just being syntactic sugar), I tried to select one from a list; for example, the 94 byte solution below.
To try and get rid of the loop, I tried `sapply`, but that only works with a single function and input list. Then I remembered the multivariate form, `mapply`, which takes an `n-ary` function `FUN` and `n` succeeding arguments, applying `FUN` to the first, second, ..., elements of each of the arguments, *recycling if necessary*. There is also a wrapper function to `mapply`, `Map` that ["makes no attempt to simplify the result"](https://stat.ethz.ch/R-manual/R-devel/library/base/html/funprog.html). Since it's three bytes shorter, it's a good golfing opportunity.
So I defined a trinary function (as in the 80 byte solution below) that takes a function as its first argument, and applies it to its second and third ones. However, I realized that `Map` is a function that takes a function as its first argument and applies it to successive ones. Neat!
Finally, we subset at the end to ensure we only return the first `length(l)` values.
# [R](https://www.r-project.org/), 80 bytes
```
function(l)Map(function(x,y,z)x(y,z),c(`+`, `*`, `-`, `%/%`, `%%`,`^`),l,rev(l))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNH0zexQAPOrdCp1KnSrNAAkTrJGgnaCToKCVogQhdEqOqrgikgmRCXoKmTo1OUWgY0Q/N/moahlaXmfwA "R – Try It Online")
This one doesn't work, as it will return 6 values for lists with less than 6 elements.
# [R](https://www.r-project.org/), 94 bytes
```
function(l){for(i in 1:sum(l|1))T[i]=switch(i%%6+1,`^`,`+`,`*`,`-`,`%/%`,`%%`)(l,rev(l))[i]
T}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHszotv0gjUyEzT8HQqrg0VyOnxlBTMyQ6M9a2uDyzJDlDI1NV1UzbUCchLkEnQRuItYBYF4hV9VVBpGqCpkaOTlFqGdAsTaA2rpDa/2kahlaWmv8B "R – Try It Online")
Explanation (mildly ungolfed):
```
function(l){
for(i in 1:length(l)){
fun <- switch(i%%6+1,`^`,`+`,`*`,`-`,`%/%`,`%%`) # select a function
res <- fun(l,rev(l)) # apply to l and its reverse
T[i] <- res[i] # get the i'th thing in the result
}
T # return the values
}
```
Because each of the functions is vectorized, we can index at the end (`res[i]`). This is better than the `eval` approach below.
## [R](https://www.r-project.org/), 100 bytes
```
function(l)eval(parse(t=paste("c(",paste(l,c("+","*","-","%/%","%%","^"),rev(l),collapse=","),")")))
```
[Try it online!](https://tio.run/##JYxBCoAwDAS/IgEh0Yh4VPQrQikpCEFLW/1@jQg7y7CHTTU069DUcJ@@HNeJSvI4xehSFixbdLkIgkfgX5XNe2DojMFox/brr3YgTvLYB/tL1cUsm81kASKqAadlpvoC "R – Try It Online")
This is the shortest `eval` approach I could find; because we have to collect the results into one vector, we need to `paste` a `c( )` around all the expressions, which adds a ton of unnecessary bytes
[Answer]
# Casio-Basic, 108 bytes
```
{x+y,x*y,x-y,int(x/y),x-int(x/y)y,x^y}⇒o
dim(l)⇒e
Print seq(o[i-int(i/6)6+1]|{x=l[i+1],y=l[e-i]},i,0,e-1)
```
That was painful. Especially because `mod(x,y)` returns `x` when it really shouldn't, which meant I had to make my *own* mod function: hence the `x-int(x/y)y`.
Loops `i` from 0 to `length(l)-1`, taking successive elements in the `o` list and applying `l[i]` for `x` and `l[-i]` for `y`. (negative indices don't work though, so instead I subtract `i` from the length of the list and take that index.)
107 bytes for the function, +1 byte to add `l` in the parameters box.
[Answer]
# Java 8, ~~336~~ 332 bytes
```
import java.math.*;a->{int b[]=a.clone(),l=b.length,i=l/2,s,t;for(;i-->0;b[i]=b[l+~i],b[l+~i]=t)t=b[i];BigInteger r[]=new BigInteger[l],u,v;for(;++i<l;t=b[i],v=new BigInteger(t+""),r[i]=(s=i%6)<1?u.add(v):s<2?u.multiply(v):s<3?u.subtract(v):s<4?u.divide(v):s<5?u.remainder(v):t<0?u.ZERO:u.pow(t))u=new BigInteger(a[i]+"");return r;}
```
-4 bytes thanks to *@ceilingcat*.
[Try it here.](https://tio.run/##rVFNb9swDL37VxAFBkiLrNRpk3V13GEDdtgh2LDeFvgg20qiTP6ATLkIAu@vZ7RdbEOv64ngI/n4@HhUnQrrRlfH4ufFlE3tEI6EyVLhQb6NAWA@h2@K4HoHeNCQnVCHee0rDILcqraFjTLVGSAAMBVqt1O5hs2ZUoBPZv@FsL122xRyRnWKisdU7INxpEWFJocNlJDARYUPZ2qCbJsmSua2rjTjwiaZtLra40GYxM4XohUY72rHYhOGD9dxtjVpkm3t7JdJxXNMkGMyFOK/GoBUJJV@@leWTYUX3cQ2m5m1jacx0b3oZDi7uuLCDbtYm5g3K76OPnipioJ1/L5dLygpvUXT2NOE3BDS@gydynFCbgkpTGcKPeVLyp0uycCCNhCE62uCfnz@/vXey6Z@Ysi5f6lEkYZBTOw0eleBi/tLHJCZjc8smfnsaVebAgZu9ojOVPvR@ukvj6cWdSlrj7KhEtqKjV/3aKz86Jw6tRLraYyVMmeDgvF750jAQsCNgFsBSwErAe8E3Al433M@Pva/2JcjNZHSmuhVGBcj192rcEXReHYY0cnRcjJiFY0@LP5s6IP@8hs)
Sigh..
Input as `int[]`, output as `java.math.BigInteger[]`.
Without the rule "*To cover the corner cases, the input will never contain a 0, but may contain any other integer in the range from negative infinity to positive infinity.*", using integers in the range `-2147483648` to `2147483647`, it would be **~~186~~ 182 bytes** instead (input as `int[]`, and no output because it modifies this input-array instead to save bytes):
```
a->{int b[]=a.clone(),l=b.length,i=l/2,t,u,v;for(;i-->0;b[i]=b[l+~i],b[l+~i]=t)t=b[i];for(;++i<l;v=b[i],a[i]=(t=i%6)<1?u+v:t<2?u*v:t<3?u-v:t<4?u/v:t<5?u%v:(int)Math.pow(u,v))u=a[i];}
```
[Try it here.](https://tio.run/##vVG7bsIwFN35irtUSopjmvAoJZio6gwLI2JwggFT46DkOgih9NepnVB16VqWHOX4Xp@HD7ziQX4S@rD5vGWKlyXMudTXDoDUKIotzwQs3C9AlcsNZJ7lV2vgfmzJumM/JXKUGSxAA4MbD2ZXOwLpas04zVSuhecTxVKqhN7hnkimehFBYkgVb/PCi2UQzF7idCXXLF2p7pdckzsy9JG5g3aw25VTFVcNQ7ib95DJp5E/DRPTrSY4jRLz7LCfmMDhIDE9h8PEPFUTZ92fc9zTU372rL7vG@buietb7JKcTKpsknugJu/RtuEtsZB616Ruq2g7QFHiBy@Fja3FuSWvIYGIQJ/AgMCQwIjAK4Exgbc6blY1zbyfRb@llpcSxZHmBunJCqHS3sG@CzUoFX0vCn4pKeatid/d@/KfJoaNA6tt3YSPFI4ayfEjJcOw6ToIbc/hsG1/FDblR/9jpO7Ut28)
**Explanation:**
```
import java.math.*; // Required import for BigInteger
a->{ // Method with int[] parameter and BigInteger[] return-type
int b[]=a.clone(), // Make a copy of the input-array
l=b.length, // Length of the input
i=l/2, // Index-integer, starting at halve the length
s,t; // Temp integers
for(;i-->0;b[i]=b[l+~i],b[l+~i]=t)t=b[i];
// Reverse the input-array and store it in `b`
BigInteger r[]=new BigInteger[l],
// Result-array
u,v; // Temp BigIntegers
for(;++i<l; // Loop over the array(s):
// After every iteration:
t=b[i], // Set the current item of `b` in `t`
v=new BigInteger(t+""), // And also set it in `v` as BigInteger
r[i]=(s=i%6)<1? // If the index `i` modulo-6 is 0:
u.add(v) // Add the items with each other
:s<2? // Else-if index `i` modulo-6 is 1:
u.multiply(v) // Multiply the items with each other
:s<3? // Else-if index `i` modulo-6 is 2:
u.subtract(v) // Subtract the items with each other
:s<4? // Else-if index `i` modulo-6 is 3:
u.divide(v) // Divide the items with each other
:s<5? // Else-if index `i` modulo-6 is 4:
u.remainder(v) // Use modulo for the items
: // Else (index `i` modulo-6 is 5):
t<0? // If `t` is negative:
u.ZERO // Simply use 0
: // Else:
u.pow(t)) // Use the power of the items
u=new BigInteger(a[i]+""); // Set the current item of `a` to `u` as BigInteger
return r;} // After the loop, return the result BigInteger-array
```
] |
[Question]
[
The [Penrose triangle](https://en.wikipedia.org/wiki/Penrose_triangle), also known as the Penrose tribar, or the impossible tribar, is an impossible object.
The goal in this challenge is to display a Penrose triangle in the fewest bytes possible.
[](https://i.stack.imgur.com/s8SNl.png)
*Source: [Wikipedia](https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Penrose-dreieck.svg/192px-Penrose-dreieck.svg.png)*
**Rules:**
1. You must display the Penrose Triangle digitally after generating it.
2. They must look the same as the above image of the wiki page (source above) without directly showing the image.
3. The same image with the same color scheme must be shown in at least 400x400 size.
4. Should be as accurate as possible.
Good luck and have fun!
[Answer]
## SVG (HTML5), 191 bytes
```
<svg width=498 height=433 stroke=#000><path d=M211,134l38,66L154,365H496L458,431H40 /><path fill=#777 d=M211,2L2,365l38,66L211,134l95,165h76 /><path fill=#FFF d=M496,365L287,2H211L382,299H192
```
[Answer]
# Python 2, ~~211~~ ~~201~~ ~~195~~ ~~188~~ ~~175~~ 173 bytes
```
from turtle import*
d="t(120);fd(333);rt(120);fd(67);"
s="color(0,%r);begin_fill();fd(200);l"+d+"rt(60);fd(400);r"+d+"end_fill();fd(133);rt(180);"
exec s%'#fff'+s%0+s%'gray'
```
Unfortunately, `exec` is not implemented in Trinket, so this cannot be tested online as-is. At least, not in the free version. I [printed out the string](https://tio.run/nexus/python2#bY7LCoMwEEX3@QoZkSS1i/jAFoLfUlqTSCAmMqbQfr31QWkXLmYxd86ZmTk1GIYkPjE6ndhhDBhPRLUQWVEKLo1iVVVxib@@uXAJZGqhCy4gE@cMuXzo3vqbsc6xDSrFAjvIVQ6L2uxmvYa4hdqrP7r4nriKdXeqX7pLpoymxhiaT5lYivZ4f1NCRrQ@wsHXsI@OvXn@AA) and pasted as code to test it. If you're clever with scripts, you could resize the html/css as necessary to get a larger canvas. Let me know if you do.
[**Try it online**](https://trinket.io/python/f19ae1927e) - uses a smaller size since the site's canvas is too small for 400px, but you can see the entire output.
**Ungolfed:**
```
from turtle import*
w=200
def f(n):
c=255*n/2
color(0,(c,c,c))
begin_fill()
fd(w)
lt(120)
fd(5*w/3)
rt(120)
fd(w/3)
rt(60)
fd(2*w)
rt(120)
fd(5*w/3)
rt(120)
fd(w/3)
end_fill()
fd(2*w/3)
rt(180)
f(2);f(0);f(1)
```
[Answer]
# PHP, 153 bytes
This will only work if the `short_open_tag` setting is enabled. The source code contains unprintable characters, so have a hex dump instead:
```
0000000: 3c3f 3d67 7a69 6e66 6c61 7465 2827 b329 <?=gzinflate('.)
0000010: 2e4b 5728 cb4c 2d77 caaf b0d5 3531 3000 .KW(.L-w....510.
0000020: 611d 0b08 5628 2e29 cacf 4eb5 5536 3030 a...V(.)..N.U600
0000030: b0b3 2948 2cc9 5048 b1f5 d535 35d6 3536 ..)H,.PH...55.56
0000040: b7d0 8152 c6a6 263a 8626 c6ba 8626 0660 ...R..&:.&...&.`
0000050: dac2 5cc7 14c8 b234 0452 510a 6999 3939 ..\....4.RQ.i.99
0000060: b6ca 6969 690a 2545 8979 c569 f945 b9b6 ..iii.%E.y.i.E..
0000070: 45f9 2589 25a9 1a06 9a0a fa14 990a 7415 E.%.%.........t.
0000080: a6a9 8646 949a 9b5e 945a 8969 ae2e cc60 ...F...^.Z.i...`
0000090: 7d60 88d9 0100 2729 3b }`....');
```
The decompressed data looks like this (with line breaks added for legibility):
```
<svg viewBox=-400-400,800,800 stroke=#000>
<path d=M-53-378,53-378,354,143-140,143-87,50,191,50Z fill=#fff transform=rotate(0) />
<path d=M-53-378,53-378,354,143-140,143-87,50,191,50Z fill=#000 transform=rotate(120) />
<path d=M-53-378,53-378,354,143-140,143-87,50,191,50Z fill=grey transform=rotate(-120) />
</svg>
```
Although the SVG data isn't entirely valid, PHP serves it as `text/html` by default. Without a doctype declaration, the document is handled in quirks mode, which is very forgiving.
To improve the compression, I broke the image into three "7"-shaped parts that can be drawn using near-identical `<path>` elements. The resulting image will expand to fill the viewport. Here's a screen grab from a 500×500 pixel window:
[](https://i.stack.imgur.com/aIVnO.png)
[Answer]
# HTML + JS (ES6), 34 + 306 = 340 bytes
Makes use of a 30 degree horizontal skew - in the 3rd argument of the matrix transform, the tangent of 30° is represented as `pow(3,-.5)`.
There are quite a few ugly magic numbers, and it doesn't quite match the proportions of the Wikipedia image. I'm certain there is a more "mathematical" way to go about this; any help would be appreciated.
[See the ungolfed version on CodePen.](http://codepen.io/darrylyeo/pen/pegVON?editors=0010)
```
f=
_=>{with(Math)with(C=c.getContext`2d`)for(l=lineTo.bind(C),lineWidth=.01,transform(50,0,0,50,200,224),N=4;N--;rotate(PI*2/3))beginPath(fill(save(fillStyle=N?N>1?'#fff':'#000':'#777'))),transform(-1,0,-pow(3,-.5),-1,3.965,1.71),l(0,0),l(0,6),l(1,6),l(1,1),l(4.616,1),l(5.772,0),closePath(restore(stroke()))}
f()
```
```
<canvas id=c width=400 height=400>
```
[Answer]
## Mathematica 171 Bytes
```
w=(v=AnglePath)[s={{9,0},{11,2(b=Pi/3)},{2,b},{9,2b},{5,-2b},{2,b}}];x={w[[5]],2b}~v~s;y={x[[5]],-2b}~v~s;Graphics@{White,EdgeForm[Black],(p=Polygon)@w,Gray,p@x,Black,p@y}
```
Draws 3 polygons using AnglePath, multiples of 60 degree turns, and taking advantage that the starting point for each polygon is the 5th point of the previous polygon.
[Answer]
# logo, ~~129~~ 120 bytes
Draws only the first 4 sides of each L shape, then lifts the pen, moves to the corresponding spot on the next L shape, lowers the pen and draws 4 sides of that. Each L shape borrows 2 sides from the previous one.
Latest edits: move from black fill area to grey fill area using `fd` instead of `setx`, and change all movements from `fd` to `bk` to save one byte on a 180 deg rotation: `rt 210` -> `rt 30`, shorten `setpencolor` to `setpc` (undocumented in the intepreter I'm using, but it works.)
```
rt 30 repeat 3[pd bk 200 lt 120 bk 360 rt 120 bk 80 rt 60 bk 440 pu rt 139 bk 211 rt 41] setx -2 fill fd 9 setpc 15 fill
```
# logo, 140 bytes
Draws the 6 sides of each L shape, overshoots on the last edge, then turns 180 deg to start the next one.
```
rt 30 repeat 3[rt 180 fd 200 lt 120 fd 360 rt 120 fd 80 rt 60 fd 440 rt 120 fd 360 rt 120 fd 200] pu setx -5 fill setx 5 setpencolor 15 fill
```
run at <http://www.calormen.com/jslogo/#>
It is recommended to do `cs pd setpencolor 0` before running to ensure the screen is clear, the turtle is centred and pointing upwards, the pen is down and set to black (default settings, not required for a brand new session) and also `ht` to hide the turtle (`st` will show it again.)
[](https://i.stack.imgur.com/aPtjr.png)
[Answer]
# HTML + CSS, 9 + ~~315~~ ~~309~~ 308 = 317 bytes
Borders and skews galore! Tested on Chrome. [See the ungolfed version on CodePen](http://codepen.io/darrylyeo/pen/MpKqoj?editors=0100).
```
body{margin:9em}b,:after{position:fixed;transform:rotate(240deg)}b:after{content:'';left:-6.1em;top:-7.95em;width:6em;height:9em;border-left:transparent 2.32em solid;border-right:2em solid;border-bottom:2em solid;transform:skew(30deg);filter:drop-shadow(0 0 .1em)}b{color:#777}b>b{color:#000}b>b>b{color:#fff
```
```
<b><b><b>
```
[Answer]
# Tcl/Tk, 205
```
grid [canvas .c -w 402 -he 402]
.c cr p 171 2 237 2 401 337 125 337 156 280 301 280 -f #FFF
.c cr p 2 335 171 2 310 280 250 280 171 121 31 401 -f gray
.c cr p 171 127 34 401 374 401 401 337 127 337 201 188
```
[](https://i.stack.imgur.com/vJGdI.png)
[Answer]
# Java 8, ~~367~~ 351 bytes
```
import java.awt.*;v->new Frame(){public void paint(Graphics g){g.drawPolygon(new int[]{193,348,178,148,448,263},new int[]{38,318,318,373,373,38},6);g.fillPolygon(new int[]{448,148,233,198,43,418},new int[]{373,373,223,158,438,438},6);g.setColor(Color.GRAY);g.fillPolygon(new int[]{43,198,283,348,193,8},new int[]{438,158,318,318,38,378},6);}{show();}}
```
-16 bytes by drawing on the Frame itself instead of an inner Panel. Now all x-coordinates are increased by 8 to adjust for the left side of the Frame border, and all y-coordinates are increased by 38: 8 to adjust for the top side of the Frame border and 30 for the Frame title-bar.
The Penrose triangle itself has a height of 400 and a width of 440 pixels (since it has to be at least 400x400 by the challenge rules).
**Output:**
[](https://i.stack.imgur.com/TYhrB.png)
**Explanation:**
```
// Method with empty unused parameter and Frame return-type
v->
// Create a Frame (window for graphical output)
new Frame(){
// Override it's default paint method
public void paint(Graphics g){
// Draw the white with black outlined 6-pointed polygon:
g.drawPolygon(new int[]{193,348,178,148,448,263},new int[]{38,318,318,373,373,38},6);
// Draw the black 6-pointed polygon:
g.fillPolygon(new int[]{448,148,233,198,43,418},new int[]{373,373,223,158,438,438},6);
// Change the color to dark gray:
g.setColor(Color.GRAY);
// Draw the dark gray 6-pointed polygon:
g.fillPolygon(new int[]{43,198,283,348,193,8},new int[]{438,158,318,318,38,378},6);}
// Start an initializer block for this Frame
{
// And finally show the Frame
show();}}
```
] |
[Question]
[
In this challenge, an *infinitely proportional sequence* is defined as a infinite sequence of positive integers such that:
* All positive integers are contained infinitely many times within the sequence.
* As more and more terms are added to the sequence, for all positive integers \$n\$, the ratio of the number of \$n\$s to the number of \$n+1\$s in the sequence must grow arbitrarily large.
An example of such a sequence is the following function taking an index and returning a value:
$$
S(n)=\begin{cases}S(\sqrt{n})+1 & n \text{ is perfect square > 1} \\ 1 & \text{otherwise} \end{cases}
$$
This results in a sequence `[1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 3 ...`, and it's fairly easy to see why this list satisfies the given properties. The first 4 occurs at index \$2^8 = 256\$, the first 5 at index \$2^{16} = 65536\$, and so on, with each positive integer occuring infinitely many more times than the previous.
An example of an invalid sequence is this:
$$
S(n)=\begin{cases}S(\frac{n}{2})+1 & n \text{ is even} \\ 1 & \text{otherwise} \end{cases}
$$
This sequence goes `[1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, ...]`, and while it does contain every positive integer infinitely many times, and contains each positive integer more than the previous, it does not contain each integer infinitely many more than the previous. In the limiting case, the sequence contains twice as many 1s as 2s, twice as many 2s as 3s, and so on.
Your challenge is to output any infinitely proportional sequence. Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply - you may output as a function that takes \$n\$ and outputs the \$n\$th or first \$n\$ terms, or output an infinite sequence in some form. You may use 0-indexing, 1-indexing or 2-indexing (taking the first term as f(2))
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
Óθ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1wQZDAwNXPzt7JQVdOwUlez-7paUlaboWSw5PPrdjSXFScvFCHYjIggUQGgA)
Returns the exponent of the largest prime factor of \$n\$.
## Proof of correctness
Let's look at the ratio between the number of values which return \$k\$ and the number which return \$k + 1\$. For each number which gives \$k+1\$, with greater prime factor \$p\_m\$, we can create \$m-1\$ new numbers, by dividing by \$p\_m\$ and multiplying by \$p\_i\$ for \$i < m\$. However, some numbers are generated multiple times, but it's bounded by their number of distinct prime divisors. If we look at numbers up to \$n\$, that's bounded by \$O(\frac{\log(n)}{\log\log(n)})\$. Therefore we have \$\sum\_{p\_m} \frac{(m-1)\log\log(n)}{\log(n)} \Psi(\frac n{p\_m^{k+1}}, p\_m-1) \leq \sum\_{p\_m} \Psi(\frac n{p\_m^k}, p\_m-1)\$. We want to show that for every \$N\$, for large enough \$n\$, we have \$ N \sum\_{p\_m} \Psi(\frac n{p\_m^{k+1}}, p\_m-1) \leq \sum\_{p\_m} \frac{(m-1)\log\log(n)}{\log(n)} \Psi(\frac n{p\_m^{k+1}}, p\_m-1)\$. We'll split it at \$m = 2N \log(n)\$. From theorem 1.4 in [Integers without large prime factors](http://www.numdam.org/item/JTNB_1993__5_2_411_0.pdf), we have \$\Psi(n, p\_m) = n^{O\_N(\frac 1{\log\log n})}\$. The inequality is trivial for \$m > 2N \log(n)\$, and because \$\sum\_{p\_m} \Psi(\frac n{p\_m^{k+1}}, p\_m-1) = \Omega(\frac{n^{k+1}}{\log(n)})\$ grows faster than \$n^{O\_N(\frac 1{\log\log n})}\$ the fact that we used \$2N\$ balances the terms we split out.
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes, thanks to @GregMartin
```
Ó¿
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m73MwDQxyTB1wQZDAwNXPzt7JQVdOwUlez-7paUlaboWSw5PPrR_SXFScvFCHYjIggUQGgA)
Returns the gcd of the prime exponents, which is the largest \$k\$ such that \$n\$ is a \$k\$-th power.
[Answer]
# [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 10 bytes
```
nM l<gr<bi
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN3czcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRABXmpWVZ16Jrh2QWFpakqZrsSbNNs9XIccmvcgmKRMitDU3MTPPNjdeoaBIJc0m2lBPz9DAIBYit2ABhAYA)
## Explanation
* `bi` convert the input to binary
* `gr` group equal elements
* `nM l` length of the shortest group
This finds the shortest run of equal elements in the binary expansion of the input.
## Proof
I will provide a proof that the proportion of 1s approaches 1. That is \$P(f(x)=1)=1\$ This argument can be repurposed to show that for any number the proportion relative to numbers greater than or equal to it approaches 1. That is \$P(f(x)=n\mid f(x)\geq n)=1\$.
Let's consider the two least significant bits of a number \$x\$. If they are `10` or `01` then \$f(x)=1\$.
The two other options `11` and `00` may be any value. This means that at least half of all numbers give 1.
Now in the general case, let us treat the case where the least significant \$2n\$ bits do not rule out values other than 1. Considering the least significant \$2n+2\$ bits. A fourth of all cases of begin with `010` or `101` and thus \$f(x)=1\$. So 3/4 of all cases have the *possibility* of being something other than 1.
We can use recursion to then derive the following formula:
\$
P(f(x)\neq 1) \leq \frac{1}{2}\left(\frac34\right)^n
\$
We can take the limit:
\$
\displaystyle P(f(x)\neq 1)\leq\frac{1}{2}\lim\_{n\rightarrow\infty} \left(\frac{3}{4}\right)^n=0
\$
So the probability of getting a 1 converges to 1.
## Reflection
There are a couple of things that would be nice here.
* There is `sss` which gives the shortest continuous substring satisfying a predicate, and `sSn` which gives the *maximal* substrings satisfying a predicate. Here it would have been useful to have a function which gives the shortest maximal substring satisfying a predicate.
* It might be nice to have a version of `gr` which just gives the lengths of the groups. It's not uncommon to care only about group lengths and not their contents.
[Answer]
# [Python](https://www.python.org), 36 bytes
*-6 bytes thanks to l4m2, Command Master and xnor*
```
f=lambda n:-n&n<n or-~f(len(bin(n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3VdJscxJzk1ISFfKsdPPU8mzyFPKLdOvSNHJS8zSSMvM08jQ1NaFqlQqKMvNKNKLTNDI10_KLFDIVMvMUihLz0lM1DHWMTM01Y6EqYaYDAA)
**[39 bytes](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY31dNscxJzk1ISFfKs8tTydA0T81IUDPOLdOvSNHJS8zSSMvM08jQ1NaHKlQqKMvNKNKLTNDI10_KLFDIVMvMUihLz0lM1DHWMTM01Y6EqYRYAAA) if using `True` as `1` is not allowed:**
```
f=lambda n:n&n-1and 1or-~f(len(bin(n)))
```
Similar to example but with logarithm base 2 instead of square root.
*I known that `len(bin(n))` is not exactly the logarithm, but it does not make a difference for the purpose of this challenge*
---
# [Python](https://www.python.org), 36 bytes
*suggested by Wheat Wizard*
```
lambda n:len(min(bin(n).split("1")))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3VXISc5NSEhXyrHJS8zRyM_M0koA4T1OvuCAns0RDyVBJU1MTqla5oCgzr0QjOk0jUzMtv0ghUyEzT6EoMS89VcNQx9DAyFgzFqp0wQIIDQA)
[Answer]
# [R](https://www.r-project.org), 32 bytes
```
f=\(n,i=n^.5)`if`(i%%1,1,f(i)+1)
```
Uses the sequence from the question (2-indexed).
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3FdJsYzTydDJt8-L0TDUTMtMSNDJVVQ11DHXSNDI1tQ01oerU0jSMTM00uYpTS_wSc1OLNYoTCwpyKjWMrAwNgGo1dcAMqOoFCyA0AA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
Nθ⊞υ¹W›θΣυ«≧⁻Συθ⊞υ×⌈υLυ»I⊕ΣEυ›θΣ✂υκ
```
[Try it online!](https://tio.run/##Xc7NCsIwDAfws32KHlOYsJ13Eg8ycDKcL1BrWIttnf1QQXz2usp2MaeQf/glQnInblyn1NgxhkM0Z3RwZzXpopcQC1pN/VMqjRR2DnnIcUH7aCAyxuibrFo@brxXgz2qQQZolY1@2ShotlYLdlIGPbT8pcwc79EOQf6smnxI55QNsOU@QGOFQ4M24AUyNp3JxN8TvVYC8/zK5qpTqsqyTOuH/gI "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th term. Explanation:
```
Nθ
```
Input `n`.
```
⊞υ¹
```
Start with `1` `1` as the first term of the sequence.
```
W›θΣυ«
```
While more terms are needed, ...
```
≧⁻Συθ
```
... account for previous terms, and...
```
⊞υ×⌈υLυ
```
generate a new set of terms.
```
»I⊕ΣEυ›θΣ✂υκ
```
Calculate the resulting term.
The result is the following sequence:
```
1
1 2
1 1 2 3
1 1 1 1 1 1 2 2 3 4
1 (24 times) 2 2 2 2 2 2 3 3 4 5
1 (120 times) 2 (24 times) 3 3 3 3 3 3 4 4 5 6
1 (720 times) 2 (120 times) ...
```
Within each group, the number of times `m-1` appears more than `m` is more than the number of times `m-1` appeared more than `n` in the previous group.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 27 bytes
```
S=n=>++n**.5%1?1:S(n**.5)+1
```
[Try it online!](https://tio.run/##HchRCoAgDADQ0wSbq2Af/STaITxBlMYiXFh0faP@Hm@fn/laipx3l3WNtQaXnSfKxvRDwxOPAX4jcU1aQBxbSyQoCQIIesZF86VH7A/dQNovsb4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 39 bytes
```
i;f(n){i=sqrt(n);n=i*i-n||1/n?:f(i)+1;}
```
[Try it online!](https://tio.run/##bVDbTsMwDH3fV1iVJiVto9FNPEAoPCC@gvahSpMRsWUjiURF118nuFeYRORY9rF95GPB9kKEoLkihrY6dx/WY8RNrmPNzOWSbczTvSKaJhnvgjYejpU2hEK7Anw9IJuzFF7WryXk0GYpjLadg3/T0XYdH2jEW2Vj9FK8S4s80DNFRfOyLZq7Z/y3UQp/8100TaqTBdJvoU0tGxy74VP4AE5/yZMi8350MwHxgnBIkqF71jNr8sg00iSQ8auSw5Iinl6jEtHlEMNk@dtwttiiSLSugT0C@rUrDCryKbh0kY0UObhyIu5WXfgW6lDtXWCfgR2OPw "C (gcc) – Try It Online")
[Answer]
# [Scala 3](https://www.scala-lang.org/), ~~64~~ 63 bytes
A port of [@pajonk's R answer](https://codegolf.stackexchange.com/a/268808/110802) in Scala.
Saved 1 byte(s) thanks to the comment of @pajonk
---
```
def f(n:Double):Int={val i=math.sqrt(n);if(i%1>0)1 else f(i)+1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9BTsMwEEX3PcWoEpItlLSGDUqVoCI2SHSFWFUVclKnNXLGwZ5Ao6onYdMNbLgD9-ht6oSwmvme_7-eP799IY28_lmOI7Qf0uF4dZrZ_FUVBAupEfYjgLUqoQqCSbfxCcydk-3yiZzGzYon8IyaIO2d8NVQGd2cbrtIyTC5t01uFE8ekNL9uzSg00rSNvZvjhjymS6ZvhDZlAtQxquQ0fxSHIaa39AIkwnM69q0QNtwb7AgbRHI9hqbKlfOQ-lsBVfdq5gKkLiGOuBR73HKN4Z8hwcdwqADMvtP8LiSNUNIM0CIsg49JjvA87AuZN3n-1aDbOgIl0ftKfbW0V3Ldmm2i18E58F7GA2_OB7_5hk)
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 16 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍵≠⌊⍵:0⋄1+∇⍵*.5}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu/VR54JHPV1AhpXBo@4WQ@1HHe1AjpaeaS0A&f=K0ktLil@1DbBUPtR72YTS64SEF8nWs80Nu3QCjAHAA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f)
-1 byte thanks to att.
A tacit function which takes an integer \$n\geq 2\$ on the right and outputs the \$n\$th term in the sequence in the question.
```
{⍵≠⌊⍵:0⋄1+∇⍵*.5}­⁡​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢⁤​‎⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­
⌊⍵ ⍝ floor ‎⁡input
0≠ ⍝ ‎⁢not input
⍵≠⌊⍵: ⍝ ‎⁣If input is non-integer:
0 ⍝ ‎⁤ return 0
⋄ ⍝ ‎⁢⁡Else:
⍵*.5 ⍝ ‎⁢⁢sqrt input
∇ ⍝ ‎⁢⁣apply this dfn
1+ ⍝ ‎⁢⁤add 1
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
] |
[Question]
[
A palindrome is a word that is its own reverse. I will define the left palindromic root of a word as the shortest prefix of the word for which the shortest possible palindrome that begins with that prefix is the original word. So the left palindromic root of `racecar` is `race` and the left palindromic root of `ABBA` is `ABB`.
The second case may not seem obvious at first, so consider this table:
```
Prefix | Shortest palindrome with same prefix
|
"" | ""
"A" | "A"
"AB" | "ABA"
"ABB" | "ABBA"
"ABBA" | "ABBA"
```
Since the shortest prefix which maps to `ABBA` is `ABB`, it is the left palindromic root of `ABBA`.
The process of converting from a prefix to the minimum palindrome is also called the left palindromic closure, as can be found in [this related challenge](https://codegolf.stackexchange.com/q/47850/31625).
Write the shortest code that, given a palindrome as input, returns the shortest palindrome that begins with the reverse of the left palindromic root of the input. Equivalently, find the left palindromic closure of the reverse of the left palindromic root of the input.
You may assume the input is part of some arbitrary alphabet, such as lower-case ASCII or positive integers, as long as it does not trivialise the challenge.
## Test cases
```
girafarig -> farigiraf
farigiraf -> girafarig
racecar -> ecarace
ABBA -> BBABB
->
a -> a
aa -> aa
aba -> bab
aaa -> aaa
1233321 -> 333212333
11211 -> 2112
ABABA -> BABAB
CBABCCBABC -> CCBABCC
```
You can make additional cases using [this program](https://tio.run/##jZDBasMwDIbvegqRXWxGy5xcRqCDto/R9eA1dmJIbSN7bKP02TMrGVsHO0w2sqVf9icUP/IQfPMYaZru0DrfYRoCZZMyRj2WmMIZ31weMJKx7h0TdMZiL5JsAYvZQOjQeSTteyNG44v0pbFF3GDCe0yH1h0PbbtSx2/NWZY3GJf8zyM2MvmVPEa4CRLMdPtvOjGdybfMXpBkbPoTWNSlHfmLPPFMUvkuxAJ5kGsyuhNyneLosqiefSUBuJ15dqWjuX4hRHI@C1tdOHfF1RNerOC7vFZysppc70hbmD1HQPpkTppgu9ttATTosl/40KDqpmlqBUrVSpWCsmBf/H52nw).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ ~~10~~ 9 bytes
*-1 byte thanks to Jonathan Allan!*
```
¦:R⋎ḟꜝȯḂ⋎
```
[Test suite](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiwqY6UuKLjuG4n+qcnciv4biC4ouOIiwiIiwiJ2dpcmFmYXJpZydcbidmYXJpZ2lyYWYnXG4ncmFjZWNhcidcbidBQkJBJ1xuJydcbidhJ1xuJ2FhJ1xuJ2FiYSdcbidhYWEnXG4nMTIzMzMyMSdcbicxMTIxMSdcbidBQkFCQSdcbidDQkFCQ0NCQUJDJyAiXQ==)
## Explanation
```
¦ # prefixes of input
: # duplicate
R # reverse of each element
⋎ # merge join (vectorises)
# - combines the strings on their longest common
# suffix and prefix respectively
ḟ # find the first index of the original input
ꜝ # bitwise not
ȯ # get this last number of characters in the input
Ḃ # push the reverse
⋎ # merge join
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
No built-in palindromising :(
```
;ⱮṚḊ$ƤŒḂƇḢȯ
ŻḊƤÇ⁼¥Ƈ⁸ḢṚÇ
```
A monadic Link that accepts a list of characters and yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8/9/60cZ1D3fOerijS@XYkqOTHu5oOtb@cMeiE@u5ju4GCh5bcrj9UeOeQ0uPAakdQAmg2sPt////d3ZydHIGEwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##TY@xDoJADIb3PgWDow4Ho4kJ8BSOhSDBOLG5qQuJo6PRxeBmNBoHjE4SL77G3Ytge6iw9P/79dL@N44mk2lV9fX5qG5rVSw7Mn@tVLGQmSp27xO87gRlXmZ6/njuJUlBA3pbZpW6X7tlNtazjdUbWHq2lRe9OAyrOElxhGkSMzaGAfwd4/8bSDGMQkwZslIHrue53JN4HrAD5IqARi0kFxgbYECwnhIVtuM4tuDWGG5BCFsYRGLTcve7nR34VHxTmNXOb77QpP4FNekAOAuHgNbZ@lJ9obX4Aw "Jelly – Try It Online").
### How?
```
;ⱮṚḊ$ƤŒḂƇḢȯ - Helper Link: get shortest palindrome: left palindromic prefix, S
Ƥ - for prefixes (of S):
$ - last two links as a monad:
Ṛ - reverse
Ḋ - dequeue
Ɱ - (S) map (that) with:
; - concatenate
Ƈ - keep those for which:
ŒḂ - is palindrome?
Ḣ - head (Note: when S='' we head [] and get zero)
ȯ - (that) logical OR (S) (deal with that zero)
ŻḊƤÇ⁼¥Ƈ⁸ḢṚÇ - Main Link: palindrome, P
Ż - prepend a zero
Ƥ - for prefixes (of that):
Ḋ - dequeue
Ƈ - keep those for which:
¥ ⁸ - last two links as a monad - f(X=that, P):
Ç - call Helper (X)
⁼ - equals (P)?
Ḣ - head
Ṛ - reverse
Ç - call Helper
```
[Answer]
# JavaScript (ES6), 113 bytes
Essentially a port of the Python program provided by the OP. Although I did find shorter methods, I've yet to find a *working* shorter method.
```
s=>[...s].some(c=>(F=S=>[...S].some(c=>[p+R==(Q=S+q)][q=c+q,p+=c,0],p=q='')&&Q)(S+=c,R=c+R)==s,R=S='')?F(R,R=S):s
```
[Try it online!](https://tio.run/##ZdBBb4MgGAbg@36F4dBCtHTobcnXRk16rx6NB2RqXLqqsOzvO1CrC1wM7/s9fgl88V@uhOyGn9Oz/6ynBiYFl4JSqkqq@u8aC7jgG@RLme9lMfgZAL5D7o@kLEYQ/hgMPojgvQwGGOF4JIfDneDcdJkeZwRA6VNuRtcbzsyZfKhJ9E/VP2r66FvcYNR2kjdcdi3yCPHOZ28Opnyz5DZ4ye1XW0ouasEl8rxVmqQ728VJEhu0OZ2TxFar2JUNOLIAd8ROVuGSajMLqXjlrrEMd/ewMIqikO13n6MpHclCxtC/bTqG7hPFrzdan8g0tkp1l84ftKglpNMf "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 33 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
U{ÊÆê jUÊXÃfêS Ì
©å+ æ_gV ¥UÃÔgV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ClV7ysbqIGpVyljDZupTIMwKqeUrIOZfZ1YgpVXD1GdW&input=IkNCQUJDQ0JBQkMi)
[Try all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ClV7ysbqIGpVyljDZupTIMwKqeUrIOZfZ1YgpVXD1GdW&input=WwoiZ2lyYWZhcmlnIgoiZmFyaWdpcmFmIgoicmFjZWNhciIKIkFCQkEiCiIiCiJhIgoiYWEiCiJhYmEiCiJhYWEiCiIxMjMzMzIxIgoiMTEyMTEiCiJBQkFCQSIKIkNCQUJDQ0JBQkMiCl0tbVI)
Explanation:
```
/n # Store input as U
U{ÊÆê jUÊXÃfêS Ì # Define a function V which calculates left palindromic closure
U{ # Start defining a function with one input named U
Ê # Get the length of U
Æ Ã # For each number X in the range [0...length):
ê # U palindromized
j X # Remove X characters
UÊ # Starting at index "length of U"
fêS # Keep the ones which are palindromes
Ì # Return the last (shortest) one
©å+ æ_gV ¥UÃÔgV # Main program
© # Return U if it is an empty string
å+ # Otherwise get the prefixes of U
æ_ Ã # Find the first (shortest) one where:
gV # The left palindromic closure
¥U # Is U
Ô # Reverse it
gV # Return its left palindromic closure
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηε‚ε瀨íyì.ΔÂQ]ʒнQ}нθ
```
Iterative port of the example implementation.
[Try it online](https://tio.run/##ATYAyf9vc2FiaWX//863zrXDguKAms61zrfigqzCqMOtecOsLs6Uw4JRXcqS0L1RfdC9zrj//0FCQkE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLoZVK/89tP7f1cNOjhlnntp7b/qhpzaEVh9dWHl6jd27K4abA2FOTLuw9tC6w9sLeczv@K@mF6fyPVkrPLEpMSyzKTFfSUQLTID6QXZSYnJqcWARkOTo5OQIpIEoEYTCRBGGCSEMjY2NjI0MQy9DI0BCswRGswxlIO4MJpVgA).
**Explanation:**
```
η # Get the prefixes of the (implicit) input-string
ε # Map over each prefix:
 # Bifurcate it; short for Duplicate & Reverse copy
‚ # Pair the two together
ε # Map over this pair:
η # Get the prefixes of the current string
۬ # Remove the last character from each prefix
í # Reverse each
yì # Prepend the current string to each
.Δ # Find the first that's truthy for:
ÂQ # Check if it's a palindrome:
 # Bifurcate; short for Duplicate & Reverse copy
Q # Check if the two strings are the same, thus a palindrome
] # Close the find_first and nested maps
ʒ }н # Find the first pair that's truthy for†:
н # Where the first palindrome in the pair
Q # Equals the (implicit) input-string
θ # Only leave the last/second palindrome of the found result-pair
# (which is output implicitly as result)
```
NOTE: The empty input `""` perhaps requires an additional explanation for the execution path it follows:
1. `η` on an empty string becomes `[]`, so it won't execute the nested maps `ε‚ε瀨íyì.ΔÂQ]` and remains `[]` after it.
2. It also won't enter the filter `ʒнQ}`, so again remains `[]`.
3. `н` on an empty list will result in an empty string.
4. `θ` on an empty string is basically a no-op.
† If I'd used `.ΔнQ}` ('find first' builtin) instead of `ʒнQ}н` (filter + 'keep first' builtins), which I initially had when I was working on golfing my program, it would have resulted in `-1` for the empty list `[]`, incorrectly giving an output of `1` after the 'keep last' builtin `θ`.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~102~~ 90 bytes
```
L$vr`(?(1)$)(?<-1>\1)*.?(.)*
$&$' $' $^$`
0G`( .*)\1
r`((?(2)$)(?<-2>\2)*.?(.)*) .*
$1$^$`
```
[Try it online!](https://tio.run/##NYvBCsIwEETv8xU9rJoELG56lZa2h178hCJZSy25eAji78dNUXZ4w8K8tL7jSzgfzBTyjT4pmM6wJWu665nbma2rO1NbBzrSqSq5U8BlCqaqnZ0Zaqjif4pvZ/9XrC5AXISct5jkKSlu2Fk@JFnWRRL6YegBgWgepQTsm6bxDGbPrAM9jMpxxxc "Retina – Try It Online") Link includes test cases. Input cannot contain spaces. Explanation:
```
L$vr`(?(1)$)(?<-1>\1)*.?(.)*
```
Find the longest palindromic suffix of each prefix of the input.
```
$&$' $' $^$`
```
For each match, make a list of the match and its suffix, another copy of the suffix and the reversed prefix. We'll check that the latter two are the same below, after which we know that the match and its suffix is the same as the reverse of the match with its prefix.
```
0G`( .*)\1
```
Keep only the result of the match with the shortest prefix that equals its suffix. This means that the left palindromic closure of the match with its prefix is the original input, but also it means that the match and its suffix is the reverse of the match with its prefix, thus avoiding manually reversing it.
```
r`((?(2)$)(?<-2>\2)*.?(.)*) .*
```
Find the longest palindromic suffix of the reversed prefix.
```
$1$^$`
```
Outputs its palindromic closure and delete the suffix and reversed prefix of the match.
Instead of taking the left palindromic closure of the reverse of the left palindromic root, it's also possible to take the right palindromic closure of the left palindromic root for the same byte count:
```
L$vr`(?(1)$)(?<-1>\1)*.?(.)*
$`$& $' $^$`
0L$`(.*)( .*)\2
$1
^(.)*.?(?<-1>\1)*(?(1)^)
$^$=
```
[Try it online!](https://tio.run/##PYxBDoJADEX3/xQsqnYmkdhhqxJg4YYjEDKVIGHjYmK8/lhYmDbvp8n7TfNnfavkAz9i7umbItcsjhzX17PcB3G@rLl0HhTpWNCpoJEiLj1FLr3jwjAEkGDcLHP/vf3R6GCFW87LmvSlaV2wc7uQdJonTWjatgEUavvcQiGhqqogEAkiJtigM3Y7fg "Retina – Try It Online") Link includes test cases. Input cannot contain spaces. Explanation:
```
L$vr`(?(1)$)(?<-1>\1)*.?(.)*
$`$& $' $^$`
```
As above, but directly taking the match with its prefix instead of the match and its suffix.
```
0L$`(.*)( .*)\2
$1
```
As above, but removing the suffix and reversed prefix.
```
^(.)*.?(?<-1>\1)*(?(1)^)
$^$=
```
Output the right palindromic closure by replacing the longest palindromic prefix with the reverse of the whole value.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
∨⌊ΦEθ…θ⊕κ⁼⊗⊕κL⁺θ⊟ΦEι…⮌ι⊕μ⁼λ⮌λω‖OO←L⊟ΦE⊕ⅈ…KAκ⁼ι⮌ι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZDPTgIxEMbjladoOE2Tctg9ETkpQmKCYcPJxHgoddZtdrYL_QPhWbxw0Kiv5NNYBLLFHqaZbya_78u8falKWtVK2u8_gi8Hw5-r28Jq42Fu4UEb3YQGppo8xlauYC3YeKcIx1X719wbZbFB4_EFas65YJN1kOTgrg1LiuK_BcFmaF59BQUFdwAUkZPwdcpf4AatQ9D80qhJfEiw8xrx8xNsy_mot8CSUPl5HJNcnT64nmHpuxyX_qnNIxxIXZwCsb4hgijWSQLdJdBH-9G7Wyp3OujnU3-wof7zd5ZleZ7HetR_AQ) Link is to verbose version of code. Explanation:
```
∨⌊ΦEθ…θ⊕κ⁼⊗⊕κL⁺θ⊟ΦEι…⮌ι⊕μ⁼λ⮌λω
```
Output the shortest prefix whose palindromic closure equals the input to the canvas. This is calculated as the length of longest palindromic suffix of the prefix plus the length of the input equals twice the length of the prefix.
```
‖OO←L⊟ΦE⊕ⅈ…KAκ⁼ι⮌ι
```
Calculate the length of the longest palindromic prefix of the prefix and reflect the canvas to the left with that amount of overlap, thus generating its right palindromic closure.
] |
[Question]
[
Given a compressed string \$s\$ made of printable ASCII characters (32 to 126), your task is to print or return the original text by applying this simple decompression algorithm:
1. Start with \$k=0\$
2. Look for the first occurrence of the digit \$k\$ in \$s\$ and the sub-string \$s'\$ consisting of the \$2\$ characters preceding it. If the pattern is not found, stop here.
3. Remove the first occurrence of the digit \$k\$. Replace all other occurrences with \$s'\$.
4. Increment \$k\$. If it's less than or equal to \$9\$, resume at step \$2\$.
## Example 1
Input: `bl3a2h1 00001!`
1. The first occurrence of `"0"` is preceded by `"1 "`. We remove the first occurrence of `"0"` and replace all other ones with `"1 "`, leading to `"bl3a2h1 1 1 1 1!"`.
2. We do the same thing for `"1"`, with the sub-string `"2h"`. This gives `"bl3a2h 2h 2h 2h 2h!"`.
3. We do the same thing for `"2"`, with the sub-string `"3a"`. This gives `"bl3ah 3ah 3ah 3ah 3ah!"`.
4. We do the same thing for `"3"`, with the sub-string `"bl"`. This gives `"blah blah blah blah blah!"`, which is the final output because there are no more digits in \$s\$.
## Example 2
Input: `Peter Pipe1r pick0ed a 10 of pi0led 1p1rs.`
The first step uses the sub-string `"ck"` and gives:
```
Peter Pipe1r picked a 1ck of pickled 1p1rs.
```
The second and final step uses the sub-string `"pe"` and gives:
```
Peter Piper picked a peck of pickled peppers.
```
## Rules
* The input string is guaranteed to be valid. In particular, there will always be at least 2 characters before the first occurrence of a digit.
* However, the input string may not be compressed at all, in which case it must be returned as-is.
* The uncompressed text is guaranteed not to contain any digit.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
### Input
Short test cases (one per line):
```
Hello, World!
antidis0establ0hmentarian0m
bl3a2h1 00001!
A AB4 43C22D11E00F0FG
Peter Pipe1r pick0ed a 10 of pi0led 1p1rs.
The 7first 9rul7of Fi6g5h98C3l2ub1 is: You4 do no9talk ab495210. Th7second rul7of 50 is: Y4 do no9talk ab4950.
```
Longer test case (first paragraph of the Adventures of Sherlock Holmes / A Scandal in Bohemia, from [Project Gutenberg](http://www.gutenberg.org/files/48320/48320-0.txt)):
```
To Sher6lock Holmes 3she 9i3a8lway3_the_ woman. I h4av9seldom4eard4im mention246 und68ny oth6 name. In4i3eye3sh9eclipses8nd predomin5ate3t7h19whol9of46 sex. It 0wa3not1at49felt8ny emoti28k57o lov9for Iren9Adl6. All emoti2s,8nd1a029particularly, w69abhorrent7o4i3cold, precise, but8dmirably balanced m5d. H9was, I7ak9it,19mos0p6fec0reas25g8nd obs6v5g mach59that19world4a3seen; but,8s8 lov6,49would4av9placed4imself 58 fals9positi2. H9nev6 spok9of19soft6 passi2s, sav9with8 gib9and8 sne6. They w69admirabl9th5g3for19obs6v6--excellen0for draw5g19veil from men'3motives8nd8cti2s. Bu0for19tra5ed reas267o8dmi0such 5trusi235to4i3own delicat9and f5ely8djusted7emp6amen0was7o 5troduc9a distract5g factor which might1row8 doub0up28ll4i3mental results. Gri058 sensitiv95strument, or8 crack 5 29of4i3own4igh-pow6 lenses, would no0b9mor9disturb5g1an8 str2g emoti2 58 natur9such8s4is. And yet169wa3bu029woman7o4im,8nd1a0woman was19lat9Iren9Adl6, of dubious8nd questi2abl9memory.
```
### Output
```
Hello, World!
antidisestablishmentarianism
blah blah blah blah blah!
A AB ABC ABCD ABCDE ABCDEF ABCDEFG
Peter Piper picked a peck of pickled peppers.
The first rule of Fight Club is: You do not talk about Fight Club. The second rule of Fight Club is: You do not talk about Fight Club.
```
Longer one:
```
To Sherlock Holmes she is always _the_ woman. I have seldom heard him mention her under any other name. In his eyes she eclipses and predominates the whole of her sex. It was not that he felt any emotion akin to love for Irene Adler. All emotions, and that one particularly, were abhorrent to his cold, precise, but admirably balanced mind. He was, I take it, the most perfect reasoning and observing machine that the world has seen; but, as a lover, he would have placed himself in a false position. He never spoke of the softer passions, save with a gibe and a sneer. They were admirable things for the observer--excellent for drawing the veil from men's motives and actions. But for the trained reasoner to admit such intrusions into his own delicate and finely adjusted temperament was to introduce a distracting factor which might throw a doubt upon all his mental results. Grit in a sensitive instrument, or a crack in one of his own high-power lenses, would not be more disturbing than a strong emotion in a nature such as his. And yet there was but one woman to him, and that woman was the late Irene Adler, of dubious and questionable memory.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
s=input()
for k in'0123456789':a,*b=s.split(k);s=a+a[-2:].join(b)
print(s)
```
[Try it online!](https://tio.run/##ZY09T8MwFEV3/4rXKQmUyM5H0wRlKKWBjQ6VEEIMTvJKTFw7sh1Bf31IVTbecnWkc@8bzq7TKp4a3SKU4HneZEuhhtH5ATlqAz0I5VEWxUm6yta5V/DlTV3a0A5SOL8P7m3Jb/n7XVR8hF9aKL8OyGCEcr4NpnmOkO9OSISDGbEgAM6cLwGAP9j4l7cBuUCDg4PdS7UzRpurURvk/fSMUuolvGoj2wXhyolWWIrW8VrS7oTKcSO4oidSy5hHHQM6H1uQDWweEkjibRQ9MrajtKLVE9mjQwN7MSAzMIimp9gCB0ZBH2emckY2MGNDcugQsqMw1kFuRpnNQiVWn2mXr7exjMaagbAFvOkxgVaD0rnjsgdeJ3kaMRrCocssNlq18FdP6bXx36fhLw "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 36 bytes
```
~(`.+
9*
L$`
(?<=(..)$.`.$*)?$.`¶$$1
```
[Try it online!](https://tio.run/##ZVRbruQ0EP3vVdRIjbgzhMjOq2MeGt2Z4T4kPkZiJISENNdJKh3Tjh386Ez/IBbBWlgAS2Ejl3Jo8UP/RGm7Tp0651QcBmUkf/7s5v7p@bebp/yLnXi1@37/tLt5/c23N3n@cp8/5ftXL1/T868/93v@/PyAWtsMfrRODy920gQ1KM/QB9lpNs1ognRKGjbvOl3KYuLA6Mdf7G7h9k0FVfm2KN5x/h1jd@zufvceAzp4rxbkDhbVnxgOIIEzsCO9M02vfOHO57sPE8JhVM4HEC7qA124U82xnkT7ttRF7Dgo/xX8ZGMFgwVjRZD6BLKrRF1wlsOH6eCxt2aAa3nN/q34/31G7Sz8MKFrtO1P8GD1jB5KTxyEKmWrV3kpP4YJP8JqZ2lyeISpkmfhUQ92rlC6oVIzJEGUNUXVQDRD05oL2DA1YOSMVGMqVeIFCVdgr9Xi0bfEb3FIIMrUMmAZDhMX62S1sCPBePxEhQHYKktjA5ehEiPqkKBxtkEV7ak@WND2LEbr4NGhEbeDbnK41fp6xWfUhktWiEW6oPqopdOXDNZGyG6yjmrCwRK53uohS3x65TGDLoZ2mJUjsy/QSS1NTwbN9ZDDg1ilz@DxIE9ChYyL2Xq2NCP2zKH0RX1Mk9nON@f6CLPsp1qESQaaLWWpkqVHNF@nFlnr28S/ySo6jOnwLBYtqRdpSgqTdS2MUnuxWK9ontTe4JnUWeyJdOLC2zE0sEjv07TgCWFVYWrhqDohzdCCN9ikUOBlG/s6FnGqjyUJx8XGtfn79z/wU0@pR8OSnoOTa33k4oxKw@js5vHPn5dJ1/NmX9snhXN4E9mGE5ysSaVNheZgk4DMx36COrhI9Mo6JKntamBArXoZEkEYa9SXdvgl@oDDAeelocwYst2Tu1Rqh9gLCbR@1KAPJOpID2K4TorAZ3WcAnd2bSndsWNxKVqtqc@2o5ro@KgD0bx3ipGcHk2S8ixqwovpUgbWtdAT@AlqKFL8NpYVIX@52LUB0oQSS7FJJtEGsY5cdyJRiq4jlaQh4OCK4zV3yTcj6VAkAVpfKSJwS8NeMPCGElR2kUK5rVTK33zN6fYH0OhcaJLnv0xn6TMxxE7ZuC3Or5G@RKpIPs7U0V3yfwA "Retina – Try It Online") Link includes test cases. Unfortunately Retina does not have a convenient way to access a loop index in its loop construct, so it turns out to be easier to create and evaluate the 179-byte program Retina 0.8.2 would need to solve this. Explanation:
```
~(`
```
When the inner program has finished, evaluate the result as a Retina program on the original input.
```
.+
9*
```
Replace the input with 9 characters that we can loop over.
```
L$`
```
Loop `$.`` from `0` to `9`.
```
(?<=(..)$.`.$*)?$.`¶$$1
```
Generate a replacement stage that for each `$.`` in the input, replaces it with the two characters preceding the first `$.``. If the first `$.`` could not be found then this is the first `$.`` and it is simply deleted. Expanded for `$.` = 0` the code looks like this:
```
(?<=(..)0.*)?0
$1
```
[Answer]
# [J](http://jsoftware.com/), ~~49~~ 48 bytes
```
(i.~{2<\.]rplc[;i.~{2]\[,,)&> ::]/@|.@;;/@Num_j_
```
[Try it online!](https://tio.run/##ZY1NT8IwAIbv/orXC9NkKW3ZnNvADNHpyXAgMQYWMrbOFSptuu0k8a8P4kc4eHw/njzbvq8mBFeSfH3y8Ypk1qhiGX/HbLV03evBHaIoGyYHksTxMHnpPtbbdS@KWqOCs6gFgkrapkVoOxXoCqm8effr8HY2UrzbMMgmwpvuPJQaex22udoh33ihzxklWNRBIwq9L/GL@/SH@P@nxLn48z4LpbSLV21VeXmup5jee/BGM84fGHukNKXp03mei1ZYzKURzMLIYkdFiRyM4iQ2kqpTZIbZhjj9EQ)
```
({~rplc~^:_~>@]{3({:;}:)\_2|.[)i.&Num_j_<^:3@-.#
```
[Try it online!](https://tio.run/##ZY1NT4MwAIbv/orXmMiWaNMWEKkf2ZyiJ7PDEmPUEQZFutW1KXBC@eu4RM0OHt@PJ896GMorglHXO6vzfinS/nry1vmjTlx8ifFryj/Jy1iR48f2I12nl0vhT07J0SDzyqCEt6gkolK5ukHsWh2ZEok6ew@r@Hzma96uGFQt8GzaAIXB1sRNpjfIVkEcckYJFlVUy9xsC/ziIf0h/v8p8Q7@vA9Sa3OCJ@N0cbivp5jeBAj8Gee3jN1RmtDkfj/PZSMd5spK5mBVvqGyQAZGsRNbRfUuMstcTbzhGw)
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~113~~ 112 bytes
```
s=`rev`
for n in {0..9};{ s=`sed "s/\(.*\)$n/\1/;s/$n/$(sed "s/.*$n\(..\).*/\1/"<<<"$s")/g"<<<"$s"`;}
rev<<<"$s"
```
[Try the test suite online!](https://tio.run/##ZVRNb@M2EL37V8waBpoEikx9WmzSg3e72eS2QBcoCgTYUNLIYk2RKklZMbb729Oh6raH6mLSw3nz5s0ja@H6t7mXCsGiaOF1Ba1ZAQA2vYH15nUNf8LVm/vpxeLpZdUZCxqkhm8sjvn3u29AEYctrN32@Sq@eb7e6O1zsr1zW1psri6h@GajKRw/X8c3Iby@v79fb9z6env4Z/ly931FJS67N/jvuw50Fj60aI3Gt0dUykTwq7GqfbcS2stWOobOi1qxfkDthZVCs2FVq0ykfQKMvuTdag/79znk2Yc0/TlJPjL2wB4@rT6jRwuf5YiJhVE2R0asBSQMTEd7pmibjIl18epLj7DrpHUeuJ3Ujg48yPJQ9Lz6kKl0qhOQ7kf4zUw5UQVtuBfqCKLOeZEmLIYv/c5hY3QLl/SC/Z3x//OMyhn4pUdbKtMc4dGoAR1kjjhwmYlKzeKcffU9foXZDELH8AR9Lk7coWrNkKOwbS4HCIJIo9O8hEm3ZaXPYHxfghYDUo7OZYZnJFyOjZKjQ1cRv9EigUhdCI@Z3/UJn3ujuOkIxuErJXpgs8i08YnwOe9Q@QCNg/EyrY7FzoAyJx4s82RR832ryhj2Sl2OuIjKJIKlfBTWy2ZSwqpzBHPJRd0bSzl@Z4hcY1QbBT6NdBhBPfmqHaSlYZ@hFkrohgY0FG0Mj3wWLoKnnThy6aOED8axseywYeRulxaH0JmpXXkqDjCIpi@474Wn3oKXcpE5RH0XSkSVqwL/MsopOIXgiY9KUC3SlBSm0VXQCeX4aJykfkJ5jSdSZzRH0inhznS@hFE4F7oFRwiz9H0FB1lzodsKnMYymALPS9uXtohTcchIuIQvXMvbW3xtyPSoWZCztWIuDgk/oVTQWbOM@IcsqHpahlc1Qd8Y3k9sQfFWFKTRokG5M0E@5qamh8LbichlhQ9Cm1lDi0o2wgd60BWozlX7@@Q8tjscxpIco2nojmZLqaadGi6ALh8VaDxJ2tEPEaQHhcAHeeh9Ys1ckbenmk1jWilFdZYbqoiOm5Qnmp@sZCSmQx2EPPGC8KZwKAJjK2gI/AgFpMF8C8uckG9HM5dAkpBfyTRhRHR/WE0ztzxQmmxNIglNwN6mh4vrwtS0oCAPAlQul0RgT82e0Scl@SerJ7LkcqGC@4aLS5c/gFpPuCJ5/nV0FB6JdqqlmZZr88dE75BMwxQHqmjP8eov "Bash – Try It Online")
Input on stdin, output on stdout.
Here's how the program works:
>
> **(1)** The input is reversed right-to-left, to accommodate sed's greedy regex matching.
>
>
> **(2)** Then the reversed string is decompressed using multiple calls to sed (using the mirror image of OP's decompression
> rules because the string has been reversed).
>
>
> **(3)** Finally, the resulting string is reversed again.
>
>
>
**Step (2),** the mirror-image decompression, is implemented as follows.
>
> **For each `n`** from `0` to `9`:
>
>
> **(2a)** Due to the way bash does its expansions, the inner sed
>
>
> `$(sed "s/.*$n\(..\).*/\1/"<<<"$s")`
>
>
> is evaluated first. Its value is the
> string consisting of the two characters immediately following the last
> `n`. That two-character string replaces the entire string
>
>
> `$(sed "s/.*$n\(..\).*/\1/"<<<"$s")`
>
>
> in its enclosing larger expression, and only then is the larger expression
> evaluated.
>
>
> **(2b)** Now, going back to the first sed, the last `n` in the string is
> deleted.
>
>
> **(2c)** All the earlier occurrences of `n` in the string are replaced with
> the two-character string evaluated in step 2a.
>
>
>
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
9ƒN¡ćDŠ2.£ý«
```
-1 byte thanks to *@CommandMaster*.
[Try it online](https://tio.run/##yy9OTMpM/f/f8tgkv0MLj7S7HF1gpHdo8eG9h1b//5@UY5xolGGoYAAEhooA) or [verify all test cases](https://tio.run/##ZVTLruQ0EN33V9TcDZvQsvPqeFiMema4c@8GRmIkhIQ0cpJKx7RjBz86EwkkduwRHwBiyZ4dm8vjQ/iRSzk0bMgmcuw6deqc41gvW4WPX11u7s0cw1O4ebZmu5uPY/h39Sj@/O6jhx9///blHz/k@4effvv14efHr7OHX5493qHWNoNPrdP9k500QfXKM/RBtpqNE5ognZKGTbtWFzIfOTB6@JPdEY7PSyiLF3n@kvMPGbtlt692rzGgg9dqRu5gVt2ZYQ8SOAM70JppWvKZO7/fvRkRDoNyPoBwUR/owK2qT9UomheFzmPLQfmn8JmNJfQWjBVB6jPIthRVztke3owHj501PVzLK/ZPxf/PM2pn4ZMRXa1td4Y7qyf0UHjiIFQhG73ItXgbRnwLi52k2cM9jKW8CI@6t1OJ0vWlmiAJoqzJyxqi6evGrGDDWIORE1KNKVWBKxKuwE6r2aNviN/skECUqWTAIhxGLpbRamEHgvH4jgoDsEUWxgYuQykG1CFB42SDyptzdbCg7UUM1sG9QyOOva73cNT6esRn1IZLlotZuqC6qKXTawZLLWQ7Wkc14WCJXGd1nyU@nfKYQRtD00/KkdkrtFJL05FBU9Xv4U4s0mdwf5BnoULGxWQ9m@sBO@ZQ@rw6pcls6@tLdYJJdmMlwigDzZayVMrCI5oPUous8U3iX2clbca0eRGzltSLNCWFyboGBqm9mK1XNE9qb/BC6sz2TDpx4e0Qapil92la8ISwqDA2cFKtkKZvwBusUyhw3ca@jkWcqlNBwnGxca3/@uZ7fNdR6tGwpGfv5FKduLig0jA4u3n8@XtF0vWy2dd0SeE9PI9swwlOVqTSpkJ9sElA5mM3QhVcJHpFFZLUdjHQo1adDIkgDBXqtem/iD5gf8Bprikzhmz35C6V2j52QgJdP2rQBRJ1oBcxXEZF4JM6jYE7uzSU7tiyOOeN1tRnu6Oa6PioA9F85RQjOT2aJOVFVIQX06EMrGugI/AzVJCn@G0sS0J@f7ZLDaQJJZZik0yiG8Ract2JRCm6llSShoCDy0/X3CXfjKRNkQRofKmIwJGGXTHwmhJUtJFCuV2plL/pmtPtA9DoXGiS579MZ@k30cdW2bhdnC8j/YlUnnycqKNb938D).
**Explanation:**
```
9ƒ # Loop `N` in the range [0,9]:
N¡ # Split the string at `N`
# (which uses the implicit input in the first iteration)
ć # Extract head; pop and push remainder-list and first item separated
D # Duplicate this head
Š # Triple swap a,b,c to c,a,b on the stack (head, remainder-list, head)
2.£ # Pop the head, and only leave its last two characters
ý # Join the remainder-list by this 2-char string as delimiter
« # Append it to the duplicated head
# (after the loop, the resulting string is output implicitly)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 53 bytes
```
for$c(0..9){s/(..)\K$c(.*)/"'$2'=~s|$c|\Q$1\E|gr"/ee}
```
[Try it online!](https://tio.run/##ZYtdS8MwGEbv@yvejcJWcembflgreDHnNkGECQMRepO26RqWNSVJr6z@dGNB73zuzsM5Pdcyda5R2q@WSEgefJhwSUhQPE8HuQrC@cKPFvdfZvSrsXj1abEdT3oecv7p3BOXUl3Dm9Kynnmss6IWBrmxrJTYXnhnmRasw4tXyphFLQWcRmfeGtYPCSTxJooeKd0i7nC39w7ccg0H0XOqoRfVGXkNDCiCaiZGOSHtqTbEO7YcskZoYyHXg8wmYSduTmmb325iGQ0lBWHu4F0NCdQKOpVbJs/AyiRPI4oEjm1meKW6Gv7yFH@L/z6Sb9VboTrjVi8pQYpu1csf "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~111~~ \$\cdots\$ ~~98~~ 97 bytes
Saved ~~2~~ 10 bytes thanks to [Uriel](https://codegolf.stackexchange.com/users/65326/uriel)!!!
Save a byte thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
```
def f(s):
for k in'0123456789':i=s.find(k);s=[s,s[:i]+s[i+1:].replace(k,s[i-2:i])][i>0]
print s
```
[Try it online!](https://tio.run/##nZJRa9swEMef509xe4pNPSM5TlN7ZNClzfbYh8Ioxg@yLdeHFclIcmH78pksp6Rsg0GFfLJ0/5O4H//xp@2VTE@nlnfQhSYqAuiUhgFQrghN19nmenuTrwrcmaRD2YZD9NnsShObssDqypR4RYsq0XwUrOHh4M7xU@pSUVXiF1IFMGqUFswJpYEdlMGH1XcuhIrhh9Ki/biK3QmTFls0hBvLakH6I5eWaWSSHH2@FmuW9hSIG3QpuYXbrxlk632a3lF6T8iBHL75zAO3XMMDjpxqGLEZCG@BASWgOrcnwm3pSLVJvPyx57DtUBsLuZ7E1okOeP286fOb/VqkU00BTQFPasqgVSBVbpkYgNVZvkkpSeCx3xreKNnCuXxDloq/9WR@sgrUZP/LYkGB5sICzSsM1sM/woWLm/v5u/PhfomH8/InpIWRRzTyZlggNcNMaeSjy7/htGBybXLwmJ57C3sx1a@EloYtnDt2fb4RzaQ4XFC96w7Pzzo4M8AWGxv@wjF03ophphpFQeD9G8OLszB4ZYKWH004e9uNzlnY/yzGfDn9Bg "Python 2 – Try It Online")
Borrowed test rig from [Uriel](https://codegolf.stackexchange.com/users/65326/uriel).
[Answer]
# [Red](http://www.red-lang.org), ~~94~~ 91 bytes
```
func[s][foreach k"0123456789"[t: copy/part p: any[find s k""]-2 take p replace/all s k t]s]
```
[Try it online!](https://tio.run/##ZZAxT8MwEIX3/oojM23tJCVNBqRSKIwVqoRQ5MGJL8SKa1u2M/TXB6OmMHDbu/e9O@k5FNM7ipotugqmbtRt7VndGYe87WFICE2zfPNQbMukDhW0xl7WlrsAtgKuL3UntQAfwYQtUwh8QLDg0Cre4por9eNBYJ5Nt5sBfWi5R6gXECd5Q6XMPXwYp8Rdct1xHaSQnkSUN4r0Z9SBO8k1Oc9EozKe9hRIHHqL7WD3lEOe7dP0mdIXQg7k8Dp7Rwzo4CgtUgdWtgNBARwoAdNFTVSU1FLnV3Pg1CMUnXQ@QOlGVUTsIB@@Nn253WcqHRsK0lfwacYchAFtysDVALzJy01KyQpOfeGxNbGfOb4h18R/nsSn7NqHdVIHqM9Gib@qkuVjAt2vZgs2fQM "Red – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
Fχ«≔⌕θIιη≔⁺…θη⪫⪪✂θ⊕ηLθ¹Iι✂θ⁻η²η¹θ»θ
```
[Try it online!](https://tio.run/##ZY1BS8QwEIXP9lfMMYG6tHVrrXuSwoKisLB78dhN02YwTrZJKoj422OCsgh7G@Z933tC9VaYXocwGgusLDh8ZVcPzuFEbIs0sDmHrneeIec5KL45pzu9ONZ9Ci07ZU6JU5F4Mkhsf9Lo2V6jkOn/SMLKd0leDiwxz5Imr9gcz5L/rz8bL0ixXOVQpdGEpXiO69/ZziL5KG9COCgJzYjWeWjtohszwhZvp1q1d92NrpZjCeju4dUsaxgMkGl9r9@gP67buiqLFRxU46QwNMCfXhe/xiVfrLJw/aF/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Fχ«
```
Loop over each digit.
```
≔⌕θIιη
```
Find the first digit in the input.
```
≔⁺…θη⪫⪪✂θ⊕ηLθ¹Iι✂θ⁻η²η¹θ
```
Replace each digit in its suffix with the last two characters of the prefix, and prepend its prefix.
```
»θ
```
After all the digits have been expanded, print the result.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~93~~ ~~89~~ 87 bytes
```
f=lambda s,k=0:(g:=s.find(m:=str(k)))+1and f(s[:g]+s[g+1:].replace(m,s[g-2:g]),k+1)or s
```
[Try it online!](https://tio.run/##nZbfbts2FMavl6c4u4qNqoZkW7KUIRdpu669K7ACw9AVBSXRFmeK1EjKrjcM2EPsCfci3XcoJzXSAgMWJP5H8vz5zsdfPJxCZ82qHNynT9tbLfq6FeST/W16M9vd3PrFVpl21uNVcLP9fD5/kgnT0nbm393s3j/x73ZPspv3CycHLRo56xN88nSJpXmyf5LNrSP/SRlPt/Tu6pvrV1Jrm9BP1un22@sEnwgTVKt8Kn0QtU67XpognBIm7eN6rVdi2WWU4iebjtzR3bM1rVfPl8sXWfZ9mr5MX/4QV97IIB29UYPMHA2q2aeyJUFZSnaL96nG22zInF/E7W87SZutcj5Q5Ua9waaXqtjlXVU@X@nlWGek/A39bMc1tZaMrYLQexL1usqXWbqgt93Gy8ZCj/PxPJ1OfLk/Pae09GMnXaFts6dXVvfS08qjjkqtRKmP4rT6EDr5gY62F2ZBr6lbi0PlpW5tv5bCtWvVE4ukrFmuCxpNW5TmRDZ0BRnRS5wxa7WSJ4m4lWy0Grz0JWocnEQQZXIR5Cpsuqw6dlZXdoswXn7EwUDpUayMDZkI62ordeDQsrdBLct9vrGk7aHaYqivnTTVXauLBd1pfd7iE6TJRLqsBuGCakYtnD4ldCwqUXfW4UzYWBTXWN0mXE@jvEyoHkPZ9srBACeqhRamwaD6vF3Qq@oofEKvN2JfqZBkVW99OhRb2aROCr/Md9yZrX1xyHfUi6bLq9CJgN7YY2ux8lKa7zhFUvqS6y@SNRZHXjxU0bWsKRTG@EraCu2rwXqFfji9kQeoM9g9dMoqb7ehoEF4z92SR4SjCl1JO1VXuBcleSMLNoY8xbbPbaGmfLeCcFkVay3@@etv@bHBbZAmZT1bJ475LqsOUmnaOhtn/Mv1inU9xPGVDSu8oGdjGuMEJ3KoFFUoNpYFTP3YdJQHN6K8VR5Yans01EqtGhGqeHFzqU9l@@vog2w3sh8KeMZg7B7TxVHbjk0lCFcSCZoAUbd4QoXHTiF4r3ZdyJw9lnD4WKfjsCy1Rp54bzXK8aMOKPMHp1LI6aVhKQ9Vjngjb0rIupIaBN9TTku2X6xyjchPB3ssCJrAsbANDwm3KK0xdVdxSaOroZIwCBzccnf2Hc/NCCxWLEDp1woF3KHZkwxZAQet6hGmjFeK/deffRo/ILSeVRryPHg6YVy0Y63sGC/ObyPopJY8xx4Z3WlxffX@yo7hP7E2UU35z1hT/p5roqOvPHxGHH6f89@L@PD99Pjy/PSYdxPuIu0GCWUj75o9A2@QA9YvkDcRD8SSFImHidJzPdb3sJvYFegML/R5sSl6mz5T73/FuEThJQkZhMqTYA56egxCceDEDELqmITUfUYhPnHMQjyKiYZ4dY9DbPQEIE4J7pFI4oKJQKInHCJGYuyJA9xTERaZugFZiBUEGWOe6D9kF3tlKEQ8YvXMR0kwk3QXhLQGtua0MZDFjkeglE7SAyo5IFf@JS1JfAWX@D8NYEmagAnl9xAT1427AjUDjODAzRCRYY0yu1gKeCTdgd8xPRVqisVFLdjP0B26PUCU8E7EPl1Ccc8Y96DviaU8lQhTKCIiTrESeWpNrA9EZWmB1KgzJ2KssoWZq1Ejz/GYrAgBtMpYqWC4sp4TXaNWZx24aLTgo/YccepKugvOBroHLTfLmx7B1tOZtlO2Js6LgRsewoKJUKg9S4iSMSKuIVBErzKRvTjGL6fpXQB4agNfqIBgHJsYTAEQlo4pPBkN5zgOgxgHHkjMRX@JYlQFGPM20DjQOLAZYTfO/BUkh2kq91SGQcwll7E0gRm72J18Dc4tdGc8o@fHfA5Us8MwjjOiJ31FzIRGzO7hnsTsEdVyUgz9dhe0ZpFdtHC0OdcwQTqK2V9cngd2x7loFvfizl0SPJ6ZEG5N9MoFxHHtI8Vb1YTZ72qYKbYfo30@v7rise8TOnDdcedCYVp@Nr@5IvwMDoOaXb/748/31wvs7UWYbfEl@fb2ME@IX80//Qs "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 121 bytes
```
s->{int j;for(char i=47;++i<58;s=j>0?s.replaceFirst(""+i,"").replace(""+i,s.substring(j-2,j)):s)j=s.indexOf(i);return s;}
```
[Try it online!](https://tio.run/##ZVTbbuM2EH3PV8zmpXajCNTVYrxJkd3WmzwUXSALFEVbLCiJsmhTpJYXK8YiQD@iX9gfcYeKW6CoAUPgZc6cOXOGO3Zg17t2fxLDqI2DHa5j74SMO68aJ7SKv11fjL6WooFGMmvhRyYUfL0AOO9axxx@Dlq0MODZ4skZoba//g7MbO1yvgqwOcO9fT2NXj930N2e7PXdV6Ew97rTZtH0zIC4zVfrqyvxtqjW9nZ3R76zseGjZA3fCGPd4vLySkSXl8t/dl83bGx9bWfkxe46jXbL5Y1d7m5tLFTLn3/qFmK5Ntx5o8CuX07rmVrIesCkSPfmP5wBno7W8SHW3sUjojqpFl3MxlEeF3hxuXwFeLkI/5fT6YFLqSP4WRvZvjkx5UQrLOGoUC1JP3DlmBFMkeFUy4ylfQIEf8mb0z3cv8shz96n6fdJ8gMhG7L5cPrIHTfwUYw8MTCKZk94CwwSArrDNZG4TMbE2Pj0qeew6oI0QI2XK7ywEeW26Gn1PpOprxMQ9gZ@0T6HVoPS1DG5B1bntEgTEsOnfmV5o1UL5/CCvEb8/z7BdBqeem5KqZs9PGg5cAuZRQ5UZKySEztmn13PP8OkB6ZieIQ@ZwdquWz1kHNm2lwMEARBS6R5CV61ZaWOoF1fgmIDxxiVi4wfOeJS3kgxWm4r5DcajiBCFczxzK36hE69llR3CGP5MwY6IBPLlHYJczntuHQBmg/aibTaFysNUh8oth0eDVf0vpVlDPdSnq/YCNMkjKR0ZAat7SUz8hjBVFJW99pgjFtpJNdo2UaBTyMsj6D2rmoHYbDZR6iZZKrBBg1FG8MDnZiN4HHF9lS4KKGDtmQsO94Qw5lNi22oTNe2PBRbnKKmL6jrmcPagpdyllnO1TqkiCpbBf5llOOhD4cHOs9A0BQVxtZV0DFp6aitwHpCesUPqM6o96hTQq3uXAkjTnOoFiwiTML1FWxFTZlqK7CKl8EU/DiXfS4LORXbDIVL6My1/OuPP/lzg67nigQ9W8OmYpvQAxcSOqPnHv/2TRZ0Pcztq5qgcAzvPJlxnGEFqjSrUK50EJBY3/RQOOORXla4ILWeFLQcnxvmAkHoCi6PVbvzOJ/tig9jiZ5R2HaL3cVQ3fqGMsDxwwSNQ1E7/CDDqRcIPoht7xKjpwrd7Wvix7SSEvPMMyqRjvXSIc0PRhCU03IVpDzQAvF8uBSBNhU0CL6HAtJgv5lljsjXo55KQE3QsWib0CScIFJj1w0NlLypUSWmENiZdHv2XeibYnhIgwCVzQUSuMdij9wlJTooqz2ach6p4L/h7NN5A7D0hEqU519PR@GZaH0ttJ8H54vHl0ikoY8DZjTH@G8 "Java (JDK) – Try It Online")
Naive Java implementation.
## Credits
* -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [Raku](https://raku.org) (raku -p), ~~66~~ ~~61~~ ~~58~~ 56 Bytes
```
my $a=-1;$_=S/(..)$a/{$0}/.subst(/$a/,$0,:g)until ++$a>9
```
First attempt. I am sure it can be improved
[Answer]
# [Haskell](https://www.haskell.org/), ~~154~~ 148 bytes
```
n%c=show n==[c]
n#(a:s@(b:c:_))|n%c=[a,b]|1>0=n#s
_#_=""
f n s|n>9||n#s==[]=s|1>0=f(n+1)$l++r>>= \c->last$[c]:[n#s|n%c]where(l,(_:r))=break(n%)s
f 0
```
[Try it online!](https://tio.run/##ZVTbbuM2EH33V0yTXdRGFIPUzaILB81um02APiywCxRFGhiURFmsKVLlxVoD@fd0qAZFFtWLTXHmzJkzZ9RzdxRKvbzo983O9WYCvds9Nk8LfbnkW/fzst422/1q9RzvH3lSPz3TG7LTl26xv9zvLi4WHWhwz/qGPT/jW0x@2rk5plvqK7p6p66u7M3NDv5srm8Ud/4dom8fMTRCPk29sGKpkuV@a1erXW0FPy71@5V78cJ52MEY/Bdvf9Owhg7IYjFwqfF1axaAzxx0cY8dmAR@N1a1P1y8ueDay1Y6ggdeK9IPQntuJddkeBtWq4ynPQWCD/0O4BZuP@SQZx/T9BdKfyXkjtx9ehvwWXhh4bMcBbUwyuZIRAscKAHT4ZkoPNKRWrd@m/W1F7DppMX/zAa1wdg7WR6KnlUfM5WGmoJ0W/jDhBw7BW2Y5@oIvM5ZkVKyhq/9xonG6BZe0wvyb8b/48n3lQ18QclLZZoj3Bs1CAeZQzpMZrxSEz9ne9@LPUxm4HoND9Dn/MScUK0ZcsFtm8sBoo7S6DQvIei2rPQZjO9L0HwQmKNzmYmzQFwmGiVHJ1yFVEcrEETqgnuR@U1P2dQbxUyHME58w0QPZOKZNp5yn7NOKB@hxWC8TKtjsTGgzIl1xsKDFZrdtqpcw61SryEuwTKUk5SN3HrZBMWtOicwlYzXvbGY4zcGyTVGtUnk00gnEqiDr9pBWvTIGWquuG5wbEPRruGeTdwl8LDhRyZ9QtlgHBnLTjQErerS4hA7M7UrT8UBBt70BfM999hbdGPOMyeE/imWSCpXRf5lkuNliJcnNiqOtVBTVBinWEHHlWOjcRL7ieW1OKE6ozmiTpQ50/kSRu5c7BYcIkzS9xUcZM24bitwWpTRH@I8t/3aFnIqDhkKR9nMtby@Ft8aXBuhSZSztXwqDpSdhFTQWTOP@Mcsqnqah1c1Ud81fAhkRvGWF6jRrEG5MVE@4kLTQ@FtQHJZ4aPQZtLQCiUb7iM96AqhzlX7V3BetBsxjCU6RuPQHc4WU00bGsYBdxYLNB4l7fAHCU69RPBBHnpPrZkqtHmoSRjTSimsMy@2QjouKI80P1lJUEwndBTyxArECzEoAWMraBD8CAWk0XwzyxyRr0czlYCSoF/RNHFEuEqkxplbFikFW6NIXCOwt@nh1XVxaprjJYsCVC6XSOAWmz0LT0v0T1YHtOS8UNF9w6tL5xeArVOmUJ7/HJ3ET0cbamnCvDZ/B9xcmcYpDljRntcXL/8A "Haskell – Try It Online")
### Ungolfed:
```
digitIsChar :: Int -> Char -> Bool
digitIsChar n c = show n == [c]
getSubStr :: Int -> String -> String
getSubStr n (a:b:c:s)
| digitIsChar n c = [a,b]
| otherwise = getSubStr n (b:c:s)
getSubStr _ _ = ""
replaceKey :: Int -> String -> Char -> String
replaceKey n key c
| digitIsChar n c = key
| otherwise = [c]
decompress :: Int -> String -> String
decompress n s
| n >= 10 || null key = s
| otherwise = decompress (n+1) (lhs ++ replaced)
where
key = getSubStr n s
(lhs, (_:rhs)) = break (digitIsChar n) s
replaced = rhs >>= replaceKey n key
```
### Edits
1. -6 bytes (@FrownyFrog)
[Answer]
# Wolfram Language (Mathematica), 124 bytes
```
(r=StringReplace;s=ToString;i=-1;FixedPoint[(i++;r[r[#,s@i->"",1],s@i->StringCases[#,_~~_~~s@i][[1]]~StringTake~2])&,#,10])&
```
[Try it online!](https://tio.run/##ZVTbbuM2EH3vV0y9QLvFKl5SN4sNUiSbNrt5S7sBisIwAkoaWawpUiUpK0bR/Ho6lIO@1DCgy3BmzpxzRoMMPQ4yqEa@dlev793V1@CU2f@Go5YNXvqrR3t@c6muLvjlnXrG9sEqE7bv1YcPl27rtu8Sf60uflqtEr47354zbqVHT9Gnlxf6U2C33fLd7uUcfZQHfEl3P3yXvEs4o@vrr5PCsH2gYPh43X28/nv1BbW2CfxunW6/XSXfrKQJqlWeoQ@y1qwf0ATplDRsiOFaZzLtOTD68SXhBm4@5ZBnt2n6M@e/MHbH7j7HwAMGdPCgRuQORtUcGLYggTOwHT0zTY985M6v4@nHHmHTKecDCDfpDZ25U@W@6EV1m@l0qjko/yP8YaccWgvGiiD1AWSdiyLlbA2P/cZjY00Lb@kFO2f8/zw7d7TwtUdXatsc4IvVA3rIPMEQKpOVnuUpeyLpnmC2gzRruIc@l0fhUbd2yFG6NlcDRH6UNWlewmTasjInsKEvwcgBKcfkKsMTUl2BjVYj6VURxNEhFVGmkAGzsOm5mHurhe2ojMdnSgzAZpkZG7gMuehQh1gaBxtUWh2KjQVtj6KzDu4dGnHT6nINN1q/HfEJteGSpWKUjrw3aen0KYG5FLLuraOcsLEErrG6TSKeRnlMoJ5C1Q7KkfYnqKWWpiGZhqJdwxcxS5/A/UYehAoJF4P1bCw7bJhD6dNiHyeztS@PxR4G2fSFCL0MNFt0Vy4zj2guY4uk8lXEXyY5BacYPIplHSKnxDCpV0EntRej9Yrmie0NHomd0R6IJy687UIJo/Q@TgueKswq9BXsVS2kaSvwBsvoCzwtY7@NRZiKfUbEcbFgLS8u8LmhNUDDIp2tk3Ox5@KISkPn7CLx91lk9biIVzWR3zV8mthSJThZEEcLB@XGRvqYn5oeiuAmApcVIRJtZwMtavoMhAgPugL1qWr/nHzAdoPDWJJjDInuSVtKte3UCAm0i9SgCURpRxcCOPeKig9q3wfu7FyRvaeaTWNaaU19loXVBMdPOhDMz04xItOjiUQeRUH1pngoAesqaKj4AQpIo/kWlDlVvhjtXAJRQn4l00SJaIVYTZo7ESFNriaSpKHCwaX7N9dF1YykoIgEVD5XBOCGhj1h4CX5J6snsuSyUNF9w5tLlxdAo3OhiZ7/HJ3ET0U71cpOy9r8NdFnSaVRxYE6utN69c/u9V8 "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Your task is to write a computer program or function that takes a list of nonnegative integers of at least length 2 and determines if they are a "zigzag". A sequence is a zigzag if and only if the numbers alternate in being larger and smaller than the number that comes before them. For example \$[1,2,0,3,2]\$ and \$[4,2,3,0,1]\$ are zigzags but \$[1,2,0,0,3,1]\$ and \$[1,2,3,1]\$ are not.
For your decision you should output one of two different consistent values for each possibility (zigzag and not zigzag).
The code-points of your program or function must also be a zigzag itself. This means that when you take the sequence of code-points it should be a zigzag.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
IṠIỊẸ
```
Returns \$0\$ (zigzag) or \$1\$ (not zigzag).
The code points are \$[73, 205, 73, 176, 174]\$ in the [Jelly code page](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page).
[Try it online!](https://tio.run/##y0rNyan8/9/z4c4Fng93dz3cteP/4fZHTWuAyP3//2guBSBSiDY31lEwMjDVUQAxDM3NQIRJrA5IylDHSMdAx1jHCMI1AXKNgQKGsVwKIJFohBqQKkOEJhAnlisWAA "Jelly – Try It Online")
### How it works
```
IṠIỊẸ Main link. Argument: A (array)
I Increments; compute the forward differences of A.
Ṡ Take their signs.
A is zigzag iff the signs are alternating.
I Take the increments again.
Alternating signs result in an increment of -2 or 2.
Non-alternating signs result in an increment of -1, 0, or 1.
Ị Insignificant; map each increment j to (|j| ≤ 1).
Ẹ Any; return 0 if all results are 0, 1 in any other case.
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 23 bytes
```
{*/ 0 >1_ *':1_ -': x }
```
[Try it online!](https://tio.run/##fY7PDoIwDMbve4qmkLDB0E08bcqLoBETxBgMJowDBPHVsWLwaA9t8/u@/qni@lpPkzM4hGtQkOoThIGhHAcGOhjxn8ZYaVbgWA6KcMDlgevIc8LDJwoZ@CpyUiLOOsb7CBOpI652hYhVWtAILSLPrDs2F45osb24ls4K1prBz/pXY0robP6oLM/L8@1uO9vbRhxH1mYaNvRbQhmsPhLYUpsQ0gv4Oj4ebdUCko9Ojhk4@AWNTG8 "K (ngn/k) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 87 bytes
```
f(a:b:c:d)|(>)a b,b<c=f$b:c:d |(<)a b,b>c=f$b:c:d |1>0=1>12
f[a ] =1<12
f(a:b:_)= a/= b
```
[Try it online!](https://tio.run/##hc2xDsIgEMbx3ae4NAyQGBVHwrHoW6gxRyspsVCCjH131LrUwbjd/Yfv19PjfhuG6kMac4EjFdocesrVcVJWtaoTEzeCwK6tbtGxucHE9aeZRZNmh9LI/cqdCC6AUr/veecqEGiLYGsgHzFlHwtzLFCCMXfNP8z8xs5xob2eb66pTw "Haskell – Try It Online")
I wanted to get the ball rolling in terms of Haskell answers. I can't see a way to improve this yet, but I am convinced it can be done. I'm looking forward to what people can do from here.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
dt?ZSd]pA
```
[Try it online!](https://tio.run/##y00syfn/P6XEPio4JbbA8b9qtKGOkY6BjrGOUSyXarQJkGMM5BqCOBAZkBycC2Ua6SgY6ihASLCAgQIYguUUjBVMFEwhTHMFIwVTBUMFS7DhQAZIwDD2P4oJIDIWAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D@lxD4qOCW2wPG/S8j/aEMdIx0DHWMdo1iuaBMg2xjIMwSyIeIgGRgPwjLSUTDUUUCQQCEDBTAESSoYK5gomIJZ5gpGCqYKhgqWIIOBNIhvGAsA)
My first ever MATL program! The penultimate `p` was added for the zigzag requirement.
Explanation:
```
d %take the difference between successive elements of input
t %duplicate that
? %if that is all non-zero
ZS %take the sign of those differences (so input is all `-1`s and `1`s now)
d %take the difference of that (so if there are successive `1`s or `-1`s, this will have a 0)
] %end-if
p %take the product of topmost stack vector (will be 0 if either the original difference or
% the difference-of-signs contained a 0)
A %convert positive products to 1 (since OP specifies "you should output one of two different consistent values for each possibility ")
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~225~~ ~~223~~ ~~161~~ 139 bytes
-2 bytes thanks to Jakob
-62 bytes thanks to Dennis
```
e={eval }.pop()
p ="i"+"n"+"p"+"u"+"t ( "
s=e(p +")")
e(p +"` a"+"l"+"l([(x<y>z)+(x>y<z)f"+"o"+"r x,y,z i"+"n zip(s,s [1: ],s [2: ])])` )")
```
[Try it online!](https://tio.run/##RY/RasMwDEXf/RUXvdRe3FEH@tDQ9EdCWEPmskCJRZwNO2PfnikdrA9HutKFi8R5/ghjufbh3ddEtPr62391d/y8cmBtFKOmgQoaBRY@hRkapGLtNaMgQ0b9qSs6ce8butHpnC@LKXS65PNibrINwoRks13wyMQysI42onEV2q2X0k1rrpDUVe4RY@9adQsT3jCM2GH3cqwU5ilXPvke2@EKPvWe54q7GB@vKNU4W1pn3cHuT/bY/i8OTyn1OZTb8As "Python 2 – Try It Online")
Credits for the bumpy algorithm goes to [this answer](https://codegolf.stackexchange.com/a/93062/)
`input`, `print`, `exec`, `def` and `lambda` aren't bumpy so I only got `eval` left, which is stored on `e`
There are 2 main ways to bypass the restriction, placing `"+"` or between the non-bumpy pairs, I opted for the former ( is shorter for each use, but it would need `replace(' ','')` resulting in more bytes)
Since `print` isn't bumpy, I can't use it directly, and since it isn't a funcion I can't use it inside `eval()`, so I had to use `input(result)` to output the result
[Answer]
# [Ohm v2](https://github.com/nickbclifford/Ohm), 5 [bytes](https://github.com/nickbclifford/Ohm/blob/master/code_page.md)
```
δyδ½Å
```
[Try it online!](https://tio.run/##y8/INfr//9yWynNbDu093Pr/f7ShjpGOsY5hLAA "Ohm v2 – Try It Online")
The indices of the characters are \$[131,121,131,16,165]\$ in the linked code page.
### How it works
```
δyδ½Å – Full program / Single-argument block.
δy – The signs of the deltas of the input
δ – The differences of the signs. Results in a sequences of 2's or -2's for
bumpy arrays, as the signs alternate, giving either -1-1=-2 or 1-(-1)=2.
Å – Check if all elements yield truthy results when...
½ – Halved.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¥ü*dZ
```
-2 bytes by taking the answer from the same challenge without source restriction. [All credit goes to *@Grimmy*](https://codegolf.stackexchange.com/a/199062/52210), so make sure to upvote his answer as well!!
Outputs `0` for zigzagging and `1` for non-zigzagging sequences.
The code points are [`[165,252,42,100,90]`](https://tio.run/##yy9OTMpM/f//6L4jbcXB2f//H1p6eI9WShQA) in the [05AB1E code page](https://github.com/Adriandmen/05AB1E/wiki/Codepage).
[Try it online.](https://tio.run/##yy9OTMpM/f//0NLDe7RSov7/jzY0M9VRMDI10lEwAWJDAwMdBUuDWAA)
**Original 7-byter:**
```
¥.±¥Ä;P
```
Outputs `1.0` for zigzagging and `0.0` for non-zigzagging sequences.
The code points are [`[165,46,177,165,196,59,80]`](https://tio.run/##yy9OTMpM/f//6L4jbcXB2f//H1qqd2jjoaWHW6wDAA) in the [05AB1E code page](https://github.com/Adriandmen/05AB1E/wiki/Codepage).
[Try it online.](https://tio.run/##yy9OTMpM/f//0FK9QxsPLT3cYh3w/3@0oZmpjoKJmY6Cobk5kADxDC2BXFNLHQULg1gA)
**Explanation:**
```
¥ # Take the forward differences (deltas) of the (implicit) input-list
# i.e. [1,2,0,3,2,3] → [1,-2,3,-1,1]
ü # For each overlapping pair:
* # Multiply them together
# → [[1,-2],[-2,3],[3,-1],[-1,1]] → [-2,-6,-3,-1]
d # Check for each whether it's non-negative (>= 0)
# → [0,0,0,0]
Z # Take the maximum of that
# → 0
# (after which it is output implicitly as result)
¥ # Take the forward differences (deltas) of the (implicit) input-list
# i.e. [1,2,0,3,2,3] → [1,-2,3,-1,1]
.± # Calculate the sign for each of them (-1 if a<0; 0 if 0; 1 if a>0)
# → [1,-1,1,-1,1]
¥ # Calculate the deltas of those
# → [-2,2,-2,2]
Ä # Take the absolute value of each
# → [2,2,2,2]
; # Halve each
# → [1.0,1.0,1.0,1.0]
P # Take the product of the list resulting in either 1.0 or 0.0
# → 1.0
# (after which it is output implicitly as result)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/) `-!`, ~~16~~ 14 bytes
Well, this ain't pretty but I'm just happy it works!
Outputs `true` for zig-zag or `false` if not.
```
ä'- m'g ä'a èÍ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=5CctIG0nZyDkJ2Eg6M0=&input=WzIyOCwzOSw0NSwzMiwxMDksMzksMTAzLDMyLDIyOCwzOSw5NywzMiwyMzIsMjA1XQotIQ==)
Codepoints are `[228,39,45,32,109,39,103,32,228,39,97,32,232,205]` and included as the test in the link above.
---
## Explanation
```
:Implicit input of array
ä'- :Consecutive differences
m'g :Map signs
ä'a :Consecutive absolute differences
Í :Subtract each from 2
è :Count the truthy (non-zero) elements
:Implicitly negate and output resulting boolean.
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 154 bytes
```
(d Z(q ( ( X Y T )(i T(i(l X Y )(i(l(h T)Y )(F(c Y T ) ) 0 )(i(l Y X )(i(l Y(h T ) )(F(c Y T ) ) 0)0 ) )(e(e X Y)0
( d F(q ( ( L )(Z(h L )(h(t L ) )(t(t L
```
[Tr y i t o n lin e!](https://tio.run/##bY09DsIwDIX3nuKN9pY2nCETY4bSlVZqpAqByMLpg19bJEKRB7@fz0lOt9eSnvdSZMQgD4hNjwsiVBKiJFlWr1QyIyp1kOvG2LitM99/FDl2NaduzSaZ@KK6RjAi7H@erRnsjnuWzG0qUxUJINWiU9Vmdx3aL2dd5c1VNHsHX2Uny7yl7YEj@Zv6v9yRpCtv "tinylisp – Try It Online")
### Explanation
`(load library)` is disallowed by the source restriction, so we have to use only builtins. Since these are each one character, we can just add spaces wherever necessary to make the codepoints zigzag.
The solution uses a pair of mutually recursive functions. `F` takes a list of at least two elements and calls `Z` with three arguments: the first two elements (`X` and `Y`) and the remainder of the list (`T`). `Z` does most of the work:
* If `T` is not empty:
+ If `X` is less than `Y`:
- If head of `T` is also less than `Y`, call `F` with `Y` prepended to `T`
- Otherwise, return false
+ Else, if `Y` is less than `X`:
- If `Y` is also less than head of `T`, call `F` with `Y` prepended to `T`
- Otherwise, return false
+ Else (`X` equals `Y`), return false
* Else (`T` is empty, `X` and `Y` represent a two-element list):
+ Return true if `X` is not equal to `Y`, false otherwise
Ungolfed:
```
(load library)
(def zigzag?
(lambda (X Y T)
(if T
(if (less? X Y)
(if
(less? (head T) Y)
(zigzag-list? (cons Y T))
0)
(if (less? Y X)
(if
(less? Y (head T))
(zigzag-list? (cons Y T))
0)
0))
(equal? (equal? X Y) 0))))
(def zigzag-list?
(lambda (L)
(zigzag?
(head L)
(head (tail L))
(tail (tail L)))))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
IṠµaIẠ
```
[Try it online!](https://tio.run/##y0rNyan8/9/z4c4Fh7Ymej7cteD////RhjpGOgZAaKxjGAsA "Jelly – Try It Online")
Returns `1` for truthy, `0` for falsy.
[Codepoints](https://tio.run/##AR8A4P9qZWxsef//w5hKaeKxruKAmf///0nhuaDCtWFfxp1Q): `[73, 205, 9, 97, 73, 171]` ([valid](https://tio.run/##y0rNyan8/9/z4c4Fh7Ymej7cteD/4RlemY82rnvUMPNwO4oMAA))
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 61 bytes
```
{ [*] ($_[{1…*} ] Z<@$_)Z+^ ($_[{1…*} ] Z>@$_[{2…*} ])}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiFaK1ZBQyU@utrwUcMyrVqFWIUoGweVeM0o7Th0cTsHEN8Iytes/V@cCDJGI9pQx1THUMcoVtOaCyFkpGOMKgRSY6ljgSlkCRLiUqfILep6@UUpxXpqaXpAs/8DAA "Perl 6 – Try It Online")
The code points are:
```
(123 32 91 42 93 32 40 36 95 91 123 49 8230 42 125 32 93 32 90 60 64 36 95 41 90 43 94 32 40 36 95 91 123 49 8230 42 125 32 93 32 90 62 64 36 95 91 123 50 8230 42 125 32 93 41 125)
```
And yes, those are unicode characters in there. This is more or less my original solution, with a few spaces and curly braces mixed in.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
¥DÄ/¥(Ä2QP
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0FKXwy36h5ZqHG4xCgz4/z/aUMdIx0DHWMcoFgA "05AB1E – Try It Online")
**Explanation**
```
¥ # calculate deltas of input
DÄ/ # divide each by its absolute value
¥ # calculate deltas
( # negate each
Ä # absolute value of each
2Q # equals 2
P # product
```
Code points are: `[165, 68, 196, 47, 165, 40, 196, 50, 81, 80]`
] |
[Question]
[
I found it quite hard to achieve a range of numbers as rows in `MySQL`.
For example the range 1-5 is achieved by:
```
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
UNION
SELECT 5
```
will result in:
>
>
> ```
> 1
> 2
> 3
> 4
> 5
>
> ```
>
>
for 0-99 I can cross join two 0-9 tables:
```
CREATE TABLE nums as
SELECT 0 as num
UNION
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
UNION
SELECT 5
UNION
SELECT 6
UNION
SELECT 7
UNION
SELECT 8
UNION
SELECT 9
;
Select n.num*10+nums.num v
From nums n cross join nums
```
I'm tired of writing all these `UNION`s and looking for a way to shrink the code.
Any ideas how to **golf it** (for example 0-1,000,000 range) in MySQL or any SQL syntax ?
**Extra points** are given for:
* single statement
* no procedures
* no variables
* no DDL statements
* only DQL statements
[Answer]
For SQL dialects that support [recursive CTEs](https://sqlite.org/lang_with.html) like sqlite, you can do something like the following:
```
WITH RECURSIVE f(x) AS
(
SELECT 1 UNION ALL SELECT x + 1 FROM f LIMIT 1000000
)
SELECT x
FROM f;
```
This doesn't depend on any existing table and you can change the LIMIT clause as desired. I originally saw a variant of this on StackOverflow.
[Answer]
Similar to [@BradC's method](https://codegolf.stackexchange.com/a/129221/61613).
I used MS SQL, which has a table in `[master]` with a number range of -1 through 2048. You can use the `BETWEEN` operator to create your range.
```
SELECT DISTINCT(number)
FROM master..[spt_values]
WHERE number BETWEEN 1 AND 5
```
If you want to golf this, you can do:
```
SELECT TOP 5 ROW_NUMBER()OVER(ORDER BY number)FROM master..spt_values
```
[Answer]
### PostgreSQL, 35 bytes
PostgreSQL has this easy:
```
SELECT * FROM generate_series(1,5)
```
If you need it named:
```
SELECT num FROM generate_series(1,5)AS a(num)
```
You can also do this with timestamps. <https://www.postgresql.org/docs/9.5/static/functions-srf.html>
[Answer]
Great option [from this post](https://stackoverflow.com/questions/186756/generating-a-range-of-numbers-in-mysql/21286493#21286493) (found by @Arnauld):
```
SELECT id%1000001 as num
FROM <any_large_table>
GROUP BY num
```
For me - it's pretty much solves the challenge.
[Answer]
# PostgreSQL specific
[`generate_series()`](https://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SERIES) generates a set, so you can user it not only in `from` clause, but anywhere where a set may occur:
```
psql=# select generate_series(10, 20, 3);
generate_series
-----------------
10
13
16
19
(4 rows)
```
You can also do operations directly on the set:
```
psql=# select 2000 + generate_series(10, 20, 3) * 2;
?column?
----------
2020
2026
2032
2038
(4 rows)
```
If multiple sets have the same length, you can traverse them in parallel:
```
psql=# select generate_series(1, 3), generate_series(4, 6);
generate_series | generate_series
-----------------+-----------------
1 | 4
2 | 5
3 | 6
(3 rows)
```
For sets with different lengths a Cartesian product is generated:
```
psql=# select generate_series(1, 3), generate_series(4, 5);
generate_series | generate_series
-----------------+-----------------
1 | 4
2 | 5
3 | 4
1 | 5
2 | 4
3 | 5
(6 rows)
```
But if you use them in `from` clause, you get Cartesian product for same length sets too:
```
psql=# select * from generate_series(1, 2), generate_series(3, 4) second;
generate_series | second
-----------------+--------
1 | 3
1 | 4
2 | 3
2 | 4
(4 rows)
```
It can also generate set of timestamps. For example you born on 2000-06-30 and want to know in which years you celebrated your birthday in a weekend:
```
psql=# select to_char(generate_series, 'YYYY - Day') from generate_series('2000-06-30', current_date, interval '1 year') where to_char(generate_series, 'D') in ('1', '7');
to_char
------------------
2001 - Saturday
2002 - Sunday
2007 - Saturday
2012 - Saturday
2013 - Sunday
(5 rows)
```
[Answer]
MS SQL has an undocumented system table in the `master` database called `spt_values`. Among other things, it contains a range of numbers from 0 to 2047:
```
--returns 0 to 2,047
SELECT number n
FROM master..spt_values
WHERE TYPE='P'
```
Useful as a numbers table just by itself, but in a CTE you can get some big numbers pretty quickly:
```
--returns 0 to 4,194,304
WITH x AS(SELECT number n FROM master..spt_values WHERE TYPE='P')
SELECT 2048*x.a+*y.a
FROM x,x y
ORDER BY 1
```
[Answer]
(These work in MS-SQL, not sure if they works for mySQL or other platforms.)
For smaller sets (ordered or non-ordered), use the `VALUES` constructor:
```
--Generates 0-9
SELECT a
FROM(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9))x(a)
```
(This works for anything, although strings can get pretty long with all the repeated single quotes.)
Then you can cross-multiply using a named CTE (common table expression) so you don't have to repeat it:
```
--Generates 0-999
WITH x AS(SELECT a FROM(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9))x(a))
SELECT 100*x.a+10*y.a+z.a
FROM x,x y,x z
ORDER BY 1
```
There are tons of other techniques out there, look for "SQL generating a number table", although most aren't optimized for golfing.
[Answer]
One more option, this one specific to MS SQL 2016 and above:
```
SELECT value v
FROM STRING_SPLIT('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16', ',')
```
I'll likely find this more handy for lists of strings, but I can see ways it will be useful with numbers as well.
[Answer]
# T-SQL, 98 bytes
```
WITH H AS(SELECT 0i UNION ALL SELECT i+1FROM H WHERE i<99)SELECT H.i+1e4*A.i+B.i*1e2FROM H,H A,H B
```
* ✓ single statement
* ✓ no procedures
* ✓ no variables
* ✓ no DDL statements
* ✓ only DQL statements
[Answer]
Another for SQL Server...
```
WITH
cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)), -- 10
cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b), -- 100
cte_Tally (n) AS (
SELECT TOP (<how many ROWS do you want?>)
ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM
cte_n2 a CROSS JOIN cte_n2 b -- 10,000
)
SELECT
t.n
FROM
cte_Tally t;
```
] |
[Question]
[
Given a positive integer *n* and a number *a*, the *n*-th [tetration](https://en.wikipedia.org/wiki/Tetration) of *a* is defined as *a*^(*a*^(*a*^(...^*a*))), where *^* denotes exponentiation (or power) and the expression contains the number *a* exactly *n* times.
In other words, tetration is right-associative iterated exponentiation. For *n*=4 and *a*=1.6 the tetration is 1.6^(1.6^(1.6^1.6)) ≈ 3.5743.
The inverse function of tetration with respect to *n* is the [super-logarithm](https://en.wikipedia.org/wiki/Super-logarithm). In the previous example, 4 is the super-logarithm of 3.5743 with "super-base" 1.6.
# The challenge
Given a positive integer *n*, find *x* such that *n* is the super-logarithm of itself in super-base *x*. That is, find *x* such that *x*^(*x*^(*x*^(...^*x*))) (with *x* appearing *n* times) equals *n*.
# Rules
Program or function allowed.
Input and output formats are flexible as usual.
The algorithm should theoretically work for all positive integers. In practice, input may be limited to a maximum value owing to memory, time or data-type restrictions. However, the code must work for inputs up to `100` at least in less than a minute.
The algorithm should theoretically give the result with `0.001` precision. In practice, the output precision may be worse because of accumulated errors in numerical computations. However, the output must be accurate up to `0.001` for the indicated test cases.
Shortest code wins.
# Test cases
```
1 -> 1
3 -> 1.635078
6 -> 1.568644
10 -> 1.508498
25 -> 1.458582
50 -> 1.448504
100 -> 1.445673
```
# Reference implementation
Here's a **reference implementation** in Matlab / Octave (try it at [Ideone](http://ideone.com/6yuUaZ)).
```
N = 10; % input
t = .0001:.0001:2; % range of possible values: [.0001 .0002 ... 2]
r = t;
for k = 2:N
r = t.^r; % repeated exponentiation, element-wise
end
[~, ind] = min(abs(r-N)); % index of entry of r that is closest to N
result = t(ind);
disp(result)
```
For `N = 10` this gives `result = 1.5085`.
The following code is a **check** of the output precision, using variable-precision arithmetic:
```
N = 10;
x = 1.5085; % result to be tested for that N. Add or subtract 1e-3 to see that
% the obtained y is farther from N
s = num2str(x); % string representation
se = s;
for n = 2:N;
se = [s '^(' se ')']; % build string that evaluates to iterated exponentiation
end
y = vpa(se, 1000) % evaluate with variable-precision arithmetic
```
This gives:
* For `x = 1.5085`: `y = 10.00173...`
* For `x = 1.5085 + .001`: `y = 10.9075`
* For `x = 1.5085 - .001` it gives `y = 9.23248`.
so `1.5085` is a valid solution with `.001` precision.
[Answer]
# Haskell, ~~55~~ ~~54~~ 52 bytes
```
s n=[x|x<-[2,1.9999..],n>iterate(x**)1!!floor n]!!0
```
Usage:
```
> s 100
1.445600000000061
```
Thanks to @nimi for 1 byte!
Thanks to @xnor for 2!
[Answer]
## Javascript, ES6: 77 bytes / ES7: ~~57~~ 53 bytes
### ES6
```
n=>eval("for(x=n,s='x';--x;s=`Math.pow(x,${s})`);for(x=2;eval(s)>n;)x-=.001")
```
### ES7
Using `**` as suggested by DanTheMan:
```
n=>eval("for(x=2;eval('x**'.repeat(n)+1)>n;)x-=.001")
```
### Example
```
let f =
n=>eval("for(x=n,s='x';--x;s=`Math.pow(x,${s})`);for(x=2;eval(s)>n;)x-=.001")
console.log(f(25));
```
[Answer]
# Mathematica, ~~40~~ 33 bytes
*Thanks to murphy for an almost 20% savings!*
```
1//.x_:>x+.001/;Nest[x^#&,1,#]<#&
```
`Nest[x^#&,1,n]` produces the nth tetration of x. So `Nest[x^#&,1,#]<#` tests whether the (input)th tetration of x is less than (input). We simply start at x=1 and add 0.001 repeatedly until the tetration is too large, then output the last x value (so the answer is guaranteed to be larger than the exact value, but within 0.001).
As I'm slowly learning: `//.x_:>y/;z` or `//.x_/;z:>y` means "look for anything that matches the template x, but only things for which the test z returns true; and then operate on x by the rule y; repeatedly until nothing changes". Here the template `x_` is just "any number I see", although in other contexts it could be further constrained.
When the input is at least 45, the tetration increases so rapidly that that last step causes an overflow error; but the value of x is still updated and output correctly. Decreasing the step-size from 0.001 to 0.0001 fixes this problem for inputs up to 112, and gives a more precise answer to boot (and still runs quickly, in about a quarter second). But that's one extra byte, so forget that!
Original version:
```
x=1;(While[Nest[x^#&,1,#]<#,x+=.001];x)&
```
[Answer]
# J, ~~39~~ ~~31~~ 28 bytes
```
(>./@(]*[>^/@#"0)1+i.%])&1e4
```
Based on the reference implementation. It is only accurate to three decimal places.
Saved 8 bytes using the method from @Adám's [solution](https://codegolf.stackexchange.com/a/93208/6710).
## Usage
Extra commands used to format multiple input/output.
```
f =: (>./@(]*[>^/@#"0)1+i.%])&1e4
(,.f"0) 1 3 6 10 25 50 100
1 0
3 1.635
6 1.5686
10 1.5084
25 1.4585
50 1.4485
100 1.4456
f 1000
1.4446
```
## Explanation
```
(>./@(]*[>^/@#"0)1+i.%])&1e4 Input: n
1e4 The constant 10000
( ) Operate on n (LHS) and 10000 (RHS)
i. The range [0, 10000)
] Get (RHS) 10000
% Divide each in the range by 10000
1+ Add 1 to each
( ) Operate on n (LHS) and the range (RHS)
#"0 For each in the range, create a list of n copies
^/@ Reduce each list of copies using exponentation
J parses from right-to-left which makes this
equivalent to the tetration
[ Get n
> Test if each value is less than n
] Get the initial range
* Multiply elementwise
>./@ Reduce using max and return
```
[Answer]
# Python, 184 bytes
```
def s(n):
def j(b,i):
if i<0.1**12:
return b
m = b+i
try:
v = reduce(lambda a,b:b**a,[m]*n)
except:
v = n+1
return j(m,i/2) if v<n else j(b,i/2)
return j(1.0,0.5)
```
Test output (skipping the actual print statements):
```
s(1) 1.0
s(3) 1.63507847464
s(6) 1.5686440646
s(10) 1.50849792026
s(25) 1.45858186605
s(50) 1.44850389566
s(100) 1.44567285047
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~33~~ 25 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Needs `⎕IO←0` which is default on many systems.
```
⌈/⎕(⊢×⊣≥(*/⍴)¨)(1+⍳÷⊢)1E4
```
Theoretically calculates for all integers, but practically limited to very small one only.
[TryAPL online!](http://tryapl.org/?a=%u2206%u21901%20%u22C4%20%u2308/%u2206%28%u22A2%D7%u22A3%u2265%28*/%u2374%29%A8%29%281+%u2373%F7%u22A2%291E4%20%u22C4%20%u2206%u21902%20%u22C4%20%u2308/%u2206%28%u22A2%D7%u22A3%u2265%28*/%u2374%29%A8%29%281+%u2373%F7%u22A2%291E4%20%u22C4%20%u2206%u21903%20%u22C4%20%u2308/%u2206%28%u22A2%D7%u22A3%u2265%28*/%u2374%29%A8%29%281+%u2373%F7%u22A2%291E4%20%u22C4%20%u2206%u21904%20%u22C4%20%u2308/%u2206%28%u22A2%D7%u22A3%u2265%28*/%u2374%29%A8%29%281+%u2373%F7%u22A2%291E4&run)
[Answer]
## Racket 187 bytes
```
(define(f x n)(define o 1)(for((i n))(set! o(expt x o)))o)
(define(ur y(l 0.1)(u 10))(define t(/(+ l u)2))(define o(f t y))
(cond[(<(abs(- o y)) 0.1)t][(> o y)(ur y l t)][else(ur y t u)]))
```
Testing:
```
(ur 1)
(ur 3)
(ur 6)
(ur 10)
(ur 25)
(ur 50)
(ur 100)
```
Output:
```
1.028125
1.6275390625
1.5695312499999998
1.5085021972656247
1.4585809230804445
1.4485038772225378
1.4456728475168346
```
Detailed version:
```
(define (f x n)
(define out 1)
(for((i n))
(set! out(expt x out)))
out)
(define (uniroot y (lower 0.1) (upper 10))
(define trying (/ (+ lower upper) 2))
(define out (f trying y))
(cond
[(<(abs(- out y)) 0.1)
trying]
[(> out y)
(uniroot y lower trying)]
[else
(uniroot y trying upper)]))
```
[Answer]
# [Perl 6](https://perl6.org), 42 bytes
```
{(0,.0001…2).min:{abs $_-[**] $^r xx$_}}
```
( Translation of example Matlab code )
## Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my &code = {(0,.0001…2).min:{abs $_-[**] $^r xx$_}}
my @tests = (
1 => 1,
3 => 1.635078,
6 => 1.568644,
10 => 1.508498,
25 => 1.458582,
50 => 1.448504,
100 => 1.445673,
);
plan +@tests + 1;
my $start-time = now;
for @tests -> $_ ( :key($input), :value($expected) ) {
my $result = code $input;
is-approx $result, $expected, "$result ≅ $expected", :abs-tol(0.001)
}
my $finish-time = now;
my $total-time = $finish-time - $start-time;
cmp-ok $total-time, &[<], 60, "$total-time.fmt('%.3f') is less than a minute";
```
```
1..8
ok 1 - 1 ≅ 1
ok 2 - 1.6351 ≅ 1.635078
ok 3 - 1.5686 ≅ 1.568644
ok 4 - 1.5085 ≅ 1.508498
ok 5 - 1.4586 ≅ 1.458582
ok 6 - 1.4485 ≅ 1.448504
ok 7 - 1.4456 ≅ 1.445673
ok 8 - 53.302 seconds is less than a minute
```
[Answer]
# PHP , 103 Bytes
```
$z=2;while($z-$a>9**-9){for($r=$s=($a+$z)/2,$i=0;++$i<$n=$argv[1];)$r=$s**$r;$r<$n?$a=$s:$z=$s;}echo$s;
```
[Answer]
**Axiom 587 bytes**
```
l(a,b)==(local i;i:=1;r:=a;repeat(if i>=b then break;r:=a^r;i:=i+1);r);g(q,n)==(local r,y,y1,y2,t,v,e,d,i;n<=0 or n>1000 or q>1000 or q<0 => 0;e:=1/(10**(digits()-3));v:=0.01; d:=0.01;repeat(if l(v,n)>=q then break;v:=v+d;if v>=1 and n>25 then d:=0.001;if v>=1.4 and n>40 then d:=0.0001;if v>=1.44 and n>80 then d:=0.00001;if v>=1.445 and n>85 then d:=0.000001);if l(v-d,n)>q then y1:=0.0 else y1:=v-d;y2:=v;y:=l(v,n);i:=1;if abs(y-q)>e then repeat(t:=(y2-y1)/2.0;v:=y1+t;y:=l(v,n);i:=i+1;if i>100 then break;if t<=e then break;if y<q then y1:=v else y2:=v);if i>100 then output "#i#";v)
```
less golfed + numbers
```
l(a,b)==
local i
i:=1;r:=a;repeat(if i>=b then break;r:=a^r;i:=i+1)
r
g(q,n)==
local r, y, y1,y2,t,v,e,d, i
n<=0 or n>1000 or q>1000 or q<0 => 0
e:=1/(10**(digits()-3))
v:=0.01; d:=0.01
repeat --cerco dove vi e' il punto di cambiamento di segno di l(v,n)-q
if l(v,n)>=q then break
v:=v+d
if v>=1 and n>25 then d:=0.001
if v>=1.4 and n>40 then d:=0.0001
if v>=1.44 and n>80 then d:=0.00001
if v>=1.445 and n>85 then d:=0.000001
if l(v-d,n)>q then y1:=0.0
else y1:=v-d
y2:=v; y:=l(v,n); i:=1 -- applico il metodo della ricerca binaria
if abs(y-q)>e then -- con la variabile i di sicurezza
repeat
t:=(y2-y1)/2.0; v:=y1+t; y:=l(v,n)
i:=i+1
if i>100 then break
if t<=e then break
if y<q then y1:=v
else y2:=v
if i>100 then output "#i#"
v
(3) -> [g(1,1), g(3,3), g(6,6), g(10,10), g(25,25), g(50,50), g(100,100)]
Compiling function l with type (Float,PositiveInteger) -> Float
Compiling function g with type (PositiveInteger,PositiveInteger) ->
Float
(3)
[1.0000000000 000000001, 1.6350784746 363752387, 1.5686440646 047324687,
1.5084979202 595960768, 1.4585818660 492876919, 1.4485038956 661040907,
1.4456728504 738144738]
Type: List Float
```
[Answer]
# Common Lisp, 207 bytes
```
(defun superlog(n)(let((a 1d0)(i 0.5))(loop until(< i 1d-12)do(let((v(or(ignore-errors(reduce #'expt(loop for q below n collect(+ a i)):from-end t))(1+ n))))(when(< v n)(setq a (+ a i)))(setq i(/ i 2)))) a))
```
Using `reduce` with `:from-end t` avoids the need of doing a "reversing exponentiation" intermediate lambda (basically `(lambda (x y) (expt y x))`, saving 14 bytes (12, if you remove removable spaces).
We still need to handle float overflow, but an `ignore-errors` form returns `nil` if an error happened, so we can use `or` to provide a default value.
] |
[Question]
[
Create a function or program that takes two inputs:
* A list of integers that shall be sorted (less than 20 elements)
* A positive integer, `N`, saying how many comparisons you should take
The function shall stop, and output the resulting list of integers after `N` comparisons. If the list is fully sorted before `N` comparisons are made, then the sorted list should be outputted.
---
The [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) algorithm is well known, and I guess most people know it. The following Pseudo-code and animation (both from the linked Wikipedia-article) should provide the necessary details:
```
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
```
The animation below shows the progress:
[](https://i.stack.imgur.com/bKL9U.gif)
An example (taken directly from the linked Wikipedia article) shows the steps when sorting the list: `( 5 1 4 2 8 )`:
**First Pass**
```
1: ( 5 1 4 2 8 ) -> ( 1 5 4 2 8 ) // Here, algorithm compares the first two elements,
// and swaps since 5 > 1.
2: ( 1 5 4 2 8 ) -> ( 1 4 5 2 8 ) // Swap since 5 > 4
3: ( 1 4 5 2 8 ) -> ( 1 4 2 5 8 ) // Swap since 5 > 2
4: ( 1 4 2 5 8 ) -> ( 1 4 2 5 8 ) // Now, since these elements are already in order
// (8 > 5), algorithm does not swap them.
```
**Second Pass**
```
5: ( 1 4 2 5 8 ) -> ( 1 4 2 5 8 )
6: ( 1 4 2 5 8 ) -> ( 1 2 4 5 8 ) // Swap since 4 > 2
7: ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
8: ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
```
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
**Third Pass**
```
9: ( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
10:( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
11:( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
12:( 1 2 4 5 8 ) -> ( 1 2 4 5 8 )
```
## Test cases:
Format: `Number of comparisons (N): List after N comparisons`
```
Input list:
5 1 4 2 8
Test cases:
1: 1 5 4 2 8
2: 1 4 5 2 8
3: 1 4 2 5 8
4: 1 4 2 5 8
5: 1 4 2 5 8
6: 1 2 4 5 8
10: 1 2 4 5 8
14: 1 2 4 5 8
Input list:
0: 15 18 -6 18 9 -7 -1 7 19 19 -5 20 19 5 15 -5 3 18 14 19
Test cases:
1: 15 18 -6 18 9 -7 -1 7 19 19 -5 20 19 5 15 -5 3 18 14 19
21: -6 15 18 9 -7 -1 7 18 19 -5 19 19 5 15 -5 3 18 14 19 20
41: -6 9 -7 15 -1 7 18 18 -5 19 19 5 15 -5 3 18 14 19 19 20
60: -6 -7 -1 9 7 15 18 -5 18 19 5 15 -5 3 18 14 19 19 19 20
61: -6 -7 -1 7 9 15 18 -5 18 19 5 15 -5 3 18 14 19 19 19 20
81: -7 -6 -1 7 9 15 -5 18 18 5 15 -5 3 18 14 19 19 19 19 20
119: -7 -6 -1 -5 7 9 15 5 15 -5 3 18 14 18 18 19 19 19 19 20
120: -7 -6 -1 -5 7 9 15 5 15 -5 3 18 14 18 18 19 19 19 19 20
121: -7 -6 -1 -5 7 9 5 15 15 -5 3 18 14 18 18 19 19 19 19 20
122: -7 -6 -1 -5 7 9 5 15 15 -5 3 18 14 18 18 19 19 19 19 20
123: -7 -6 -1 -5 7 9 5 15 -5 15 3 18 14 18 18 19 19 19 19 20
201: -7 -6 -5 -1 -5 3 5 7 9 14 15 15 18 18 18 19 19 19 19 20
221: -7 -6 -5 -5 -1 3 5 7 9 14 15 15 18 18 18 19 19 19 19 20
```
---
* Yes, built-in Bubble sort algorithms are permitted.
* No, you can not assume only positive integers, or unique integers.
* The sorting must be in the order described above. You can't start at the end of the list
[Answer]
# JavaScript (ES6), ~~102~~ ~~82~~ ~~80~~ ~~86~~ 80 bytes
*Bug fix and 1 byte saved thanks to @edc65*
```
(a,m)=>eval("for(i=0;m;a[j=i-1]>(b=a[i])?a[a[i]=a[j],j]=b:0)1/a[++i]?m--:i=0;a")
```
Recursion ~~may not be~~ ~~is definitely not~~ is probably the best approach, but I'm sticking with a loop for now.
### Try it out:
```
f=(a,m)=>eval("for(i=0;m;a[j=i-1]>(b=a[i])?a[a[i]=a[j],j]=b:0)1/a[++i]?m--:i=0;a")
```
```
Enter your numbers:<br>
<input id=A rows=10 value="5 1 4 2 8"><br>
Enter the number of steps:<br>
<input type="number" min=0 id=B rows=10 value="1"><br>
<button onclick="C.innerHTML=f((A.value.match(/-?\d+/g)||[]).map(Number),B.value)">Run</button><br>
<pre id=C></pre>
```
[Answer]
## Haskell, ~~83~~ ~~82~~ 81 bytes
```
y%x@(a:b:c)=(y++x):(y++[min a b])%(max a b:c)
y%x=[]%(y++x)
[x]!_=[x]
x!n=[]%x!!n
```
Usage example: `[5,1,4,2,8] ! 5` -> `[1,4,2,5,8]`.
In function `%` `y` keeps track of the elements visited so far during the current pass, `x` are ones yet to examine. `a` and `b` are the next two, i.e. the candidates to swap. If we reach the end of the list, we start from the beginning: `y%x = []%(y++x)`. All steps are stored in a list where the main function picks the `n`th element.
Edit: previous versions didn't work for single element lists, luckily the new version is even shorter.
[Answer]
# Python 3, ~~77~~ 74 bytes
-3 bytes thanks to @Maltysen (init `j` in declaration)
```
lambda l,n,j=0:exec('j*=j<len(l)-1;l[j:j+2]=sorted(l[j:j+2]);j+=1;'*n)or l
```
Test cases at [**ideone**](http://ideone.com/5pVfiM)
Uses `sorted` to do each compare and swap operation, but it is performing a bubble sort.
Sets `j=0` (the left index), then performs `n` compare and swaps of adjacent list items, resetting `j` to `0` whenever this window goes out of bounds.
The `j*=j<len(l)-1` will multiply `j` by `False` (i.e. `0`) at that point, whereas every other time it will multiply `j` by `True` (i.e. `1`).
(It will still work for an empty list too.)
[Answer]
## PowerShell v2+, ~~135~~ 129 bytes
```
param($a,$n)for($s=1;$s){($s=0)..($a.count-2)|%{if($a[$_]-gt$a[$_+1]){$a[$_],$a[$_+1]=$a[$_+1],$a[$_];$s=1}if(!--$n){$a;exit}}}$a
```
So. Many. Dollars.
(*Saved six bytes by realizing that this challenge doesn't include the "for free" optimization of skipping the last element(s) on each pass since that's guaranteed sorted, and instead runs through a full pass each time. This moved the `$a.count` into the `for` loop and eliminated the `$z` variable.*)
Straight up bubble sort, with one nifty spot, doing the swap in one step --
`$a[$_],$a[$_+1]=$a[$_+1],$a[$_]`
The exiting logic is handled via `if(!--$n){$a;exit}`
### Test Cases
(The array is shown as space-separated here because the default [Output Field Separator](https://blogs.msdn.microsoft.com/powershell/2006/07/15/psmdtagfaq-what-is-ofs/) for stringifying an array is a space. The stringification happens because we're concatenating with the labels `"$_ -> "`.)
```
PS C:\Tools\Scripts\golfing> 1,2,3,4,5,6,10,14|%{"$_ -> "+(.\bubble-sorting-in-progress.ps1 @(5,1,4,2,8) $_)}
1 -> 1 5 4 2 8
2 -> 1 4 5 2 8
3 -> 1 4 2 5 8
4 -> 1 4 2 5 8
5 -> 1 4 2 5 8
6 -> 1 2 4 5 8
10 -> 1 2 4 5 8
14 -> 1 2 4 5 8
PS C:\Tools\Scripts\golfing> 1,21,41,60,61,81,119,120,121,122,123,201,221|%{"$_ -> "+(.\bubble-sorting-in-progress.ps1 @(15,18,-6,18,9,-7,-1,7,19,19,-5,20,19,5,15,-5,3,18,14,19) $_)}
1 -> 15 18 -6 18 9 -7 -1 7 19 19 -5 20 19 5 15 -5 3 18 14 19
21 -> -6 15 18 9 -7 -1 7 18 19 -5 19 19 5 15 -5 3 18 14 19 20
41 -> -6 9 -7 15 -1 7 18 18 -5 19 19 5 15 -5 3 18 14 19 19 20
60 -> -6 -7 -1 9 7 15 18 -5 18 19 5 15 -5 3 18 14 19 19 19 20
61 -> -6 -7 -1 7 9 15 18 -5 18 19 5 15 -5 3 18 14 19 19 19 20
81 -> -7 -6 -1 7 9 15 -5 18 18 5 15 -5 3 18 14 19 19 19 19 20
119 -> -7 -6 -1 -5 7 9 15 5 15 -5 3 18 14 18 18 19 19 19 19 20
120 -> -7 -6 -1 -5 7 9 15 5 15 -5 3 18 14 18 18 19 19 19 19 20
121 -> -7 -6 -1 -5 7 9 5 15 15 -5 3 18 14 18 18 19 19 19 19 20
122 -> -7 -6 -1 -5 7 9 5 15 15 -5 3 18 14 18 18 19 19 19 19 20
123 -> -7 -6 -1 -5 7 9 5 15 -5 15 3 18 14 18 18 19 19 19 19 20
201 -> -7 -6 -5 -1 -5 3 5 7 9 14 15 15 18 18 18 19 19 19 19 20
221 -> -7 -6 -5 -5 -1 3 5 7 9 14 15 15 18 18 18 19 19 19 19 20
```
[Answer]
## R, ~~132~~ ~~131~~ ~~112~~ 136 bytes
The programme receives the input as follows: first `N`, then the vector itself. For example, if you want `v = [5 1 4 2 8]` and `n = 1`, the input that goes into the `scan` is `1 5 1 4 2 8`. So in order to run this programme, you **run the first line**, *feed the numbers one by one in the console*, and **then run the rest** (this is a REPL answer).
Then the following code does the trick:
```
v=scan()
s=m=0
while(!s){s=T;for(i in 3:length(v)){m=m+1
if(m>v[1]){s=T;break}
if(v[i-1]>v[i]){v[c(i-1,i)]=v[c(i,i-1)];s=F}}}
cat(v[-1])
```
Test:
```
Input: a vector with N first and the elements to be sorted next
1 5 1 4 2 8
5 5 1 4 2 8
14 5 1 4 2 8
60 15 18 -6 18 9 -7 -1 7 19 19 -5 20 19 5 15 -5 3 18 14 19
Output:
1 5 4 2 8
1 4 2 5 8
1 2 4 5 8
-6 -7 -1 9 7 15 18 -5 18 19 5 15 -5 3 18 14 19 19 19 20
```
Update: golfed 1 byte owing to [Vlo](https://codegolf.stackexchange.com/users/30693/vlo).
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 25 bytes
```
ḣ©ṫ-Ṣ®ṖṖ¤;;ṫḊ¥
JḊṁ¹³W¤;ç/
```
Based on my [answer](https://codegolf.stackexchange.com/a/92828/6710) in J.
[Try it online!](http://jelly.tryitonline.net/#code=4bijwqnhuast4bmiwq7huZbhuZbCpDs74bmr4biKwqUKSuG4iuG5gcK5wrNXwqQ7w6cv&input=&args=WzUsIDEsIDQsIDIsIDhd+Nw)
[Verify number of comparisons.](http://jelly.tryitonline.net/#code=4bijwqnhuast4bmiwq7huZbhuZbCpDs74bmr4biKwqUKSuG4iuG5gcK5wrNXwqQ7w6cvCsOnw5DigqzCueG5rSLFkuG5mOKCrFk&input=&args=WzUsIDEsIDQsIDIsIDhd+WzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwLCAxMSwgMTJd)
## Explanation
The helper link modifies the list at index `[i-1, i]` by sorting it which produces the same result as the bubble sort comparison.
```
ḣ©ṫ-Ṣ®ṖṖ¤;;ṫḊ¥ Helper link - Input: list A, index i
ḣ Take the first i values
© Save a copy of it
ṫ- Take the last two values
Ṣ Sort them
; Append them to
® Get the copy
ṖṖ¤ Pop the last two values (Ṗ is pop)
; Prepend it to
ṫ Take the last i values
Ḋ¥ Dequeue - remove the head
JḊṁ¹³W¤;ç/ Input: list A and # of comparisons n
J Enumerate the indices of A
Ḋ Dequeue - remove the head
ṁ Reshape it cyclically to length n
¹ Identity function (Just to avoid parsing rules)
; Append it to
³ The list A
W¤ Wrap it as an array
ç/ Reduce from left to right using the helper link and return
```
[Answer]
# Pyth, ~~34~~ 32 Bytes
```
AQVH=*<ZtlGZ=GsXJcG,Zh=hZ1ShtJ;G
```
A translation of Jonathan Allan's Python answer.
[Try it here!](http://pyth.herokuapp.com/?code=AQVH%3D%2a%3CZtlGZ%3DGsXJcG%2CZh%3DhZ1ShtJ%3BG&input=%5B%5B5%2C4%2C3%2C2%2C1%5D%2C+5%5D&debug=0)
[Answer]
## JavaScript (ES6), ~~82~~ ~~80~~ 79 bytes
```
f=(a,m,n=0,_,b=a[n+1])=>1/b?m?f(a,m-1,n+1,a[n]>b?a[a[n+1]=a[n],n]=b:0):a:f(a,m)
```
Based on @ETHproduction's original answer. Edit: Saved 2 bytes thanks to @JonathanAllan. Saved 1 byte thanks to @edc65.
[Answer]
# [J](http://jsoftware.com), ~~62~~ 60 bytes
```
>@([:({.,(2/:~@{.}.),]}.~2+[)&.>/]|.@;<:@#@]<@|i.@[)^:(]1<#)
```
This is a verb that takes two arguments: the number of comparisons on the LHS and the list of integers on the RHS. First it checks if the length of the list if greater than one. If it isn't, it returns the list unmodified, otherwise it operates on it by performing the specified number of comparisons before returning the result.
## Usage
For the first test case, extras commands are used to format multiple input/output. The second test case is shown as single input/output.
```
f =: >@([:({.,(2/:~@{.}.),]}.~2+[)&.>/]|.@;<:@#@]<@|i.@[)^:(]1<#)
1 2 3 4 5 6 10 14 ([;f)"0 1 ] 5 1 4 2 8
┌──┬─────────┐
│1 │1 5 4 2 8│
├──┼─────────┤
│2 │1 4 5 2 8│
├──┼─────────┤
│3 │1 4 2 5 8│
├──┼─────────┤
│4 │1 4 2 5 8│
├──┼─────────┤
│5 │1 4 2 5 8│
├──┼─────────┤
│6 │1 2 4 5 8│
├──┼─────────┤
│10│1 2 4 5 8│
├──┼─────────┤
│14│1 2 4 5 8│
└──┴─────────┘
1 f 15 18 _6 18 9 _7 _1 7 19 19 _5 20 19 5 15 _5 3 18 14 19
15 18 _6 18 9 _7 _1 7 19 19 _5 20 19 5 15 _5 3 18 14 19
123 f 15 18 _6 18 9 _7 _1 7 19 19 _5 20 19 5 15 _5 3 18 14 19
_7 _6 _1 _5 7 9 5 15 _5 15 3 18 14 18 18 19 19 19 19 20
221 f 15 18 _6 18 9 _7 _1 7 19 19 _5 20 19 5 15 _5 3 18 14 19
_7 _6 _5 _5 _1 3 5 7 9 14 15 15 18 18 18 19 19 19 19 20
```
## Explanation
It's hard to write terse code in J that uses mutability, so instead I convert the problem into reducing a list on a set of indicies. I think this code is messy so I will walkthrough the job of each phrase instead of each primitive. The first part grabs the length of the list and produces a range. Then, operate on each infix of size 2 to emulate one pass of comparisons.
```
i. # 5 1 4 2 8
0 1 2 3 4
2 <\ i. # 5 1 4 2 8
┌───┬───┬───┬───┐
│0 1│1 2│2 3│3 4│
└───┴───┴───┴───┘
2 <@{.\ i. # 5 1 4 2 8
┌─┬─┬─┬─┐
│0│1│2│3│
└─┴─┴─┴─┘
```
These are the start indicies of each comparison. If 7 comparisons are being performed, reshape it to get the desired amount. J parses right to left, so its reduces right to left, like fold-right. Append the initial list and reverse it.
```
7 $ 2 <@{.\ i. # 5 1 4 2 8
┌─┬─┬─┬─┬─┬─┬─┐
│0│1│2│3│0│1│2│
└─┴─┴─┴─┴─┴─┴─┘
|. 5 1 4 2 8 ; 7 $ 2 <@{.\ i. # 5 1 4 2 8
┌─┬─┬─┬─┬─┬─┬─┬─────────┐
│2│1│0│3│2│1│0│5 1 4 2 8│
└─┴─┴─┴─┴─┴─┴─┴─────────┘
```
Alternatively, the range [0, 7) can be made and each value taken modulo the length of the list minus 1 to create the same range.
```
(<: # 5 1 4 2 8) <@| i. 7
┌─┬─┬─┬─┬─┬─┬─┐
│0│1│2│3│0│1│2│
└─┴─┴─┴─┴─┴─┴─┘
```
The last part is a verb that takes a list on the RHS and an index on the LHS which marks the start index of the comparison. Select the two elements starting at that index, sort them, and plug them back into the list and return it.
```
> ({.,(2/:~@{.}.),]}.~2+[)&.>/ |. 5 1 4 2 8 ; 7 $ 2 <@{.\ i. # 5 1 4 2 8
1 2 4 5 8
```
[Answer]
# Matlab, ~~93~~ 91 bytes
```
function l=f(l,m)
n=numel(l)-1;i=0;while n&m;i=mod(i,n)+1;m=m-1;l(i:i+1)=sort(l(i:i+1));end
```
Saves 11 bytes by omitting `if l(i)>l(i+1);l(i:i+1)=l([i+1,i])`, and instead just sort the two elements every time. Works for lists of length 1. Could save a byte or two using Octave's `m--` operator, but that's not much.
Saves two more bytes by setting `n=numel(l)-1;`, because then I can just do `while n` instead of `while n>1`, and `i=mod(i,n)+1` instead of `i=mod(i,n-1)+1`.
---
For the record, this answer was written many hours after the challenge was created.
[Answer]
# Groovy (101 Bytes)
```
{l,n->(l.size()..0).each{i->(0..i-2).each{if(l[it]>l[it+1] && n>0 && it>-1){l.swap(it,it+1)};n--}};l}
```
*EDIT: I didn't need to write my own swap closure, groovy had this built in.*
Try it here: <https://groovyconsole.appspot.com/script/5104724189642752>
## Example Output Trace:
```
4:[1, 5, 4, 2, 8]
3:[1, 4, 5, 2, 8]
2:[1, 4, 2, 5, 8]
1:[1, 4, 2, 5, 8]
0:[1, 4, 2, 5, 8] - Locks in the final answer.
-1:[1, 4, 2, 5, 8]
-2 (Return):[1, 4, 2, 5, 8]
```
---
# Old Implementation (122 Bytes)
```
m={l,n->s={x,y->t=l[x];l[x]=l[y];l[y]=t};((l.size()-2)..2).each{i->(0..i).each{if(l[it]>l[it+1] && n){s(it,it+1)};n--}};l}
```
Try it here: <https://groovyconsole.appspot.com/script/6316871066320896>
[Answer]
# php, ~~148~~ 145 bytes
```
<?php for($i=2,$a=$argv;$a[1]--;$i=$i==count($a)-2?2:$i+1)if($a[$i]>$a[$i+1])list($a[$i],$a[$i+1])=[$a[$i+1],$a[$i]];echo substr(join(' ',$a),5);
```
I'm not very happy with the loop structure but I like the list switch and it does work so I'm posting it anyway. php7.1 would allow me to save at least 4 bytes.
With nicer formatting:
```
<?php
for($i=2,$a=$argv;$a[1]--;$i=$i==count($a)-2?2:$i+1)
if($a[$i]>$a[$i+1])
list($a[$i],$a[$i+1])=[$a[$i+1],$a[$i]];
echo substr(join(' ',$a),5);
```
Edit: Jörg Hülsermann reminded me of join, instead of implode.
note: needs to be in a file with a single character filename.
[Answer]
## Ruby, ~~52~~ 50 bytes
Wait... no Ruby?
```
->l,n{n.times{|a|l[s=a%~-l.size,2]=l[s,2].sort};l}
```
] |
[Question]
[
*[Related](https://codegolf.stackexchange.com/questions/249908/extract-strings-from-text)*
We start with the string `a`, and forever append to the string a comma followed by the string quote-escaped, where quote-escaping means doubling all quotes in a string, and then surrounding it with an additional pair of quotes.
In the first few steps we will get:
* `a`
* `a,'a'`
* `a,'a','a,''a'''`
* `a,'a','a,''a''','a,''a'',''a,''''a'''''''`
If we continue to do that forever, we get the following infinite string:
`a,'a','a,''a''','a,''a'',''a,''''a''''''','a,''a'',''a,''''a'''''',''a,''''a'''',''''a,''''''''a''''''''''''''','a,''a'',''a,''''a'''''',''a,''''a'''',''''a,'''...`
If create a sequence, which is 1 at indices that string contains a quotes, we'll get the following sequence:
1. `0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, ...`
Alternatively, we can look at the indices of quotes, and get the following sequence (this is 0-indexed):
2. `2, 4, 6, 9, 10, 12, 13, 14, 16, 19, 20, 22, 23, 25, 26, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 42, 45, 46, ...`
Your task is to output one of these numeric sequences.
## Rules
* You can choose whether you use 0-indexing or 1-indexing.
* If you output sequence 1, you can use any truthy/falsey values instead of 1/0, or any two different consistent values.
* If you output sequence 2 (the one with the indices), you can choose if those indices use 0-indexing or 1-indexing.
* You can use one of following output modes:
+ Take \$n\$ as an input, and output the \$n\$-th element in the sequence.
+ Take \$n\$ as an input, and output all elements in the sequence up to the \$n\$-th element.
+ Take no input, and output the entire sequence forever.
* You can use any reasonable input/output format.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
This is code golf, so the shortest code wins.
[Answer]
# [Python](https://www.python.org), 57 bytes (@Steffan)
```
a=b="/"
while[print(end=b)]:b="/\%s\\"%repr(a)[1:-1];a+=b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3LRNtk2yV9JW4yjMyc1KjC4oy80o0UvNSbJM0Y61AMjGqxTExSqpFqQVFGoma0YZWuoax1onatkkQA6DmwMwDAA)
### Old [Python](https://www.python.org), 58 bytes
```
a=b="/"
while[print(end=b)]:b="/\\%s\\"%repr(a)[1:-1];a+=b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3rRJtk2yV9JW4yjMyc1KjC4oy80o0UvNSbJM0Y61AMjExqsUxMUqqRakFRRqJmtGGVrqGsdaJ2rZJEBOgBsEMBAA)
Prints the entire sequence using `/` for `0` and `\` for `1`.
[Answer]
# [J](http://jsoftware.com/), 22 19 bytes
```
{1&(],1,~0 1,+#])&0
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/qw3VNGJ1DHXqDBQMdbSVYzXVDP5rcqUmZ@QrpClpK2TqGZpDeIbmCtV6CgY6IGSIQUIYhkgM/LLIDGQthhhcKpj2HwA "J – Try It Online")
*-3 thanks to ovs!*
Quite slow, as we iterate n times and take the nth result.
TIO link shows first 17 terms.
Approach is straightforward recursion:
* `{` nth item (0-indexed) from...
* `1&( )&0` Iterate n times, starting with 0, and using a constant left arg of 1...
* `(],1,~0 1,+#])` Bookend `+#]` (to be explained below) with `0 1` and `1`
* `+#]` The only interesting part, really. This is how we double up the quotes. Consider `0 0 1 0 1`:
+ `+` adds 1 to every element, taking advantage of the fixed left arg of 1:
```
1 1 2 1 2
```
+ `#]` use that as a duplication mask for `0 0 1 0 1`:
```
0 0 1 1 0 1 1
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
```
0w?(:k≈$vß"1Wf)Ẏ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIwdz8oOmviiYgkdsOfXCIxV2Yp4bqOIiwiIiwiMTUiXQ==)
Same idea as the Jelly answer.
[Answer]
# [lin](https://github.com/molarmanful/lin), 57 bytes
```
.\n0\;.n e*.n `t
dup \; `' `flat1`,0`,1`+ `+
dup \; e&
1,
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Returns an iterable with the first *n* elements.
The code above extremely inefficiently runs through *n* iterations. For testing purposes, the following code is equivalent:
```
100 ; `_
.\n0;.n `t
dup \; `' `flat1`,0`,1`+ `+ `size.n < \@ e&
dup \; e&
1,
```
## Explanation
Prettified code:
```
.\n 0 \; .n e* .n `t
dup ( dup ( 1, ) e& ) `' `flat 1`, 0`, 1`+ `+
```
* `.\n 0 \; .n e*` store the input as *n*, push 0, execute the next line *n* times...
+ `dup ( dup ( 1, ) e& ) `' `flat` top of stack with 1s replaced with `1 1`
+ `1`, 0`, 1`+ `+` prepend `0 1`, append `1`, append result to existing sequence
[Answer]
# [Haskell](https://www.haskell.org), 43 bytes
```
f n=iterate(\x->x++'b':show x)"a"!!n!!n<'a'
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuxNu9zEzDwFW4WC0pLgkiIFFYWUfIVMBRtdhWgDPT1DA4NYa4XMNIU0oFhJRmqegpKhjoKSQmpOcaqCkgGQubS0JE3X4qZ2mkKebWZJalFiSapGTIWuXYW2tnqSulVxRn65QoWmUqKSomIeENmoJ6pDtCyAUlAaAA)
`f n` is the `n`th element of sequence #1, as either True or False.
The string built by `iterate` has the same "shape" as the real string:
```
ab"a"b"ab\"a\""b"ab\"a\"b\"ab\\\"a\\\"\""…
a,'a','a,''a''','a,''a'',''a,''''a'''''''…
```
`"\` both correspond to quotes, `ab` correspond to `a,`. So, we can use `char<'a'` to detect quotes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
0;x‘Ø1jƲŻ$$¡ḣ
```
A monadic Link that accepts `n` and yields the first `n` terms of the boolean is-a-quote sequence.
**[Try it online!](https://tio.run/##ASEA3v9qZWxsef//MDt44oCYw5gxasayxbskJMKh4bij////MTI "Jelly – Try It Online")** Or see a longer prefix (by not heading) [here](https://tio.run/##AR0A4v9qZWxsef//MDt44oCYw5gxasayxbskJMKh////NA "Jelly – Try It Online").
### How?
Starts with a zero (the initial `a`) and builds up the sequence exactly as described in the question, using zeros for non-quotes and ones for quotes.
```
0;x‘Ø1jƲŻ$$¡ḣ - Link: integer, n
0 - set the left argument, x, to zero
¡ - repeat n times:
$ - last two links as a monad - f(x):
$ - last two links as a monad - g(x):
Ʋ - last four links as a monad - h(x): e.g. [0,0,1,0,1]
‘ - increment [1,1,2,1,2]
x - repeat (double the quotes) [0,0,1,1,0,1,1]
Ø1 - [1,1]
j - join (wrap in quotes) [1,0,0,1,1,0,1,1,1]
Ż - prepend a zero (prepend a comma) [0,1,0,0,1,1,0,1,1,1]
; - concatenate that to x
ḣ - head to index n
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
;Ø.;x‘$;1
0Ç¡ḣ
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//O8OYLjt44oCYJDsxCjDDh8Kh4bij////MTU "Jelly – Try It Online")
Full program yielding first \$n\$ elements of the quote/non-quote sequence. Exponentially slow; better tested with [manual control of the number of iterations](https://tio.run/##ASQA2/9qZWxsef//O8OYLjt44oCYJDsxCjDDh8aTwqHhuKP//zf/NjE).
```
;Ø.;x‘$;1 Monadic helper link: iterate
;Ø. Append [0, 1].
; Append
x $ the argument with its elements repeated by
‘ themselves incremented.
;1 Append 1.
0Ç¡ḣ Main link
Ç¡ Repeat that n times
0 starting from 0,
ḣ and take the first n elements.
```
[Answer]
# Batch Script, 80 bytes
Outputs the first n elements of sequence 1,
```
CMD/VON/CSET s=0^&(FOR /L %%Q in (1,1,8)DO @SET s=!s!01!s:1=11!1)^&ECHO !s:~,%1!
```
so ie if file is called quote.bat
```
CALL quote.bat 5
```
gives you
```
00101
```
I hardcoded 8 iterations because that's the maximum amount before the string gets too big and CMD fails to parse it. So I'm not too sure if this answer counts, but I thought it would be neat to post it anyway.
Edit : minus a bunch of bytes thanks to Neil
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~52~~ 47 bytes
```
f=->n,r=?0{r[n]||f[n,r+"01#{r.gsub ?1,'11'}1"]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5Pp8jW3qC6KDovtqYmLRrI1VYyMFSuLtJLLy5NUrA31FE3NFSvNVSKrf1foKBhoKdnaGCgqZebWKChlqapZa/zHwA "Ruby – Try It Online")
Returns the nth element.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~109~~, ~~71~~, ~~64~~, ~~63~~, 62 bytes
```
a=w='0'
while[print(end=w)]:w=f"01{a.replace('1','11')}1";a+=w
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9G23FbdQJ2rPCMzJzW6oCgzr0QjNS/Ftlwz1qrcNk3JwLA6Ua8otSAnMTlVQ91QXUfd0FBds9ZQyTpR27b8/38A "Python 3 – Try It Online")
-45 thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)
-1 because of [this answer](https://codegolf.stackexchange.com/questions/250015/infinite-quote-escaping-sequence/250023#250023)
-1 thanks to [@AnttiP](https://codegolf.stackexchange.com/users/84290/anttip)
## Explanation (Outdated):
```
a=w="0"
```
Self-explanatory
```
while 1:
```
Repeat infinite times.
```
print(end=w+"0");
```
print w with 0. There's "0" because "0" is a comma.
```
w="1"+
```
w is "1" and...
```
a.replace("1","11")+
```
double the ones of a and...
```
"1";
```
one.
```
a="00"+w
```
Put two zeroes and w.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
Nθ≔0ηW›θLη≔⁺⁺η0⪫11⪫⪪η1¦11η…ηθ
```
[Try it online!](https://tio.run/##LY3LCsMgEEX3/Qpx5YCFuM6qZFFaSgn0C6xIRrBqfLT066022QwznDP3KpRReWlrvbhQ8r28njqyFcbDKSWzOEYHygm2@4PGasLOUcvcFU5u2i0ZGQIA2e3ZlrQN5KS9AidXb1qKEHRfH8Ga/Mei405awNYxR@Mym77K6gl96NYKMNYqhnp82x8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` elements of sequence 1. Explanation:
```
Nθ
```
Input `n`.
```
≔0η
```
Start with a string of `0` instead of `a`.
```
W›θLψ
```
Repeat until there are enough elements.
```
≔⁺⁺η0⪫11⪫⪪η1¦11η
```
Extend the string by appending its quotation, but use `0` instead of a comma and `1` instead of a quote.
```
…ηθ
```
Output the first `n` elements.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÎFDX3:5šbJÀ«I£
```
Outputs the first \$n\$ items of the binary sequence as string.
[Try it online.](https://tio.run/##yy9OTMpM/f//cJ@bS4SxlenRhUlehxsOrfY8tPj/f0MDAwA)
**Explanation:**
```
Î # Push 0 and the input
F # Pop and loop the input amount of times:
D # Duplicate the current string
X3: # Replace all 1 with 3
5š # Convert the string to a list of digits, and prepend a 5
b # Convert each digit to a binary string
# (3 become 11; 5 becomes 101; 0 and 1 remain unchanged)
J # Join it back together to a single string
À # Rotate it once towards the right, so the leading 1 is trailing
« # Append it to the previous string we've duplicated
I£ # Only leave the first input amount of characters
# (after the loop, the result is output implicitly)
```
[Answer]
# JavaScript (ES6), ~~50~~ 49 bytes
*Saved 1 byte thanks to @tsh*
Returns the \$n\$-th term of the binary sequence, 0-indexed, where `0`'s are encoded with `2`'s.
```
f=(n,s='2')=>s[n]||f(n,s+21+s.replace(/1/g,11)+1)
```
[Try it online!](https://tio.run/##FcxBCsMgEADAr3hzF@2mBno0kHeEUMSakGBX0VIo5O8mvc5hdvd11Zctf26cXqG1xQLramUv0Q514vk4lr@o3qhKJeTofIDOdKs2BpXB5hPXFAPFtMJERGMp7gePO870dhngqQWjsIO4HkTa08YgtZCI7QQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 61 bytes
```
for((a=0;${#a}<=$1;));do a+=01${a//1/11}1;done;echo ${a:$1:1}
```
[Try it online!](https://tio.run/##lVDBaoQwEL37FUOaQ0QWTemhu9m0hW2/YvWQxhFDiy6agiD5djtaLR56aWDe5D3ehMl7N309VV@N9a5toBIxjFPVdkIYnSk@3plw1lyqOFZlCybRmeSjSVOZShkkaQ0qtHULpJ64PMkwhahE@2k6hIMBHG5oPZZaZJCB3NWMcsW/tA03h9zd/jUT7/exNdoP7LRg@fB2nw/HC9UDg42@5sPjhcURRQBCgKMQwJ0ZBbH95PpSBKYgSdySSQR0vCaHC2whOJNfN3fFqveaiwoY9/T8MoS9J9oz0Jo6/rhunWv8YoPDE/Cegl13vvLnIuQNi@bQp28 "Bash – Try It Online")
Returns the \$0\$-based \$n^{\text{th}}\$ element of the binary sequence.
[Answer]
# [Haskell](https://www.haskell.org), 57 bytes
```
s>>=id
s=[0]:[0:1:[b|b<-a,c<-[0..b]]++[1]|a<-scanl1(++)s]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ2W0km6Ec0CAUuzu3MTMPAVbhYKizLwSBRWFksTsVAVDAwMgM2ZpaUmarsVNy2I7O9vMFK5i22iDWKtoAytDq-ikmiQb3USdZBvdaAM9vaTYWG3taMPYmkQb3eLkxLwcQw1tbc3iWIgBC6AUlAYA)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 27 bytes
```
{{∊⍵0 1(,⍨¨@(⍸⍵)⊢⍵)1}⍣⍵⊢,0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v7r6UUfXo96tBgqGGjqPelccWuGg8ah3B1BE81HXIhBlWPuodzGQAeTqGNT@f9Q39VHbBFK1Gf8HAA "APL (Dyalog Extended) – Try It Online")
] |
[Question]
[
Given a number `n` and an upper limit `l` list the numbers that can be created by multiplying two or more numbers consisting of **only sevens** of length `n` or less that are less than `l`. [A161145](http://oeis.org/A161145) is close to this challenge, however, you will NOT be including the 7, 77, 777, 7777, 77777, etc..
# Examples
**`n=anything, l<49` would result in:**
```
[]
```
**`n=1, l=49` would result in:**
```
7*7=49
f(1,49)=[49]
```
**`n=1, l=343` would result in:**
```
7*7 =49
7*7*7 =343
f(1,343)=[49,343]
```
**`n=2,l=6000` would result in:**
```
7*7 =49
7*7*7 =343
7*7*7*7=2401
7*77 =539
7*7*77 =3773
77*77 =5929
f(2,6000)=[49,343,539,2401,3773,5929]
```
**`n=3, l=604000` would result in:**
```
[49, 343, 539, 2401, 3773, 5439, 5929, 16807, 26411, 38073, 41503, 59829, 117649, 184877, 266511, 290521, 418803, 456533, 603729]
```
Etc...
# Rules
1. You **do not** have to output intermediate steps, this was done for clarity.
2. Output can be as an array or separated by any character (even newlines).
3. Output must be in numerical order, lowest to highest.
4. To make the title relevant, highest `n` that must be handled is `n=77` (if you can't handle that high, note why - language restrictions are acceptable, laziness is not). This limitation is to hinder those looking to build the entire superset in memory.
5. If TIO cannot run `n=77` for your code, explain what specs were required to achieve `n=77`.
6. For a product to be valid it must consist of at least 2 numbers.
7. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") lowest byte-count will be deemed victorious.
8. You may choose the list to contain items less than `l` or less than/equal to `l`.
9. **BONUS**: If your code is exactly 77 bytes, kudos from me; worthless, I know.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~20~~ ~~19~~ 18 bytes
```
R7ẋḌµ;ŒċP€⁹f€FµÐLḟ
```
Note that the output doesn't match the OP's. I've left a comment.
[Try it online!](https://tio.run/nexus/jelly#@x9k/nBX98MdPYe2Wh@ddKQ74FHTmkeNO9OAlNuhrYcn@DzcMf/////G/80MTAwMDAA "Jelly – TIO Nexus")
### How it works
```
R7ẋḌµ;ŒċP€⁹f€FµÐLḟ Main link. Left argument: n. Right argument: l
R Range; yield [1, ..., n].
7ẋ Times; yield [[7], ..., [7] * n].
Ḍ Undecimal; yield s := [7, 77, ...].
µ µÐL Begin a new chain with argument s and call the chain between
until the results no longer chain.
Return the last unique result.
Œċ Combinations; return all unordered pairs in integers in the
return value.
; Concatenate the return value and its pairs.
P€ Take the product of each individual integer and each pair in
the result.
⁹f€ Filter each; for each j in [1, ..., l], intersect [j] with the
array of products. The result is sorted and contains no
duplicates.
ḟ Filterfalse; remove the elements of s from the result.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~116~~ ~~113~~ 109 bytes
```
n,l=input()
r=t={1}
exec't|={10**n/9*7};n-=n>1;r=r|{x*y for x in r for y in t if l/x/y};'*l
print sorted(r-t)
```
Note that TIO doesn't have enough memory for the last test case.
[Try it online!](https://tio.run/nexus/python2#HcZLCoMwEADQfU4xO3VQErtoKWG8TBshEEaZTiFBc/b081av8Zgo8v7WfjBCSsdcTcjh0en5vUNke8db9TwRL7MXkvPIWGDdBDJEBvm3/KoQV0g221J9h8nsElnhtYmGZy@TDq1dRrg65z4 "Python 2 – TIO Nexus")
[Answer]
## JavaScript (ES6), ~~103~~ 101 bytes
Takes input in currying syntax `(n)(l)`.
```
n=>l=>(a=[],g=(n,m,p,i)=>(p>l||g(n,m,(a[i>1?p:a]=p)*m,-~i),--n?g(n,m+7,p,i):a.filter(n=>n)))(n,'7',1)
```
### Test cases
The last test case may take a few seconds to complete.
```
let f =
n=>l=>(a=[],g=(n,m,p,i)=>(p>l||g(n,m,(a[i>1?p:a]=p)*m,-~i),--n?g(n,m+7,p,i):a.filter(n=>n)))(n,'7',1)
console.log(f(1)(49))
console.log(f(1)(343))
console.log(f(2)(6000))
console.log(f(3)(604000))
```
[Answer]
# PHP, 142 Bytes
```
$r=[];for([,$n,$l]=$argv;$n--;)f($v[]=$z.=7);function f($t){global$v,$l,$r;while($c=$t*$v[+$i++])$l<$c?:f($c)&$r[$c]=$c;}sort($r);print_r($r);
```
-5 Bytes removing `$r=[];` and replace `sort($r);` with `@sort($r);`
[Online Version](http://sandbox.onlinephpfunctions.com/code/a65d4abd194ccf6032ce3764f4b027fe469d491e)
Expanded
A recursive function make all permutations including the limit
```
$r=[];
for([,$n,$l]=$argv;$n--;)
f($v[]=$z.=7);
function f($t){
global$v,$l,$r;
while($c=$t*$v[+$i++])
$l<$c?:f($c)&$r[$c]=$c;
}
sort($r);
print_r($r);
```
PHP, 145 Bytes
```
for([,$n,$l]=$argv;$n;)$t[]=str_pad(7,$n--,7);for(;$l>=$i+=49;$v>1?:$u[]=$r)for($v=$i,$r=!$c=0;$d=$t[$c];)$v%$d?$c++:($v/=$d)&$r*=$d;print_r($u);
```
Expanded
a loop till including the limit
check every value that is divisible by 49
```
for([,$n,$l]=$argv;$n;)
$t[]=str_pad(7,$n--,7);
for(;$l>=$v=$i+=49;$v>1?:$u[]=$r)
for($r=!$c=0;$d=$t[$c];)
$v%$d?$c++:($v/=$d)&$r*=$d;
print_r($u);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/4546b26d83b5fff5d384b0dc7a579e2fdbfd5757)
a few bytes more and an associative array can be created
key the number and as value an array of the used sevens
```
for([,$n,$l]=$argv;$n;)
$t[]=str_pad(7,$n--,7);
for(;$l>=$v=$i+=49;$v>1?:$u[array_product($r)]=$r)
for($r=[],$c=0;$d=$t[$c];)
$v%$d?$c++:($v/=$d)&$r[]=$d;
print_r($u);
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/ee6891be780577cbf373848c4b2dca782ff0ce7e)
[Answer]
# Ruby, ~~89~~ 86 bytes
A recursive solution.
-3 bytes by remembering that anything times 0 is 0.
```
f=->n,l,b=1{n*l>0?(f[n,l/k=eval(?7*n),b*k]+f[n-1,l,b]+(b>1&&l>=k ?[k*b]:[])).sort: []}
```
[Try it online!](https://tio.run/nexus/ruby#HY3BCgIhFADvfcU7ibquKUWBoH6ISKywG4vmLildom836zoMM23Ro8kssaDlO9NkhMWL6@AY9fyaErZXmgkLNPqh81H@VD/gYCRCyegI1kUavHKeEF62Z1Xg/Kf1Ami4z7Xwsqe18se0A1J1u62HHf4H305wEWchxBc "Ruby – TIO Nexus")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 22 bytes
```
JsM._*\7Eu@s*LR+JGJSQJ
JsM._*\7E
E second input
*\7 repeat "7" as many times as the above
._ all prefixes of above
sM convert each to integer
J store list as J
u@s*LR+JGJSQJ
u repeat the following until results not unique
J starting from G = J
at each iteration, G is the current value
+JG append G to J
J J
*LR multiply the elements of the above two, vectorizing each
s flatten list
@ SQ intersect with [1,2,3,...,first input]
this takes elements from [1,2,3,...,first input] and
check if each element is in the previous list
which ensures the result is sorted and unique
```
[Try it online!](http://pyth.herokuapp.com/?code=JsM._%2a%5C7Eu%40s%2aLR%2BJGJSQJ&input=6000%0A2&debug=0)
## Specs
* Input: `l[newline]n`
* Output: `array containing the sorted result`
[Answer]
# PHP, ~~128 125 130 129 127~~ 123 bytes
will work up to 22 `7`s but will round larger values (7\*\*23 is floating point on a 64 bit machine).
3 bytes saved by Jörg, 3 by me, ~~5 4~~ 1 added to avoid warning for empty results.
```
for([,$c,$z]=$argv,$n=$c+1;$c<$z;$p<$z&&$r[$p]=$p)for($b=$c+=$p=1;$b|0;$b/=$n)$p*=str_pad(7,$b%$n,7);@sort($r);print_r($r);
```
takes input from command line arguments; run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/f2b1f71dc5e9e1eb56c7478c639c126edcd1f3ef).
**breakdown**
```
for([,$c,$z]=$argv,$n=$c+1; # $z=L, $n=N+1
$c<$z; # loop $c from N to L-1:
$p<$z&&$r[$p]=$p # 2. if product is < L, add to array
) # (key=val to avoid duplicates)
for($b=$c+=$p=1;$b|0;$b/=$n) # 1. loop $b through ++$c as base-N+1 number
$p*=str_pad(7,$b%$n,7); # take each base-N+1 digit as length
# for a streak of 7s as factor
// (str_pad is 1 byte shorter than str_repeat and saves 3 by ensuring positive $p)
@sort($r); # sort array (muted to avoid warning for empty result)
print_r($r); # print array
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes
```
h>.ḋ{p~c×ᵐ{=h7&l}ᵐobt≤~t?∧!}
```
There's a lot of scope for improvement in the language itself, here; quite a few things I wrote look like they'd be obviously improvable with some changes to the language's design. This is the shortest way I've found with the current version. I may well make some suggestions for Brachylog which would make this program more efficient, shorter, and more readable.
Very, very slow; TIO times out even on the simplest possible nontrivial answer, so there's not much point in providing a TIO link. I've verified this program by running it locally.
This is a function (not a full program), whose output is a generator (as opposed to a list). Add `.w⊥` to the end of the function if you want to see all outputs, rather than just the first. (Note that this doesn't really matter in practice, because as the program is too slow for TIO anyway, you have to run it locally, and the local Brachylog interpreter runs in a REPL which can describe a generator just fine.)
## Explanation
```
h>.ḋ{p~c×ᵐ{=h7&l}ᵐobt≤~t?∧!}
. The desired output is
h> a number less than the first input
ḋ p such that taking its prime factors in some order,
~c partitioning them,
×ᵐ and taking the product of each partition
{ }ᵐ produces a number for which each digit
=h7 is composed only of 7s
&l and for which the lengths of those numbers
o are in sorted order
t and the last element
b (which is not also the first element)
≤ is less than or equal to
~t? the last input.
∧ (Delete an unwanted implicit constraint.)
ḋ{ !} Output each number only once.
```
[Answer]
# Bash + GNU utilities, 108
```
seq -f3o%gp $2|dc|sed -r "/0|1{$1}/d;s/./&7/g;s/1//g;s/2/*/g;/[*]/!d;s/^/a=7/;s/$/;if(a<=$2)a;/"|bc|sort -un
```
[Try it online](https://tio.run/nexus/bash#NY5BDoIwEEX3nmJsqlGSOi0QiVYS72E0qbQgG6oUV9az40DibN7Ln8zP1L6HwYWhMsFB2wFTkB/YhCzPiCnspZQkGUk@qQbrF0AT3ABCAP@fz6GrHn4uBMbP7DgG9wJRZ37VPIGn0VYxOAuiB4Yyqg9XX7Q64A7XBTYkCmekmBDxklxxOe1vaMoCSTjqtt6YU8nTrdHI4p0afU@fvLvR@s6NPw). TIO takes about a minute for the last testcase. My [results match](https://codegolf.stackexchange.com/questions/117637/seventy-seven-sevens#comment287866_117637) @Dennis's.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
L7×1¸ì©IF®âPD²‹Ïê®K
```
[Try it online!](https://tio.run/nexus/05ab1e#ATAAz///TDfDlzHCuMOswqlJN3ptw65Gwq7DolBEwrLigLnDj8Oqwq5L//83Nwo2MDQwMDA "05AB1E – TIO Nexus")
**Explanation**
Very inefficient. TIO link performs `ceil(l^(1/7))` iterations instead of the `l` iterations used in the golfed version to easier test large testcases.
```
L7× # create the list ['7', '77', '777' ...]
# with the final item having n 7's
1¸ì© # prepend a 1 and store a copy in register
IF # l times do:
®â # cartesian product between current list and the list in register
P # product of each sublist
D²‹Ï # keep only numbers smaller than l
ê # remove duplicates and sort
®K # remove 1, 7, 77, 777 ... from the list
```
[Answer]
# Pyth -- ~~57~~ ~~51~~ ~~49~~ 42 bytes
```
FY}2eQKYJv*\7hQWJIqYJBW!%KJ=/KJ)=/JT)Iq1KY
```
[Try it](http://pyth.herokuapp.com/?code=FY%7D2eQKYJv%2a%5C7hQWJIqYJBW%21%25KJ%3D%2FKJ%29%3D%2FJT%29Iq1KY&input=3%2C9999&debug=0)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~94~~ ~~91~~ 88 bytes
```
n=>l=>(X=[]).filter(g=(i,j=1,k)=>j>l|i[n]||(X[g(i+7,j,k)|g(i,j*i,-~k),k>1&&j]=j),l=g`7`)
```
[Try it online!](https://tio.run/##ZcpNCoMwEEDhfQ8iM20UbaRSyuQcggiK1ZAfkqLSVejV09pttt97enyP27Sq1547/5zjQtGRsCSgpa7HYlF2n1eQBIppqphBElrYoDrXhwBtJ0FdGqZ/IcjjOSuWfwwyI6os0z1pZJbk0AwYH6fJu83bubBewgIVQn1HTJXXPOErwq0sy8T54fW/xC8 "JavaScript (Node.js) – Try It Online")
```
n=>l=> // input
(X=[]).filter( // X stores index=results
g=(i,j=1,k)=> // recurse Reuse of g for filter:
j>l|i[n]|| // out of range 49>1|49[n] (true)
(X[g(i+7,j,k)|g(i,j*i,-~k),k>1&&j]=j)
// k<=1: X[false]=j, ignored
// k>1: X[j]=j
,l=g`7`) // First call [0/1]|[0/1]||1 ==1
```
] |
[Question]
[
Chameleon challenges are a [bad thing](http://meta.codegolf.stackexchange.com/a/8214/13486 "I actually got the idea for this challenge after reading this post on Meta"), apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.
## Challenge
Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.
*Like this:* 
The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .
## Objective
Given the colors of the surrounding pixels, output the color of the chameleon.
The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.
## Input
An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:
```
[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]
```
You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.
If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. `044200255044200255044200255044200255044200255044200255044200255044200255` is valid, so are `44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255` and `44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255`, but `4420025544200255442002554420025544200255442002554420025544200255` is not.)
## Output
An array / string / etc. containing the colors of the center pixel (in decimal), like this:
```
[<red>,<green>,<blue>]
```
In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. `044200255` is valid, so is `44 200 255`, but `44200255` is not.)
The numbers may not contain decimal points, so e.g. `44.0 200 255.0` is invalid.
### Rounding
Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is *1620*, you must output `203`, not `202` or `202.5`.
## Examples
**Pictures are for illustration only.** The middle pixel is the output, the surrounding pixels are the input.
### Input:
```
[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]
```
### Output:
```
[200,200,200]
```

---
### Input:
```
[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]
```
### Output:
```
[128,128,128]
```

---
### Input:
```
[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]
```
### Output:
```
[83,125,103]
```

---
### Input:
```
[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]
```
### Output:
```
[45,65,85]
```

Submissions can be a full program or a function. Standard [I/O](http://meta.codegolf.stackexchange.com/q/2447/13486) and [loophole](http://meta.codegolf.stackexchange.com/q/1061/13486) rules apply.
[Answer]
## Python, 38 bytes
```
lambda l:[sum(r)+4>>3for r in zip(*l)]
```
Rounds the average (towards the nearest integer, with halves rounding up) by adding 4 to the sum, then floor-dividing by 8 via the bit-shift `>>3`.
[Answer]
# MATL, ~~8~~ 4 bytes
```
YmYo
```
[Try it online!](http://matl.tryitonline.net/#code=WW1Zbw&input=W1swIDIwMCAyMDBdO1syMDAgMCAyMDBdO1syMDAgMjAwIDBdO1s2MCAyMDAgMF07WzIwMCAwIDIwMF07WzAgMjAwIDIyMF07WzIgMjAwIDBdO1swIDAgMF1d)
*4 bytes saved thanks to beaker!*
Explanation:
```
Ym "Get the average of each column
Yo "And round up
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
S+4:8
```
[Test suite](http://jelly.tryitonline.net/#code=Uys0OjgKw4figqw&input=&args=W1syMDAsMjAwLDIwMF0sWzIwMCwyMDAsMjAwXSxbMjAwLDIwMCwyMDBdLFsyMDAsMjAwLDIwMF0sWzIwMCwyMDAsMjAwXSxbMjAwLDIwMCwyMDBdLFsyMDAsMjAwLDIwMF0sWzIwMCwyMDAsMjAwXV0sW1swLDAsMF0sWzI1NSwyNTUsMjU1XSxbMCwwLDBdLFsyNTUsMjU1LDI1NV0sWzI1NSwyNTUsMjU1XSxbMCwwLDBdLFsyNTUsMjU1LDI1NV0sWzAsMCwwXV0sW1swLDIwMCwyMDBdLFsyMDAsMCwyMDBdLFsyMDAsMjAwLDBdLFs2MCwyMDAsMF0sWzIwMCwwLDIwMF0sWzAsMjAwLDIyMF0sWzIsMjAwLDBdLFswLDAsMF1d). (Slightly modified so as to verify all testcases at once.)
```
S+4:8
S sum (vectorized)
+4 add 4
:8 floor division by 8
```
[Answer]
# C, ~~151~~ ~~123~~ ~~103~~ 91
Requires 24 parameters passed to the program, in the order R G B R G B ... and outputs the triplet R G B without a newline.
```
i,t;main(c,v)char**v;{for(i=0;t=4,i++<3;printf("%d ",t/8))for(c=i;c<24;c+=3)t+=atoi(v[c]);}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
m.R.Od0C
```
[Test suite](http://pyth.herokuapp.com/?code=m.R.Od0C&test_suite=1&test_suite_input=%5B%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%2C%5B200%2C200%2C200%5D%5D%0A%5B%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%5D%0A%5B%5B0%2C200%2C200%5D%2C%5B200%2C0%2C200%5D%2C%5B200%2C200%2C0%5D%2C%5B60%2C200%2C0%5D%2C%5B200%2C0%2C200%5D%2C%5B0%2C200%2C220%5D%2C%5B2%2C200%2C0%5D%2C%5B0%2C0%2C0%5D%5D&debug=0).
```
m.R.Od0C input: Q
m.R.Od0CQ implicit arguments
Q input
C transpose
m d for each:
.O take average
.R 0 round off
```
[Answer]
## Pyke, 7 bytes
```
,FsOO8f
```
[Try it here!](http://pyke.catbus.co.uk/?code=%2CFsOO8f&input=%5B%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%2C%5B255%2C255%2C255%5D%2C%5B0%2C0%2C0%5D%5D)
[Answer]
# J, 11 bytes
```
0.5<.@++/%#
```
Takes the input as an 8x3 array where each row is an RGB value
## Explanation
```
0.5<.@++/%# Input: a
# Count the number of rows
+/ Sum along the columns
% Divide each sum by the count to get the averages
0.5 + Add 0.5 to each average
<.@ Floor each value and return
```
[Answer]
# JavaScript, ~~75~~ ~~64~~ 55 bytes
```
a=>a.reduce((p,c)=>p.map((e,i)=>e+c[i])).map(x=>x+4>>3)
```
A JavaScript answer to get you started.
**Edit:** Saved 11 bytes thanks to [Dendrobium](https://codegolf.stackexchange.com/users/20519/dendrobium), and another 9 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil).
[Answer]
# Lisp - 180 179 bytes
EDIT: Formatted for further golfing.
```
(defun a(l)(/(apply #'+ l)(length l)))(defun r(a)(if(integerp(* a 2))(ceiling a)(round a)))(defun c(s)(mapcar(lambda(i)(r(sqrt(a(mapcar(lambda(x)(expt(nth i x)2))s)))))'(0 1 2)))
```
Does it [the correct way](https://www.youtube.com/watch?v=LKnqECcg6Gw), I guess. Untested.
* `a` is just average
* `r` is this challenge's proper rounding, since Lisp `round` rounds to the nearest even integer
* `c` does the real work, taking in input in the format
`'((R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B))`, and returning a `'(R G B)` list containg the answer.
[Answer]
# [Nim](http://nim-lang.org), ~~134~~ ~~126~~ ~~115~~ ~~108~~ 78 bytes
```
import math,future
x=>lc[(lc[x[j][i]|(j<-0..7),int].sum+4)shr 3|(i<-0..2),int]
```
Defines an anonymous procedure, which requires the input passed in as a double-nested sequence and outputs as a 3-element array. The procedure can only be used as an argument to another procedure; to test, use the following wrapper:
```
import math,future
import strutils
proc test(x: seq[seq[int]] -> seq[int]) =
echo x(#[ Insert your input here ]#)
test(x=>lc[(lc[x[j][i]|(j<-0..7),int].sum+4)shr 3|(i<-0..2),int])
```
A Nim sequence is an array with `@` in front, like `@[1, 2, 3]`. An input to this procedure could therefore be:
```
@[@[0,0,0],@[255,255,255],@[0,0,0],@[255,255,255],@[255,255,255],@[0,0,0],@[255,255,255],@[0,0,0]]
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 65 bytes
```
: f 3. do 8. do 3 j - i * 2 + roll loop 4 8. do + loop 8 / loop ;
```
[Try it online!](https://tio.run/##tYzNCsMgEITveYo5NyQVraLN05QW@4Og2EAe366J1KSF3ors7Ozs@lkfx1t3tbmldISF6HHx0LMKPNDhjh04WkTvHJz3AYeyb5dRY7@YgQiBGNGP9LePeE6nfE1ulnPE0HDG8M8KDUN@XMp3fSe/t0uSSWvy56TW8eaEU5W5oqSC1FCyHAlRMeQZjK4QvWEYQyIR0gs "Forth (gforth) – Try It Online")
Takes input as stack arguments (r g b order)
### Explanation
For each of the 3 color channels:
* move all the numbers of that channel to the top of the stack
* add them together
* add 4 (to handle rounding)
* divide by 8
### Code Explanation
```
: f \ start new word definition
3. do \ start a counted loop from 0 to 2
8. do \ start a counted loop from 0 to 7
3 j - \ get the offset of the channel
i * 2 + \ get the absolute position of the channel value
roll \ move the value to the top of the stack
loop \ end the inner loop
4 \ add 4 to the top of the stack
8. do \ loop from 0 to 7
+ \ add the top two stack numbers
loop \ end loop. (Result on top of stack with be sum of values for channel + 4)
8 / \ divide by 8
loop \ end outer loop
; \ end word definition
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 41 bytes
```
>iRi+ i+ i+ i+ i+ i+ i+8,'rA' q$;
>iU
>iU
```
[Try it online!](https://tio.run/##KyrNy0z@/98uMyhTWwEDWeioFzmqKxSqWHPZZYaC8P//BgqmZgqmFgpmpgoGCkYGBgrGxmDKQMEMzDZQsLSAygBJCwUjIyAF5VpaAglTAA "Runic Enchantments – Try It Online")
Utilizes 3 instruction pointers to parse the input in the correct order (as the input values are always in the order `RGB, RGB,...`) and as long as each of the three IPs don't merge, and don't advance to the next read `i`nput command too early (hence all the spaces), it works out and saves bytes over having to continuously [rotate the stack](https://tio.run/##KyrNy0z@/z/G2i4zM7M6U5sSVMQVZKGjXuSooq6g8v@/gYKpmYKphYKZqYKBgpGBgYKxMZgyUDADsw0ULC2gMkDSQsHICEhBuZaWQMIUAA) to keep the correct value on top in order to calculate the sums.
*Technically* this code contains an error in correctly rounding `x.5` values for some inputs, but this is due to the [default rounding method used by C#](https://docs.microsoft.com/en-us/dotnet/api/system.math.round?view=netframework-4.7.2#System_Math_Round_System_Double_), which is to round to the nearest event number, rather than upwards and is due to issues in floating point accuracy loss, and I was unaware of this issue prior to writing this answer and checking the test cases. This will be [fixed in a future build](https://github.com/Draco18s/RunicEnchantments/blob/master/Assets/draco18s/runic/runes/RuneMathFunc.cs#L39), along with a few other things such as [this unhandled exception](https://tio.run/##KyrNy0z@/9/OVsX6/38DBVMzBVMLBTNTBQMFIwMDBWNjMGWgYAZmGyhYWkBlgKSFgpERkIJyLS2BhCkA).
In the meantime, [this modification](https://tio.run/##KyrNy0z@/98uMyhTWwEDHdqqbaGjXuSorlCoYs1llxkKwv//GyiYmimYWiiYmSoYKBgZGCgYG4MpAwUzMNtAwdICKgMkLRSMjIAUlGtpCSRMAQ) makes the necessary adjustment.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
mȯ÷8+4ΣT
```
[Try it online!](https://tio.run/##yygtzv7/P/fE@sPbLbRNzi0O@f//f3S0gY6pmY6pRaxOtJmpjoGOkYEBkGlsDGLogJhmBjpAHohlaQGXB9IWOkZGIKYRXKWlJVDeNDYWAA "Husk – Try It Online") Transposes the array and does the usual transformation.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~8~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
y_x÷8 r
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=eV949zggcg&input=W1swLDIwMCwyMDBdLFsyMDAsMCwyMDBdLFsyMDAsMjAwLDBdLFs2MCwyMDAsMF0sWzIwMCwwLDIwMF0sWzAsMjAwLDIyMF0sWzIsMjAwLDBdLFswLDAsMF1d)
```
y_x÷8 c :Implicit input of 2D array
y :Transpose
_ :Map
x : Reduce by addition
÷8 : Divide by 8
r : Round
```
] |
[Question]
[
This challenge is to find the longest chain of English words where the first 3
characters of the next word match the last 3 characters of the last word. You will use
an common dictionary available in Linux distributions which can be downloaded
here:
<https://www.dropbox.com/s/8tyzf94ps37tzp7/words?dl=0>
which has 99171 English words. If your local Linux `/usr/share/dict/words` is the same file (has md5sum == cbbcded3dc3b61ad50c4e36f79c37084), you can use that.
Words may only be used once in an answer.
**EDIT:** Letters must match exactly including upper/lower case, apostrophes, and accents.
An example of a valid answer is:
`idea deadpan panoramic micra craftsman mantra traffic fiche`
which would score 8.
The answer with the longest valid chain of words will be the winner. In the
event of a tie, the earliest answer will win. Your answer should list the chain
of words you have found and (of course) the program you wrote to do it.
[Answer]
## Java, heuristic favouring the vertex which induces the largest graph: 1825 1855 1873
The code below runs in under 10 minutes and finds the following path:
```
[wad, wadis, dis, dismay, may, mayfly, flywheels, elsewhere, erecting, ingratiate, ateliers, ersatzes, zest, esthetic, tickled, ledger, germicide, idealizes, zestful, fulling, ingrains, institute, uterine, ineptness, essaying, ingeniously, slyness, essences, cessations, onshore, ores, resoundingly, glycerine, inertness, essay, say, saying, ingenuous, ousted, tediously, sly, slyest, estrogen, genuflecting, ingestion, ionizer, zeros, roses, sesames, mes, meshed, hedonist, isthmuses, sesame, amending, ingredient, entrapment, enthuses, session, ionosphere, erectness, essayist, isthmus, mustaches, hesitatingly, glycogen, generation, ions, onset, settable, blew, lewder, deriding, ingratiates, testicles, lessen, sensitization, ionization, ionizing, ingratiating, ingenious, ouster, terrorizing, ingest, estranges, gesticulating, ingrates, testis, tissue, sue, suede, edelweiss, issuing, ingraining, ingrown, owner, nerdiest, estimation, ionospheres, rescue, cue, cueing, ingesting, ingot, got, gotten, tensor, sorrowing, ingratiated, tedious, ousting, ingratiatingly, glycerin, ringside, identifiable, bleariest, ester, terminological, calibrator, torrent, entraps, apse, pseudonym, nymphomania, niacin, cinema, emailed, led, ledges, gesticulates, testicle, clement, entail, ail, ailment, enter, terrains, inspires, restaurateur, euros, rosiest, estimates, tester, termite, iterator, torture, urethras, raspiest, estimator, tore, oregano, anointment, enthuse, useful, fulfil, filmstrip, riposte, stereotyped, pedicure, urea, readmits, itself, elf, elfin, finagles, lesbians, answerable, bleat, eatery, erythrocytes, testosterone, one, ones, nest, esteemed, medicine, inextricable, blessed, sediment, entry, try, tryout, outsources, cesarians, answered, redressed, seducer, cervical, calumniates, test, establishment, entombment, enthusiastic, tickles, lessens, ensemble, blemishes, hesitant, antic, tick, ickiest, estimable, blemished, hedgehog, hogan, gantlet, letdown, own, ownership, hippest, estates, testates, testiest, establishes, hes, hesitates, testable, bleakest, esthetes, testament, entice, iceberg, erg, ergonomic, microscope, operatives, vestibules, lesser, serenade, adenoidal, dales, lest, estrangement, entrap, raptures, resourceful, fulsome, omen, menswear, earthliest, established, hedges, gestates, testy, styes, yeshivot, voter, terrible, blender, derides, descent, enticed, cedillas, lass, assailable, bleacher, hermit, mite, item, temperas, rash, ashtray, rayon, yonder, dermis, mismanage, agendas, dash, ashy, shy, shyster, terrapins, insatiable, bleeder, derives, vestment, entangle, glen, lengthens, ensconced, ceded, deduced, cedars, arsenic, nice, ice, iced, cedar, daredevil, villa, llamas, masseuse, use, useable, bleach, achievable, bleached, hedonistic, tic, ticker, kerchieves, vessel, sell, ell, elliptic, ticket, kettles, lessee, seeps, epsilon, longboat, oath, atherosclerosis, sisterhood, oodles, lesson, sonatas, tassel, selvage, age, agent, entranced, cedes, descender, deranges, gestures, restraint, interment, enthused, seduced, cedilla, llama, amalgam, gamut, mutable, blend, endear, earthy, thymus, mussel, seltzer, zero, erodes, despot, potful, fulfillment, enthrall, allot, lotus, tussle, sledgehammered, redolent, entrapped, pedestal, talk, alkalis, listen, tended, deductible, bleeped, pedigree, reentered, redistribute, uterus, rustproofed, fed, fedora, oranges, gesundheit, either, herdsman, manes, nestles, lessor, sorrowful, fullback, acknowledges, gestured, redoubtable, blended, deduces, cesareans, answer, werewolves, vesper, perseveres, restructures, reside, ideogram, rammed, meddlesome, omens, ensign, ignores, restrains, insolent, entanglement, entrenchment, enticement, entomological, calligraphy, physical, calico, iconoclast, astringent, entertainment, entrant, antennas, nasty, stymie, miens, enslave, averred, redefine, inexorable, blenched, hedgerow, rowboat, oat, oaten, tend, endears, arson, songwriter, terminable, blent, entreaty, atypical, calypso, psoriasis, sister, term, ermine, ineligible, bleaker, kerosene, enema, emancipator, tormentor, torrider, derailment, entertains, instil, tildes, destine, inelegant, anthropomorphic, hiccup, cupolas, lastingly, glycerol, rollback, acknowledgment, entombed, bedridden, denser, servicewomen, menopause, used, sedatives, vesicle, clearinghouse, user, servant, antipodes, descry, crystalline, inexpedient, enthusiast, astonishment, entirety, etymological, calendared, redbreast, astronomer, merinos, nosedove, overpay, pay, paymaster, termagant, antiaircraft, aftercare, ares, resentful, fulcrum, rumpus, pushcart, artiste, stethoscopes, pesetas, taste, steadfast, astride, ides, destitute, utensil, silvan, vanguard, ardent, entryway, waysides, despair, airdrop, ropes, pestered, redder, derangement, entered, redeemed, medullas, lasagnas, nasal, salsas, sashay, hay, haymow, mow, mowed, wedder, derringer, germane, anemic, microfilmed, media, diatom, tomboys, oyster, terminator, toreador, dorsal, salespeople, pleased, sedater, terabit, bitten, tentacle, clergyman, manifesto, stomach, achoo, hoopla, plaza, azalea, leaven, vendor, dormant, antiparticle, cleared, redraft, afterword, ordains, insufficient, entitlement, entomb, ombudsmen, men, mental, tallyhos, hospice, icecap, cape, aperitif, tiffed, fedoras, rasped, pediatric, rickshaw, hawker, keratin, tinctures, reset, setback, acknowledgement, enthronement, entwine, inexact, actor, torpedos, dosed, sedan, dancer, cerebrum, rumple, plea, leach, ache, cheaper, per, periscopes, pestilent, entreat, eater, terser, serape, ape, apes, pesky, skycap, capped, pederast, astuter, terrace, acetaminophen, henchmen, menopausal, saltcellar, lard, ardor, dormice, icebound, underbrush, ushered, redrew, rewound, underclass, assassin, sinew, newscast, astrologer, gerund, undertaken, ken, kens, ensnared, redcap, cappuccinos, nostrum, rum, rumored, redraw, rawhide, identical, calcine, inertia, tiara, arabesque, queerer, reruns, unsold, oldie, diesel, selectmen, mentored, redden, dental, talon, longhand, and, androgen, genome, omelet, lethal, hallucinogenic, nickname, amen, menhaden, denudes, despaired, redevelop, lope, operas, rasp, aspired, redskin, kindergartens, ensnares, resultant, anthropological, callus, lustful, fulcra, crammed, mediocre, crepes, pesticide, ideas, eastbound, under, derrières, respired, rediscovered, redundant, antihero, erode, ode, odes, described, bedevil, villager, gerrymander, deride, ideograph, aphid, hid, hides, describes, besides, despoil, oilskin, kingdom, dominant, ant, antipasti, stiffens, ensured, redeemer, merchant, antiwar, warped, pederasty, stylus, lush, usher, her, hereafter, terrapin, pinnacle, clerical, caliber, bereave, avenger, geriatric, rickshas, haste, stereoscopes, pester, termini, initiator, tortures, restorer, reran, ransomed, medulla, llanos, nostril, rill, illogical, calif, lifer, fervor, vortex, textures, resister, termed, medieval, valor, lord, ordered, rediscover, verbatim, times, mesdames, mescal, caliper, periscope, opera, erasures, restart, artichokes, kestrel, reliant, antebellum, lumbago, agog, goggle, gleeful, fulfill, illustrator, tor, torque, questionnaires, resumed, mediator, tort, orthodoxy, oxymora, oratorio, riot, iotas, taster, terrific, fiche, checkpoint, interloper, perfumes, mesas, sassafras, rasher, heraldry, drywall, all, allergens, ensnare, area, rearm, armchair, airman, manufactures, resurface, acerbic, bicycle, cleverer, rerun, runt, untidy, idyllic, lichens, ensures, resend, endemic, microchip, hippopotamus, muscatel, telecast, astronaut, autopilot, lot, loth, other, heros, rosin, single, gleamed, mediaeval, valet, lettered, redound, underside, ideological, calliper, perihelia, liaison, sonic, nicknames, messenger, germicides, descendant, antigen, genital, tall, allergen, gentleman, mangos, gossipped, pedicures, resistant, antlered, redeveloped, pedagogical, calligrapher, heroins, inside, idea, deafen, fen, fencer, cerebra, bravuras, rascal, calculus, lusher, herbivores, resins, instill, illicit, citric, ricochet, heterodoxy, oxygen, generic, rice, icebox, box, boxcar, cartography, physique, quell, ellipsis, sis, sisal, sallow, lowbrow, rowel, well, elliptical, calf, alfresco, scow, cow, cowboy, boy, boyfriend, end, endeared, red, redesign, ignoramus, musket, kettledrum, rump, umped, pedlar, larvas, vassal, salmonellas, last, astronomical, calfskin, kingfisher, hereupon, ponchos, hospital, talisman, mantel, telethon, honcho, chomped, pedant, antitoxins, instant, antipastos, tossup, superintend, endangered, redskins, instigator, torpor, portico, icon, conquistador, dormer, merganser, seraphic, hiccuped, pedagogue, guerrillas, laser, sera, eraser, seraph, aphasic, sickbed, bed, bedsores, resign, ignorant, anthropocentric, richer, herdsmen, menu, enures, resuscitator, tornado, ado, adobe, obeisant, anthill, illegal, gallon, longshoremen, menace, ace, acetylene, enemas, mas, mascot, cot, cotton, tonsures, restores, result, ultraviolet, letterbox, boxer, xerography, physiological, calmer, merchantmen, mentor, torus, russet, settee, teenager, gerbil, billfold, old, olden, denatures, resubmit, mitten, ten, tenon, nonchalant, antique, queasy, asymmetric, ricksha, shanghai, haircut, cutups, upsides, descriptor, torpid, pidgin, gins, instep, tepee, peeper, perturb, urbane, anemia, miasmas, mascaras, raspy, spy, spyglass, assures, resonator, tortilla, llano, anon, nontechnical, calabash, ashram, rampart, arthropod, podia, diagram, ramp, amp, amphitheatres, resistor, tortillas, lasagna, gnat, natal, talc, alcoholic, licensee, seemed, medical, calm, almanac, nacho, choreography, phylum, lumbar, barman, mannequins, insures, respires, resound, underarm, armatures, resides, desideratum, tumult, ultrasound, underdog, dogcatcher, herald, alderwoman, mandarins, insecticides, desires, respirator, torrid, rid, rides, descant, anticlimax, maximum, mum, mummer, meringue, guesser, sermon, monogram, ramrod, rodeo, deodorant, antelopes, peso, esophagus, gusset, setups, upshot, hotel, telescope, open, penicillin, lingos, gossip, sip, siphon, honor, normal, maltreat, eaten, tenet, nether, herpes, pesticides, descend, endow, downfall, alleyway, way, waylay, layman, manicures, reshuffle, flea, lea, leash, ashen, henchman, mandolin, linchpins, inscribes, bestow, townspeople, plectrum, rumbas, baste, sternum, numb, umbilici, icicle, cleaver, vertebra, brains, insouciant, antidepressant, anthem, hemoglobin, binocular, largos, gossamer, mermaid, aid, aides, desperado, adopt, opt, optima, imam, mambos, bosun, sun, sunspot, potpourris, risky, sky, skyscraper, perturbed, bedraggle, glee, lee, leech, echo, choreographer, heraldic, dictum, tumid, midday, day, daybed, bedsides, desktop, topknot, notepaper, periodical, calendar, dare, areas, easel, selfsame, amebas, basins, ins, insulin, linnet, nettlesome, omegas, gasp, aspartame, amend, endures, researcher, herbal, balsas, sass, assault, ultimatum, tumor, mortgagor, gores, resort, orthopaedic, dictatorship, hipper, person, sonar, narc, arc, archduke, ukelele, elegant, anther, hereabout, outfox, fox, foxtrot, rotogravures, restaurant, antechamber, beret, retriever, verbena, enamor, morsel, sellout, outmaneuver, vertical, call, allergenic, niche, chessman, mandolins, insipid, pidgins, install, allures, rescind, indignant, antithetical, calicos, cosmonaut, auto, utopia, piano, another, heretical, calk, alkali, alibi, ibis, bistro, troupe, upend, endorser, serviceman, mandarin, rind, inductee, teepee, pee, peekaboo, bootstrap, rape, apertures, resin, singular, larval, valiant, antiperspirant, antipasto, stop, topical, calisthenic, nicer, cervix, vixen, xenophobic, bicep, cephalic, licit, citizenship, hippopotami, amigos, gospel, pellet, letups, upstart, artificer, cerebellum, lumberman, manic, nicknamed, medic, dickie, kielbasas, sash, ash, ashcan, cannon, nonskid, kid, kidnaper, perjures, resolver, vernacular, larkspur, puree, reefer, ferret, retains, insofar, far, fart, artisan, sandbag, bagel, gelatin, tinsel, selectman, manacle, clever, versus, sustains, inscribed, bedpan, pandemic, microprocessor, sorbet, bet, betcha, char, harem, remodel, deli, elicit, citadel, deliver, verandas, dashikis, kisser, servicemen, menthol, holiday, daydreamer, merchantman, manikins, insane, anew, newsprint, interwove, overreach, achieve, even, venom, nomad, mad, madrigal, gala, alarm, armpit, pitchman, manor, northbound, underbid, bidet, detox, toxemia, miasma, smarten, tenderloins, insult, ultra, travel, velvet, veteran, random, domino, inopportune, uneconomic, microbes, bestir, tiro, ironware, arena, enamel, melodramas, mastodon, don, donut, nut, nutmeg, meg, megalopolis, lissom, sombre, breathe, therefrom, romper, performer, merman, mangrove, overshadow, downcast, astir, tiros, rostra, trachea, heaven, ventricle, clergywoman, maneuver, verbal, ballad, ladyship, hippie, pie, piebald, alderman, manatee, teethe, thereupon, poncho, choicer, ceramic, microscopic, picayune, uneaten, tendon, donor, northeast, astound, underpass, assessor, sorghum, hum, human, mantra, trainee, needlepoint, interplay, laywoman, mannikin, kinsman, mantillas, lassie, sieve, ever, verdigris, risen, sensor, sorrel, relabel, belabor, borsch, schlep, leprechauns, unsnap, nap, napkin, kin, kingpin, pinkeye, eyeglass, assemblyman, manikin, kingship, hip, hippos, postpartum, tumbrel, relic, lichee, heehaw, haw, hawser, servicewoman, many, anyhow, howsoever, vertex, text, extra, trap, rap, rapper, periwig, wigwag, wag, wagon, gonorrhea, heave, aver, vermin, minesweeper, perplex, lexicon, congas, gastronomic, microfiche, cheapen, pentathlon, longhair, air, aircraft, aft, aftertaste, stem, tempos, postwar, war, wart, article, clear, earshot, hotshot, hotbed, bedlam, lam, lambkin, kindergarten, tenser, serum, rumor, mortar, tarmac, macabre, breech, echos, hostel, telescopic, pickerel, relay, laypeople, pleas, east, astronomic, micra, crackpot, pot, potato, atom, tombed, bedbug, bugaboo, bootleg, leg, legato, atop, topple, plethora, orangutang, angora, orangutan, tan, tandem, democrat, rat, rattan, tang, angry, gryphon, honeybee, bee, beeswax, waxen, xenon, nonplus, lustre, trellis, lisle, sleepwear, earwig, wig, wigwam, wampum, pummel, melanomas, massacre, cretin, tin, tint, interviewee, wee, weeper, persimmon, monsignori, origin, gingham, ham, hamper, pericardia, diarrhea, heartthrob, rob, robes, besom, sombreros, rosebud, bud, budgerigar, garret, retrodden, denim, nimbus, bus, bushel, helmet, metaphor, horsefly, flypaper, peritonea, near, ear, earlobes, bestowal, wall, allay, layout, outlast, astrakhan, handicapper, perusal, saltpetre, tremor, moribund, undercut, cut, cutoff, off, offal, falcon, con, consul, sultan, tannin, ninepin, pinball, allegro, grommet, metro, trot, rot, rotten, tenpin, pineapple, plectra, transit, sitar, tar, taro, arousal, salmon, moneybag, bagpipe, ipecac, cache, checkout, outrun, runaround, undersea, sea, sear, earache, cherub, rub, rubicund, underpin, pin, pint, intagli, glib, lib, libel, bellyache, cherubim, bimbos, bosuns, unsound, undertow, tow, towel, wellington, ton, tonsil, silicon, concoct, octet, tetrahedra, drachmae, maestri, tripos, possum, sum, sumac, macro, crocus, custom, tom, tomcat, catsup, sup, superstar, tarpaulin, linchpin, pinpoint, intercom, comet, met, metacarpus, pussycat, catastrophe, phenomenon, nonverbal, ballpoint, interurban, bani, animal, malt, altar, tartar, tarot, rotund, undergrad, radio, diocesan, sandbar, bar, barren, renewal, walkout, outstrip, ripen, pen, pencil, cilantro, trout, outran, rancor, corncob, cob, cobra, bra, brag, rag, ragas, gas, gasohol, holdout, output, put, putsch, schwas, was, waste, stereo, reoccur, cur, curb, urban, ban, bantam, tam, tamp, ampul, pullout, outwit, wit, withal, halo, alohas, hasp, asparagus, gusto, stove, overlap, lapel, pelvis, visit, sit, sitcom, compendia, diadem, demigod, god, goddam, dam, dampen, pennon, non, noncom, compel, pelican, cancan, can, cancel, celesta, starlit, lit, litmus, muscat, cat, catnap, naphtha, than, handcar, carpel, pellagra, grammar, mar, mariachi, chichi, chi, chimp, imp, impel, pelvic, vicar, car, caribou, bourgeoisie, siesta, stab, tab, tabu, abut, but, butterfat, fat, fathom, homespun, pun, puns, unsheathe, the, theorem, remove, overtax, tax, taxicab, cab, cabal, balsam, sambas, basal, salamis, missal, salt, altho, tho, thou, housebound, underground, underclassman, man, mannikins, insectivores, resonant, antelope, operator, torn, ornamental, tallow, low, lowered, reddens, enshrine, inefficient, entertainer, nerves, vestiges, gesturing, ingested, tediousness, essentials]
```
### Core ideas
In [Approximating longest directed paths and cycles](http://repository.upenn.edu/cgi/viewcontent.cgi?article=1202&context=cis_papers), Bjorklund, Husfeldt, and Khanna, *Lecture Notes in Computer Science* (2004), 222-233, the authors propose that in sparse expander graphs a long path can be found by a greedy search which selects at each step the neighbour of the current tail of the path which spans the largest subgraph in G', where G' is the original graph with the vertices in the current path deleted. I'm not sure of a good way to test whether a graph is an expander graph, but we're certainly dealing with a sparse graph, and since its core is about 20000 vertices and it has a diameter of only 15 it must have good expansion properties. So I adopt this greedy heuristic.
Given a graph \$G\left(V, E\right)\$, we can find how many vertices are reachable from each vertex using [Floyd-Warshall](http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm) in \$\theta\left(V^3\right)\$ time, or using [Johnson's algorithm](http://en.wikipedia.org/wiki/Johnson%27s_algorithm) in \$\theta\left(V^2 lg V + VE\right)\$ time. However, I know that we're dealing with a graph which has a very large strongly connected component (SCC), so I take a different approach. If we identify SCCs using [Tarjan's algorithm](http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm) then we also get a topological sort for the compressed graph \$G\_c(V\_c, E\_c)\$, which will be much smaller, in \$O\left(E\right)\$ time. Since \$G\_c\$ is a DAG, we can compute reachability in \$G\_c\$ in \$O\left(V\_c^2 + E\_c\right)\$ time. (I have subsequently discovered that this is hinted at in exercise 26-2.8 of [CLR](http://mitpress.mit.edu/books/introduction-algorithms)).
Since the dominant factor in the running time is \$E\$, I optimise it by inserting dummy nodes for the prefixes/suffixes. So rather than 151 \* 64 = 9664 edges from words ending *-res* to words starting *res-* I have 151 edges from words ending *-res* to *#res#* and 64 edges from *#res#* to words starting *res-*.
And finally, since each search takes about 4 minutes on my old PC, I try to combine the results with previous long paths. This is much faster, and turned up my current best solution.
### Code
`org/cheddarmonk/math/graph/Graph.java`:
```
package org.cheddarmonk.math.graph;
import java.util.Set;
public interface Graph<V> {
public Set<V> getAdjacent(V node);
public double getWeight(V from, V to);
}
```
`org/cheddarmonk/math/graph/MutableGraph.java`:
```
package org.cheddarmonk.math.graph;
import java.util.*;
public class MutableGraph<V> implements Graph<V> {
private Map<V, Map<V, Double>> edgesBySource = new HashMap<V, Map<V, Double>>();
public void addEdge(V from, V to, double weight) {
if (!edgesBySource.containsKey(to)) edgesBySource.put(to, new HashMap<V, Double>());
Map<V, Double> e = edgesBySource.get(from);
if (e == null) edgesBySource.put(from, e = new HashMap<V, Double>());
if (e.containsKey(to)) throw new IllegalArgumentException("There is already an edge between the vertices");
e.put(to, weight);
}
@Override
public Set<V> getAdjacent(V node) {
Map<V, Double> e = edgesBySource.get(node);
if (e == null) throw new IllegalArgumentException("node doesn't appear to be in the graph");
return Collections.unmodifiableSet(e.keySet());
}
@Override
public double getWeight(V from, V to) {
Map<V, Double> e = edgesBySource.get(from);
if (e == null) throw new IllegalArgumentException("from doesn't appear to be in the graph");
if (!edgesBySource.containsKey(to)) throw new IllegalArgumentException("to doesn't appear to be in the graph");
Double c = e.get(to);
return c == null ? 0 : c.doubleValue();
}
}
```
`org/cheddarmonk/math/graph/StronglyConnectedComponents.java`:
```
package org.cheddarmonk.math.graph;
import java.util.*;
/**
* A helper class for finding the strongly connected components of a graph using Tarjan's algorithm.
* http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
*/
public class StronglyConnectedComponents<V> {
private final Graph<V> g;
private List<Set<V>> topologicallySortedSccs = new ArrayList<Set<V>>();
private final LinkedList<V> S = new LinkedList<V>();
private final Set<V> S2 = new HashSet<V>();
private final Map<V, Integer> index = new HashMap<V, Integer>();
private final Map<V, Integer> lowlink = new HashMap<V, Integer>();
private StronglyConnectedComponents(Graph<V> g) {
this.g = g;
}
private void strongConnect(V v) {
int idx = index.size();
index.put(v, idx);
lowlink.put(v, idx);
S.push(v);
S2.add(v);
for (V w : g.getAdjacent(v)) {
if (!index.containsKey(w)) {
strongConnect(w);
if (lowlink.get(w) < lowlink.get(v)) {
lowlink.put(v, lowlink.get(w));
}
}
else if (S2.contains(w)) {
if (index.get(w) < lowlink.get(v)) {
lowlink.put(v, index.get(w));
}
}
}
if (lowlink.get(v).equals(index.get(v))) {
Set<V> scc = new HashSet<V>();
V w;
do {
w = S.pop();
S2.remove(w);
scc.add(w);
} while (!w.equals(v));
topologicallySortedSccs.add(scc);
}
}
public static <V> List<Set<V>> analyse(Graph<V> g, Set<V> sources) {
if (g == null) throw new IllegalArgumentException("g");
StronglyConnectedComponents<V> scc = new StronglyConnectedComponents<V>(g);
for (V v : sources) {
if (!scc.index.containsKey(v)) {
scc.strongConnect(v);
}
}
return scc.topologicallySortedSccs;
}
}
```
`org/cheddarmonk/ppcg/PPCG.java`:
```
package org.cheddarmonk.ppcg;
import java.io.*;
import java.util.*;
import org.cheddarmonk.math.graph.*;
public class PPCG44922 {
private static final String path = "/usr/share/dict/words";
private static Set<String> allWords;
private static Graph<String> fullGraph;
public static void main(String[] args) {
loadGraph();
Random rnd = new Random();
rnd.setSeed(8104951619088972997L);
List<String> a = search(rnd);
rnd.setSeed(-265860022884114241L);
List<String> b = search(rnd);
List<String> chain = spliceChains(a, b);
System.out.println(chain.size());
System.out.println(chain);
}
private static List<String> search(Random rnd) {
List<String> chain = new ArrayList<String>();
chain.add(selectOptimalReachabilityCount(fullGraph, allWords, rnd));
while (true) {
String tail = chain.get(chain.size() - 1);
FilteredGraph g = new FilteredGraph(chain);
// We know that tail only has one successor, so skip ahead.
Set<String> candidates = new HashSet<String>(fullGraph.getAdjacent(suffix(tail)));
candidates.removeAll(chain);
if (candidates.isEmpty()) break;
chain.add(selectOptimalReachabilityCount(g, candidates, rnd));
}
Iterator<String> it = chain.iterator();
while (it.hasNext()) {
if (it.next().charAt(0) == '#') it.remove();
}
return chain;
}
private static List<String> spliceChains(List<String> a, List<String> b) {
Set<String> intersect = new HashSet<String>(b);
intersect.retainAll(a);
if (intersect.isEmpty()) return null;
// Splice the longest bits. To avoid cycles, we look for intersection points which have the same set of reached intersection points.
// Thus to get from one to the next we can take either route without violating the unique occurrence of each element in the spliced chain.
Set<String> left = new HashSet<String>();
Set<String> right = new HashSet<String>();
List<String> newChain = new ArrayList<String>();
// NB We assume that either a(0) and b(0) are the same or neither is in intersect.
// This is a safe assumption in practice because they're both "wad".
int idxA = 0, idxB = 0, nextA = 0, nextB = 0;
while (idxA < a.size()) {
nextA++;
while (nextA < a.size() && !intersect.contains(a.get(nextA))) nextA++;
String tailA = nextA < a.size() ? a.get(nextA) : "";
left.add(tailA);
nextB++;
while (nextB < b.size() && !intersect.contains(b.get(nextB))) nextB++;
String tailB = nextB < b.size() ? b.get(nextB) : "";
right.add(tailB);
if (left.equals(right) && tailA.equals(tailB)) {
// We take the longer of idxA to nextA-1 or idxB to nextB - 1.
if (nextA - idxA > nextB - idxB) newChain.addAll(a.subList(idxA, nextA));
else newChain.addAll(b.subList(idxB, nextB));
idxA = nextA;
idxB = nextB;
}
}
if (new HashSet<String>(newChain).size() == newChain.size()) return newChain;
throw new IllegalStateException();
}
private static void loadGraph() {
Set<String> words = new HashSet<String>();
Set<String> prefixes = new HashSet<String>();
Set<String> suffixes = new HashSet<String>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
if (line.length() >= 3) {
words.add(line);
prefixes.add(prefix(line));
suffixes.add(suffix(line));
}
}
br.close();
}
catch (IOException ioe) {
throw new RuntimeException(ioe);
}
// Filter down to a core with decent reachability.
prefixes.retainAll(suffixes);
MutableGraph<String> g = new MutableGraph<String>();
Iterator<String> it = words.iterator();
while (it.hasNext()) {
String line = it.next();
if (prefixes.contains(prefix(line)) && prefixes.contains(suffix(line))) {
// In the interests of keeping the number of edges down, I insert fake vertices.
g.addEdge(prefix(line), line, 1);
g.addEdge(line, suffix(line), 1);
}
else it.remove();
}
fullGraph = g;
allWords = Collections.unmodifiableSet(words);
}
private static String prefix(String word) {
return "#" + word.substring(0, 3) + "#";
}
private static String suffix(String word) {
return "#" + word.substring(word.length() - 3, word.length()) + "#";
}
private static <V> Map<V, Integer> reachabilityCount(Graph<V> g, Set<V> sources) {
List<Set<V>> sccs = StronglyConnectedComponents.analyse(g, sources);
int n = sccs.size();
// Within a strongly connected component, each vertex can reach each other vertex.
// Then we need to also take into account the other SCCs which they can reach.
// We can exploit the fact that we already have a topological sort of the DAG of SCCs to do this efficiently.
Map<V, Integer> index = new HashMap<V, Integer>();
for (int i = 0; i < n; i++) {
for (V v : sccs.get(i)) index.put(v, i);
}
BitSet[] reachableSccs = new BitSet[n];
Map<V, Integer> reachabilityCounts = new HashMap<V, Integer>();
for (int i = 0; i < n; i++) {
Set<V> scc = sccs.get(i);
reachableSccs[i] = new BitSet(n);
reachableSccs[i].set(i);
for (V v : scc) {
for (V w : g.getAdjacent(v)) {
int j = index.get(w);
if (j < i) reachableSccs[i].or(reachableSccs[j]);
}
}
int count = 0;
for (int j = reachableSccs[i].nextSetBit(0); j >= 0; j = reachableSccs[i].nextSetBit(j+1)) {
count += sccs.get(j).size();
}
for (V v : scc) {
reachabilityCounts.put(v, count);
}
}
return reachabilityCounts;
}
private static <V extends Comparable<? super V>> V selectOptimalReachabilityCount(Graph<V> g, Set<V> candidates, Random rnd) {
Map<V, Integer> r = reachabilityCount(g, candidates);
int max = 0;
List<V> attaining = new ArrayList<V>();
for (V candidate : candidates) {
int score = r.get(candidate);
if (score > max) {
max = score;
attaining.clear();
}
if (score == max) attaining.add(candidate);
}
return selectRandom(attaining, rnd);
}
private static <T extends Comparable<? super T>> T selectRandom(Collection<T> elts, Random rnd) {
List<T> deterministic = new ArrayList<T>(elts);
Collections.sort(deterministic);
Collections.shuffle(deterministic, rnd);
return deterministic.get(0);
}
private static class FilteredGraph implements Graph<String> {
private final Set<String> filteredVertices;
public FilteredGraph(Collection<String> filteredVertices) {
this.filteredVertices = new HashSet<String>(filteredVertices);
}
@Override
public Set<String> getAdjacent(String node) {
if (filteredVertices.contains(node)) return Collections.emptySet();
Set<String> adj = new HashSet<String>(fullGraph.getAdjacent(node));
adj.removeAll(filteredVertices);
return adj;
}
@Override
public double getWeight(String from, String to) {
throw new RuntimeException("Not used");
}
}
}
```
[Answer]
# Ruby, 1701
`"Del" -> "ersatz's"` ([full sequence](https://gist.github.com/britishtea/d716333e81195310e1ea#file-result-txt))
Trying to find the optimal solution proved too costly in time. So why not pick random samples, cache what we can and hope for the best?
First a `Hash` is built that maps prefixes to full worlds starting with that prefix (e.g. `"the" => ["the", "them", "their", ...]`). Then for every word in the list the method `sequence` is called. It gets the words that could possibly follow from the `Hash`, takes a sample of `100` and calls itself recursively. The longest is taken and proudly displayed. The seed for the RNG (`Random::DEFAULT`) and the length of the sequence are also displayed.
I had to run the program a few times to get a good result. This particular result was generated with seed `328678850348335483228838046308296635426328678850348335483228838046308296635426`.
## Script
```
require "json"
def prefix(word); word[0, 3]; end
def suffix(word); word[-3, 3]; end
def sequence(word, prefixes, skip)
if SUBS.key?(word) && (SUBS[word] - skip) == SUBS[word]
return SUBS[word]
end
skip += [word]
suffix = suffix(word)
possibilities = (prefixes[suffix] ||= []) - skip
if possibilities.empty?
return [word]
else
sequences = possibilities.sample(100).map do |possibility|
sequence(possibility, prefixes, skip)
end
return SUBS[word] = [word] + sequences.max_by(&:size)
end
end
def correct?(sequence)
once_only = sequence.all? { |y| sequence.count(y) == 1 }
following = sequence.each_cons(2).all? { |a,b| a[-3,3] == b[0,3] }
return once_only && following
end
words = open("words.txt", "r", &:read).split.select { |word| word.size >= 3 }
SUBS = {}
PREFIXES = {}
# Built a Hash that maps prefixes to an Array of words starting with the prefix.
words.each do |word|
prefix = prefix(word)
PREFIXES[prefix] ||= []
PREFIXES[prefix] << word
end
longest = [1]
words.each do |word|
PREFIXES[prefix(word)].delete(word)
sequence = sequence(word, PREFIXES, [word])
if sequence.size > longest.size
longest = sequence
end
end
puts longest.inspect
puts
puts "Generated with seed: #{Random::DEFAULT.seed}"
puts "Length: #{longest.size}"
puts "Correct: #{correct?(longest)}"
```
[Answer]
# Score: ~~1631~~ 1662 words
```
['Aachen', 'hen', 'henceforward', 'ardor', 'dorsal', 'salmon', 'monolog', 'log', 'logjam',
'jam', 'jamb', 'ambassador', 'dormouse', 'useable', 'bleeding', 'ingenious', 'ouster',
'terminable', 'bleakness', 'essay', 'say', 'saying', 'ingress', 'essences', 'cession',
....
....
'ionosphere', 'ere', 'erecting', 'ingratiating', 'ingrate', 'ate', 'ateliers', "ersatz's"]
```
You can find the whole sequence here: <http://pastebin.com/TfAvhP9X>
I don't have the complete source code. I was trying out different approaches. But here are some code snippets, that should be able to generate a sequence of about the same length. Sorry, it's not very beautiful.
## Code (Python):
First some preprocessing of the data.
```
from collections import defaultdict
with open('words') as f:
words = [line.strip() for line in f]
words = [word for word in words if len(word)>=3 and word[-2:]!="'s"]
word_connections = defaultdict(list)
for word in words:
word_connections[word[:3]].append(word)
```
Then I defined a recursive function (Depth first search).
```
global m
m=0
def find_chain(chain):
s = set(word_connections[chain[-1][-3:]])-set(chain)
if len(s)== 0:
global m
if len(chain) > m:
m=len(chain)
print(len(chain), chain)
else:
for w in s:
if w not in chain:
find_chain(chain + [w])
for word in words:
find_chain([word])
```
Of course this takes way too long. But after some time it found a sequence with 1090 elements, and I stopped.
The next thing to do, is a local search. For each two neighbors n1,n2 in the sequence, I try to find a sequence starting at n1 and ending at n2. If such a sequence exists, I insert it.
```
def tryimpove(chain, length, startvalue=0):
s=set(chain)
for i in range(startvalue,len(chain)-1):
print(i)
for sub in sorted(short_sequences([chain[i]],length,chain[i+1]),key=len,reverse=True):
if len(s & set(sub))==1:
chain[i:i+1]=sub
print(i,'improved:',len(chain))
return tryimpove(chain,length,i)
return chain
def short_sequences(chain,length,end):
if 2 <= len(chain):
if chain[-1][-3:]==end[:3]:
yield chain
if len(chain) < length:
s = set(word_connections[chain[-1][-3:]])-set(chain)
for w in s:
for i in short_sequences(chain + [w],length,end):
yield i
for m in range(5, 100):
seq = tryimpove(seq,m)
```
Of course I also had to stop the program manually.
[Answer]
# PHP, 1742 1795
I've been messing about with PHP on this.
The trick is definitely culling the list to the around 20k that are actually valid, and just throwing the rest away. My program does this iteratively (some words it throws away in the first iteration mean others are no longer valid) at the start.
My code is horrible, it uses a number of global variables, it uses way too much memory (it keeps a copy of the entire prefix table for every iteration) and it took literally days to come up with my current best, but it still manages to be winning - for now.
It starts off pretty quickly but gets slower & slower as time goes on.
```
<?php
function show_list($list)
{
$st="";
foreach ($list as $item => $blah)
$st.="$item ";
return rtrim($st);
}
function mysort($a,$b)
{
global $parts;
$a_count=isset($parts[substr($a,-3,3)])?count($parts[substr($a,-3,3)]):0;
$b_count=isset($parts[substr($b,-3,3)])?count($parts[substr($b,-3,3)]):0;
return $b_count-$a_count;
}
function recurse($line,$list,$parts)
{
global $lines;
global $max;
global $finished;
global $best;
$end=substr($line,-3,3);
$count=0;
if ($finished)
return;
if (isset($parts[$end]))
{
$maxp=count($parts[$end])-1;
if ($maxp<0)
return;
$randa=array();
for ($a=1;$a<3;$a++)
{
$randa[mt_rand(0,$maxp)]=1;
}
$n=mt_rand(0,$maxp);
foreach ($parts[$end] as $key => $endpart)
{
if (!isset($list[$endpart]))
{
$this_part=$parts[$end];
unset($this_part[$key]);
$new_parts=$parts;
unset($new_parts[$end][$key]);
$list[$endpart]=1;
recurse($endpart,$list,$new_parts);
unset($list[$endpart]);
}
}
}
$count=count($list);
if ($count>$max)
{
//echo "current best: $count\n";
file_put_contents('best.txt',show_list($list) . "\n",FILE_APPEND);
$max=$count;
$best=$list;
}
}
function cull_lines(&$lines)
{
global $parts;
do
{
$wordcount=count($lines);
$parts=array();$end_parts=array();
foreach ($lines as $line)
{
if (strlen($line)<3)
continue;
$parts[substr($line,0,3)][]=$line;
if (strlen($line)>3)
$end_parts[substr($line,-3,3)][]=$line;
}
foreach ($lines as $key => $line)
{
$end=substr($line,-3,3);
if (strlen($line)<3 || !isset($parts[$end]) || !isset($end_parts[substr($line,0,3)] ) )
unset($lines[$key]);
}
foreach ($parts as $part)
{
if (count($part)==1)
{
$source_part=mt_rand(0,count($part)-1);
$this_part = substr($part[0],0,3);
$this_min = 10000;
$this_key = 0;
if (strlen($part[$source_part])==3)
{
foreach ($lines as $key => $line)
if ($line == $part[$source_part])
{
unset($lines[$key]);
break;
}
}
elseif (isset($end_parts[$this_part]))
{
foreach ($end_parts[$this_part] as $key => $end_part)
{
if (isset($parts[substr($end_part,0,3)]))
{
$n=count($parts[substr($end_part,0,3)]);
if ($n<$this_min)
{
$this_min=$n;
$this_key=$key;
}
}
}
foreach ($lines as $key => $line)
if ($line == $part[$source_part])
{
unset($lines[$key]);
}
elseif ($line == $end_parts[$this_part][$this_key])
{
$lines[$key].=' ' . $part[$source_part];
}
}
}
}
echo "$wordcount words left\n";
}
while ($wordcount!=count($lines));
}
ini_set('xdebug.max_nesting_level',10000);
ini_set('memory_limit','1024M');
$lines = explode("\n",file_get_contents('words.txt'));
cull_lines($lines);
$max=0;
foreach ($parts as $key=>$part)
usort($parts[$key],'mysort');
$n=count($lines);
foreach ($lines as $rand => $blah)
{
if (mt_rand(0,$n)==1)
break;
}
$rand=$lines[$rand];
$line[$rand]=1;
echo "Starting with $rand...\n";
recurse($rand,$line,$parts);
unset($line[$rand]);
?>
```
An obvious improvement would be using an orphan word for the start & finish.
Anyway, I really don't know why my pastebin list was moved to a comment here, it's back as a link to pastebin as I've now included my code.
<http://pastebin.com/Mzs0XwjV>
[Answer]
# Python : ~~1702~~ - ~~1704~~ - 1733 words
I used a Dict to map all the prefixes to all the words , as
```
{
"AOL" : [
"AOL", "AOL's"
],...
"oct" : [
"octet","octets","octette's"
],...
}
```
**Edit** little improvement:
removing all `useless` words at the beginning, if their suffixes aren't in the prefixes list (would obviously be a end word)
Then take a word in the list and browse the prefix map like a tree Node
```
import sys, fileinput
def p(w):return w[:3]
class Computing:
def __init__(_):
_.wordData = []; _.prefixes = {}
_.seq = []; _.bestAttempt = []
_.stop = False
for l in fileinput.input():
word = l.strip()
if len(word) > 2:_.wordData.append(_.addPfx(word, p(word)))
_.rmUseless();_.rmUseless()
_.fromI = 0; _.toI = len(_.wordData)
def rmUseless(_):
for w in _.wordData:
if not w[-3:] in _.prefixes: _.wordData.remove(_.rmPfx(w,p(w)))
def addPfx(_, w, px):
if not px in _.prefixes:_.prefixes[px] = []
_.prefixes[px].append(w)
return w
def rmPfx(_,w,px):
_.prefixes[px].remove(w)
if len(_.prefixes[px]) == 0:del _.prefixes[px];
return w
def findBestSequence(_):
def pickItem():
r = None
if _.fromI < _.toI:r = _.wordData[_.toI-1];_.toI -= 1;
return r
while not _.stop:
w = pickItem()
if not w:break;
_.seq = [_.rmPfx(w,p(w))]
_.checkForNextWord()
_.addPfx(w, p(w))
print " ".join(_.bestAttempt)
def checkForNextWord(_):
_.stop = len(_.seq) >= 1733
cw = _.seq[-1]
if not _.stop:
if cw[-3:] in _.prefixes:
lW = []
for word in _.prefixes[cw[-3:]]:
if not word[-3:] in lW:
_.seq.append(_.rmPfx(word,p(word)))
_.checkForNextWord()
if _.stop :break;
_.addPfx(_.seq.pop(), p(word))
lW.append(word[-3:])
if _.stop :break;
if len(_.bestAttempt) < len(_.seq):_.bestAttempt = _.seq[:];
sys.setrecursionlimit(6000)
Computing().findBestSequence()
```
The program need a number of words to know when stop, can be find as `1733` in the method `checkForNextWord̀`
The program need the file path as argument
Not very pythonic but I tried.
It took less than 2 min to compute this sequence : [full output](http://pastebin.com/2gwGcCSh):
>
> études desalinate ate ateliers ... blest esteeming ingenuous ousters
>
>
>
[Answer]
# Score: ~~249~~ ~~500~~ 1001
>
> Aachen --> hen --> henceforward --> ardent --> entail --> ail -->
> ailed --> led --> ledger --> gerbil --> bilateral --> rallying -->
> ingenious --> ousted --> tedious --> ouster --> terabit --> bit -->
> bitched --> hedgehog --> hog --> hogan --> gander --> derail -->
> ailerons --> onset --> set --> setback --> acknowledgement -->
> entailed --> ledgers --> ersatzes --> zest --> established -->
> hedgerow --> row --> rowboat --> oat --> oaten --> ten --> tenable -->
> bleach --> ache --> cheapen --> pen --> penalizes --> zestful -->
> fulcra --> crab --> rabbinical --> calabash --> ash --> ashamed -->
> medal --> dale --> ale --> alerted --> tediously --> sly --> slyest
> --> establishes --> hes --> hesitant --> ant --> antacid --> cider --> derailed --> ledges --> gestated --> tediousness --> essay --> say -->
> saying --> ingeniously --> slyness --> essaying --> ingenuous -->
> ousting --> ingenuousness --> essayist --> isthmus --> muscat --> cat
> --> cataclysmic --> mice --> ice --> iceberg --> erg --> ergonomic --> micra --> crabbed --> bed --> bedazzles --> lesbians --> answer -->
> were --> ere --> erecting --> ingest --> establishing --> ingesting
> --> ingestion --> ion --> ionization --> ionizer --> zero --> erode --> ode --> odes --> desalinates --> test --> establishment - -> entailing --> ingot --> got --> gotten --> tenant --> antagonist -->
> isthmuses --> sesame --> amebas --> basal --> salaamed --> medallion
> --> ionizing --> ingraining --> ingrains --> ins --> insane --> anecdotal --> talc --> alcohol --> hold --> old --> olden --> den -->
> denature --> urea --> reach --> ached --> hedges --> gestates -->
> testable --> bleached --> hedging --> ingrates --> testament -->
> entangle --> gleamed --> medallions --> onshore --> ore --> oregano
> --> anodes --> desalinating --> ingratiates --> testates --> tester --> terabits --> its --> itself --> elf --> elfin --> fin --> finagle --> gleaming --> ingratiating --> ingratiatingly --> glycerin --> rind --> indebtedness --> essences --> cesareans --> answerable --> bleacher --> her --> herald --> alder --> derailing -- > ingredient
> --> entanglement --> entangles --> lesion --> ionosphere --> erection --> ionospheres --> resale --> alerting --> ingresses --> sesames --> mes --> mesas --> sash --> ashcan --> can --> canard --> ardor -->
> dorkiest --> estates --> testes --> testicle --> cleaner --> nerdiest
> --> esteemed --> meddles --> lessee --> see --> seeded --> dedicates --> testicles --> lessen --> senates --> testiest --> esteeming --> ingrown --> own --> owner --> nerves --> vesicle --> cleanest -->
> ester --> terabytes --> testis --> tissue --> sue --> suede --> edema
> --> emaciates --> testosterone --> one --> ones --> nest --> esthetes --> testy --> sty --> styes --> yes --> yeshivas --> vascular --> larches --> hesitatingly --> glycerine --> inedible --> bleaches -->
> hesitates --> testifying --> ingrate --> ate --> ateliers
>
>
>
Here's my code:
```
import sys
sys.setrecursionlimit(10000)
w=[i for i in open("words.txt").read().split("\n") if len(i)>=3 and "'" not in i]
b=[i[:3] for i in w]
e=[i[-3:] for i in w]
a=[i for i in zip(*(w,b,e))]
def pathfrom(i,a,l):
longpath=[]
for j in a:
if j[1]==i[2]:
r=pathfrom(j,[m for m in a if m!=j],l+1)
path=[i]+r[0]
if r[1]:
return path,r[1]
if len(path)>len(longpath):
longpath=path
if l>=250:
return longpath,True
sys.exit()
return longpath,False
for i in a[:2]:
print i
p=pathfrom(i,[j for j in a if i!=j],1)
if len(p)>len(chain_):
chain_=p
print p
print p
```
Edit: 1001:
<http://pastebin.com/yN0eXKZm>
Edit: 500:
>
> Aachen --> hen --> henceforward --> ardent --> entail --> ail -->
> ailed --> led --> ledger --> gerbil --> bilateral --> rallying -->
> ingenious --> ousted --> tedious --> ouster --> terabit --> bit -->
> bitched --> hedgehog --> hog --> hogan --> gander --> derail -->
> ailerons --> onset --> set --> setback --> acknowledgement -->
> entailed --> ledgers --> ersatzes --> zest --> established -->
> hedgerow --> row --> rowboat --> oat --> oaten --> ten --> tenable -->
> bleach --> ache --> cheapen --> pen --> penalizes --> zestful -->
> fulcra --> crab --> rabbinical --> calabash --> ash --> ashamed -->
> medal --> dale --> ale --> alerted --> tediously --> sly --> slyest
> --> establishes --> hes --> hesitant --> ant --> antacid --> cider --> derailed --> ledges --> gestated --> tediousness --> essay --> say -->
> saying --> ingeniously --> slyness --> essaying --> ingenuous -->
> ousting --> ingenuousness --> essayist --> isthmus --> muscat --> cat
> --> cataclysmic --> mice --> ice --> iceberg --> erg --> ergonomic --> micra --> crabbed --> bed --> bedazzles --> lesbians --> answer -->
> were --> ere --> erecting --> ingest --> establishing --> ingesting
> --> ingestion --> ion --> ionization --> ionizer --> zero --> erode --> ode --> odes --> desalinates --> test --> establishment - -> entailing --> ingot --> got --> gotten --> tenant --> antagonist -->
> isthmuses --> sesame --> amebas --> basal --> salaamed --> medallion
> --> ionizing --> ingraining --> ingrains --> ins --> insane --> anecdotal --> talc --> alcohol --> hold --> old --> olden --> den -->
> denature --> urea --> reach --> ached --> hedges --> gestates -->
> testable --> bleached --> hedging --> ingrates --> testament -->
> entangle --> gleamed --> medallions --> onshore --> ore --> oregano
> --> anodes --> desalinating --> ingratiates --> testates --> tester --> terabits --> its --> itself --> elf --> elfin --> fin --> finagle --> gleaming --> ingratiating --> ingratiatingly --> glycerin --> rind --> indebtedness --> essences --> cesareans --> answerable --> bleacher --> her --> herald --> alder --> derailing -- > ingredient
> --> entanglement --> entangles --> lesion --> ionosphere --> erection --> ionospheres --> resale --> alerting --> ingresses --> sesames --> mes --> mesas --> sash --> ashcan --> can --> canard --> ardor -->
> dorkiest --> estates --> testes --> testicle --> cleaner --> nerdiest
> --> esteemed --> meddles --> lessee --> see --> seeded --> dedicates --> testicles --> lessen --> senates --> testiest --> esteeming --> ingrown --> own --> owner --> nerves --> vesicle --> cleanest -->
> ester --> terabytes --> testis --> tissue --> sue --> suede --> edema
> --> emaciates --> testosterone --> one --> ones --> nest --> esthetes --> testy --> sty --> styes --> yes --> yeshivas --> vascular --> larches --> hesitatingly --> glycerine --> inedible --> bleaker -->
> keratin --> tin --> tincture --> urethras --> rascal --> calamine -->
> ineducable --> bleakest --> esthetic --> tic --> tick --> ickiest -->
> estimable --> bleariest --> estimator --> tor --> torched -->
> hedonistic --> ticker --> kerchieves --> vesicles --> lessens -->
> ensconced --> cedar --> dare --> are --> area --> reachable --> bleat
> --> eat --> eatable --> bleeder --> derailment --> enter --> term --> ermine --> ineffable --> bleeped --> pedagog --> goggle --> gleans -->
> answered --> red --> redbreast --> aster --> termagant -->
> antagonistic --> ticket --> kettledrum --> rum --> rumbas --> basalt
> --> altar --> tar --> tarantulas --> lasagna --> gnarliest --> estrangement --> entered --> redcap --> cap --> capable --> bleeps -->
> epsilon --> loneliest --> estranges --> gestured --> redcaps --> apse
> --> pseudonym --> nymphomania --> niacin --> cinchonas --> nasal --> salable --> blend --> end --> endanger --> geriatric --> rice -->
> icebound --> undeceives --> vesper --> per --> perambulator --> tore
> --> ores --> resales --> lesser --> sera --> era --> eras --> rash --> ashen --> henchman --> man --> manacle --> cleanliest --> estrogen -->
> gendarmes --> mescal --> calcine --> inefficient --> entertainingly
> --> glycerol --> role --> oleander --> derangement --> entertainment --> entertains --> insatiable --> blended --> deduced --> cedars --> arsenic --> nice --> icebox -- > box --> boxcar --> car --> caracul
> --> cullender --> deranges --> gestures --> reschedules --> lesson --> son --> sonar --> narc --> arc --> arcade --> adenoidal --> dales -->
> lessor --> sorbet --> bet --> betaken --> ken --> kens --> ensemble
> --> blender --> deride --> idea --> deacon --> con --> concave --> avenger --> germane --> anemia --> miaowed --> wed --> wedded -->
> deducible --> blent - -> enthrall --> all --> allay --> lay -->
> layaway --> way --> wayfarer --> reran --> ran --> rancher -->
> heralded --> deductible --> blessed --> sedan --> danced --> cedes -->
> descant --> anteater --> termed --> meddlesome --> omegas --> gas -->
> gash --> ashram --> ram --> ramble --> blew --> lewder --> derides -->
> descend --> endangered --> redcoat --> oath --> atherosclerosis -->
> sis --> sisal - -> salad --> lad --> ladder --> derivatives --> vessel
> --> seldom --> domains -- > inscribed --> bedbug --> bug --> bugaboo --> boo --> boobed --> bedder --> derives --> vestiges --> gesundheit --> either --> heraldic --> dice --> icebreaker --> kerosene --> enema --> email --> ailment --> enthronement --> enthuse --> use --> used --> sedater --> terminator --> toreador --> dormant --> antebellum - -> lumbago --> ago --> agonizingly --> glycogen --> gender --> dermis --> misadventures --> rescind --> indecent --> enthused --> sedatives --> vestment --> enthusiast --> astir --> tirades --> descendant --> antecedent --> entice --> icecap --> capacitor --> torment --> enticed
> --> cedilla --> llama --> amalgam --> gambit --> bitches --> hesitates --> testifying --> ingrate --> ate --> ateliers
>
>
>
[Answer]
# Mathematica ~~1482~~ 1655
Something to get started...
```
dict=Import["words.txt"];
words=Union@Select[StringSplit[dict],(StringFreeQ[#,"'s"])\[And]StringLength[#]>2
\[And]LowerCaseQ@StringTake[#,1]&]
```
Links are the intersection prefixes and suffixes for words.
```
prefixes=Union[StringTake[#,3]&/@words];
suffixes=Union[StringTake[#,-3]&/@words];
links=Intersection[prefixes,suffixes];
linkableWords=(wds=RandomSample@Select[words,MemberQ[links,StringTake[#,3]]\[And]MemberQ[links,StringTake[#,-3]]& ])/.
w_String:> {w,StringTake[w,3],StringTake[w,-3]}
```
Edges are all the directed links from a word to other words:
```
edges[{w_,fr_,fin_}]:= Cases[linkableWords,{w1_,fin,_}:> (w\[DirectedEdge]w1)]
allEdges=Flatten[edges/@linkableWords];
g=Graph@allEdges;
```
Find a path between "mend" and "zest".
```
FindPath[g, "begin", "end", {1480, 3000}, 1][[1]]
```
Result (1655 words)
```
{"mend", "endorser", "server", "vertebral", "rallying", "ingrains",
"insurrectionist", "isthmus", "mussels", "elsewhere", "erection",
"ionizes", "zestful", "fullness", "essaying", "ingeniously",
"slyest", "estimator", "tornados", "doses", "sesame", "amebic",
"bicycled", "ledges", "gestation", "ionizing", "ingratiates",
"testifying", "ingesting", "inglorious", "ouster", "terminated",
"tediousness", "essayist", "isthmuses", "session", "ion",
"ionization", "ionospheres", "resubmitted", "tedious", "ousting",
"ingest", "ester", "terminates", "testicle", "cleanliness", "essay",
"say", "saying", "ingratiating", "ingratiatingly", "glycerine",
"inefficient", "entrances", "cesarians", "answering", "ingenious",
"ousted", "tediously", "sly", "slyness", "essences", "cesareans",
"answer", "were", "erecting", "ingredient", "enterprises",
"sessions", "onshore", "oregano", "anorak", "raking", "ingraining",
"ingrown", "owner", "nerdiest", "estranging", "ingot", "gotten",
"tendonitis", "tissue", "suede", "edelweiss", "issuing", "ingestion",
"ionosphere", "erections", "onset", "settles", "lesion", "ionizer",
"zeroing", "ingresses", "sesames", "mesmerizing", "ingrates",
"testes", "testiest", "estrangement", "entail", "ail", "ailment",
"entice", "icecap", "captivates", "testy", "sty", "stylistic",
"tickles", "lessee", "seeded", "deductibles", "lesser",
"servicewoman", "many", "anymore", "ores", "resourceful", "fullback",
"acknowledgment", "entertainer", "nerves", "vest", "esteemed",
"mediates", "testament", "entered", "redbreast", "astonishes",
"hesitatingly", "glycogen", "genera", "eras", "rashes", "hesitates",
"testicles", "lest", "establishment", "entwines", "nest", "estates",
"testates", "testosterone", "oneself", "elf", "elfin", "fingered",
"redcaps", "apse", "pseudonym", "nymphomania", "niacin", "cinemas",
"masochistic", "tickled", "led", "ledger", "geriatric", "rice",
"icebreaker", "kerosine", "inexperienced", "ceded", "deductible",
"blew", "lewder", "derivable", "blemished", "hedgerow", "rowel",
"welfare", "arena", "enamel", "melded", "dedicates", "tester",
"terabit", "bitmap", "mapped", "pedicures", "restored", "redeemer",
"merchantman", "manipulator", "torpedos", "dosed", "seduced",
"cedilla", "llano", "another", "heretic", "tic", "ticker", "keratin",
"tinctures", "restaurateur", "euros", "rosettes", "testable",
"bleaker", "kerosene", "energizer", "zero", "eroded", "deduced",
"cedar", "dare", "ares", "respondent", "entranced", "cedillas",
"lasagnas", "nastiest", "esthetic", "ticket", "ketches", "hes",
"hesitant", "antipasto", "stoppered", "redounded", "deducible",
"bleeped", "pedant", "antimatter", "terminable", "blent", "enthuse",
"user", "serenade", "adenoidal", "dales", "lessen", "sentimental",
"talker", "kerchieves", "vestry", "try", "tryout", "outdone", "ones",
"nestles", "lesson", "songwriter", "terrapin", "pinched",
"hedonistic", "tick", "ickiest", "established", "hedgehog", "hogan",
"gander", "derringer", "gerbil", "billboard", "ardor", "dorkiest",
"estrogen", "gent", "entirety", "etymological", "calk", "alkalis",
"lissome", "omegas", "gasolene", "enema", "emaciates", "test",
"estranges", "gestured", "redeemed", "medic", "diced", "cedars",
"arsenic", "nice", "iceberg", "erg", "ergonomic", "microcomputer",
"terser", "sergeant", "antipastos", "tost", "osteopathy", "thy",
"thymus", "mussiest", "estimable", "blend", "endeavored", "redound",
"undercover", "verbal", "balk", "alkali", "alibi", "ibis", "bison",
"sonar", "narcosis", "sister", "terraced", "cede", "edema",
"emancipator", "torpor", "portraiture", "urea", "reassign",
"ignoble", "blenched", "hedges", "gesture", "urethras", "raspy",
"spyglass", "ass", "assailant", "antiquarians", "answered",
"reduced", "cedes", "despair", "airfares", "resumed", "medicine",
"ineffable", "bleacher", "herdsmen", "menhaden", "dent",
"entitlement", "enticement", "entangle", "gleamed", "medullas",
"lassie", "sieve", "even", "vender", "derivatives", "vessel",
"selectmen", "mentor", "toreador", "dormer", "meringue", "guerrilla",
"llanos", "nosedove", "overact", "actionable", "bleeps", "epsilon",
"longhorn", "ornament", "entreaty", "atypical", "calendar", "dares",
"resurgent", "entreat", "eater", "term", "ermine", "inedible",
"bleeder", "derrières", "resentful", "fulcra", "crabbed",
"bedevilment", "entwine", "inelegant", "antitoxins", "inspired",
"redder", "derides", "descendant", "antihistamine", "inequitable",
"bleat", "eaten", "tenured", "redcap", "capstans", "answerable",
"blender", "deranges", "gestures", "restart", "arteriosclerosis",
"sis", "sisal", "saltpeter", "terrifyingly", "glycerin", "rink",
"inkwell", "ellipsis", "sisterhood", "oodles", "lessor", "sorrowed",
"wedges", "gesundheit", "either", "hereafter", "termite", "iterator",
"tornado", "adobes", "bespoken", "ken", "kens", "ensnare", "area",
"rear", "earful", "fulfil", "fillet", "letdown", "ownership",
"hipped", "pediatric", "richer", "heretical", "calculus", "lusher",
"heraldic", "dice", "icebound", "underscored", "redskins", "instant",
"antiperspirant", "anthropomorphic", "hiccup", "cup", "cups",
"upstage", "agendas", "dashingly", "glycerol", "role", "oleo",
"leonine", "ineluctable", "blessed", "sedatives", "vesicles",
"lessens", "ensured", "redefine", "inextinguishable", "bleach",
"achoo", "hooch", "ocher", "hero", "erode", "ode", "odes", "desktop",
"topple", "pleasured", "redeveloped", "pediment", "entrapped",
"pederasty", "stylus", "lush", "usher", "hermaphrodite", "item",
"tempos", "postpaid", "aide", "ideogram", "rampart", "artisan",
"sandhog", "hog", "hogwash", "ash", "ashram", "rammed", "mediocre",
"crestfallen", "lend", "endow", "downcast", "astronomer",
"merriment", "entrant", "antiwar", "warden", "dentures", "restful",
"fulfillment", "entrapment", "enthrall", "allay", "layout",
"outbound", "underclassman", "manhole", "oleander", "dermis",
"misused", "sedater", "terrific", "fiche", "cheapens", "ensnares",
"restrains", "insolent", "entombed", "bedraggle", "gleeful",
"fulfilment", "entrenchment", "entrap", "rapper", "persistent",
"enthronement", "enthusiast", "astute", "uterus", "rustproofed",
"fedora", "orangeades", "despised", "seducer", "ceramic",
"microscopic", "picnic", "nicotine", "inexpedient", "entomb",
"ombudsman", "mantel", "teletypewriter", "terminological", "calif",
"lifetimes", "mescaline", "inertia", "tiaras", "raster", "terrace",
"acetaminophen", "henchmen", "menhadens", "enslaves", "vesper",
"peroxide", "ideograph", "aphid", "hides", "desideratum", "tumor",
"mortgagee", "geegaw", "gawk", "awkward", "ardent", "enthused",
"sediment", "enter", "termed", "mediaeval", "valentine", "inexact",
"actives", "vestment", "entourage", "agent", "entryway", "wayside",
"idea", "dear", "earache", "checkups", "upsides", "descent",
"entertainment", "entomological", "calicos", "cosign", "ignored",
"redcoat", "oaten", "tensed", "sedan", "dank", "anklet", "lettered",
"redskin", "kingpin", "pinups", "ups", "upshot", "hotbed",
"bedtimes", "mes", "messenger", "germicides", "destitute", "utensil",
"silencer", "cervix", "vixens", "ensign", "ignorant", "antipasti",
"stimulus", "lusty", "stymie", "miens", "enslave", "averred",
"redrew", "rewritten", "tenpins", "instructor", "torrent",
"entertains", "insult", "ultrasound", "undersides", "despoil",
"oilcloth", "other", "hereupon", "pondered", "redundant", "anthill",
"ill", "illicit", "citizens", "ensnared", "rediscovered", "redesign",
"ignoramus", "muskmelon", "longer", "gerrymander", "deride", "ideas",
"easy", "asylum", "lumbermen", "mendicant", "antlered", "redevelop",
"lopes", "pester", "terrapins", "instil", "tildes", "deserves",
"vesicle", "cleave", "avenger", "germane", "anemia", "miasmas",
"mash", "ashy", "shy", "shyster", "termagant", "antiaircraft",
"afterglow", "lowland", "and", "androgen", "genitalia", "liars",
"arson", "sonatas", "taste", "stepsister", "termini", "initiator",
"tor", "torn", "ornamental", "tallow", "lowered", "red", "redraft",
"aft", "aftertaste", "stereotypes", "pesky", "skyrocket",
"kettledrum", "rummer", "merciful", "fulsome", "omens", "ensures",
"resultant", "antennas", "nasal", "saleswoman", "mane", "anemometer",
"terrains", "insightful", "fulcrum", "rumbas", "baseman",
"mannikins", "insures", "resound", "underpass", "assassins", "inset",
"settee", "teethe", "theological", "calf", "alfresco", "scornful",
"fulfill", "illustrator", "torpid", "pidgin", "gins", "instal",
"talc", "alcove", "overtakes", "kestrel", "relabel", "beleaguered",
"redraw", "rawhide", "identical", "caliber", "beret", "retrace",
"acetylene", "enemas", "massacred", "redeploys", "oyster",
"terminator", "tortillas", "last", "astronomical", "calliope",
"operator", "tort", "orthographic", "hiccups", "upstart",
"artificer", "cervical", "callus", "lustre", "trend", "endeavor",
"vortex", "textures", "researcher", "heroins", "instill", "illegal",
"galloped", "pedagogical", "callipered", "rediscover", "vertebra",
"brasher", "herbicides", "descry", "cryptogram", "ramrod", "rodeo",
"deodorizer", "zeros", "rosebush", "ushered", "redden", "denatures",
"reset", "setups", "upside", "ides", "describes", "besides",
"desperado", "adores", "reshuffle", "flea", "leaflet", "lethal",
"halibut", "but", "button", "tonic", "niche", "cherubim", "bimbos",
"bosun", "sunk", "unkind", "indentures", "resend", "endures",
"restorer", "reran", "rang", "anger", "germicide", "ideological",
"calabash", "ashamed", "medical", "caloric", "rickshas", "hasten",
"tendon", "donkey", "keyword", "ordains", "insecticides", "desires",
"resin", "sins", "inspector", "torrid", "rid", "rides", "despot",
"potpie", "piebald", "aldermen", "menace", "ace", "acerbic", "bicep",
"cephalic", "lichen", "hennas", "nasty", "styes", "yesterday", "day",
"daybed", "bedridden", "dental", "talisman", "mankind", "indignant",
"antique", "questionnaires", "resubmit", "mitten", "tenfold", "old",
"olden", "denudes", "design", "ignores", "resumes", "mesdames",
"mesas", "sass", "assemblywoman", "mangle", "glee", "leeway",
"waylay", "laywomen", "menswear", "ear", "earldom", "domains", "ins",
"instrumental", "tall", "all", "allegorical", "calm", "almanac",
"nacre", "credit", "dittos", "tossup", "superman", "mandolin",
"linesman", "manacle", "cleverer", "rerun", "runaway", "way",
"wayfarer", "reruns", "unshaven", "ventures", "resell", "elliptical",
"calmer", "mercuric", "ricochet", "heterodoxy", "oxymora",
"orangutang", "angina", "inapt", "apt", "aptitudes", "descend",
"endear", "earlobes", "bestowal", "walleyes", "yes", "yeshivas",
"vassal", "saltcellar", "larval", "valiant", "anthropological",
"calfskin", "kind", "inductee", "tee", "teenager", "gerund",
"underclass", "assemblyman", "manservant", "antelopes", "peso",
"esoteric", "rickshaw", "hawser", "servicewomen", "mental",
"tallyhos", "hospital", "talon", "longshoremen", "men", "menthol",
"holography", "phylum", "lumberman", "manikin", "kingpins",
"install", "allures", "resuscitator", "tortilla", "llamas",
"massacres", "resistor", "tormentor", "torque", "queasy",
"asymmetric", "ricksha", "sharped", "pedlar", "largos", "gossamer",
"merganser", "service", "icebox", "boxer", "xerography", "physical",
"calculator", "tortures", "resonant", "anticlimax", "maxima", "imam",
"mammon", "monograph", "aphelia", "liaison", "sonic", "nicknamed",
"media", "diametrical", "calliper", "performed", "medulla", "llama",
"amalgam", "gamins", "insulin", "lineman", "mantra", "transplant",
"antigen", "genres", "respires", "resold", "oldie", "diesel",
"seldom", "domed", "medieval", "valor", "lordship", "hipper", "per",
"perspires", "restores", "restructures", "resort", "orthodoxy",
"oxygen", "gentlemen", "menopausal", "saltpetre", "treacle",
"cleaver", "verdigris", "risen", "send", "end", "endemic",
"microfiche", "checkout", "outclass", "assault", "ultraviolet",
"let", "letterbox", "boxcar", "carom", "roman", "manifesto",
"stovepipes", "pesticides", "described", "bedsides", "descant",
"anthem", "hempen", "penguins", "insignificant", "antebellum",
"lumbar", "barracudas", "dash", "ashcan", "cannonball", "allover",
"verbena", "enamor", "morgue", "guerrillas", "lash", "ashen",
"henchman", "mandolins", "inspires", "resistant", "antechamber",
"bereave", "aver", "vermin", "minim", "nimbus", "bus", "businessman",
"mantras", "rasp", "asphalt", "altogether", "her", "hereabout",
"outcast", "astrological", "calisthenic", "nicknames", "mescal",
"calliopes", "pesetas", "tassel", "selectman", "mannikin",
"kinswoman", "man", "manic", "nicer", "cerebra", "bravado", "adobe",
"obeisant", "antiparticle", "clever", "versus", "sushi", "shirr",
"irrelevant", "antelope", "open", "pentagon", "gonad", "nadir",
"directorship", "hippopotami", "amid", "midwifed", "fedoras",
"rasher", "herbal", "ball", "allot", "lot", "lotus", "tussle",
"sledgehammer", "merchant", "ant", "antidepressant", "anther",
"heraldry", "drywall", "allegros", "rosebud", "budgerigar",
"garbageman", "manikins", "inscribes", "bestow", "townsmen", "menu",
"enures", "restaurant", "antithetical", "calico", "icon", "confound",
"underbid", "bidden", "denser", "seraphic", "hiccuped", "pedigree",
"reeve", "ever", "vertical", "caliper", "perusal", "salami", "amir",
"mires", "restraint", "interstellar", "larkspur", "puritanical",
"calligrapher", "herdsman", "manatee", "teepee", "peeve", "everyday",
"daydreamer", "meres", "result", "ultimatum", "tumbril", "rill",
"illogical", "calligraphy", "physic", "sickbed", "bedsores",
"resolver", "vertebras", "rascal", "call", "allergenic", "nickname",
"amebas", "baste", "stepson", "son", "sonnet", "net", "nether",
"heros", "rosins", "insular", "larvas", "vast", "astrakhan",
"handyman", "manicures", "resins", "instep", "tepid", "pidgins",
"inscribed", "bedbug", "bug", "bugbear", "earwax", "waxen",
"xenophobia", "biathlon", "longhair", "airstrip", "ripple", "pleas",
"eastbound", "underachiever", "verbatim", "timbre", "brew",
"rewound", "underplay", "laywoman", "mandarins", "insofar", "farm",
"armpit", "pitcher", "herald", "alderman", "mangos", "gossip",
"sipped", "pedagogue", "guerillas", "laser", "serape", "aped",
"pederast", "astound", "underground", "underpins", "insane",
"anemic", "micra", "crane", "anew", "new", "newscast", "astir",
"tiro", "ironware", "are", "areas", "east", "astronomic",
"microchip", "hippopotamus", "mustache", "chervil", "villas", "lass",
"assassin", "sinew", "newsman", "mangrove", "overtax", "taxicab",
"cabana", "anathemas", "mast", "astronaut", "author", "horoscope",
"opera", "eraser", "serfdom", "dominos", "nostrum", "rumpus", "pus",
"pushcart", "arthropod", "podia", "diatom", "tomboy", "boycott",
"ottoman", "manhunt", "untidy", "idyllic", "licensee", "seethe",
"thereabout", "outplay", "layoff", "officer", "cerebrum", "rum",
"rumple", "plethora", "oracle", "clergyman", "maneuver", "verandas",
"dashikis", "kisser", "serum", "rumor", "morbid", "bidet", "detach",
"achiever", "vertex", "text", "extremer", "merino", "inopportune",
"uneaten", "tensor", "sort", "orthopedic", "dickie", "kielbasas",
"sashay", "hayloft", "often", "ten", "tenpin", "pinkeye", "eyeball",
"allegro", "grout", "outfox", "fox", "foxtrot", "rot", "rotund",
"underwear", "earshot", "hot", "hotshot", "hotel", "telex",
"lexicon", "congresswoman", "manor", "northbound", "undertow",
"township", "hippos", "possessor", "sorbet", "betcha", "chart",
"art", "article", "clear", "earwig", "wigwam", "wampum", "pummel",
"melodic", "dictum", "tumbrel", "relic", "licit", "citadel", "delay",
"lay", "laypeople", "plectra", "traumas", "mascot", "cotyledon",
"donor", "nor", "normal", "malt", "altar", "tart", "artiste",
"stencil", "cilantro", "trouper", "pericardia", "diadem", "democrat",
"rattan", "tang", "angstrom", "romper", "perturb", "urban", "bang",
"angel", "gelatin", "tint", "intros", "rostra", "trapper",
"persimmon", "monsignori", "origin", "ginkgos", "gospel", "pelvis",
"visor", "sorghum", "humid", "midair", "air", "airfoil", "oil",
"oilskin", "kin", "kindergarten", "tentacle", "cleanser", "sermon",
"monolog", "logarithmic", "microbes", "bestir", "tiros", "rosin",
"sin", "singleton", "tonsil", "silicon", "con", "constraint",
"intagli", "glint", "interwove", "overshadow", "downtrodden",
"dentin", "tin", "tinsel", "sellout", "out", "output", "put",
"putsch", "schoolmarm", "arm", "armor", "moribund", "underpin",
"pint", "interloper", "periwig", "wig", "wigwag", "wagon",
"gonorrhea", "hearten", "tenon", "nonverbal", "balsam", "samovar",
"varmint", "interviewee", "weeper", "perturbed", "bed", "bedpan",
"panache", "chestnut", "nut", "nutmeg", "meg", "megalopolis",
"lissom", "somersault", "ultra", "tram", "ramp", "amputee", "teeth",
"ethos", "hos", "hostel", "telescopic", "picayune", "uneven",
"vendor", "dorsal", "salad", "ladybug", "bugaboo", "boomerang",
"angora", "orangutan", "tandem", "demagogry", "gryphon",
"honeycombed", "bedlam", "lamb", "ambergris", "risky", "sky",
"skycap", "capstan", "tannin", "ninepin", "pinpoint", "interpret",
"retiree", "reefer", "fer", "ferret", "returnee", "needlepoint",
"interurban", "bantam", "tamp", "ampul", "pullout", "outrun",
"runabout", "outstrip", "rip", "ripen", "pennon", "nonfat", "fathom",
"homespun", "puns", "unsubscribes", "besom", "sombre", "breathe",
"theatre", "tremor", "mortar", "tarpaulin", "lintel", "telethon",
"honeydew", "dewlap", "lap", "lapel", "pelvic", "victim", "timpani",
"animus", "muscat", "cat", "catsup", "sup", "superstar", "taro",
"arousal", "salamis", "misprint", "interwoven", "venom", "nomad",
"madam", "dam", "dampen", "penicillin", "lint", "intercom",
"compound", "underpay", "pay", "payoff", "off", "offal", "fallout",
"outwit", "withal", "halt", "altho", "tho", "thou", "housebound",
"undergrad", "radio", "diocesan", "sanserif", "riffraff",
"affidavit", "vitamin", "minicam", "campus", "pussycat", "catamaran",
"rancor", "cornucopia", "piano", "anon", "non", "nonpartisan",
"sandbar", "bar", "barren", "renewal", "walkout", "outruns",
"unsnap", "naphtha", "thalamus", "musky", "skydove", "overrun",
"run", "runs", "unsheathe", "the", "theorem", "remove", "overreach",
"ache", "cherub", "rubes", "beseech", "echo", "chosen", "sensor",
"sorrel", "relay", "layman", "mantillas", "lasagna", "gnat",
"natures", "resonator", "torus", "russet", "set", "setback",
"acknowledgement", "entanglement", "entombment", "entourages",
"gestates", "testing", "ingratiate", "ate", "ateliers", "ersatzes",
"zest"}
```
[Answer]
# Python, 90
>
> upended deductibles lessee seesawed wed wedded deduces cesarians answerable blesses sesames meshes hesitation ionosphere erection ionizer zero erode ode odes deserter terminations onshore ores reside idealistic tic tickles lesson song ongoing ingrains instill illiberal rallying ingest estranges gestures responses sesame amend endives vestment entertainer nervously slyest esters ersatzes zestful fullback acknowledges gesture urethras rashes hesitant anticlimax maxima imagine inebriates tested tediously slyness essences cesareans answer werewolves vest esteemed meddlesome omelet lettuces cession ionization ionizing ingestion ionospheres rescue cueing ingrown ownership hip hippie piety etymologist isthmuses sessions onset settled ledgers
>
>
>
First i clean up the list manually by deleting all
* words with a Capital letter
* words with apostrophe's
* words with éêèáâàö
* 1- and 2-letter words
this costs me at most 2 points because those words can only be in the beginning or the end of the chain but it reduces the wordlist by 1/3 and i dont have to deal with unicode.
Next I construct a list of all pre- and suffixes, find the overlap and discard all words unless both the pre- and suffix is in the overlap set. Again, this shaves off at most 2 points off my maximal achievable score, but it reduces the wordlist to a third of original size (try running your algorithm on the [short\_list](https://dl.dropboxusercontent.com/u/27435112/words_veryshort.txt) for a possible speedup) and the remaining words are highly connected (except some 3-letter words which are connected only to themselves). In fact, almost any word can be reached from any other word through a path with an average of 4 edges.
I store the number of links in an [adjacency matrix](http://en.wikipedia.org/wiki/Adjacency_matrix) which simplifies all operations and lets me do cool stuff like looking n steps ahead or counting cycles... at least in theory, since it takes around 15 seconds to square the matrix I dont actually do this during the search. Instead i start at a random prefix and walk around randomly, either picking an ending uniformly, favoring those that occur often (like '-ing') or those that occur less often.
All three variants suck equally and produce chains in 20-40 range, but at least its fast. Guess I gotta add recursion after all.
```
from numpy import *
f = open('words_short.txt')
words = f.read().split() # 62896
f.close()
prefix = [w[:3] for w in words] # 2292
suffix = [w[-3:] for w in words] # 2262
common = set(prefix) & set(suffix) # 1265
PSW = [(p,s,w) for (p,s,w) in zip(prefix, suffix, words) if p in common and s in common] # 28673
common = list(common)
mapping = dict(zip(common, range(len(common)))) # enumerate trigrams
M = zeros((len(common), len(common)), dtype=int) # for fast processing
W = [[[] for i in range(len(common))] for j in range(len(common))] # for reconstruction
for p,s,w in PSW: # build adjacency matrix
M[mapping[p], mapping[s]] += 1
W[mapping[p]][mapping[s]].append(w)
def chain(A, rho=0):
B = array(A)
links = []
start = random.randint(len(B))
links.append(start)
while 1:
nextpos = where(B[links[-1],:]>0)[0]
if len(nextpos)==0: return links
nextnum = B[links[-1],nextpos]
p = ones(len(nextnum))/len(nextnum) # pick uniformly
if rho>0: p = nextnum*1./sum(nextnum) # prioritize many links
if rho>1: p = 1/p; p = p/sum(p) # prioritize few links
chosen = random.choice(nextpos, p=p)
B[links[-1], chosen] -= 1
links.append(chosen)
def chain2words(L):
# can only be used once because of .pop()
z = zip(L[:-1],L[1:])
res = []
for p,s in z:
res.append(W[p][s].pop())
return res
chains = [chain(M) for i in range(100)]
bestchain = chains[argmax(map(len, chains))]
print ' '.join(chain2words(bestchain))
```
Originally I wanted to try something similar to [this](https://softwareengineering.stackexchange.com/a/246080/160977) but since this is a directed graph with cycles, none of the standard algorithms for Topological Sorting, Longest Path, Largest Eulerian Path or Chinese Postman Problem work without heavy modifications.
And just because it looks nice, here is a picture of the adjacency matrix M, M^2 and M^infinity (infinity = 32, it doesnt change afterwards) with white = nonzero entries

] |
[Question]
[
As the title says, I was thinking to contest in which one must detect edges of an ASCII art.
The code should accept a B/W ASCII art as input.
A *B/W ASCII art* is defined as (by me) an *ASCII art* with only one kind of non-white-spaces character (in our case: an asteriks `*`). And as *output* produce a standard *ASCII* art (all *ASCII* characters are accepted) which should remember the contourn of the first.
The purpose of using more than one character in the output is to make some edges ssmoother.
For instance, one could let this input
```
***
****
******
******
******
******
****
***
```
could became:
```
___
_/ )
_/ /
/ |
| /
| \
\ |
`\ |
\___)
```
The input `\n` separated string as input. Each line has a maximum of `80` characters. The number of rows is not specified.
This is my sample Python3 program:
```
import fileinput as f
import re as r
import copy as c
a,s,p='*',' ','+'
def read(n):
s=[list(' '*n)]
for l in f.input():
if(len(l)>n):l=l[:n]
k=list(r.sub('[^ ^\%c]'%a,'',' '+l+' '))
s.append(k+[' ']*(n-len(k)))
s.append([' ']*n)
return s
def np(s):
s=c.deepcopy(s)
for l in s[1:-1]:
for w in l[1:-1]: print(w,end='')
print()
def grow(i):
o=c.deepcopy(i)
for x in range(1,len(o)-1):
for y in range(1,len(o[x])-1):
if(i[x][y]==a): o[x-1][y-1]=o[x-1][y+1]=o[x-1][y]=o[x+1][y]=o[x+1][y-1]=o[x+1][y+1]=o[x][y+1]=o[x][y-1]=a
return o
def diff(i,o):
c=[]
for x in range(0,len(i)):
l=[]
for y in range(0,len(i[x])):
if(i[x][y]==a and o[x][y]==s): l.append(p)
else: l.append(s)
c.append(l)
return c
I=read(80)
np(diff(grow(I),I))
```
### Input:
Here below I put both input of the programs. It is an 80x70 ASCII ART. It means it has 70 lines of 80 characters, each separated by `\n`.
This input file contains only spaces and the asterisk `*`, it has a maximum of 80 columns as every *ASCII art*.
If you find a nicer art let me know!
```
*************
***** *****
****** ***
*** ****
********* **
*********** **
****** ******* **
***** ******* *** **
**** ******** ***** *
** ********* ***** ***** *
*** ********* ******* ****** **
** ********** ******* ****** **
** ********** ******* ******** *
* *********** ****** ******** *
** ************ ***** ******** *
* ************ *** ******** *
* ************* ****** *
* ************* *** *
** ************* *
* ************** *
** ************* **
* ************* **
** ************* ***
*** ************* ****
** ************ ****
** ************* ****
** ************* ***** ****
** ************* ** ** ** ****
** ************ * * ** ** ****
* ************ ** ** ** ** ****
* ************* ******* ** *** ****
* ************ ***** ******* ****
* ************ *** ***** ****
** * ************* **** *****
** *** ************** *****
* ***** ************* ******
** ******* ************** *******
********** *************** * *********
********** ***************** *** ***********
*********** ******************* **************
*********** ********************** ******************
************ ***************** ** ***********************
************* ****************** **** *******************
************** ****************** ********************
**************** ****************** *******************
*************** ******************* *******************
**************** ****************** ******************
****************** ****************** *******************
******************* ***************** *******************
********************* ****************** ********************
********************************************* *********************
********************************************** ***********************
************************ ***************** ************************
********************** ******************* **************************
********************* *********************************************
********************* **************************** ***************
******************** ************************** ***************
******************** ********************* ***************
******************* ******************** ****************
****************** ***************** ****************
***************** **************** ***************
***************** **************** ***************
***************** ***************** ***************
**************** ***************** ***************
************** ****************** ***************
**************** ****************
************** ***************
**************
************
```
### Possible output:
A possible output could be:
```
+++++ ++++
++++++ ++++++++++ +++
++ +++++ +++++ +++++
++++++++ +++++ ++++ ++
++++ ++ ++++ ++
++++++ ++ ++ ++
+++++ +++ + +++++ ++ ++
++++ +++++++ ++ ++ ++ ++ ++
++ +++++ ++ + + + +++++++ ++
+++ ++++ ++ + ++ ++ ++ ++ ++
++ ++ ++ ++ + + + ++ ++
++ +++ + + ++ + ++ +++ +
++ ++ ++ + ++ ++ + +++ +
++ +++ ++ + + +++ + + + ++
+ + + + + ++ + ++++ +
++ ++ ++ + ++ ++ ++ + + +
++ ++ + + +++++ ++ ++ + +
++ ++ + + +++ ++ + +
+ + ++ + +++++ + +
++ ++ + + ++ +
+ + + ++ + +
++ ++ ++ + + ++
++ + + ++ + ++
+ + + + + +
+ ++ ++ ++ + +
+ + + + +++++++ + +
+ + + + ++ ++ ++++ + +
+ + + + + +++ + ++ +++ + +
+ + ++ + + ++ ++ + ++ + ++ + +
+ ++ + ++ ++ +++ + + +++ ++ + +
+ + + + + ++ + +++ + + +
+ + + ++ ++ ++ ++ + + +
+ + +++ ++ ++ + +++ +++ + ++ +
+ ++ ++ + ++ +++++ + ++ ++ +
+ ++ ++ + + ++++++ ++ ++
++++ + ++ +++ ++ +
+ + ++ ++ +++ +++ +
+ + ++++ ++ ++ +++ +
++ ++ ++++ + + ++++ +
+ ++ +++++ +++++ +++++ +
++ ++ +++ ++++++ +
++ + +++++ +++++ +
++ + + +++ +++++ +
+++ + ++ ++++++ + +
+ ++ + ++ +
++ + + + +
+++ ++ + ++ ++
++ + + + +
+++ ++ + +++ +
++++++ + ++ ++
++ +++ +
+ ++ +
+++++ ++++++ +
+ ++ ++ + +
+ ++ + ++
+ + + ++ +
+ ++ + ++++ +
+ + + ++++++ ++ +
+ ++ + ++ + +
+ ++ + ++++ + +
+ ++ ++ + + ++
+ + + ++ + +
+ + + + + +
++ + + ++ + +
++ ++ + + + ++
++++++++++++++++ +++ + + +
++ ++ ++ +
++++++++++++++++ ++ +
++ ++
++++++++++++++
```
This is also the output produced by the script above. Of course it is not the best output and I'm sure one can easily produce a smoother one.
It is a **popularity-contest** since, I hope votes will be proportional to elegance and quality of outputs! (Also I guess good results acan be obtained combinig `aplay` and `gimp-cli`)
There are no strict rules on how the output should be..just use your fantasy!
[Answer]
### GolfScript
I thought golfing is popular on this site, so a GolfScript submission always fits for a popularity contest.
```
n%.0=,' '[*]\1$++{0\0++{42=}%[{.}*]);2/}%{.}*]);2/{zip{~+2base' /\-\|/ /\| - '=}%n+}%
```
You can try the code with your own ascii art [here](http://golfscript.apphb.com/?c=OyIgICAgICoqKgogICAqKioqIAogKioqKioqIAoqKioqKiogIAoqKioqKiogIAogKioqKioqIAogICAqKioqIAogICAgICoqKiIKCm4lLjA9LCcgJ1sqXVwxJCsrezBcMCsrezQyPX0lW3sufSpdKTsyL30ley59Kl0pOzIve3ppcHt%2BKzJiYXNlJyAvXC1cfC8gL1x8IC0gICAnPX0lbit9JQo%3D&run=true). Note that it is required that all lines have the same length.
Example:
```
/------------\
/--- --------- --\
/---- ---/ \--- -\
/ ---/ \--\---\
/------ / \-- \
/-- / \ \
/---- -- | \ \
/--- ----/ / / /--\ \ \
/-- ---/ / | / \ \-\\
/ --/ / | | | /----\\\\
/- / / / / \ / | | \
/ -/ / | | | | | \ \
/ / | | / / / \ \ |
//-/ / | / -/ | | ||
/ | / | | / | | \\\
| / | | \ / \ \ ||
/// / | \--/ \ / ||
/// | | \- / ||
/ | | | \--/ ||
| / / | ||
/ | | / / |
| / | | | |
/ | / / | \
/ | | | | \
| / | / | |
| | / | | |
| | | | /----\ | |
| | | | / -- \ /-\ | |
| | \ | | / \ | / \-\ | |
| / | | | \ / | / /\ \ | |
|| | \ / -- / | | | \ | |
|| | / \ / \ -- | | |
|| \ \ | -/ \- | | |
/ | /\ | \ \--/ | / / |
| | / \ | \ \---/ / /
| / / \ \ | / |
| \/- | \ -\ / |
| | | \ /\ /- |
| | \ --\ / \ /- |
| \ \ --\ \--/ /-- |
| | \ ---\ /--- |
| \ | ----\-\ /---- |
| \ | \ \-\---\\--- |
| \ | | \---/ / |
| -\ \ \ \ |
| / / | | |
| \ \ | | /
| -\ | | / |
| \ \ | | |
| -\ / | /- /
| ----- | / |
| \ /- |
| ---- | / |
\ / \ --\/- |
| / | /
| | | - |
| / | -/ | |
| | | ----/ | |
| / | / / |
| / | --/ | |
| / \ | | /
| | | | | |
| | | \ | |
\ | | | | |
\ / | \ | |
\-------------/ \- | | \
\ / \ |
\-------------/ \ |
\ /
\-----------/
```
[Answer]
The Python code, primarily relies on regex to do the task.
```
def edge_detect(st):
width = len(max(st.split('\n'), key=len))
#Pad the image with extra blank lines above and below
st = '{{0: <{0}}}\n{{1}}\n{{0: <{0}}}'.format(width).format('', st.rstrip('\n'))
return re.sub(r""" #Match a non space character
(?<=\s.{{{0}}})[^\s]|#When the char above is a space
[^\s](?=.{{{0}}}\s) |#When the char below is a space
(?<=\s)[^\s]| #When the previous char is a space
[^\s](?=\s) #When the following char is a space
""".format(width),
'+', #Replace it with edge character '+'
st,
flags=re.X|re.S).replace('*',' ') # And finally replace all
# non-space character with spaces
```
**\*Output**
```
>>> print edge_detect(st)
+++++++++++++
+++++ +++++
++++++ +++
+++ ++++
+++++++++ ++
++++ + ++
++++++ + ++ ++
+++++ ++ + +++ ++
++++ ++ + ++ + +
++ ++ ++ + + +++++ +
+++ ++ + ++ + ++ + ++
++ ++ + + ++ + + ++
++ + + ++ +++ ++ + +
+ ++ + ++ ++ + + +
++ ++ + + ++ + + +
+ + + +++ + ++ +
+ ++ + + ++ +
+ + + +++ +
++ + + +
+ ++ ++ +
++ + + ++
+ + ++ ++
++ ++ + + +
+++ + ++ + +
++ + + + +
++ ++ + + +
++ + + +++++ + +
++ + + ++ ++ ++ + +
++ + + + + ++ ++ + +
+ + + ++ ++ ++ ++ + +
+ + ++ ++ +++ ++ + + + +
+ + + + +++ + +++ + + +
+ + + +++ + ++ + +
++ + + + ++++ ++ ++
++ +++ + + ++ +
+ ++ + + + ++ +
++ +++ + + + ++ +
+ + + + + + +++ +
+ + + ++ +++ +++ +
+ + + ++ ++++ +
+ + + ++++++ +++++ +
+ + + + ++ ++++++ +
+ + + + ++++ + +
+ + + + ++ +
+ ++ + + + +
+ + ++ + + ++
+ + + + + +
+ + + + ++ +
+ + + + + ++
+ + ++ + +++ +
+ ++++++ + ++ +
+ +++++ + +++ +
+ ++ + + ++ +
+ ++ + ++ +++ ++
+ + + + ++ +
+ ++ + +++ + +
+ + + ++++++ + +
+ ++ + ++ + +
+ ++ + ++++ ++ +
+ ++ + + + ++
+ + + + + +
+ + + + + +
+ + + + + +
+ ++ + + + +
++++++++++++++ + + + +
+ ++ + +
++++++++++++++ + +
+ ++
++++++++++++
```
**Another one**
```
print edge_detect(st)
+++
++ +
++ +
+ +
+ +
++ +
++ +
+++
```
[Answer]
# Python
Using gradient operation to identify edges:
```
from numpy import gradient, zeros
import matplotlib.pylab as plt
b = open("file").readlines()
bi = zeros((len(b),len(b[0])))
e = enumerate
for i,l in e(b):
for j,c in e(l):
if(c=="*"): bi[i][j]=1
g = gradient(bi,.5,.5)
g = (abs(g[0])+abs(g[1]))>=1.
plt.subplot(2,1,1)
plt.imshow(bi,cmap='Greys'), plt.show()
plt.subplot(2,1,2)
plt.imshow(g*1,cmap='Greys'), plt.show()
```
**Output** for the banana and panda:

To make an ASCII Output, the part of the plots should be replaced with:
```
r = range
s = ""
for i in r(len(b)):
for j in r(len(b[0])):
if(g[i][j]!=0):
s+="*"
else:
s+=" "
s +="\n"
print s
```
**ASCII Output:**
Banana:
```
*** **
**** **
*** **
* **
* **
*** **
**** **
*** **
```
Panda:
```
*************** ****
****** ************* ***
*** ***** ***** *****
******** ***** **** **
********** ** ******
****** * ** ****
***** ***** ** *** ****
**** ****** ** ** ***** ****
** ***** ** ** ** ** **** * *
******* ** ** ** ** **********
** ** ** ** ** ** ** ******
***** ** ** ** ** ** ** ****
**** ** ** ** *** ** ** * *
**** ** ** ** *** ** ** ***
**** ** ** ** ** ** ** ***
*** ** ** ***** ** ** * *
* * ** ** *** *** ** * *
*** ** ** ****** * *
**** ** ** *** * *
* * ** ** * *
**** ** ** ****
* * ** ** ****
**** ** ** ** **
** ** ** ** ** **
**** ** ** ** **
**** ** ** ***** ** **
**** ** ** ** ** ** ** **
**** ** ** ********* ***** ** **
**** ** ** * * * * ******* ** **
* * ** ** ********* **** **** ** **
* * ** ** ** ***** ******* ** ** **
* * ** ** ** *** ** ** ** ** **
* * * ** ** ****** *** ** ** **
*** *** ** ** *** ****** ** **
** ** ** ** ** **** ** **
** *** ** ** *** ** **
**** ** ** *** * *** **
* ** ** **** *** **** **
** ** ****** ***** ***** **
** ** ******* *** ******* **
** ** * *** ********* **
** ** ************** * **
** ** ** *** ******* **
*** ** ** **** ** **
*** ** ** ** **
** ** ** ** **
*** ** ** ** **
*** ** ** ** **
*** ** ** *** **
********* ** *** **
****** ** *** **
***** ** *** **
* ******* **** *** **
** ** ** ****** **
** ** ** * ** **
** ** ** ***** **
** ** ** ******* ** **
** ** ** ****** ** **
** ** ** **** ** **
** ** ** **** ** **
** ** ** ** ** **
** ** ** ** ** **
** ** ** ** ** **
** ** ** ** ** **
**************** *** ** ** **
************** *** ** ** **
**************** ** **
************** ** **
** **
```
[Answer]
# Mathematica
Assuming that `panda` contains the original string, the following obtains the pixels of the contour edges and replaces them with "+".
```
t = (Most /@ Partition[Take[Characters@panda, {61, 5636}], 82]) /. {"*" -> 1, " " -> 0};
Grid[ImageData[EdgeDetect[Image[t]]] /. {1 -> "+", 0 -> " "}, Spacings -> 0]
```

---
## How it works
`Partition[Take[Characters@panda, {61, 5636}], 82]` breaks the string up into lines of characters.
`Most` removes the new line characters.
`Image[t]]]` converts the matrix of 0's and 1's into an image.
`EdgeDetect` finds the edges of the image.
`ImageData` obtains the binary matrix of the image.
`/. {1 -> "+", 0 -> " "}` replaces each 0 and 1 with the appropriate character.
`Grid` displays the Ascii art.
[Answer]
**Java**
This checks lines and rows if there's anything on top, left, right or bottom and based on that picks a value from array holding symbol that's used to generate new art using edges!
Example output:
```
/^^^^^^^^^^^\
/^^^/ \_^^\
/^^^^/ \^\
/ / /^^\
/^^^^^^ / \\
/^^_ | \\
/^^^^/ | / \\
/^^^/ / | /^\ \\
/^^/ / | / \ /
// / / | | /^^^\ /
/^/ / | / \ / | \\
// / | | / | | \\
// | | / _/ / \ |
/ / | / / | | \
// / | \ / \ | /
\ | | \_/ \ \ |
/ / | \_ / |
/ | | \_/ |
// | | |
| / / |
// | | /|
| | / ||
/| / | | \
/ / | / | \
|| | | | |
|| / | | |
|| | | /^^^\ | |
|| \ | // \\ /\ | |
|/ | | | | // /\ | |
| | | |\ // /| |\ | |
| | \ / ^^^/ \| | \ | |
| \ | | _/ \^^^ | | |
| | \ \_/ | / | |
/| / | \ \__/ / /
|/ / \ \ \ / |
| / \ \ | / |
|\ /^ | | ^\ / |
| ^ | \ \ / /^ |
| | \ ^^\ /_\ /^ |
| \ \ ^^\ /^^ |
| | | _^^^\ /^^^ |
| \ | | /\ /^^^^ |
| \ | \ /^^\ | |
| \ \ | / |
| ^\ | \ | |
| | / | | /
| \ | | | |
| ^\ \ | / |
| \ | | | /
| ^\ / | /^ |
| ^^^^^^ | / |
| _____ \ /^ |
\ / \ | / |
| / | ^^\ /^ /
| | | ^ __ |
| / | _/ | |
| | | ____/ | |
| / | / | |
| / | __/ / |
| / \ | | /
| | | | | |
| | | | | |
\ | | \ | |
\ / | | | |
\____________/ \_ \ | |
\ / \ \
\____________/ \ |
\ /
\__________/
/^\
/^ |
/^ /
/ |
\ |
\_ \
\_ |
\_\
```
Code:
```
package com.ruuhkis.asciiedge;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ASCIIEdge {
public static void main(String[] args) {
try {
if (args.length > 0) {
for (String arg : args) {
new ASCIIEdge().detach(new FileInputStream(new File(arg)));
}
} else {
new ASCIIEdge().detach(new FileInputStream(new File("art.txt")));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void detach(InputStream is) throws IOException {
BufferedReader bw = new BufferedReader(new InputStreamReader(is));
StringBuilder artBuilder = new StringBuilder(100);
int longestLineLength = 0;
int numLines = 0;
String line = null;
while ((line = bw.readLine()) != null) {
artBuilder.append(line + System.getProperty("line.separator"));
if (line.length() > longestLineLength) {
longestLineLength = line.length();
}
numLines++;
}
bw.close();
char[][] artBuffer = new char[numLines][longestLineLength];
String[] lines = artBuilder.toString().split(
System.getProperty("line.separator"));
for (int i = 0; i < lines.length; i++) {
lines[i].getChars(0, lines[i].length(), artBuffer[i], 0);
for (int j = lines[i].length(); j < longestLineLength; j++) {
artBuffer[i][j] = ' ';
}
}
detach(artBuffer, longestLineLength, numLines);
}
private void detach(char[][] artBuffer, int longestLineLength, int numLines) {
char[][] outputBuffer = new char[numLines][longestLineLength];
for (int i = 0; i < numLines; i++) {
for (int j = 0; j < longestLineLength; j++) {
;
int horizontalEdge = isHorizontalEdge(artBuffer[i], j,
longestLineLength);
int verticalEdge = isVerticalEdge(artBuffer, i, j, numLines);
char[][] result = { { '/', '^', '\\' }, { '|', ' ', '|' },
{ '\\', '_', '/' } };
outputBuffer[i][j] = result[verticalEdge + 1][horizontalEdge + 1];
;
}
System.out.println(outputBuffer[i]);
}
}
private int isVerticalEdge(char[][] chars, int row, int col, int numLines) {
boolean canBeEdge = chars[row][col] != ' ';
boolean upperEdge = row - 1 < 0 || chars[row - 1][col] == ' ';
boolean lowerEdge = row + 1 >= numLines || chars[row + 1][col] == ' ';
return (canBeEdge && (upperEdge || lowerEdge)) ? upperEdge ? -1 : 1 : 0;
}
private int isHorizontalEdge(char[] chars, int index, int length) {
boolean canBeEdge = chars[index] != ' ';
boolean leftEdge = index - 1 < 0 || chars[index - 1] == ' ';
boolean rightEdge = index + 1 > length - 1 || chars[index + 1] == ' ';
return (canBeEdge && (leftEdge || rightEdge)) ? leftEdge ? -1 : 1 : 0;
}
}
```
Ps. first timer here, don't be rough :D
Pps. that Panda looks like its sad :(
[Answer]
**Python (ascii -> image -> edge filter -> ascii)**
I kind of cheated, I converted the ascii text to an image and ran PIL edge detect filter on it. Then, I inverted the image and converted back to ascii text:
```
from PIL import Image, ImageFilter, ImageOps
import random
from bisect import bisect
greyscale = [" "," ",".,-","_ivc=!/|\\~","gjez2]/(YL)t[+T7Vf","mdK4ZGbNDXY5P*Q","W8KMA","#%$"]
zonebounds=[36,72,108,144,180,216,252]
f=open('input.txt', 'r')
lines=f.readlines()
f.close()
width=82
height=len(lines)
im = Image.new("RGB", (width,height), "white")
pixels = im.load()
y=0
for line in lines:
x=0
for px in line:
if px != ' ' and x < width:
pixels[x,y] = (0,0,0)
x+=1
y+=1
im=im.resize((width, height),Image.BILINEAR)
im=im.convert("L")
im=im.filter(ImageFilter.FIND_EDGES)
im=ImageOps.invert(im)
str=""
for y in range(0,im.size[1]):
for x in range(0,im.size[0]):
lum=255-im.getpixel((x,y))
row=bisect(zonebounds,lum)
possibles=greyscale[row]
str=str+possibles[random.randint(0,len(possibles)-1)]
str=str+"\n"
print str
```
Here is the result:
```
$#$$#%$$$$$$%%$$$%$$$$%$###%%#%%%$##$$$%%#$#%# $%%%%$$%$###$$%%%##%##
% $%%$$$ %#$%$$$#$$ $%# #
% %% $%$#$ $$$$% %#%#% #
% %$#$%%$$ #%$$% %%%% %$ #
$ #$$$ %$ $### #% $
% #%$#$# $% %# #$ #
# #%$%# $## $ $%%$% $$ $% #
% $%#% $##%$%$ ## $% %# $$ %$ $
% %$ %$%$$ %# $ # # $#$#$$$ $$ %
% $%# $##% ## # #% %$ #$ #% %% %
% #$ #$ %$ %$ # % $ $$ $$ #
# $% $%# % # ## # $% %#% $ #
% #% #% %# # $$ $% $ $$# $ %
% #% $$% %% % $ $%# # % $ ## $
% $ % # # % %% % #$#$ # #
% $% $% #% % %$ #% %% # $ % %
$ $$ %$ % # %#$%% ## $$ # $ %
# $% #$ $ $ #$$ $% % $ $
% % % #% # %$#%# $ $ %
# $$ #% $ # ## # %
$ % # $ #$ # $ %
%$$ ## %# % $ $$ #
$$ % # $% # #$%
$ $ % % % $#
$ %# #% $% # #$
% % # $ #%$##%$ % %#
$ $ # $ $% $# %#%% # %%
# % # # % $%$ % %% %%# % $#
% # #% # # ## $# # %# % %$ $ #$
$ $% % $% $% $$$ % $ #$# %# % #$
# % $ $ # $% $ #$% % $ $$
% % $ $% %# ## $$ $ # ##
% # ### %# #% $ %%$ #$% # %# %%
# %% $# # ## ##%$# # %# $$ %#
% %% $$ % % ##$%$# %% #%%
#%$% # #$ ##% %# % %
% % %% $# %#% $%$ $ %
$ # $$$% #$ %$ %## $ #
#% $% %$#% % $ %%$# # $
% ## #%##$ #$#$$ %#%%% % %
$% $% $## %##$$% # %
%# % ##$## ##$#$ % #
$% # % %#$ $$#%# # %
#%% % ## %$##$% # # $
% %$ $ %$ % %
%% # $ % $ #
%%# #% # ## $$ $
%$ $ % # % %
%## #% $ %#$ # #
%#$##% $ #% %$ $
$$ #%$ $ #
# ## # $
#%%$% $%#%$% % $
# $% %$ # % $
# %# # $# %
% # % $# $ $
% %# # #$#% $ %
$ $ # %%%$#$ #$ % #
$ $% $ %% $ $ %
# #$ % #%#% % $ %
% $% ## # % #$ $
% # # %$ % # #
$ # $ # # % %
%$ # $ %$ % $ #
##% #% % # $ %$ %
# ##%#%$$#%#%$$#%# #%$ # % # %
# ## ## $# $ #
% $##$#%$#$$$#$$%% $$ # %
$#%#$#$$#$##$%#$%#$$$$%#$#%%#$%#$$#%%%%$%%$%$#%$##%%$#$$##%#$% #$%$$$$$
```
Sources cited (for greyscale image to ascii conversion):
<http://stevendkay.wordpress.com/2009/09/08/generating-ascii-art-from-photographs-in-python/>
[Answer]
## k4
this is a lazy version that just finds the edges, it doesn't try to find the prevailing shape and pick an appropriate character
the "algo" is just to find all cells that differ from the one to the left or above, then use array-language magic to turn the boolean matrix back into ASCII art
there's a minor hack to pad the beginning of everything with an extra space, or it would consider the left and top to be "edges" -- this way it still does, but i can just drop that off later
```
$ cat o.k
f:{(1_~~':" ",)'x}
g:{(f x)|+f@+x}
h:{-1" +"g@0:`$,/$x;}
h@*.z.x
\\
$
```
more or less the same output as the sample in the spec
here it is on the boomerang/banana:
```
$ cat b.txt
***
****
******
******
******
******
****
***
$ q o.k -q b.txt
+++
++ +
++ +
+ +
+ +
++ ++
+++ +
+++ +
$
```
[Answer]
# Python
This is very simple Python version of "highpass" filter :). It checks whether a pixel is at least surrounded by its 4 sides. This is one of my first Python codes ever so please be subtle...
```
import sys
s = open("ascii.txt",'r').read().split("\n")
def px(x,y):
try:
v = s[x][y]
except IndexError:
v = ' '
return v
def r(x,y):
return '{:<3}'.format(s[x][y-1:y+2])
def v(x,y):
return (px(x,y)==' ' or r(x,y)=='***' and px(x-1,y)=='*' and px(x+1,y)=='*') and ' ' or '*'
for row in range(len(s)):
for cell in range(len(s[row])):
sys.stdout.write(v(row,cell))
print
```
Output:
```
*************
***** *****
****** ***
* * ****
******* * **
**** * **
****** * * **
***** * * *** **
**** * * * * *
** * * * * ***** *
*** * * * * * * **
** * * * * * * **
** * * * ** * * *
* * * * * * * *
** * * * * * * *
* * * *** * * *
* * * ** * *
* * * *** *
** * * *
* * * *
** * * **
* * * **
** * * * *
* * * * * *
** * * * *
** * * * *
** * * ***** * *
** * * ** ** ** * *
** * * * * ** ** * *
* * * ** ** ** ** * *
* * * * **** ** * * * *
* * * * ** **** * * *
* * * *** * * * *
** * * * **** * *
** * * * * * *
* * * * * * *
** ** * * ** * *
* * * * * * ** *
* * * *** *** ** *
* * * *** *** *
* * * ***** **** *
* * * * ** ***** *
* * * * **** * *
* * * * * *
* ** * * * *
* * * * * *
* * * * * *
* ** * * * *
* * * * * *
* ** * * ** *
* ****** * * *
* ***** * ** *
* * * * * *
* * * *** ** *
* * * * ** *
* * * ** * *
* * * ***** * *
* * * * * *
* * * *** * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
************** ** * * *
* * * *
************** * *
* *
************
```
[Answer]
# R
For each point in the matrix, *hide* the character if it's surrounded by asterisks on right, left, top and bottom. This is naive but works very well.
```
text = scan(commandArgs(T)[1], what='raw', sep="\n", quiet=T)
height = length(text); width = max(sapply(text, nchar))
mat_2 = mat = matrix(unlist(strsplit(text, '')), height, width, byrow=T)
for (y in 1:nrow(mat_2)) {
for (x in 1:ncol(mat_2)) {
if (
((x < ncol(mat)) && (mat[y, x + 1] == '*')) # right
&&
((x > 1) && (mat[y, x - 1] == '*')) # left
&&
((y > 1) && (mat[y - 1, x] == '*')) # top
&&
((y < nrow(mat)) && (mat[y + 1, x] == '*')) # bottom
) {
mat_2[y,x] = ' '
}
}
}
for (a in 1:nrow(mat_2)) {
cat(paste(mat_2[a,], collapse=""), "\n")
}
```
Usage: `Rscript script.r input_.txt`
## Output
```
*************
***** *****
****** ***
* * ****
******* * **
**** * **
****** * * **
***** * * *** **
**** * * * * *
** * * * * ***** *
*** * * * * * * **
** * * * * * * **
** * * * ** * * *
* * * * * * * *
** * * * * * * *
* * * *** * * *
* * * ** * *
* * * *** *
** * * *
* * * *
** * * **
* * * **
** * * * *
* * * * * *
** * * * *
** * * * *
** * * ***** * *
** * * ** ** ** * *
** * * * * ** ** * *
* * * ** ** ** ** * *
* * * * **** ** * * * *
* * * * ** **** * * *
* * * *** * * * *
** * * * **** * *
** * * * * * *
* * * * * * *
** ** * * ** * *
* * * * * * ** *
* * * *** *** ** *
* * * *** *** *
* * * ***** **** *
* * * * ** ***** *
* * * * **** * *
* * * * * *
* ** * * * *
* * * * * *
* * * * * *
* ** * * * *
* * * * * *
* ** * * ** *
* ****** * * *
* ***** * ** *
* * * * * *
* * * *** ** *
* * * * ** *
* * * ** * *
* * * ***** * *
* * * * * *
* * * *** * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
************** ** * * *
* * * *
************** * *
* *
************
```
] |
[Question]
[
In Java/.NET/C/JavaScript/etc. you can use ternary-ifs to shorten if-statements.
For example (in Java):
```
// there is a String `s` and an int `i`
if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";
```
Can be shortened with a ternary-if to:
```
s=i<0?"Neg":i>0?"Pos":"Neut";
```
## Challenge:
**Input:** A regular if-else (possible with nesting) that sets a single variable.
**Output:** The converted ternary-if.
## Challenge rules:
* You can assume all if-else cases are possible without brackets (so each if/else-if/else block has a single body).
* You can assume there won't be any spaces, tabs, or new-lines, except for a single space after each `else` (including at `else if`).
* You can assume the variable names used are always a single lowercase letter (`[a-z]`).
* The values given to the variables can be one of:
+ Strings (without spaces/tabs/new-lines), which will be surrounded by double-quotes (i.e. `"Test"`, `"SomeString"`, `"Example_string"`, etc.). You can assume the strings will never contain the substrings `if` or `else`, nor will it contain spaces, tabs, newlines, (escaped) double-quotes, or the character `=`. It can contain the characters `><(){}[];?:!&|`, but will be in the printable ASCII range only (`['!' (33), '~' (126)]`).
+ Integers (i.e. `0`, `123`, `-55`, etc.)
+ Decimals (i.e. `0.0`, `0.123`, `-55.55`, etc.)
* The values won't ever be mixed. So all variables assigned are integers, and not some are integers and some are strings.
* The conditions within parenthesis can contain the following characters `=<>!+-/*%&|[]`, `a-z`, `0-9`. You can assume there won't be any inner parenthesis, and you can also assume there won't be any (confusing) fields of more than one character used (like `if(if<0)`).
* You can assume there won't be any short-cuts like `i*=10` instead of `i=i*10`.
* You won't have to handle dangling `else` cases, so all `if` can be paired up with an `else`. I.e. `if(a)if(b)r=0;else r=1;` isn't a possible input-case. `if(a)if(b)r=0;else r=1;else r=2;` or `if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;` are however.
* I/O is flexible. Input and Output can be a string, list of characters, read from STDIN, output to STDOUT, etc. Your call.
* All ternaries will have a right associativity, as is the standard in most languages ([but not in for example PHP](https://stackoverflow.com/a/38231137/1682559)).
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if possible.
## Test cases:
```
Input: if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";
Output: s=i<0?"Neg":i>0?"Pos":"Neut";
Input: if(i%2<1)r=10;else r=20;
Output: r=i%2<1?10:20;
Input: if(n<10)if(m<0)i=0;else i=10;else if(m<0)i=-1;else i=1;
Output: i=n<10?m<0?0:10:m<0?-1:1;
Input: if(i==1)i=0.0;else i=0.25;
Output: i=i==1?0.0:0.25;
Input: if(!a)if(b)r=0;else r=1;else r=2;
Output: r=!a?b?0:1:2;
Input: if(a)if(b)r=0;else r=1;else if(c)r=2;else r=3;
Output: r=a?b?0:1:c?2:3;
Input: if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;
Output: r=a&&b?0:a&&!b?1:-1;
Input: if(i[0]>0)if(j>0)if(q>0)r="q";else r="j";else r="i";else r="other";
Output: r=i[0]>0?j>0?q>0?"q":"j":"i":"other";
Input: if(i>0)r="i";else if(j>0)r="j";else if(q>0)r="q";else r="other";
Output: r=i>0?"i":j>0?"j":q>0?"q":"other";
Input: if(a>0)if(a<2)x="one";else if(a<3)x="two";else if(a<4)x="three";else x="other";else x="other";
Output: x=a>0?a<2?"one":a<3?"two":a<4?"three":"other":"other";
Input: if(b[0]<=b[1])q=5;else if(b[0]==null)q=0;else q=-10;
Output: q=b[0]<=b[1]?5:b[0]==null?0:-10;
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~126~~ ~~121~~ ~~120~~ ~~114~~ 100 bytes
```
lambda s:findall(' (.=)',s)[0]+sub('if.(.*?)\)(.=)?',r'\1?',sub('.{5} (.=)?',':',s))
from re import*
```
[Try it online!](https://tio.run/##fZPBbuIwEIbvPEWItE3cligO7cWNO@oLVJX2uPQQICmOIAEn1VKt9tnpjJM43WL2gGz@mfn@X4PZf7SbukpOhVycttluuc68RhSqWmfbbRh4YSRZcNuwX/HrTfO@DANVRGF0DWzBqATBrQ4WHA9TjP7c//V6PRA0xyaFrneezj2129e6vT49Pf@UfLLXqmq9gnihSmPWSP85f/Mf8m2Drag9Gu2lbnrNNLy3/kPAJqrwkCIMI2gkzoOZFjgFZkYMzZ3Rv3Y/kpQzLXnckbVM4jOqlqYNeCyo6sBUKY8ZnjtMr2TPUpZqKzNuS2cuShIFsBFigVZ0mXHB3bml5OQUWa84Su4dTGoEbBNd3YGaZpR8iUuwO@B2GY5dTDNYUkKROHEXaSivGCF7ee5gD@gVJGLuxl9dfYF3wpQUm3nGXWAcQ7JpBi5mF7aKL/vR/JBldxzw0NI/@APcL8erGq91u8m173o4hgiIgwO9xwO@xhI/Cj/DkCtI56vG/0DZKeWonGe7nIKs0ZJikL2N8p8IWbeBLE3YEdFVPjpn6Zy09nf9Vbsz2kbnQ@fRJvr29XvAo0QzQCcwPgL5YOh4u4OeOYQdQ58@AQ "Python 2 – Try It Online")
---
Saved:
* -1 byte, thanks to Kevin Cruijssen
[Answer]
# [Perl 5](https://www.perl.org/) -p, ~~50~~ ~~49~~ 48 bytes
```
s/if.(.*?)\)(.=)/\2\1?/g;s/.if./?/g;s/;.{6}=/:/g
```
[Try it online!](https://tio.run/##dY7dCoIwGEDve4oQAhe4Ofu5aPv0DaQH8MaLqQNzshkF0au3dP4URFfbd853xlqh64O1hsgC@3iboAz5GBDJoowmpGSG4N6Q8crw4/gEciKltbLwJQ@RAS8VpcdEbcR6YAAOslRcuwn341kZj63@NbFjbmcOxtwVm4hTpIGGo9QQhU40nIaoPy/9kxImK5e9xQR0Ua7LY5flPEJ38FQjPj/J@W5g3U19s71jlRbz5pB1ldA/40u1nVSNsUH7Bg "Perl 5 – Try It Online")
The 48 byte version is inspired by Neil's Retina answer.
### Explanation
```
# Replace "if(e1)if(e2)x=" with "x=e1)if(e2?"
s/if.(.*?)\)(.=)/\2\1?/g;
# Replace ")if(" with "?"
s/.if./?/g;
# Replace ";else x=" with ":"
s/;.{6}=/:/g
```
### Old 49 byte solution
```
s/.{5} (.=)?/:/g;s/if.(.*?)\)(.=)?/\1?/g;$_=$2.$_
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes
```
+r`if.(.*?)\)(.=)
$2$1?
;.{6}=
:
```
[Try it online!](https://tio.run/##dZBNTsMwEIX3OQW1ShWDatkpZUE87Q0Q@1KpDnKpo5AoTioqIc4e/FcnArGayffevIlHy17VYhju9UEdSUrutvgVpwRwMs/mbJvk5OvxG5KnYVDHVHGKO0DP8h3lsurkjWUbx16aLjBnOPcoT6x6m3GGNTDqRQ0ZdULNGcWmfphIBUFV0ReVJYuSDwRgdoDEEUqytZNmwgYWZltcxuJW5/jXYPAbtq6AV96@WEzMHswsibHL8FM7ut@455S@tKZoQC26GlE5tmpsm/4kdbiUH1HjZUtPypH8jZ0ECL9a8AxfjFDLcU7wlWX9ZzNlD46dtLw6LzHv16eNL8wbORQ7tsctrGOMxQD1uaoMDpdqzV1ia7of "Retina 0.8.2 – Try It Online") Explanation:
```
r`if.(.*?)\)(.=)
$2$1?
```
Handle an `if` immediately before an assignment by moving the assignment before the condition and appending a `?`. The stage is matched right-to-left to ensure we get the if closest to the assignment, while the `\)` ensures that we don't match `else` by mistake.
```
+
```
Repeat the stage to take care of nested `if`s.
```
;.{6}=
:
```
Any remaining assignments are `else`s so replace the `;else ?=` with a `:`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~72~~ 71 bytes
```
->s{$a=$2while s.gsub!(/if.(.*?)\)(.=)?(.*?);\w* (.=)?/,'\1?\3:');$a+s}
```
[Try it online!](https://tio.run/##dZRfk5owFMXf/RTI2IW4yD@3L5GYmX3rdGbtuzidYKPGcRUJjLarn929CQKi2wckOTn3d24kkBXJ38uCXAZj@dFjpBceVmLDDekuZZF0bU8sXNvtUxQj2yWI6vEoPvQNPfUcKw5oPMQWGvXYszxfci7z33MmuSRR9Dp5dWW6EbnR8zo/tmmRY8MwxMIWkY8kMd/40hzxjeRaG2vt105eNW0ocnPUmRR5WSsJVFJdh8FPtRtXtnbEtzAKUEYCv6RlJPRvSBnRBhr4WOmt0m0U@Aju79ClINd6UZPqlUFQL92QBVH1FCzUx4BXg0GAg/v@CAkU3a35vht@b3GUhYIBlyut8i5THSawwXp/Qb3R1j67jCaqExzeIf5LAHmOFOYqD1u8CjenIR7eI5@eboCl0FVK3dsgaMOgAGjaRgM8ePiXpv5srB/Gurzt4ZYRc29WQHPdDEUz3OUrnpntB65ZFEB0r87OHk7OGi4BV2Vvh5dZojmj61JZN8pjP18lqziIUdEqso7/MpaVO2VRiI6A2/ImjUVDpeWH3a32orVVxivnse7ibto0dSQQQyGD6gQMZKq5MHqhV1rVYNMovNGdjlDNkuZNd5cZT22v3AN8IVDPQ@47Sz9O7MSm6hPS92bnzk5nP9Zde3osdElZWAa6/0Rql4zK5CQnmEljamoHjvM4N5@ZY7J5XrDNdb6Ysplj8mPK5zn/g5WUOLZSCUkQtSY/LWy9wa9jWbPz5RM "Ruby – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 119 116 bytes
Almost entirely pure regex solution, chopped and changed a bit from a couple of the other answers.
*-3 bytes thanks to some more regex trickery from Kevin*
```
s->s.replaceAll(".*(.=).*","$1$0").replaceAll("if.(.*?)\\)","$1?").replaceAll("([ ?]).=","$1").replace(";else ",":")
```
[Try it online!](https://tio.run/##lZLfboIwFMbvfYqucYaa0QBuN5Nq9gAzS3YpXlSsWoagbXUui8/OWqgM9y/shnJ@p@c732mb0AN1k8VLEadUSvBIefbeAYBniokljRmYmBCAZyV4tgKxY38kGmp@6uiPVFTxGExABggopDuSWLBtqosf0tSBuO9ggnAf3sCu3/UgusjyJXZwf4yiCJUbxl/yzhSMZwiTMvmZc@CQpZIBje8hKobGx3Y/T7UPa@eQ8wXY6HGs4@kMUGRneZOKbXC@V3irUyrNnAzHxovDQw9JEsEJW0W2haGjij7l8kyrTXulY4jKs/hb9zoIfSSI71XlggReq8Is9D2k1402xomt5rVOnXH9OtXOECG@EcS1pIeDu1alV9QYmutp6mH8eqpWCr8KaBwjo2LxoJ1cr9cQq8CVIbUtt@WhTL3ZqDzupFp2ehH6pnfnazdB0gx4M8jVmom2L8JK88Y7SyxLGuxHC/9pRKtRaBigoynNWEOdhoOSqtf8gt5WdC1YvfvY6PsNWCOnzqn4AA "Java (JDK) – Try It Online")
**Explanation**
```
s-> // Lambda function taking a String
s.replaceAll(".*(.=).*","$1$0") // Find assigned variable and append to start of String
.replaceAll("if.(.*?)\\)","$1?") // Replace any 'if' statements with their condition
// followed by '?'
.replaceAll("([? ]).=","$1") // Remove all assignments after a '?' or space
.replace(";else ",":"); // Simple replace (no regex) to remove 'else' statements
```
[Answer]
# [Kakoune v2018.09.04](https://kakoune.org/), 43 38 37 bytes
```
xs\w=(?!=)<ret>d<a-h>Psif.<ret>df);r?xs;else<space><ret>c:<esc>
```
Explanation:
Kakoune is a multiple selection based, modal editor, inspired by Vim.
1. `x` select the whole line
2. `s` ... `<ret>` filter the selection with the regular expression `\w=(?!=)`, which matches all variable assignments, and doesn't match `==` comparisons
3. `d` delete each selection and put its contents in the default register
4. `<a-h>` extend all selections to the beginning of their line
5. `P` paste the content of the default register before each selection
6. `s` ... `<ret>` filter the selection with the regular expression `if.`
7. `d` delete each selection
8. `f` extend each selection forward to the next `)`
9. `;` reduce each selection to its cursor
10. `r` replace each character of each selection with `?`
11. `x` select the whole line
12. `s` ... `<ret>` filter the selection with `;else<space>`
13. `c` ... `<esc>` clear each selection and replace it with `:`
### animation of the code on a test case:
[](https://i.stack.imgur.com/fh9tp.gif)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~386~~ ~~375~~ ~~216~~ ~~196~~ 189 bytes
Look ma, no regex!
```
import StdEnv,Data.List
?[_,'=':b]= $b
?b= $b
$['if(':s]#(h,[_:t])=span((<>)')')s
=h++['?': ?t]
$[';else ':s]=[':': ?s]
$[a:b]|b>[]=[a: $b]=b
@s=hd[[v,e: $s]\\['else ',v,e=:'=':_]<-tails s]
```
[Try it online!](https://tio.run/##JY5Ni8IwEIbv/RWBFdJiK@7CXqJjPehhwcOCxxjKpB82kLbiRGFhf/tmE8scZuaB96O2LY5@mJqHbdmAZvRmuE13x86uOY7P/IAOVydDLilllXPgQitgC52U@rUWkpsu5YLUW9rnshJOZUA3HNN0u8t4GEqgXy4lL7lgpVNRsWkttSyKQHIROUWOwftX72SgKIK5Ap3sCfpGymfeBkLqcpF8FucBgYiFKrUtHBpLjJQ/Owzlge3Zq5gBeM8MrFfrOTOeH58brvxf3Vm8ki@@Tv7wM@Jg6vn5tui66T74Qv8D "Clean – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
s=>(p=s.replace(/(?:if.(.*?)\)|;.*? )(.=)?/g,(_,t,v)=>(V=v||V,t)?t+'?':':'),V+p)
```
[Try it online!](https://tio.run/##fZPBUsIwEIbvPoV0RptoW5uil9Cwb@B44qKOU2vAdJBCW5ED746btKSoqcN0Ev7sfv/fJRTZNqvzSq2bcFW@ycNcHGoxJWtRR5VcL7NckhsCXM0jEl0BfaL7Ca7nlESCws0iIC9BE2wptszEdr@fBQ2F5toHn@OHBrPrNT3k5aoulzJalgsyJ76aE5XGtBbevVx4E7ms5bnWpkZ7KOtOMwWfjTfxKZ2cnUL8WiABTD/HPjBd3Jb/rO4sL5KU0UqwuKVXIokd5EqYQmAxN@cu1CplMcX1A99CiY6nLNmehMweOZyU0BzAUog52ulNyDgbyi8E026R9Yuj5M7J1aWAhbyrcOFGmX6DVxyInQezg3HOZZTBq07KkwHkIBHlnGpsJ4@d/CM@h4SPhywuL08MWmGkFZs9ZG44NiLdlAPj4eCUH@Pnqflxi3bZ4FIJb@MdDbyi36p@WzbvsvLcF8owAYGw0Xd1gze1wEfhY9ucYVpv1f9HilYpeuVvvv@SaHu01VF0BBvn3xhZO4ksTegO8SvZu2fpWGvNV3mq3RrtvZLHyp1N9evr35A7gXaAXmCcODqA4ePuFjrqMfBp8MM3 "JavaScript (Node.js) – Try It Online")
Thanks to Kevin Cruijssen, 2 bytes saved.
] |
[Question]
[
Many digital clocks display the time using simplified digits comprised of only seven different lights that are either on or off:
[](https://i.stack.imgur.com/kfYal.png)
When mirrored horizontally, the digits `018` don't change because they are symmetrical. Also, the digits `2` and `5` get swapped, `2` becoming `5` and vice versa. All the other digits become invalid when mirrored.
Thus, given a 24-hour digital clock, there are many clock readings such that the mirrored image of the digital display is also a valid clock reading. Your task is to output all such clock readings along with the mirrored readings.
For example, `22:21` becomes `15:55`, and `00:15` becomes `21:00`. On the other hand, `12:34` or `16:27` are no longer valid when mirrored (digits `34679` become invalid), and neither are `22:22` or `18:21`, because, as there are only 24 hours in a day and 60 minutes in an hour, no sane clock would display `55:55` or `12:81`.
### Task
Write a program or a function that takes no input and outputs all valid pairs in ascending order as shown below:
```
00:00 - 00:00
00:01 - 10:00
00:05 - 20:00
00:10 - 01:00
00:11 - 11:00
00:15 - 21:00
00:20 - 05:00
00:21 - 15:00
00:50 - 02:00
00:51 - 12:00
00:55 - 22:00
01:00 - 00:10
01:01 - 10:10
01:05 - 20:10
01:10 - 01:10
01:11 - 11:10
01:15 - 21:10
01:20 - 05:10
01:21 - 15:10
01:50 - 02:10
01:51 - 12:10
01:55 - 22:10
02:00 - 00:50
02:01 - 10:50
02:05 - 20:50
02:10 - 01:50
02:11 - 11:50
02:15 - 21:50
02:20 - 05:50
02:21 - 15:50
02:50 - 02:50
02:51 - 12:50
02:55 - 22:50
05:00 - 00:20
05:01 - 10:20
05:05 - 20:20
05:10 - 01:20
05:11 - 11:20
05:15 - 21:20
05:20 - 05:20
05:21 - 15:20
05:50 - 02:20
05:51 - 12:20
05:55 - 22:20
10:00 - 00:01
10:01 - 10:01
10:05 - 20:01
10:10 - 01:01
10:11 - 11:01
10:15 - 21:01
10:20 - 05:01
10:21 - 15:01
10:50 - 02:01
10:51 - 12:01
10:55 - 22:01
11:00 - 00:11
11:01 - 10:11
11:05 - 20:11
11:10 - 01:11
11:11 - 11:11
11:15 - 21:11
11:20 - 05:11
11:21 - 15:11
11:50 - 02:11
11:51 - 12:11
11:55 - 22:11
12:00 - 00:51
12:01 - 10:51
12:05 - 20:51
12:10 - 01:51
12:11 - 11:51
12:15 - 21:51
12:20 - 05:51
12:21 - 15:51
12:50 - 02:51
12:51 - 12:51
12:55 - 22:51
15:00 - 00:21
15:01 - 10:21
15:05 - 20:21
15:10 - 01:21
15:11 - 11:21
15:15 - 21:21
15:20 - 05:21
15:21 - 15:21
15:50 - 02:21
15:51 - 12:21
15:55 - 22:21
20:00 - 00:05
20:01 - 10:05
20:05 - 20:05
20:10 - 01:05
20:11 - 11:05
20:15 - 21:05
20:20 - 05:05
20:21 - 15:05
20:50 - 02:05
20:51 - 12:05
20:55 - 22:05
21:00 - 00:15
21:01 - 10:15
21:05 - 20:15
21:10 - 01:15
21:11 - 11:15
21:15 - 21:15
21:20 - 05:15
21:21 - 15:15
21:50 - 02:15
21:51 - 12:15
21:55 - 22:15
22:00 - 00:55
22:01 - 10:55
22:05 - 20:55
22:10 - 01:55
22:11 - 11:55
22:15 - 21:55
22:20 - 05:55
22:21 - 15:55
22:50 - 02:55
22:51 - 12:55
22:55 - 22:55
```
A trailing or a leading newline is allowed. Having a few spaces directly before a linefeed is also allowed. The times must be in format `hh:mm`, padded with zeros when necessary.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. As usual, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~187~~ ~~180~~ ~~178~~ 177 bytes
```
R=range(11)
for t in['0000111122201250125012'[j::11]+':'+'0001112255501501501015'[i::11]for i in R for j in R]:print t+' - '+''.join(map(dict(zip('0125:','0152:')).get,t))[::-1]
```
[Try it online!](https://tio.run/##LY1LCsMwDET3PYV2ssmHSOCNoJfI1mQR2jR1oI4J3qSXd5Wkgz4DGp7Snt9r5FL6@zbGeTJE9vZaN8gQosdORSpm7ojdv9EvIkRDhYIVXhFm5/R2lQ704cwcrKAs6OGwy2kHSVuIGXKF0IAysF3WEM1nTOYZHtl8QzJ4fBOsdTsWtLadp1xna71IQ0MpPw "Python 2 – Try It Online")
Thanks for +1 Kevin Cruijssen.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 84 bytesSBCS
Complete program outputting to STDOUT. Requires `⎕IO` (**I**ndex **O**rigin) to be `0` which is default on many systems.
```
{0::⋄∧/23 59≥⍎¨(':'≠t)⊆t←⌽'015xx2xx8x:'[⎕D⍳i←∊⍺':'⍵]:⎕←1↓⍕i'-'t}⌿1↓¨⍕¨100+0 60⊤⍳1440
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862n3/VxtYWT3qbnnUsVzfyFjB1PJR59JHvX2HVmioW6k/6lxQovmoq60EqPxRz151A0PTigqjigqLCiv1aKA5Lo96N2eC5Dq6HvXuAmno3RprBZQAihk@apv8qHdqprqueknto579IP6hFUCRQysMDQy0DRTMDB51LQEaYGhiYvAf6JT/vgA "APL (Dyalog Unicode) – Try It Online")
`⍳1440` that many **ɩ**ntegers
`0 60⊤` convert to mixed-base ∞,60
`100+` add 100 (this pads the needed 0s)
`⍕¨` format (stringify) each
`1↓¨` drop the first character from each (this removes the leading 1s)
`{`…`}⌿` apply the following anonymous function column-wise (`⍺` is top hour, `⍵` is minute)
`0::` if any error happens, return nothing
`⋄` try:
`'015xx2xx8x:'[`…`]` index this string with:
`∊⍺':'⍵` the **ϵ**nlisted (flattened) list of hour, colon, minute
`i←` stored in `i` (for **i**nput)
`⎕D⍳` **ɩ**ndices of each character in the list of **D**igits
`⌽` reverse that
`t←` store as `t` (for **t**ime)
`(`…`)⊆` group runs where:
`':'≠t` colon differs from `t`
`⍎¨` execute (evaluate) each
`23 59≥` Boolean for each whether they are less than or equal to 23 and 59 respectively
`∧/` are both true?
`:` if so, then:
`⍕i'-'t` the formatted (space-separated) list of input, dash, time
`1↓` drop the first (space)
`⎕←` output to STDOUT
[Answer]
# [Retina](https://github.com/m-ender/retina), 57 bytes
```
-
+m`^.{3,9}$
0$&0¶1$&1¶2$&5¶5$&2
A`\b2?5
\b\d.
$&:
O`
```
[Try it online!](https://tio.run/##K0otycxL/P@fS0FXgUs7NyFOr9pYx7JWhctARc3g0DZDFTXDQ9uMVNRMD20zVVEz4nJMiEkysjflikmKSdHjUlGz4vJP@P8fAA "Retina – Try It Online") Explanation:
```
-
```
Insert the separator.
```
+m`^.{3,9}$
0$&0¶1$&1¶2$&5¶5$&2
```
Generate all possible sets of four mirrored digits.
```
A`\b2?5
```
Delete those with illegal hours.
```
\b\d.
$&:
```
Insert the colons.
```
O`
```
Sort into order.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~279~~ ~~277~~ 255 bytes
```
for h in range(1440):
q=[[[0,(a+"52")[(a=="2")+(a=="5")*2]][a in"01825"]for a in c]for c in[("%02d"%e)[::-1]for e in[h%60,h/60]]]
if all(q[0]+q[1]):
z=[int(''.join(j))for j in q]
if(z[1]<60)*(z[0]<24):print"%02d:%02d - %02d:%02d"%(h/60,h%60,z[0],z[1])
```
[Try it online!](https://tio.run/##PY7BboMwDIbP5SmiSKh2oVuIAE1ReRLLh6iDEVSFgnpZX57FOexifZb9@ffz9zWv0R7HtO5qViGq3cefEZq2NegKtQ1EZGrwle6sRgI/DDpBlaHTeLHM5JOoTfNlO81ySHp1z3hPSKBLY791OSI5d23yYJTBXPamnj97w8yFCpPyjwdsZLjaqOH0wOk9UIgvOJ8/ljVEWBBFXiRg4@IUJninzVtv8JLI8M226J57cnKmk6Ku6p91CZJX52QRavHxOP4A "Python 2 – Try It Online")
# Credits
* 279 bytes reduced to 256 by [dylnan](https://codegolf.stackexchange.com/users/75553/dylnan).
* 256 bytes reduced to 255 by [FlipTrack](https://codegolf.stackexchange.com/users/60919/fliptack).
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~269~~ ... ~~172~~ 170 bytes
```
import StdEnv
?n=toChar n+'0'
$c|c<2=c=7-c
n=[0,1,2,5]
t=flatlines[u++[' - ':v]\\[u,v]<-[[map?[a,b,10,x,y],map?[$y,$x,10,$b,$a]]\\a<-n,b<-n,x<-n,y<-n]|['23:59']>=max u v]
```
[Try it online!](https://tio.run/##HY6xCsIwFEX3fkWGQIa@QK2IKI0O6iC4OcYMr7FqoXkVTUsLfrsxdTlwD1zutU2FFFx77ZqKOawp1O7Zvjw7@@uB@mRLyre7B74YpSITCbcfW@TKqqW0CSmdwQxyWJjEq1uDvqmpeusuTbVgkol1by4X3UFvCqm1w@dWI5Qwy2CA0cBf8BH4MCleAkcTC1hIgnLCMGGMMB8t8vl6sRJmoxwOrGO9CWeP8aliPnxtXL@/gzyewn4kdLWNofwB "Clean – Try It Online")
Ungolfed:
```
import StdEnv
numeral n = toChar (n+48)
mirror 2 = 5
mirror 5 = 2
mirror c = c
digits = [0, 1, 2, 5]
times
= flatlines [ // flatten with interspersed newlines
original ++ [' - ' : reflection] // insert separator
\\ // generate all pairs of times and their mirrored copies
[original, reflection] <- [
[map numeral [a, b, 10, x, y], map (numeral o mirror) [y, x, 10, b, a]]
\\ // generate every combination of display digits
a <- digits,
b <- digits,
x <- digits,
y <- digits
]
| ['23:59'] >= max original reflection // make sure both times actually exist
]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 34 bytes
```
0125DâDâεÂ5n‡í)}ʒ€н25‹P}':ý… - ý»
```
[Try it online!](https://tio.run/##AT8AwP8wNWFiMWX//zAxMjVEw6JEw6LOtcOCNW7DguKAocOtKX3KkuKCrNC9MjXigLlQfSc6w73igKYgLSDDvcK7//8 "05AB1E – Try It Online")
**Explanation**
```
0125 # push "0125"
Dâ # cartesian product with itself
Dâ # cartesian product with itself
ε } # apply to each
 # bifurcate
5n # push 25 bifurcated
‡ # transliterate
í # reverse each
) # wrap in a list
ʒ } # filter each on
€н # head of each
25‹ # less than 25
P # product
':ý # merge on ":"
… - ý # merge on " - "
» # join on newlines
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 48 bytes
```
Lj\:c2bjf!:T"5.:|25:"0mj" - ",ydyX_d`25)^"0125"4
```
[Try it online!](https://tio.run/##K6gsyfj/3ycrxirZKCkrTdEqRMlUz6rGyNRKySA3S0lBV0FJpzKlMiI@JcHIVDNOycDQyFTJ5P9/AA "Pyth – Try It Online")
Generates all possible combinations of `0125` and then manipulates them into the times. These are in the correct order because they are generated in lexicographic order. Finally, this filters out the extra invalid times by removing lines that match the regex `5.:` or `25:`. Sadly, it doesn't seem like compression works nicely on any of the strings that this program uses, unless I've made an error or oversight.
[Answer]
# [Perl 5](https://www.perl.org/), 147 bytes
```
map{$h=0 x($_<10).$_;map{$_="0$_"if$_<10;say"$h:$_ - $q:$i"if($i=reverse$h=~y/25/52/r)<60&&"$h$_"!~/[34679]/&&($q=reverse y/25/52/r)<24}0..59}0..23
```
[Try it online!](https://tio.run/##TYzfCoIwGMVfZcnH0Au3z@kM/z1CTxAxvFg4sNQZkUQ@emsJQTfn4nd@54za9tK5Szs@oWuQPEJQdYIRA1VtUDUBggrMeePV3C4BdCUoEhOYSjC@CcE0Vt@1nbX/WBcuJJeC26jOkVKv@/1u5cc0y/fFiVMawvQbkD9bZC9kTBbfFKlz72G8meE6u/ggGSb4AQ "Perl 5 – Try It Online")
[Answer]
# [Japt v2](https://github.com/ETHproductions/japt) (+ `-R`), 51 bytes
```
G²Çs4 ùT4 i':2î+" - "+Zw r\d_^Z>1})r3,5Ãkf/5.|25):
```
[Test it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=R7LHczQg+VQ0IGknOjLDrisiIC0gIitadyByXGRfXlo+MX0pcjMsNX0ga2YvNS58MjUpOg==&input=LVI=)
### Explanation
```
G²Ç s4 ùT4 i':2à ® +" - "+Zw r\d_ ^Z>1})r3,5à kf/5.|25):
G²oZ{Zs4 ùT4 i':2} mZ{Z+" - "+Zw r\dZ{Z^Z>1})r3,5} kf/5.|25):/ Ungolfed
G² Calculate 16**2, or 256.
oZ{ } Create the range [0...256) and map each integer Z to:
Zs4 Convert Z to a base-4 string. [0, 1, 2, 3, 10, ..., 3331, 3332, 3333]
ùT4 Pad-left with 0's to length 4. [0000, 0001, 0002, ..., 3331, 3332, 3333]
i':2 Insert a colon at index 2. [00:00, 00:01, 00:02, ..., 33:31, 33:32, 33:33]
mZ{ } Map each string Z in the resulting array to:
Zw r\dZ{ } Reverse Z, and replace each digit Z' with
Z^Z>1 Z' xor'd with (Z>1). This turns 2 to 3 and vice versa.
We now have [00:00, 10:00, 30:00, 20:00, 01:00, ..., 12:22, 32:22, 22:22]
Z+" - "+ Append this to Z with " - " in between. This gives
[00:00 - 00:00, 00:01 - 10:00, 00:02 - 30:00, ..., 33:32 - 32:22, 33:33 - 22:22]
r3,5 Replace all 3s in the result with 5s.
[00:00 - 00:00, 00:01 - 10:00, 00:02 - 50:00, ..., 55:52 - 52:22, 55:55 - 22:22]
k Remove all results that
f/5.|25):/ match the regex /(5.|25):/g. This removes times with impossible hours.
Implicit: output result of last expression, joined with newlines (-R)
```
[Answer]
# JavaScript (ES6), 142 bytes
```
f=(n=0)=>n<176?(s=(g=n=>d[n>>2]+d[n&3])(n%4*4|n/4&3,d='0152')+':'+g(n>>6|(n/4&12)),s<'25'?g(n>>4,d='0125')+`:${g(n&15)} - ${s}
`:'')+f(n+1):''
```
[Try it online!](https://tio.run/##JYrLDoIwFET3fgULpPdaUFoeJoTWDzEkEF7RkIuxxg3w7bXqambOmXvzbkz7vD1eEc1db@2ggFSMSlMpzvkFjIJRkdLdlbSWFXcZJBUC7dNDutIpDZKwUywWmWTIWcH4CO6Zr/B1QiKGpmQyY5cfT/9nt5HXhb84GIgMNy/y/MVsu7pgzgxAXKCrtp3JzFN/nOYRBkC0Hw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes
```
F012F0125F0125F015¿›‹⁺ικ25⁼⁺λμ25«ικ:λμ - F⟦μλ3κι⟧§015::2Iν⸿
```
[Try it online!](https://tio.run/##dY4xC8IwEIVn/RXHTRdIQSsudRIRERy6q0OoEUPTFpNUBPG3x7Ra4@L2He/j3SsuwhSN0N6fGwOEk2mKDL48/3d0rM5AGyOFk4Z20lrKdWtJcSgZB@x0DutrK/Qn0RyqIWEMHuNRblTtSLHFgGVEzDAeOmL1o0ACvdSv2lccwgucYVjAQR0ZvLWl29Ynee9nZ1ka4pWwjuowIlYdTNf09N4nN/0C "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F012F0125F0125F015
```
Create four nested loops for the unmirrored digits.
```
¿›‹⁺ικ25⁼⁺λμ25«
```
Check that neither the hours nor minutes is 25. (Mirroring the 25 minutes will result in 25 hours, so that's a no-go.)
```
ικ:λμ -
```
Print the unmirrored time.
```
F⟦μλ3κι⟧§015::2Iν⸿
```
Print the mirrored time by converting the reversed digits (or `3` for the colon) from string to integer and looking them up in a translation table.
Alternatively, also for 59 bytes:
```
F¹¹F¹⁶¿⁻¹¹κ¿⁻²﹪κ⁴«≔⟦÷ι⁴﹪ι⁴¦⁴÷κ⁴﹪κ⁴⟧θFθ§0125:λ - F⮌θ§0152:λ⸿
```
[Try it online!](https://tio.run/##bY49C8IwFEXn9lc8MiWQgimtg04Flw4FcVWH0qYaGhKatEUQf3vsh1RFt3fvPQdecc1NoXPpXKUNYMYIzMeagKgAZ0J1dqgp1OSzCSlkuuykxjWFiAzb3fcSa8VF4WOq2p3oRcmxGMcFfaWIwpuov4gpnSk0ZOt70yMNgb0RqsVJm6qS3zBasTDeIAqSjNA8IggALc6B99xYPrh/5Dj8kU9mdB/OuaCXTw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F¹¹F¹⁶
```
Create loops for the hours and minutes.
```
¿⁻¹¹κ¿⁻²﹪κ⁴«
```
Exclude `25` and also any minutes ending in `2`.
```
≔⟦÷ι⁴﹪ι⁴¦⁴÷κ⁴﹪κ⁴⟧θ
```
Convert the hours and minutes to base 4.
```
Fθ§0125:λ
```
Print the digits looked up in a translation table.
```
-
```
Print the separator.
```
F⮌θ§0152:λ⸿
```
Print the reversed digits looked up in a mirrored translation table.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~72~~ ~~66~~ ~~62~~ 55 bytes
```
®ṢiЀUị®
“0152:”©ṢṖp`⁺ḣ176j€“:”µ;"Ç€⁾25ẇ$ÐṂœs€2j€“ - ”Y
```
[Try it online!](https://tio.run/##y0rNyan8///Quoc7F2UenvCoaU3ow93dh9ZxPWqYY2BoamT1qGHuoZVAyYc7pxUkPGrc9XDHYkNzsyygQqAKsOxWa6XD7SB@4z4j04e72lUOT3i4s@no5GKgmBFUoYKuAlBp5P//AA "Jelly – Try It Online")
Niladic program. I got the double product of `'0125'` idea from the [05AB1E answer by Emigna](https://codegolf.stackexchange.com/a/151166/75553) but the rest I did without consulting that since the languages diverge after that. There are probably opportunities for golfing, possibly by a lot.
**Explanation**
The program works as follows:
* Take all products of length four of the list of characters `'0125'` with `“0152:”©ṢṖp`⁺`. `©` copies the string `'0152:'` to the register for use later. `ṢṖ` sorts then pops the last element of the string → `'0125'`. `⁺` duplicates the product link.
* `ḣ176` removes any times with format `25xx` or `5xxx` (not valid hours).
* `j€“:”` joins each pair of digits with a `':'`. e.g. `['05'],['21']]` → `'05:12'`.
* `Ç€` applies the first link to each of these times. It finds the index of each character in the string `'0125:'` then for each of those indices gets the character in the string `'0152:'` and reverses it. This is the mirror operation (reversing and swapping `2`s and `5`s).
* `µ;"` concatenates the original time with the mirrored time → `'05:2115:20'`
* `⁾25ẇ$ÐṂ` filters out the times with the substring `'25'`. This catches any time pairs with mirrored half `25:xx` or `5x:xx`. *Note*: I don't know why the `$` is necessary. Perhaps someone could golf it out with the proper syntax but I'm not sure.
* Split each of these times into two halves (`œs€2`) then join them with the string `' - '` (`j€“ - ”`). `'05:2115:20'` → `'05:21 - 15:20'`.
* Finally, `Y` joins all the strings with a newline and everything is implicitly printed.
**Old versions**
62 bytes
```
i@€®ị“:0152”
“:0125”©Ḋp`⁺ḣ176j€“:”µ,"UÇ€$F€⁾25ẇ$ÐṂœs€2j€“ - ”Y
```
[Try it online!](https://tio.run/##y0rNyan8/z/T4VHTmkPrHu7uftQwx8rA0NToUcNcLgjbyBTIPrTy4Y6ugoRHjbse7lhsaG6WBVQPkgZJbdVRCj3cDhRQcQOJNu4zMn24q13l8ISHO5uOTi4GihlBlSvoKgA1RP7/DwA "Jelly – Try It Online")
66 bytes
```
“0125”
i@€¢ị“0152”
UṚÇ€
Ñp`⁺ḣ176µ,"Ç€j€€“:”j€“ - ”¹⁾2 ẇ$ÐṂ⁾25ẇ$ÐṂY
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxwDQyPTRw1zuTIdHjWtObTo4e5usKCpEUgw9OHOWYfbgRJchycWJDxq3PVwx2JDc7NDW3WUwMJZQAxCDXOsgMqzIEwFXQUg59DOR437jBQe7mpXOTzh4c4mEM8Uzov8/x8A "Jelly – Try It Online")
72 bytes
```
⁾25
i@€¢µẋ@€¢ṙ"
Ṛµ;@""Ç€Ḣ€€
“0125”p`⁺j€“:”ḣ176µ,"Ç€j€“ - ”¹⁾2 ẇ$ÐṂÑẇ$ÐṂY
```
[Try it online!](https://tio.run/##y0rNyan8//9R4z4jU65Mh0dNaw4tOrT14a5uCPPhzplKXA93zjq01dpBSelwO1Dw4Y5FQBKIuB41zDEwNDJ91DC3IOFR464skHDDHCsg/@GOxYbmZoe26kC0QGUUdBWAcod2gixTeLirXeXwhIc7mw5PhDMj//8HAA "Jelly – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~175~~ 174 bytes
One off thanks to @Steadybox.
```
char*p,s[14],*e;f(t){for(t=0;sprintf(p=s,"%02d:%02d -",t/100,t%100),t<2400;)if(t++%10^2&&!strpbrk(s,"346789")&&t%100^26){for(e=s+12;p<e;p++)*e--=*p^7*(*p>49&*p<58);puts(s);}}
```
[Try it online!](https://tio.run/##JY5BDoIwFAXXcgoloelvSywVFSx4ESOJIigx6k9bV4Sz16qbWbxkMq9Nr23rfXs7GYbCHrL8KFine@pg7F@Gulpqi2Z4up5ibUWcSHXZfTFPY@GWmZTCJYEgXKVyKTUMQeY8bI0iZGGdwbO506Cu8s22KGMg5Gc0avNvdLXlmdJYdRo5B9alac2w2TLKcJ@XhGG1LkDj21lqQU@TD3fmj9PwpBCN0aynoKPJfwA "C (gcc) – Try It Online")
[Answer]
# Befunge, 178 bytes
```
>0>:5g"7"`>v1\,+55<
v_^#`+87:+1_4>99p\ :99gg48 *-:55+/"0"+,55+%"0"+,":",\v
>$1+:55v v,," - "_^#-5g99,+"0"%+55,+"0"/+55:-*84gg99:<
v_@#!`+< >,\5^
!"%*+,/4569RSTW
*R4!+S5%/W9",T6
```
[Try it online!](http://befunge.tryitonline.net/#code=PjA+OjVnIjciYD52MVwsKzU1PAp2X14jYCs4NzorMV80Pjk5cFwgOjk5Z2c0OCAqLTo1NSsvIjAiKyw1NSslIjAiKywiOiIsXHYKPiQxKzo1NXYgdiwsIiAtICJfXiMtNWc5OSwrIjAiJSs1NSwrIjAiLys1NTotKjg0Z2c5OTo8CnZfQCMhYCs8ID4sXDVeCiAhIiUqKywvNDU2OVJTVFcKICpSNCErUzUlL1c5IixUNg&input=)
[Answer]
# [Kotlin](https://kotlinlang.org), ~~205~~ 207 bytes
```
(0..1439).map{"%02d : %02d".format(it/60,it%60)}.let{it.map{i->i to i.reversed().map{x->"25180:X52180:".let{it[it.indexOf(x)+7]}}.joinToString("")}.filter{(_,b)->it.contains(b)}.map{(a,b)->println("$a-$b")}}
```
## Beautified
```
(0..1439)
.map { "%02d : %02d".format(it / 60, it % 60) } // Make the times
.let { it.map {i->
i to i.reversed().map {x-> // Pair it with the reversed times
"25180:X52180:".let{ it[it.indexOf(x)+7] } // - X means bad times are removed
}.joinToString("") // - Make the string
}.filter {(_,b)-> it.contains(b) } // Remove the unpaired times
.map { (a, b) -> println("$a - $b") } // Print out the pairs
}
```
## Test
```
fun main(args: Array<String>) {
f()
}
fun f() =
(0..1439).map{"%02d:%02d".format(it/60,it%60)}.let{it.map{i->i to i.reversed().map{x->"25180:X52180:".let{it[it.indexOf(x)+7]}}.joinToString("")}.filter{(_,b)->it.contains(b)}.map{(a,b)->println("$a-$b")}}
```
## TIO
[TryItOnline](https://tio.run/##LY/BTsMwDIbvfYoo2iRHrCErbEAFlXgCDnBAmhBKaTIZ2mRKDSqq8uwl7fDBtuT/829/eWrRTZn9dqzT6ECHY1+yxxD07/0zBXTHSrAxYyksiCxmizS17GECJeX2+upOyE6fRr5WRVPOiUvrQ6cJkC73aoO03isRZWtoRFq0mFfIyDOUwfyY0JsGzkuGvOLFbnurytddMRf+jx0Sia4xw5OFQVzcvMUoPz26F3++EjhPFhZbMmGE900tkgXJD+8ovdVDnaazAehldEoMtQ74SuerOqFxmv4A)
## Edits
* +2 [Steadybox](https://codegolf.stackexchange.com/users/61405) - Fixed IO formatting
[Answer]
# Deadfish~, 9627 bytes
```
{iiiii}ddcc{i}c{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}c{d}cc{dddd}iic{iiii}ddcc{i}c{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}c{d}cc{dddd}iic{iiii}ddcc{i}c{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}c{d}cc{dddd}iic{iiii}ddcc{i}c{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dc{d}cc{dddd}iic{iiii}ddcc{i}c{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dc{d}cc{dddd}iic{iiii}ddcc{i}c{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dc{d}cc{dddd}iic{iiii}ddcc{i}c{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiic{d}cc{dddd}iic{iiii}ddcc{i}c{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiic{d}cc{dddd}iic{iiii}ddcc{i}cdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddc{d}cc{dddd}iic{iiii}ddcc{i}cdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddc{d}cc{dddd}iic{iiii}ddcc{i}cdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddc{d}cc{dddd}iic{iiii}ddcic{i}dc{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}c{d}icdc{dddd}iic{iiii}ddcic{i}dc{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}c{d}icdc{dddd}iic{iiii}ddcic{i}dc{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}c{d}icdc{dddd}iic{iiii}ddcic{i}dc{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dc{d}icdc{dddd}iic{iiii}ddcic{i}dc{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dc{d}icdc{dddd}iic{iiii}ddcic{i}dc{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dc{d}icdc{dddd}iic{iiii}ddcic{i}dc{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiic{d}icdc{dddd}iic{iiii}ddcic{i}dc{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiic{d}icdc{dddd}iic{iiii}ddcic{i}dcdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddc{d}icdc{dddd}iic{iiii}ddcic{i}dcdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddc{d}icdc{dddd}iic{iiii}ddcic{i}dcdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddc{d}icdc{dddd}iic{iiii}ddciic{i}ddc{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}cdddddcdddddc{dddd}iic{iiii}ddciic{i}ddc{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}cdddddcdddddc{dddd}iic{iiii}ddciic{i}ddc{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}cdddddcdddddc{dddd}iic{iiii}ddciic{i}ddc{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dcdddddcdddddc{dddd}iic{iiii}ddciic{i}ddc{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dcdddddcdddddc{dddd}iic{iiii}ddciic{i}ddc{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dcdddddcdddddc{dddd}iic{iiii}ddciic{i}ddc{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiicdddddcdddddc{dddd}iic{iiii}ddciic{i}ddc{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiicdddddcdddddc{dddd}iic{iiii}ddciic{i}ddcdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddcdddddcdddddc{dddd}iic{iiii}ddciic{i}ddcdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddcdddddcdddddc{dddd}iic{iiii}ddciic{i}ddcdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddcdddddcdddddc{dddd}iic{iiii}ddciiiiiciiiiic{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}c{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiic{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}c{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiic{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}c{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiic{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dc{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiic{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dc{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiic{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dc{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiic{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiic{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiic{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiic{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiicdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddc{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiicdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddc{d}iicddc{dddd}iic{iiii}ddciiiiiciiiiicdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddc{d}iicddc{dddd}iic{iiii}dcdc{i}c{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}c{d}cic{dddd}ic{iiii}dcdc{i}c{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}c{d}cic{dddd}ic{iiii}dcdc{i}c{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}c{d}cic{dddd}ic{iiii}dcdc{i}c{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dc{d}cic{dddd}ic{iiii}dcdc{i}c{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dc{d}cic{dddd}ic{iiii}dcdc{i}c{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dc{d}cic{dddd}ic{iiii}dcdc{i}c{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiic{d}cic{dddd}ic{iiii}dcdc{i}c{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiic{d}cic{dddd}ic{iiii}dcdc{i}cdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddc{d}cic{dddd}ic{iiii}dcdc{i}cdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddc{d}cic{dddd}ic{iiii}dcdc{i}cdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddc{d}cic{dddd}ic{iiii}dcc{i}dc{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}c{d}icc{dddd}ic{iiii}dcc{i}dc{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}c{d}icc{dddd}ic{iiii}dcc{i}dc{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}c{d}icc{dddd}ic{iiii}dcc{i}dc{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dc{d}icc{dddd}ic{iiii}dcc{i}dc{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dc{d}icc{dddd}ic{iiii}dcc{i}dc{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dc{d}icc{dddd}ic{iiii}dcc{i}dc{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiic{d}icc{dddd}ic{iiii}dcc{i}dc{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiic{d}icc{dddd}ic{iiii}dcc{i}dcdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddc{d}icc{dddd}ic{iiii}dcc{i}dcdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddc{d}icc{dddd}ic{iiii}dcc{i}dcdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddc{d}icc{dddd}ic{iiii}dcic{i}ddc{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}cdddddcddddc{dddd}ic{iiii}dcic{i}ddc{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}cdddddcddddc{dddd}ic{iiii}dcic{i}ddc{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}cdddddcddddc{dddd}ic{iiii}dcic{i}ddc{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dcdddddcddddc{dddd}ic{iiii}dcic{i}ddc{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dcdddddcddddc{dddd}ic{iiii}dcic{i}ddc{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dcdddddcddddc{dddd}ic{iiii}dcic{i}ddc{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiicdddddcddddc{dddd}ic{iiii}dcic{i}ddc{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiicdddddcddddc{dddd}ic{iiii}dcic{i}ddcdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddcdddddcddddc{dddd}ic{iiii}dcic{i}ddcdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddcdddddcddddc{dddd}ic{iiii}dcic{i}ddcdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddcdddddcddddc{dddd}ic{iiii}dciiiiciiiiic{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}c{d}iicdc{dddd}ic{iiii}dciiiiciiiiic{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}c{d}iicdc{dddd}ic{iiii}dciiiiciiiiic{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}c{d}iicdc{dddd}ic{iiii}dciiiiciiiiic{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dc{d}iicdc{dddd}ic{iiii}dciiiiciiiiic{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dc{d}iicdc{dddd}ic{iiii}dciiiiciiiiic{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dc{d}iicdc{dddd}ic{iiii}dciiiiciiiiic{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiic{d}iicdc{dddd}ic{iiii}dciiiiciiiiic{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiic{d}iicdc{dddd}ic{iiii}dciiiiciiiiicdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddc{d}iicdc{dddd}ic{iiii}dciiiiciiiiicdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddc{d}iicdc{dddd}ic{iiii}dciiiiciiiiicdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddc{d}iicdc{dddd}ic{iiii}cddc{i}c{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}c{d}ciiiiic{dddd}dddc{iiii}cddc{i}c{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}c{d}ciiiiic{dddd}dddc{iiii}cddc{i}c{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}c{d}ciiiiic{dddd}dddc{iiii}cddc{i}c{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dc{d}ciiiiic{dddd}dddc{iiii}cddc{i}c{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dc{d}ciiiiic{dddd}dddc{iiii}cddc{i}c{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dc{d}ciiiiic{dddd}dddc{iiii}cddc{i}c{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiic{d}ciiiiic{dddd}dddc{iiii}cddc{i}c{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiic{d}ciiiiic{dddd}dddc{iiii}cddc{i}cdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddc{d}ciiiiic{dddd}dddc{iiii}cddc{i}cdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddc{d}ciiiiic{dddd}dddc{iiii}cddc{i}cdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddc{d}ciiiiic{dddd}dddc{iiii}cdc{i}dc{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}c{d}iciiiic{dddd}dddc{iiii}cdc{i}dc{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}c{d}iciiiic{dddd}dddc{iiii}cdc{i}dc{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}c{d}iciiiic{dddd}dddc{iiii}cdc{i}dc{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dc{d}iciiiic{dddd}dddc{iiii}cdc{i}dc{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dc{d}iciiiic{dddd}dddc{iiii}cdc{i}dc{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dc{d}iciiiic{dddd}dddc{iiii}cdc{i}dc{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiic{d}iciiiic{dddd}dddc{iiii}cdc{i}dc{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiic{d}iciiiic{dddd}dddc{iiii}cdc{i}dcdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddc{d}iciiiic{dddd}dddc{iiii}cdc{i}dcdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddc{d}iciiiic{dddd}dddc{iiii}cdc{i}dcdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddc{d}iciiiic{dddd}dddc{iiii}cc{i}ddc{d}cc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicc{i}cdddddcc{dddd}dddc{iiii}cc{i}ddc{d}cic{dd}iiic{i}iiic{d}dddc{ii}dddcdc{i}cdddddcc{dddd}dddc{iiii}cc{i}ddc{d}ciiiiic{dd}dc{i}iiic{d}dddc{ii}ddcddc{i}cdddddcc{dddd}dddc{iiii}cc{i}ddc{d}icdc{d}ddddddc{i}iiic{d}dddc{i}iiiiiicic{i}dcdddddcc{dddd}dddc{iiii}cc{i}ddc{d}icc{dd}iiic{i}iiic{d}dddc{ii}dddcc{i}dcdddddcc{dddd}dddc{iiii}cc{i}ddc{d}iciiiic{dd}dc{i}iiic{d}dddc{ii}ddcdc{i}dcdddddcc{dddd}dddc{iiii}cc{i}ddc{d}iicddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciiiiiciiiiicdddddcc{dddd}dddc{iiii}cc{i}ddc{d}iicdc{dd}iiic{i}iiic{d}dddc{ii}dddciiiiciiiiicdddddcc{dddd}dddc{iiii}cc{i}ddcdddddcdddddc{d}ddddddc{i}iiic{d}dddc{i}iiiiiiciic{i}ddcdddddcc{dddd}dddc{iiii}cc{i}ddcdddddcddddc{dd}iiic{i}iiic{d}dddc{ii}dddcic{i}ddcdddddcc{dddd}dddc{iiii}cc{i}ddcdddddcc{dd}dc{i}iiic{d}dddc{ii}ddcc{i}ddcdddddcc
```
[Answer]
# C, 225 bytes
```
h,m,l,r,d=10,L[]={0,1,5,9,9,2,9,9,8,9};M(h,m){l=L[h%d]*d+L[h/d];r=L[m%d]*d+L[m/d];return L[h%d]<9&L[h/d]<9&L[m%d]<9&L[m/d]<9;}f(){for(h=0;h<24;++h)for(m=0;m<60;++m)M(h,m)&l<60&r<24&&printf("%02d:%02d - %02d:%02d\n",h,m,r,l);}
```
Since there is no C answer, I post my own. Some other approach might be shorter.
[Try it online!](https://tio.run/##PY9RCoMwDIbfPUUZWNoZWZVtzFVv4E7gfBh2roJxo7gn8ewuKi6B8Ofjg5AqfFXVNFlAaMGBySIFeVFmg4IITpBQx8u8QDLqmyBRDm2WF9Y35d4EFA6m1I4IbgQX8uy/rmOrmCZ8FZeAG8GF6LEWcqjfTthMaZvGRx0EVs4ACWB6VgRQrsd5Szt3ZHH@cU3X12Lnq9hc58FC9s/3bgfzWw5aqceJTIaPphPSGzxGRUe1N04/)
] |
[Question]
[
A subsequence is any sequence that you can get from another by deleting any amount of characters. The distinct non-empty subsequences of `100` are `0`, `1`, `00`, `10`, `100`. The distinct non-empty subsequences of `1010` are `0`, `1`, `00`, `01`, `10`, `11`, `010`, `100`, `101`, `110`, `1010`.
Write a program or function that given a positive integer *n* returns the number of distinct non-empty subsequences of the binary expansion of *n*.
Example: since `4` is `100` in binary, and we saw that it had five distinct non-empty subsequences above, so `f(4) = 5`. Starting from *n = 1*, the sequence begins:
```
1, 3, 2, 5, 6, 5, 3, 7, 10, 11, 9, 8, 9, 7, 4, 9, 14, 17, 15, 16, 19, 17, 12
```
However, your program must work for any *n < 250* in under a second on any modern machine. Some large examples:
```
f(1099511627775) = 40
f(1099511627776) = 81
f(911188917558917) = 728765543
f(109260951837875) = 447464738
f(43765644099) = 5941674
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~95 bytes~~ 83 bytes
[-12 bytes thanks to Mr.XCoder :)]
```
def f(x):
v=[2,1];c=1
for i in bin(x)[3:]:k=int(i);c+=v[k];v[1-k]+=v[k]
return c
```
[Try it online!](https://tio.run/##JYxBCsMgEEX3nmKWkbaLaQhNlDmJuKmNdBAmQYykp7eVbj483uPvn/LeZGwnLYg4zws@pqlve60R4nBqo6CSu1/R20CoIG4ZGFjgyfLTbjTeJGIpA2sbLlRd8rY6vCX/BwV5LUcWCG3Pveuvun0B "Python 3 – Try It Online")
A note on the algorithm.
The algorithm computes the increment in unique subsequences given by the bit at a given position t.
The increment for the first bit is always 1. The algorithm then runs over the sequence of bits s(t) and adds the increment v[s(t)]. At each step, the increment for the complement of s(t), v[1 - s(t)] is updated to v[1]+v[0].
The final number is the sum of all increments.
It should run in O(log2(n)), where n is the input number.
[Answer]
# JavaScript (ES6), ~~53~~ 51 bytes
```
f=(n,r=~(a=[]))=>n<1?~r:f(n/2,r*2-~~a[n&=1],a[n]=r)
```
### Test cases
```
f=(n,r=~(a=[]))=>n<1?~r:f(n/2,r*2-~~a[n&=1],a[n]=r)
console.log(f(1099511627775)) // 40
console.log(f(1099511627776)) // 81
console.log(f(911188917558917)) // 728765543
console.log(f(109260951837875)) // 447464738
console.log(f(43765644099)) // 5941674
```
### Formatted and commented
```
f = ( // f is a recursive function taking:
n, // n = integer
r = ~( // r = last result, initially set to -1
a = [] // and using a[] = last results for 0 and 1,
) // implicitly initialized to [0, 0]
) => //
n < 1 ? // if n is less than 1:
~r // we're done: return -(r + 1)
: // else:
f( // do a recursive call with:
n / 2, // n / 2
r * 2 - ~~a[n &= 1], // updated result = r * 2 - last result for this binary digit
a[n] = r // update last result for this binary digit
) // end of recursive call
```
# Non-recursive version, 63 bytes
*Saved 3 bytes thanks to @ThePirateBay*
```
s=>[...s.toString(2)].map(l=c=>l[p=r,r=r*2-~~l[c],c]=p,r=1)|r-1
```
### Test cases
```
let f =
s=>[...s.toString(2)].map(l=c=>l[p=r,r=r*2-~~l[c],c]=p,r=1)|r-1
console.log(f(1099511627775)) // 40
console.log(f(1099511627776)) // 81
console.log(f(911188917558917)) // 728765543
console.log(f(109260951837875)) // 447464738
console.log(f(43765644099)) // 5941674
```
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
f=lambda x,a=1,b=1:x and f(x/2,a+~x%2*b,x%2*a+b)or a+b-2
```
[Try it online!](https://tio.run/##HYxLDsIwDAXX9BTeIMU0iNqo9CPlMI5KoBJNq6gLs@HqIbCZN5s323t/rpFzDu4li58E1Ioj6x2NChInCEYvbKX@6JFP3v4otcc1QZkz51BMYY6QJD7uhiwTjtVhS3PcTTkjVn8vIWoGvjVDS/2167sW8xc "Python 2 – Try It Online")
Taking the [method from NofP](https://codegolf.stackexchange.com/a/145397/20260).
**59 bytes iteratively:**
```
x=input()
v=[1,1]
while x:v[x%2]=sum(v);x/=2
print sum(v)-2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERDk6vMNtpQxzCWqzwjMydVocKqLLpC1SjWtrg0V6NM07pC39aIq6AoM69EASKiC9RsaWhoaGFhaWhuagoiAQ "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
B3;BSṛ¦/’S
```
This uses [@xnor's improvement](https://codegolf.stackexchange.com/a/145398/12012) on [@NofP's algorithm](https://codegolf.stackexchange.com/a/145397/12012).
[Try it online!](https://tio.run/##y0rNyan8/9/J2Nop@OHO2YeW6T9qmBn8/@iew@2Pmta4//9vaGBpaWpoaGZkbm5uqqOAzDXTUbA0NDS0sLA0NDc1BZFgeSMzA6ASC2NzC5AGE2NzM1MzExOgPgA "Jelly – Try It Online")
### Background
Let **(a1, ..., an)** be a finite binary sequence. For each non-negative integer **k ≤ n**, define **ok** as the number of unique subsequences of **(a1, ..., ak)** that are either empty or end in **1**, **zk** as the number of unique subsequences that are either empty or end in **0**.
Clearly, **o0 = z0 = 1**, as the only subsequence of the empty sequence is the empty sequence.
For each index **k**, the total number of subsequences of **(a1, ..., ak)** is **ok + zk - 1** (subtracting **1** accounts for the fact that both **ok** and **zk** count the empty sequence). The total number of *non-empty* subsequences is therefore **ok + zk - 2**. The challenge asks to compute **on + zn - 2**.
Whenever **k > 0**, we can compute **ok** and **zk** recursively. There are two cases:
* ### ak = 1
**zk = zk-1**, since **(a1, ..., ak-1)** and **(a1, ..., ak-1, 1)** have the same subsequences that end in **0**.
For each of the **ok - 1** non-empty subsequences of **(a1, ..., ak)** that end in **1**, we can remove the trailing **1** to obtain one of the **ok-1 + zk-1 - 1** subsequences **(a1, ..., ak-1)**. Conversely, appending a **1** to each of the latter **ok-1 + zk-1 - 1** sequences results in one of the **ok - 1** former sequences. Thus, **ok - 1 = ok-1 + zk-1 - 1** and **ok = ok-1 + zk-1**.
* ### ak = 0
Similarly to the previous case, we obtain the recursive formulae **ok = ok-1** and **zk = zk-1 + ok-1**.
### How it works
```
B3;BSṛ¦/’S Main link. Argument: n (positive integer)
B Binary; convert n to base 2.
3; Prepend a 3.
B Binary; convert all integers in the resulting array to base 2, mapping
0 to [0], 1 to [1], and the prepended 3 to [1, 1].
/ Reduce the resulting array by the quicklink to the left, which will be
called with left argument [x, y] (integer pair) and right argument [j]
(either [0] or [1]).
¦ Sparse application.
S Compute the sum (x + y) and...
ṛ for each index in the right argument (i.e., for j)...
replace the element of [x, y] at that index with (x + y).
’ Decrement both integers in the resulting pair.
S Take the sum.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
0¸sbvDO>yǝ}O
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f4NCO4qQyF3@7yuNza/3//7c0NDS0sLA0NDc1BZEA "05AB1E – Try It Online") Explanation: As pointed out by the other answers, the number of subsequences for a binary string `a..y0` that end in a 1 is the same as the number for the binary string `a..y`, while the number that end in a `0` is the total number of subsequences for the binary string `a..y` (which each gain a `0` suffix) plus one for `0` itself. Unlike the other answers I don't include the empty subsequence as this saves a byte constructing the initial state.
```
0¸s Push [0] under the input
b Convert the input to binary
v } Loop over the digits
D Duplicate the array
O Take the sum
> Increment
yǝ Replace the index corresponding to the binary digit
O Take the sum of the final array
```
[Answer]
# Java 8, 97 bytes
```
n->f(n,1,1)long f(long n,long a,long b){return n>0?f(n/2,a+Math.floorMod(~n,2)*b,n%2*a+b):a+b-2;}
```
Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/145398/52210), which in turn is an improvement of [*@NofP*'s Python 3 answer](https://codegolf.stackexchange.com/a/145397/52210).
[Try it here.](https://tio.run/##lU9Nc4IwFLzzK96lM4kCGpSvUu0fUC8eOz0EDIqFFwaCHcehf50G8NhO7WV3Xt5m3@6ZX7glS4Hnw0eX5LyuYcszvBkAGSpRpTwRsOtHgFziERKy6QlppN9aQ8MOEFbQobVOCZrMZNSItHo2g51UUPJKgUxBnQTEVyWsRDaojMErJQOhORAfKaa3SqimQsD1/FVbzhyTT7dcnew0l7LaygP5QtOhk9jEJ2fCpzF91mA5UdsBlE2cZwnUiitNF5kdoNCFyF5VGR7f3oHTsU1fEwqdHMXnMJChEkAqqzFXtmKbCLKXleP2PJ3SYQ@wv9ZKFLZslF1qV5UjKWy0E5LRu8cPit834182D0OXMc/xfd/d0P/Ivb/lIWMsCELmu26PD/k73lyfCBZ@8Eig5cL3XG@51Lnu4tZou28)
---
Maybe it's a good thing the [restricted-time](/questions/tagged/restricted-time "show questions tagged 'restricted-time'")-tag was present, because I initially had the following to bruteforce all subsequences:
```
import java.util.*;n->p(n.toString(n,2)).size()-1;Set p(String s){Set r=new HashSet();r.add("");if(s.isEmpty())return r;Set q=p(s.substring(1));r.addAll(q);for(Object o:q)r.add(""+s.charAt(0)+o);return r;}
```
[Try it here.](https://tio.run/##lVJLb@IwEL7zK0a9rA3FEEoIbJaVeqi0BworsbfVHpzEgGliB3vSiq347ew40FsrdS8ez@Obxzezl8@yb2tl9sXTWVe1dQh7sokGdSm6KQAMBvBTktluAHcKsiOqfm4bg51OXkrv4VFq89oB0AaV28hcwTKoAKU1W8jZIgjDU7KdOvQswcAczqb/vWZGoF2j02bLzO2Ic@H1X8V4P@pcSy8tQv1@@bUiF7ugwfPXoLu5US/wQ/odaYynTsiiYDc3PNUb5oX2D1WNR8a5U9g4Ay4NqMO8JqdvMn9pJeJX5H1ZsgNPN9axVbZXObXx9cDfkva8yHfS3SMb8p4lyFvO0xmgbrJS5@BRIolnqwuoiKhrv7//gOQXlgJ9UBEjofOgsJYqgFC1pVDPo0UK@tt8FAfZ6/HWD7A@elSVsA2KmrJiaVgljMiZ5tcc70R87Llgo@FsFkfRZJQkSbzg/xM@acPbeFrdr532kLmGFkaj0Fl4W9JZWeOhsMqbLwgv1j2FOdvV0jEhfZxSgIq@ufTK30LRkG5h1eBq86gq644PzhGkhVlLMLdVQGv0QlxKdz9sdhZF0XQ6i5I4Du@nphtNhjTg9C6ZfoaO8V0yiSfjMbESgruD9upP538)
Which also worked, but took way too long for the last three test cases. Not to mention it's way longer (**~~208~~ 204 bytes**).
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 321 bytes
```
00 C0 20 FD AE A2 00 9D 4F C1 E8 20 73 00 90 F7 9D 4F C1 A0 FF C8 B9 4F C1 D0
FA A2 15 CA 88 30 0A B9 4F C1 29 0F 9D 4F C1 10 F2 A9 00 9D 4F C1 CA 10 F8 A9
00 A0 07 99 64 C1 88 10 FA A0 40 A2 6C 18 BD E4 C0 90 02 09 10 4A 9D E4 C0 E8
10 F2 A2 07 7E 64 C1 CA 10 FA 88 F0 13 A2 13 BD 50 C1 C9 08 30 05 E9 03 9D 50
C1 CA 10 F1 30 D1 A2 0F A9 00 9D 3F C1 CA D0 FA A9 01 8D 3F C1 8D 47 C1 A2 08
CA BD 64 C1 F0 FA A0 09 1E 64 C1 88 90 FA B0 0A CA 30 28 A0 08 1E 64 C1 90 04
A9 47 B0 02 A9 4F 8D AF C0 86 FE A2 F8 18 BD 47 C0 7D 4F C0 9D 47 C0 E8 D0 F4
A6 FE 88 D0 DC F0 D5 A2 F8 BD 47 C0 7D 4F C0 9D 6C C0 E8 D0 F4 AD 64 C1 E9 01
8D 64 C1 A2 F9 BD 6C C0 E9 00 9D 6C C0 E8 D0 F5 A0 15 A9 00 99 4E C1 88 D0 FA
A0 40 A2 13 BD 50 C1 C9 05 30 05 69 02 9D 50 C1 CA 10 F1 0E 64 C1 A2 F9 3E 6C
C0 E8 D0 FA A2 13 BD 50 C1 2A C9 10 29 0F 9D 50 C1 CA 10 F2 88 D0 D1 E0 14 F0
06 E8 BD 4F C1 F0 F6 09 30 99 4F C1 C8 E8 E0 15 F0 05 BD 4F C1 90 F0 A9 00 99
4F C1 A9 4F A0 C1 4C 1E AB
```
**[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22binseq.prg%22:%22data:;base64,AMAg/a6iAJ1PweggcwCQ951PwaD/yLlPwdD6ohXKiDAKuU/BKQ+dT8EQ8qkAnU/ByhD4qQCgB5lkwYgQ+qBAomwYveTAkAIJEEqd5MDoEPKiB35kwcoQ+ojwE6ITvVDByQgwBekDnVDByhDxMNGiD6kAnT/BytD6qQGNP8GNR8GiCMq9ZMHw+qAJHmTBiJD6sArKMCigCB5kwZAEqUewAqlPja/Ahv6i+Bi9R8B9T8CdR8Do0PSm/ojQ3PDVovi9R8B9T8CdbMDo0PStZMHpAY1kwaL5vWzA6QCdbMDo0PWgFakAmU7BiND6oECiE71QwckFMAVpAp1QwcoQ8Q5kwaL5PmzA6ND6ohO9UMEqyRApD51QwcoQ8ojQ0eAU8AbovU/B8PYJMJlPwcjo4BXwBb1PwZDwqQCZT8GpT6DBTB6r%22%7D,%22vice%22:%7B%22-autostart%22:%22binseq.prg%22%7D%7D)**
**[Online demo with error checking](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22binseq.prg%22:%22data:;base64,AMAghcCiD6kAnVjBytD6qQGNWMGNYMGiCMq9fcHw+qAJHn3BiJD6sArKMCigCB59wZAEqWCwAqlojUbAhv6i+Bi9YMB9aMCdYMDo0PSm/ojQ3PDVovi9YMB9aMCdhcDo0PStfcHpAY19waL5vYXA6QCdhcDo0PUg/cCpaKDBTB6rTAivTEiyIP2usPWiAJ1owejgFfDuIHMAkPOdaMGg/8i5aMHQ+qIVyogwCrlowSkPnWjBEPKpAJ1owcoQ+KkAoAeZfcGIEPqgQKJsGL39wJACCRBKnf3A6BDyogd+fcHKEPqI0AasfMHQmWCiE71pwckIMAXpA51pwcoQ8TDLoBWpAJlnwYjQ+qBAohO9acHJBTAFaQKdacHKEPEOfcGi+T6FwOjQ+qITvWnBKskQKQ+dacHKEPKI0NHgFPAG6L1owfD2CTCZaMHI6OAV8AW9aMGQ8KkAmWjBYA==%22%7D,%22vice%22:%7B%22-autostart%22:%22binseq.prg%22%7D%7D)** (346 bytes)
**Usage:** `sys49152,[n]`, e.g. `sys49152,911188917558917`.
The time restriction and the test-cases require solutions to calculate in 64bit numbers, so time to prove the C64 qualifies as "**modern machine**" ;)
Of course, this needs quite a bit of code, the OS doesn't provide **anything** for integers wider than 16bit. The lame part here: it's *yet another implementation* (slightly modified) of [NofP's algorithm](https://codegolf.stackexchange.com/a/145397/71420) resp. [xnor's improved variant](https://codegolf.stackexchange.com/a/145398/71420). Thanks for the idea ;)
---
### Explanation
Here's a commented disassembly listing of the relevant part doing the algorithm:
```
.C:c06c A2 0F LDX #$0F ; 15 bytes to clear
.C:c06e A9 00 LDA #$00
.C:c070 .clearloop:
.C:c070 9D 3F C1 STA .num_a,X
.C:c073 CA DEX
.C:c074 D0 FA BNE .clearloop
.C:c076 A9 01 LDA #$01 ; initialize num_a and num_b
.C:c078 8D 3F C1 STA .num_a ; to 1
.C:c07b 8D 47 C1 STA .num_b
.C:c07e A2 08 LDX #$08 ; 8 bytes of input to check,
.C:c080 .findmsb: ; start at most significant
.C:c080 CA DEX
.C:c081 BD 64 C1 LDA .nc_num,X
.C:c084 F0 FA BEQ .findmsb ; repeat until non-0 byte found
.C:c086 A0 09 LDY #$09 ; 8 bits to check (+1 for pre dec)
.C:c088 .findbit:
.C:c088 1E 64 C1 ASL .nc_num,X ; shift left, highest bit to carry
.C:c08b 88 DEY
.C:c08c 90 FA BCC .findbit ; bit was zero -> repeat
.C:c08e B0 0A BCS .loopentry ; jump into calculation loop
.C:c090 .mainloop:
.C:c090 CA DEX ; next byte
.C:c091 30 28 BMI .done ; index -1? -> done calculating
.C:c093 A0 08 LDY #$08 ; 8 bits to check
.C:c095 .bitloop:
.C:c095 1E 64 C1 ASL .nc_num,X ; shift left, highest bit to carry
.C:c098 90 04 BCC .tgt_b ; if 0, store addition result in num_b
.C:c09a .loopentry:
.C:c09a A9 47 LDA #$47
.C:c09c B0 02 BCS .tgt_a ; ... else store in num_a ...
.C:c09e .tgt_b:
.C:c09e A9 4F LDA #$4F
.C:c0a0 .tgt_a:
.C:c0a0 8D AF C0 STA $C0AF ; ... using self-modification.
.C:c0a3 86 FE STX $FE ; save byte index
.C:c0a5 A2 F8 LDX #$F8 ; index for adding
.C:c0a7 18 CLC
.C:c0a8 .addloop:
.C:c0a8 BD 47 C0 LDA $C047,X ; load byte from num_a
.C:c0ab 7D 4F C0 ADC $C04F,X ; add byte from num_b
.C:c0ae 9D 47 C0 STA $C047,X ; store to num_a or num_b
.C:c0b1 E8 INX ; next index
.C:c0b2 D0 F4 BNE .addloop ; done if index overflown
.C:c0b4 A6 FE LDX $FE ; restore byte index
.C:c0b6 88 DEY ; decrement bit index
.C:c0b7 D0 DC BNE .bitloop ; bits left in current byte -> repeat
.C:c0b9 F0 D5 BEQ .mainloop ; else repeat main loop
.C:c0bb .done:
.C:c0bb A2 F8 LDX #$F8 ; index for adding
.C:c0bd .addloop2:
.C:c0bd BD 47 C0 LDA $C047,X ; load byte from num_a
.C:c0c0 7D 4F C0 ADC $C04F,X ; add byte from num_b
.C:c0c3 9D 6C C0 STA $C06C,X ; store to nc_num (result)
.C:c0c6 E8 INX ; next index
.C:c0c7 D0 F4 BNE .addloop2 ; done if index overflown
.C:c0c9 AD 64 C1 LDA .nc_num ; load least significant result byte
.C:c0cc E9 01 SBC #$01 ; subtract 2 (1 + negated carry)
.C:c0ce 8D 64 C1 STA .nc_num ; store least significant result byte
.C:c0d1 A2 F9 LDX #$F9 ; index for subtract
.C:c0d3 .subloop:
.C:c0d3 BD 6C C0 LDA $C06C,X ; subtract 0 from all other bytes
.C:c0d6 E9 00 SBC #$00 ; for handling carry if necessary
.C:c0d8 9D 6C C0 STA $C06C,X
.C:c0db E8 INX
.C:c0dc D0 F5 BNE .subloop
```
The rest is input/output and converting between string and 64bit unsigned integer (little-endian) using some double-dabble algorithm. In case you're interested, [here's the whole assembly source for the version with error-checking](https://github.com/Zirias/c64binseq) -- the "golfed" version is in the branch "golf".
] |
[Question]
[
Given a matrix consisting of positive integers, output the path with the lowest sum when traversing from the upper left element to the bottom right. You may move vertically, horizontally and diagonally. Note that it's possible to move both up/down, right/left and diagonally to all sides.
### Example:
```
1* 9 7 3 10 2 2
10 4* 1* 1* 1* 7 8
3 6 3 8 9 5* 7
8 10 2 5 2 1* 4
5 1 1 3 6 7 9*
```
The path giving the lowest sum is marked with asterisks, and results in the following sum: **1+4+1+1+1+5+1+9=23**.
### Test cases:
```
1 1 1
1 1 1
Output: 3
7 9 6 6 4
6 5 9 1 6
10 7 10 4 3
4 2 2 3 7
9 2 7 9 4
Output: 28
2 42 6 4 1
3 33 1 1 1
4 21 7 59 1
1 7 6 49 1
1 9 2 39 1
Output: 27 (2+3+4+7+7+1+1+1+1)
5 6 7 4 4
12 12 25 25 25
9 4 25 9 5
7 4 25 1 12
4 4 4 4 4
Output: 34 (5+12+4+4+4+1+4)
1 1 1 1
9 9 9 1
1 9 9 9
1 9 9 9
1 1 1 1
Output: 15
2 55 5 3 1 1 4 1
2 56 1 99 99 99 99 5
3 57 5 2 2 2 99 1
3 58 4 2 8 1 99 2
4 65 66 67 68 3 99 3
2 5 4 3 3 4 99 5
75 76 77 78 79 80 81 2
5 4 5 1 1 3 3 2
Output: 67 (2+2+3+3+4+5+4+3+3+3+1+2+2+1+3+1+1+4+5+1+2+3+5+2+2)
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in each language wins.
[Answer]
# JavaScript, ~~442 412 408~~ 358 bytes
This is my first PPCG submission. Feedback would be appreciated.
```
(m,h=m.length,w=m[0].length)=>{for(i=0;i<h*w;i++)for(x=0;x<w;x++){for(y=0;y<h;y++){if(m[y][x]%1==0)m[y][x]={c:m[y][x],t:m[y][x]};for(X=-1;X<=1;X++)for(Y=-1;Y<=1;Y++){t=x+X;v=y+Y;if((X==0&&Y==0)||t<0||t>=w||v<0||v>=h)continue;if(m[v][t]%1==0)m[v][t]={c:m[v][t],t:null};c=m[y][x].t+m[v][t].c;if (c<m[v][t].t||m[v][t].t==null)m[v][t].t=c}}}return m[h-1][w-1].t}
```
This takes a multi-dimensional array as input.
# Explanation
Basically, loop through all of the cells over and over adjusting the lowest known cost to get to each of the neighbors. Eventually, the grid will reach a state where the total cost to reach the bottom right is the lowest cost to get there.
# Demo
```
f=(m,h=m.length,w=m[0].length)=>{for(i=0;i<h*w;i++)for(x=0;x<w;x++){for(y=0;y<h;y++){if(m[y][x]%1==0)m[y][x]={c:m[y][x],t:m[y][x]};for(X=-1;X<=1;X++)for(Y=-1;Y<=1;Y++){t=x+X;v=y+Y;if((X==0&&Y==0)||t<0||t>=w||v<0||v>=h)continue;if(m[v][t]%1==0)m[v][t]={c:m[v][t],t:null};c=m[y][x].t+m[v][t].c;if (c<m[v][t].t||m[v][t].t==null)m[v][t].t=c}}}return m[h-1][w-1].t}
//Tests
console.log(f([[1,1,1],[1,1,1]])===3);
console.log(f([[7,9,6,6,4],[6,5,9,1,6],[10,7,10,4,3],[4,2,2,3,7],[9,2,7,9,4]])===28);
console.log(f([[2,42,6,4,1],[3,33,1,1,1],[4,21,7,59,1],[1,7,6,49,1],[1,9,2,39,1]])===27);
console.log(f([[5,6,7,4,4],[12,12,25,25,25],[9,4,25,9,5],[7,4,25,1,12],[4,4,4,4,4]])===34);
console.log(f([[1,1,1,1],[9,9,9,1],[1,9,9,9],[1,9,9,9],[1,1,1,1]])===15)
console.log(f([[2,55,5,3,1,1,4,1],[2,56,1,99,99,99,99,5],[3,57,5,2,2,2,99,1],[3,58,4,2,8,1,99,2],[4,65,66,67,68,3,99,3],[2,5,4,3,3,4,99,5],[75,76,77,78,79,80,81,2],[5,4,5,1,1,3,3,2]])===67);
```
Edit: Special thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) for helping me shave dozens of tasty bytes.
More thanks to [@Stewie Griffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin) for your tips that knocked off 50 bytes.
[Answer]
# [Python 3](https://docs.python.org/3/) + [numpy](http://numpy.org) + [scipy](https://www.scipy.org/), 239 222 186 bytes
```
from numpy import*
from scipy.sparse.csgraph import*
def f(M):m,n=s=M.shape;x,y=indices(s);return dijkstra([(M*(abs(i//n-x)<2)*(abs(i%n-y)<2)).flatten()for i in range(m*n)])[0,-1]+M[0,0]
```
[Try it online!](https://tio.run/##bVTbjtsgEH3nK5ClSuA62eC7s80n5AvSPLCJs6GNiQVeaf31KQMYr7d58Jg5zJw5w60fh@tdZo/HRd07LD@6fsSi6@9qiJGF9En041r3XOl2fdLvivfXEHFuL/hC9nTbJXKnd/u1vvK@ff1Mxp2QZ3FqNdH0VbXDh5L4LP781YPi5ED2MeFvmoiXF7n6pL9S6v0fcjWCS9eXGx@GVhJ6uSsssJBYcfneki6W9EgPm2TFjj/35r85PiBEQ8ghiiKEWYwxbsyHKzCZ@dgGRqk1yDk5RLGlsfE1sim4nJJxjSfCwkYhi3zhLMLI0uTIISyYmdCWaGJklK5V29/4qSVRHCU4imgCKGI@iX0ZGdxN@vxAZ42pVwYZTSha@k6rIDa3WpD7p8FYdaarJiBzlXyubWby1NfMrSyTmGWTSIsYPGWOoGhCE5XLymekcZWy5lt7xXKhcieBQVlr0mI2XnA@IX6L0Jyahm1gqe/6u5lrs0UjjedbSrbfE@/ZToHcogj7ki1PhK3OfFQ5wU3zv4GOILmolkctGBfFfFQd2NNwdgM19stQAk0JZUu7N/Wk0EVl6Mu5zoP6bHInXRUEVEBTAU0FNBXM1XDcauYrzjTPrkXmosyaHbcI73dcKT6Sw03ogXS8J0IOCb4J2ZpH6CYGQinFcOMBgkuvPR79lhE9sK15GI4U4V6ZRPM0TSN4poJDH/8A "Python 3 – Try It Online")
[Answer]
# Octave + Image Processing package, ~~175~~ ~~162~~ ~~157~~ ~~151~~ ~~142~~ 139 bytes
Saved 14 bytes thanks to [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) and 1 byte thanks to [@notjagan](https://codegolf.stackexchange.com/users/63641/notjagan)
```
function P(G)A=inf(z=size(G));A(1)=G(1);for k=G(:)'B=im2col(padarray(A,[1,1],inf),[3,3])+G(:)';B(5,:)-=G(:)';A=reshape(min(B),z);end,A(end)
```
Uses the Image Processing package, because why not? Isn't that how everybody solves graph problems?
[Try it online!](https://tio.run/##JYvNCsIwEITvPsXe3MUIpq0tuuSQXnrtvfQQ2hSDmkr9AfvydVUGvpmBmbF7uJdfluEZu0cYI9RYkTUhDjibe5i9VGKLmkwl4GGc4CzxSOvShGvSjRe8ud5Nk3ujVY1WulXyJtWkKm1p85tyiXt1pO3/yNZM/n5yN4/XELEkNRP72CuLQloEvKqxKeAAuSjjHPaSNeSsd1CAIIOUM0hEKRR8EP@us5aWDw)
**Exploded**
```
function P(G)
A=inf(z=size(G)); % Initialize distance array to all Inf
A(1)=G(1); % Make A(1) = cost of start cell
for k=G(:)' % For a really long time...
B=im2col(padarray(A,[1,1],inf),[3,3])+G(:)';
% B=padarray(A,[1,1],inf); % Add border of Inf around distance array
% B=im2col(B,[3,3]); % Turn each 3x3 neighborhood into a column
% B=B+G(:)'; % Add the weights to each row
B(5,:)-=G(:)'; % Subtract the weights from center of neighborhood
A=reshape(min(B),z); % Take minimum columnwise and reshape to original
end
A(end) % Display cost of getting to last cell
```
---
**Explanation**
Given an array of weights:
```
7 12 6 2 4
5 13 3 11 1
4 7 2 9 3
4 2 12 13 4
9 2 7 9 4
```
Initialize a cost array so that the cost to reach every element is Infinity, except the starting point (the upper left element) whose cost is equal to its weight.
```
7 Inf Inf Inf Inf
Inf Inf Inf Inf Inf
Inf Inf Inf Inf Inf
Inf Inf Inf Inf Inf
Inf Inf Inf Inf Inf
```
This is iteration 0. For each subsequent iteration, the cost to reach a cell is set to the minimum of:
* the current cost to reach that element, and
* the current cost to reach the element's neighbors + the weight of the element
After the first iteration, the cost of the path to element (2,2) (using 1-based indexing) will be
```
minimum([ 7 Inf Inf] [13 13 13]) = 20
[Inf Inf Inf] + [13 0 13]
[Inf Inf Inf] [13 13 13]
```
The full cost array after the first iteration would be:
```
7 19 Inf Inf Inf
12 20 Inf Inf Inf
Inf Inf Inf Inf Inf
Inf Inf Inf Inf Inf
Inf Inf Inf Inf Inf
```
After iteration `k`, each element will be the lowest cost of reaching that element from the start taking at most `k` steps. For example, the element at (3,3) can be reached in 2 steps (iterations) for a cost of 22:
```
7 19 25 Inf Inf
12 20 22 Inf Inf
16 19 22 Inf Inf
Inf Inf Inf Inf Inf
Inf Inf Inf Inf Inf
```
But on the 4th iteration, a path of 4 steps is found with a cost of 20:
```
7 19 25 24 28
12 20 22 32 25
16 19 20 30 34
20 18 30 34 35
27 20 25 40 39
```
Since no path through the *mxn* matrix can be longer than the number of elements in the matrix (as a very loose upper bound), after `m*n` iterations every element will contain the cost of the shortest path to reach that element from the start.
[Answer]
# JavaScript, 197 bytes
```
a=>(v=a.map(x=>x.map(_=>1/0)),v[0][0]=a[0][0],q=[...(a+'')].map(_=>v=v.map((l,y)=>l.map((c,x)=>Math.min(c,...[...'012345678'].map(c=>a[y][x]+((v[y+(c/3|0)-1]||[])[x+c%3-1]||1/0)))))),v.pop().pop())
```
Prettify:
```
a=>(
// v is a matrix holds minimal distance to the left top
v=a.map(x=>x.map(_=>1/0)),
v[0][0]=a[0][0],
q=[
// iterate more than width * height times to ensure the answer is correct
...(a+'')
].map(_=>
v=v.map((l,y)=>
l.map((c,x)=>
// update each cell
Math.min(c,...[...'012345678'].map(
c=>a[y][x]+((v[y+(c/3|0)-1]||[])[x+c%3-1]||1/0)
))
)
)
),
// get result at right bottom
v.pop().pop()
)
```
[Answer]
## Mathematica 279 Bytes
Basic idea is to create a graph with vertices corresponding to matrix entries and directed edges between any two vertices separated by a `ChessboardDistance` greater than zero but less than or equal to 1. Incidentally, this happens to be known as a [King graph](http://mathworld.wolfram.com/KingGraph.html), since it corresponds to the valid moves of a king on a chessboard.
`FindShortestPath` is then used to get the minimal path. It works on `EdgeWeight`, not `VertexWeight`, so there is some extra code to define the `EdgeWeight` as the matrix entry corresponding to the destination of each directed edge.
Code:
```
(m=Flatten[#];d=Dimensions@#;s=Range[Times@@d];e=Select[Tuples[s,2],0<ChessboardDistance@@(#/.Thread[s->({Ceiling[#/d[[1]]],Mod[#,d[[1]],1]}&/@s)])≤1&];Tr[FindShortestPath[Graph[s,#[[1]]->#[[2]]&/@e,EdgeWeight->(Last@#&/@Map[Extract[m,#]&,e,{2}])],1,Last@s]/.Thread[s->m]])&
```
Note that the `` character is the transpose symbol. It will paste into Mathematica as-is.
Usage:
```
%@{{2, 55, 5, 3, 1, 1, 4, 1},
{2, 56, 1, 99, 99, 99, 99, 5},
{3, 57, 5, 2, 2, 2, 99, 1},
{3, 58, 4, 2, 8, 1, 99, 2},
{4, 65, 66, 67, 68, 3, 99, 3},
{2, 5, 4, 3, 3, 4, 99, 5},
{75, 76, 77, 78, 79, 80, 81, 2},
{5, 4, 5, 1, 1, 3, 3, 2}}
```
Output:
```
67
```
If you set `g=Graph[...,GraphLayout->{"GridEmbedding","Dimension"->d},VertexLabels->Thread[s->m]` and `p=FindShortestPath[...` then the following graphic will visually display the solution (top of the matrix corresponds to the bottom of the graph):
```
HighlightGraph[g,PathGraph[p,Thread[Most@p->Rest@p]]]
```
[](https://i.stack.imgur.com/DWiiz.gif)
[Answer]
# Haskell, 228 bytes
Positions are lists of two elements, because those are easy to generate with `sequence` and just as easy to pattern match as 2-tuples.
```
h=g[[-1,-1]]
g t@(p:r)c|p==m=0|1<2=minimum$(sum$concat c):(\q@[a,b]->c!!a!!b+g(q:t)c)#(f(e$s$(\x->[0..x])#m)$f(not.e t)$zipWith(+)p#s[[-1..1],[-1..1]])where m=[l(c)-1,l(head c)-1]
(#)=map
f=filter
e=flip elem
s=sequence
l=length
```
Start at `-1,-1` and count the cost of each steps destination field.
Alternative first two lines: start at `0,0`, count the departure fields, terminate at the coordinates equal to the matrix dimensions (so down-right from the goal, which needs to be added to the list of legal destinations) - exact same length but slower:
```
j=i[[0,0]]
i t@(p@[a,b]:r)c|p==m=0|1<2=c!!a!!b+(minimum$(sum$concat c):(\q->i(q:t)c)#(f(e$m:(s$(\x->[0..x-1])#m))$f(not.e t)$zipWith(+)p#s[[-1..1],[-1..1]]))where m=[l c,l$head c]
```
Using an infix for `map` does not save bytes here but I substitute it as soon as it doesn't cost one, because it can only get better with more uses, and sometimes with other restructurings as well which shave off another pair of parentheses.
To be improved: Redundant `filter`s. Merging/in-lining them to `filter(flip elem$(s$(\x->[0..x])#m)\\p)` with `import Data.List` for `\\` costs 3 bytes.
Also, too bad `(fromEnumTo 0)` is 2 bytes longer than `(\x->[0..x])`.
`sum$concat c` is all fields' cost summed up and thus a concisely expressible upper bound on the path cost which is given to the `minimum` to avoid an empty list (my type checker has already determined the whole thing to work on `Integer`s, so no hard-coding the maximum, hehe). No matter how I restrict steps based on the previous one made (which would speed up the algorithm a lot, but also cost bytes), I can not avoid the dead ends that make this fall-back necessary.
* One filter idea was `((not.e n).zipWith(-)(head r))` with extracting `n=s[[-1..1],[-1..1]]`, which necessitates adding `,[-1,-1]` to the initial path. The algorithm then avoids going where it could already have gone in the previous step, which makes stepping on an edge field orthogonally to that edge a dead end.
* Another was `((>=0).sum.z(*)d)` with extracting `z=zipWith`, which introduces a new argument `d` to the recursive function that is given as `(z(-)p q)` in the recursion and `[1,1]` in the initial case. The algorithm avoids successive steps with a negative scalar product (`d` being the previous step), which means no sharp 45°-turns. This still narrows down the choices considerably, and avoids the previous trivial dead end, but there are still paths that end up enclosed in already-visited fields (and possibly an 'escape' which however would be a sharp turn).
[Answer]
# Python 2, ~~356~~ 320 bytes
```
s=input()
r=lambda x:[x-1,x,x+1][-x-2:]
w=lambda z:[z+[(x,y)]for x in r(z[-1][0])for y in r(z[-1][1])if x<len(s)>0==((x,y)in z)<len(s[0])>y]
l=len(s)-1,len(s[0])-1
f=lambda x:all(l in y for y in x)and x or f([a for b in[l in z and[z]or w(z)for z in x]for a in b])
print min(sum(s[a][b]for(a,b)in x)for x in f([[(0,0)]]))
```
[Try it here!](https://tio.run/##TY/BasMwEETv/godtWQNlkOhmCo/suxBJjE1yIpxHCLr592VQt2eVpqZ1RvN2/p9D@2@P@wY5ueqoVqsd1N/dSp2FGuDEePJMNWxbjuuXr9u6iidSEfcgIf7oqIag1p0olrCDUPWtv@aYRgHFb/8LegHXBprddmWSIK3mvcuG1fevkNCP/TaVMNfM@e99vn1TR2gCC5cpYfcB02uGL0YVIJJiUuJRXzpVOqlslXau3zsGap5GcOqplGoz0nIjqnPCe2whwI5PisQ0g02wAyw70QGDZ4ZZX5gW@YnGuYf)
-36 bytes thanks to [notjagan](https://codegolf.stackexchange.com/users/63641/notjagan)!
Receives a list of lists as an input, and outputs the lowest cost when navigating the matrix from the upper left to the bottom right.
## Explanation
Find every possible route from the upper left to the bottom right of the matrix, creating a list of x,y coordinates for each route. The routes cannot backtrack, and they must end at `(len(s)-1,len(s[0])-1)`.
Sum the integers on each path of coordinates, and return the minimum cost.
The `print` can be easily changed to output the list of coordinates for the shortest route.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 33 bytes
```
{⊃⌽,(⊢⌊⍵+(⍉3⌊/⊣/,⊢,⊢/)⍣2)⍣≡+\+⍀⍵}
```
[Try it online!](https://tio.run/##VVDbSsNAEH33K@YtCW1ps5ds1m/xJVQqxUCl7YtIQVAKjY3ogx9g@w19EfyZ@ZF4ZjfeOJvJyWT2zJypburR5W1VL65G07parebTjp/f5gvevky6GeIdNw@8/xym3Bx433B7GqTc7jT4mJvjeIi8POOM26OSwLv3wcWA23vUbrpuHUTaE@8OS9AZtx/nyaya1wkY8kt@ekwW18nmLOXta5oTkPWvbE06ph15KgCTpQVZfORUoGpCjhAM6Sw1pABNLks9iNwwoqDKKKHIKFEQeU1aU98K93JUWx/7OqnpuehoHwdRLspY/HdQwSS5Ihxl45G2RqgncBc5Oihp0SM4Mn@cSh9Pgr4h8I/8LCK33zasxQbi@MEMMgW497/HikULU2EnSlLBtS1lLCpjeZisgCFsFrZLiCKrg6LsFDC9mrPk4NuRK8l5KidU5nJf6oLLUK1k0MJ9AQ "APL (Dyalog Classic) – Try It Online")
`{ }` function with argument `⍵`
`+\+⍀⍵` take partial sums by row and by column to establish a pessimistic upper bound on path distances
`( )⍣≡` repeat until convergence:
* `(⍉3⌊/⊣/,⊢,⊢/)⍣2` min of distances to neighbours, i.e. do twice (`( )⍣2`): prepend leftmost column (`⊣/,`) to self (`⊢`) and append rightmost columns (`,⊢/`), find minima in horizontal triples (`3⌊/`) and transpose (`⍉`)
* `⍵+` add each node's value to its min of distances to neighbours
* `⊢⌊` try to beat the current best distances
`⊃⌽,` finally, return the bottom right cell
] |
[Question]
[
>
> This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, the robbers thread can be found [here](https://codegolf.stackexchange.com/questions/137382/solving-secret-swapping-sequences).
>
>
>
Your task is to write some code that outputs an OEIS sequence, and contains the name of the sequence in the code (`A______`) and outputs a second separate sequence when the name of the sequence in the code is changed to the name of the second sequence.
Here's an example in Haskell that works for [A000217](https://www.oeis.org/A000217) and [A000290](https://www.oeis.org/A000290).
```
f x|last"A000217"=='0'=x^2|1>0=sum[1..x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoiYnsbhEydHAwMDI0FzJ1lbdQN22Is6oxtDOwLa4NDfaUE@vIvZ/bmJmnm1BUWZeiUqagqHBfwA "Haskell – Try It Online")
You are then to reveal one of the two sequences, and the code keeping the second sequence a secret. Robbers will attempt to figure out what the hidden sequence is. If a robber manages to determine what your sequence is (or another sequence that fits the criteria) you answer is cracked. If none do so in a week of your answer being posted you may mark your answer as **Safe** and reveal the intended solution for verification. **Safe** answers cannot be cracked.
## Input Output
Taken from [here](https://codegolf.stackexchange.com/questions/137213/swap-the-sequence)
Your code can be a function or complete program that takes **n** via a standard input method and outputs the **n**th term of the sequence as indexed by the provided index on the OEIS page.
You must support all values provided in the OEIS b files for that sequence, any number not in the b files need not be supported.
## Scoring
Your score will be the number of bytes in your code, with less bytes being better.
[Answer]
# Python 3, 59 bytes, [A162626](https://oeis.org/A162626), [cracked](https://codegolf.stackexchange.com/a/137434/59523)
```
lambda n:n*(n+1)*(n+2)/3if 0<=n<=3else n*(n**2+5)/3#A162626
```
This ~~is~~ was supposed to be impossible, wasn't it?
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes, [A017016](https://www.oeis.org/A010716) ([Cracked](https://codegolf.stackexchange.com/a/137391/59487))
```
n=int(input())
print(sum(1for i in"A017016"if i>"0")*-~n//-~n)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P882M69EIzOvoLREQ1OTq6AIxC0uzdUwTMsvUshUyMxTcjQwNDcwNFPKTFPItFMyUNLU0q3L09cHEpr//5sAAA "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 13 bytes ([Cracked](https://codegolf.stackexchange.com/a/137413/58974))
There is (at least) one other solution, if anyone else wants to take a stab at it.
```
p#A000012uCnG
```
[Try it online](https://tio.run/##y0osKPn/v0DZ0QAIDI1KnfPc//@3AAA)
[A000012](https://oeis.org/A000012)
---
## Explanation
>
> `#` followed by a character in Japt gives us the charcode of that character, so `#A=65`, which the rest of the number then gets appended to, giving us `65000012` or `65000290`.
>
>
>
> `u` is the modulo method (it differs from `%` in that it will always return a positive number).
>
>
>
> The `n` method subtracts the number it is applied to from the number passed to it. `C` and `G` are the Japt constants for 11 & 15, respectively. So, `CnG` gives us `4`.
>
>
>
> We now have `65000012%4=0` and `65000290%4=2`. The `p` method raises the number it's applied to (in this case that is, implicitly, the input integer `U`) to the power of the number passed to it, giving us the 2 final formulas of `U**0` and `U**2`.
>
>
>
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~30~~ 29 bytes ([Cracked](https://codegolf.stackexchange.com/a/137544/72733))
```
A077430I\2-|Gw^1Mwx*10&Ylk1+&
```
[A077430](https://oeis.org/A077430)
[Try it online!](https://tio.run/##y00syfn/39HA3NzE2MAzxki3xr08ztC3vELL0EAtMifbUFvt/38LEwA "MATL – Try It Online")
-1 byte thanks to @Sanchises
[Answer]
# C#, 28 bytes ([Cracked](https://codegolf.stackexchange.com/a/137384/38550))
```
n=>n*n*("A000290"[6]<49?1:n)
```
Works with [A000290](https://oeis.org/A000290).
An easy one to get this started.
[Try it online!](https://tio.run/##Sy7WTc4vSv2fl5ibWlyQmJyqEFxZXJKay1XNpQAEyTmJxcUKAWA2RAQEiksSSzKTFcryM1MUfBMz8zQ04VIIRSDgVpqXbJOZV6KjACTsFNIUbBX@59na5WnlaWkoORoYGBhZGihFm8XamFjaG1rlaf635kLR75yfV5yfk6oXXpRZkuqTmZeqkaZhpKlpTVCRMTGKTIhRZApShFVVUGpiClgRkim1XBCy9j8A "C# (.NET Core) – Try It Online")
[Answer]
# Python 2, 43 bytes, [A000079](https://oeis.org/A000079) ([Cracked](https://codegolf.stackexchange.com/a/137405/66855))
[Try it online](https://tio.run/##K6gsycjPM/rvYxvzPycxNyklUSHPSkOjuDRXIzexQCO/KEVH3dEACMwt1TU1tYw0VS00tbTy/qflFylkKmTmKRQl5qWnahjoGBoYaFpxcRYUZeaVKGTqKPhoZGr@BwA)
```
lambda n:((sum(map(ord,'A000079'))*2)%8)**n
```
[Answer]
# C#, 75 bytes, ([Cracked](https://codegolf.stackexchange.com/a/137414/38550))
```
n=>{int r=1,e=3-0xA000244%2;for(;n>0;e*=e){r*=(n%2>0?e:1);n>>=1;}return r;}
```
[A000244](https://oeis.org/A000244)
[Try it online!](https://tio.run/##VU7LagMxDLzvV@gSsPPCu82pjh1KoacWSnvo2ThaMGTlYjulZfG3b70JfXgO0kiakWTjZvDkJzIDxndjEV6/YsKhGRsosCcTIzxf@LUzIyaTnIUP747wZBwx/jv6E814OJPdO0prKEFDD2oipcdSQFDtGtXNRnzeCSG63W7Ryd4HJkkLiUuFfAxLxWjRaXHA25aXgVatzAHTORAEmSfZVNeKHdi824ECIUvaK2gLWa0cr5T1lzPuPUV/wu1bcAkfHSHrmeNcVsJc3/vxvKA5Xiz/5Lm5xjx9Aw "C# (Mono) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes, [A000012](https://oeis.org/A000012) [[cracked]](https://codegolf.stackexchange.com/a/137424/59523)
```
lambda x:len(`x**(sum(map(int,'A000012'[1:]))==22)`)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCKic1TyOhQktLo7g0VyM3sUAjM69ER93RAAgMjdSjDa1iNTVtbY2MNBM0Ff4XFAFlFdKAagpKSzQ0Nf8bGRsZAQA "Python 2 – Try It Online")
>
> The next sequence is A055642(length of digits in a decimal number). For which the number evaluates to itself, since sum of the digits in OEIS equals 22; the len(...) thus calculates to actual length of the input number for 'A055642'. For sequences A000012(or any other than A055642. The len will always equal to one, since the number evaluted will be '1'.
>
>
>
[Answer]
## Haskell, 226 bytes, safe!
Not sure if clever or ugly, maybe both...
```
o n=read.pure.(!!n)$"A001906"
m::Integral a=>[a->a->a]
m=[const,(+),(-),(*),div,(^)]++(flip<$>m)
l=o 1:o 3-o 1:zipWith(m!!(o 6+o 3-o 2))(tail l)l
f=(l!!).((m!!(o 4+o 5+o 6-2*o 1-o 2))$sum[1|n<-[1..6],odd(o n)]).((m!!o 6)$o 3)
```
So now this computes [A001906](https://oeis.org/A001906), but it should be able to generate a lot of sequences.
[Try it online!](https://tio.run/##LcxNasMwEAXgvU4xCl5oYlnIaWuIiQxd9gRdGBdEbDci@sNWuii9u6uQwDwGhm/eRa/XydptC@DVMulRxNsyCUapx2L3LmV9lM2OuLb98Gn6XrQFrbpeV919BuJUfw5@TZyVyFmVs0c@mh/OvnAoSzZbE09F55BYFaBuA7xU9/1r4qdJF@YoZQGa8nE/ILKkjQWLlsyKWUpRsCd6zegtp6kO@1zx4MV6c339509VXwvRDDyMY7Yeh@dj9ljkdiSb08aDgrgYn6AApyPM0Eshajls/w "Haskell – Try It Online")
---
Solution: [A131078](https://oeis.org/A131078)
Wondering if this was too difficult or no one tried?
`o 1` to `o 6` are the digits of the series number, `m` is a list of operations. `l` is a recursively defined infinite list with the first two values derived from the series number and the remaining ones computed from the previous two using a fixed operation from `m`. In the case of A001906, the definition can be simplified to
```
l=0:1:zipWith(flip(+))(tail l)l
```
`(flip(+))` is (usually) the same as `(+)`, and we get a well known (but not the shortest) definition of the Fibonacci numbers. This recursion scheme could directly compute A001906, but that needs an operation more complicated than those in `m`. Another example: using starting values `1` and `2` and the operation `(*)` gives the series [A000301](https://A000301). It is computed by our code when the series number is replaced with `?103206`.
Finally, the function `f` indexes into the list `l`, but only after some transformation of the input. For A001906, the middle part reduces to `(*)2`, so that we only get the Fibonacci numbers at even positions. The right part becomes `flip const 1`, which is the identity function and does not further interfere.
For the solution `A131078`, the starting values of `l` are `1` and `0`, and the operation is `flip const`, which lets `l` be `1,0,1,0,...`. The middle part of `f` becomes `(flip div 4)`, resulting in `1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,...`. This looked like a nice answer, but then I saw that A131078 starts at `n=1`, so I added the right part of `f`, which here is `flip(-)1` to subtract one.
My idea was to make it a bit obfuscated by using `m` and indexing into it with digits from the series numbers, then it became more obfuscated (complicated terms) to make it work (maybe I wasn't searching long enough for alternatives); and then it became even more obfuscated (right part of `f`) to make it really work. Still I think some guessing and trying could have cracked it.
[Answer]
# Python 3, 65 bytes, A000027, cracked
```
a=lambda a,n=((int("A000027",11)-0x103519a)%100%30+1)/2:a//(14-n)
```
Yay crazy arithmetic!
[Answer]
# Smalltalk, 148 bytes, safe!
```
|x o|x:=(16rA018253*0.00861-1445345)floor. o:=OrderedCollection new. 1 to:x/2 do:[:i|x\\i=0 ifTrue:[o add:i]].o add:x.^o at:stdin nextLine asInteger
```
[A018253](https://oeis.org/A018253)
Takes an integer as input, sequence is 1-based.
>
> The intended second sequence is [A133020](https://oeis.org/A133020). In the writeup for [A018253](https://oeis.org/A018253) is a link to a [list of entries for sequences related to the divisors of numbers](https://oeis.org/index/Di#divisors). In that list, [A133020](https://oeis.org/A133020) is under *divisors of squares: 100²*. If you want to see the entire sequence, insert `Transcript show: o printString; cr.` before the return `^` statement in the code.
>
>
>
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 52 bytes, [cracked](https://codegolf.stackexchange.com/a/137555/48198)
This one works with [A000217](https://oeis.org/A000217):
```
?SaA000217d8d1+Sb%1r-dScla*r10 7^-Lb%+la*1+Lc+La*2/p
```
[Try it online!](https://tio.run/##S0n@/98@ONHRwMDAyNA8xSLFUDs4SdWwSDclODknUavI0EDBPE7XJ0lVG8gz1PZJ1vZJ1DLSL/j/39AAAA "dc – Try It Online")
[Answer]
# Python 3.6, 114 bytes, [cracked](https://codegolf.stackexchange.com/a/138295/56819)
```
from random import*
g=lambda n:eval(''.join(Random("A005843").choices('n8-9+17n#8*+26%n1 32-3+4-545*-#6*7',k=34)))
```
[A005843](https://oeis.org/A005843)
`g(n)` returns the n-th value of the sequence for n >= 0.
`random.choices(s,k)` is new in Python 3.6, it returns `k` items selected from `s` with replacement.
[Answer]
# [Chip](https://github.com/Phlarx/chip), 67 bytes, [cracked](https://codegolf.stackexchange.com/a/138357/56819) by Yimin Rong
```
2D5B#{*Cm49!}E-7
(A000012d#,zkmsh
b-\6/e2)[1Zv^~^S
33a#kcf3g88taz1@
```
[A000012](http://oeis.org/A000012). A bit cheeky, yes.
[Try it online!](https://tio.run/##PZBNT4NAEIbv/IqxHLqrsBRQi2lr/KpXD97UtFnYBTYVdmWnCrX615Ea4xwmed68eTKZlNuyzzjCJVj5xrLSwHwOy4f7Pro7u3E/j2@r04ujr6U/dcj1ZJgwEq6321S2dFL/5TyQEX0On95X36tHJ465u8nyuEgS5Lvwqh88jnOwM1WbLTJUGvZgOix1HYOfwUhVRjcItrMzaGEBqkYyALMoVM0ayQWhdAZ/kR4c6TbPZcM@GoWStAz1Ou1QWlLxlgycKly/yrrAktCTKQ2CxAupB4eOboRsFuNUFWNKR8MhgTYYZKUyv4uZ7v8He9ACfNFPfgA "Chip – Try It Online")
Uses bytes for i/o, so I was nice and built a bashy/pythony wrapper.
---
>
> Alternate sequence is [A060843](http://oeis.org/A060843). [Try it online](https://tio.run/##PZBNT4NAGITv/IrXcuiuwlJKbTFtjV/16sGbmja7sMCmwq7sW4Va/etIjfEyyUwmTyYjuC26hCNcgpVvLCkMLBawerjvxnfnN@7n6W05uTj5Wvkzh1yPpqN4EqWut9@WtnCE/zIN5Jg@h0/v6@/1oxNF3N0mWZTHMfJ9eNX1HMc50pmqzA4ZKg0HMC0WuorAT2CgSqNrBNvaOTSwBFUh6Q2zmKqK1ZKnhNI5/EW6Z4hdlsmafdQKJWkY6o1oUVpS8ob0XijcvMoqx4LQsxkNgtgLqQfHjq5TWS@HQuVDSgf9kEAbDJJCmV9hpv3/4AA6BT/tJj8 "Chip – Try It Online") for inputs `1..4`.
>
>
>
> Yimin Rong hunched right, such a short Chip program can only calculate very simple things. The original sequence is all one's, and the alternate sequence is the busy beaver numbers, of which only 4 are known.
>
>
>
> These numbers, `1, 6, 21, 107`, are simply hard-coded for the inputs `1..4`.
>
>
>
> One interesting thing about using Chip for this challenge is that the digits `0`-`9` are not numbers, but logical elements. Specifically, `0`-`7` are the eight bits addressing the head of the stack, and `8` and `9` are the read and write toggles. That made this a bit more interesting and much more obfuscated.
>
>
>
> A potential giveaway is that only `A`-`D` appear, meaning that we only have 4 bits for indexing the sequence. This meant that there could be at most 16 different values. In fact, only `A`-`C` are actually used for the alternate sequence, giving at most 8 different values.
>
>
>
> For any who might be interested, here is the same code, stripped of the no-ops and unused elements:
>
>
>
.
>
>
> ```
> B *C 49!
> A000012d ,z s
> b-\6/e 1Zv-~^S
> `3a`-cf3g`8taz1
>
> ```
>
>
] |
[Question]
[
3D-modeling software mainly uses [UV Mapping](https://en.wikipedia.org/wiki/UV_mapping) to map textures onto a 3D object. The valid values for both U and V are usually located in an inclusive `[0..1]` range.
## Challenge
You bought a new 3D-modeling software which is super-easy to use. However there is one issue with it: it adds or subtracts a random integer number from UV values. Your task is to create a program or a function that modifies an input value to get a float value in an inclusive `[0..1]` range.
The resulting float should have the same fractional part as the original, and be as close to the original as possible. Because both `0` and `1` are in the output range, any integers 0 or less should change to 0, and any integers 1 or greater should change to 1.
An example algorithm in JavaScript:
```
function modFloat(input) {
while (input < 0 || input > 1) {
if (input < 0) input += 1;
if (input > 1) input -= 1;
}
return input;
}
```
## Rules
* Input is a single integer or float value. Any reasonable format is allowed as long as it is specified in your answer.
* The output should be a decimal representation of a float value.
* The output precision should be at least same decimal places as input.
* Trailing zeros are allowed.
* Be sure your code correctly chooses which of 0 or 1 to output for integer inputs.
## Test cases
```
Input | Output
------------+---------
-4 | 0
-1 | 0
0 | 0
1 | 1
2 | 1
1.0001 | 0.000100
678.123456 | 0.123456
-678.123456 | 0.876544
4.5 | 0.5
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# [Python](https://docs.python.org/2/), 20 bytes
```
lambda x:x%1or+(x>0)
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQYVWhaphfpK1RYWeg@T85sTi1WMFWIVrXSEfXUM8YSOjo6hnqGOgA2XrmOoY6RjrGepaxXGn5RQoVCpl5CmAdVlycBUWZeSUKFToK6jEl6joKaRoVmv8B "Python 2 – TIO Nexus")
Takes the input modulo 1, then handles the boundary case by converting outputs of 0 to 1 for positive inputs. A bool output would save two bytes.
```
lambda x:x%1or x>0
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 11 bytes
*Thanks to Fatalize for golfing 3 bytes.*
```
∧≜:?+.≥0∧1≥
```
For a change, this answer doesn't use mod :)
[Try it online!](https://tio.run/nexus/brachylog2#@/@oY/mjzjlW9tp6jzqXGgB5hkD6//94M0MLPUMjYxNTs/9RAA "Brachylog – TIO Nexus")
### Explanation
```
∧≜ Label an integer variable. This will start trying different
values for this variable, the ones closest to 0 first.
:?+. This variable summed to the input is equal to the output
.≥0∧1≥ which is >= 0 and <= 1
```
[Answer]
# JavaScript (ES6), 19 bytes
```
n=>(n%1+1)%1||n>0|0
```
In JavaScript, `n%x` returns a negative number if `n` is negative, meaning that if we want to get the positive residue, we must add `x` if `n` is negative. `(n%x+x)%x` covers all cases:
```
n n%1 n%1+1 (n%1+1)%1
0 0 1 0
1 0 1 0
2.4 0.4 1.4 0.4
-1 0 1 0
-2.4 -0.4 0.6 0.6
```
Another working solution at 20 bytes, which shows a bit more of a pattern:
```
n=>n%1+(n%1?n<0:n>0)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
1&\0>yg>+
```
[Try it online!](https://tio.run/nexus/matl#@2@oFmNgV5lup/3/v5m5hZ6hkbGJqRkA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/hvqBZjYFeZbqf9P8Il5L@uCZeuIZcBlyGXEZehnoGBgSGXmbmFnqGRsYmpGZcuEttEzxQA).
### Explanation
Example with input `678.123456`
```
1 % Push 1
% STACK: 1
&\ % Implicit input. Divmod with 1
% STACK: 0.123456, 678
0> % Is it positive?
% STACK: 0.123456, 1
y % Duplicate from below
% STACK: 0.123456, 1, 0.123456
g % Convert to logical: nonzero becomes 1
% STACK: 0.123456, 1, 1
> % Greater than? This is true if fractional part of input was zero
% and non-fractional part was positive
% STACK: 0.123456, 0
+ % Add. Implicitly display
% STACK: 0.123456
```
[Answer]
# Javascript, 28 bytes
```
m=f=>f<0?m(f+1):f>1?m(f-1):f
```
Recursively decreases/increases the values by 1 until the result is in [0,1]
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
u1 ªUbV1
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=dTEgqlViVjE=&input=Mg==)
I think this is the first time I've ever used `b`...
### Explanation
```
u1 ªUbV1 // Implicit: U = input, V = 0
Uu1 // Take U%1, but add 1 if U is negative. This is equivalent to %1 in Python.
ª // If the result is falsy (0), instead take
UbV1 // U bound between 0 and 1.
// This converts positive integers to 1, zero/negative integers to 0.
// Implicit: output result of last expression
```
[Answer]
## Mathematica, 20 bytes
```
#~Mod~1/. 0/;#>0->1&
```
### Explanation
This is a rather unusual use of `/;` where I'm using it more like an `&&` because the condition after it has nothing to do with the pattern it matches.
```
#~Mod~1...
```
Compute `x % 1`, which is correct for all cases except positive integers.
```
.../. 0/;...
```
Replace zeros in the previous expression if...
```
...#>0...
```
...the input is positive...
```
...->1...
```
with `1`.
[Answer]
# PHP, 37 bytes
```
<?=($m=fmod($argn,1))+(!!$m^$argn>0);
```
Run with `echo <number> | php -R '<code>'`.
There are so many ways to do this ... this should be one of the shortest in PHP.
The `fmod` result is negative for negative floats and `0` for positive integers; those need adjustment: `!!$m` is true for floats, xoring with `$n>0` results in false for positive float and negative int, true for negative float and positive int; `+` casts that to `1` or `0` - done.
[Answer]
## C ~~57~~ ~~56~~ 73 bytes
```
b;f(float n){b=n;printf("%f",((!(n-b)&&n<=0)?0:n<0?1.+n-b:(n-b)?n-b:1));}
```
@pinkfloydx33 Thanks for pointing out!
#
Ungolfed version:
```
f(float n)
{
int b=n;
printf("%f",( (!(n-b)&&n<=0)?0:n<0?1.+n-b:(n-b)?n-b:1) );
}
```
[Try it online!](https://tio.run/nexus/c-clang#HYzBCoMwEAXv@YpXobJLa0muRsm3RHGp0K4lxJP42T2n2tswA1OE5LXEDGWzGWDWjKFXb/BJBwtVV6nuRBfSZuC61q63HGyrnQ3ucTtk@y/hJMdgb3ZTzss7zkq8QcixR5rymhTWYy9fXZoxjs/pBw "C (clang) – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
%1o>0$
```
**[Try it online!](https://tio.run/nexus/jelly#@69qmG9noPL/6J7D7Y@a1rj//x@ta6Kja6hjoGOoY6RjqGdgYGCoY2ZuoWdoZGxiaqaji8Q20TONBQA "Jelly – TIO Nexus")**
Jelly has no `True` or `False`, but uses `1` and `0` in their place.
```
%1o>0$ - Main link: float v
%1 - v mod 1
$ - last two links as a monad
>0 - v greater than zero?
o - or - replace the 0 result of the mod with 1 when v is greater than 0.
```
[Answer]
# SmileBASIC, 28 bytes
```
INPUT N?N-FLOOR(N)+(N<<0==N)
```
[Answer]
## JavaScript (ES6), 19 bytes
```
n=>(n>0==!(n%=1))+n
```
Explanation: `%1` doesn't give the correct results in all cases:
```
input %1 output
-ve int -0
-ve frac -ve frac +ve frac
0 0
+ve frac +ve frac
+ve int 0 1
```
An extra 1 needs to be added in the cases that are wrong, which are those of a negative non-integer and a positive integer. This is what the expression `(n>0==!(n%1))` calculates.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 26 bytes
```
:1%:?vr1(?v1n;
>n;n0<
```
[Try it online!](https://tio.run/nexus/fish#@29lqGplX1ZkqGFfZphnzaUAAnZ51nkGNv///9ctUzAAAA "><> – TIO Nexus")
Because solutions in *good* golfing languages are almost always pretty instantly given, I decided to mix things up. First <>< answer!
## Explanation
```
:1%:?vr1(?v1n; Assume input i in stack
>n;n0<
: Duplicate i (need it if i%1 != 0)
1 Push 1
% Pop i and 1, push i%1
: Duplicate top of stack because we need one for the if
?v If i%1 != 0 ------------------------,
r Reverse stack so that i is TOS |
1(?v If i > 0 (not < 1) |
1n; Print 1 and Exit |
Else |
n0< Print 0 and --, |
>n Print n <-------|-------------------'
; Exit <----------'
```
Fun fact: the explanation is a valid <>< program!
[Answer]
# Javascript, ~~41~~ 28 bytes
```
n=>n-Math.floor(n)+(n<<0==n)
```
`Math.floor()` is so long...
[Answer]
# Pyth, 7 bytes
```
|%Q1s<0
```
Explanation
```
|%Q1s<0
|%Q1s<0Q Implicitly add input
%Q1 Input mod 1
| Short-circuting or
s<0Q 1 if input is positive, 0 otherwise
```
If you don't mind using True and False as 1 and 0, you can drop the `s` for 6 bytes.
[Answer]
# [Perl 6](https://perl6.org), 15 bytes
```
{+($_%1||$_>0)}
```
[Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLU7D9X62toRKvalhToxJvZ6BZ@z8tv0hB10RHQddQR8FARwFIGgFJPQMDAyDTzNxCz9DI2MTUDKgAmWOiZ6qga6egkqdQzaUABMWJlQppQK41V@1/AA "Perl 6 – TIO Nexus")
Inspired by [seshoumara's comment](https://codegolf.stackexchange.com/questions/111174/mod-the-floats#comment270808_111174) that mod 1 *almost* works.
*EDIT: Ha, [xnor's Python solution](https://codegolf.stackexchange.com/a/111182/14880) beat me to it.*
] |
[Question]
[
Getting the area covered by a rectangle is really easy; just multiply its height by its width. However in this challenge we will be getting the area covered by multiple rectangles. This is equally easy ... so long as the rectangles don't overlap.
If the rectangles don't overlap the total area covered is the sum of the areas of each individual rectangle. However if they do overlap this method will double count the area they intersect.
For example, in the following picture we have 2 rectangles: A rectangle with opposite corners at \$(3,7)\$ and \$(9,3)\$ and a rectangle with opposite corners at \$(8,10)\$ and \$(14,4)\$. On their own they cover \$24\$ and \$36\$ square units respectively. However they have an overlap area of 3 units so the total area covered by the both of them is \$24 + 36 - 3 = 57\$
[](https://i.stack.imgur.com/yZIYB.png)
# Task
Your task is to take a list of positive integer rectangles as input and output the total area covered by those rectangles.
You may take a rectangle as a pair of pairs representing opposite corners, or as a flattened 4-tuple. You may assume a particular pair of corners in a certain order will be given if you please.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal.
## Test cases
```
[((3,7),(9,3))] -> 24
[((8,10),(14,4))] -> 36
[((3,7),(9,3)),((8,10),(14,4))] -> 57
[((8,10),(14,4)),((3,7),(9,3)),((5,8),(10,3))] -> 61
[((1,1),(8,8)),((2,3),(3,5))] -> 49
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~60~~ 59 bytes
```
->r,*w{r.map{|a,b,c,d|w|=[*a...c].product [*d...b]};w.size}
```
[Try it online!](https://tio.run/##PcpLCsIwFEbhuavoOPxeLK1okbqRyx3kYcGBGGJLsE3Xnj4Ep985YTDf3LX5eA9QcQr00n5KGgYWLsXUstJEZIV8eLvB9gUrt4KR@Rbp8xwfc/ZFx8wVLmhQicjhB1eUJ5Q1asE/gs/YffvyAg "Ruby – Try It Online")
**Input**: array of array of coordinates: [left, top, right, bottom]
Convert every rectangle to a set of cells, and calculate the size of the union of the sets.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
r/Ḋ€p/)ẎQL
```
A monadic Link that accepts a list of rectangles each composed of a list of opposing corner coordinates as specified.
**[Try it online!](https://tio.run/##y0rNyan8/79I/@GOrkdNawr0NR/u6gv0@f//f3R0tLGOeaxOtKWOcSyQirbQMTQA0oYmOiaxsbEA "Jelly – Try It Online")**
### How?
Constructs the coordinates of a corner of each unit square of each rectangle, and counts the unique values found in the resulting collection.
```
r/Ḋ€p/)ẎQL - Link: integer rectagle corner coordinates, R
) - for each rectangle, r in R:
/ - reduce by:
r - inclusive range
Ḋ€ - dequeue each (we exclude one edge, consistently, from each dimension, as we
want "fences", rather than "fence-posts")
/ - reduce by:
p - Cartesian product -> all the coordinates we want for the rectangle
Ẏ - tighten -> all coordinates used by all rectangles
Q - deduplicate
L - length
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~76~~ ~~74~~ 73 bytes
```
lambda l:len({(x,y)for*a,b,c in l for x in range(*a)for y in range(b,c)})
```
[Try it online!](https://tio.run/##bVDbboMwDH3nK/xGXHlSuZW2EvsRykOAsKJmFEEmwRDfzpxoVbdpeTo@F8d2P5vrvYu2JrtsWr6XtQR91qoTi5hoxuY@7CSVVEHbgQYuYbJwkN2bEjtpDTA/GXbiiptRoxkhA5ELEVGKJE4UIRYETBwp2DMTxBQ/qB8e@tfwi6K/gYSOVtw//wgcwymnhywQZxKW0VNTryqjajtfGBNEB4IkJTgEBPEJveqqqpsarOxfPsI0rnwCh4LIR89ubEjZnT/bXrhVCR5N8ewBP53lQlJFNZX2RIxLnoBr5JgpnMceqBEaXdEPbWdE4y9mhZdXWMYVlu9BcpVlY7H6uH0B "Python 3 – Try It Online")
*Saved 2 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!*
*Saved a byte thanks to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!!!*
Inputs a list of rectangles as flattened 4-tuples - `(left, right, bottom, top)`.
Returns the area.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
Area[RegionUnion@@Cuboid@@@#]&
```
[Try it online!](https://tio.run/##bY5La8MwEITv@hVCLcWGNYkT50WIUWhz6K0k7UnooLpKKnAsIysQcP3b3RUJgT4uYndmvh0dlf/UR@VNofr9ql87rcRWH4yt3ip8OH88vVvzwTm/kw/9kxWkNWA7uqKlqfSSGJxe7eZcO900Adh5Z6rDVtelKrQwQFsWsy8mWZKzjgGLcBFhaVknr7xTVVPbRouddX7Ab3vopANOzZK84FUvTJLvuQFGIwYW8LAE0oaPwKV2c/ZOFV7c7wpnav9c1Sd/cYARLF2XJcJJTi@z7GQvomgMsxiiBYzjWAZzlBFU55AOUU4zyK76eEp@puG/1GT2h4bf1ATmwRzeKqdpgFJIUZ6jGUIjdAHByTWTLb4B "Wolfram Language (Mathematica) – Try It Online")
Input a list of `{bottom left, top right}` pairs.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
#?,/{+a+!(|/x)-a:&/x}'
```
[Try it online!](https://ngn.bitbucket.io/k#eJxtkEsKg0AMQPc5RUqhdTCicTIfHWh7j9pFN55B6OfsjSJWbHcz770QSN/uz1Q+8nu+y57lYIp7eyiH1xGglnd/ocxiSA1aA9ZP/4hcJRYUAy4oyZYirZwBz5P8orQKHcbElT4NSDN1jJwiRnU12mTRqYKuA7jqAgqGsoY0v2FxwlpGGokrxSwkM7d+U9O/yoWfadpOOYqjrJaVnschJlYcVY5RrVbvQ25upPkAZcBBFQ==)
Or, if we can take corners as (lower-left, upper-right) pairs:
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~18~~ 15 bytes
```
#?,/{+x+!y-x}/'
```
[Try it online!](https://ngn.bitbucket.io/k#eJxtkEsKwjAQQPdzihEXJnRKO83fgHoP67ZnqIie3UkoWqq75L03Gch03J+pezRzs7u387M7AAz2NV1IGTQ5YNJgfL1HtJktcq/BBSGqFgmDziunwXOVX5RXoZMT9xils6l2jJyjgKwGcQadKBhHgKssoKBJJTJa37A94WALjSSPkmJLduHGb2r6V7nwM03bKUexyP6z0nMZYmLBUWSJBrHyP+SWxqY3RYQ/cA==)
[Answer]
# JavaScript (ES6), 96 bytes
A very basic solution that tests whether each cell in the grid belongs to at least one rectangle.
Expects a list of flattened 4-tuples.
```
a=>eval(`for(t=0,x=q=Math.max(${a});x--;)for(y=q;y--;)t+=a.some(([a,b,c,d])=>x<a^x<c&&y<b^y<d)`)
```
[Try it online!](https://tio.run/##fY9JDoJAEEX3nMKFId2xQJpBMdDcwBMQCCWDQ9BWIaaJ8ezYGhfGgapVDe//qh1esMnP22NrHERR9hXvkUflBWuSVeJMWm6B5Ce@xHZj7lGS8RVvNJCGEdDHvOOnoHsU7YSj2Yh9SUiMsIIcioTySIaYyjDX9S5cpV1Y0Iz2uTg0oi7NWqxJReLYgTkswEkSSkf/Yjod2a72SfrALGAuuAOsIp2Z9s8TBjQU6c0HPOFNxYNn//WEImfsi2TA1Javtm1wVHo/rlaku@jv "JavaScript (Node.js) – Try It Online")
### How?
When coerced to a string, an array is always turned into a flattened list of values separated with commas. For instance, `[[3,7,9,3],[8,10,14,4]]` is turned into the string `"3,7,9,3,8,10,14,4"`.
As a consequence, `eval(`q = Math.max(${a})`)` loads in `q` the highest value that can be found in `a[]`, no matter the encapsulation depth of any sub-arrays in there.
For each position \$(x,y),\:0\le x<q,\:0\le y<q\$ and each rectangle tuple \$(a,b,c,d)\$, we increment the final result if:
$$((x < a)\operatorname{XOR}(x < c)) \operatorname{AND} ((y < b)\operatorname{XOR}(y < d))$$
Note that \$((x < a)\operatorname{XOR}(x < c))\$ is true iff we have either \$x\in[a,c[\$ or \$x\in[c,a[\$ (ditto for \$y\$, \$b\$ and \$d\$). This means that the corners can be passed in any order, as suggested by the test cases (it turns out that it's actually not a strict requirement).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εøεŸ¨}`â}€`Ùg
```
[Try it online](https://tio.run/##yy9OTMpM/f//3NbDO85tPbrj0IrahMOLah81rUk4PDP9///o6GgLHUODWJ1oQxMdk1ggHW2sYw6kLHWMwTxTHQuQpAGIGwsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1sP7zi39eiOQytqEw4vqn3UtCbh8Mz0/zr/o4HAWMc8VifaUsc4NjZWRwEoYKFjaAAUMTTRMYEJIanRwaoARUgHXYOpjgVI0gBhh6GOIVDEAigOkjcCSugA9ZgCpWMB).
**Explanation:**
```
ε # Map over each pair of coordinates in the (implicit) input-list:
ø # Zip/transpose; swapping rows/columns
# (so we'll have a list [[Xa,Xb],[Ya,Yb]]
ε # Map both to:
Ÿ # Pop the pair, and push a list in this range
¨ # Remove the last item, so the range is [a,b)
}` # After the inner map: pop and push both lists separated to the stack
â # Get the cartesian product of these two lists
}€` # After the outer map: flatten this list of list of pairs one level down
Ù # Uniquify this list of cell-coordinates
g # And pop and push its length
# (after which the result is output implicitly)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
Luṁ(ΠmhṁẊ…T
```
[Try it online!](https://tio.run/##yygtzv7/36f04c5GjXMLcjOA9MNdXY8aloX8//8/OjraWMc8VifaUsc4FkhFW@gYGgBpQxMdk9jYWAA "Husk – Try It Online")
```
Lu # length of uniqe elements from
ṁ( # mapping over input:
Π # cartesian product of:
ṁ # for each coordinate pair
T # transpose
Ẋ… # and get the range,
mh # (removing the last element)
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~55~~ 52 bytes
```
!t=length(∪([a:~-c.=>(b:d-1)' for(a,b,c,d)=t]...))
```
[Try it online!](https://tio.run/##bY5NboMwEIX3nMJZZUYaUBwgIZFA6gF6AsTCgNu6chwEbpVuuu5ZeqxehI4jFKk/sxp9772Z9/xijZKXeV750mr36J/g6@MTanV8j7ukrKA99rHEtXg4j6CopY56LH2TJAnizFBYYZwYteqtcXoCjASPEqWYBms8WKxlc2WemX5VFu61V8mgxkmDQrxpd@6thpNx/KZDCkvLv@ikLgvhJRAMXQSENkgQ@oRC1zPDaJy3DvhcJVYeI@36uQZIac/WA6WIjYgrsc0ipgXJDWOZUbbwdBf9dNN/rnz/J02/UzkVQdzcXu5kCEmSjAsWg2nLKnEwXzzZ4Rs "Julia 1.0 – Try It Online")
* input is an array of flattened 4-tuples in the order `(left,bottom,right,top)`
* for each rectangle, we create all their points in the form `x=>y` with `(a:c-1).=>(b:d-1)'`
example with `(1,2),(4,6)`:
```
julia> (1:4-1).=>(2:6-1)'
3×4 Matrix{Pair{Int64, Int64}}:
1=>2 1=>3 1=>4 1=>5
2=>2 2=>3 2=>4 2=>5
3=>2 3=>3 3=>4 3=>5
```
* then `∪` (`union`) removes duplicates
* `length` is self-explanatory I think
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~42~~ 40 bytes
```
IΣE⌈Eθ⌈ιΣE⌈Eθ⌈λ⊙θ∧››§ν²ι›§ν⁰ι››§ν³λ›§ν¹λ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sQCIKzJzoexCHQXHEs@8lNQKjUwdBSNNTU0dBQLqcnQUjMHqHPMqweJ5KRruRamJJalFcBqmNg9kpo5CJhBjkTIASyHJYVFjDJTOwa7dECwFB9b//0dHR1vomOgYApFBrE60sY6xjqWOOZBlCmQZGuhYxMbG/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of 4-tuples (bottom, left, top, right). Edit: Saved 2 bytes after reading @Arnauld's answer. Explanation:
```
Eθ Map over input list
⌈ι Get maximum co-ordinate
⌈ Take the maximum
E Map over implicit range
Eθ Map over input list
⌈λ Get maximum co-ordinate
⌈ Take the maximum
E Map over implicit range
θ Input list
⊙ Does any rectangle match
ι ι Current y value
››§ν² ›§ν⁰ Inside rectangle bounds
λ λ Current x value
››§ν³ ›§ν¹ Inside rectangle bounds
∧ Logical And
Σ Take the sum
Σ Take the sum
I Cast to string
Implicitly print
```
A coordinate `x` is within a half-open range `[a, b)` if it is less than `b` but not less than `a`. In normal logic, this is written `(b>x)&&!(a>x)`, however the `&&!` operator works out as equivalent to the `>` operator so the result is simply `(b>x)>(a>x)`.
[Answer]
# Scala, 72 bytes
```
_.map{(?,<,c,d)=>Set(?to c-1*)flatMap(d+1 to<map _.->)}.reduce(_|_).size
```
[Try it in Scastie!](https://scastie.scala-lang.org/zwsNlmexS3mDBgUCawJD7Q)
Does it the simple, stupid way: by making sets of all the points each rectangle contains and then finding the size of their union. Input is a list of flattened 4-tuples, with the top left corner first and the bottom right corner second.
[Answer]
# [Python 3](https://docs.python.org/3/), 83 bytes
```
lambda a:len({*chain(*[product(*map(range,*x))for x in a])})
from itertools import*
```
[Try it online!](https://tio.run/##bY9BDoIwEADvvKLHbbMHayEiiS9BDhWoNIG2qTXBGN9eKwlGjXvbmdnDulsYrBFRHY5xlNOpk0RWY2/gztpBagOsdt521zYAm6QDL825RzZTqqwnM9GGyIY@aKa8nYgOvQ/WjheiJ2d9YPFd1TWAQEER9rijtMEsgRLzBHiOfLOijwb/Bl8Ifw@KZeMbLNeeI0@kfIHkt4sXWCTdVBlJ47w2ARSkn@IT "Python 3 – Try It Online")
-3 thanks to pxeger.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 11 bytes
```
N†⊢×⊢
↑¦|⊢l
```
[Try it online!](https://tio.run/##S0/MTPz/3@9Rw4JHXYsOTwcSXI/aJh5aVgNk5fxPBbP/RytER0cbK5jHKkRbKhjHxsaC@BYKhgZAhqGJgglUBEmFAjZ5FBEFdPWmChYgSQO4BYYKhkDaAigM4hoBxRWAWkxBsrEA "Gaia – Try It Online")
```
N†⊢×⊢ -- helper function to convert rectangle corners to coordinate list
N†⊢ -- reduce rows by vectorized half-inclusive range
×⊢ -- reduce the two ranges by cartesian product
↑¦ -- map the helper function over each rectangle
|⊢ -- reduce by set union
l -- take the length
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 77 bytes
```
x=>x.map(([i,b,c,d])=>{for(;i++<c;)for(j=b;j++<d;)x[y=[i,j]]=s+=!x[y]},s=0)|s
```
[Try it online!](https://tio.run/##fY7NDoIwEITvPgXe2rACFRAIlhdpesAiBqKUUGMw6rPXJV6MP2z2MJPMN7tteSmNGpr@vOp0tbc1tyMvRu9U9oSIBnagoJKUF7daDyRvXHercjrplu/yFm2V01FcOWZbKblx@RKtfIDhAb0bq3Rn9HHvHfWB1ESIEELIIJGSUuff@L6zjhafZAoRMNxghkUy3Cz@3YSZDiTjZOYmvLXEqFgA6asEyQ37IhkwSDECYg0TGf/4Gskos08 "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
[Sociable numbers](https://en.wikipedia.org/wiki/Sociable_number) are a generalisation of both [perfect](https://en.wikipedia.org/wiki/Perfect_number) and [amicable numbers](https://en.wikipedia.org/wiki/Amicable_number). They are numbers whose proper divisor sums form cycles beginning and ending at the same number. A number is \$n\$-sociable if the cycle it forms has \$n\$ unique elements. For example, perfect numbers are \$1\$-sociable (\$6\to6\to\cdots\$) and amicable numbers are \$2\$-sociable (\$220\to284\to220\to\cdots\$).
Note that the *entire* cycle must begin and end with the same number. \$25\$ for example is not a \$1\$-sociable number as it's cycle is \$25 \to 6 \to 6 \to \cdots\$, which, despite containing a period \$1\$ cycle, does not begin and end with that cycle.
The proper divisor sum of an integer \$x\$ is the sum of the positive integers that divide \$x\$, not including \$x\$ itself. For example, the proper divisor sum of \$24\$ is \$1 + 2 + 3 + 4 + 6 + 8 + 12 = 36\$
There are currently \$51\$ known \$1\$-sociable numbers, \$1225736919\$ known \$2\$-sociable pairs, no known \$3\$-sociable sequences, \$5398\$ known \$4\$-sociable sequences and so on.
You may choose whether to:
* Take a positive integer \$n\$, and a positive integer \$m\$ and output the \$m\$th \$n\$-sociable sequence
* Take a positive integer \$n\$, and a positive integer \$m\$ and output the first \$m\$ \$n\$-sociable sequences
* Take a positive integer \$n\$ and output all \$n\$-sociable sequences
If you choose either of the last 2, each sequence must have internal separators (e.g. `220, 284` for \$n = 2\$) and distinct, external separators between sequences (e.g. `[220, 284], [1184, 1210]` for \$n = 2\$). For either of the first 2, the sequences should be ordered lexicographically.
You can choose whether to include "duplicate" sequences, i.e. the sequences that are the same as others, just beginning with a different number, such as including both `220, 284` and `284, 220`. Please state in your answer if you do this.
The [Catalan-Dickson conjecture](https://en.wikipedia.org/wiki/Aliquot_sequence#Catalan%E2%80%93Dickson_conjecture) states that every sequence formed by repeatedly taking the proper divisor sum eventually converges. Your answer may assume this conjecture to be true (meaning that you are allowed to iterate through each integer, testing if it is \$n\$-sociable by calculating if it belongs to an \$n\$-cycle, even though such approaches would fail for e.g. \$276\$ if the conjecture is false).
You may also assume that for a given \$n\$, there exists an infinite number of \$n\$-sociable sequences.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins
## Test cases
```
n -> n-sociable sequences
1 -> 6, 28, 496, 8128, ...
2 -> [220, 284], [284, 220], [1184, 1210], [1210, 1184], [2620, 2924], [2924, 2620], [5020, 5564], [5564, 5020], [6232, 6368], [6368, 6232], ...
4 -> [1264460, 1547860, 1727636, 1305184], ...
5 -> [12496, 14288, 15472, 14536, 14264], [14264, 12496, 14288, 15472, 14536], ...
6 -> [21548919483, 23625285957, 24825443643, 26762383557, 25958284443, 23816997477], ...
8 -> [1095447416, 1259477224, 1156962296, 1330251784, 1221976136, 1127671864, 1245926216, 1213138984], ...
9 -> [805984760, 1268997640, 1803863720, 2308845400, 3059220620, 3367978564, 2525983930, 2301481286, 1611969514], ...
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes
Generates the sequences with duplicates.
```
;X{≠tℕfk+}ᵃ⁽At~hAk
```
[Try it online!](https://tio.run/##ATcAyP9icmFjaHlsb2cy/3vihrDigoLhuol94bag/ztYe@KJoHTihJVmayt94bWD4oG9QXR@aEFr//8y "Brachylog – Try It Online")
### How it works
```
;X{≠tℕfk+}ᵃ⁽At~hAk implicit input n
;X [n, something]
{ }ᵃ⁽ starting with [something], generate a list
by applying {…} n times:
≠ all elements are different
t the last element
ℕ is a natural number
f and its factors
k without itself
+ summed
-> [220, 284, 220]
A is A
t A's tail
~h is the head
A of A
k output A without the last element
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~86~~ ~~84~~ 78 bytes
```
->n{1.step{|x,*a|x==(n.times{a|=[x=(1...x).sum{|i|x%i>0?0:i}]};a[n-1])&&p(a)}}
```
[Try it online!](https://tio.run/##BcFBCoAgEADA1xQatWjHYush4sGgwEMiabDh@nabed7jaxe2aQtFQ8pnLEzj4JgQRYDs7zMVx2gIhQYAkpDeu7Bn6vymdrX4auvqTJi0lX0fhZO1tsvMtv0 "Ruby – Try It Online")
Prints the sequence for a given \$n\$ infinitely.
6 bytes saved by G B.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 69 bytes
Takes a positive integer n and outputs all n-sociable sequences
```
Do[NestList[Tr@Divisors@#-#&,d,#]/.{a__,d}/;0!=a:>Print@{a},{d,∞}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yU/2i@1uMQns7gkOqTIwSWzLLM4v6jYQVlXWU0nRUc5Vl@vOjE@XielVt/aQNE20couoCgzr8ShOrFWpzpF51HHvNpYtf/p0Uax//8DAA "Wolfram Language (Mathematica) – Try It Online")
-20 bytes thanks to @att
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~106 97~~ 96 bytes
*Saved 1 byte thanks to @tsh*
A function that takes \$n\$ and prints the sequence forever, including duplicates.
```
n=>{for(k=0;a=[];)(g=j=>{for(s=d=0;++d<j;s+=j%d?0:d);a.push(s)<n?s-k&&g(s):s-k||print(a)})(++k)}
```
[Try it online!](https://tio.run/##LcjBCoMwDADQr5kkBIfsNKyZHzI8hJU6W@hK47yo3971sNvjedlEX3lJa7vdi@MS@bG7T4bAnRF@TgZhZv9PZVubyA7eKLG/2LHrLRq5pq@@QXGIo7ahaebqvuo4Ul7iCoInAlHAszi4YfkB "JavaScript (V8) – Try It Online")
### Commented
```
n => { // n = input
for( // main infinite loop:
k = 0; // start with k = 0
a = []; // a[] = sequence of proper divisor sums
) ( //
g = j => { // g is a recursive function that takes an integer j,
// fills the sequence a[] and prints it if valid
for( // loop:
s = // s is the proper divisor sum
d = 0; // d is the current divisor
++d < j; // increment d; stop when it's equal to j
s += j % d ? 0 : d // add d to s if d is a divisor of j
); // end of loop
a.push(s) // push s into a[]
< n ? // if there are less than n elements:
s - k && g(s) // if s != k, do a recursive call with j = s
: // else:
s - k || print(a) // if s = k, print a[]
} // end of g
)(++k) // initial call to g with j = k incremented
} // end of loop / end of function
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~126~~ 115 bytes
```
import Data.List
f m=[init r|r@(h:t)<-[scanl(\a x->sum[d|d<-[1..a-1],a`mod`d<1])y[1..m]|y<-[1..]],h==r!!m,t==nub t]
```
[Try it online!](https://tio.run/##JclBC4IwFADge7/iCR0UdGB0CicdOvYPbOCrKQ73pmxPSNh/X0XX75swzIO1KRlaF89wQ0ZxN4EPI5DsjDMMPvprPl24aKouvNDZ/IHwrtqwUaej/motBFa1KrGnRfe6qVWx/5BU3P@tVDlJ6bOMSpbSbU9glQiNAwmrN46PwDgPcM5HOBXpAw "Haskell – Try It Online")
* saved 10 thanks to @benrg
[Answer]
# [J](http://jsoftware.com/), 75 73 67 bytes
```
(>:@][[echo@}:^:((~.-:}:)*{.={:)@]1&((,i.@{:(1#.[#~0=|){:)@]))^:_&1
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NeysHGKjo1OTM/Idaq3irDQ06vR0rWqtNLWq9WyrrTQdYg3VNDR0MvUcqq00DJX1opXrDGxrNMEymppxVpZAoGb4X5MrTcGQC2SKgrqurq46kGv0HwA "J – Try It Online")
Prints infinitely.
Note: TIO has +3 in the byte count because I changed infinite `_` iteration to 9999 times.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
m₁fo=⁰S€₁N
Ut¡ȯΣhḊ
```
Outputs all n-sociable sequences (including duplicates beginning with different numbers).
[Don't try it online!](https://tio.run/##yygtzv7/P/dRU2Navu2jxg3Bj5rWADl@XKElhxaeWH9uccbDHV3//xv@NwQA "Husk – Try It Online"): Assumes Catalan-Dixon conjecture: calculates cycle for *every* integer befpre choosing which ones to output. So, the example on TIO stalls.
[Try this](https://tio.run/##yygtzv7/P/dRU2Navu2jxg3Bj5rWADkPdyw2NTDgCi151DbR0ODQwhPrzy3OeLij6////0YA) for a (6-byte longer) version that restricts calculations up to a cycle-length of 10 (`↑10`), and only outputs sequences arising from integers up to 500 (`ḣ500` instead of `N`).
**Explanation:**
```
Ut¡ȯΣhḊ # helper function ₁:
# calculate cycle for input integer x
U # longest unique prefix of list
t # (without first element)
¡ȯ # from repeatedly applying 3 functions:
Σ # sum of
Ḋ # divisors
h # without the last one
# to the input argument
m₁fo=⁰S€₁N # main program:
m₁ # apply helper function ₁ to each of
N # all integers x
fo # filtered to include only those for which
S€₁ # the position of x in
# the results of applying helper function ₁ to x
=⁰ # is equal to the input argument
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes
```
Nθ≔⁰ζFN«≔⟦⟧υW⁻θ⊕⌕υζ«≦⊕ζ≔ζη≔⟦⟧υFθ«≔↨Φη∧μ¬﹪ημ¹η⊞υη»»»Iυ
```
[Try it online!](https://tio.run/##TY69CsIwGEXn9Cm@8QtE8Gd0UkFwqLiLQ2yjCaSJzY@C4rPH1FopZLnJzTm3ktxVluuUduYWwz42Z@Gwpcti5b26GpwyeOZ0sQ5wXKEUXgX5lY4nBjG3yEMqLQBLZaLHlsHOVE40wgRR41aZGmOHo/1nUvLbDzDq9T4yoJ8M5Dj/VeQ7qe1Jw@uae5FFOuSFksEqGxsGexuwtHXUtrtsOj@DGR3I5BC97Jb18V3k8y4OTpmAG@4DRkqXKc1hkSZ3/QE "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` and `m` as inputs and outputs the `m`th sequence, in order of last element of the cycle, including duplicate sequences. Very slow so in practice you need `n<3`. Explanation:
```
Nθ
```
Input `n`.
```
≔⁰ζ
```
Start at zero.
```
FN«
```
Repeat `m` times.
```
≔⟦⟧υ
```
Clear any previous calculation.
```
W⁻θ⊕⌕υζ«
```
Repeat until a perfect `n`-cycle is found.
```
≦⊕ζ
```
Increment the test number.
```
≔ζη
```
Make a copy of the number.
```
≔⟦⟧υ
```
Start building a list of divisor sums.
```
Fθ«
```
Repeat `n` times.
```
≔↨Φη∧μ¬﹪ημ¹η
```
Calculate the next divisor sum.
```
⊞υη
```
Save it to the list.
```
»»»Iυ
```
Output the collected divisor sums, including the copy of the original counter as the last element of this list.
[Answer]
# Scala, ~~114~~ ~~109~~ 119 bytes
+10 bytes to fix a mistake, indirectly pointed out by AZTECCO.
```
n=>for(k<-Stream from 2;s=Seq.iterate(k,n+1)(x=>1.to(x-1).filter(x%_<1).sum).tail.distinct if s.indexOf(k)>n-2)yield s
```
[Try it in Scastie!](https://scastie.scala-lang.org/h7rdPhd9StGXoGfnvGWaFQ)
An infinite `Stream` that can also be treated as a function that returns the mth sequence. Uses `tail` instead of `init` like the previous one, so the sequences are `[284, 220]`, `[220, 284]`, `[1210, 1184]` (first element removed).
Using `>n-2`, as in Arnauld's answer, instead of `==n-1`, saves a byte.
```
n =>
for(
k <- Stream from 2 //For every integer k ≥ 2
s = Seq.iterate(k, n + 1)( //Build first n+1 terms of the sequence by repeatedly applying:
x => //Function for proper divisor sum
1.to(x - 1) //Range of possible proper divisors
.filter(x % _ < 1) //Keep only divisors
.sum //Sum them
).tail //Drop the first element (always k)
if s.indexOf(k) > n - 2 //Make sure k appears at the end of the cycle (and only there)
) yield s //Yield the sequence (without k at the start)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 104 bytes
```
n=>{for(i=1;s=++i;)for(o=[];o.push(v=s)<=n;new Set(o).size-n|s-i||print(o))for(j=s=0;++j<v;s+=v%j?0:j);}
```
[Try it online!](https://tio.run/##HctBCgIxDEDRq7gRWkKH0ZWYiR7CpbgYpMV00ZZmjKD17JVx@R/8OOss98plcXrogXqi0yfkaph2KATAaNfMdL1hHspTHkZJ7EQJk39tLn4x2Q7Cb@9SE8etlcppxf8XSWhEgDgpCpBu43k8RovfHsze9h8 "JavaScript (V8) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 105 bytes
```
function(n)repeat{y=v=T=T+1;w=n;while({z=1:y;y=sum(z[!y%%z])-y}!=T&(w=w-1)&y)v=c(v,y);if(!w&y==T)show(v)}
```
[Try it online!](https://tio.run/##Xc49CoMwGADQvaeIFCUfrYOODd8tspUiNkQMpIk1f0Tx7GmXLn0neGsxg7NCjU8tByffDssUjPDKGmpglYsc/Z4xIkd@6VhCw9KstKT7ht0ts4wuvOh2r3Jdbw9o81Ehb2jC1HbQZIgoaLxmYGqiVWoyIgc320QjHOVMbPBL8GTUmvTt70G@jyCNkO52@tvRHsoH "R – Try It Online")
Outputs n-sociable sequences indefinitely.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞εIFDѨO})}ʒćQJ}€¨
```
Outputs the infinite sequence including "duplicates".
[Try it online.](https://tio.run/##AScA2P9vc2FiaWX//@KIns61SUZEw5HCqE99KX3KksSHUUp94oKswqj//zI)
If we're allowed to output every inner list one size to large (i.e. `[6,6]` instead of `[6]` for \$n=1\$; `[220,284,220]` instead of `[220,284]` for \$n=2\$, etc.) we could omit the last three bytes:
[try it online](https://tio.run/##ASEA3v9vc2FiaWX//@KIns61SUZEw5HCqE99KX3KksSHUUr//zI).
**Explanation:**
```
∞ # Push the infinite positive sequence: [1,2,3,...]
ε # Map each to:
IF # Loop the input amount of times:
D # Duplicate the current integer
Ñ # Get its divisors (including itself)
¨ # Remove the last item (itself)
O # Take the sum of those divisors
}) # After the loop: wrap all values into a list
}ʒ # After the map: filter the list of lists by:
ć # Extract head; pop and push remainder-list and first item separated
Q # Check for each value in the remainder-list if it's equal to this head
J # Join those checks together to a string
# (only 1 is truthy in 05AB1E, including something like "00001";
# so in the filter we basically check if the first item is equal to the last
# item and NONE of the other items)
}€ # After the filter: map over each remaining inner list
¨ # And remove the final duplicated item
```
] |
[Question]
[
**The Challenge**
Given an integer input, return the first Fibonacci number that contains the input within itself along with the index of that Fibonacci number (indexes starting at 0 or 1 - up to you, but please mention which in your answer). For example, if given the input of 12, the program would return `26: 121393` as 12 is found within the number (**12**1393) and it is at index 26 of the Fibonacci numbers.
**Examples**
Given the input:
```
45
```
Your program should output:
```
33: 3524578
```
Input:
```
72
```
Output:
```
54: 86267571272
```
Input:
```
0
```
Output:
```
0: 0
```
Input:
```
144
```
Output:
```
12: 144
```
**Scoring**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
0ÆḞ©w¥1#;®
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//MMOG4biewql3wqUxIzvCrv///zMz "Jelly – Try It Online")
### How it works
```
0ÆḞ©w¥1#;® Main link. Argument: n
0 Set the return value to 0.
# Call the second link to the left with arguments k = 0, 1, 2, ... until
1 one match has been found.
¥ Combine the two links to the left into a dyadich chain.
ÆḞ Compute the k-th Fibonacci number...
© and copy it to the register.
w Yield 1 if n occurs inside the Fibonacci number, 0 otherwise.
® Yield the value stored in the register.
; Concatenate the index and the Fibonacci number.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
f=lambda n,i=0,a=0,b=1:`n`in`a`and(i,a)or f(n,i+1,b,a+b)
```
[Try it online!](https://tio.run/##DYvBCoAgEAXvfcXeSnpBihEE9i2uhLRQW0SXvt48zGWYub93v9SVksPBZ9qYFBJGcCUFu0SNopEj69YJ2FwP5a4mvUUC98mUXJWQKPkJs8MI6/3SEN2P6EuCdlhb1ElMmd0P "Python 2 – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 30 bytes
```
{first :kv,/$_/,(0,1,*+*...*)}
```
[Try it online!](https://tio.run/##BcFhCkAwAAbQq3xpiVkzGgrbVZYfVkK0SWnt7PPevbqjT@eH3EKlYDfnH4z7y2pialYI1jBaUc45LWOa4JcPGTFQGsGCmJjBXg6z7DC0EGik1FP6AQ "Perl 6 – Try It Online")
`first` is a function that returns the first element of a sequence that passes a test, and it conveniently takes a `:kv` adverb that tells it to return both the key (index) and the matching value.
[Answer]
## Batch, 104 bytes
```
@set/an=x=0,y=1
:l
@call set t=%%x:%1=%%
@if "%t%"=="%x%" set/an+=1,x+=y,y=x-y&goto l
@echo %n%: %x%
```
Works for `n=0..45` due to the limited range of Batch's integer arithmetic. Explanation: Batch doesn't have a built-in match test, but it does have an operator that can replace literal strings with other literal strings, so for example `if "%s:l=%"=="%s%"` is true if `%s%` is not empty but does not contain `l`. The use of `call` is then a trick to substitute `%1` (the input) into the replacement operator, however `call` doesn't work on control flow statements so an intermediate temporary assignment is necessary.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
³DẇÆḞ¬
0‘Ç¿µ,ÆḞ
```
[Try it online!](https://tio.run/##y0rNyan8///QZpeHu9oPtz3cMe/QGi6DRw0zDrcf2n9oqw5Y6P///@ZGAA "Jelly – Try It Online")
[Answer]
# Javascript ES6, 68 chars
```
n=>eval('for(q=x=0,y=1;!`${x}`.match(n);++q)[x,y]=[y,x+y];q+": "+x')
```
Test:
```
f=n=>eval('for(q=x=0,y=1;!`${x}`.match(n);++q)[x,y]=[y,x+y];q+": "+x')
console.log([45,72,0,144].map(f).join`
`)
```
[Answer]
# Python 3, 76 bytes
```
f=lambda n,l=[1,0]:str(n)in str(l[1])and(len(l)-2,l[1])or f(n,[l[0]+l[1]]+l)
```
[Answer]
# [Emojicode](http://www.emojicode.org/), 133 bytes
```
üêñüî¢üçáüçÆa 0üçÆb 1üçÆi 0üîÅ‚òÅÔ∏èüîçüî°a 10üî°üêï10üçáüçÆb‚ûïa büçÆa‚ûñb aüçÆi‚ûï1iüçâüòÄüî°i 10üòÄüî°a 10üçâ
```
[Try it online!](https://tio.run/##S83Nz8pMzk9J/f9h/oRuhQ/zZzUBid52EHfah/lTFoE4QLwuUcEARCUpGIKoTBBvSuOjGY3vd/QDWb1AvDBRwRAkuhCodSqIBdGY9Gje1ESFJLAZj@ZNS1JIBBsAFDXMBLI6P8yf0QDSlQnWDWFDTOrt/A8iuLg@zO9vBLuKS0EB5CYFE1MusDQA "Emojicode – Try It Online")
[Answer]
# Dyalog APL, 39 bytes
```
{⍺←0⋄∨/(⍕⍵)⍷⍕x←1∧+∘÷/0,⍺/1:⍺,x⋄(1+⍺)∇⍵}
```
Using tail recursion. Don't attempt 72, it'll break your machine because its recalculating fibonacci all over every call.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR727gJTBo@6WRx0r9DUe9U591LtV81HvdiCrAihj@KhjufajjhmHt@sb6AAV6xtaAUmdCqAGDUNtIFPzUUc7UEst0DwFE1MA)
[Answer]
# Mathematica, 119 bytes
1-indexed
```
(T=ToString;If[(h=#)==0,"0:0",a=#&@@Select[k=T/@(Array[Fibonacci,9#]),StringContainsQ[#,T@h]&];Min@Position[k,a]":"a])&
```
[Try it online!](https://tio.run/##JcyxCsIwEADQXwkNlAYCFhfRcnAiCA5CpdlChjO0zVFNoM3i10fB/fHelAP7rUxQGgMmDXnlOHe3yTYBpAJoddWeRFtpAlkjDuNr9NkuYHbYnNeVPvbKzxTJe9ZH6ZT@D5cUM3HcHlZqg8HVrrtzxD5tnDlFu2hygpwSdel/PgucBB725Qs "Mathics – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 13 bytes
```
╗1⌠F$╜@c⌡╓i;F
```
[Try it online!](https://tio.run/##AScA2P9hY3R1YWxsef//4pWXMeKMoEYk4pWcQGPijKHilZNpO0b//yIxMiI "Actually – Try It Online")
Explanation:
```
╗1⌠F$╜@c⌡╓i;F
‚ïó save input in register 0
1⌠F$╜@c⌡╓ smallest non-negative integer n where the following function returns truthy:
F$ nth Fibonacci number, stringified
‚ïú@c count occurrences of input
i;F flatten the list, duplicate the index, and push the Fibonacci number at that index
```
[Answer]
# R, 65 bytes
```
f=function(x,n=1,a=1,b=0)`if`(grepl(x,b),c(b,n-1),f(x,n+1,a+b,a))
```
Standard recursion to generate Fibnums, but instead of terminating based on `n`, terminates when `b` matches the regex `x`. This actually works surprisingly well. I assumed that using regex with numerics would require a lot of hassle converting them to strings, but that doesn't seem to be necessary :)
This also has to overshoot the recursion by 1 step, by checking on `b` instead of `a` and then substracting `1` from `n`. This is to make sure `f(0)` works properly.
This fails for most values when input exceeds `1001`, because of maxint. If we replace `a` and `b` for bigints, this works for higher inputs (current testing is at `x = 11451`)
```
f=function(x,n=1,a=gmp::as.bigz(1),b=gmp::as.bigz(0))`if`(grepl(x,b),c(b,n-1),f(x,n+1,a+b,a))
```
[Answer]
# JavaScript ES6, ~~79~~ ~~78~~ 75 bytes
-1 byte by *Step Hen*
-3 bytes by *Neil*
```
i=>eval('d=a=b=1;while(!~(a+"").indexOf(i)){c=b;b=a+b;a=c;‌​d++};d+": "+a')
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 99 bytes
```
n=>{int a=0,b=1,c,d=0;for(;b.ToString().IndexOf(n.ToString())<0;c=a,a=b,b+=c,d++);return d+": "+b;}
```
[Try it online!](https://tio.run/##dYtNC8IgGIDv@xUvnRRtLCKCzC5BEBQRBZ3VuSHUK6iLYuy3r9WpQ12fDxPHxgfbN9FhDadnTPYmMnNVMcKxzWJSyRm4e1fCXjkktM02DZqlw8QhpjBcK6hlj3LVDgyULLiWE254KQtR@UCEzs/@9CkJzbdY2sehIvgF6bIQRiqupOaayWFljIpgUxMQSjZawIhp0fUiW3uM/mrzS3DJ7hxaUpMppb/F/J@YzN6m6/oX "C# (.NET Core) – Try It Online")
Takes input as an integer, returns a string with the output.
[Answer]
# [Haskell](https://www.haskell.org/), 84 bytes
```
import Data.List
f=0:scanl(+)1f
g n=filter(isInfixOf(show n).show.snd)(zip[0..]f)!!0
```
[Try it online!](https://tio.run/##FcixCsIwEIDhvU9x3RLE0DoW0sUuBcHBURyCTdLD9FpyB4ovH@vw88E/O375lErBZVuzwODEmQuyVME2HT8dJXXQbagikA2YxGeFPFLAzzUontc3kDZ/DdOk1Re3e2PMI@i6bsrikMBC9HJeSTwJQ99b2DKSgIG4p7J3E3Qd3GS/EY49jCS6tKcf "Haskell – Try It Online")
[Answer]
## PHP, 80 bytes
```
<?php for($a=1,$b=$n=0;strpos($a=-$a+$b=$a+$b,"$argv[1]")<-1;$n++);echo"$n: $a";
```
The script is quite straightforward, simply storing the current and next terms of the sequence in $a and $b throughout. To allow for the 0th term of 0, $a and $b are initially assigned the values for the -1th term (1) and 0th term (0) respectively.
Both values are recalculated in a single expression, which is two assignments in one; effectively:
```
$b = $a + $b; // The next term is the sum of the two previous terms
$a = $b - $a; // The current term is now recalculated from the next and the previous
```
If the input value matches the beginning of the term, the strpos() function will return 0 (which is falsey and would give a false negative), but in the Wonderphul World of PHP, although `false == 0` is true and `false < 0` is false, `false < -1` is true! And so, using this comparison saves five bytes compared to `!==false`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~17~~ 14 bytes
*Saved 3 bytes thanks to @JustinMariner*
```
_ŬøU}a@[XMgX]
```
[Try it online!](https://tio.run/##y0osKPn/P/5w66E1h3eE1iY6REf4pkfE/v9vbgQA "Japt – Try It Online")
### Explanation
```
_ŬøU}a@[XMgX] Implicit: U = input integer
a@ For each integer X in [0, 1, 2, ...]:
[XMgX] take [X, Fibonacci(X)].
_ }a Return the first pair where
√Ö all but the first item
¬ joined on the empty string (simply returns Fibonacci(X) as a string)
√∏U contains U.
Implicit: output result of last expression
```
[Answer]
# [PHP](https://php.net/), ~~163~~ 141 bytes
```
<?php $x=fgets(STDIN);$b=[0,1];if($x<1)$b=[0];for(;($c=count($b)-1)&&strpos($b[$c],$x)===false;){$b[]=$b[$c]+$b[$c-1];}die($c.': '.$b[$c]);?>
```
[Try it online!](https://tio.run/##K8go@P/fxr4go0BBpcI2LT21pFgjOMTF00/TWiXJNtpAxzDWOjNNQ6XCxlATLBBrnZZfpGGtoZJsm5xfmleioZKkqWuoqaZWXFJUkF8M5EarJMfqqFRo2trapiXmFKdaa1YDBWNtITLaYEoXaGxtSmYq0Bg9dSsFdT2IpKa1vd3//wA "PHP – Try It Online")
Uses `$b[0] = 0;` and `$b[1] = 1;` for the start of fib sequence
[Answer]
# [Perl 5](https://www.perl.org/), 67 + 1 (-p) = 68 bytes
```
@f=(0,1);push@f,$f[-1]+$f[-2]while($f[-2]!~/$_/);$_=--$#f." $f[-1]"
```
[Try it online!](https://tio.run/##K0gtyjH9/98hzVbDQMdQ07qgtDjDIU1HJS1a1zBWG0QZxZZnZOakakDYinX6KvH6mtYq8ba6uirKaXpKChC1Sv//G/zLLyjJzM8r/q/ra6pnYGjwX7cAAA "Perl 5 – Try It Online")
[Answer]
# [PHP](https://php.net/), 93 bytes
```
for($a[0]=$a[1]++;!strpos(" $a[$i]","$argv[1]");$a[$i+2]=$a[$i+1]+$a[$i++]);echo"$i: $a[$i]";
```
Simple loop through the Fibonacci sequence. The check for our input number is done in `strpos(" $a[$i]","$argv[1]")`; the extra space is because `strpos` will return false-y if the 'needle' is found at the beginning of the string. We end if the input is found and echo out the required string.
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQSow1ibYGkYay2trVicUlRQX6xhpICUEQlM1ZJR0klsSi9DCirpGkNFtM2AisHMoA6IAztWE3r1OSMfCWVTCuYRuv///8bGgEA "PHP – Try It Online")
[Answer]
# Common Lisp, 105 bytes
```
(lambda(x)(do((a 0 b)(b 1(+ a b))(i 0(1+ i)))((search(#1=format()"~a"x)(#1#()"~a"a))(#1#()"~a: ~a"i a))))
```
[Try it online!](https://tio.run/##RYzRCoJAEEV/5bIS3UECN1eCoP5ldIsWtBX1oSd/3SZ86O3MHc7p@jSPG/ucRzzzhIT0xpGhweWMJqCCD0EQM2jvQRcscGsdcbpj9bWuB2cOraBDG5UfYcykmtgKW3iWUENhQkVfIokx54dO3YuFv@1VilvVmVz4YmeV/3GFDQk2iWy/wPYF)
] |
[Question]
[
Consider the string `160615051`. It can be "triangulated" as such:
```
1
606
15051
```
Then, each row is a palindrome. Also note that each side on the perimeter is also a palindrome:
```
1 | 1 |
6 | 6 |
1 | 1 | 15051
```
Therefore, this string can be considered to be a fully-palindromic triangle. Don't worry about the altitude `100` in this case, it doesn't have to be palindromic.
**Input:** A string of printable ASCII characters from 0x20 to 0x7E. This can be a character array, a single string, or an array of ASCII code points. Your input will always be able to be triangulated (that is, its length will always be a perfect square).
**Output**: A truthy value if the string is a fully-palindromic triangle, or a falsey value otherwise.
## Test cases
```
input => output
1 => true
A => true
AAAA => true
nope => false
{{}} => false
1101 => true
1011 => false
1202 => false
111110001 => true
160615051 => true
160625052 => false
1111111111111111 => true
1121123211234321123454321 => true
HHeHHeleHHellleHHellolleH => true
HellolleHHellleHHeleHHeHH => false
111111111111111111111111111111111111 => true
abcbdefeddefgfedbcdefedcbabcdefedcba => true
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes
```
J’ƲœṗZ⁻¦µU⁼
```
[Try it online!](https://tio.run/##y0rNyan8/9/rUcPMw22HNh2d/HDn9KhHjbsPLTu0NfRR457/D3dvObT16J7D7Y@a1mQB8aOGOQq2dgqPGuZG/v9vyOXI5QgEXHn5Balc1dW1tVyGhgaGXEAMJIwMjIBcIDAwAImZGZgZmhqYQlhGQBZUFgkABYyAyBhMmEApUxCDy8MjFYhywEQOlMoHMbjgLIRMKlg1hvHYAFdiUnJSSmpaagqQSAdSSclgXnJSIoIFAA "Jelly – Try It Online")
### Background
We start by looking at the 0-based indices of the input string.
```
H H e H H e l e H H e l l l e H H e l l o l l e H
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
```
To get the rows of the triangle, we can split the string before the indices **1**, **1 + 3 = 4**, **1 + 3 + 5 = 9**, and **1 + 3 + 5 + 7 = 16**. Since **(n + 1)² = n² + (2n + 1)**, these sums are precisely the positive, perfect squares in the index list. If we also split the string before **0**, this is as simple as splitting before all 0-based indices that are perfect squares.
After splitting, we get the following strings.
```
""
"H"
"HeH"
"HeleH"
"HellleH"
"HellolleH"
```
Next, we replace the empty string at the beginning with all the characters in the first column.
```
"HHHHH"
"H"
"HeH"
"HeleH"
"HellleH"
"HellolleH"
```
The task is now reduced to checking whether reversing all strings yields the same string array.
### How it works
First `J` generates all 1-based indices of the input string `J`, then decrements them with `’` to yield all 0-based indices. `Ʋ` tests all 0-based indices for squareness. For our example from above, this yields the following Boolean array.
```
1 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
```
Next, we call `œṗ` to partition the input string, e.g.,
```
H H e H H e l e H H e l l l e H H e l l o l l e H
```
before all **1**'s (actually, all truthy elements). For our example, this yields the following string array.
```
['',
'H',
'HeH',
'HeleH',
'HellleH',
'HellolleH'
]
```
`Z⁻¦` is arguably the most interesting part of this answer. Let's analyze the more straightforward `Z1¦` first.
`¦` is the *sparse* quick. It consumes two links from the stack, specifically `1` and `Z` in this case. First `Z` is applied to its argument: the string array from before. `Z` is the *zip* atom and reads the string array / 2D character array by columns, yielding
```
['HHHHH',
'eeee',
'Hlll',
'ell',
'Hlo',
'el',
'Hl',
'e',
'H'
]
```
What used to be left side of the input string and the first column of the string array now becomes the first *string*.
Now `¦` peeks at `1` and finds a single index: **1**. Thus the first string in the original string array is replaced with the first string in the return value of `Z`; strings at other indices remain unaffected.
```
['HHHHH',
'H',
'HeH',
'HeleH',
'HellleH',
'HellolleH'
]
```
Let's call this array **A**.
We used `Z⁻¦` instead of `Z1¦`, but this makes no difference: `⁻` compares the string array with the input string for inequality, yielding **1** since they're not equal. The difference between the two is that `Z⁻¦` is dyadic because `⁻` is, allowing us to write `œṗZ⁻¦` instead of `œṗ¹Z1¦`. This is because a dyad (`œṗ`) followed by a monad (`œṗ¹Z1¦`) is a *fork* (the monad is applied to the chain's argument / the input string, and the returned value is passed as the right argument to `œṗ`), while a dyad followed by another dyad (or at the end of the chain) is a *hook*, i.e., its right argument is the chain's argument.
All that's left to do is check for palindromicness. `µ` begins a new (monadic) chain who's argument is **A**. The *upend* atom `U` reverses all strings in **A** (but not **A** itself), then `⁼` compares the result with **A** for equality. The returned Boolean **1** indicates a fully-palindromic triangle; other strings would return **0**.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~25~~ ~~21~~ 17 bytes
*Saved 2 bytes thanks to @obarakon*
```
ò@°T ¬v1
pUmg)eêP
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=8kCwVCCsdjEKcFVtZyll6lA=&input=IjE2MDYxNTA1MSI=)
### How it works
```
ò@ ° T ¬ v1 // Implicit: U = input string, T = 0
UòXY{++T q v1} // First line; reset U to the result of this line.
UòXY{ } // Partition U at indices where
++T q // the square root of T incremented
v1 // is divisible by 1.
// This breaks U at square indices, giving rows of 1, 3, 5, ... chars.
pUmg)eêP
UpUmg)eêP
Umg // Take the first char of every item of U.
Up ) // Append this to U.
e // Check that every item in the resulting array
êP // is a palindrome.
// Implicit: output result of last expression
```
Note that we don't need to check *both* sides; if the sides are not the same, At least one of the rows is not a palindrome.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
gÅÉ£õÜÐíQs€¬āÈÏÂQ*
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##AS4A0f8wNWFiMWX//2fDhcOJwqPDtcOcw5DDrVFz4oKswqzEgcOIw4/DglEq//9ub3Bl "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 16 bytes
```
J²‘Ṭœṗ⁸ZḢ$ṭ$ŒḂ€Ạ
```
[Try it online!](https://tio.run/##y0rNyan8/9/r0KZHDTMe7lxzdPLDndMfNe6IerhjkcrDnWtVjk56uKPpUdOah7sW/P//XykxKTkpJTUtNQVIpAOppGQwLzkpEcFSAgA "Jelly – Try It Online")
Thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for trivial but not so obvious -2 byte savings.
[Answer]
## JavaScript (ES6), 112 bytes
```
f=(s,n=1,t='',u='',g=([...a])=>''+a==a.reverse())=>s?g(s.slice(0,n))&f(s.slice(n),n+2,t+s[0],u+s[n-1]):g(t)&g(u)
```
`t` and `u` collect the sides so that they can be tested at the end.
[Answer]
# C#, 184 bytes
```
using System.Linq;
b=a=>string.Concat(a.Reverse())==a
f=>{string c=f[0]+"",d=c,e="";for(int i=1,k=1,s=f.Length;i<s;)
{c+=f[i];d+=f[(i+=k+=2)-1];e=f.Substring(s-k);}return b(c)&b(d)&b(e);}
```
Thought the solution was looking good until I got to the palindrome part
Ungolfed version:
```
Func<string, bool> b = a => string.Concat(a.Reverse()) == a;
Func<string, bool> func = f => {
string c = f[0] + "", d = c, e = "";
for (int i = 1, k = 1, s = f.Length; i < s;) {
c += f[i];
d += f[(i += k += 2) - 1];
e = f.Substring(s - k);
}
return b(c) & b(d) & b(e);
};
```
[Answer]
# Java 8, ~~358~~ 301 bytes
```
import java.util.*;s->{List<String>l=new Stack();for(int i=0,p=1,t=1;p<=s.length();p+=t+=2)l.add(s.substring(i,i=p));String a="",b=a;for(String q:l){a+=q.charAt(0);b+=q.charAt(q.length()-1);}return p(a)&p(b)&p(l.get(l.size()-1));}boolean p(String s){return s.equals(new StringBuffer(s).reverse()+"");}
```
Input is a `String`, output is a `boolean`.
**Explanation:**
[Try it here.](https://tio.run/##nVQ9b9swEN39Kw4aCrK2GcmtM1RhgHTK0BoFPAYdKImy6dAULVIuUkG/3T3JauwhbYkeiPugHu/IewftxFHMKyvNrng@qb2tag873GONV5q9T@HmBr4J3KxK8FsJ2YuX87xqjJ/kWjgHX4Uy7QRAGS/rUuQSVn0IkFWVlsJATta@VmYDjqb4oZugWoEBDic3v2@/KOfvzoh7zY38AWsv8mdC07KqCWYFxeOZ5cnM8yS1d9wxLc3GbxFhp9xP@YJqJoqCOOaazA2ZiJopbilNx9KCR9Es42LIOe4dPmnaiik/sHwr6gdPYppmV@Hhtc48oWlXS9/UBiwR9J0lWa8020iP2qmfckAhbJLi07Fnq8qDfbtvvxtjL41p@3fq66eN5RyTh0ZoR86N6eGfm7KUNXGU1fIoa4elp1GEpU8Atsm0ysF54dEcK1XAHvkZCz19B0HP5JTKCD1wB3tkos/eB2SgaHiArxs5@OsX5@WeVY1nFrN4bcieGZaTKInoiP8z5iEEgxIAS5I4CYKhxHEY9ja@TZbxMjjvlQQdWeD6MKiPo1n2TsDZx0eJSw9Kj6bqnf@46lsSkEZkeVbIUhaoNmiyfIjyTFy8v6W5DFOJI/yvaTL4Fwq4VNt2XUgL4jCGFvEicE4WOCch2FeiLsTJgczxbDfpTr8A)
```
import java.util.*; // Required import for List and Stack
s->{ // Method (1) with String parameter and boolean return-type
List<String>l=new Stack(); // Create a String-list
for(int i=0,p=1,t=1; // Initialize some index/counter integers
p<=s.length(); // Loop (1) over the String in sections
p+=t+=2) // And increase `p` like this after every iteration: 1,4,9,16,25,etc.
l.add(s.substring(i,i=p)); // And add a substring-section to the list (0,1 -> 1,4 -> 4,9 -> 9,16 -> etc.)
// End of loop (1) (implicit / single-line body)
String a="",b=a; // Two temp Strings
for(String q:l){ // Loop (2) over the list
a+=q.charAt(0); // And append the first character to String `a`
b+=q.charAt(q.length()-1); // And the last character to String `b`
} // End of loop (2)
return p(a) // Return if String `a` is a palindrome
&p(b) // as well as String `b`
&p(l.get(l.size()-1)); // as well as the last String in the list
} // End of method (1)
boolean p(String s){ // Method (2) with String parameter and boolean return-type
return s.equals(new StringBuffer(s).reverse()+"");
// Return if this String is a palindrome
} // End of method (2)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
+2 bytes - I released buggy code :(
-1 byte - moved from moulding like odd integers to partitioning at square indexes
```
JƲ0;œṗ⁸ZḢ$ṭ$ŒḂ€Ạ
```
A monadic link accepting a list of characters and returning `1` (Truthy) or `0` (Falsey).
Note: this uses the part of the specification that limits the input to a square length.
**[Try it online!](https://tio.run/##y0rNyan8/9/rcNuhTQbWRyc/3Dn90FYjp4e7uw9PeNS05lHjjihrIHF00sMdTUD@w10L/v//r@ThkQpEOWAiB0rlgxhKAA)** or see the [test suite](https://tio.run/##y0rNyan8/9/rcNuhTQbWRyc/3Dn90FYjp4e7uw9PeNS05lHjjihrIHF00sMdTUD@w10L/h/dc7gdyMwCSTfMUbC1U3jUMDfy//9oJUMlHSVHEAYCIJWXX5CqpKOgVF1dWwvkGhoagBQASTBlZGAEFgQCAwOIjJmBmaGpgSmMbQRkw9UgAbCQERAZgwkTKGUKYgDlPDxSgSgHTORAqXwQAyQHYyPkUsHqsViDDQCVJSYlJ6WkpqWmAIl0IJWUDOYlJyUiWEqxAA).
This may be simplified to **17 bytes** by noting that if all rows are palindromes only one "side" needs checking (`JƲ0;œṗ⁸ZḢ$ṭ$ŒḂ€Ạ`), however Erik the Outgolfer already noticed this fact and used it in [their answer](https://codegolf.stackexchange.com/a/125469/53748) so I have given the triangle construction method to them saving a byte there.
Additionally, that may in turn be improved to **16 bytes** by noting that partitioning at truthy indexes does not mind if there is excess in the left argument (`J²‘Ṭœṗ⁸ZḢ$ṭ$ŒḂ€Ạ`).
### How?
```
JƲ0;œṗµ2BịЀ⁸Z;⁸ŒḂ€Ạ - Link: list, a e.g. "abcbazxza"
J - range of length of a = [1,2,3,4,5,6,7,8,9]
Ʋ - is square? (vectorises) [1,0,0,1,0,0,0,0,1]
0; - prepend a zero [0,1,0,0,1,0,0,0,0,1]
œṗ - partition a at 1s ["a","bcb","azxza"]
µ - monadic chain separation, call that t
2B - 2 in binary = [1,0]
⁸ - chain's left argument, t
ịЀ - map with index into ["aa","bb","aa"] (1st and last of each of t)
Z - transpose ["aba","aba"] (left and right "sides" of t)
;⁸ - concatenate t ["aba","aba","a","bcb","azxza"]
ŒḂ€ - palindromic? for €ach [1,1,1,1,1]
Ạ - all? 1
```
[Answer]
# Mathematica, 156 bytes
```
B=StringTake;Count[PalindromeQ/@Join[A=Table[B[#,{i^2+1,(i+1)^2}],{i,0,(s=Sqrt@StringLength@#)-1}],{StringJoin@Table[B[A[[i]],1],{i,Length@A}]}],True]==s+1&
```
**input**
>
> ["1101"]
>
>
>
[Answer]
# [PHP](https://php.net/), 97 bytes
```
for($t=1;~$s=substr($argn,$i**2,$i++*2+1);$d.=$s[0])$t&=strrev($s)==$s;$t&=strrev($d)==$d;echo$t;
```
[Try it online!](https://tio.run/##TcqxDsIgFIXh3cdobkwBNUDSLrc3PohxqIDiUgigY9@6M9LN5STnyx99rNM1@niAOb0W6tQoRz3IQXdYnyH1UEjhCpny55FL@3t2gjfnuq0QXAvFEOyFIN/knUE5UuuS@/aQGTXFf7I7WXTGByhY67aEs5mNdz8 "PHP – Try It Online")
[Answer]
# Java, 136 bytes
```
l->{for(int i=0,j,k=1;i<l.size();i=j,k+=2)if(!l.subList(i,j=i+k).equals(l.subList(i,j).asReversed().toList()))return false;return true;}
```
Uses a `MutableList<Character>` from Eclipse collections
```
Function<MutableList<Character>, Boolean> func = l->{
for(int i=0,j,k=1;i<l.size();i=j,k+=2) // `i` is the start index, `j` is the end index, `k` increments by 2
if(!l.subList(i,j=i+k).equals( //Check that the first partition equals
l.subList(i,j).asReversed().toList()) // The same sublist reversed
)
return false;
return true;
};
```
[Answer]
# [Perl 5](https://www.perl.org/), 81 + 1 (`-p`) = 82 bytes
```
$a[0].=$1while($a[++$q]=substr$_,0,($#i+=2),'')=~/(.)/;$\||=$_ ne reverse for@a}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lMdogVs9WxbA8IzMnVQPI1dZWKYy1LS5NKi4pUonXMdDRUFHO1LY10tRRV9e0rdPX0NPUt1aJqamxVYlXyEtVKEotSy0qTlVIyy9ySKyt/v/fEQj@5ReUZObnFf/X9TXVMzA0@K9bAAA "Perl 5 – Try It Online")
Outputs `undef` (i.e., blank, null) for true, any number for false
[Answer]
# Excel VBA, 87 Bytes
Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window
```
k=1:For i=1To[Len(A1)^.5]:s=Mid([A1],j+1,i*2-1):j=j+i*2-1:k=k*(s=StrReverse(s)):Next:?k
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~128~~ ~~118~~ 115 bytes
```
def f(s):
w=1;l=r='';b=[]
while s:l+=s[0];r+=s[w-1];b+=[s[:w]];s=s[w:];w+=2
print all(d==d[::-1]for d in[l,r]+b)
```
[Try it online!](https://tio.run/##bVHBjoMgFLz7FdzQuE2AXXuAcNhb/4FwEMWtCVEDTcym6bfbp2DroRPyZubNEA5M/7frOLBlaW2HujwUPEOzpMJJLzEWRioNi2vvLArclTIoooVfeT5RLUwpVVB81lqEdce1mEvJMjT5frih2rm8lbJVnEO7Gz1qUT8o9@V1aYqlyzHFRQb0mwgQ1TBONqr7/fGIilKS6iB2xQjbUwAhr8qZnGlFqoNlYI/lA/Ytg/O9jZ9E1SpifLlYOG4bLtG4ihTv9h3b7crnJz8hNmvTGPgO28L4AzLN5hpTvxUulic "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 38 bytes
```
{(⌽¨≡⊢)(⊢,⊢/¨,⍥⊂⊃¨)⍵⊆⍨w⍴∊⍴⍨¨1+2×⍳w←≢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6s1HvXsPbTiUefCR12LNDWAhA4Q6x9aofOod@mjrqZHXc2HVmg@6t36qKvtUe@K8ke9Wx51dIHI3hWHVhhqGx2e/qh3cznQrEedi4DKav@ngdi9fUCNj3rXABUeWm/8qG0i0MbgIGcgGeLhGfw/TUHd0MzAzNDUwNRQHQA "APL (Dyalog Extended) – Try It Online")
The cuts are of size `1,3,5,7...`, so that is used with `⊆` to get the appropriate array.
Requires `⎕IO←0` for zero indexing.
Shortened with a lot of help from Marshall and dzaima.
## Explanation
```
{(⌽¨≡⊢)(⊢,⊢/¨,⍥⊂⊃¨)⍵⊆⍨w⍴∊⍴⍨¨1+2×⍳w←≢⍵}
≢⍵ length of the string
w← assign to var w
⍳ range from 0..length-1
1+2× convert each to 2n+1 (odd numbers)
⍴⍨¨ replicate each element times itself
∊ flatten that
w⍴ reshape to string's length
⍵⊆⍨ partition the string based on that
(⊢,⊢/¨,⍥⊂⊃¨) Train:
(⊢, ) concatenate the partition with:
( ⊢/¨ ) last character of each partition
( ⊃¨) first character of each partition
( ⍥⊂ ) both enclosed into two strings
⌽¨ do the reverses of each part
≡ match
⊢ the parts?
```
] |
[Question]
[
# Challenge
Given a graphical input of a shape, determine how many holes there are in it.
# Not Duplicate
This question was marked as a possible duplicate of [Count Islands](https://codegolf.stackexchange.com/questions/6979/code-golf-count-islands). I believe this challenge is different from the Count Island challenge because in this one, you have to figure out how to eliminate blocks that touch the border.
# Input
Input will be given as some 2D form of input, either a multiline string, an array of strings, or an array of character arrays. This represents the shape. The shape is guaranteed to be in only one piece, connected by edge. Please specify how you want input to be taken.
# Output
Output is a single integer stating how many holes there are in the shape. A trailing newline is permitted, but no other leading or trailing whitespace. In other words, the output must match the regular expression `^\d+\n?$`.
# What is a hole?
These are single holes:
```
####
# #
# #
####
####
# #
# ##
###
#####
# # #
# #
#####
```
These are not holes:
```
########
########
# ####
# ####
# ######
#
########
###
#
###
##########
#
# ########
# # #
# # #### #
# # ## #
# ###### #
# #
##########
```
Pretty much, if it the gap joins the outside edge, it is not a hole.
# Test cases
```
#####
# # # -> 2
#####
#####
#
# ### -> 1
# # #
#####
####
## # -> 1 (things are connected by edges)
# ##
####
###
### -> 0 (You must handle shapes with no holes, but input will always contain at least one filled space)
###
```
You can use any character in place of the '#', and in place of the spaces.
# Objective Scoring Criteria
The score is given as the number of bytes in your program.
# Winning
The winner will be the submission with the lowest score, by April 4th.
[Answer]
# MATLAB / Octave, 18 bytes
```
@(g)1-bweuler(g,4)
```
[Try it online!](https://tio.run/nexus/octave#@@@gka5pqJtUnlqak1qkka5jovk/Ma9YQyHaUEFBAQVzKYABiG2ATCOJo@BYBc3/AA "Octave – TIO Nexus")
This is an anonymous function taking a logical matrix as input. The object is formed by the `true` entries (with the specified connectivity), the empty space are the `false` entries.
`bweuler` then calculates the euler number of the binary image represented by that matrix, that is the number of objects minus the number of holes.
[Answer]
## Mathematica, ~~59~~ 57 bytes
```
1/.ComponentMeasurements[#,"Holes",CornerNeighbors->0>1]&
```
There's a built-in for that. Takes input as a 2D matrix of `1`s (walls) and `0`s (holes). For convenience, here are all the test cases in this input format:
```
{{{1,1,1,1},{1,0,0,1},{1,0,0,1},{1,1,1,1}},
{{1,1,1,1},{1,0,0,1},{1,0,1,1},{1,1,1,0}},
{{1,1,1,1,1},{1,0,1,0,1},{1,0,0,0,1},{1,1,1,1,1}},
{{1,1,1,1,1,1,1,1},{1,1,1,1,1,1,1,1},{1,0,0,0,1,1,1,1},{1,0,0,0,1,1,1,1},{1,0,1,1,1,1,1,1},{1,0,0,0,0,0,0,0},{1,1,1,1,1,1,1,1}},
{{1,1,1},{1,0,0},{1,1,1}},
{{1,1,1,1,1,1,1,1,1,1},{1,0,0,0,0,0,0,0,0,0},{1,0,1,1,1,1,1,1,1,1},{1,0,1,0,0,0,0,0,0,1},{1,0,1,0,1,1,1,1,0,1},{1,0,1,0,0,0,1,1,0,1},{1,0,1,1,1,1,1,1,0,1},{1,0,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1}},
{{1,1,1,1,1},{1,0,1,0,1},{1,1,1,1,1}},
{{1,1,1,1,1},{1,0,0,0,0},{1,0,1,1,1},{1,0,1,0,1},{1,1,1,1,1}},
{{1,1,1,1},{1,1,0,1},{1,0,1,1},{1,1,1,1}}}
```
## Alternative solution, 59 bytes
This was my original approach. It's also based on the component-related built-ins, but doesn't count the holes directly (instead it treats the holes themselves as components).
```
Max@*MorphologicalComponents@*DeleteBorderComponents@*Image
```
Takes the same input format as above, but with the roles of `0`s and `1`s swapped.
The reason I need to convert this to an `Image` first is that, otherwise, Mathematica would consider all the `1`-cells as part of a single component (because it treats the matrix as a component-label matrix). Hence, if any `1`-cell borders the margin, it would delete all of them. When `DeleteBorderComponents` is used on an image instead, then it will do an implicit connectivity check to find the components.
Alternatively, I could call `MorphologicalComponents` *first*, which would turn the input into a suitable label matrix, but if I do `DeleteBorderComponents` second it's no longer guaranteed that the maximum component label corresponds to the number of components (because I might delete a smaller component).
[Answer]
# [Perl 5](https://www.perl.org/), 154 bytes
152 bytes of code + 2 bytes for `-p0` flag.
```
s/^ | $/A/gm;s/^.*\K | (?=.*$)/A/&&redo;/.*/;$@="@+"-1;for$%(A,X){$~="(.?.?.{$@})?";(s/$%$~ /$%$1$%/s||s/ $~$%/$%$1$%/s)&&redo}s/ /X/&&++$\&&redo}{$\|=0
```
[Try it online!](https://tio.run/nexus/perl5#bc07DoMwDAbgvadIE4MSKDHMUQTMvQAD6lTahQpERgJXp654tENtyfr9DbY4983QsqRPF4c35hlgic@XoUVH9ZVA5lZHoIjDcGjunUEdoYHC8iLmSWYe3QCBLC@VGmG2XOqceoRiUjk30iEEMLPPzCBA571DBjPFXdR6diLHin7EMdQbjVB7my6LOOok2F4Uv7ixOJDtusY/B37xDQ "Perl 5 – TIO Nexus")
I think the code is quite self-explanatory.
---
If you need some explanations to understand, here are a few steps of the transformations done by the program on a simple input (coming from [here](https://tio.run/nexus/perl5#TY5NDoIwEIX3nGKE4V9aWDcEWHsBFsSExOJGA2llYShnx6lg4mvS1@/NtFPvNEn1gGzKnVlLGGT/mpWEUPfvUGy0C82vYAB5w@9PCyzpLkAUBEreRkogqkqWYGw7hL3BWcIF1qVbp25WiGFU6EfNuY2XSHM6sorWgvUaV0CMBfpcG2Nf@itR@KvF@6xV7P8B3tL0NMXuyBfsTJlvm/eV44EV2UHEZKTDKPwA)), followed by some explanations bellow:
```
######
#
# ####
# # #
#### #
######
######
# A
# ####
# # #
#### #
######
######
#AAAAA
#A####
#A# #
#### #
######
######
#AAAAA
#A####
#A#X #
#### #
######
######
#AAAAA
#A####
#A#XX#
####X#
######
```
First, `s/^ | $/A/gm;s/^.*\K | (?=.*$)/A/&&redo` will replace the spaces in the border (1st regex for left/right, 2nd for bottom/top) with `A` (I choose that character quite arbitrary).
Then, we get the width the shape with `/.*/;$@="@+"-1;`.
Now, we want to replace every space that is connected to a `A` with a `A` (because if a space is connected to a `A`, it means it can't be part of a hole. That's done by `for$%(A,X){(s/$%(.?.?.{$@})? /$%$1$%/s||s/ (.?.?.{$@})?$%/$%$1$%/s)&&redo}`. (you'll notice that this is done once for the `A`s and one for the `X`s - explanations for the `X` are bellow). There are two regex here: `s/$%(.?.?.{$@})? /$%$1$%/s` deals with the spaces that are on the right or bottom of a `A`. And `s/ (.?.?.{$@})?$%/$%$1$%/s` with the spaces on top or left of a `A`.
At this point, the only spaces that are left in the string are part of holes.
While there are still spaces, we repeat:
- To know how much holes there are, we replace a space with a `X` (`s/ /X/`) and increment the counter of holes (`$\++`), and redo the entire program (actually, we only want to redo the `for` loop, but it's less bytes to redo the whole program).
- Then, the `for` loop will replace every space that is connected to a `X` with a `X`, as they are part of the same hole.
At the end, `$\|=0` ensures that if there are no holes, a `0` is printed instead of an empty string. And `$\` is implicitly printed thanks to `-p` flag.
[Answer]
## Python 2, 282 bytes
+100 to handle diagonal touches TT\_TT (do we really need that?)
-119 thanks to @Rod guidance :)
[Try it online](https://tio.run/nexus/python2#nU9BboMwEDzHr1gJVdjFtKDeID4gvpADyPKBEkItAUFpoto99OvUlLSlCmoIB493Zmc93i5ismlPR0xQzjyUsKpocMQ9QVwfpQPry22xgxhvSIBAUc02CMpq/5xVUCKQO4i4FlyJtW3ZAVoZQa/9/QE0YymYW30xxVgSlCZldbYzYw/rrMUxfZctNsr9k8Nr2WDl@DQhA80UVq5PvZ5Srmnf16afEtr39HePEPT2IqvCBls28HqqcUS5IIFkP/WDbLaFwsZBwpL5YYyxvHM/EiofDRIS5g4rUXuQzRHyzuLcfJCOjqC/CvxRYNJzVkQ3vASzAUZUUOAj9Sa4mLZug6npa4n/Z8OcledmT00v2ftaNizdewkI8Qk). Takes array of arrays of chars '#' and whitespace as input.
```
A=input()
c=0
X=len(A[0])-1
Y=len(A)-1
def C(T):
x,y=T
global g
if A[y][x]<'#':
if y<1or y==Y or x<1or x==X:g=0
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(' ');g=1;C((i%-~X,i/-~X));c+=g
print c
```
Searches for first whitespace and mark it as non-empty ('#'). Recursively check all of it's surrounding, while filling all empty cells. If any empty cell of current "hole" appears to be on border counter won't change, otherwise it would be increased by 1. Repeat process, until there is no more whitespaces.
[Answer]
## Python 2, 233 225 222 bytes
*[math\_junkie](https://codegolf.stackexchange.com/users/65425/math-junkie): -8 bytes*
Takes 2d array of booleans/integers (0/1) as input
```
s=input()
o=[-1,0,1]
m=lambda x,y:0if x in[-1,len(s[0])]or y in[-1,len(s)]else 1if s[y][x]else(s[y].__setitem__(x,1),all([m(x+a,y+b)for a in o for b in o]))[1]
e=enumerate
print sum(m(x,y)-c for y,l in e(s)for x,c in e(l))
```
[Try it online!](https://tio.run/nexus/python2#lU5BigMhELz7ioZcbNJZ9LowLxEZnMSAoE4YZ0Ahf59Vs0sS2D1s24eq6qpu9zS4eNtWjmwe1EmSIKlZGLwJ08VApvIp3BUyuNim3kaelNCo5wXKq4ja@mRBVnNSRavcOW/4YxyTXd1qwzjyTBLJeM9V4PloqBwnvNZlpi6DGRqcOtSIqn7FDjZuwS5mtey2uLhC2gKvWSp4Ond/Id8S9VjflOn8oB5xP9zh0Io10B57V2q9g5@RUpLg2ZqgCaIz8RR@c3z3X8JLRO//P6O/AA "Python 2 – TIO Nexus")
Formatted version:
```
s = input()
o = [-1, 0, 1]
m = lambda x,y:
0 if x in [-1, len(s[0])] or y in [-1, len(s)]
else
1 if s[y][x]
else
(s[y].__setitem__(x, 1),
all([m(x + a, y + b) for a in o for b in o]))[1]
e = enumerate
print sum(m(x, y) - c for y, l in e(s) for x, c in e(l))
```
[Answer]
# C# 7, 364 bytes
Less than happy with this... maybe someone else can sort it out... If I have the energy later I will invert the first loop, and see if that can help to trim the bounds checking.
```
using C=System.Console;class P{static void Main(){string D="",L;int W=0,H=0,z;for(;(L=C.ReadLine())!=null;H+=W=L.Length)D+=L;int[]S=new int[H*9];int Q(int p)=>S[p]<p?Q(S[p]):p;void R(int r)=>S[Q(r+=z)]=S[r]>0?z:0;for(z=H;z-->0;)if(D[z]<33){S[z]=z;R(1);R(W);R(W+1);R(W-1);}for(;++z<H;)S[Q(z)]*=z>H-W-2|z%W<1|z%W>W-2?0:1;for(;W<H;)z+=Q(W)<W++?0:1;C.WriteLine(z-H);}}
```
[Try it online](https://tio.run/nexus/cs-core#TVCxboMwEN37FW6iSnYcEGmmxhwZyMBApRIGD4gBJU5qiRoEpFWd5ttT22lQT/Lz87u7pztfT71URxRD/t0P4sOPG9U3tWC7uup79Hbuh2qQO/TZyD16raTCxEidbdnAZDJPmVQD4hDME3M0OzQdZjiF2N@Kap9KJTAhj6BOdc0SChxSPxXqOLyTDQXXXJQ5KPGFLE1mL6UzzLDFlkCUF20ZtusMW0JWLXOTbF2@c/kMdxQ0KSEvujIK1noVuDE0JEx7XhQwIg94U@gyXC7JOTcENNviBTHAHdAb98x1cRtQqsOEEWtunGego8Tj3vOPfuLhwmJkXutgtbgtzG2xppAZv5BT6jKxzzs5CPcH2kuM9eV6nY7xMEX3MPSf@qffqNXQXb3T6aiisXaMXw)
Complete program, accepts input to standard in, output to standard out. Uses disjoint sets to determine provisional holes, and when kills any touch the borders (with some dodgyness for the top-edge).
Formatted and commented code:
```
using C=System.Console;
class P
{
static void Main()
{
string D="", // the whole map
L; // initally each line of the map, later each line of output
// TODO: some of thse might be charable
int W=0, // width, later position
H=0, // length (width * height)
z; // position, later counter
// read map and width
for(;(L=C.ReadLine())!=null; // read a line, while we can
H+=W=L.Length) // record the width, and increment height
D+=L; // add the line to the map
// disjoint sets
int[]S=new int[H*9]; // generousness (relieve some bounds checking)
// note that S[x] <= x, because we call R with decending values of z
// returns whatever p points to
int Q(int p)=>S[p]<p?Q(S[p]):p;
// points whatever r points to at z if r is empty
void R(int r)=>S[Q(r+=z)]=S[r]>0?z:0; // note that is never called when z=0
// fill out disjoint sets
for(z=H;z-->0;)
if(D[z]<33) // if cell is empty
{
S[z]=z; // point it at itself
// point the things next to z at z
R(1);
R(W);
R(W+1);
R(W-1);
}
// zero sets which are against the left, bottom, or right edges
for(;++z<H;)
S[Q(z)]*=z>H-W-2|z%W<1|z%W>W-2?0:1; // TODO?: this suggests inverting the first loop (NOTE: would break S[x]<=x)
// starting from the second row, count all the sets that point to this cell (ignores any non-zeros pointing to first row)
for(;W<H;)
z+=Q(W)<W++?0:1;
C.WriteLine(z-H);
}
}
```
[Answer]
# [Snails](https://github.com/feresum/PMA), 48 bytes
```
!{\ z`+~}\ {t\ z!.!~=((lu|u.+r)!(.,~},!{t\ z!.!~
```
Ungolfed:
```
!{
(\ z)+
~
}
\
{
t \
z !.!~
={
(lu|u.+r)
!(.,~)
}
},
!{
t \
z !.!~
}
```
[Answer]
## JavaScript (ES6), 192 bytes
```
v=a=>Math.min(...a=a.map(s=>s.length))==Math.max(...a);
f=(s,t=(u=` `.repeat(w=s.search`
`+1))+`
`+s.replace(/^|$/gm,` `)+`
`+u,v=t.replace(RegExp(`( |@)([^]{${w},${w+2}})?(?!\\1)[ @]`),`@$2@`))=>t!=v?f(s,v):/ /.test(t)?f(s,t.replace(` `,`@`))+1:-1
```
```
<textarea id=i rows=10 cols=10></textarea><input type=button value=Count onclick=o.textContent=/^[\s#]+$/.test(i.value)*v(i.value.split`\n`)?f(i.value):`Invalid_Entry`><span id=o>
```
Based on my answer to [Detect Failing Castles](https://codegolf.stackexchange.com/questions/109015). First the string is padded with spaces to make an area around the shape. The RegExp then looks for two adjacent squares, one containing an `@`, one containing a space, and replaces them both with an `@`. If it can't do this, it fills in a space with an `@` and counts this as a new hole. Finally one is subtracted to account for the surrounding area.
] |
[Question]
[
**RNA**, like DNA, is a molecule found in cells encoding genetic information. It consists of *nucleotides*, which are represented by the bases adenine (A), cytosine (C), guanine (G) and uracil (U).\* A **codon** is a sequence of three nucleotides.
**Proteins** are large molecules which perform a vast array of functions, such as keratin which is found in hair and nails and hemoglobin which carries oxygen in blood cells. They are made up of **amino acids**, which are encoded as codons in RNA molecules. Sometimes different codons may encode for the same amino acid. Each amino acid is commonly represented by a single letter, for example H stands for histidine.
Given a sequence of `ACGU`, can you translate it into the corresponding protein string?
\* DNA consists of ACGT, where the T is thymine. During DNA to RNA transcription, thymine is replaced by uracil.
---
## Input
Input will be a single string consisting of only the characters `ACGU` in upper case. You may write either a function or a full program for this challenge.
## Output
You may choose to output via either printing or returning a string (the latter choice is only available in the case of a function).
Translation should begin at a start codon (`AUG`, represented as `M`) and end at a stop codon (one of `UAA`, `UAG` or `UGA`, represented as `*`). There are four cases where input may be invalid:
* The input does not begin with a start codon
* The input does not end with a stop codon
* The input's length isn't a multiple of 3
* The input contains a stop codon somewhere other than at the end
In all of these cases, `Error` should be outputted. Note that, unlike stop codons, start codons may appear after the start of the string.
Otherwise, you should convert each codon into its respective amino acid via the following [RNA codon table](https://en.wikipedia.org/wiki/Genetic_code#RNA_codon_table):
```
* UAA UAG UGA
A GCU GCC GCA GCG
C UGU UGC
D GAU GAC
E GAA GAG
F UUU UUC
G GGU GGC GGA GGG
H CAU CAC
I AUU AUC AUA
K AAA AAG
L UUA UUG CUU CUC CUA CUG
M AUG
N AAU AAC
P CCU CCC CCA CCG
Q CAA CAG
R CGU CGC CGA CGG AGA AGG
S UCU UCC UCA UCG AGU AGC
T ACU ACC ACA ACG
V GUU GUC GUA GUG
W UGG
Y UAU UAC
```
...and output the translated string.
## Examples
Invalid cases:
```
<empty string> -> Error
AUG -> Error
UAA -> Error
AUGCUAG -> Error
AAAAAAA -> Error
GGGCACUAG -> Error
AUGAACGGA -> Error
AUGUAGUGA -> Error
AUGUUUGUUCCGUCGAAAUACCUAUGAACACGCUAA -> Error
```
Valid cases:
```
AUGUGA -> M*
AUGAGGUGUAGCUGA -> MRCS*
AUGGGUGAGAAUGAAACGAUUUGCAGUUAA -> MGENETICS*
AUGCCAGUCGCACGAUUAGUUCACACGCUCUUGUAA -> MPVARLVHTLL*
AUGCUGCGGUCCUCGCAUCUAGCGUUGUGGUUAGGGUGUGUAACUUCGAGAACAGUGAGUCCCGUACCAGGUAGCAUAAUGCGAGCAAUGUCGUACGAUUCAUAG -> MLRSSHLALWLGCVTSRTVSPVPGSIMRAMSYDS*
AUGAAAAACAAGAAUACAACCACGACUAGAAGCAGGAGUAUAAUCAUGAUUCAACACCAGCAUCCACCCCCGCCUCGACGCCGGCGUCUACUCCUGCUUGAAGACGAGGAUGCAGCCGCGGCUGGAGGCGGGGGUGUAGUCGUGGUUUACUAUUCAUCCUCGUCUUGCUGGUGUUUAUUCUUGUUUUAA -> MKNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVVYYSSSSCWCLFLF*
```
*Edit: Added more test cases*
## Scoring
This is code golf, so the code in the fewest bytes wins.
Note: I'm no expert in molecular biology, so feel free to correct me if I've misstated anything :)
[Answer]
**JavaScript (ES6) 167 ~~177~~** chars encoded in UTF8 as **167 ~~177~~** bytes
... so I hope everyone is happy.
**Edit** In fact, no need for a special case for last block too short. If the last 2 (or 1) chars are not mapped, the result string does not end with '\*' and that gives error anyway.
```
F=s=>/^M[^*]*\*$/.test(s=s.replace(/.../g,x=>
"KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF"
[[for(c of(r=0,x))r=r*4+"ACGU".search(c)]|r]))?s:'Error'
```
**Explained**
Each char in a triplet can have 4 values, so there are exactly 4^3 == 64 triplets. The C function map each triplet to a number between 0 and 63. No error check needed as input chars are only ACGU.
```
C=s=>[for(c of(r=0,s))r=r*4+"ACGU".search(c)]|r
```
Each triplet maps to an aminoacid identified by a single char. We can encode this in a 64 character string. To obtain the string, start with the Codon Map:
```
zz=["* UAA UAG UGA","A GCU GCC GCA GCG","C UGU UGC","D GAU GAC","E GAA GAG"
,"F UUU UUC","G GGU GGC GGA GGG","H CAU CAC","I AUU AUC AUA","K AAA AAG"
,"L UUA UUG CUU CUC CUA CUG","M AUG","N AAU AAC","P CCU CCC CCA CCG","Q CAA CAG"
,"R CGU CGC CGA CGG AGA AGG","S UCU UCC UCA UCG AGU AGC","T ACU ACC ACA ACG"
,"V GUU GUC GUA GUG","W UGG","Y UAU UAC"]
a=[],zz.map(v=>v.slice(2).split(' ').map(x=>a[C(x)]=v[0])),a.join('')
```
...obtaining "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV\*Y\*YSSSS\*CWCLFLF"
So we can scan the input string and use the same logic of the C function to obtain the code 0..63, and from the code the aminoacid char. The replace function wil split the input string in 3 chars blocks, eventually leaving 1 or 2 chars not managed (that will give an invalid result string, not ending in '\*').
At last, check if the encoded string is valid using a regexp: it must start with 'M', must not contain '\*' and must end with '\*'
**Test** In FireBug/FireFox console
```
;['AUGCUAG','GGGCACUAG','AUGAACGGA','AUGUAGUGA','AAAAAAA',
'AUGUUUGUUCCGUCGAAAUACCUAUGAACACGCUAA',
'AUGAGGUGUAGCUGA','AUGCCAGUCGCACGAUUAGUUCACACGCUCUUGUAA',
'AUGCUGCGGUCCUCGCAUCUAGCGUUGUGGUUAGGGUGUGUAACUUCGAGAACAGUGAGUCCCGUACCAGGUAGCAUAAUGCGAGCAAUGUCGUACGAUUCAUAG']
.forEach(c=>console.log(c,'->',F(c)))
```
*Output*
```
AUGCUAG -> Error
GGGCACUAG -> Error
AUGAACGGA -> Error
AUGUAGUGA -> Error
AAAAAAA -> Error
AUGUUUGUUCCGUCGAAAUACCUAUGAACACGCUAA -> Error
AUGAGGUGUAGCUGA -> MRCS*
AUGCCAGUCGCACGAUUAGUUCACACGCUCUUGUAA -> MPVARLVHTLL*
AUGCUGCGGUCCUCGCAUCUAGCGUUGUGGUUAGGGUGUGUAACUUCGAGAACAGUGAGUCCCGUACCAGGUAGCAUAAUGCGAGCAAUGUCGUACGAUUCAUAG -> MLRSSHLALWLGCVTSRTVSPVPGSIMRAMSYDS*
```
[Answer]
# C,190 bytes (function)
```
f(char*x){int a=0,i=0,j=0,s=1;for(;x[i];i%3||(s-=(x[j++]=a-37?a-9?"KNRSIITTEDGGVVAA*Y*CLFSSQHRRLLPP"[a/2]:77:87)==42,x[j]=a=0))a=a*4+(-x[i++]/2&3);puts(*x-77||i%3||s||x[j-1]-42?"Error":x);}
```
# ~~199~~ 194 bytes (program)
```
a,i,j;char x[999];main(s){for(gets(x);x[i];i%3||(s-=(x[j++]=a-37?a-9?"KNRSIITTEDGGVVAA*Y*CLFSSQHRRLLPP"[a/2]:77:87)==42,x[j]=a=0))a=a*4+(-x[i++]/2&3);puts((*x-77||i%3||s||x[j-1]-42)?"Error":x);}
```
Saved a few bytes by improving hash formula.
Here's a fun test case:
```
AUGUAUCAUGAGCUCCUUCAGUGGCAAAGACUUGACUGA --> MYHELLQWQRLD*
```
**Explanation**
The triplet of letters is converted to a base 4 number. Each letter is hashed as follows.
```
x[i] ASCII code Hashed to (-x[i]/2&3)
A 64+ 1 1000001 00
G 64+ 7 1000111 01
U 64+21 1010101 10
C 64+ 3 1000011 11
```
This gives a number in the range `0..63`. The idea now is to use a lookup table similar to the ones used by edc65 and Optimizer. However, the hash is designed so that G and A are next to each other and U and C are next to each other.
Looking at the table at <https://en.wikipedia.org/wiki/Genetic_code#RNA_codon_table>, we see that with the letters ordered in this way, generally the last bit can be ignored. Only a 32-character lookup table is needed, except in two special cases.
See below first two letters, and corresponding amino acids (where 3rd letter is G/A, and where 3rd letter is U/C). Corrections for the two special cases that do not fit the 32-character table are hardcoded.
```
A/G U/C A/G U/C A/G U/C A/G U/C
AAX> K N AGX> R S AUX> I I ACX> T T
GAX> E D GGX> G G GUX> V V GCX> A A
UAX> * Y UGX> * C UUX> L F UCX> S S
CAX> Q H CGX> R R CUX> L L CCX> P P
Corrections for special cases (where last bit cannot be ignored)
AUG 001001=9 --> M
UGG 100101=37--> W
```
**Commented code**
In golfed version the `i%3` code is in the increment position of the `for` bracket, but it is moved into a more readable position in the commented code.
```
a,i,j;char x[999]; //Array x used for storing both input and output. i=input pointer, j=output pointer.
main(s){ //s is commandline string count. if no arguments, will be set to zero. Will be used to count stops.
for(gets(x);x[i];) //Get a string, loop until end of string (zero byte) found
a=a*4+(-x[i++]/2&3), //Hash character x[i] to a number 0-3. leftshift any value already in a and add the new value. Increment i.
i%3||( //if i divisible by 3,
s-=(x[j++]=a-37?a-9?"KNRSIITTEDGGVVAA*Y*CLFSSQHRRLLPP"[a/2]:77:87)==42, //lookup the correct value in the table. for special cases a=24 and a=32 map to 'M' and 'W' (ASCII 77 and 87). If character is '*' (ASCII42) decrement s.
x[j]=a=0 //reset a to 0. clear x[j] to terminate output string.
);
puts((*x-77||i%3||s||x[j-1]-42)?"Error":x); //if first character not M or i not divisible by 3 or number of stops not 1 or last character not * print "Error" else print amino acid chain.
}
```
[Answer]
## CJam (97 93 92 91 bytes)
```
q"GACU"f#3/{4b"GGEDAAVVRSKNTTMIRRQHPPLLWC*YSSLF"{_s"MW""I*"er}%=}%s_'*/(1<"M"=*Qa=\"Error"?
```
This is a port of my GolfScript solution with a slightly tweaked hash function because to my surprise one thing which CJam hasn't borrowed from GolfScript is treating strings as arrays of integers.
6 bytes saved thanks to suggestions by [Optimizer](https://codegolf.stackexchange.com/users/31414/optimizer) (including two bytes from something which I thought I'd tried and didn't work - huh).
[Answer]
# CJam, ~~317 121~~ 104 bytes
```
q3/{{"ACGU"#}%4b"KN T RS IIMI QH P R L ED A G V *Y S *CWC LF"S/{_,4\/*}%s=}%_('M=\)'*=\'*/,1=**\"Error"?
```
This can still be golfed further.
*Updated* the mapping mechanism to the one used in edc65's answer.
Even though I came up with this on my own, he beat me to it :)
**UPDATE** : Shortened the codon table map by observing the pattern in it.
[Try it online here](http://cjam.aditsu.net/)
[Answer]
### GolfScript (103 bytes)
```
{)7&2/}%3/{4base'GGEDAAVVRSKNTTMIRRQHPPLLWC*YSSLF'{..'MW'?'I*'@),+=}%=}%''+.'*'/(1<'M'=*['']=*'Error'or
```
[Online demo](http://golfscript.apphb.com/?c=IyMKOycKRXJyb3IKQVVHCkVycm9yClVBQQpFcnJvcgpBVUdDVUFHCkVycm9yCkFBQUFBQUEKRXJyb3IKR0dHQ0FDVUFHCkVycm9yCkFVR0FBQ0dHQQpFcnJvcgpBVUdVQUdVR0EKRXJyb3IKQVVHVVVVR1VVQ0NHVUNHQUFBVUFDQ1VBVUdBQUNBQ0dDVUFBCkVycm9yCkFVR1VHQQpNKgpBVUdVR0FBVUcKRXJyb3IKQVVHQUdHVUdVQUdDVUdBCk1SQ1MqCkFVR0dHVUdBR0FBVUdBQUFDR0FVVVVHQ0FHVVVBQQpNR0VORVRJQ1MqCkFVR0NDQUdVQ0dDQUNHQVVVQUdVVUNBQ0FDR0NVQ1VVR1VBQQpNUFZBUkxWSFRMTConbi8yL3t%2BOkVYUEVDVEVEOwojIwoKeyk3JjIvfSUzL3s0YmFzZSdHR0VEQUFWVlJTS05UVE1JUlJRSFBQTExXQypZU1NMRid7Li4nTVcnPydJKidAKSwrPX0lPX0lJycrLicqJy8oMTwnTSc9KlsnJ109KidFcnJvcidvcgoKIyMKOk9CU0VSVkVEIEVYUEVDVEVEPSdPaydbJ0ZhaWw6IGV4cGVjdGVkICdFWFBFQ1RFRCcsIGdvdCAnT0JTRVJWRURdaWYgcHV0c30vCiMj) (NB doesn't include the two largest test cases because it needs to run in 15 seconds).
### Dissection
As Steve Verrill pointed out in the sandbox, the lookup table can be reduced to 32 elements plus two special cases. It turns out that the special cases both involve characters (`M` and `W` respectively) which only occur once, and with the right mapping of the characters to base 4 digits it's possible to build the full 64-element lookup table from the 32 elements by doing a duplicate-and-[`tr`](https://codegolf.stackexchange.com/a/6273/194):
```
'GGEDAAVVRSKNTTMIRRQHPPLLWC*YSSLF' # 32-element lookup table
{ # Map over the 32 elements...
. # Duplicate the element
.'MW'?'I*'@),+= # Apply tr/MW/I*/ to the duplicate
}%
```
Then once we've done the decode, the validation allows for many approaches. The shortest I've found is
```
.'*'/ # Duplicate and split the copy around '*' retaining empty strings
(1<'M'=* # Pull out the first string from the split (guarantee to exist even if input is
# the empty string); if it starts with 'M' leave the rest of the split intact;
# otherwise reduce it to the empty array
['']= # Check whether we have ['']. If so, the split produced [prefix ''] where
# prefix begins with 'M'. Otherwise we want an error.
* # If we have an error case, reduce the original decoded string to ''
'Error'or # Standard fallback mechanism
```
[Answer]
# Python, 473 bytes
```
t={'U(A[AG]|GA)':'*','GC.':'A','UG[UC]':'C','GA[UC]':'D','GA[AG]':'E','UU[UC]':'F','GG.':'G','CA[UC]':'H','AU[UCA]':'I','AA[AG]':'K','(UU[AG]|CU.)':'L','AUG':'M','AA[UC]':'N','CC.':'P','CA[AG]':'Q','(CG.|AG[AG])':'R','(UC.|AG[UC])':'S','AC.':'T','GU.':'V','UGG':'W','UA[UC]':'Y'}
import re
i=raw_input()
a=''
for x in[i[y:y+3]for y in range(0,len(i),3)]:
a+=[t[u]for u in t.keys()if re.match(u, x)][0]
print["Error",a][all((a[0]+a[-1]=="M*",len(i)%3==0,not"*"in a[1:-1]))]
```
[Answer]
# Python 2, ~~370~~ ~~358~~ 354 bytes
This is a very straight forward approach using no compression, just trying to pack the information quite densly:
```
s=lambda x:x and[x[:3]]+s(x[3:])or[]
def f(I):O=''.join(d*any(0==x.find(p)for p in e)for x in s(I)for d,e in zip('*ACDEFGHIKLMNPQRSTVWY',map(s,'UAAUAGUGA,GC,UGUUGC,GAUGAC,GAAGAG,UUUUUC,GG,CAUCAC,AUUAUCAUA,AAAAAG,UUAUUGCU,AUG,AAUAAC,CC,CAACAG,AGAAGGCG,AGUAGCUC,AC,GU,UGG,UAUUAC'.split(','))));return['Error',O][len(I)%3==0==len(O)-O.find('*')-(O[0]=='M')]
```
**Edit:** Shaved off a few characters following xnor's suggestion.
[Answer]
## Scala (317 chars)
```
def g(c:Char)="ACGU"indexOf c;def h(s:String,i:Int)=g(s(i))*16+g(s(i+1))*4+g(s(i+2));def p(a:Int)=a!=48&&a!=50&&a!=56;def f(s:String)=if(s.length%3!=0||h(s,0)!=14||p(h(s,s.length-3)))"Error"else{var r="";for(i<-0 to s.length-3 by 3)r+="KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF"charAt h(s,i);r}
```
The main function is `f`. Of course, a better choice would be to return an `Option[String]`.
[Answer]
# JavaScript (ES6), 143 bytes
```
s=>/^M\w*\*$/.test(s=s.replace(/.../g,c=>"PVLVLHDVLGRGRAPGR*KYNVL*KTSTSGRTSILIFYNMLR*SCTSRWEQDHIFEQPAPASC.A"[parseInt(c,36)%128%65]))?s:'Error'
```
[Try it online!](https://tio.run/##dVJhi9pAEP3eX3GEHqfhmtCWHqXglWWMk@BG4m6yInoF8XLHFdEjkevPt/NWSy2Ng0LYefPmvbf7c/W2atfNy@v@w3b3WB@eBod2cB//yJe/wmX4Po72dbvvtYM2aurXzWpd9@IoiuLn2/XgPiicdjodOs2GjSrYhOP5xOlwXNrSsiltprPRfJJrE1oqrZkl02GajZJpoQplKVLB4nXVtHW23ffWt5/v@tcfP329vvvy0O9/b7/dJE2za24O69223W3qaLN77gWLbPu22rw8PgT9d@eNp14Q9P87UhV3nFZKdWOpUl14dayODjOTujRVsVLEfGGXDFUXexX@RFyRcKhKkezwdEJIJ/n/zAXL7cJdyAWEftNVHF/lYZdOZi@IznCGbBcUSCVKoEbEKEglsXIU5Sc5mSRl1j1OwBJCwyjm6GSK4PkvSeGU0S4tte6kkZ8okVjAVeEGJCz4hBIv0rMJKXm55NPGhOAUVHi/Ei3YGJ@IyTehDB3@o0Uba1Ot9EwzOXnGpbOFK9hmuVG5nQ87nfonI6zs709hpzBDqcI2hhq/ngDGRgRBXhSwKPYGEY@4xWsQJphmhAVqKGflbwBoRjA4ki8@3Sk8IRWMHo15Up830P61oeHf3Pk9jifjSSllrLFZlmfTdJoWUkZKSyXDZAiTWOWk5nMrRTPSIz0KD78B "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Given a string of printable ASCII text (including newlines and spaces) that contains at least one character that is neither a newline nor a space, output a truthy value if the string is rectangular, and a falsey value otherwise. **Additionally, the source code for your solution must be rectangular**.
A string is rectangular if it meets all of the following conditions:
1. The first line and the last line contain no spaces.
2. The first and last character of each line is not a space.
3. All lines have the same number of characters.
For example, the following text is rectangular:
```
abcd
e fg
hijk
```
This text, however, is not rectangular (requirement #3):
```
1234
567
8900
```
## Test Cases
Truthy:
```
sdghajksfg
```
```
asdf
jkl;
```
```
qwerty
u i op
zxcvbn
```
```
1234
5 6
7890
```
```
abcd
e fg
hijk
```
Falsey:
```
a b c
```
```
123
456
7 9
```
```
12
345
```
```
qwerty
uiop
zxcvnm
```
```
1234
567
8900
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~127~~ ~~125~~ ~~124~~ 118 bytes
* Saved two bytes by golfing `r*=!e&(!t|t==c);` to `r>>=e||t&&t-c;`. *(This golf was the inspiration for my recent C tips answer [Inverse flag update](https://codegolf.stackexchange.com/a/164010/73111).)*
* Saved a byte by golfing `*(_-2)` to `_[~1]`.
* Saved six bytes by golfing `*_++-10||(...)` to `*_++<11?...:0` and utilizing the placeholder zero `...:0` (which is not used constructively) to golf the `c++` increment. Those golfs allowed some further loop reshuffling.
* When one can use multiple falsey values, [114 bytes](https://tio.run/##hZDrbsIwDIV/b0@RVVqV9CK1tIWxEvEgyxS1ISmFYVgadiPs1UurDWlMWif5hyV/xz4@IqyEaFsdyEAEJudYLAvtcXJQW401NVTQKPd4V74/i@O59umNcV3cDQJJrPX4LEksf/iMH/vGmlAEgkoa3QvfJx4Pk5G1WNKY5NpS2QGu2zH5sd0UNWByuL7a6RqMwo5Bc3S7YOAEiGOnWVTLYrVuVOUQkv9FFc1CMVitn/Ih6vlVavPOYI9qtN0x@HgTLyUMKeJRkjLIEBozmNxNo0EPpeh6iVTFYFmv1t/s3jTYcX7K1KUMlUhc7lW/PTBIs94Bmg6DDJI0G0LOCaB9fQ4ANv8c7wMYTxh073/9f2xP) could be possible.
```
r,e,c,t;_(char*_){for(r=1,t=c=0;*_;*_++<11?r*=(t||(t=c,!e))&*_>32&_[~1]>32&t==c,c=e=0:c++)*_-32||(e=1);r>>=e||t&&t-c;}
```
[Try it online!](https://tio.run/##hZDrTsMwDIV/w1OESlRJm0pruwsjpHsQgqIuS7puzBtpxm0dr15awSSGRJH8w5K/Yx8fFRVKNY2lmirqmMRqmdtAkoPZWmx5TB1XfMAC2VYY3sXxzAYcu7rG7YBeaUL8QGZp4sv7j/ihaxxvB4prPrhVYUgCGaVJi2seE2azjOu6dr7vIsWOzSYvAZPD5cXOluAM9hyaoeuFAI8iib1qUSzz1boyhUcI@4vKq4URsFo/sj7q6UVb9yZgj0q03Ql4f1XPc@hTxEk6FDBCaCxgcjMd9HqYq7bXyBQCluVq/c3uXYU976fMnMvQHKnzvea3BwHDUecATftBAelw1IecEkD78hQAbP453gUwngho3//6/9h8Ag "C (gcc) – Try It Online")
*[Source layout achieving a taller rectangle.](https://tio.run/##hZDrboJAEIV/l6fYkpTscokiqLV09UG6zQaWXUTraJelN9FXp5jWpDYpTebHJPOdmTNHBIUQbat96QvfJByLZapdTvZqq7GmoW@ooMPE5V153r0VhgvtUmyaBncT/1oS4rh8Ho0c/nAMH0@Nod3AElTS4Z3wPOLyIBp1vKQhSfR8TmXTGMcxgUgOg0G7SUvAZG9d7XQJRmHboAW6yRnYPuLYrvJima7WlSpsQpK/qLTKFYPV@inpo55fpTbvDGpUou2OwcebeMmgTxGOopjBGKEJg@ntbNjrIRNdL5EqGCzL1fqbrU2FbfunTF3KUIbE5V712wODeHxygGb9IIMoHvch5wRQXZ4DgM0/x08BTKYMuve//j@0nw)*
# Explanation
*The following explains the 124 bytes long version.*
```
r,e,c,t;_(char*_){ // `r` is the boolean result flag, `e` a boolean flag if the current line contains
// a space, `t` the first line's width, `c` the current line's current width
for(r=1,t=c=0;*_;c++) // initialize, loop through entire string
*_-32|| // if the current char is a space,
(e=1), // the current line contains a space
*_++-10|| // if the current char is a newline (char pointer `_` now incremented)
(r*=(t||(t=c,!e)) // if t is not yet set, the current line is the first line; set it
// to this line's length, check that no spaces where found
&*_>32 // the next line's first char should not be a space
&_[~1]>32 // this line's last char should not have been a space
&t==c,c=~0,e=0); // the line lengths should match, reset `c` and `e` to zero
// (`~0 == -1`, countering the loop's increment of `c`)
r>>=e||t&&t-c;} // return boolean flag, check that the last line does not contain spaces,
// there was either no newline or line lengths match
// (here) equivalent to `r*=!e&(!t|t==c)`
```
[Try it online!](https://tio.run/##hVPbcpswEH1uvmLjmbpg44kd59IMQ/ohpQOyWEAxlhwh4lzc/Lq7ku04xAnlCdDu2XNZ8VHB@WajAwx4YMLE4yXTg8R/AfucnUGqUxA1mBJhplSFTILGuqkM5BUrAkgxBfZ2ZP@ByF05b7RGaaASkj6UNEzI@gQ@f2gSwdRLxpEwTeoQcqHrbf@PGlYiMyWd8fQInU73n67qBHKlPR1NAhPxaBwOkpAPh74dIqQwglXimcZUSi0JS6umKIGahUaojRayIJaDZDQ9X6@PWH4QZ@2y/uy5W30eRhM/ONb3pSn7bjd2OBxNxu3BXWMlrhyWCw6WSkiDGtIkBalWJJdrXFAHZr6jpgeRZ9Zrj4wJTtH3D@gWTioDT2igRhMc092twSGV0BaCMF2hGkVN1LnLqUJZ2Bh5iXxOJ8zQ0K16irhEiiBXjcwcZH@Q3E7PP0JaDhIf36Lf8nHy61I1VeZkzPCdqwSV/H6d/GmhOah3zNgnKCV7oL1HlG0wE5F9PHodBxiN/fDAy/m01VjvcRbMcFJMt4bMsuvLZOauDVnzjFp1ueelr2OIIhhNUvKMjKFwaT@3s2h9ifdbxKByC08569vbCNdr0@@bEQ//HvA0mkbL1m1tReFg2S5dyBRuV2K3p7uYgs64XYQrVgMK@27T3a@o0m1/nDGd6i2YD3jfiAdWWYlkWUorfIp979SsbQx@ulkQN89/Ofm2JG9M7vUM/ILvWSx7ASRer86Kkt3N67zo@X74VRWrszyWd/Mq7Kq6X6E2T7FsQIBaxvL5kT/MZFfH5Hx6EctLgKtYXv@8GXdymHF6pxtQxLIUd/NdbWNqr9d735a322AGvI2bf@QQy4tLywBuugtjOb247CrZOwCN2BsgF/8Zbg24uo4lyd/q/7v5Bw "C (gcc) – Try It Online")
[Answer]
# Java 10, ~~214~~ ~~176~~ ~~169~~ ~~152~~ ~~144~~ 139 bytes
```
s->{String[]a=s.split("\n")
;int r=1,i=0,R=a.length;for
(;i<R;i++)if(i<1|i>R-2?a[i]
.contains(" "):a[i].trim( )
!=a[i])r=0;return-r<0;}////
```
-5 bytes thanks to *@Neil*.
Uses `String[]a` instead of `var a`; `return-r<0;` instead of `return r>0;`; and added a comment `//` at the very end, so there aren't spaces on the first and last rows.
Note that this rectangle is shorter than a single-line input, because `int r=1,...;` should be replaced with `int[]v{1,...};`, and all uses of the integers would then becomes `v[n]` (where *n* is the index of the variable in the array `v`).
[Try it online.](https://tio.run/##rVTPU@IwFL73r3jmlAxSQFF3LXVv3vQAe7Me0jQtKSHpJimKyt/OBpTZmR0lOEOmObzme@97v@ar6YJ262K2ZpJaC3dUqNcIQCjHTUkZh/uNCZBrLTlVwPDEGaEqsCTxDyt//WcddYLBPShIYW27N6/vqIdHmtrYNlI4jDKFSJT4yGDSwalI@6fjlMaSq8pNk1KbCCdiNE5Ep0NEicVo8CZuxt2zX/RBPEYx08r55CxGgMj15l/sKeYYSHSSbkxi0n5iuGuN6ppRP1n1/FlvkmzaXPrsPpJcaFHA3IfCuxyBkvciez34bVo3XV5vzcnSOj6PdevixiOdVFjFDCOas8IX09mCvjiIQ1kFQVNRzxDZdvJrOltUU1rPbFkFodQWZZC0nskkGOnPEzduGYzVggDdBGEvz2yRqyDp4Ox8GIx1AXAZBF39@NkPd@v4c9yt0S2VlgfW6LBqL68gCPLFHlAt5MAOGEGY7nx4caz9gVboBg7aHzU/0v58q6O7gU50a7waMl1wEM5yWe4f7ucamKEsUxkiQf49Mhn03SOjQd9/MpshyP4T2qD3HiH@mN0qWq3/Ag)
**Explanation:**
```
s->{ // Method with String parameter and boolean return-type
String[]a=s.split("\n"); // Input split by new-lines
int r=1, // Result-integer, starting at 1
i=0, // Index `i`, starting at 0
R=a.length; // Amount of rows `R`
for(;i<R;i++) // Loop `i` over the rows
if(i<1 // If it's the first row,
|i>R-2? // or the last row:
a[i].contains(" ") // And the current row contains a space
:a[i].trim()!=a[i]) // Or either column of the current row contains a space
r=0; // Set the result `r` to 0
return-r<0;} // Return whether `r` is still 1
//// // Comment to comply to the rules of the challenge
```
Here is the same base program with spaces (**~~128~~ 126 bytes**):
```
s->{var a=s.split("\n");int r=1,i=0,R=a.length;for(;i<R;i++)if(i<1|i>R-2?a[i].contains(" "):a[i].trim()!=a[i])r=0;return r>0;}
```
-2 bytes thanks to *@Neil*.
[Try it online.](https://tio.run/##rVTPU@IwGL3zV3zm1AxSQFF3DWVv3vQAe7Me0jQtKSHpJimKyt/OBhbG2XEkOEOmPXzty/ve92NeRRe0U@WzNZPUWrinQr21AIRy3BSUcXjYhACZ1pJTBSyaOCNUCRYT/2PlX/9YR51g8AAKEljbzuhtQQ3QxMa2lsJFKFUIE08KJumfi6R3Pk5oLLkq3ZQU2kREDMdEtNtYFJEY9t/FaNy5@EUfxVPMtHJelY0QIHy7/eQVzCN8lmwCbJIeMdw1RoEZ9chqTVpeUd1k0ivaCVtokcPcs@zUPz4Bxf8K63bht2ncdHm7DSdL6/g81o2La490UkUqZhGiGct9Ee0t6IuDOBRlEDQV1Qzhbfe@TmfzckqrmS3KIJTavAgmrWaSBJn@PHPjlkGuBgToOgh7fWGLTAWT9i8uB0GuK4DrIOjmx89euFunn@N@je6otDywRsdVe30DQZAv9ohqIQN2xAjC6S4HV6faH2iEruGo/VHzE@3Ptzq6H@hEN8Y7INM5B@Esl8Xh4W58b@8vH96XojRVKcLB/Af8MXj3gIEG7344bIog/c9jIaz6kwt3zNC7cNef3exWrdX6Lw)
[Answer]
# T-SQL, ~~237~~ 207 bytes
```
SELECT(SELECT(IIF(max(len(v))=min(len(v)),1,0)*IIF(SUM(len(v+'x')-len
(trim(v))-1)=0,1,0))FROM t)*(SELECT(IIF(SUM(charindex(' ',v))=0,1,0))
FROM[t]WHERE[i]IN(SELECT(min(i))FROM[t]UNION(SELECT(max(i))FROM[t])))
```
Outputs 1 for rectangular, 0 otherwise. I had to use tons of extra parens and brackets to eliminate spaces, I'm sure there is vast room for improvement.
**Explanation**:
[Per our allowed I/O options](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341) and clarification in the question comments, input is taken as separate rows in a pre-existing table **t**. Because data in SQL is inherently unordered, that table includes a "row number" identity field **i**:
```
CREATE TABLE t (i INT IDENTITY(1,1), v VARCHAR(999))
```
Basically my SQL performs 3 subqueries, each of which returns `0` or `1` based on the 3 criteria of "rectangular" code. Those 3 values are multiplied together, only returning `1` for code that satisfies all 3.
**EDIT**: Combined criteria 2 and 3 into the same SELECT to save space
```
SELECT(
SELECT(IIF(max(len(v))=min(len(v)),1,0) --All rows same length
*IIF(SUM(len(v+'x')-len(trim(v))-1)=0,1,0))FROM t) --no leading or trailing spaces
*(SELECT(IIF(SUM(charindex(' ',v))=0,1,0)) --No spaces at all in
FROM[t]WHERE[i]IN(SELECT(min(i))FROM[t] -- first row or
UNION(SELECT(max(i))FROM[t]))) -- last row
```
The `TRIM(v)` function is only supported by SQL 2017 and above. Earlier versions would need `LTRIM(RTRIM(v))`, which would require rebalancing the rows.
One random note: the `LEN()` function in SQL ignores trailing spaces, so `LEN('foo ') = 3`. To get a "true" length you have to tack a character on to the end then subtract one :P
[Answer]
# C++, ~~199~~ ~~183~~ ~~181~~ 175 bytes
This template function accepts lines as a collection of strings (which may be wide strings), passed as a pair of iterators.
```
#include<algorithm>//
template<class I>bool
f(I a,I b){return!~+(
*a+b[-1]).find(' ')&&
std::all_of(a,b,[&a](
auto&s){return' '+-s.
back()&&s[0]-' '&&a->
size()==s.size();});}
```
Thanks are due to user [Erroneous](/users/42487) for reminding me of the `back()` member of `std::string` and for pointing out that `npos+1` is zero.
## Ungolfed equivalent
The only real golfing is to concatenate the first and last lines so we can perform a single `find` for spaces in those.
```
#include <algorithm>
template<class It>
bool f(It a, It b)
{
return (*a+b[-1]).find(' ') == a->npos
&& std::all_of(a, b,
[=](auto s) {
return s.back() != ' '
&& s.front() != ' '
&& s.size() == a->size(); });
}
```
# Test program
```
#include <iostream>
#include <string>
#include <vector>
int expect(const std::vector<std::string>& v, bool expected)
{
bool actual = f(v.begin(), v.end());
if (actual == expected) return 0;
std::cerr << "FAILED " << (expected ? "truthy" : "falsey") << " test\n";
for (auto const& e: v)
std::cerr << " |" << e << "|\n";
return 1;
}
int expect_true(const std::vector<std::string>& v) { return expect(v, true); }
int expect_false(const std::vector<std::string>& v) { return expect(v, false); }
```
```
int main()
{
return
// tests from the question
+ expect_true({"sdghajksfg"})
+ expect_true({"asdf", "jkl;",})
+ expect_true({"qwerty", "u i op", "zxcvbn",})
+ expect_true({"1234", "5 6", "7890",})
+ expect_true({"abcd", "e fg", "hijk",})
+ expect_false({"a b c",})
+ expect_false({"123", "456", "7 9",})
+ expect_false({"12", "345",})
+ expect_false({"qwerty", " uiop", "zxcvnm",})
+ expect_false({"1234", "567", "8900",})
// extra tests for leading and trailing space
+ expect_false({"123", " 56", "789"})
+ expect_false({"123", "45 ", "789"})
// the function source
+ expect_true({"#include<algorithm>//",
"template<class I>bool",
"f(I a,I b){return!~+(",
"*a+b[-1]).find(' ')&&",
"std::all_of(a,b,[&a](",
"auto&s){return' '+-s.",
"back()&&s[0]-' '&&a->",
"size()==s.size();});}",})
;
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 85 bytes
```
x=>(x=x.split`\n`).some(s=>s.length-x[0].length|s.trim()!=s)<!/\s/.test(x[0]+x.pop())
```
[Try it online!](https://tio.run/##jZBdT8IwFIbv@RWHq7UhFJQNJDD@iDNhH93WrWvHTsFq/O9T1DRGbcLdeZPnPXnzNOklxXwQvZkrXfCxjEcbH4iNLcNeCnNM1JEy1B0nGB@QSa4qU8/t4/Lp@35DZgbRETqNke6niwQXzHA05MrMLOt1Tygdc61QS86krkhJJgABFlWdNi2WVUDpbvIXSLEoExXA7BqaVu483OmZD@bFkWcQoHsXX21@yZSnene/Ch0ZAaxd2Dxsl75dWV44jkNZuVCLpv0s/deCDHL/DPcjjH6MgK234aBVGN0mBs7ilxfV3eRlvQEXPrR8eRnfAQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 82 bytes
```
lambda*s:len(set(map(len,s)))<2<'!'<=min(tuple(s[0]+s[-1])+zip(*s)[0]+zip(*s)[-1])
```
[Try it online!](https://tio.run/##rZBLcoMwEET3c4rJShKOUzYGO3bgJMYLPsKIj5AZkcS@PBFUOblAdt1T3a@qx9xt1Wt/KuNkatMuK1KPTq3UnKTlXWq4068khIj8iL2wKO6U5nY0reR03lxWdF5vL2L1UIZ7JObLU873yUqyhDEOjDEqrlVaN1ReAVIqSqib9gPg9iUHe4cRFfYGHt/5Z6YBtv4ugBBxD4f348YVsrwAia5bqbpxHjPMlxgEoQvhcTYIuyD8ReKoeoMLUndP5P4ADuiI/7/WbXwj0yrLWaITzQRA2Q9oUWlcHnFCMyhtseSe/UsyIWD6AQ "Python 2 – Try It Online")
Invoke as `f("abcd", "e fg", "hijk")`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~106~~ ~~102~~ ~~98~~ ~~110~~ ~~109~~ 102 bytes
```
(\a->all(==[])a||and(e((1<$)<$>a):map(all(>='!').($a))[head,last,map$last,map$head]));e(a:s)=all(==a)s
```
Thanks to @nimi and @Laikoni for a byte each!
[Try it online!](https://tio.run/##vY9NDoIwEIX3nmIkJM4kSOJWLTfwBJTFiEUbS60Uf@PZrajowgO4ei/ve5mX2bDfKmNCJWRAyeOMjUEh8oL4dmO7QoU4mcc0jzOmac0On4VMjIYjSjFmonyjeJUY9m3S4fhrnnFBNFPIU0/ifZfJh5q1BQFdZwHoGm3btEqNtsoTDAByiBiWUEadTyDan1TTXqSFg945aa/n8mjrH3YADR@4tD1E@Zd3@rVe5Gu9CPeyMrz2YVw69wA "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 79 bytes
```
g(x:r)=all((==(0<$x)).(0<$))r&&all(>='!')(x++last(x:r)++(head<$>r)++(last<$>r))
```
[Try it online!](https://tio.run/##tY9BDoIwEEX3nmIkBDqpIRp3SrmBJwAWRRtoLBULaPXyFRrcuHcx@T//TeZnGt5fhVLO1cQeDDKuFCGMkW0aWsRkVkQTRXOesXgdI7GUKt4Pfp9S0gh@ScPM@zn3Ho91XrJdunctlxoYtLw7AemM1AMkUE@jpBY9wgogh4BDBedg8hsI7k9hhlehYZS3rtBve37o9oeNIOELK73AP72wXF@k8G2l@wA "Haskell – Try It Online") Takes input as a list of lines.
The pattern `g(x:r)= ...` binds the first line to `x` and the (possibly empty) list of remaining lines to `r`. Then `all((==(0<$x)).(0<$))r` checks if all lines in `r` have the same length as `x` (Using [this tip](https://codegolf.stackexchange.com/a/146634/56433)).
If not, then the conjunction `&&` short-circuits and returns `False`, otherwise the right hand side is evaluated. There a string is build which consists of `x` for the first line, `last(x:r)` for the last line of `r` (or the first line again in case `r` is empty) and `(head<$>r)` for the first and `(last<$>r)` for the last character of each line. For this string, `all(>='!')` checks that it does not contain any spaces (we can't use `(>' ')` because of the source code restriction).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
ctgF6Lt&()32>
```
Input is an array of strings, in the format `{'abc' 'de'}`.
Output is an array containing only ones, which is [truthy](https://codegolf.stackexchange.com/a/95057/36398), or an array containing at least a zero, which is [falsey](https://codegolf.stackexchange.com/a/95057/36398).
[Try it online!](https://tio.run/##y00syfn/P7kk3c3Mp0RNQ9PYyO7//2r1xKTkFHUdBfVUhbR0EJ2RmZWtXgsA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##VY7NTsMwEITvfoq9UDeXqDQ/pUKCS0FC4tgrEk5sJ05cO8QOJVR99rCkUCU@eHdnNPvtgXk9vMP13cDOhmF4LJUWsFRGKqO8AG1tEwy5L57TV79YBtH6YXicpl4kob7tfNlTcp4aT9oJQiXDgtbbzDKc7GZo5RrNerKfivu2w0t@D4DcGq68siYYTtTxomRV7WRBz@REmeOSAq1qfT/OH0fR@h6VDhTYBpvvr/wzM6N5u45iVBKAFMvmbru67MhyjrMA3Am0VFV9kSGD/D@HRpyMKdj@aThEcTKnQqeuUHOYQdMN/ohE5g8), including truthiness/falsihood test.
### Explanation
```
c % Implicit input. Convert to char. This concatenates the
% strings of the input cell array as rows of a rectangular
% char array, right-padding with spaces as needed
tg % Duplicate, convert to logical. Gives a logical array with
% the same size containing true in all its entries
F % Push false
6L % Push the array [2, j-1], where j is the imaginary unit.
% When used as an index, this is interpreted as 2:end-1
t % Duplicate
&( % Assignment indexing with 4 inputs: original array, new
% value, two indexing arrays. This writes false at the inner
% rectangle (2:end-1)×(2:end-1) of the logical array that
% initially only contained true. This will be used as a
% logical index (mask) into the rectangular char array
) % Reference indexing. This selects the border of the char
% array. The result is a column vector of chars
32> % Is each entry greater than 32? (ASCII code for space)
% Implicit display
```
[Answer]
# JavaScript (ES6), 88 bytes
```
s=>!s.split`\n`.some((s,i,a)=>s[L='length']-a[0][L]|(++i%a[L]>1?/^\s|\s$/:/\s/).test(s))
```
[Try it online!](https://tio.run/##jZDtboJAEEX/@xTTpA27QUEraK2BvoBvADQusMAC7lJntR/x3am2yaZpS@K/ucm5k5tTsyPDbC86PZEq530R9BiEN@hg1wq9jeXWQbXjhOBYjBkNQow2gdVyWerKSiYsmibRJjkR2xZ37HyFsyf3OcZTjLfuoxujSx3NUROktM@URNVyp1UlKcgIwMK8rFjdYFFalK5HfwGGeRFLC@xLqJt2PcC9vPK9fjfkAQSozsSPt@yYyoHq7H7uGdIHWJiwfFhNh3alWW44DkVpQiXq5qv0XwtSyIZnmB@e/2MErAYbBpp7/nVi4CB@eZG7q7wslmDCWcu3l/4T "JavaScript (Node.js) – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~17~~ 15 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
4[↷K;}┐){SL]∑4≡
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE0JXVGRjNCJXUyMUI3JXVGRjJCJXVGRjFCJXVGRjVEJXUyNTEwJXVGRjA5JXVGRjVCJXVGRjMzJXVGRjJDJXVGRjNEJXUyMjExJXVGRjE0JXUyMjYx,i=JTYwJTYwJTYwJTBBMTIzNDUlMEE2JTIwJTIwJTIwJTBBMyUyMCUyMCUyMDMlMEE4OTEyMyUwQSU2MCU2MCU2MA__,v=2)
Explanation (ASCII-fied for monospace):
```
4[↷K;}┐){SL]∑4= full program; pushes the input to the stack.
4[ } repeat 4 times
↷ rotate ToS clockwise. This also pads the input with spaces
K; take off the last line and put it below the item
┐ pop the remaining of the input (the center)
) and wrap the rest (the sides) in an array
{ ] map over those
S split on spaces - should result to one item in the array
L and get the length
∑ sum those lengths together
4= check if equal 4
```
[Answer]
# [Perl 5](https://www.perl.org/), 70 bytes
```
$f||=$_;$l||=y///c;$,||=/^\s|\s$/||$l-y///c;$e=$_}{$\="$f$e"=~/\s/||$,
```
[Try it online!](https://tio.run/##LYoxCoAwEAR7XyGypXKVleQnQVFJRAgmGC3E06d7RrCagZlgVleLwDIrdA1c4kFEY4MyKbU6so4gZrjqDyad1wmtCliYQt2k4zeUIv0wZjb32eT3x4dt9kuUKrgX "Perl 5 – Try It Online")
Outputs `0` for truthy, any other number for falsey.
[Answer]
# [Red](http://www.red-lang.org), 216 191 bytes
```
func[s][d:(length?(first(s:(split(s)"^/"))))sp:
func[a][none = find a" "]b: on foreach c s[b: b
and(d = length? c )and(c/1 <>" ")and(" "<> last
c)]res:(sp(first(s)))and(sp(last(s)))and(b)res]
```
[Try it online!](https://tio.run/##bY7NTsMwEITv@xQrn5JTKbRArVLegatlJP82huAE2@FXffawiUrLAV/smfl2x8nZ8cFZIcHz0Q/RiCyF5VXr4r4095UPKZcq8yr3baBHzR4XrKaTew4zr6SIXXR4hz5Ei4ohk5pjF9F3ySnToMEsyNGgoq0sgcflFNSTZRZL3O5oblZ0b3fYqlzA1DK5ufv3H1Q8MWRMwEnrmjg59inEgh6@lTYWHPo9NOHp@QBwSl7fXSqfMGDAroevD/Om4998eXm1gjXiNdzcbi7OCTKFGg07GzMLqzWRuPmnAodwbIgvh/EH "Red – Try It Online")
I put a lot of otherwise not necessary parentheses in the first and last rows.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Ỵµ.ịЀ;ịɗẎ⁶e<L€E$
```
[Try it online!](https://tio.run/##y0rNyan8///h7i2Htuo93N19eMKjpjXWQMbJ6Q939T1q3JZq4wMUcVX5//9/YXlqUUklV6lCJldVRXJZUh4A "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Uses a method developed by Mnemonic in a (currently - due to an edge-case failure) deleted Pyth submission. (if it is now fixed up, [go give some credit](https://codegolf.stackexchange.com/a/163978/53748)!)
```
ỴµL€Eȧt€⁶ZUƊ4¡⁼
```
A monadic link accepting a list of characters which returns 1 or 0.
**[Try it online!](https://tio.run/##y0rNyan8///h7i2Htvo8alrjemJ5CZB61LgtKvRYl8mhhY8a9/z//z8xKTmFK1UhLZ0rIzMrGwA "Jelly – Try It Online")**
### How?
```
ỴµL€Eȧt€⁶ZUƊ4¡⁼ - Link: list of characters
Ỵ - split at newlines (making a list of lists - the rows)
µ - start a new monadic chain, call that ROWS
L€ - length of €ach row in ROWS
E - all equal? (an integer: 1 if so, otherwise 0)
4¡ - repeat four times:
Ɗ - last three links as a monad:
t€⁶ - trim spaces (⁶) from €ach row in current ROWS
Z - transpose that result
U - upend (reverse each new row)
ȧ - logical AND (0 if L€E was 0 else the result of the repeated transform)
⁼ - equal to X? (the integer 0 is not equal to any listy of characters)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 22 bytes
Noncompeting answer: there's a [known bug in Japt](https://github.com/ETHproductions/japt/issues/38), where two-dimensional array rotations truncate the results. Due to that bug the code below only works on inputs that are square. If the bug wasn't present, though, the code below should work completely correctly.
```
e_ʶUÌÊéUeº4o)r_z)mx}U
e_ // Check if every line in the input array
ʶUÌÊ // has the same length as the last item.
é // Also,
r_z)mx}U // check if rotating and trimming the input array
º4o) // four times
Ue // is equal to the input array.
```
Takes input as an array of strings. Using parentheses instead of spaces makes the rectangular code requirement quite easy.
[Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=ZV/KtlXMysOpVWW6NG8pcl96KW14fVU=&input=WyJhYmMiLAogImQgZSIsCiAiZmdoIl0=).
[Answer]
# [Ruby](https://www.ruby-lang.org/) 2.5+, 63 bytes
```
->a{!a.uniq(&:size)[1]&&a.none?(/^\s|\s$/)&&!(a[0]+a[-1])[?\s]}
```
Takes input as an array of strings. No test link, since the version on TIO (2.4) is too old for this one. Instead, here is a slightly longer (69 bytes) version for testing:
```
->a{!a.uniq(&:size)[1]&&a.none?{|l|l=~/^\s|\s$/}&&!(a[0]+a[-1])[?\s]}
```
[Try it online!](https://tio.run/##PY3tboJAFET/36dYE0MgrQsoaK2lPAjQ5AKLLB8LstBWgb66ro3tr8kkZ850Q3y@Zt519Y7jAukg@EnXXiW/MCOwI01DKhrB/HGqpsr7MT9COYVyac6attAxsKInDFZ2ZAR@KKP5unyjHcOUyrbivW6GYlzPpkEZJvk49Uz2E3r3eAB@KAxaY6sek7ypW@PQEnzOAlQqmR5zLEqZHQFQphkUZXUAOH2xrj/DQDhpWrh8J5@xALDXGwdcQrawe9lbahAnKTCitjkvStVJTJJfDBxXQWR/L7Bx3H8jGfhDKOo/4XYHSmfdAA "Ruby – Try It Online")
The difference is that since 2.5 Ruby supports directly passing a Regex pattern to `all?, any?, none?` methods, which saves us a few bytes. The method itself is quite self-explanatory - we test:
1. If there is only 1 unique line size
2. If there are any spaces on line boundaries
3. If there are spaces on the first and last lines.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 119 bytes
Takes input as a list (s) of n strings.
```
f(s,n,m,r,p)char**s,*p;{for(r=m=n;m--;r*=strlen(*s)==strlen(s[m])&(!p||m&&m^n-1&&p!=s[m]&&p[1]))p=strchr(s[m],32);n=r;}
```
[Try it online!](https://tio.run/##xZLJboMwEIbP4SkmlooMMlLZ0gVx7Qu0tySViFmTYKgNbdM0z56aJURJuJcDzOBv5h/PDDUSSo/HGAvCSE44KTWaBlzXBdFLbx8XHHM/95mXG4bHdV9UfBsxrAvNP9lini81FU/L399cVfN3ZpiqWk795r805uZS08oGpilvYWJbmsd87h2On0UWQoIbSWg0IWMVME3ZK5OSSzvG6C5cMESgqVCeaJ5yUJSGyoOM4ZakBRMVdDkqXkfmfAk@7JEIkzRYb0ScoIN3i1k9FogwRgStN1tvlLN77uMr4tVOkjVkUJTS@Pmmnys2GuT0QaZlO5J0AWby8/D4dD@Ku6daVjSUXASyZoLSbL1p8cuAONiK4ZIBrIDe5GwR61yDTOa4bQXwNA7bAywp23HHKee6F1BnQytYPh7kXvVi9iDfshP3I3ejRRj1@D/tZF9UWVcCozdeV@nuecEM@SC5fJMEtytGwDx7FgHr7NkE7LPnXHhu753yL9hL06ErhW7Ag0Q3zCFPN65BspvL5emtzGu0jS9Fmk53EofjHw "C (gcc) – Try It Online\"nline")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~145~~ 167 bytes
```
S[0].Length>1&&S[0].IndexOf
(" ") + S[ S.Count() - 1 ].
IndexOf(" ")<-1&Array.Find(
S,x=>x[0]==' '| x [x.Length
-1] == ' ' | S[0].Length
!=x.Length)==null?11>0:0>1;
```
[Try it online!](https://tio.run/##nVNdb9owFH1ufsVZHiDRRkRWaNdlYZqqMk3qtGmZtAfMQ0hMMJgbajtd6MdvZ4aWDSFtUnbfrn0@ro@uM93JSsU3lRZUIFlrw5eRc9gFl6WUPDOiJB185MSVyI4Q14Jujo6@89oE33hRyVRd1SvFtd4KRE4mU63xVZWFSpe4d2BLm9SIDLelyPE5FeRpo6zWaIxUFdrHDvQE3dalFSolD34oYbj15t7Qc3VezNL5Qk8L9@QkSFZSGK/NqO37fvRvZqrzKaP5QkZNmTc/uTJrRhUEyhWjuzq7nZDbTCR8fdpj1AfOGJ2/ueg2Hn@S5Yw4pgWjmZgvGvMxQWZJjadm1OtvZ8aF25jM6LTXb2y6zxuV2MdNy/@L@@yckQ37b2k//hY5XNBJWUoM/2xn4h9tpuKmUoRNMuqOg2tOhZkNwlZr136inNdfpo7nwvXxEskIif1bFRnPRwchxoHzjNlB3nXC1gel0nUwFJR7TvKqjge1VYrjNtoPqDGqnz2cTjgG4hiwN8ADDvydF/Ee5scxVVK@D8NB9213EEabp6c@bn4B "C# (.NET Core) – Try It Online")
```
S[0].Length>1& // And if the lenght of the first argument is more than 1 char
Array.Find( // Find a string in an array
S, // The array which will be searched in
x=> // For x as the current string from the array
x.Length!=S[0].Length| // If the string lenght match not the first argument lenght
x[0]==' '| // Or if the string begins with a spacer
x[x.Length-1]==' ' // Or if the string ends with a spacer
)==null& // And if there was no string found which matched the conditions
S[0].IndexOf(" ")+S[S.Count()-1].IndexOf(" ")<-1 // And if the first and last string doesn't have a spacer
? // If all above is true do
1>0 // Return True
: // Else
0>1 // Return False
```
] |
[Question]
[
**This challenge was posted as part of the [April 2018 LotM challenge](https://codegolf.meta.stackexchange.com/questions/16116/language-of-the-month-for-april-2018-brain-flak)**
---
[Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) is a turing-tarpit language which has gained quite a lot of fame here on PPCG. The memory of the language is composed by two stacks, but a "hidden" third stack [was discovered](https://codegolf.stackexchange.com/a/109859/62393) by [Wh~~e~~at Wizard](https://codegolf.stackexchange.com/users/56656/what-wizard), leading to some interesting new ways of thinking Brain-Flak programs.
So, what about giving that poor hidden third stack more visibility? Let's create a language where the third stack has the recognition it deserves! Here I present you **Third-Flak**.
# The language
In Third-Flak there is only one stack, called the third stack. Operators work on the third stack in the same way they do in Brain-Flak, but here there are no `[]`,`{}`,`<>` nilads and no `{...}` monad (so the only admissible characters in a Third-Flak program are `()[]<>`). Here is what each operator does (examples will be given representing the third stack with a list where the last element is the top of the stack):
* `()` is the only two-characters operator in Third-Flak. It increases the top of the third stack by 1. Example: `[1,2,3]`→`[1,2,4]`
* `(`,`[`,`<`: all opening parentheses that are not covered by the previous case push a `0` to the third stack. Example: `[1,2,3]`→`[1,2,3,0]`
* `)` pops two elements from the third stack and pushes back their sum. Example: `[1,2,3]`→`[1,5]`
* `]` pops two elements from the third stack and pushes back the result of subtracting the first from the second. Example: `[1,2,3]`→`[1,-1]`
* `>` pops an element from the third stack. Example `[1,2,3]`→`[1,2]`
And here are the other rules of the language:
* At the beginning of execution the third stack contains only a single 0.
* It is forbidden to have empty `[]` or `<>` inside a program (they would be noops anyway if following the semantics of Third-Flak, but they actually have a different meaning in Brain-Flak that is not possible to recreate here).
* Parentheses always need to be balanced, except for the fact that trailing closing parentheses at the end of the program can be missing. As an example, `[()<(()` is a valid Third-Flak program (and the third stack at the end of the program would be `[1,0,1]`).
* A program can only contain the six allowed characters `()[]<>`. Programs are guaranteed to be non-empty.
Note: it is implied by the previous rules that you won't have to deal with situations where you need to pop from an empty stack.
# The challenge
Simple, write an interpreter for Third-Flak. Your program must take as input a Third-Flak program and return as output the state of the third stack at the end of the program.
Your output format is flexible as long as it is possible to unambiguously read from it the state of the third stack and the same number is always encoded in the same way (This is just a way of saying that any output format that's not a blatant way to try to cheat is fine).
Your output choice may restrict the range of numbers you can manage as long as this does not trivialize the challenge (since this would be [a default loophole](https://codegolf.meta.stackexchange.com/a/8245/62393)).
# Test cases
For each test case the first line is the input, and the second line the output stack represented as a space separated list of numbers where the top of the stack is the last element.
```
[()<(()
0 1 0 1
[((((()()()()()))
0 0 0 5
((([()][()][()])))
-3
[<<(((()()()())(((((
0 0 0 0 0 4 0 0 0 0 0
[()]<(([()])><[()]
-1 0 -1
(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(())(())(()())(())(())(())(()())(()()()())(())(()()()()())(()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(())(())(()())(())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(())(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(()()())(())(()()())(())(())(())(()())(()()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(())(())(())(()()())(())(())(())(()())(())(()())(()()()())(())(())(()()()()())(()())(()())(())(()()())(())(())(())(())(()()())(()())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(()()()()())(())(()()())(())(())(()())(())(()()()()())(())(()()()()())(())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()()()())(())(()()()()())(())(())(())(()())(())(()()()()())(())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()()()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(())(()())(()()()())(())(())(()())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(()()())(())(())(()())(())(())(()()()()())(()()()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(()()()())(()()()())(()()
718 2
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 276 bytes
```
{({}<>)<>}<>{(((()()()()()){})((({}){})())(({})({}{}([{}])(<>))))((()()(){[()]<{}>}{}){()<{{}}>}{}<<>({}({})())>{()(<{}>)}{}<>)<>}<>{(([{}]()<>)){{}({}())((){[()](<({}())((){[()](<({}())((){[()](<{}([{}]{})>)}{}){(<{}{}>)}{}>)}{}){(<{}({}{})>)}{}>)}{}){(<{}{}({}())>)}}{}<>}<>
```
[Try it online!](https://tio.run/##hU@5DcMwDFyHV3gDQosYLpQigJEgRdoDZ5ePlA0kaaKHFAneo9u776/l/uyPMWgMb/CmSNPCtcGAasV8APXUZdjK2GCCIdtznKthc0aLRBicjCrcm1A2SaQhoKYQX7rJKIwYWbOlNznN/9WnIykUrdQ9bVbx0Snv@O1ecmqVJZ0x6i9ypYTmmcbSDw "Brain-Flak – Try It Online")
You had to know this was coming.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~64~~ ~~48~~ 46 bytes
```
\(\)
_
[([<]
¶
+1`¶(.*)\)|(.*)¶\2]|¶.*>
$1
%`_
```
[Try it online!](https://tio.run/##K0otycxL/K@qoZWgp8X1P0YjRpMrnitaI9omluvQNi5tw4RD2zT0tDRjNGtA1KFtMUaxNYe26WnZcakYcqkmxP//H62haaOhoQnUBAKaMKgJFLGxQRLSBMsDAA "Retina 0.8.2 – Try It Online") Outputs the stack from bottom to top. Only works with non-negative integers, and the last test case is too slow, so the link only includes three test cases. Explanation: The stack implicitly precedes the program, so it starts off as the empty string, which represents a single zero. The `()` nilad is turned into a `_` which is used to count in unary, while the other open brackets are turned into newlines which push a zero on to the stack as they are encountered. The close brackets are then processed one at a time so that the stack will be correct; the `)` deletes the previous newline, adding the top two elements together, the `]` deletes the top element and matches it from the previous element on the stack thus subtracting it, and the `>` just deletes the top element. Finally the stack is converted to decimal. Edit: Saved 2 bytes thanks to @Leo.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~145 144 132 122 116 109~~ 104 bytes
*-7 bytes thanks to Leo!*
*And - 5 thanks to Lynn!*
```
s=[0]
for i in input().replace('()',' '):s+=i in']>) 'and(i<'!'or(2-ord(i)%5)*s.pop())+s.pop(),
print(s)
```
[Try it online!](https://tio.run/##zVXNDoIwDL7zFHgwawWJ0Xgx4osYDkQxkhi2bHjw6RGiBoX9oUDMGGm70vZbvw12y880WxWFCPeLyDlR7qZumpUPu@aAAU/YJT4kQACJT1yCG@GFlQeJduiSODtCuiUTQjks55SXGk7XOBMBowwQvafgO4ynWQ4CiwJKezmrgVBPnf4aD7lp0Xk3p2xtnMy1j9xizvvp245nrtWmFvl@2Nm6SPbv4fv2rg@ZE3vnvg5Rmy@6qLZcVmdRcVnHZ1VEedVjMNTMP5s@mbimqlK3632fNztcXe8YUx/UCL/D2hXXUDj17P@3@/UX9Orv5Oeg77@XPP4d "Python 3 – Try It Online")
~~Pretty standard implementation.~~ Not so readable now though. I'm disappointed I couldn't figure out a shorter way to check between start and end brackets though.
Some attempts at one-liners:
* 124 bytes (anonymous function):
```
lambda c:[s.append(i in']>) 'and(i<'!'or~-']>)'.index(i)*s.pop())+s.pop())or s for s in[[0]]for i in c.replace('()',' ')][0]
```
* 115 bytes (full program):
```
s=[0];[s.append(i in']>) 'and(i<'!'or~-']>)'.index(i)*s.pop())+s.pop())for i in input().replace('()',' ')];print(s)
```
Append is annoyingly longer than plain assignment
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~98~~ 91 bytes
```
->s{a=[i=0];s.chars{|c|a<<("([<"[c]?s[i,2]["()"]?1:0:a.pop*~-"]>)".index(c)+a.pop);i+=1};a}
```
[Try it online!](https://tio.run/##zVVLDoIwEN17CtNVxw9Rl1LgIE0XFTWyUQIx0YheHUFFUPpDwQgp0OnMm3nta4n2i2O6dtKxG5@4QwNnwuzY8jc8ik@Jn3BCMMKUIOozL6bBaMYowoCYN51P5twKd@HgMkbMBWQF2@XqgH0Y3sxgB0Nnerb5OQ37a4ooBoLzyN6jm19Q3PAcyKyZKytaZYRmtZQxcAMo4YCReyS4JH@VeLlrEfJsqn4lBdQtKu/3Jhr7TebSR2zR5331rePpazWpRTwfZrYmX@bP7tet2u8yJ7SufRWjul5UqKZalmeRaVmlZxmiuOpfKFSvP5N10mlNVqVq1tveb2a8mp4xunWQM/yMa1NeXfFUq//fztdv2MvjxPug7b@XGB@x9Ao "Ruby – Try It Online")
My initial code worked similarly in spirit to Jo King's Python answer, so that before looping through the source chars we replaced all `()` substrings by another character, as a distinct operator.
However, at least in Ruby, it turned out golfier not to do this, but rather go for a slightly more cumbersome approach. Here, we maintain an additional indexer `i` keeping track of our position in the source string, and whenever an opening bracket is encountered, we do a lookahead checking if our current+next chars `s[i,2]` form the `()` operator. In that case we push 1 instead of 0 on top of the stack, and let the closing `)` do its job in the next step.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
```
΄()1:v"0+0\0->"žuykè.V})
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cN@jhnkamoZWZUoG2gYxBrp2Skf3lVZmH16hF1ar@f9/tIZmrI2GBojStLMBUQA "05AB1E – Try It Online")
**Explanation**
```
Î # initialize the stack with 0 and the input
„()1: # replace any occurrence of "()" in the input with 1
v } # for each char y in this string
žuyk # get its index in the string "()[]<>{}"
"0+0\0->" è # use this to index into the string "0+0\0->"
.V # eval
) # wrap the stack in a list
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 34 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
0,Ƨ() Iŗ{"(<[”č0ŗΖ)+ŗ ] -ŗΖ>Xŗ!!}⁰
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MCUyQyV1MDFBNyUyOCUyOSUyMEkldTAxNTclN0IlMjIlMjglM0MlNUIldTIwMUQldTAxMEQwJXUwMTU3JXUwMzk2JTI5KyV1MDE1NyUyMCU1RCUyMC0ldTAxNTcldTAzOTYlM0VYJXUwMTU3JTIxJTIxJTdEJXUyMDcw,inputs=JTVCJTI4JTI5JTVEJTNDJTI4JTI4JTVCJTI4JTI5JTVEJTI5JTNFJTNDJTVCJTI4JTI5JTVEJTBB,v=0.12)
[Answer]
# [R](https://www.r-project.org/), ~~182~~ 177 bytes
```
function(P){for(k in utf8ToInt(gsub("\\(\\)",7,P))%%8){if(k%in%0:4)F=c(0,F)
if(k==7)F[1]=F[1]+1
if(k==1)F=c(F[2]+F[3],F[-3:0])
if(k==5)F=c(F[2]-F[1],F[-2:0])
if(k==6)F=F[-1]}
F}
```
[Try it online!](https://tio.run/##zVXPa4MwFL77V0hAeI8qaLutpdRrYLcedoteVsiQQoROT6V/uzWjrd3MLzctUxLM917ee1/yJR4a7m8iv@G12FVFKWCLR14eYO8Xwq8rvnorX0UFH5/1O5AsgyxDEi7DLWIQrPBYcNgHhQji9RPSdAdxSNGTYJoukbIkT2U3Sy5Y8uVE2TyfUbbIQ8qixTrOr1Oeb@ZITpPm@Z35pTW3UJKfPHpqOBAG8sHri0jQa@EWwguM0DXT@BYCur7vofL@2VS2x2TufNSIPe933348e60utajXww0b8uXeT79v9@Mpc@Lo2jcx6uvFFNVVy/osOi2b9KyLqK76EQq1689ln2xa01VpWvWxz5sbr6F3jG0f9Ax/x3Uor6l4mtX/3@7Xv7DXz1Ofg7H/Xur4BJsz "R – Try It Online")
Returns the stack, where the top of the stack is first and the bottom of the stack is last.
Swaps `()` with `7` and then computes the code points mod 8 to get distinct
numeric values, which are easier and golfier to work with than strings.
It's golfier to work with the beginning of a vector in R, so we construct the stack that way.
Then it sees a `)`, or when `k==1`, it adds an extra zero to the top of the stack since it's golfier to add it and remove it.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 29 bytes
```
0q")]>([<""+-;U"er"U+"/')*~]p
```
[Try it online!](https://tio.run/##S85KzP3/36BQSTPWTiPaRklJW9c6VCm1SClUW0lfXVOrLrbg//9oDc1YGw0NEKVpZwOiAA "CJam – Try It Online")
```
0q Push 0, input
")]>([<""+-;U"er Translate )]>([< to +-;UUU
"U+"/')* Replace U+ by )
~ Eval as CJam code
]p Wrap and pretty-print stack
```
[Answer]
## Ceylon, ~~285~~ 266 bytes
```
function f(variable String c){variable Integer[]s=[0];value o=>[s[0]else nothing,s=s.rest][0];void u(Integer i)=>s=[i,*s];while(c!=""){if(c[0:2]=="()"){u(1);c=c.rest;}switch(c[0])case(')'){u(o+o);}case(']'){u(-o+o);}case('>'){noop(o);}else{u(0);}c=c.rest;}return s;}
```
[Try it online!](https://try.ceylon-lang.org/?gist=a5ca7a1cc2215e204cc7f1955080f875)
(Saved 19 bytes due to a suggestion by Leo.)
Formatted and commented:
```
// Interpreter for ThirdFlak
// Question: https://codegolf.stackexchange.com/q/163242/2338
// This answer: https://codegolf.stackexchange.com/a/163403/2338
//
// This function takes the code as a string, and returns the value
// of the stack as a sequence of Integers.
function f(variable String c) {
// stack, in the beginning just a single 0.
// Top element of the stack is the first, because push + pop is easier this way.
variable Integer[] s = [0];
// pop – used like an Integer variable (not a function – this saves the `()`), but has side effects.
value o =>
// `s[0]` is the first element of the stack. We tell the compiler
// that it is non-null (otherwise we'll get an error at run time)
// using the `else nothing`. `s.rest` is `s` without its first element.
// Both together are wrapped into a 2-tuple, of which we then take just
// the first element, to have both together in an expression instead
// the longer way using an accessor block with a temporary variable and a return.
// value o {
// value r = s[0] else nothing;
// s = s.rest;
// return r;
// }
[s[0] else nothing, s = s.rest][0];
// push
void u(Integer i) =>
// a tuple enumeration, using the spread argument.
s = [i, *s];
// the main loop
while (c != "") {
if (c[0:2] == "()") {
// »`()` is the only two-characters operator in Third-Flak. It increases the top of the third stack by 1.«
// As `)` alone adds the two top elements together, we can just push a one here, and let the handling for `)` do the rest.
u(1);
c = c.rest;
}
switch (c[0])
case (')') {
// »`)` pops two elements from the third stack and pushes back their sum.«
u(o + o);
}
case (']') {
// »`]` pops two elements from the third stack and pushes back the result of subtracting the first from the second.«
// As the o written first is the first one, we can't write this as a subtraction.
u(-o + o);
}
case ('>') {
// »`>` pops an element from the third stack.«
// `o;` alone is not a valid statement, so we pass it to the `noop` function.
noop(o);
}
else {
// all other valid code characters are `(`, `[`, `<`, which all just push a 0.
u(0);
}
c = c.rest;
}
return s;
}
```
[Try it online!](https://try.ceylon-lang.org/?gist=e12c8382d40572847ccaee3520ae1f24)
] |
[Question]
[
# The task:
Output a value for `x`, where `a mod x = b` for two given values `a,b`.
# Assumption
* `a` and `b` will always be positive integers
* There won't always be a solution for `x`
* If multiple solutions exist, output at least one of them.
* If there aren't any solutions, output nothing or some indication that no solutions exist.
* Built-ins are allowed (not as fun as other mathematical approaches)
* Outputs are always integers
# Examples
```
A, B >> POSSIBLE OUTPUTS
5, 2 >> 3
9, 4 >> 5
8, 2 >> 3, 6
6, 6 >> 7, (ANY NUMBER > 6)
8, 7 >> NO SOLUTION
2, 4 >> NO SOLUTION
8, 5 >> NO SOLUTION
10,1 >> 3, 9
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest bytes wins.
[Answer]
# [JavaScript](https://babeljs.io/), ~~28~~ ~~27~~ ~~26~~ ~~24~~ 23 bytes
```
a=>b=>(a-=b)?a>b&&a:b+1
```
[Try it online!](https://tio.run/nexus/javascript-babel-node#S7f9n2hrl2Rrp5Goa5ukaZ9ol6SmlmiVpG34Pzk/rzg/J1UvJz9dI13DVFNDwUhT05oLVdgSKGyCKWyBXbUZUNgMu2pzTGEj7GYbGmhqGAKF/wMA "JavaScript (Babel Node) – TIO Nexus")
`false` indicates no solution.
-1 thanks [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
tQ:\=f
```
[Try it online!](https://tio.run/nexus/matl#@18SaBVjm/b/vwWXEQA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/hfEmgVY5v2X83FJeS/KZcRlyWXCZcFkDYDQgsucyALxDflMjTgMgQA).
### Explanation
Consider inputs `8`, `2` as an example.
```
t % Implicit input. Duplicate STACK: 8, 8
Q % Add 1 STACK: 8, 9
: % Range STACK: 8, [1 2 3 4 5 6 7 8 9]
\ % Modulo STACK: [0 0 2 0 3 2 1 0 8]
= % Implicit input. Equality comparison STACK: [0 0 1 0 0 1 0 0 0]
f % Indices of nonzeros. Implicit display STACK: [3 6]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~40~~ 34 bytes
-6 bytes thanks to Bubbler
```
lambda a,b:[(a==b)*-~a,a-b][a>b*2]
```
[Try it online!](https://tio.run/##TY1BDoIwEEX3nGISNy0OUVpahAQvgl1MBSKJFkJY4Mar1zbExMX/b17@Yub3@pic8ENz80962Y6A0NYto6axPM0@hJRZ09LVpsL4YVrCDhZGBy1TKDgCq7CIuOymUe9WRojfpiLyM@a7FtzUCczL6FYYWHjJkwP029zf176rQcIJVIhEHbo8htr@IrGKl/8C "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
‘R⁸%i
```
Returns the minimal valid **x** or **0** is there is none.
[Try it online!](https://tio.run/nexus/jelly#@/@oYUbQo8Ydqpn/Dy/Xf9S0JvL//2hTHQWjWB2FaEsdBRMQbQHlm@komEH55iDaCCFvCqINDXQUDGMB "Jelly – TIO Nexus")
[Answer]
# Groovy, 48 bytes (using built-in):
```
{a,b->Eval.me(a+"g").modInverse(Eval.me(b+"g"))}
```
---
`Eval.me(...+"g")` - Affixes "g" to the input, making it a BigInteger.
`modInverse(...)` - Performs the inverse modulo operation.
---
# Java 8, 70 bytes
```
{a,b->return BigInteger.valueOf(a).modInverse(BigInteger.valueOf(b));}
```
[Answer]
# [R](https://www.r-project.org/), ~~33~~ 28 bytes
```
pryr::f(match(b,a%%1:(a+1)))
```
[Try it online!](https://tio.run/nexus/r#S7P9n1aal1ySmZ@nkaiTpJmbWJKcoZGkk6iqamilkahtqKn5P03DVMdIkytNw1LHBERZQHhmOmYQnjmIMoLJmYIoQwMdQ83/AA "R – TIO Nexus")
-4 bytes thanks to Jarko Dubbeldam.
-1 byte thanks to Giuseppe.
Returns `NA` if there is no solution. TIO doesn't have the pryr library installed, so the code at that link uses `function(a,b)` instead.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
³%_⁴
r‘ÇÐḟ
```
A full program taking the two positive integers, `a` and `b`, and printing a list of the integer solutions between `min(a,b)+1` and `max(a,b)+1` inclusive.
**[Try it online!](https://tio.run/nexus/jelly#ARoA5f//wrMlX@KBtApy4oCYw4fDkOG4n////zj/Mg)**
[Answer]
## Mathematica 36 Bytes
```
a_±b_:=Select[Range[9a],a~Mod~#==b&]
```
Input:
```
5 ± 2
9 ± 4
8 ± 2
6 ± 6
8 ± 7
2 ± 4
8 ± 5
10 ± 1
```
Output:
```
{3}
{5}
{3, 6}
{7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, \
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, \
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54}
{}
{}
{}
{3, 9}
```
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
Crashes with `code.hs: out of memory (requested ??? bytes)` if there is no solution (times out on TIO before that):
```
a!b=[x|x<-[b+1..],mod(a-b)x<1]!!0
```
[Try it online!](https://tio.run/##HYyxDoIwGIR3nuJgglgJGDVKgMXJRCdHQsxfaIQIrWlrYPDdsbrcfXe5XEfmKYZhWcjnRTV/5nxd8VUaxzUbVRvSmkdznta@nywj9RIFRnpd7whfb3uz@iIR46GcTEq3JnIw9FIYFHmOh7AnJa2Q1mDqhBYeftuKGK/dUaNkQ/YXA4aAcRagLB2YTk0IQy2oBSHLcJY2go9/waN62WHjHbH1Ds732HtpgvQL "Haskell – Try It Online")
Thanks at [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen?tab=profile) for spotting a mistake!
[Answer]
# [C# (Mono C# compiler)](http://www.mono-project.com/docs/about-mono/languages/csharp/), ~~57 56~~ 26 bytes
Port of Rod's [Python answer.](https://codegolf.stackexchange.com/a/120912/82859)
Thanks to W W for -1 byte.
HUGE thanks to Kevin Cruijssen for -30 bytes.
```
a=>b=>a-b>b?a-b:a==b?a+1:0
```
[Try it online!](https://tio.run/##fY2xCsIwFEX3fkXGBKO0xVZtqQ5CJzs5OKc1yIP2BfpSQUq/PRpwNC73XjgcbkfrwaBxEwE@2PVFVg9l1ysi1sxklYWOAVpWc59K@mzFPGo7jcjVuj224vSpgquq8nOVFHG5OBd95aeBO2sUIBdzdDZIpteb2whWXwA1r3kmUyHKn@ggtyG0D1u5zMPWLoTSf19ZCCWxTDxbosW9AQ "C# (Mono C# compiler) – Try It Online")
[Answer]
# Pyth, 16 bytes
```
hhx!0mqeQ%hQdShh
```
[Try it online!](http://pyth.herokuapp.com/?code=hhx%210mqeQ%25hQdShh&debug=0)
[All test cases](http://pyth.herokuapp.com/?code=hhx%210mqeQ%25hQdShh&test_suite=1&test_suite_input=%5B5%2C+2%5D%0A%5B9%2C+4%5D%0A%5B8%2C+2%5D%0A%5B6%2C+6%5D%0A%5B8%2C+7%5D%0A%5B2%2C+4%5D%0A%5B8%2C+5%5D%0A%5B10%2C+1%5D&debug=0)
Takes input as `[a, b]`, errors if no solution found. Will revise if erroring isn't allowed.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 bytes
```
A←{(⍳⍵+1)/⍨⍺=⍵|⍨⍳⍵+1}
```
[Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG1Ctcaj3s2PerdqG2rqP@pd8ah3ly2QVwNmQsRr//@vftQ3FagWyNVRf9Q2SV1Hw@hRVzOQq@moYAhh1R5aofGoq8lUwUhTB8SwVDCBMCxgImYKZjARcwjDCKHGFMIwNFAw1AQA "APL (Dyalog Unicode) – TIO Nexus")
Golfing in progress...
[Answer]
# Mathematica, 28 bytes
```
Which[#>2#2,#-#2,#==#2,#+1]&
```
[Answer]
# PHP>=7.1, 51 Bytes
```
for([,$a,$b]=$argv;++$x<2*$a;)$a%$x!=$b?:print$x._;
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/9b7ef707279c3b1e85c55023a15bb1312ec5600d)
[Answer]
# Axiom, ~~147~~ 128 bytes
```
g(a:PI,c:PI):Union(List PI,Stream INT)==(a<c=>[];r:=a-c;r=0=>expand((a+1..)::UniversalSegment INT);[b for b in divisors(r)|b>c])
```
ungolf it and test
```
--a%b=c return all possible b
f(a:PI,c:PI):Union(List PI, Stream INT)==
a<c=>[]
r:=a-c
r=0=>expand((a+1..)::UniversalSegment INT)
[b for b in divisors(r)|b>c]
(3) -> [[i,j,g(i,j)] for i in [5,9,8,6,8,2,8,10] for j in [2,4,2,6,7,4,5,1]]
(3)
[[5,2,[3]], [9,4,[5]], [8,2,[3,6]], [6,6,[7,8,9,10,11,12,13,14,15,16,...]],
[8,7,[]], [2,4,[]], [8,5,[]], [10,1,[3,9]]]
Type: List List Any
```
This would find all the solution even the infinite set solution...
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 9 bytes
```
a%,a+2@?b
```
Takes the two numbers as command-line arguments. Outputs the smallest solution, or nil if no solution exists. [Try it online!](https://tio.run/##K8gs@F/9P1FVJ1HbyME@6X@tgm@oQjSXQrSpglEskLJUMAFRFhCemYIZhGcOooxgcqYgytBAwTCWK/b/f90AAA "Pip – Try It Online")
### Explanation
```
a, b are cmdline args (implicit)
,a+2 Range from 0 up to but not including a+2
a% Take a mod each of those numbers
(Note that a%0 returns nil; it emits a warning, but only if warnings are turned on)
@?b Find the index of the first occurrence of b in this list, or nil if it doesn't occur
Autoprint (implicit)
```
For example, with input of `8` and `2`:
```
a+2 10
, [0 1 2 3 4 5 6 7 8 9]
a% [() 0 0 2 0 3 2 1 0 8]
```
The 0-based index of the first occurrence of `2` in this list is `3`, which is our solution.
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
(->]){-,~=*1+]
```
[Try it online!](https://tio.run/##PUy7DcMgFOzfFKc0NgQsQwz@SLjIAFnAooDChSewFMWrE/QK63Tf4o7y6NDsCEsDhd@CHpWl1WsUX62uIM0zFkGfd4etTSFkIfWVVNI5bmnN0sbisMPSXHWgibOv6jmPZO/dkemrGS4D8ecLDh4jTsaM8w8 "J – Try It Online")
Translation of [Rod's Python 2 solution](https://codegolf.stackexchange.com/a/120912/78410).
### How it works
The rare cases where a J code can be directly translated into Python.
```
(->]){-,~=*1+] <=> [(a==b)*(1+b),a-b][a-b>b]
=*1+] (a==b)*(1+b)
-,~ [ ,a-b]
{ [ ]
(->]) a-b>b
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
UµV ?U>V©U:ÒV
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=VbVWID9VPlapVTrSVg==&input=OCAz)
Translation of [eush77's JS solution](https://codegolf.stackexchange.com/a/120913/78410).
The code is just `(U-=V)?U>V&&U:-~V` when transpiled to JS, where `U` and `V` are the two input values.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
```
->a,b{(1..a+1).find{|x|a%x==b}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6law1BPL1HbUFMvLTMvpbqmoiZRtcLWNqm29j9IxkJTLzexACRcoJAWbaFTEVv7HwA "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
(Eventually) Outputs `undefined` if there's no solution.
```
@%X¥V}a
```
[Try it here](https://ethproductions.github.io/japt/?v=1.4.6&code=QCVYpVZ9YQ==&input=NQoy)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes
```
{grep $^a%*==$^b,^$a+2}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUBBJS5RVcvWViUuSSdOJVHbqPZ/cWKlQpqGqY6CkWadkoKdnYKxkjUXRNBSR8EEKmgKF7RAUqlgBhc201EwgwqbI6s1hwr6@SsE@/uEhnj6@8GljRDmY5MG6jbFI21ooGMId4ilkvV/AA "Perl 6 – Try It Online")
Anonymous code block that returns a list of possible values from `2` up to `a+1`
[Answer]
# [ORK](https://github.com/TryItOnline/ork), 566 bytes
```
When this program starts:
I have a inputter called I
I have a number called a
I have a number called b
I is to read a
I is to read b
I have a mathematician called M
M's first operand is a
M's second operand is b
M is to subtract
I have a number called n
n is M's result
M's first operand is b
M's second operand is n
M is to compare
I have a scribe called W
If M says it's less then W is to write n
If M says it's less then W is to write "\n"
M's second operand is a
M is to compare
If M says it's equal then W is to write a
If M says it's equal then W is to write a
```
[Try it online!](https://tio.run/##jZCxbsMwDER3fQWRJXPG9g88ePbShVKYWqhMOSSVIF/vymlSp2gMZBFA3t07Qlm@pqnricH6qDBK/hQcQA3F9N010OOJACHyWMxIIGBKtIdmkbgMfhFwTfBVqA2WQQh/fA@jX2IDWk/1iSEi39Ota7cKhyhqkEcS5P0cx@taKeQ6P@y9a290Ld4Eg62dxY5n54wR0pLseZFfKeLfopCHEYWWHg0SPd17OtccoAXFi0K0ykqkNTf/fHcjnCUaVeKLxs0Hb1auwv9X/WXSsWB6BsXXndP05nbf "ORK – Try It Online")
**O**bjects **R** **K**ool. Luckily, however, I didn't need to use any (besides the built-in ones) for this task.
[Answer]
## F#, 40 bytes
```
let m a b=Seq.find(fun x->a%x=b){1..a+1}
```
[Try it online!](https://tio.run/##ZZBBC4IwGIbv/YqXYKCkkpJWlN46F3QUD7NcDGrVXGFUv32tBWL13Z4978b7jdX@5igrrfeVwgEUZbquzgHjYuuwi0DjZ5Q0aenewyCgg/Cp8/lCKHlbHblQWdGz9ygXoHJ3RdqDmdyJPUTuzAKcqYdRC5OuSTwkLYRDD2E3N24h@nkhdmeFpUeGd12uKgnb90S5hJ99ombe9ShSsFpZ9yVKI2qx/ReNEfYz2tOTNOsygT7hIARkaRKE902mQena2FC/AA)
Pretty straight-forward. Throws a `System.Collections.Generic.KeyNotFoundException` if no solution can be found.
You could also modify it to `Seq.tryFind`, which will return an `int option`, with `None` if no solution could be found.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
>Lʒ¹s%Q
```
[Try it online](https://tio.run/##yy9OTMpM/f/fzufUpEM7i1UD//@34DICAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWVC6KGV/@18Tk06tK5YNSLwf63O/@hoUx2jWB2FaEsdExBlAeGZ6ZhBeOYgyggmZwqiDA10DGNjAQ).
**Explanation:**
```
> # First (implicit) input + 1
L # Create a range [1, n]
ʒ # Filter; only keep elements where:
¹s% # The first input modulo this value
Q # Equals the second (implicit) input
```
[Answer]
# Java 8, 26 bytes
```
a->b->a-b>b?a-b:a==b?a+1:0
```
[Port of *@Epicness*' C# answer](https://codegolf.stackexchange.com/a/173141/52210), after I golfed it a bit more.
[Try it online.](https://tio.run/##nY67DoJAEEV7vmJKNspGiPhm7UwsrCiNxfAyi@tCZCAxxm/HNaKtaDM5yZzce3Ns0MmTUxsrrCrYodQ3C6AiJBlDbr68Jql4VuuYZKH5poPVVlN6TC/DflIHQkAGQYuOiByBTiSitbkLDAIDA3cxapeWqS/rSJn6bkVTyATOZpkd0kXq4/6A7DkSILxWlJ55URMvzYeUtjOOZamuts868BhbfpPnb3ncQ579kjxhH/ghedpD9v7a7PeQ3dHbdl/23bq3Dw)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 21 bytes
Same trick as most posted solutions. First, we prepare all necessary values on the stack and then check the comparisons.
```
::r::{-:{)?nr=?!;1+n;
```
[Try it online!](https://tio.run/##S8sszvj/38qqyMqqWteqWtM@r8jWXtHaUDvP@v///7plCoYGYBIA "><> – Try It Online")
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 128 bytes
```
> Input
> Input
>> 1²
>> (3]
>> 1%L
>> L=2
>> Each 5 4
>> Each 6 7
>> L⋅R
>> Each 9 4 8
> {0}
>> {10}
>> 12∖11
>> Output 13
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtO2ykYHtoEojSMY8E8VR8Q5WNrBKJcE5MzFEwVTOBsMwVzsPSj7tYguKClgomCBdDIaoNakFi1IYQ2NHrUMc3QEMT0Ly0B2qZgaPz/vwWXOQA "Whispers v2 – Try It Online")
Returns a set of all possible solutions, and the empty set (i.e. \$\emptyset\$) when no solution exists.
## How it works
Unsurprisingly, it works almost identically to most other answers: it generates a list of numbers and checks each one for inverse modulus with the argument.
If you're familiar with how Whispers' program structure works, feel free to skip ahead to the horizontal line. If not: essentially, Whispers works on a line-by-line reference system, starting on the final line. Each line is classed as one of two options. Either it is a **nilad line**, or it is a **operator line**.
Nilad lines start with `>`, such as `> Input` or `> {0}` and return the exact value represented on that line i.e `> {0}` returns the set \$\{0\}\$. `> Input` returns the next line of STDIN, evaluated if possible.
Operator lines start with `>>`, such as `>> 1²` or `>> (3]` and denote running an operator on one or more values. Here, the numbers used do not reference those explicit numbers, instead they reference the value on that line. For example, `²` is the square command (\$n \to n^2\$), so `>> 1²` does not return the value \$1^2\$, instead it returns the square of line **1**, which, in this case, is the first input.
Usually, operator lines only work using numbers as references, yet you may have noticed the lines `>> L=2` and `>> L⋅R`. These two values, `L` and `R`, are used in conjunction with `Each` statements. `Each` statements work by taking two or three arguments, again as numerical references. The first argument (e.g. `5`) is a reference to an operator line used a function, and the rest of the arguments are arrays. We then iterate the function over the array, where the `L` and `R` in the function represent the current element(s) in the arrays being iterated over. As an example:
Let \$A = [1, 2, 3, 4]\$, \$B = [4, 3, 2, 1]\$ and \$f(x, y) = x + y\$. Assuming we are running the following code:
```
> [1, 2, 3, 4]
> [4, 3, 2, 1]
>> L+R
>> Each 3 1 2
```
We then get a demonstration of how `Each` statements work. First, when working with two arrays, we zip them to form \$C = [(1, 4), (2, 3), (3, 2), (4, 1)]\$ then map \$f(x, y)\$ over each pair, forming our final array \$D = [f(1, 4), f(2, 3), f(3, 2), f(4, 1)] = [5, 5, 5, 5]\$
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTiHaUEfBSEfBWEfBJJYLyDUBs4EihkCunYKPdhCIck1MzlAwVjBUMPoP5PmXlhSUliiY/AcA "Whispers v2 – Try It Online")
---
**How *this* code works**
Working counter-intuitively to how Whispers works, we start from the first two lines:
```
> Input
> Input
```
This collects our two inputs, lets say \$x\$ and \$y\$, and stores them in lines **1** and **2** respectively. We then store \$x^2\$ on line **3** and create a range \$A := [1 ... x^2]\$ on line **4**. Next, we jump to the section
```
>> 1%L
>> L=2
>> Each 5 4
>> Each 6 7
```
The first thing executed here is line **7**, `>> Each 5 4`, which iterates line **5** over line **4**. This yields the array \$B := [i \: \% \: x \: | \: i \in A]\$, where \$a \: \% \: b\$ is defined as the [modulus](https://en.wikipedia.org/wiki/Modulo_operation) of \$a\$ and \$b\$.
We then execute line **8**, `>> Each 6 7`, which iterates line **6** over \$B\$, yielding an array \$C := [(i \: \% \: x) = y \: | \: i \in A]\$.
For the inputs \$x = 5, y = 2\$, we have \$A = [1, 2, 3, ..., 23, 24, 25]\$, \$B = [0, 1, 2, 1, 0, 5, 5, ..., 5, 5]\$ and \$C = [0, 0, 1, 0, 0, ..., 0, 0]\$
We then jump down to
```
>> L⋅R
>> Each 9 4 8
```
which is our example of a dyadic `Each` statement. Here, our function is line **9** i.e `>> L⋅R` and our two arrays are \$A\$ and \$C\$. We multiply each element in \$A\$ with it's corresponding element in \$C\$, which yields an array, \$E\$, where each element works from the following relationship:
$$E\_i =
\begin{cases}
0 & C\_i = 0 \\
A\_i & C\_i = 1
\end{cases}$$
We then end up with an array consisting of \$0\$s and the inverse moduli of \$x\$ and \$y\$. In order to remove the \$0\$s, we convert this array to a set (`>> {10}`), then take the set difference between this set and \$\{0\}\$, yielding, then outputting, our final result.
[Answer]
**C#, 53 bytes (83 with function heading)**
```
static int F(int a, int b){
for(int i=1;i<=a+1;i++){if(a%i==b)return i;}return 0;
}
```
[Try It Online](https://tio.run/nexus/cs-mono#fY0xC8IwEIX3/oosQkKDtMVWJWYSOtnJwTmtqRzUBJJUkJDfXm3Rzbi8u3cf795oQd3Q@WmdvLOkG4S1qPGJdcJBh0A5VONZBV1MS/zUa7OcgOcMDlyk75GmxEOPxQo4b4mRbjQKAQufLWNT@P58aLiiRoDCxCdHrawe5PpiwMkTKIlrXNKCEPYT7ekmhnbxVEWreGobQ8W/rjKG8ozmMwtJmF4)
First try at codegolf. Probably not the best language to use, nor the most efficient coding.
] |
[Question]
[
# About the Series
First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series [in the first post](https://codegolf.stackexchange.com/q/45302/8478).
Although I have a bunch of ideas lined up for the series, the future challenges are not set in stone yet. If you have any suggestions, please let me know [on the relevant sandbox post](http://meta.codegolf.stackexchange.com/a/4750/8478).
# Hole 3: Integer Partitions
Time to increase the difficulty a bit.
A [**partition**](http://en.wikipedia.org/wiki/Partition_(number_theory)) of a positive integer `n` is defined as a multiset of positive integers which sum to `n`. As an example if `n = 5`, the following partitions exist:
```
{1,1,1,1,1}
{2,1,1,1}
{2,2,1}
{3,1,1}
{3,2}
{4,1}
{5}
```
Note that these are multisets, so there is no order to them, `{3,1,1}`, `{1,3,1}` and `{1,1,3}` are all considered identical.
Your task is, given `n`, to generate a random partition of `n`. Here are the detailed rules:
* The distribution of partitions produced must be **uniform**. That is, in the above example, each partition should be returned with probability 1/7.
Of course, due to the technical limitations of PRNGs, perfect uniformity will be impossible. For the purpose of assessing uniformity of your submission, the following operations will be regarded as yielding perfectly uniform distributions:
+ Obtaining a number from a PRNG (over any range), which is documented to be (approximately) uniform.
+ Mapping a uniform distribution over a larger set of numbers onto a smaller set via modulo or multiplication (or some other operation which distributes values evenly). The larger set has to contain at least 1024 times as many possible values as the smaller set.
* Since the partitions are multisets you may return them in any order, and this order does not have to be consistent. However, for the purpose of the random distribution, the order is ignored. That is, in the above example, `{3,1,1}`, `{1,3,1}` and `{1,1,3}` *together* must have a probability of 1/7 of being returned.
* Your algorithm must have a **deterministic runtime.** In particular, you cannot generate random multisets and reject them if they don't sum to `n`.
* Your algorithm's time complexity must be polynomial in `n`. In particular, you cannot simply generate all partitions and select a random one (since the number of partitions grows exponentially with `n`). You may assume that the PRNG you're using can return uniformly distributed values in O(1) per value.
* You must not use any built-in function which solves this task.
You may write a full program or a function and take input via STDIN or closest alternative, command-line argument or function argument and produce output via return value or by printing to STDOUT (or closest alternative).
You may assume that `n ≤ 65` (such that the number of partitions is less than 221). Output may be in any convenient, unambiguous list or string format.
If you submit a function, please consider also providing a little test program which calls the function a number of times and prints the results. It's okay if the parameters have to be tweaked in the code. This is just so people can check that the solution is at least approximately uniform.
This is code golf, so the shortest submission (in bytes) wins. And of course, the shortest submission per user will also enter into the overall leaderboard of the series.
# Leaderboard
**[The first post of the series generates a leaderboard.](https://codegolf.stackexchange.com/q/45302/8478)**
To make sure that your answers show up, please start every 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
```
*(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)*
[Answer]
# Python 2, 179 bytes
```
from random import*
m=r=input();i=q=r+1;h=[1]+[0]*q*q;exec"h[i]=h[i+~q]+h[i-i%q*q];i+=1;"*r*q
while r:
x=random()*sum(h[r*q:r*q-~m]);m=0
while x>0:m+=1;x-=h[r*q+m]
print m;r-=m
```
I used formula (39) from [this Knuth extract](http://www.cs.utsa.edu/%7Ewagner/knuth/fasc3b.pdf), which gives the number of partitions of `n` that have exactly `m` parts. This happens to equal the number of partitions of `n` that have `m` as the maximum element, which is the interpretation I'm using. The elements of the partition are generated from greatest to least. At each stage the formula is reused with the current remainder of `n` and maximum allowed element.
[Answer]
# Dyalog APL, ~~67~~ ~~59~~ 51 bytes
`p←{⍵,⊂1,⍨+/¨⌽⍵↑¨⍨⌽⍳⍴⍵}⍣⎕⊢⍬⋄f←{⍵=0:⍬⋄a,a∇⍵-a←{1++/(?+/⍵)>+\⍵}⍺↑⍵⊃p}⍨` (67 bytes)
`p` is a vector of vectors in which `p[n][k]` is the number of partitions of `n` into `k` summands, or equivalently: the number of partitions with greatest summand `k`. We build `p` by starting with the empty vector `⍬`, reading `n` (the `⎕` reads input) and repeatedly applying the following:
```
{⍵,⊂1,⍨+/¨⌽⍵↑¨⍨⌽⍳⍴⍵}
⍴⍵ ⍝ the current length, initially 0
⍳⍴⍵ ⍝ 1 2 ... length
⌽⍳⍴⍵ ⍝ length ... 2 1
⍵↑¨⍨ ⍝ take length elements from p[1], length-1 from p[2], etc
⍝ padded with 0-s, e.g. if p was (,1)(1 1)(1 1 1)(1 2 1 1)(1 2 2 1 1):
⍝ we get: (1 0 0 0 0)(1 1 0 0)(1 1 1)(1 2)(,1)
⌽ ⍝ reverse it: (,1)(1 2)(1 1 1)(1 1 0 0)(1 0 0 0 0)
+/¨ ⍝ sum each: 1 3 3 2 1
1,⍨ ⍝ append 1: 1 3 3 2 1 1
⍵,⊂ ⍝ append the above to the vector of vectors
```
After `n` applications (`⍣⎕`), we have built `p`.
`f` picks a random partition. `n f k` is a random partition of *at most* `k` summands. `f n` is `n f n`.
```
{⍵=0:⍬⋄a,a∇⍵-a←{1++/(?+/⍵)>+\⍵}⍺↑⍵⊃p}⍨
⍨ ⍝ "selfie" -- use n as k if no k is provided
⍵=0:⍬ ⍝ if n=0 return empty
⍵⊃p ⍝ pick the n-th element of p
⍺↑ ⍝ take k elements from that
{1++/(?+/⍵)>+\⍵} ⍝ use them as weights to pick a random number 1...k
{ +\⍵} ⍝ partial sums of weights
{ (?+/⍵) } ⍝ a random number 1...sum of weights
{ (?+/⍵)>+\⍵} ⍝ which partial sums is it greater than?
{ +/ } ⍝ count how many "greater than"-s
{1+ } ⍝ we're off by one
a← ⍝ this will be the greatest number in our partition
a∇⍵-a ⍝ recur with n1=n-a and k1=a
a, ⍝ prepend a
```
---
Some improvements:
* inline `p` at the cost of slightly worse (but still good enough) performance
* in the computation of `p` rearrange `⌽` and `1,` to save a character
* turn `{1++/(?+/⍵)>+\⍵}` into a train with `1+` in front: `1+(+/(?+/)>+\)`
* make `f` an anonymous function and supply `⎕` (eval'ed input) as an argument to obtain a complete program
`{⍵=0:⍬⋄a,a∇⍵-a←1+(+/(?+/)>+\)⍺↑⍵⊃{⍵,⊂⌽1,+/¨⍵↑¨⍨⌽⍳⍴⍵}⍣⍵⊢⍬}⍨⎕` (59 bytes)
[Test with n=5](http://tryapl.org/?a=%7B%u2375%3D0%3A%u236C%u22C4a%2Ca%u2207%u2375-a%u21901+%28+/%28%3F+/%29%3E+%5C%29%u237A%u2191%u2375%u2283%7B%u2375%2C%u2282%u233D1%2C+/%A8%u2375%u2191%A8%u2368%u233D%u2373%u2374%u2375%7D%u2363%u2375%u22A2%u236C%7D%u23685&run)
[Test with n=65](http://tryapl.org/?a=%7B%u2375%3D0%3A%u236C%u22C4a%2Ca%u2207%u2375-a%u21901+%28+/%28%3F+/%29%3E+%5C%29%u237A%u2191%u2375%u2283%7B%u2375%2C%u2282%u233D1%2C+/%A8%u2375%u2191%A8%u2368%u233D%u2373%u2374%u2375%7D%u2363%u2375%u22A2%u236C%7D%u236865&run)
And the following link runs n=5 thousands of times and gathers statistics about the frequency of each partition:
[`⎕rl←0 ⋄ {⍺,⍴⍵}⌸ {⍵=0:⍬⋄a,a∇⍵-a←1+(+/(?+/)>+\)⍺↑⍵⊃{⍵,⊂⌽1,+/¨⍵↑¨⍨⌽⍳⍴⍵}⍣⍵⊢⍬}⍨ ¨10000⍴5`](http://tryapl.org/?a=%u2395rl%u21900%20%u22C4%20%7B%u237A%2C%u2374%u2375%7D%u2338%20%7B%u2375%3D0%3A%u236C%u22C4a%2Ca%u2207%u2375-a%u21901+%28+/%28%3F+/%29%3E+%5C%29%u237A%u2191%u2375%u2283%7B%u2375%2C%u2282%u233D1%2C+/%A8%u2375%u2191%A8%u2368%u233D%u2373%u2374%u2375%7D%u2363%u2375%u22A2%u236C%7D%u2368%20%A810000%u23745&run)
---
More improvements, with help from [Roger Hui](https://en.wikipedia.org/wiki/Roger_Hui):
* replace `{⍵=0:A⋄B}` with `{×⍵:B⋄A}`. Signum (`×⍵`) returns true for `⍵>0` and false for `⍵=0`.
* replace `(+/(?+/)>+\)` with `+/b<?⊃⌽b←+\`, it saves a character
* use a matrix instead of vector of vectors to compute `p`: replace `⍵⊃{⍵,⊂⌽1,+/¨⍵↑¨⍨⌽⍳⍴⍵}⍣⍵⊢⍬` with `⊃↓(0,⍨⊢⍪⍨1 1⍉+\)⍣⍵⍪1`.
`{×⍵:a,a∇⍵-a←1++/b<?⊃⌽b←+\⍺↑⊃↓(0,⍨⊢⍪⍨1 1⍉+\)⍣⍵⍪1⋄⍬}⍨` (51 bytes)
[test n=5](http://tryapl.org/index.dyalog?a=%7B%D7%u2375%3Aa%2Ca%u2207%u2375-a%u21901++/b%3C%3F%u2283%u233Db%u2190+%5C%u237A%u2191%u2283%u2193%280%2C%u2368%u22A2%u236A%u23681%201%u2349+%5C%29%u2363%u2375%u236A1%u22C4%u236C%7D%u23685&run); [test n=65](http://tryapl.org/index.dyalog?a=%7B%D7%u2375%3Aa%2Ca%u2207%u2375-a%u21901++/b%3C%3F%u2283%u233Db%u2190+%5C%u237A%u2191%u2283%u2193%280%2C%u2368%u22A2%u236A%u23681%201%u2349+%5C%29%u2363%u2375%u236A1%u22C4%u236C%7D%u236865&run); [freq stats](http://tryapl.org/index.dyalog?a=%7B%u237A%2C%u2374%u2375%7D%u2338%20%7B%D7%u2375%3Aa%2Ca%u2207%u2375-a%u21901++/b%3C%3F%u2283%u233Db%u2190+%5C%u237A%u2191%u2283%u2193%280%2C%u2368%u22A2%u236A%u23681%201%u2349+%5C%29%u2363%u2375%u236A1%u22C4%u236C%7D%u2368%20%A81e4%u23745&run)
[Answer]
## GolfScript, 90 bytes
```
~[[[1.]]]\({..[[{{(\{)}%+}%1$,1$,-=}%[1,]@0=+{1+}%]zip{{(\.,/*~}%.,.rand@=+}:^%]\+}*0=^(;`
```
[Online demo](http://golfscript.apphb.com/?c=Oyc1JwoKfltbWzEuXV1dXCh7Li5bW3t7KFx7KX0lK30lMSQsMSQsLT19JVsxLF1AMD0rezErfSVdemlwe3soXC4sLyp%2BfSUuLC5yYW5kQD0rfTpeJV1cK30qMD1eKDtg)
This is an adaptation of my (simpler) [partition counting code](https://codegolf.stackexchange.com/a/32821/194) which instead of merely tracking a count tracks both a count and a uniformly selected one of the counted elements.
Side-by-side comparison of the two:
```
~[[[1.]]]\({..[[{{(\{)}%+}%1$,1$,-=}%[1,]@0=+{1+}%]zip{{(\.,/*~}%.,.rand@=+}:^%]\+}*0=^(;`
[[ 1 ]]\({..[[{ 1$,1$,-=}% 0 @0=+ ]zip{{+}* }:^%]\+}*0=^
```
Differences:
* The initial `~` is because this is a program rather than a snippet.
* The `[1.]` replacing `1` corresponds to the change in what's tracked.
* The additional `{(\{)}%+}%` increments each element in that partition, and the `{1+}%` adds `1` to the partition.
* `0` becomes `[0]` (golfed to `1,`) as part of the change in what's tracked, but because it needs to remain an array when prepended to another one it needs the extra `[ ]`.
* The simple sum `{+}*` becomes a weighted selection from the partitions, combined with a summing of their count.
* The `(;`` removes the count from the output and puts the partition into a nice format.
### Test framework
```
;7000,{;
'5'
~[[[1.]]]\({..[[{{(\{)}%+}%1$,1$,-=}%[1,]@0=+{1+}%]zip{{(\.,/*~}%.,.rand@=+}:^%]\+}*0=^(;`
}%
:RESULTS
.&${
RESULTS.[2$]--,' '\n
}/
```
Tweak the initial 7000 if you want to run a different number of trials. Note that this is far too slow for an online demo.
[Answer]
# Pyth, 64 bytes
Uses <https://stackoverflow.com/a/2163753/4230423> except that a)No cache since Pyth automatically memoizes, b)Prints each instead of appending to list, and c) is translated to Pyth.
```
M?smg-Gddr1hhS,GHG1Akd,QOgQQWQFNr1hhS,QkKg-QNNI<dKB-=dK)N=kN-=QN
```
I'll post an explanation of this when I have the time, but here is the corresponding python code:
```
g=lambda G,H: sum(map(lambda d:g(G-d, d), range(1, (H if H<G else G) + 1))) if G else 1
Q=input()
k,d = Q,random.randrange(g(Q, Q))
while Q:
for N in range(1, min(k, Q) + 1):
K = g(Q-N, N)
if d < K:
break
d -= K
print N
k=N
Q -= N
```
**Edit:** I finally got around to doing the explanation:
```
M Lambda g(G,H)
? G If G truthy
s Sum
m Map
g Recursive call
-Gdd G-d,d
r Range
1 1 to
h +1
hS First element of sorted (does min)
,GH From G and H
1 Else 1
A Double assign
kd Vars k and d
, To vals
Q Q (evaled input)
O Randrange 0 till val
gQQ Call g(Q, Q)
WQ While Q is truthy
FN For N in
r Range
1 From one
h Till +1
hS,QK Min(Q,K)
Kg K=g(
-QN Q-N
N N
I<dK If d<k
B Break (implicit close paren)
-=dk Subtracts d-=k
) Close out for loop
N Prints N
=kN Set k=N
-=QN Subtracts Q-=N
```
[Answer]
# Java, ~~285~~ 267 bytes
```
int[][]p;void p(int n){p=new int[n+1][n+1];int a=n,b=k(n,a),c,d;for(b*=Math.random();n>0;System.out.print(c+" "),n-=a=c)for(c=0;c++<(a<n?a:n)&b>=(d=k(n-c,c));b-=d);}int k(int n,int k){if(p[n][k]<1)for(int a=0,b=0;b<k&b++<n;p[n][k]=a)a+=k(n-b,b);return n>0?p[n][k]:1;}
```
This is the same method as TheBestOne's answer, but it uses a simple array instead of a map. Also, instead of returning the random partition as a `List`, it prints them to the console.
Below is a test program that runs it 100000 times. For the example `n=5`, all sets were within 0.64% of a perfect 1/7 on my last run.
```
public class Partition {
public static void main(String[] args) {
Partition p = new Partition();
for(int i=0;i<100000;i++){
p.p(5);
System.out.println();
}
}
int[][]p;
void p(int n){
p=new int[n+1][n+1];
int a=n,b=k(n,a),c,d;
for(b*=Math.random();n>0;System.out.print(c+" "),n-=a=c)
for(c=0;c++<(a<n?a:n)&b>=(d=k(n-c,c));b-=d);
}
int k(int n,int k){
if(p[n][k]<1)
for(int a=0,b=0;b<k&b++<n;p[n][k]=a)
a+=k(n-b,b);
return n>0?p[n][k]:1;
}
}
```
[Answer]
# CJam, 64 56 bytes
```
ri_L{_0>{\,f{)_@1$-j+}{)@)2$+:Umr@<@@?U+}*}{!a\;}?}2j);p
```
You can test it with this script:
```
ria100*{_L{_0>{\,f{)_@1$-j+}{)@)2$+:Umr@<@@?U+}*}{!a\;}?}2j);}%__|\f{_,\2$a-,-}2/p
```
### Explanation
```
ri_ " Read an integer and duplicate. ";
L{ " Create a memoized function of the maximum and the sum, which returns
a random partition, and the total number of partitions as the last item. ";
_0> " If sum > 0: ";
{
\,f{ " For I in 0..max-1: ";
)_@1$- " Stack: I+1 I+1 sum-I-1 ";
j+ " Recursively call with the two parameters, and prepend I+1. ";
}
{ " Reduce on the results: ";
)@)2$+ " Stack: partition1 total1 partition2 total1+total2 ";
:Umr " U = total1+total2, then generate a random number smaller than that. ";
@<@@? " If it is <total1, choose partition1, else choose partition2. ";
U+ " Append the total back to the array. ";
}*
}
{!a\;}? " Else return [0] if negative, or [1] if zero. ";
}2j
);p " Discard the total and print. ";
```
[Answer]
# Octave, 200
```
function r=c(m)r=[];a=eye(m);a(:,1)=1;for(i=3:m)for(j=2:i-1)a(i,j)=a(i-1,j-1)+a(i-j,j);end;end;p=randi(sum(a(m,:)));while(m>0)b=a(m,:);c=cumsum(b);x=min(find(c>=p));r=[r x];p=p-c(x)+b(x);m=m-x;end;end
```
Ungolfed:
```
function r=c(m)
r=[];
a=eye(m);
a(:,1)=1;
for(i=3:m)
for(j=2:i-1)
a(i,j)=a(i-1,j-1)+a(i-j,j);
end;
end;
p=randi(sum(a(m,:)));
while(m>0)
b=a(m,:);
c=cumsum(b);
x=min(find(cumsum(b)>=p));
r=[r x];
p=p-c(x)+b(x);
m=m-x;
end
end
```
Construct a square matrix where each cell (m,n) reflects the number of partitions of `m` whose largest number is `n`, according to the Knuth extract @feersum so kindly cited. For example, `5,2` gives us 2 because there are two valid partitions `2,2,1` and `2,1,1,1`. `6,3` gives us 3 for `3,1,1,1`,`3,2,1` and `3,3`.
We can now deterministically find the p'th partition. Here, we are generating `p` as a random number but you can alter the script slightly so `p` is a parameter:
```
function r=c(m,p)
r=[];
a=eye(m);
a(:,1)=1;
for(i=3:m)
for(j=2:i-1)
a(i,j)=a(i-1,j-1)+a(i-j,j);
end;
end;
while(m>0)
b=a(m,1:m);
c=cumsum(b);
x=min(find(c>=p));
r=[r x];
p=p-c(x)+b(x);
m=m-x;
end
end
```
We can now deterministically show that each outcome is solely dependent on p:
```
octave:99> for(i=1:7)
> c(5,i)
> end
ans =
1 1 1 1 1
ans =
2 1 1 1
ans =
2 2 1
ans =
3 1 1
ans =
3 2
ans =
4 1
ans = 5
```
Thus, going back to the original where p is randomly generated, we can be assured each outcome is equally likely.
[Answer]
# R, 198 bytes
```
function(m){r=c();a=diag(m);a[,1]=1;for(i in 3:m)for(j in 2:(i-1))a[i,j]=a[i-1,j-1]+a[i-j,j];p=sample(sum(a[m,]),1);while(m>0){b=a[m,];c=cumsum(b);x=min(which(c>=p));r=c(r,x);p=p-c[x]+b[x];m=m-x};r}
```
Ungolfed:
```
f <- function(m) {
r <- c()
a <- diag(m)
a[, 1] <- 1
for (i in 3:m)
for (j in 2:(i-1))
a[i, j] <- a[i-1, j-1] + a[i-j, j]
p <- sample(sum(a[m, ]), 1)
while (m > 0) {
b <- a[m, ]
c <- cumsum(b)
x <- min(which(c >= p))
r <- c(r, x)
p <- p - c[x] + b[x]
m <- m - x
}
return(r)
}
```
It follows the same structure as @dcsohl's [great solution in Octave](https://codegolf.stackexchange.com/a/47045/20469), and is thus also based on the [Knuth extract](http://www.cs.utsa.edu/~wagner/knuth/fasc3b.pdf) posted by @feersum.
I'll edit this later if I can come up with a more creative solution in R. In the meantime, any input is of course welcome.
[Answer]
# Java, 392 bytes
```
import java.util.*;Map a=new HashMap();List a(int b){List c=new ArrayList();int d=b,e=b(b,d),f=(int)(Math.random()*e),g,i;while(b>0){for(g=0;g++<Math.min(d, b);f-=i){i=b(b-g,g);if(f<i)break;}c.add(g);d=g;b-=g;}return c;}int b(int b,int c){if(b<1)return 1;List d=Arrays.asList(b,c);if(a.containsKey(d))return(int)a.get(d);int e,f;for(e=f=0;f++<Math.min(c, b);)e+=b(b-f,f);a.put(d,e);return e;}
```
Call with `a(n)`. Returns a `List` of `Integer`s
Indented:
```
import java.util.*;
Map a=new HashMap();
List a(int b){
List c=new ArrayList();
int d=b,e=b(b,d),f=(int)(Math.random()*e),g,i;
while(b>0){
for(g=0;g++<Math.min(d, b);f-=i){
i=b(b-g,g);
if(f<i)
break;
}
c.add(g);
d=g;
b-=g;
}
return c;
}
int b(int b,int c){
if(b<1)
return 1;
List d=Arrays.asList(b,c);
if(a.containsKey(d))
return(int)a.get(d);
int e,f;
for(e=f=0;f++<Math.min(c, b);)
e+=b(b-f,f);
a.put(d,e);
return e;
}
```
Adapted from <https://stackoverflow.com/a/2163753/4230423> and golfed
**How this works:** We can calculate how many partitions of an integer *n* there are in O(*n*2) time. As a side effect, this produces a table of size O(*n*2) which we can then use to generate the *k*th partition of *n*, for any integer *k*, in O(*n*) time.
So let *total* = the number of partitions. Pick a random number *k* from 0 to *total* - 1. Generate the *k*th partition.
***As usual***, suggestions are welcome :)
[Answer]
# Python 2, 173 bytes
```
from random import*
N,M=input__
R=67;d=[(0,[])]*R*R
for k in range(R*R):p,P=d[k+~R];q,Q=d[k-k%R*R];d[k]=p+q+0**k,[[x+1 for x in Q],[1]+P][random()*(p+q)<p]
print d[N*R+M][1]
```
Recursively makes a dictionary `d`, with keys `k` representing a pair `(n,m)` by `k=67*n+m` (using the guaranteed `n<=65`). The entry is the tuple of the number of partition of `n` into `m` parts, and a random such partition. The counts are computed by the recursive formula (thanks to feersum for pointing it out)
`f(n,m) = f(n-1,m-1) + f(n,n-m)`,
and the random partition is updated by picking one of the two of its branches with probability proportional to its count. The update is done by adding is done by appending a `1` for the first branch and incrementing every element for the second.
I had a lot of trouble getting out-of-bounds values of `m` and `n` to give counts of zero. At first, I used a dictionary that defaults to a count of 0 and an empty list. Here, I'm using a list and padding it with this default entry instead. Negative indices cause the list to be read from its end, which gives a default entry is nothing near the end as ever reached, and wraparounds only touch a region where `m>n`.
[Answer]
# 80386 machine code, 105 bytes
Hexdump of the code:
```
60 8b fa 81 ec 00 41 00 00 33 c0 8b f4 33 d2 42
89 14 06 42 33 ed 8b d8 03 2c 1e 2a fa 73 f9 83
c6 04 89 2c 06 42 3b d1 76 ea fe c4 3a e1 76 db
33 d2 0f c7 f0 f7 f5 86 e9 85 d2 74 1b 33 c0 8d
34 0c 39 14 86 77 03 40 eb f8 2b 54 86 fc 40 89
07 83 c7 04 2a e8 77 e1 42 89 17 83 c7 04 fe cd
7f f7 4a b6 41 03 e2 61 c3
```
As a C function: `void random_partition(int n, int result[]);`. It returns the result as a list of numbers in the supplied buffer; it doesn't mark the end of the list in any way, but the user can discover the end by accumulating the numbers - the list ends when the sum is equal to `n`.
How to use (in Visual Studio):
```
#include <stdio.h>
__declspec(naked) void __fastcall random_partiton(int n, int result[])
{
#define a(byte) __asm _emit 0x ## byte
a(60) a(8b) a(fa) a(81) a(ec) a(00) a(41) a(00) a(00) a(33) a(c0) a(8b) a(f4) a(33) a(d2) a(42)
a(89) a(14) a(06) a(42) a(33) a(ed) a(8b) a(d8) a(03) a(2c) a(1e) a(2a) a(fa) a(73) a(f9) a(83)
a(c6) a(04) a(89) a(2c) a(06) a(42) a(3b) a(d1) a(76) a(ea) a(fe) a(c4) a(3a) a(e1) a(76) a(db)
a(33) a(d2) a(0f) a(c7) a(f0) a(f7) a(f5) a(86) a(e9) a(85) a(d2) a(74) a(1b) a(33) a(c0) a(8d)
a(34) a(0c) a(39) a(14) a(86) a(77) a(03) a(40) a(eb) a(f8) a(2b) a(54) a(86) a(fc) a(40) a(89)
a(07) a(83) a(c7) a(04) a(2a) a(e8) a(77) a(e1) a(42) a(89) a(17) a(83) a(c7) a(04) a(fe) a(cd)
a(7f) a(f7) a(4a) a(b6) a(41) a(03) a(e2) a(61) a(c3)
}
void make_stack() // see explanations about stack below
{
volatile int temp[65 * 64];
temp[0] = 999;
}
int main()
{
int result[100], j = 0, n = 64, counter = n;
make_stack(); // see explanations about stack below
random_partiton(n, result);
while (counter > 0)
{
printf("%d ", result[j]);
counter -= result[j];
++j;
}
putchar('\n');
}
```
Example output (with n = 64):
>
> 21 7 4 4 3 3 3 3 2 2 2 2 2 1 1 1 1 1 1
>
>
>
This requires much explanations...
Of course I used the algorithm that everyone else used as well; there wasn't any choice with the requirement about complexity. So I don't have to explain the algorithm too much. Anyway:
I denote by `f(n, m)` the number of partitionings of `n` elements using parts no greater than `m`. I store them in a 2-D array (declared in C as `f[65][64]`), where the first index is `n`, and the second `m-1`. I decided that supporting `n=65` was too much trouble, so abandoned it...
Here is C code that calculates this table:
```
#define MAX_M 64
int f[(MAX_M + 1) * MAX_M];
int* f2;
int c; // accumulates the numbers needed to calculate f(n, m)
int m;
int k; // f(k, m), for various values of k, are accumulated
int n1;
for (n1 = 0; n1 <= n; ++n1)
{
f2 = f;
f2[n1 * MAX_M] = 1;
for (m = 2; m <= n; ++m)
{
c = 0;
k = n1;
while (k >= 0)
{
c += f2[k * MAX_M];
k -= m;
}
++f2;
f2[n1 * MAX_M] = c;
}
}
```
This code has some obfuscated style, so it can be converted to assembly language easily. It calculates the elements up to `f(n, n)`, which is the number of partitionings of `n` elements. When this code is finished, the temporary variable `c` contains the needed number, which can be used to select a random partitioning:
```
int index = rand() % c;
```
Later, this `index` is converted to the required format (list of numbers) using the generated table.
```
do {
if (index == 0)
break;
m = 0;
f2 = &f[n * MAX_M];
while (f2[m] <= index)
{
++m;
}
index -= f2[m-1];
++m;
*result++ = m;
n -= m;
} while (n > 0);
do {
*result++ = 1;
--n;
} while (n > 0);
```
This code is also optimized for conversion to assembly language. There is a small "bug": if the partitioning doesn't contain any `1` number at the end, the last loop encounters `n = 0`, and outputs an unneeded `1` element. It doesn't hurt, however, because the printing code tracks the sum of the number, and doesn't print this extraneous number.
When converted to inline assembly, this code looks like this:
```
__declspec(naked) void _fastcall random_partition_asm(int n, int result[])
{
_asm {
pushad;
// ecx = n
// edx = m
// bh = k; ebx = k * MAX_M * sizeof(int)
// ah = n1; eax = n1 * MAX_M * sizeof(int)
// esp = f
// ebp = c
// esi = f2
// edi = result
mov edi, edx;
sub esp, (MAX_M + 1) * MAX_M * 4; // allocate space for table
xor eax, eax;
row_loop:
mov esi, esp;
xor edx, edx;
inc edx;
mov dword ptr [esi + eax], edx;
inc edx;
col_loop:
xor ebp, ebp;
mov ebx, eax;
sum_loop:
add ebp, [esi + ebx];
sub bh, dl;
jae sum_loop;
add esi, 4;
mov [esi + eax], ebp;
inc edx;
cmp edx, ecx;
jbe col_loop;
inc ah;
cmp ah, cl;
jbe row_loop;
// Done calculating the table
// ch = n; ecx = n * MAX_M * sizeof(int)
// eax = m
// ebx =
// edx = index
// esp = f
// esi = f2
// ebp = c
// edi = result
xor edx, edx;
rdrand eax; // generate a random number
div ebp; // generate a random index in the needed range
xchg ch, cl; // multiply by 256
n_loop:
test edx, edx;
jz out_trailing;
xor eax, eax;
lea esi, [esp + ecx];
m_loop:
cmp [esi + eax * 4], edx;
ja m_loop_done;
inc eax;
jmp m_loop;
m_loop_done:
sub edx, [esi + eax * 4 - 4];
inc eax;
mov [edi], eax;
add edi, 4;
sub ch, al;
ja n_loop;
out_trailing:
inc edx;
out_trailing_loop:
mov dword ptr [edi], edx;
add edi, 4;
dec ch;
jg out_trailing_loop;
dec edx;
mov dh, (MAX_M + 1) * MAX_M * 4 / 256;
add esp, edx;
popad;
ret;
}
}
```
Some fun things to note:
* Generating a random number takes just 3 bytes of machine code (`rdrand` instruction)
* By a coincidence, the size of the table is 64, so the size of one row is 256 bytes. I use this to hold row indices in "high-byte" registers like `ah`, which gives me automatic multiplication by 256. To take advantage of this, I sacrificed the support for `n = 65`. I hope I can be excused for this sin...
* Allocating space on stack is performed by subtracting 0x4100 from the stack pointer register `esp`. This is a 6-byte instruction! When adding this number back, I managed to do it in 5 bytes:
```
dec edx; // here edx = 1 from earlier calculations
mov dh, (MAX_M + 1) * MAX_M * 4 / 256; // now edx = 0x4100
add esp, edx; // this deallocates space on stack
```
* When debugging this function in MS Visual Studio, I found out that it crashes when it writes data to the space that it allocated on stack! After some digging around, I discovered some sort of stack overrun protection: OS seems to allocate only a very limited range of virtual addresses for stack; if a function accesses an address too far away, OS assumes it's an overrun and kills the program. However, if a function has many local variables, OS does some extra "magic" to make it work. So I have to call an empty function that has a large array allocated on stack. After this function returns, extra stack VM pages are allocated and can be used.
```
void make_stack()
{
volatile int temp[65 * 64];
temp[0] = 999; // have to "use" the array to prevent optimizing it out
}
```
] |
[Question]
[
## Background
A [magic square](https://en.wikipedia.org/wiki/Magic_square) is an `n×n` matrix consisting of one of each of the integers from \$1\$ to \$n^2\$ where every row, column, and diagonal sum to the same value. For example, a 3×3 magic square is as follows:
```
4 9 2
3 5 7
8 1 6
```
Here, each row, column, and diagonal sum to the magic sum of 15, which can be calculated with the following formula:
$$
n × \frac{n^2 + 1}{2}
$$
Even if you didn't have the full `n×n` magic square, you could reproduce it without guessing. For example, given just the 4, 9, 2, and 3 of the prior magic square, you could fill
```
4 9 2 4 9 2 4 9 2 4 9 2 4 9 2 4 9 2
3 _ _ => 3 _ _ => 3 5 _ => 3 5 7 => 3 5 7 => 3 5 7
_ _ _ 8 _ _ 8 _ _ 8 _ _ 8 1 _ 8 1 6
```
## Task
Given a partially-filled magic square, your program or function should output the full magic square.
The input is guaranteed to be part of of a magic square, such that the only deduction necessary to solve it is taking a row, column, or diagonal in which `n-1` values are determined and filling in the final entry (**without** this rule, `4 9 _ / _ _ _ / _ _ _` would be a valid input since only one magic square starts `4 9`, but that would require a more complicated approach or a brute-force of all possibilities).
Input and output may be any reasonable format for a square matrix (`n`×`n` matrix datatype; string representations; length-`n×n` flat array; etc.). In all formats, you may optionally take `n` as another input.
You may use any character or value other than `_` in the input to represent blanks as long as that value is unmistakable for a possible entry.
Related [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") variant: [Is Magic Possible?](https://codegolf.stackexchange.com/questions/119245/is-magic-possible)
## Sample Testcases
(one newline between input and output; three between cases)
```
4 9 2
3 5 7
8 1 6
4 9 2
3 5 7
8 1 6
4 9 2
3 _ _
_ _ _
4 9 2
3 5 7
8 1 6
4 9 _
_ 5 _
_ _ _
4 9 2
3 5 7
8 1 6
_ _ _
_ 5 7
_ 1 6
4 9 2
3 5 7
8 1 6
_ 16 13 _
11 5 _ _
7 9 12 6
_ _ _ 15
2 16 13 3
11 5 8 10
7 9 12 6
14 4 1 15
1 23 _ 4 21
15 14 _ 18 11
_ _ _ _ _
20 8 _ 12 6
5 3 _ 22 25
1 23 16 4 21
15 14 7 18 11
24 17 13 9 2
20 8 19 12 6
5 3 10 22 25
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 36 bytes
```
`nZ@[]etGg)GXz-yt!hs&ytXdwPXdhsh&-ha
```
The input is an \$ n \times n\$ matrix, with \$0\$ for the unknown numbers.
The code keeps generating random \$ n \times n\$ matrices formed by the numbers \$1, \dots, n^2\$ until one such matrix meets the required conditions. This procedure is guaranteed to finish with probability one.
This is a terrible approach, in that:
* running time is random, and unbounded;
* average running time increases as \$(n^2)!\$ (that's [more than exponentially](https://matl.suever.net/?code=%3A%21tUQYgh&inputs=10&version=22.2.1));
* and so it very likely times out in the online interpreter.
... but hey, it's the shortest answer so far!
[(Don't) try it online](https://tio.run/##y00syfn/PyEvyiE6NrXEPV3TPaJKt7JEMaNYrbIkIqU8ICIlozhDTTcj8f//aBMFSwUjawVjBQMFA2sQoWAQCwA).
See below a sped-up animated GIF of an example run which happened to take about 2 minutes, here compressed to a few seconds.
[](https://i.stack.imgur.com/naLQ4.gif)
## Explanation
```
` % Do...while
n % Number of elements. This implictly takes the input in the first
% iteration, or uses the candidate solution from the previous iteration.
% Let this number be denoted as N
Z@ % Random permutation of integers 1, 2, ..., N
[]e % Reshape as a square matrix. This yields a candidate solution
t % Duplicate
Gg) % Push input, convert to logical, index: this produces a column vector
% of the entries of the candidate solution that correspond to nonzero
% entries in the input matrix
GXz % Push input, take its nonzero elements. Gives a column vector
- % Element-wise difference (*). This will be all zeros for a valid
% solution
y % Duplicate second-top object from the stack, that is, the candidate
% solution
t! % Duplicate, transpose
h % Concatenate horizontally
s % Sum of columns. This also gives the sum of rows, thanks to the
% concatenated, transposed copy. The result is a two-element row
% vector (**)
&y % Duplicate third-top object from the stack: the candidate solution
tXd % Duplicate, extract diagonal as a column vector
wPXd % Swap, flip vertically, extract diagonal. This gives the anti-diagonal
% as a column vector
h % Concatenate horizontally
s % Sum of each column. This gives the sum of the diagonal and that
% of the anti-diagonal
h % Concatenate horizontally with (**)
&- % Matrix of all element-wise differences. This will be a matrix of
% zeros for a valid solution (***)
h % Concatenate (*) and (***) horizontally. Since sizes do not match,
% both (*) and (***) are first linearized to row vectors, and the
% result is a row vector
a % Any. This gives true if any element is non-zero
% End (implicit). A new iteration is run if the top of the stack is true
% Display (implicit). The candidate solution from the last iteration is
% the valid solution
```
[Answer]
# JavaScript, ~~559~~ 551 bytes
Fast and methodical.
```
B=Boolean,f=((e,r)=>(v=r*((r**2+1)/2),e.forEach(e=>e.filter(B).length==r-1?e[e.findIndex(e=>!e)]=v-e.reduce((e,f)=>!(e+=f)||e):0),e[0].reduce((f,l,n)=>!(f[0].push(e[n][n])+f[1].push(e[n][r-1-n]))||f,[[],[]]).forEach((f,l)=>{f.filter(B).length==r-1&&(z=f.findIndex(e=>!e),e[z][l?r-1-z:z]=v-f.reduce((e,f)=>!(e+=f)||e))}),e[0].reduce((f,r,l)=>f.forEach((f,r)=>f.push(e[l][r]))||f,new Array(r).fill().map(()=>[])).forEach((f,l)=>f.filter(B).length==r-1?e[f.findIndex(e=>!e)][l]=v-f.reduce((e,f)=>!(e+=f)||e):0),e.flat(2).filter(B).length==r*r?e:f(e,r)));
```
Live examples:
```
B=Boolean,f=((e,r)=>(v=r*((r**2+1)/2),e.forEach(e=>e.filter(B).length==r-1?e[e.findIndex(e=>!e)]=v-e.reduce((e,f)=>!(e+=f)||e):0),e[0].reduce((f,l,n)=>!(f[0].push(e[n][n])+f[1].push(e[n][r-1-n]))||f,[[],[]]).forEach((f,l)=>{f.filter(B).length==r-1&&(z=f.findIndex(e=>!e),e[z][l?r-1-z:z]=v-f.reduce((e,f)=>!(e+=f)||e))}),e[0].reduce((f,r,l)=>f.forEach((f,r)=>f.push(e[l][r]))||f,new Array(r).fill().map(()=>[])).forEach((f,l)=>f.filter(B).length==r-1?e[f.findIndex(e=>!e)][l]=v-f.reduce((e,f)=>!(e+=f)||e):0),e.flat(2).filter(B).length==r*r?e:f(e,r)));
console.log(JSON.stringify(f([
[4, 9, 2],
[0, 5, 0],
[0, 0, 0]
], 3)));
console.log(JSON.stringify(f([
[1, 23, 0, 4, 21],
[15, 14, 0, 18, 11],
[0, 0, 0, 0, 0],
[20, 8, 0, 12, 6],
[5, 3, 0, 22, 25]
], 5)));
```
The "un"-golfed version can be seen at [this](https://github.com/GirkovArpa/magic-square-solver/blob/master/main.js) Github repository.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 60 [bytes](https://github.com/abrudz/SBCS)
```
{(⍵,m+.×1+⍺*2)⌹(∘.(×⊢×=)⍨⍵)⍪2×m←(⍪↑c(⌽c))⍪(⊢⍪⍴⍴⍉)⍺/c←∘.=⍨⍳⍺}
```
[Try it online!](https://tio.run/##zZQ/T8JAGMZ3PsU7XqVi79oDHJhcdBW/QMWgA0WjC8booIZIpUQGgzMJCXFxEAZJXOCb3BfB994WEuKf4p8gae56d33e5/fctal7VFrdO3VLh/vjs9LBiareqeBRVZsVpuqvFT29eUjlVNBVwbMKBobJVFAbdk3ltw0WraFy2FX@JY4Bmwp6uq82ubq91p7aEG37E6tyOL2w8PkxMcsmLjMxamFhkhuRg99xcJSSMBHWX9DuPPEvQVlcRmMaD6UxOvYRxND8v9uTDoK@8VGQwVDit0etnEGw/oKiJLGt2F@moIolCcJMNC7oCTPp5mLbxUjo2XNDq5pLr3OwVngX9Zfw8BgKjDIsFz1kG4uDM5TRJ/oNtKq1vfmxHhrNh/4EOw6xXjI1anECirh9euFx/hRYpDNoKP9q@GSjh2rc57c3sN/Z3MqPbSiCA@sgAGyw8KLOSsysS8gAZIFDerpOQjmrtyYGpLdI74D@q2CJfszTwDUFOKdaHGXQiwtIRz7AZUKC1CUSSzgIrXdAcCySwB0tyer6SE8mwsJ0VuQjaSNCgJBv "APL (Dyalog Unicode) – Try It Online")
Not likely the shortest approach, but anyway here is one with Matrix Divide `⌹`, a.k.a. Solve Linear Equation. This works because all the cells are uniquely determined by the horizontal/vertical/diagonal sums when joined with the givens. `⌹` has no problem with over-determined systems, as long as there is a solution (otherwise, it finds the least-squares fit).
A dyadic inline function (dfn) where the left argument is the side length and the right argument is the flattened matrix.
In the case of `[4 9 2][3 0 0][0 0 0]`, the coefficient matrix and constant vector are given as follows:
```
Coefficients Constants
-------------------------------
Part 1: Givens
1 0 0 0 0 0 0 0 0 4
0 1 0 0 0 0 0 0 0 9
0 0 1 0 0 0 0 0 0 2
0 0 0 1 0 0 0 0 0 3
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 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
Part 2: Magic Square sums
2 0 0 0 2 0 0 0 2 30 # diagonals
0 0 2 0 2 0 2 0 0 30
2 2 2 0 0 0 0 0 0 30 # rows
0 0 0 2 2 2 0 0 0 30
0 0 0 0 0 0 2 2 2 30
2 0 0 2 0 0 2 0 0 30 # columns
0 2 0 0 2 0 0 2 0 30
0 0 2 0 0 2 0 0 2 30
```
which is a set of 17 equations for 9 unknowns.
```
{(⍵,m+.×1+⍺*2)⌹(∘.(×⊢×=)⍨⍵)⍪2×m←(⍪↑c(⌽c))⍪(⊢⍪⍴⍴⍉)⍺/c←∘.=⍨⍳⍺}
m←(⍪↑c(⌽c))⍪(⊢⍪⍴⍴⍉)⍺/c←∘.=⍨⍳⍺ ⍝ Construct the sums part of the coef matrix
c←∘.=⍨⍳⍺ ⍝ ⍺ × ⍺ identity matrix
⍺/ ⍝ ⍺ copies of each horizontally, giving the "rows" part
( ⍴⍴⍉) ⍝ Reshape the transpose of above into the original,
⍝ giving the "columns" part
⊢⍪ ⍝ Vertically concatenate two parts
m←(⍪↑c(⌽c))⍪ ⍝ Generate the "diagonals" part and vertically prepend to above
(∘.(×⊢×=)⍨⍵)⍪2×m ⍝ Construct the entire coef matrix
2×m ⍝ Use twos so that we can avoid halving the constant
( )⍪ ⍝ Vertically concatenate with...
∘.(×⊢×=)⍨⍵ ⍝ The square diagonal matrix where nonzero entries of ⍵ give
⍝ a 1 at the corresponding position, 0 otherwise
(⍵,m+.×1+⍺*2) ⍝ Construct the constant vector
1+⍺*2 ⍝ Square of ⍺ plus 1
m+.× ⍝ Matmul with m, which has ⍺ ones on each row,
⍝ giving (# of rows of m) copies of ⍺ times above
⍵, ⍝ Prepend ⍵ to above
⌹ ⍝ Solve the linear system of equations; no postprocessing necessary
```
[Answer]
# JavaScript (ES7), ~~143 142~~ 140 bytes
Expects `(n)(m)`, where unknown cells in `m` are filled with 0's.
```
n=>g=m=>[0,1,2,3].some(d=>m.some((r,i)=>m.map((R,j)=>t^(t-=(v=d?R:r)[x=[j,i,j,n+~j][d]])||(e--,X=x,V=v),e=1,t=n**3+n>>1)&&!e))?g(m,V[X]=t):m
```
[Try it online!](https://tio.run/##lVDNisIwEL77FNmLJDoVJ62/MPUdPIgQslBslRbbSi3iQfbVu0m1WncVdi9DPr6/mSTBKThuivhQOlkeRtWWqoz8HaXkqyEgSHD14JinEQ/JT68vXkAsLEqDA@dLSAwoP3npED9RuFjOC6HOpBKIIYGs/5VoFWotLhceOQ6s6QwrOgmICKGkrNdz@5nvo@h2PyIhFjuewkqtNZVinlabPDvm@2iwz3d8y1Fw1WFMsSHTHS1E55mWDY1gFXCVwhu126g9YDNgsjG4cPM8/H@MaHtG/40Y/qo1EZMWNEeNX0Z4rQjGcGwmmiNMVuNG47Vx7Cp5EBMLZ7VNmjlmrT7WGjh62TxqfThjsi61L6@GeK@31eg1LE4txDdVPzaUFk8fizyvWd/k3llpWXnbtfoG "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // outer function taking n
g = m => // inner function taking the matrix m[]
[0, 1, 2, 3] // list of directions
.some(d => // for each direction d:
m.some((r, i) => // for each row r[] at position i in m[]:
m.map((R, j) => // for each row R[] at position j in m[]:
t ^ ( // test whether t is modified:
t -= // subtract from t:
(v = d ? R : r) // use v = r[] if d = 0 or v = R[] otherwise
[x = // use:
[ j, // r[j] if d = 0 (rows)
i, // R[i] if d = 1 (columns)
j, // R[j] if d = 2 (diagonal)
n + ~j // R[n - 1 - j] if d = 3 (anti-diagonal)
][d] //
] //
) || ( // if t was not modified:
e--, // decrement e
X = x, // copy x to X
V = v // copy v to V
), //
e = 1, // start with e = 1
t = n**3 + n >> 1 // start with t = n(n²+1)/2
) // end of map()
&& !e // e = 0 means that there's exactly one cell set
// to zero in this vector
) // end of inner some()
) ? // end of outer some(); if truthy:
g(m, V[X] = t) // update V[X] to t and do a recursive call
: // else:
m // done: return m[]
```
[Answer]
# [R](https://www.r-project.org/), ~~169~~ ~~180~~ ~~142~~ 135 bytes
*Edits: +11 bytes to rotate the magic square back to it's original orientation, -38 bytes by wrapping "replace-only-missing-element" into a function, -7 bytes by various golf obfuscations*
```
function(m,n){while(F%%4|sum(!m)){m[n:1,]=apply(m,1,f<-function(v){if(sum(!v)<2)v[!v]=(n^3+n)/2-sum(v);v})
m[d]=f(m[d<-!0:n])
F=F+1}
m}
```
[Try it online!](https://tio.run/##nZDBboMwDIbvfgo4VIrVoJEAbdeRK0@wG2JSx4qGREJF23QV67MzQ7aqWk@bFCu2Yn//73TDvm3sVg3V0ZSHujVMc4P96b1utiybzeLP/VEzXyP2OjdrwQu12e2aM7UJXqXBdcxiX1dsaraYSrS5bwvFzEs0N/ggg/HF4pO9IOj8rVAVoysN/HBtCoRMZXNxAX0ZtNKbQ1d/sJJBzL1H7kkOEffC8UDoEuRgyrZREX89d@1JPSNMa5CrCAHuGW40@ScjvJEnxnJKBPcWf2OIBcW0Cgjx7WYslpNFIQl4dUd18kOP7@nxLzrhpPsk2lcKEiC6iB1oRSFuyE5V0rVyDU6ZJhxCUi2v6sm9eoIwDF8 "R – Try It Online")
Solves rows & the first diagonal, then rotates the matrix anticlockwise (so cols become rows in the opposite order) and repeats, until there are no empty elements left.
~~Outputs the completed magic-square matrix in one of 4 possible rotated forms.~~ Then rotates matrix back to its original orientation.
Commented readable version:
```
solve=function(m,n){
t=(n^3+n)/2 # t = desired total of each row/col/diag
f=function(v){ # f = function to check if a vector
if(sum(!v)==1)v[!v]=t-sum(v);v # has only 1 missing element, and if so
} # fill it with t-sum(elements).
while(F%%4|sum(!m)){ # While rotations are not multiple-of-4, or
# there are still some empty elements of m:
m[n:1,]= # rotate the matrix anticlockwise, while
apply(m,1,f) # using f() to fix any rows; then
d=1:(n+1)==1 # define diagonal as every (n+1)th element,
m[d]=f(m[d]) # and use f() to fix diagonal.
F=F+1 # Count rotations so far,
} # and repeat.
m # Finally, output m.
}
```
# or awfully-slow [R](https://www.r-project.org/), ~~124~~ ~~123~~ ~~109~~ 105 bytes
*Edit: -14 bytes thanks to Xi'an*
```
function(m,n){x=m;`?`=rowSums;while(any(sum(x[0:n<1])!=c(sum(diag(x)),?x,?t(x))))x[!m]=sample(n^2)[-m];x}
```
[Try it online!](https://tio.run/##JY5RC4IwFEbf9yv0bRduYNpL2fBH1JsYrmU18G7hNCfRb19q8D0cPjhwuuBs@25EuA9G9doaTmjg4wXldVGLzo6ngVw@PnXbcGkm7gbivkwO5ritIBZqPW5aPrgHwMJj0S8E4MuYKuEkvWbTXFIoN1Tl/htIkOw77bnibIfRHqMUWYZRsowlfwBkRtlWZHid5ghxBraGznkZsBB@ "R – Try It Online")
Generates random permutations of the missing elements until it finds one where all row, column and diagonal sums are all equal.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 47 44 bytes
```
{0∧|}ᵐ²{l⟦₅gj↔ʰc;?z∋₍ᵐġ,?;?\ᵗc+ᵐ=&c≠≤ᵛ√~l?≜}
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v9rgUcfymtqHWycc2lSd82j@skdNrelZj9qmnNqQbG1f9aij@1FTL1D2yEIde2v7mIdbpydrA7m2asmPOhc86lzycOvsRx2z6nLsH3XOqf3/PzraUMfIWMdAx0THyDBWJ9rQVMfQBMg1tNAxBPENdKAQyDYy0LEASRnpmAF5pjogbUZGOkamsbH/owA "Brachylog – Try It Online")
### How it works
In classic Prolog style we replace zeros with uninitiated variables and based on the constraints let Brachylog figure out a solution. In Prolog you could just write `[1,_,_]` for unknown variables, in Brachylog you would have to write `[1,A,B]` and that seems too far away from the usual I/O restriction. So we use 0 for unknowns and convert them to uninitiated variables by:
```
{∧0|}ᵐ²
```
If a value is 0 try something else, otherwise use the value itself.
```
l⟦₅gj↔ʰc;?z∋₍ᵐ
l length of array, N
⟦₅ 0…N-1
gj [0…N-1],[0…N-1]
↔ʰc 0…N-1,N-1…0
;?z [[0,first row], …, [N-1,last row],
[N-1,first row], …, [0,last row]]
∋₍ᵐġ [diagonal \, diagonal /]
```
This feels a bit long just to get the two diagonals. Basically calculate the indices, zip them with the rows, and get the elements.
```
,?;?\ᵗc
```
Append all rows and all transposed rows.
```
+ᵐ=
```
Sum every row. All sums (f.e. 15 in the 3x3 case) must be equal to each other. We don't have to calculate 15 explicitly, as this follows from the next constraint:
```
&c≠≤ᵛ√~l?
c the rows concatenated
≠ all elements are different
≤ᵛ and are less-equal than X,
√ and the root of X is
~l? the length of the input
which is implicitly the output
```
The numbers are distinct and between 1 and N^2.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 100 bytes
```
#/.Solve[Tr/@Flatten[{#,Thread@#,{(d=Diagonal)@#,d@Reverse@#}},1]==Table[(l^3+l)/2,2(l=Tr[1^#])+2]]&
```
[Try it online!](https://tio.run/##fZBNa8MwDIbv@xUBQ0mpWCbns4eAD2PnseVmXPAWkwbcFLJQAsa/PbPVscMOO1jWK0vPi3zRy9lc9DJ@6m1oN5Y9vl/tzchuzsSL1ctiJukYdOfZ6F4wcGnfPo96uE7a7oPuxZu5mfnLCOY9oGrbTn9YI1N7yg92n3HgqW27WeKJqf2BK7XbXudxWjLBdpkYpHOrRAXJKjnFXHlIQq0IqoSkvqsyKISk8l490Lj8uf9isAonv@PiKCJhIjfGgoo1JMfQxiPwF7/KimIdKeU/Rgg8B3IrgKMHhyVgAbQANoCxRH60BMGJHdHhiT9BE/ImNHMI/q6EiDsq4OGzovG2fQM "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 43 41 30 bytes
*-2 bytes by replacing `Dgt` with `¹` to get first input back*
*-11 bytes thanks to Kevin Cruijssen!*
```
nLœʒ¹ôD©ø®Å\®Å/)O˜Ë}ʒøε¬_sË~}P
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/z@fo5FOTDu08vMXl0MrDOw6tO9waAyL0Nf1PzzncXXtq0uEd57YeWhNffLi7rjbg/39jrmgDHQg01TEHkoY6ZrEA "05AB1E – Try It Online")
Takes input as (n, flattened square), where zeros represent blanks, like
```
3
[4,9,2,3,0,0,0,0,0]
```
Works by generating all permutations of the numbers from 1 to n2, filtering to only keep those that are magic squares, and then iterating through and printing all that match the partial input (by input constraints, there will always only be one match). Because of this brute-force approach, it's already very slow for 3x3 magic squares and I doubt 5x5 would terminate. This is my first 05AB1E answer, so I'm sure there's savings to be had here.
The magic square checking is [borrowed from Kevin Cruijssen](https://codegolf.stackexchange.com/a/178959/81278).
**Explanation:**
```
n # Square input (implicit) (3 → 9)
L # Generate list from 1 to n^2 ([1,2,...,9])
œ # All permutations
ʒ # Filter by:
¹ # Recover n by pushing first input again
# Check if magic square, borrowed from Kevin Cruijssen
ô # Split permutation into parts of size n
D # Duplicate
© # Store in register (without popping)
ø # Zip rows to get columns
® # Push from register
Å\ # Take main diagonal
® # Push from register
Å/ # Take anti diagonal
) # Flatten stack into one list
O # Take sum (of each row/column/diagonal)
Ë # Check if all values are equal
} # End filter (to get magic squares)
ʒ # Filter magic squares by:
ø # Zip together magic square and input (implicit)
ε # Map
¬ # Push the input again
_ # Input equals 0 (to produce mask)
s # Manage stack (swap mask and zipped args)
Ë # Partial equals potential match
~ # Bitwise OR to combine masks
} # End map
P # Take product (effectively logical AND) to verify
# that combined mask is all 1s
# Implicit output
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ZṚ,⁸;Jị"$€$§FE
²Œ!ṁ€ÇƇ=ÐṀ
```
A full program taking `n` and a list-of-lists-formatted representation of the incomplete square which prints the result in the same format.
[Try it online!](https://tio.run/##y0rNyan8/z/q4c5ZOo8ad1h7PdzdraTyqGmNyqHlbq5chzYdnaT4cGcjUOBw@7F228MTHu5s@P//v/H/6GgjHQMdg1idaAMdUx1jMA3ixwIA "Jelly – Try It Online") - too slow for TIO's 60s limit
...so, **[Try a limited space](https://tio.run/##y0rNyan8/z/q4c5ZOo8ad1h7PdzdraTyqGmNyqHlbq5chzYdnaT4cMdiQ1ODE9sf7mwEShxuP9Zue3jCw50N////N/4fHW2kY6BjEKsTbaBjqmMMpkH8WAA "Jelly – Try It Online")** one which only considers the first 150K permutations - three magic squares two of which match at two and three locations.
### How?
Unfortunately, even with the ability to deduce the missing numbers one at a time, I believe brute-forcing will be terser, so that is how this works.
```
ZṚ,⁸;Jị"$€$§FE - Link 1, Is this a magic-square?: list of lists, M
Z - transpose (M)
Ṛ - reverse (together ZṚ rotate 1/4)
,⁸ - pair with chain's left argument (M)
$ - last two links as a monad:
€ - for each (m in (MZṚ, M)):
$ - last two links as a monad:
J - range of length = [1..n]
" - zip with:
ị - index into - i.e. get the leading diagonal
; - concatenate (m with it's diagonal)
§ - sums
F - flatten
E - all equal?
²Œ!ṁ€ÇƇ=ÐṀ - Main Link: integer, N; list of lists, P
² - square (n)
Œ! - all permutations of (implicit range [1..n²])
ṁ€ - mould each like (P)
Ƈ - filter keep those for which:
Ç - call the last Link as a monad - i.e. keep magic squares
ÐṀ - keep those which are maximal under:
= - equals (P) (vectorises) - i.e. keep the one which matches at all givens
- implicit print, which when given a list containing only one item prints that item
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 81 bytes
```
FθFι⊞υκUMθκ≔LθηFυF⁺⁺⪪EυληEθ⁺λ×θη⟦×θ⊕η×⊕θ⊖η⟧«≔Eκ§υλι¿⁼¹№ι⁰§≔υ§κ⌕ι⁰⁻÷×⊕×ηηη²Σι»I⪪υη
```
[Try it online!](https://tio.run/##ZVDLasMwEDzHX7FHCVSwU5JScgpOC4EWDOnN@CBsJRKR5diSQqH0292V5ZaUCPTY2Z3d0dSSD3XH9TgeuwFIT2G6FYXCW0k8gzPdJO/8kndty01D@ohsrVUnQ96EOTmJNAYS0Ynr5x6F9jYeh4tWjmCT0E9PtQxCiM2mAs3gQ7XCBkBSXAzKP2Bv6kG0wjjREBlSMXMLh/k78a@sohS@ksWsMww7M9i6vWnEZ5SBHIWaF@oI5KX3XFuSMcg7bxxRDFKUAZF@Q/t9YrNXhXbEQvyNMj5ocjt1VY0g9xojIqcPRgeWuA@@RbMp6vhOikHh6JxbNzvmoxubcSzLMmWQrXE/4sQK/clQ7Arfc/jE4BmzSwbrEKYxg8iqqqrx4ap/AA "Charcoal – Try It Online") Link is to verbose version of code. Uses zero as the "blank" marker. Explanation:
```
FθFι⊞υκ
```
Flatten the input array.
```
UMθκ
```
Replace the original array with a range from `0` to `n-1`.
```
≔Lθη
```
Also the length of the array is used a lot so capture it in a temporary to save 3 bytes.
```
Fυ
```
Loop `n²` times, which is more than enough to track down all the solvable `0`s.
```
F⁺⁺
```
Loop over all of the following ranges:
```
⪪Eυλη
```
the range from `0` to `n²-1`, split into subranges of length `n`;
```
Eθ⁺λ×θη
```
the subranges obtained from the range from `0` to `n²-1`, but taking every `n`th element (so effectively the transpose of the above);
```
⟦×θ⊕η×⊕θ⊖η⟧«
```
the range from `0` to `n²-1` in steps of `n+1`, which is the main diagonal, and the range from `n-1` to `n²-n` in steps of `n-1`, which is the main antidiagonal.
```
≔Eκ§υλι
```
Get the values in the flattened array corresponding to the elements of the current range.
```
¿⁼¹№ι⁰
```
Count whether exactly one of them is zero.
```
§≔υ§κ⌕ι⁰
```
If so then overwrite that entry in the flattened array...
```
⁻÷×⊕×ηηη²Σι
```
... with `½n(n²+1)` minus the sum of the (other) elements.
```
»I⪪υη
```
Split the flattened array back into rows and convert the values to strings for implicit print.
] |
[Question]
[
## The sequence
Given an integer \$n>0\$, we define \$a(n)\$ as the lowest positive integer such that there exists exactly \$n\$ positive integers smaller than \$a(n)\$ whose sum of digits is equal to the sum of the digits of \$a(n)\$.
*Edit: this sequence has since been published as [A332046](https://oeis.org/A332046)*
## First terms
```
n | a(n) | sum of digits | matching integers
----+------+---------------+------------------------------------------------------
1 | 10 | 1 | [1]
2 | 20 | 2 | [2, 11]
3 | 30 | 3 | [3, 12, 21]
4 | 40 | 4 | [4, 13, 22, 31]
5 | 50 | 5 | [5, 14, 23, 32, 41]
6 | 60 | 6 | [6, 15, 24, 33, 42, 51]
7 | 70 | 7 | [7, 16, 25, 34, 43, 52, 61]
8 | 80 | 8 | [8, 17, 26, 35, 44, 53, 62, 71]
9 | 90 | 9 | [9, 18, 27, 36, 45, 54, 63, 72, 81]
10 | 108 | 9 | [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
.. | .. | .. | ..
20 | 216 | 9 | [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, ..., 207]
.. | .. | .. | ..
30 | 325 | 10 | [19, 28, 37, 46, 55, 64, 73, 82, 91, 109, ..., 316]
.. | .. | .. | ..
40 | 442 | 10 | [19, 28, 37, 46, 55, 64, 73, 82, 91, 109, ..., 433]
.. | .. | .. | ..
50 | 560 | 11 | [29, 38, 47, 56, 65, 74, 83, 92, 119, 128, ..., 551]
```
## More examples
```
a(13) = 135
a(17) = 171
a(42) = 460
a(57) = 660
a(81) = 1093
a(82) = 1128
a(118) = 1507
a(669) = 9900
a(670) = 10089
a(1000) = 14552
a(5000) = 80292
a(10000) = 162085
```
As a side note, you may not assume that the sum of the digits may only increase. For instance, the sum of the digits for \$a(81)\$ is \$1+0+9+3=13\$, while the sum of the digits for \$a(82)\$ is \$1+1+2+8=12\$.
## Rules
* You may either:
+ take a 1-indexed integer \$n\$ and return \$a(n)\$
+ take a 0-indexed integer \$n\$ and return \$a(n+1)\$
+ take a positive integer \$n\$ and return the \$n\$ first terms
+ print the sequence indefinitely
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
f}hQ_XsjT;H1
```
[Try it online!](https://tio.run/##K6gsyfj/P602IzA@ojgrxNrD8P9/IwMA "Pyth – Try It Online")
* `f`: Count up from 1 to find the first number such that:
* `X ... H1`: Increment or insert the value 1 into the dictionary H at index
* `sjT;`: sum of base ten digits of current number
* `_`: values of dictionary
* `}hQ`: check whether input + 1 is contained within.
The first time this is true, exactly input numbers must have the same digit sum as the current number, for the first time.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~13~~ 10 bytes
```
1⟨┅Σ¦ṅC=⟩#
```
[Try it online!](https://tio.run/##S0/MTPz/3/DR/BWPprSeW3xo2cOdrc62j@avVAaKGgMA "Gaia – Try It Online")
Straightforward implementation.
## Explanation:
```
1⟨ ⟩# | find the first 1 positive integers N where:
C | the count of
ṅ | the digital sum d(N)
┅Σ¦ | in the list [d(1)..d(N-1)]
= | is equal to the (implicit) input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
D€§ċṪ$=ʋ1#
```
[Try it online!](https://tio.run/##y0rNyan8/9/lUdOaQ8uPdD/cuUrF9lS3ofJ/60cNcxR07RQeNcy1PtzOZWxwuB2oJvI/AA "Jelly – Try It Online")
A monadic link taking an integer \$n\$ and returning \$a(n)\$.
## Explanation
```
ʋ1# | Find the first integer x where the following is true;
D€ | - Digits of 1..x
§ | - Sum each
ċṪ$ | - Count the number equal to the tail (after popping tail)
= | - Equal to (implicit original argument to link)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
∞.Δ1Ÿ1öć¢Q
```
[Try it online!](https://tio.run/##AR0A4v9vc2FiaWX//@KIni7OlDHFuDHDtsSHwqJR//8xMw "05AB1E – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 bytesSBCS
```
{⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵}⍳+∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRT8ejnv3aMY86ZujZPupdYfioa6mhAZB41Lv40HrDR72bjQwOT3/Uu7UWyNQGqjL8n/aobcKj3r5HfVM9/R91NR9ab/yobSKQFxzkDCRDPDyD/6cdWqGgAdRgaKCpY2SgYGygYGKgYGqgYGGoYGEEAA "APL (Dyalog Unicode) – Try It Online")
### How it works
```
{⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵}⍳+∘1 ⍝ Right argument: n
{ }⍳+∘1 ⍝ Find the first index of n+1 from...
⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵ ⍝ ... the list of cumulative count of own digit sum (sort of)
20×⍵ ⍝ Practical upper bound 20×n (could also use theoretical 10*⍵)
⍳ ⍝ Range: 1..20×n
10⊥⍣¯1 ⍝ Extract decimal digits from each
1⊥ ⍝ Sum the digits of each number
∘.=⍨ ⍝ Self outer product by equality
+\ ⍝ Cumulative sum in row direction; cumulative counts of own digit sum
⌈⌿ ⍝ Maximum in column direction; cumulative maximum of cumulative count
```
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
f=lambda n,x=[0]:x.count(x[-1])+~n and-~f(n,x+[sum(map(int,`len(x)`))])
```
[Try it online!](https://tio.run/##DcpNCoMwEAbQfU/xbcQZjMWfnWAvIgHTxrQBnYhVSDdePfWt3/rbP0GalFw/m@VpDUTFfqh0F@@vcMhOcShrzcUpMGLL09EViuF7LLSYlbzsapwnocgjs@bkwgYPL9iMvCeqFdqKuxuwbtdFnjUW5QNZa3NkIK/gyDOnPw "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
W⁻№υΣLυθ⊞υΣLυILυ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDNzOvtFjDOb80r0SjVEchuDRXwyc1L70kQ6NUU1NTR6FQU1MhoLQ4A4ukNVdAUSZQm3NicQmK@P//Fob/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W⁻№υΣLυθ
```
Count the number of entries in the predefined list that are equal to the digital sum of the length of the list and repeat while that does not equal the input...
```
⊞υΣLυ
```
... append the digital sum of the length of the list to the list.
```
ILυ
```
Output the length of the list.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
->n,r=0,*w{w<<k=(r+=1).digits.sum until w.count(k)>n;r}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp8jWQEervLrcxibbVqNI29ZQUy8lMz2zpFivuDRXoTSvJDNHoVwvOR/I0sjWtMuzLqr9X6CQFm0YywWijCCUMZQygNCmUNrQwMAg9j8A "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~68~~ ~~67~~ 63 bytes
~~-1~~ -5 byte thanks Arnauld
```
n=>(F=z=>F[g=eval([...z+''].join`+`)]^n?F(-~z,F[g]=-~F[g]):z)``
```
[Try it online!](https://tio.run/##FcqxDoMgFEDR3a94m4@gxA5dap/d@AlDA7FiMASMNgwM/jq107nDXU0yx7S77duG@JmLpRJoQEmZBjkuNCfjcRRCZF7XSqzRBc01U@/wktieubkmRe35hz0y07r0lY07YDI7OCC49RdPgnvXXcU5q2CK4Yh@Fj4u6Bqw6Bjryw8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 92 93 bytes
```
f=lambda n,x=1:n==sum(sum(map(int,`i`))==sum(map(int,`x`))for i in range(x))and x or f(n,x+1)
```
[Try it online!](https://tio.run/##XY5BCsIwEEX3nmKomxkSxequkJ7ERaJtNGKnJbaQnj6OtAi6mFk8/n/8YR7vPR9z9ubpukvjgHUyZcXGvKYOP9e5AQOP2gZLtOAvSoJ8HyFAYIiOby0mIscNJBDsUWyqpDxEiUNx5mL/6AOjuEBBAbtangLrMZCFP1OpTweizXYpx7aZri2uK5Oeq98lapYtem1KL78B "Python 2 – Try It Online\"Online")
All I can get for now but I suspect someone much more competent than I am could do much better.
[Answer]
# Java 8, 138 bytes
```
n->{for(int a=9,c,i;;a++){for(c=i=0;++i<a;)c+=(i+"").chars().map(q->q-48).sum()==(a+"").chars().map(q->q-48).sum()?1:0;if(c==n)return a;}}
```
[Try it online.](https://tio.run/##hZFBbsIwEEX3nGKUlS2TKEFUpTWmJygbllUXU5O0QxMn2A5ShXL21AmpBGLRzVj/ezR@f3zAE8aH/XevS3QOXpHMeQZAxue2QJ3DdpCjAZoN1XAZnG4WivPoScMWDKjexJtzUduxB9XTXM9JShSCj65WpFIpBK1Rci0UIxFFPNFfaB3jSYUNO8abY7xc8cS1FeNKMfyn5SV7TiUVYbYy3Oa@tQZQdl0vB7im/SgD3MR4qmkPVUjHdt6S@Xx7B@SXaH/QpDIJtFaLNByBe7wE8LnzjMbQk1gurtXD47VaZTfqpjPLVne7G7kuTwwIE9Lux/m8SurWJ02g9aVhEbJIhKVxUBAJk4TP4NO0rv8F)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
for(int a=9, // Integer `a_i`, starting at 9 (since a(1)=10)
c, // Count-integer
i; // Loop-integer
; // Loop indefinitely:
a++){ // After every iteration: increase `a_i` by 1
for(c=i=0; // Reset both the count and loop integers to 0
++i<a;) // Inner loop `i` in the range (0,a):
c+= // Increase the count by:
(i+"").chars().map(q->q-48).sum()
// If the digit-sum of `i`
==(a+"").chars().map(q->q-48).sum()?
// equals the digit-sum of `a_i`:
1 // Increase the count by 1
: // Else:
0; // Leave the count the same by increasing with 0
if(c==n) // If the count equals the input integer `n` after the inner loop:
return a;}} // Return `a_i` as our `a(n)` result
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~74~~ 72 bytes
```
$a=@{}
1.."$args"|%{for(;$_-$a.(++$i|%{"$_"[0..9]-join'+'|iex})++){}}
$i
```
[Try it online!](https://tio.run/##TZHNboMwEITvPMWKOg0Igmz@3SpSrj310ltVRSTZNFSAU@I0kQjPTg0Bt77NN7OzsvYoLlifDlgUHdnDEpqOZMtV0xrM80yS1Z8n8zZr9qK2nsl6QTLPchySK2SStflOPY9/LL5EXs2d@S3Ha2s7jt20rUHyrjWMlWWAeq7FXGDUHoXvgq8FC5QVRFomSiZskqHKhrEOR8qN/2Q61PJAa5VmzE91GUsViGgygTjmLnBOdUOc0L6CpvxOHmAryhIrCdlG/CBk1Q7O1cQ2WIgLSAElogR5QHh7eYUiL3M5TqudlPaVYRT5tobRAFPq83@wT/bR2Kep@r8NN5hBM9ikOpcbrF0geD3iVuJOnYas716Np3MhFXhUFxuTg2MSazQX@K0n7adpxDTa7hc "PowerShell – Try It Online")
`2^31 = 2147483647`, so the expression `"$_"[0..9]` works with any Powershell `[int] > 0`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 92 or 113 bytes
Brute force short version:
```
(t=Total@IntegerDigits@#&;Catch@Do[If[Count[Range@(k-1),x_/;t@x==t@k]==#,Throw@k],{k,∞}])&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X6PENiS/JDHHwTOvJDU9tcglMz2zpNhBWc3aObEkOcPBJT/aMy3aOb80ryQ6KDEvPdVBI1vXUFOnIl7fusShwta2xCE71tZWWSckoyi/HMjWqc7WedQxrzZWU@1/QFFmXolDmoOhwX8A "Wolfram Language (Mathematica) – Try It Online")
Time- and memory-optimized version. Print table of values up to given number:
```
(n=0;a=<||>;r={};Do[While[FreeQ[a,i+1],a[k]=Lookup[a,k=Total@IntegerDigits@++n,0]+1];AppendTo[r,{i,n}],{i,#}];r)&
```
[Try it online!](https://tio.run/##FcpBC8IgGIDhHxNEoYftbIbBGAQdCgYdxMNHfbgPNxWz0@Zvt3V64eGdIY84Q6YXVCvrwctGgDyt61kkuRTRBf0caULdJ8SHBk6sNRy0M/IWgvvGjZwcQoZJXX1Gi6kjS/mjGPO8MdstLjGifw9BJ74Q98X8sytGpOO@3hP5rKxqm/oD "Wolfram Language (Mathematica) – Try It Online")
Ungolfed self-explained:
```
next = 0; assoc = <||>;
max = 30; result = {};
Do[
While[FreeQ[assoc, n + 1],
next += 1;
key = Total@IntegerDigits@next;
assoc[key] = Lookup[assoc, key, 0] + 1
];
AppendTo[result, {n, next}]
, {n, max}]; result
```
[Answer]
# [Scala](https://www.scala-lang.org/), 115 bytes
Golfed version. [Try it online!](https://tio.run/##Zc@xboMwEAbgPU9xoy0qC1J1wb2hUpdImUI7RVHkEKAuYEfnoyhCPDuFZivb6ftPuv9Cbhoz@ct3kTMcusv9w2cLwbABuBYltMY6YagKKbwRmfsxY7KuOskUPp1lwL9NgNus3DhRikTKf7JdyfNa4hW9rCmJ4weOm2lpVwqXws6xxOHHENBTjbFeph73NvBxjk5C6qsfKMJE10iK/eMD1ZqbOCsT3m1lWarQtbpPI6zH/ss2hehV7jvH4oxYy1d0UtM4zWd/AQ)
```
def f(n: Int)={var r,k=0;var w=List[Int]();do{r+=1;k=r.toString.map(_.asDigit).sum;w:+=k}while(w.count(_==k)<=n);r}
```
Ungolfed version. [Try it online!](https://tio.run/##ZY9Ni4MwFEX3/oq7TBgI2jIbqYuBbga66seqlJJatZlqUpLnSBn87TZVcTFuAue8e8l7LpWl7Dpz@clSwra@PPdm93b4C4BrlqOSSjNpCxfjy1r5PO7IKl2ceIyDVoSkTwIPb6nULGcR5//MYmaWcxPO1OdcRWE4yDYY98uZjvGtiffvtM6vtLCewokaTxvl6OhjJ8Ynf59SVzOW4asfCaIR3gkryAyXi0o@2FlIt1aFIi5cXY25BrFv3Xtq0dxUmYE1IjW1JnZG4mccqwR6@Nz2Z7RB170A)
```
object RubyToScala {
def main(args: Array[String]): Unit = {
println(f(1))
println(f(2))
println(f(3))
println(f(30))
println(f(50))
println(f(1000))
}
def f(n: Int): Int = {
var r = 0
var w = List[Int]()
var k = 0
do {
r += 1
k = r.toString.map(_.asDigit).sum
w :+= k
} while (w.count(_ == k) <= n)
r
}
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@¶XÇìxÃè¶Xìx}a
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLZYx%2bx4w%2bi2WOx4fWE&input=MTM)
[Answer]
# [Lua](https://www.lua.org/), 93 bytes
```
t={}n=0repeat m=0n=n+1(n..''):gsub('.',load'm=m+...')t[m]=(t[m]or 0)+1until...+0<t[m]print(n)
```
[Try it online!](https://tio.run/##FYkxCoAwDAC/4paWSklXMS8Rh4oiQhulppP49lhvuOEu1agq9LxMWLZri9JlQiZ2wbD3AHbY77oY8NCnM66QKTvfhpUpz2R@n6VD60JlOVJbDse/XuVgMWxVNWDjAw "Lua – Try It Online")
Ungolfed version:
```
t={}n=0
repeat
m=0 n=n+1 --Increment n, set m to 0
(n..''):gsub('.',load'm=m+...') --Sum digits of n, store in m
t[m]=(t[m]or 0)+1 --Increment t[m], or set to 1 if null
until...+0<t[m] --If input < t[m], stop loop
print(n)
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƘRʂṪc=
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNiU5OFIlQ0ElODIlRTElQjklQUFjJTNEJmZvb3Rlcj0maW5wdXQ9MTMmZmxhZ3M9)
#### Explanation
```
ƘRʂṪc= # Implicit input
Ƙ # Find the first positive integer, n, where:
R # Push [1..n]
ʂ # Get the digital sum of each number
Ṫ # Remove the last item and push it separately
c # Count the occurrences of this in the list
= # Does this equal the input?
```
] |
[Question]
[
Given a non-empty matrix of non-negative integers, answer which unique rows contribute most to the sum total of elements in the matrix.
Answer by any reasonable indication, for example a mask of the unique rows order of appearance (or sort order), or indices (zero- or one- based) of those, or a submatrix consisting of the rows (in any order) or some kind of dictionary construct… — but do explain it!
## Examples
`[[1,2,3],[2,0,4],[6,3,0],[2,0,4],[6,3,0],[2,0,4]]`:
The unique rows are `[1,2,3]`, `[2,0,4]`, and `[6,3,0]` each respectively contributing 6, 6, and 9 each time they occur. However, they occur once, thrice and twice respectively, so all of their respective occurrences contribute 6, 18, and 18 to the total (42), so the latter two rows are the ones that contribute most. Valid answers are therefore:
`[false,true,true]` mask in appearance/sort order or
`[1,2]`/`[2,3]` zero/one-based indices of the above or
`[[2,0,4],[6,3,0]]` the actual rows
⋮
---
`[[1,2],[3,1],[2,3],[1,2],[3,1],[2,3],[1,2]]`
`[false,false,true]`(appearance order) / `[false,true,false]`(sort order)
`[2]`/`[3]`(appearance order) / `[1]`/`[2]`(sort order)
`[[2,3]]`
⋮
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Ġị§§M
```
[Try it online!](https://tio.run/##y0rNyan8///Igoe7uw8tP7Tc9////9HRhjpGOsaxOtFGOgY6JkDaTMdYxwAnPxYA "Jelly – Try It Online")
1-based indices of sorted unique elements of input.
[Answer]
# [R](https://www.r-project.org/), 64 bytes
```
function(M)max(x<-tapply(rowSums(M),apply(M,1,toString),sum))==x
```
[Try it online!](https://tio.run/##fY4xbsMwDEX3nIJAFglg0zguOtVDh3Rqljg9gKLIsQCbdCWqdk7vKgk6dGg34pH/8Ye5qeYmkRXPpHa6N5OaXh7EDEN3UYHHOvUxc7yDHRYoXEvwdNYYU691VU3zEvZOUqAIBo7MnTMEX84KBxi9tHDYf2wf317f6y14gshBgMPJBVCdm7zlczBD661ewWIJh9ZBIv@ZHOT/WRkcxJZHAhN/rGR6FzGbwAv4CM7ECwjnXLZGMXSCMQvbW1iysOcoYJly82OS3B6YXFysFo0KR08nZVWBGyw1WrXBNT5dh2cscf0f0fp3/ropsbgf3Fx/whydvwE "R – Try It Online")
Returns a boolean vector with TRUE/FALSE in sort order (lexicographic).
The unique rows are shown as vector names, so it is easy to identify the most contributing ones.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
-1 thanks to FryAmTheEggman!
```
{s.MssZ.g
```
[Try it online!](https://tio.run/##K6gsyfj/v7pYz7e4OEov/f//6GhDHSMd41idaCMdAx0TIG2mY6xjgJMfCwA "Pyth – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~153~~ ~~145~~ 129 bytes
*-8 bytes thanks to @Mr. Xcoder!*
```
from itertools import*
def f(l):a=[[sum(map(sum,[*s])),k]for k,s in groupby(sorted(l))];return[v[1]for v in a if v[0]==max(a)[0]]
```
[Try it online!](https://tio.run/##dY7NDsIgEITvPgVHaPbQH@NB0yfZcMAUlFRYstDGPj2id08zk3xfMukoT4pTrY4pCF8sF6JXFj4k4tKdFuuEky91NTNi3oIMJsmWgF3WSsGqHbFYoRlRPJi2dD9kbqpdmqX0jW3ZOOKOw4/cv5wR3okdez3PwbylUa3qmtjHIp1EHGCESQOO0MO55QUm6P/udqN@AA)
[Answer]
## Haskell, 60 bytes
```
import Data.Lists
f x=nub$argmaxes(\e->sum e*countElem e x)x
```
Returns a list of the rows.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
IΦθ∧⁼κ⌕θι⁼×№θιΣι⌈Eθ×№θλΣλ
```
[Try it online!](https://tio.run/##dYvLCsIwEEV/JcsJjFBbceNKit0VBN2FLEItODjpIw/x72MsdSM4m8u590x3N64bDad0djQEqI0P0BCH3sGM4jjc4DRHwx4eKBrKmFuSEsVaX8n2Huox5udlQnGJFhalNS@yGVozfbYflVeV5fcOKSmltlhipVGVWOAu5x4rLP6y1mnz5Dc "Charcoal – Try It Online") Link is to verbose version of code. Default output format is each row element on its own line and rows double-spaced. Explanation:
```
θ Input array
Φ Filtered where
κ Current index
⁼ Equals
⌕ First index of
ι Current row
θ In input array
∧ Logical And
№ Count of
ι Current row
θ In input array
× Multiplied by
Σ Sum of
ι Current row
⁼ Equals
⌈ Maximum of
θ Input array
E Mapped over rows
№ Count of
λ Current row
θ In input array
× Multiplied by
Σ Sum of
λ Current row
I Cast to string
Implicitly printed
```
[Answer]
# Mathematica, 48 bytes
```
Last[SortBy[Gather[m], Total[Flatten[#]] &]][[1]]
```
or
```
TakeLargestBy[Gather[m], Total[#, 2] &, 1][[1, 1]]
```
where (for example)
```
m = {{1, 2, 3}, {2, 0, 4}, {7, 9, 5}, {6, 3, 0}, {2, 0, 4},
{6, 3, 0}, {2, 0, 4}, {7, 9, 5}};
```
[Answer]
# JavaScript (ES6), 88 bytes
Outputs an array of Boolean values in appearance order.
```
m=>m.map(h=o=r=>h=(v=o[r]=~~o[r]+eval(r.join`+`))<h?h:v)&&Object.keys(o).map(x=>o[x]==h)
```
[Try it online!](https://tio.run/##dYxLDoIwFEXnLoS04dnwMQ6MD5fgAhoSKhYLAo8U0uCErVdgrKOb@zuNcmosbT1Mx56e2lfoO8w60amBGSS0mBlkDknaHJdlk1A71TIrGqr7Iiw4v5qbuTgeBPdHo8tJvPVnZMR3xowZyTlHNNyX1I/UatHSi1VMyhgSSHOQCURwWvUMKUR/fc754Qdh7VOI99XG@p2sX/8F "JavaScript (Node.js) – Try It Online")
[Answer]
# [Groovy](http://groovy-lang.org/), 76 bytes
```
{l->m=l.toSet().sort().collect{it.sum()*l.count(it)}
m.collect{it==m.max()}}
```
[Try it online!](https://tio.run/##dYkxDsIwDAB3XmIjE5UWsYVPMEYdUNWiSHaMUheBqrw9lI2F6XR396z6fNfJ15UPF/HsTK@jAbpZ8xeDMo@DrdHcvAjgnre0JINoWHby870XJ7cXYCn1kWMyTjBBCEdqqesptNTQaeOZOmr@eo9YPw "Groovy – Try It Online")
Returns as booleans in sort order
[Answer]
# [Scala](http://www.scala-lang.org/), 63 bytes
```
l=>{var m=l.distinct.map(n=>n.sum*l.count(n==))
m.map(m.max==)}
```
[Try it online!](https://tio.run/##jY1NCsIwEIX3PUWWrYTQH3EhpKALQdATSBYxjRBJJqFJpVB69pi2HsBZfLx5jzfjBdc82udbioDuXAGSY5DQeXRybso@vEev42UAEZSF6nFTPmy4QmAMr/JsrZYcGKNR03ZaOoZq0qVMpSIx3OVAWyB@MDtNhB0gJIMWRWbWcOGY9jm6XkHQkL/y5fKGCte4KdZXeY1LvP/pA25w@ZefJpvjFw "Scala – Try It Online")
Returns booleans in appearance order
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 [bytes](https://github.com/abrudz/SBCS)
```
(⌈/=⊢)+.×∘⍴⌸
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NRT4e@7aOuRZraeoenP@qY8ah3y6OeHf/THrVNeNTbZ/Soq/lR39TgIGcgGeLhGcwFpIFSaRqPejcbaz7qXWWqYAzUYqRgoGCiYKZgrGAAU6FgrmAEMgyo7j8A "APL (Dyalog Unicode) – Try It Online")
-2 thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m). -1 thanks to alternate output format.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
#~Position~Max@#&@(Total[#,2]&/@Gather@#)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X7kuIL84syQzP6/ON7HCQVnNQSMkvyQxJ1pZxyhWTd/BHaS8yEFZU@1/ukN1taGOkY5xrU61kY6BjgmQNtMx1jHAya/9DwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 17 bytes
```
{&a=|/a:+//'x@=x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqlot0bZGP9FKW19fvcLBtqL2f4lVtUp0ZV2RVZpChXVCfra1RkJaYmaOdYV1pXWRZmwtV0m0hqGCkYKxtZGCgYKJtZmCsYIBJluTS0FBA0lUMxaq0dpYwdAapB2NDdKgA2TH/gcA "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`=x` group - form a dictionary in which the keys are rows and the values are lists of their indices in the matrix
`x@` index the original matrix with that. the result is again a dictionary with the rows as keys. the values are multiple copies of the corresponding key
`+//'` sum until convergence each (acts only on the values; keys remain as they are)
`a:` assign to `a`
`|/` maximum (of the values)
`a=|/a` a row-to-boolean dictionary of which rows contribute the most
`&` "where", i.e. which keys correspond to values of 1
[Answer]
# [Python 2](https://docs.python.org/2/), ~~81~~ 78 bytes
```
lambda a:{u for u in a if a.count(u)*sum(u)==max(a.count(t)*sum(t)for t in a)}
```
[Try it online!](https://tio.run/##dYxBCgIxDEX3niLLRILMtOJC6E3cRKVYsO0wpjAinr12RlwIuvr8l7w/3PWSk6neHepV4vEsIPtHAZ9HKBASCAQPsjnlkhQLrW8ltnAuyoQfrG@sNFu6WPSswxiSgkdA7NmwJUbDHW9b7thy97cT0OpbbifL/fIwz/wmTasv "Python 2 – Try It Online")
3 bytes thx to [Black Owl Kai](https://codegolf.stackexchange.com/users/81238/black-owl-kai).
Given a collection of tuples, the output is a set of those tuples having the desired maximal property.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ês{γOOZQÏ
```
[Try it online](https://tio.run/##yy9OTMpM/f//8Kri6nOb/f2jAg/3//8fHW2kY6BjEqsTbahjpGMMpM10jHUMgDRMHJUfCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2/w@vKq4@t9nfPyrwcP9/nf/R0dFGOgY6JrE60YY6RjrGQNpMx1jHAEjDxFH5sToK0SClQAFjHUOwsDFEMxaR2FgA).
**Explanation:**
```
ê # Sort and uniquify the (implicit) input list of lists
# i.e. [[2,0,4],[1,2,3],[6,3,0],[2,0,4],[6,3,0],[2,0,4]]
# → [[1,2,3],[2,0,4],[6,3,0]]
s # Swap so the (implicit) input list of lists is at the top again
{ # Sort it
# i.e. [[2,0,4],[1,2,3],[6,3,0],[2,0,4],[6,3,0],[2,0,4]]
# → [[1,2,3],[2,0,4],[2,0,4],[2,0,4],[6,3,0],[6,3,0]]
γ # Group the sorted list of lists
# i.e. [[1,2,3],[2,0,4],[2,0,4],[2,0,4],[6,3,0],[6,3,0]]
# → [[[1,2,3]],[[2,0,4],[2,0,4],[2,0,4]],[[6,3,0],[6,3,0]]]
O # Take the sum of each inner-most lists
# i.e. [[[1,2,3]],[[2,0,4],[2,0,4],[2,0,4]],[[6,3,0],[6,3,0]]]
# → [[6],[6,6,6],[9,9]]
O # Take the sum of each inner list
# i.e. [[6],[6,6,6],[9,9]] → [6,18,18]
Z # Get the max (without popping the list of sums)
# i.e. [6,18,18] → 18
Q # Check for each if this max is equal to the sum
# i.e. [6,18,18] and 18 → [0,1,1]
Ï # Filter the uniquified list of lists on truthy values (and output implicitly)
# i.e. [[1,2,3],[2,0,4],[6,3,0]] and [0,1,1] → [[2,0,4],[6,3,0]]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ 11 bytes
*-2 bytes from @Shaggy*
```
ü¬®xx
m¥Urw
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=/KyueHgKbaVVcnc=&input=W1sxLDIsM10sWzIsMCw0XSxbNiwzLDBdLFsyLDAsNF0sWzYsMywwXSxbMiwwLDRdXSAtUQ==)
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
[:(=>./)+/^:2/.~
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600bO309DW19eOsjPT16v5r/s9VsNVTMFQwUjDWMQKqNNExUzBWMEBhW4E5XGkKuQA "J – Try It Online")
A monadic verb that gives the boolean result in appearance order.
### How it works
```
[:(=>./)+/^:2/.~
/.~ Self-classify; collect identical rows in appearance order
For each collected rows (= a matrix),
+/^:2 Sum all the elements into one value
[:(=>./) Compute the boolean vector:
>./ Is the max of the array
= equal to this element?
```
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 15 bytes
```
l2(*)fo<fce>~sB
```
Sorts the input by how much they contribute, ascending.
## Explanation
So first we have `sB` which sorts the list by some conversion function. So we want to come up with the correct conversion function. `fo` will give the sum of the element and `fce` will count the number of times the element appears in the matrix. To get our metric we multiply them.
So put it together and you have:
```
f x=sB(\y->fo y*fce x y)x
```
So now we want to get rid of that lambda since it's pretty expensive. We can do this with `l2`/`(**)`:
```
f x=sB(l2(*)fo$fce x)x
f x=sB(ml**fo$fce x)x
```
Now we want to get rid of the `x`. We can do that by using `>~`, the monadic bind.
```
f=l2(*)fo<fce>~sB
f=(ml**fo)<fce>~sB
```
Operator precedence is not in favor of us using `(**)` so the `l2` version is what we go with.
## Reflections
I'm pretty happy overall with this. But some tweaks can be made.
* `(**)` should be given higher precedence. Right now it's just the default, it should be higher than `(<)`.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 126 bytes
```
n=>{var i=n.OrderBy(a=>a.Sum()*n.Count(a.SequenceEqual));return i.Where((a,b)=>i.Take(b).Count(a.SequenceEqual)<1).Reverse();}
```
[Try it online!](https://tio.run/##rY5NS8QwEIbv/RWhpxmNYT/ES5sclBUEQVBhz2kdd0N3p2yarEjtb68bEWVRbx7f532HeerurO7ceB25Lm8WHLfkbbWh8tZ1oXQcjJG/Y9PokbXp99YLp1nd@Sfyl69gtbHqIW4BT1hdtZEDHDLtInFNi120G8TCU4iehVPLNXkCsLJCbZx6tA1BhX/clVNU97Qn3xFgMYxFlp63mulFfIh92wH2XzSBfipncj7II3gYzeREnv/EF3IuJ/@zHorsufVk6zUk2yAciwZaxKw/KlapCJgtvQsEq9Nc5lhknzF/S2EY3wE "C# (Visual C# Interactive Compiler) – Try It Online")
#
Most of this code is spent taking out all duplicate values, since the default comparer for lists do not compare the values inside the lists. That means that I cannot use `Distinct()`, `GroupBy()`, or `Contains` to filter the list.
[Answer]
# Japt, ~~11~~ 10 bytes
```
ü¬ü_xxÃÌmâ
```
[Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=/Kz8X3h4w8xt4g==&input=W1sxLDIsM10sWzIsMCw0XSxbNiwzLDBdLFsyLDAsNF0sWzYsMywwXSxbMiwwLDRdXQoKLVI=)
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 10 bytes
```
ȯẋ_¦Σ¦:⌉=¦
```
[Try it online!](https://tio.run/##S0/MTPz//8T6h7u64w8tO7f40DKrRz2dtoeW/Y@ONlQwUjCOVYg2UjBQMAHSZgrGCgY4@bGP2ib@BwA "Gaia – Try It Online")
Since Gaia doesn't accept lists through inputs very easily, this is a *function* that accepts a list from the top from the top of the stack and leaves the result on top (as masks of sorted order).
```
ȯ Sort the list
ẋ Split it into runs of the same element (in this case, runs of the same row)
_¦ Flatten each sublist
Σ¦ Sum each sublist
:⌉ Find the maximum sum
=¦ Compare each sum for equality with the maximum
```
] |
[Question]
[
Given as input a positive integer `n>=1`, output the first `n` rows of the following triangle:
```
1
1 0 1
0 0 1 0 0
1 1 1 0 1 1 1
0 0 0 0 1 0 0 0 0
1 1 1 1 1 0 1 1 1 1 1
0 0 0 0 0 0 1 0 0 0 0 0 0
1 1 1 1 1 1 1 0 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1
```
The rows alternate between all zeroes and all ones, except the center column is flipped.
## Test cases
* **Input**: `3`
* **Output**:
```
1
1 0 1
0 0 1 0 0
```
* **Input**: `10`
* **Output**:
```
1
1 0 1
0 0 1 0 0
1 1 1 0 1 1 1
0 0 0 0 1 0 0 0 0
1 1 1 1 1 0 1 1 1 1 1
0 0 0 0 0 0 1 0 0 0 0 0 0
1 1 1 1 1 1 1 0 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1
```
Your code must work for any `n<100`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), hence the shortest code in bytes wins!
Trailing spaces / newlines and leading newlines are allowed!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ṭ=Ḃµ€ŒB
```
[Try it online!](https://tio.run/##ARoA5f9qZWxsef//4bmsPeG4gsK14oKsxZJC////Mw "Jelly – Try It Online")
-1 byte thanks to Erik the Outgolfer
# Explanation
```
Ṭ=Ḃµ€ŒB Main link
€ For each element in (implicit range of) the input:
Ṭ List 1s and 0s with 1s in the indices in the left argument (generates `[0, 0, ..., 1]`)
=Ḃ Is this equal to `(z % 2)` where `z` is the range number? (Every other row is flipped)
ŒB Reflect each row
```
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
lambda n:[i*`i%2`+`~i%2`+i*`i%2`for i in range(n)]
```
**[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjpTKyFT1ShBO6EOTEG5aflFCpkKmXkKRYl56akaeZqx/wuKMvNKNNI0jDU1uWBsQwNNzf@GBgA "Python 2 – Try It Online")**
This returns the rows as a list of Strings.
# [Python 2](https://docs.python.org/2/), ~~67 65~~ 63 bytes (formatted)
```
n=input()
for i in range(n):k=i*`i%2`;print(n-i)*" "+k+`~i%2`+k
```
**[Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDkystv0ghUyEzT6EoMS89VSNP0yrbNlMrIVPVKMG6oCgzr0QjTzdTU0tJQUk7WzuhDiSunf3/v6EBAA "Python 2 – Try It Online")**
This outputs with a trailing space on each line.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
⁼€=ḂŒḄµ€
```
[Try it online!](https://tio.run/##y0rNyan8//9R455HTWtsH@5oOjrp4Y6WQ1uBvP///xsaAAA "Jelly – Try It Online")
-2 thanks to [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino).
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
lambda n:[[i%2]*i+[~i%2]+i*[i%2]for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjo6U9UoVitTO7oOxNDO1AILpOUXKWQqZOYpFCXmpadq5GnG/i9JLS4pVrBViDbWUTA0iOXigqsBy1hxKQBBQVFmXolCmkam5n8A "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 53 bytes
```
lambda n:[(([i%2]*i+[~i%2])*2)[:-1]for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlpDIzpT1ShWK1M7ug7E0NQy0oy20jWMTcsvUshUyMxTKErMS0/VyNOM/V@SWlxSrGCrEG2so2BoEMvFBVcDlrHiUgCCgqLMvBKFNI1Mzf8A "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 67 bytes
```
lambda n:[[[i%2,~i%2][j==i]for j in range(2*i+1)]for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjo6OlPVSKcOSMRGZ9naZsam5RcpZClk5ikUJealp2oYaWVqG2qCRTMRonmasf9LUotLihVsFaKNdRQMDWK5uOBqwDJWXApAUFCUmVeikKaRqfkfAA "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~12~~ 9 bytes
```
õÈÇ¥Y^uÃê
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=9cjHPDFeWXXDdyDq&input=NSAtUg==)
~~Quite~~ Slightly sad compared to Jelly, but Japt doesn't have anything like `Ṭ` so I must make do with what I have...
### Explanation
```
õÈ Ç ¥ Y^ uà ê
UõXY{XoZ{Z==Y^Yu} ê} Ungolfed
Implicit: U = input number
Uõ Create the range [1..U]. [1, 2, 3, 4]
XY{ } Map each item X and 0-index Y in this to
Xo Create the range [0..X). [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
Z{ } Map each item Z in this to
Z==Y Z is equal to Y [[1], [0, 1], [0, 0, 1], [0, 0, 0, 1]]
^Yu XORed with Y % 2. [[1], [1, 0], [0, 0, 1], [1, 1, 1, 0]]
ê Bounce. [[1],
[1, 0, 1],
[0, 0, 1, 0, 0],
[1, 1, 1, 0, 1, 1, 1]]
Implicit: output result of last expression
```
[Answer]
# Mathematica, 77 bytes
```
Table[CellularAutomaton[51,{{1},0},#,{All,All}][[i]][[#-i+2;;-#+i-2]],{i,#}]&
```
**@Not a tree** golfed it down to 48 bytes!
# Mathematica, 48 bytes
```
#&@@@NestList[CellularAutomaton@51,{{1},0},#-1]&
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 14 bytes
*Thanks to @Jakube for saving 2 bytes!*
```
ms_+Bm%d2d%hd2
```
[Try it here!](https://pyth.herokuapp.com/?code=ms_%2BBm%25d2d%25hd2&input=10&debug=0)
# [Pyth](https://pyth.readthedocs.io), 15 bytes
*Thanks a lot to @Jakube for -1 byte*
```
m++K*d]%d2%td2K
```
[Try it here.](https://pyth.herokuapp.com/?code=m%2B%2BK%2ad%5D%25d2%25td2K&input=10&debug=0)
# [Pyth](https://pyth.readthedocs.io), 16 bytes
```
m++K*d`%d2`%td2K
```
[Try it here.](https://pyth.herokuapp.com/?code=m%2B%2BK%2ad%60%25d2%60%25td2K&input=10&debug=0)
[Answer]
# [R](https://www.r-project.org/), 73 bytes
Thanks to Giuseppe! Nice catch.
```
n=scan();for(i in 1:n)cat(c(rep(" ",n-i),x<-rep(1-i%%2,i-1)),i%%2,x,"\n")
```
[Try it online!](https://tio.run/##Hcc7CoAwDADQq5RAIYEEjKOfm7iUopAlSnXo7SO6vdcifL1rcaT5OBtaMk86OdXyYMW2XwgJ2MWI@yLfVSznkU2UiH92hs2BQod4AQ "R – Try It Online")
# [R](https://www.r-project.org/), 78 bytes
```
n=scan();for(i in 1:n)cat(x<-c(rep(" ",n-i),rep(1-i%%2,i-1)),i%%2,rev(x),"\n")
```
[Try it online!](https://tio.run/##Hcc7CoAwDADQq5RCIYEErKOfm7iUUiFLlCjS20d0e8/cdb1qUcB5PwwkiIY8KdZyQ1@4grUTYoikLEhfMktKIwlnRPpp7YGOFDeN6HnwFw "R – Try It Online")
# [R](https://www.r-project.org/), 82 bytes
```
n=scan();for(i in 1:n){j=i%%2;x=c(rep(" ",n-i),rep(1-j,i-1));cat(x,j,rev(x),"\n")}
```
[Try it online!](https://tio.run/##FcgxCoAwDADAr5RCIYF0iKOlP3GRopAOUapIQXx71PGumWk@yqyAad0aiBN1PCreNUsIQ@q5QFt28M6TRkH6wbGSREZMZT6hU/32go7kJ/X4GLO9 "R – Try It Online")
# [R](https://www.r-project.org/), 110 bytes - output to stdout
```
m=matrix(x<-rep_len(0:1,n<-scan()),n,n-1);m[upper.tri(m,T)]=" ";for(i in 1:n)cat(rev(m[i,]),1-x[i],m[i,],"\n")
```
[Try it online!](https://tio.run/##HcpLCgIxDADQq5SuEkhlup3PLdzVImWoEDCxxBnp7au4fPBsDNmkHMYd@hqstvuzKkxzJF3Dey8KiKSkIeIi6Wyt2uW3QeiKefPOL4@XATtWF2fFvRxg9QOSmDJSDD1xpr/I39TjiNP4Ag "R – Try It Online")
# [R](https://www.r-project.org/), 130 bytes - output to a file
```
m=matrix(x<-rep_len(0:1,n<-scan()),n,n-1);m[upper.tri(m,T)]=" ";for(i in 1:n)cat(rev(m[i,]),1-x[i],m[i,],"\n",file="a",append=i>1)
```
[Try it online!](https://tio.run/##HcxNCsMgEEDhq4irGRhLXebHnqI7K0VSAwNxKiYt3t6GLh98vNp7djkelRu02dRUnlsSuI6WZDb7EgUQSUiMxSn7TympXk4Nme4YnFZ6Wt8VWLEoOwou8YCavpA9U0CypnkO9C/SD9G08pacjpriuZKX45vFPgz9Bw "R – Try It Online")
Writing out to a file as I do not know how to fit it in the console if `n==99` (see the result [here](https://gist.github.com/djhurio/00a298cbb06a2b8be0fac6d05f72bd2b)).
[Answer]
# [Pascal](https://www.freepascal.org/), ~~181~~ 154 bytes
*27 bytes saved thanks to @ThePirateBay*
```
procedure f(n:integer);var i,j:integer;begin for i:=1to n do begin write(' ':(n-i+1)*2);for j:=1to i*2-1do write((ord(j<>i)+i)mod 2,' ');writeln()end end;
```
[Try it online!](https://tio.run/##RY7dDoMgDIWv51P0TurPErxZArp3cQKm6sAwtz0@A41Zk/bi9PTrWfvX0C@1WYcQVu8Grd5eg2FWkN30qD3KT@@BqukU5EOPZMG4qIqObw4sKAeH@vW0aZZDLpitqeRYNCiTdTqsVDQ1j@7Dx5xXbGrvhCXh0yloqniKct8ulqG2CmLLkDLMAs4I2f4tuyTyDKIDDhF@@@cwbEYJJyfvUkXwDsviuIYf)
**Unglofed**
```
procedure f (n: integer);
var i, j: integer;
begin
for i := 1 to n do
begin
write(' ': (n-i+1) * 2);
for j := 1 to i*2-1 do
write((ord(j<>i) + i) mod 2, ' ')
writeln()
end
end;
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 25 bytes
```
.+
$*0
0
1$`¶
T`d`10`¶.*¶
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRcuAy4DLUCXh0DaukISUBEMDIEtP69C2//8NDQA "Retina – Try It Online") Explanation: The first stage converts the input into a string of zeros of that length. The second stage then takes all of the prefixes of that string (not including the string itself) and prefixes a 1 to them. The third stage then toggles the bits on alternate lines.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 24 21 18 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
FNÉN×NÈJûIN>-úˆ}¯»
```
[Try it online!](https://tio.run/##ASYA2f8wNWFiMWX//0ZOw4lOw5dOw4hKw7tJTj4tw7rLhn3Cr8K7//8xMA)
---
Edit: Well, it is my first 05AB1E golf so I'm not surprised things can be golfed. Edit history:
* 18 (see above)
+ So there *is* a intersect mirror (both [`.∞`](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt#L358) and [`û`](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt#L302)), which eases up things a lot
+ As do [`È` and `É`](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt#L251-L252), making `2%` and `2%_` a lot shorter
* 21: [`FN2%DN×Dr_sJIN>-úˆ}¯»`](https://tio.run/##MzBNTDJM/f/fzc9I1cXv8HSXovhiL08/O93Du0631R5af2j3//@GBgA)
+ Removed implicit stuff: `IF` -> `F`, `)J` -> `J`
+ `baa` to `aab` can be done by [`.À` (rotating)](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt#L354) but also by [`r` (reversing)](https://github.com/Adriandmen/05AB1E/blob/master/docs/info.txt#L116) (shorter)
* 24: [`IFN2%DN×D.À_s)JIN>-úˆ}¯»`](https://tio.run/##MzBNTDJM/f/f083PSNXF7/B0F73DDfHFml6efna6h3edbqs9tP7Q7v//DQ0A)
[Answer]
# [Perl 5](https://www.perl.org/), 58 + 1 (-n) = 59 bytes
```
say$"x(2*--$_).($/=$i%2 .$")x$i.(1-$i%2).$".$/x$i++while$_
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJFqULDSEtXVyVeU09DRd9WJVPVSEFPRUmzQiVTT8NQF8TXBPL1VPSBItra5RmZOakq8f//m/zLLyjJzM8r/q/ra6pnYGjwXzcPAA "Perl 5 – Try It Online")
~~# [Perl 5](https://www.perl.org/), 59 + 1 (-n) = 60 bytes~~
```
say$"x(2*--$_).($i%2 .$")x$i.(1-$i%2).($".$i%2)x$i++while$_
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJFqULDSEtXVyVeU09DJVPVSEFPRUmzQiVTT8NQF8QHCSvpgVlAUW3t8ozMnFSV@P//Tf7lF5Rk5ucV/9f1NdUzMDT4r5uXCAA "Perl 5 – Try It Online")
[Answer]
# Mathematica, 90 bytes
```
Array[(x=Table[1,f=(2#-1)];x[[⌈f/2⌉]]=0;If[#==1,{1},If[OddQ@#,x/.{1->0,0->1},x]])&,#]&
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 13 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
∫:2\r*Kr1κ+╥T
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjJCJTNBMiU1Q3IqS3IxJXUwM0JBKyV1MjU2NVQ_,inputs=NQ__)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
EN⪫IE⁺¹ι﹪⁺ι¬λ² ‖O←
```
[Try it online!](https://tio.run/##JYxBCsIwEEX3niJ0NYEUbJd26UqxtfQGMaYYGDMlmfT6Y6Sb/@A9@O5jkyOLInMKkWG0G9ziVngq35dPoI26U4hwtfmIM5YMnVGhlpHeBelQwaiJGFBX3@v/NqqpHE6LX9E7fu4@YT24PPzKehDpztLu0mb8AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
EN For each of the input number of rows
⪫ Join with spaces
I Convert to string
E⁺¹ι For each column
﹪⁺ι¬λ² Calculate the digit
‖O← Reflect to the left
```
[Answer]
# JavaScript, ~~140~~ 132 bytes (with proper formatting)
```
n=>{A=Array;a='';b=0;for(x of A(n)){for(c of A(n-b))a+=' ';for(c of A(b))a+=b%2;a+=(b+1)%2;for(c of A(b))a+=b%2;a+='\n';b++}return a}
```
[Try It Online](https://tio.run/##dY7BCsIwEER/JRdJllCpvYYI/Q8vm5hKpezKNhWl9NtjRA9ePM3Mm8PMFe84RxlvuSE@p5Jl9IX8ce19L4JPh15rF3zrBhbzUDyo3hDA@o7xG5sAgNZrpd0P/sCw61wVE@wBqv3X6xPVGWs3SXkRUriVyDTzlPYTX0y9ZboWoLwA)
[Answer]
# [JavaScript (ES6)](https://babeljs.io/), ~~74~~ ~~73~~ ~~71~~ ~~68~~ 64 bytes
**-7 bytes** by @Neil
```
f=n=>n--?[...f(n), [...Array(n-~n)].map((v,i)=>(n+(i==n))%2)]:[]
```
[Try it online!](https://tio.run/##FcbBCoMwDADQX/EiJMzkMNhlI8q@Q3qIrpWOLpU6BC/@esfe6b11120ucf3SpJNPZPnlaw1i0hvRMDJzAMOu@e9Zih5gdBo6/ugKsHcRpQe7QBQxxPaK7j66OmfbcvKc8gIBboiP@gM "JavaScript (ES6) – Try It Online")
Simple recursive function that generates the lines one by one. Outputs as array of array of numbers.
---
Outputs as formatted string:
# [JavaScript (ES6)](https://babeljs.io/), ~~122~~ ~~119~~ 118 bytes
```
f=(n,w=2*n+1,N=n,s=" ".repeat((N-n)*2))=>(--n?f(n,w,N)+s+[...Array(n-~n)].map((v,i)=>(n+(i==n))%2).join(" "):s+1)+"\n"
```
[Try it online!](https://tio.run/##FcxLCsIwEADQq0hAmGk@2CyVUbxAL6Au0ppKSjspSam48erR7h9vcKvLXQrzolvX@lFzfPpSegJWb7IVy1o1xCqT2AmT/OzdAtBoxsoi0hm05ku/YdWgzPJmjLmm5D7A@sv4MJObAVYVNssSAhEj7i2aIQaGf4rHLGuU4s6idJFzHL0Z4wt6sAfEU/kB "JavaScript (Babel ES6) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
Straight forward list comprehension:
```
f n=[k++[mod i 2]++k|i<-[1..n],k<-[mod(i+1)2<$[2..i]]]
```
[Try it online!](https://tio.run/##DclBCsMgEEbhq/yLLhpsByJd6qrrnkCGIsSkg3ESEpe5u3Xx4IP3i2dO69raDPUhGxPKNkFg2Zh8iXuGkUj5kbv6uYsZB@tuwRIJM7cSReFR4v75Yj9EKwhz70hxgncOS6rvTWvSerbXHw "Haskell – Try It Online")
[Answer]
# J, 32 bytes
```
3 :'-.^:(2|y)(=|.)i.>:+:y'&.>@i.
```
[Try it online!](https://tio.run/##y/r/P81Wz1jBSl1XL85Kw6imUlPDtkZPM1PPzkrbqlJdTc/OIVOPiys1OSNfIU3B9P9/AA) This is an anonymous function that returns a boxed list of values.
I like to imagine that the explicit function definition saves bytes by virtue of removing caps and such, but it probably adds a few bytes in comparison to a tacit answer.
# Explanation
```
3 :'-.^:(2|y)(=|.)i.>:+:y'&.>@i.
i. For i = 0 ... input - 1
3 :'-.^:(2|y)(=|.)i.>:+:y' Explicit function: compute nth row
>:+:y 2n+1
i. Range [0,2n+1)
(=|.) Equate range to reversed range
(yield 0 0 0 ... 1 ... 0 0 0)
If
n = 1 (mod 2)
Then
Negate each value
&.> Box
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
FN°SRNF_}ûˆ
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fze/QhuAgP7f42sO7T7f9/29oAAA "05AB1E – Try It Online")
**Explanation**
```
F # for N in range [0 ... input-1] do:
N° # push 10^N
S # split to list of digits
R # reverse
NF_} # N times do: logical negation
û # palendromize
ˆ # add to global list
# implicitly display global list
```
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
(2&|~:0=i:)&.>@i.
```
[Try it online!](https://tio.run/##y/r/P03B1kpBw0itps7KwDbTSlNNz84hU4@LKzU5I18hTcEYwtDQMNJSjtFV1qzRU4o3VLJSs9MEShoa/P8PAA "J – Try It Online")
Outputs a list of boxed arrays.
## Explanation
```
(2&|~:0=i:)&.>@i. Input: n
i. Range from 0 to n, exclusive end
& > Unbox each and perform on each x
i: Range from -x to x, inclusive
0= Equal to 0
~: Not equal
2&| x mod 2
&.> Perform inverse of unbox (box)
```
[Answer]
# Java 8, ~~121~~ ~~111~~ ~~109~~ 101 bytes
```
n->{String r[]=new String[n],t;for(int i=0,j;i<n;r[i++]=t+i%2+t)for(j=0,t="";j++<i;t+=i%2);return r;}
```
My current byte-score (101) is also a row of the binary triangle. :)
**Explanation:**
[Try it here.](https://tio.run/##jU/LasMwELz7K5ZAwUKJSNujokI/oLn0aHxQFaWsaq@MvE4Jwd/uyrHbcy8LOw9mJtiL3cXOUzh9Tdh2MTGEjKmBsVGvKdlrrwvX2L6HN4t0KwCQ2KezdR6O8wvwzgnps6rBlZkDEjrDY5FPz5bRwREIDEy0e7ktWkhVbch//1qp3rI@x3T3o9lvg8YD6VShlLVhiQ9PksUsCJlks9noIOUBNUuTOaGT5yERJD1Oeg7uho8mB6/5l4gnaHP98q@qFWv3a8@@VXFg1WWKGyqX1YrjIi5JufJZiPuqfxse96tjLMbpBw)
```
n->{ // Method with integer parameter and String-array return-type
String r[]=new String[n], // Result String-array
t; // Temp String
for(int i=0,j; // Some index-integers
i<n; // Loop (1) from 0 to `n` (exclusive)
r[i++]= // After every iteration, set the next row to:
t+ // `t` +
i%2 // Center digit (`i` has already been raised by 1 now)
+t) // + `t` again
for(j=0,t=""; // Reset index `j` and the temp-String `t`
j++<i; // Inner loop (2) from 0 to `i` (exclusive)
t+=i%2 // Append `t` with an outer digit
); // End of inner loop (2)
// End of loop (1) (implicit / single-line body)
return r; // Return resulting String-array
} // End of method
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 49 bytes
```
~.:a;0\{..1+2%.!""+@*+" "a(:a*+.1>-1%\+"\n"+\)}*;
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v07PKtHaIKZaT89Q20hVT1FJSdtBS1tJQSlRwypRS1vP0E7XUDVGWykmT0k7RrNWy/r/f0MDAA "GolfScript – Try It Online")
] |
[Question]
[
My challenges tend to be a little bit hard and unattractive. So here something easy and fun.
## Alcuin's sequence
[Alcuin's sequence](http://en.wikipedia.org/wiki/Alcuin%27s_sequence) `A(n)` is defined by counting triangles. `A(n)` is the number of triangles with integer sides and perimeter `n`. This sequence is called after Alcuin of York.
The first few elements of this sequence, starting with `n = 0` are:
```
0, 0, 0, 1, 0, 1, 1, 2, 1, 3, 2, 4, 3, 5, 4, 7, 5, 8, 7, 10, 8, ...
```
For instance `A(9) = 3`, because the only triangles with integer sides and perimeter `9` are `1 - 4 - 4`, `3 - 3 - 3` and `2 - 3 - 4`. You can see the 3 valid triangles down below.

There are some quite interesting pattern in this sequence. For instance `A(2*k) = A(2*k - 3)`.
For more information, see [A005044](http://oeis.org/A005044) on OEIS.
## Challenge
But your challenge is about the binary representation of these numbers. If we convert each sequence number to it's binary representation, put them in column vectors and line them up, it creates a quite interesting binary picture.
In the following picture you can see the binary representation of the sequence numbers `A(0), A(1), ..., A(149)`. In the first column you can see the binary representation of `A(1)`, in the second column the representation of `A(1)`, and so on.

You can see some sort of repeating pattern in this picture. It even looks kinda like fractals, if you look for instance at the image with the sequence numbers `A(600), A(601), ..., A(899)`.

Your job is to generate such an image. Your function, your script will receive two integer `0 <= m < n`, and it has to generate the binary image of Alcuin's sequence `A(m), A(m+1), A(m+2), ..., A(n-2), A(n-1)`. So the input `0, 150` generates the first picture, the input `600, 900` the second picture.
You can use any popular graphics format you want. Let's say every format that can be converted to png using [image.online-convert.com](http://image.online-convert.com/convert-to-png). Alternatively, you may display the image on screen. No leading white rows are allowed!
This is code-golf. So the shortest code (in bytes) wins.
[Answer]
# Mathematica, ~~126~~ ~~122~~ ~~121~~ 89 bytes
```
Image[1-Thread@IntegerDigits[l=Round[(#+3#~Mod~2)^2/48]&/@Range@##,2,⌈2~Log~Max@l⌉]]&
```
This defines an unnamed function taking the two integers as parameters and displaying the image on screen. It plots each square as a single pixel, but if you like you can actually zoom in.
I'm now using an explicit formula given [in the OEIS article](http://oeis.org/A005044) (first one in the Mathematica section, thanks to David Carraher for pointing that out). It's also blazingly fast now.
Here is the indented code with a few comments:
```
Image[1-Thread@IntegerDigits[ (* 3. Convert each number to padded binary, transpose
invert colours, and render as Image. *)
l = Round[
(#+3#~Mod~2)^2/48
] & /@ Range@##, (* 1. Turn input into a range and get the Alcuin
number for each element. *)
2,
⌈2~Log~Max@l⌉ (* 2. Determine the maximum number of binary digits. *)
]] &
```
Here is the output for `0, 600`:

[Answer]
## CJam (56 55 53 chars) / GolfScript (64 chars)
CJam:
```
"P1"q~,>{_1&3*+_*24+48/}%_:e>2b,\2_$#f+2fbz(,@@:~~]N*
```
GolfScript:
```
"P1"\~,>{.1&3*+.*24+48/}%.$-1=2base,\{2.$?+2base}%zip(,@@{~}/]n*
```
Both produce output in NetPBM format, and they're essentially ports of each other.
### Dissection
```
CJam GolfScript Explanation
"P1" "P1"\ NetPBM header
q~,> ~,> Create array [m .. n-1]
{_1&3*+_*24+48/}% {.1&3*+.*24+48/}% Map the sequence calculation
_:e>2b,\ .$-1=2base,\ Compute image height H as highest bit
in largest number in sequence
2_$#f+2fb {2.$?+2base}% Map sequence to bits, ensuring that
each gives H bits by adding 2^H
z(,@@ zip(,@@ Transpose and pull off dummy row to use
its length as the "width" in the header
:~~ {~}/ Flatten double array and dump on stack
]N* ]n* Separate everything with whitespace
```
Thanks to [Optimizer](https://codegolf.stackexchange.com/users/31414/optimizer) for CJam 56 -> 53.
[Answer]
# Pyth - 101 60 59
Outputs a `.pbm`. Can likely be golfed more.
```
Km.B/++24*dd**6%d2d48rvzQJCm+*\0-eSmlkKlddK"P1"lhJlJjbmjbdJ
```
Highly ungolfed because I will be translating to Pyth.
Explanation coming next. Right now look at the equivalent Python code.
It uses the OEIS algorithm to calculate the sequence and then it converts to binary, pads the numbers, does a matrix rotation, and formats it into a `pbm` image. Since I'm not using brute force, it is incredibly fast.
```
K=
m rvzQ Map from eval input to eval input
.B Binary rep
/ 48 Divided by 48
++ Triple sum
24 Of 24,
*dd Square of d
** Triple product
6 6
%d2 Modulo d%2
d Var d
J Set J=
C Matrix rotation from columns of row to rows of columns
m K Map K (This does padding)
+ String concat
* String repeat
\0 "0"
- ld Subtract the length of the column from
eS The max
mlkK Of all the column lengths
d The column
"P1" Print header "P1"
l Length of
hJ First row
lJ Number of columns
jb Join by linebreaks
m J Map on to J
jb Joined columns by linb
d
```
Here is the `600,900` example:

[Try it here online](http://pyth.herokuapp.com/?code=Km.B%2F%2B%2B24*dd**6%25d2d48rvzQJCm%2B*%5C0-eSmlkKlddK%22P1%22lhJlJjbmj%5C%20dJ&input=600%0A900).
[Answer]
# R - ~~127~~ 125
I'm not sure if this complies with the rules totally. It doesn't output an image to a file, but it does create a raster and plot it to an output device.
I found the same formula as Martin, but [here](http://mathworld.wolfram.com/AlcuinsSequence.html).
It uses an unnamed function.
```
require(raster);function(m,n)plot(raster(mapply(function(n)rev(as.integer(intToBits(round((n+n%%2*3)^2/48)))),m:n),0,n,0,32))
```
Run as follows
```
require(raster);(function(m,n)plot(raster(mapply(function(n)rev(as.integer(intToBits(round((n+n%%2*3)^2/48)))),m:n),0,n,0,32)))(0,600)
```
Produces the following plot

[Answer]
# J (~~52~~ 45 (Codepage 437))
This would be allowed (I think)
```
[:|:' █'{~[:#:[:([:<.48%~*:+24+6*]*2|])(}.i.)
```
### Hex dump
(Nothing special really, the black square is DB16 or 21910 in codepage 437.)
```
0000: 5b 3a 7c 3a 27 20 db 27 7b 7e 5b 3a 23 3a 5b 3a [:|:' .'{~[:#:[:
0010: 28 5b 3a 3c 2e 34 38 25 7e 2a 3a 2b 32 34 2b 36 ([:<.48%~*:+24+6
0020: 2a 5d 2a 32 7c 5d 29 28 7d 2e 69 2e 29 *]*2|])(}.i.)
```
### Usage
This outputs as follows (The code tags mess it up by adding space between the lines):
```
A=:[:|:' █'{~[:#:[:([:<.48%~*:+24+6*]*2|])(}.i.)
0 A 100
█ █████████████████████
█ ██████████████████████ █ █ █████
█ ██████████████ █ █ ██████████ █ █ ██████ █
█ ██████████ █ █ ██████ █ █ ████ █ █ ████ █ █ ██ █ █ ██ █ █ █
█ ██████ █ █ ████ █ █ ██ █ █ ██ █ █ █ █ █ █ ██ ██ ██ ██ ██ ██ ██ ██
█ ████ █ █ ██ █ █ █ █ ██ ██ ██ ██ ██ █ █ █ █ ██ █ █ ████ █
█ ██ █ █ ██ ██ ██ █ █ ██ █ █ ██ █ █ ██ ██ ██ █ █ ██ █
█ ██ ██ ██ ██ █ █ ██ ██ ██ ██ █ █ ██ ██ ██ ██ █ █ ██ ██ ██ ██ █ █
2000 A 2100
████████████████████████████████████████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████████████████████████████████████████
█ █████████████████████
█ ██████████████████████████████████████████████ █
█ ██████████████████████ █ █ ██████████████████████ █
█████ █ █ ██████████ █ █ ██████████ █ █ ██████████ █ █ █████████
████ █ █ ████ █ █ ████ █ █ ████ █ █ ████ █ █ ████ █ █ ████ █ █ ████ █ █ ███
█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
██ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ ██ █
█ ██ ██ ██ ██ ██ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ ██ ██ ██ ██ █ █
██ ██ ██ █ █ ██ ██ ██ █ █ █ █ █ █ █ █ █ █ █ █ █ █ ██ ██ ██ █ █ █ █ ██ █ █ ██
█ ██ █ █ ██ █ █ ██ █ █ ██ █ █ █ █ █ █ █ █ █ █ ██ ██ ██ █ █ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ █ █ █ █ █ █ ██ █ █ ██ █ █ ████ █ █ ██████ █
█ █ █ ████ █ █ ██ █ █ █ █ ██ ██ ██ ██ ██ █ █ █ █ ██ █ █ ████ █
█ ██ █ █ ██ █ █ ██ ██ ██ █ █ ██ █ █ ██ █ █ ██ ██ ██ █ █ █
██ ██ ██ █ █ ██ ██ ██ ██ █ █ ██ ██ ██ ██ █ █ ██ ██ ██ ██ █ █ ██ ██
```
In the standard J console, there is no spacing between lines, so I call the rule 'Alternatively, you may display the image on screen.' (Nowhere did it say that this image had to be represented as a sensible image format internally)
EDIT: Jconsole (as opposed to JQT) uses codepage 437 as a default, and DOES render the rectangles correctly when using them from a string.
[Answer]
# Python 2 ~~+ PIL~~, ~~255~~ 184
My first version used PIL in order to show an image :
```
i,R,B=input,range,lambda x:bin((x*x+6*x*(x%2)+24)/48)[2:]
def F(k,v):i.load()[k]=v
a,b=i(),i();h=len(B(b));from PIL import Image;i=Image.new('P',(b-a,h))
[F((x-a,y),int(B(x).zfill(h)[y])) for x in R(a,b) for y in R(h)]
i.putpalette([255]*3+[0]*3)
i.show()
```
The new version just produces a b&w PPM image on stdout :
```
i,R,B=input,range,lambda x:bin((x*x+6*x*(x%2)+24)/48)[2:]
def p(s):print s
a,b=i(),i();h=len(B(b));p('P1 %i %i'%(b-a,h))
[p(' '.join([B(x).zfill(h)[y] for x in R(a,b)])) for y in R(h)]
```
[Answer]
## JAVASCRIPT - 291
Code:
```
(function(a,b,c){c.width=b;t=c.getContext('2d');t.strokeStyle='black';for(i=a;i<=b;i++){g=(Math.floor(((i*i)+6*i*(i%2)+24)/48)>>>0).toString(2);l=g.length;for(j=0;j<l;j++){if(g[l-1-j]=='1'){t.rect(i-a,j,1,1);t.fill();}}}document.body.appendChild(c);})(0,300,document.createElement('canvas'))
```
Explanation:
```
(function (a, b, c) {
//setting canvas width
c.width = b;
//get context 2d of canvas
t = c.getContext('2d');
//setting storke style.
t.strokeStyle = 'black';
//looping from a to b
for (i = a; i <= b; i++) {
//calculating A(i) and converting it to a binary string
g = (Math.floor(((i * i) + 6 * i * (i % 2) + 24) / 48) >>> 0).toString(2);
//looping through that string
for (j = 0; j < g.length; j++) {
//since canvas is upside down and the first digit is actually the last digit:
if (g[g.length - 1 - j] == '1') {
//we create the 1 by 1 rect
t.rect(i - a, j, 1, 1);
//we draw the rect
t.fill();
}
}
}
//we append everything to the body
document.body.appendChild(c);
//parameters are put here
})(0, 300, document.createElement('canvas'))
```
Result:
Yes the result is upside down, but that's because `0,0` on a `js canvas` is top left. :3

Demo:
[Demo on jsfiddle](https://jsfiddle.net/Grimbode/8ms76eLb/60/)
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~26 25~~ 24 bytes
```
' ⎕'[⊤⌊12÷⍨6+×⍨⊥⊖0 2⊤…⎕]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862tP@qysABdSjH3UtedTTZWh0ePuj3hVm2oenA6lHXUsfdU0zUDACSTYsA6qL/Q/U8z@Ny9DIQMEAAA "APL (Dyalog Extended) – Try It Online")
Takes the inputs in reverse(-1 byte).
-1 byte from Bubbler(`.5+12÷⍨ → 12÷⍨6+`)
Generates the sequence in the same way as the existing J solution, except Bubbler shortened it with some math [explained here.](https://chat.stackexchange.com/transcript/message/56022229#56022229)
Uses '⎕' as the display character. If '█' is required, then it becomes 27 bytes(does look nicer with it).
## Explanation
```
' ⎕'[⊤⌊12÷⍨6+×⍨⊥⊖0 2⊤…⎕]
⎕ take the second and first inputs
… create an inclusive range between them
0 2⊤ encode into parts of 0 & 2
⊖ reverse the columns
⊥ decode from base 2
(this calculates (n+3×(n%2))/2)
×⍨ square that
⌊12÷⍨6+ divide by 12, round to the nearest integer
⊤ encode in base 2
(this gives a binary matrix witht the required graph)
' ⎕'[ ] convert 0s to ' ' and 1s to '⎕'
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** [Update the question](/posts/3994/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange.
Closed 11 years ago.
[Improve this question](/posts/3994/edit)
Write a code golf task such that
1. The only input (if any) required by the task is text from standard input, and the only output required by the task is text to standard output.
2. There is exactly one correct output string of characters for every possible legal input as defined by the task.
3. Each possible legal input is less than 10000 characters long.
4. Each correct output is less than 10000 characters long.
5. **The shortest program** (that StackExchange users manage to write) **that successfully completes the task** for every input **is in Java.**
The task with the shortest associated Java program wins.
[Answer]
# 48 characters
**Task:** Ignore any input. Always produce exactly the following output:
```
java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
at M.<init>(M.java:1)
at M.<clinit>(M.java:1)
```
**Solution:**
```
enum M{M;System x;{x.setErr(x.out);int y=1/0;}}
```
Save as `M.java`, compile with `javac M.java` and run with `java M`. It also produces an error message on standard error, but that doesn't violate any of the rules.
] |
[Question]
[
# Scramble a Megaminx!
A megaminx is a dodecahedral version of the familiar Rubik's cube. Since 2008, the World Cube Association uses [Stefan Pochmann's](https://codegolf.stackexchange.com/users/40544/stefan-pochmann) [megaminx scrambler](https://www.stefan-pochmann.info/spocc/other_stuff/tools/scramble_megaminx/). The scrambles look like this:
```
R-- D++ R++ D-- R++ D-- R++ D++ R-- D-- U'
R++ D-- R++ D-- R-- D++ R-- D-- R-- D-- U'
R++ D++ R-- D++ R++ D++ R++ D++ R-- D++ U
R-- D-- R++ D++ R++ D++ R-- D++ R++ D++ U
R-- D++ R++ D-- R++ D-- R++ D++ R++ D++ U
R++ D++ R++ D++ R-- D-- R-- D-- R-- D-- U'
R-- D++ R-- D++ R++ D++ R++ D++ R++ D++ U
```
A scramble has seven lines. Each line has 10 R and D moves, starting with R and alternating R and D moves. Following each letter is randomly chosen direction `++` or `--` with equal probability. At the end of the line is randomly chosen with equal probability `U` (trailing space form `U` allowed) or `U'`. A trailing newline at the end of the output is permitted.
Your code must take no input and must produce a random scramble.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~73~~ 71 bytes
*Saved two bytes thanks to @vrintle (one directly and another with further golfing)*
```
77.times{|i|$><<(~i%11>0?:RD[i%2]+'+-'[rand 2]*2+' ':?U+?'*rand(2)+$/)}
```
[Try it online!](https://tio.run/##KypNqvz/39xcryQzN7W4uiazRsXOxkajLlPV0NDOwN4qyCU6U9UoVltdW1c9uigxL0XBKFbLSFtdQd3KPlTbXl0LJKZhpKmtoq9Z@/8/AA "Ruby – Try It Online")
`$/` is the input record separator, which is a newline by default.
---
In Ruby 2.7 (newer than the version on TIO), we get 70 bytes using numbered block parameters:
```
77.times{$><<(~_1%11>0?:RD[_1%2]+'+-'[rand 2]*2+' ':?U+?'*rand(2)+$/)}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 91 bytes
```
from random import*
for C in[choice]*7:print' '.join(c+C('+-')*2for c in'RD'*5),'U'+C("' ")
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocaXlFyk4K2TmRSdn5Gcmp8ZqmVsVFGXmlagrqOtl5WfmaSRrO2uoa@uqa2oZgdQmA9WqB7moa5lq6qiHqgMlldQVlDT//wcA "Python 2 – Try It Online")
Alternatively:
```
from random import*
C=choice
exec'print" ".join(c+C("+-")*2for c in"RD"*5),"U"+C("\' ");'*7
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocTnbJmfkZyancqVWpCarFxRl5pUoKSjpZeVn5mkkaztrKGnrKmlqGaXlFykkK2TmKQW5KGmZauoohSqBJGPUFZQ0rdW1zP//BwA "Python 2 – Try It Online")
**[Python 2](https://docs.python.org/2/), 92 bytes**
```
from random import*
C=choice
for c in('RD'*5+'U')*7:print c+[C("+-")*2,C("' ")+"\n"][c>"T"],
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocTnbJmfkZyancqXlFykkK2TmaagHuahrmWqrh6praplbFRRl5pUoJGtHO2soaesqaWoZ6QBZ6gpKmtpKMXlKsdHJdkohSrE6//8DAA "Python 2 – Try It Online")
**[Python 2](https://docs.python.org/2/), 92 bytes**
```
from random import*
for C in[choice]*7:
for c in'RD'*5:print c+C('+-')*2,
print'U'+C("' ")
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocaXlFyk4K2TmRSdn5Gcmp8ZqmVtxKYAEk4GC6kEu6lqmVgVFmXklCsnazhrq2rrqmlpGOlwKYDH1UHWgoJK6gpLm//8A "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 68 bytes
```
say+(map{map$_.("++ ","-- ")[rand 2],R,D}0..4),U,"'"x rand 2for 0..6
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJbIzexoBqIVeL1NJS0tRWUdJR0dRWUNKOLEvNSFIxidYJ0XGoN9PRMNHVCdZTUlSoUIBJp@UUKQGGz////5ReUZObnFf/X9TXVMzA0AAA "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~135~~ ~~132~~ ~~124~~ ~~123~~ 119 bytes
* -12 thanks to ceilingcat
* -1 by rearranging the inner `for` terms
For each line, I start with `R++` and then flip `R`=>`D` and `++`=>`--` (half the time). This continues ten times and concludes with either `U` or `U'`. Instead of doing string operations, I use XOR for all the manipulations and print the integer as a reinterpreted string.
```
f(j){long i,k=7;for(srand(time(0));k--;puts(rand()%2?"U'":"U"))for(j=10,i=' ++R';j--;printf(&i))i^=22+rand()%2*394752;}
```
[Try it online!](https://tio.run/##NcvfCoIwFIDxe59iDMpz0oGtQmqM3iHwNpDZ5PhnhlpdiK/eyqDbj99nRGmM9xYqnJrOlYziWqfKdj0Mfe4KGKm9QYKoaiHU/TEO8Mu4kmeehfzEM4648Epvk5h0yKLoEqpq0T250cKaEOmqpYz@52Z33KcHqWb/BazNycGzowLZFDBmAVUw@7exTV4OXrw@ "C (gcc) – Try It Online")
[Answer]
# [Python 3.6], 144 121 120 111 bytes
*Huge reduction thanks to Sisyphus, and qwr*
```
from random import*
d=choice
for r in range(35):print(end=f"R{d('-+')*2} D{d('-+')*2} "+r%5//4*f"U{d(' !')}\n")
```
[Try it online](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocaXYJmfkZyancqXlFykUKWTmgRSkp2oYm2paFRRl5pVopOal2KYpBVWnaKjraqtrahnVKrggc5S0i1RN9fVNtNKUQkHiCorqmrUxeUqa//8DAA)
Each time through the loop prints one pair of entries, one `R` and one `D`. The `r%5//4*f*` control takes care of conditionally printing the `U` entry and the end of line.
[Answer]
# [R](https://www.r-project.org/), 87 bytes
```
s=sample;for(i in 1:7)cat(paste0(c("R","D"),s(c("++","--"),10,T)),s(c("U","U'"),1),"
")
```
[Try it online!](https://tio.run/##K/r/v9i2ODG3ICfVOi2/SCNTITNPwdDKXDM5sUSjILG4JNVAI1lDKUhJR8lFSVOnGMTR1gbydHWBXEMDnRBNqGgoUDBUHSSoqaPEpaT5/z8A "R – Try It Online")
[R](https://www.r-project.org/)'s `paste0` function (to paste text strings together without separator) is conveniently vectorized, so we can exploit [R](https://www.r-project.org/)'s element recycling when the two arguments are different lengths: in this case, the 2-element vector `R,D` is automatically recycled 5 times when `paste0`-ed with the 10-element vector created by `sample`-ing `++,--` ten times. The `T` argument to `sample` indicates that sampling with replacement is `T`rue (needed to take 10 samples from 2-elements).
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 40 bytes
```
7*$(5*$(R-- D-- )U'¶
/--/_?&K`++
%?&`'
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8tcS0XDFIiDdHUVXIBYM1T90DYufV1d/Xh7Ne8EbW0uVXu1BHWu//8B "Retina – Try It Online") Explanation:
```
7*$(5*$(R-- D-- )U'¶
```
Insert 7 lines consisting of `R-- D--` repeated 5 times followed by `U'`.
```
/--/_?&K`++
```
Match each `--` and then randomly replace each one with `++`.
```
%?&`'
```
On each line, randomly delete `'`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 56 bytes
```
''' '[?7/2],⍨'U',⍨7 10⍴,/⍉2 70⍴(2/¨'+-')[?70/2],⍨70⍴'RD'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@6urqCerS9ub5RrM6j3hXqoeogylzB0OBR7xYd/Ue9nUYK5iC2hpH@oRXq2rrqmkDVBlDlYBn1IBd1kGH/0wA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# JavaScript (ES6), 92 bytes
```
f=k=>k>69?'':'RD'[k&1]+((r=Math.random()*4)&1?'++ ':'-- ')+(k%10>8?r&2?`U'
`:`U
`:'')+f(-~k)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbb1i7bzszSXl3dSj3IRT06W80wVltDo8jWN7EkQ68oMS8lP1dDU8tEU83QXl1bWwGoTFdXQV1TWyNb1dDAzsK@SM3IPiFUnSvBKiEUSKgDpdI0dOuyNf8n5@cV5@ek6uXkp2ukaWhq/gcA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 93 bytes
A non-recursive approach.
```
_=>`RDRDRDRDRDU
`.repeat(7).replace(/./g,c=>c+[['++ ','-- ',"'"][Math.random()*2|2*(c>'R')]])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i4hyAUGQ7kS9IpSC1ITSzTMNUGsnMTkVA19Pf10nWRbu2Tt6Gh1bW0FdR11XV0gqaSuFBvtm1iSoVeUmJeSn6uhqWVUY6SlkWynHqSuGRur@T85P684PydVLyc/XSNNQ1PzPwA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
E⁷⪫⮌E¹¹⎇λ⁺§RDλײ‽+-…U'⊕‽²
```
[Try it online!](https://tio.run/##LcvBCoMwEATQX1ly6YbGg1566KnYi0JBpP2AkCwYSDYSrdSvT1PpHGfemEknE7XPeUiOV3zoGS8K@ugYR9ooLXR0da3gSYl12tErGPx7wdvasaUPivEuFHhZhAu0YKNg1GxjQHGuhJRlaHfjqZ3ijOJ1KrhjkygQr2Txbxt5RIGA3@eac642/wU "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⁷ Literal `7`
E Map over implicit range
¹¹ Literal `11`
E Map over implicit range
RD Literal string `RD`
§ λ Indexed by inner index
⁺ Concatenated with
+- Literal string `+-`
‽ Random character
ײ Duplicated
⎇λ Except for the first entry use
U' Literal string `U'`
… Truncated to length
‽² Random integer less than 2
⊕ Incremented
⮌ Reversed (so `U` is now last)
⪫ Joined with spaces
Implicitly print on separate lines
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~113~~ ~~97~~ 126 bytes
Saved 6 bytes thanks to [qwr](https://codegolf.stackexchange.com/users/17360/qwr)!!!
Added 29 bytes to fix an error kindly pointed out by [qwr](https://codegolf.stackexchange.com/users/17360/qwr).
```
from random import*
f=lambda n=5,r=choice:n and f"R{r('-+')*2} D{r('-+')*2} "+f(n-1)or'U'+r(" '")
for i in range(7):print(f())
```
[Try it online!](https://tio.run/##TY1BCsIwEADvfcWSS3Ybe1ARoZCbLxB8QGy7NmA2YclFxLfHevM0DAxMedU1y7E11pxAg8wbYipZa9@xf4Z0nwOIP@3UT2uO0zIKbBWwub4V7eAs9YcPXP7FOEYZ9pTV3qxTNGANdZwVIkT5XR4LnmksGqUiI1FrXw "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/iki/Code-page)
```
7µ5,6ṁ11ż2Xx¤€$+0¦2ị“+-' RDU”KFṖ)Y
```
**[Try it online!](https://tio.run/##ATsAxP9qZWxsef//N8K1NSw24bmBMTHFvDJYeMKk4oKsJCswwqYy4buL4oCcKy0nIFJEVeKAnUtG4bmWKVn//w "Jelly – Try It Online")**
### How?
```
7µ5,6ṁ11ż2Xx¤€$+0¦2ị“+-' RDU”KFṖ)Y - Link: no argments
7 - seven
µ ) - for each (v in [1..7]):
5,6 - [5,6]
ṁ11 - mould like 11 -> [5,6,5,6,5,6,5,6,5,6,5]
$ - last two links as a monad:
€ - for each:
¤ - nilad followed by link(s) as a nilad:
2 - two
X - random integer (from [1,2])
x - repeat (two) times -> [1,1] or [2,2]
ż - zip together -> [[5,[2,2]],[6,[1,1],...]
0¦ - apply to index 0 (rightmost):
+ 2 - add two (e.g. [5,[1,1]] -> [7,[3,3]])
“+-' RDU” - "+-' RDU"
ị - index into (i.e. 1 -> '+' ... 7 -> 'U')
K - join with space characters
F - flatten
Ṗ - pop (remove the repeated space or quote from the right)
Y - join with newline characters
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 28 bytes
```
V7jd+m+@"RD"d*2O"+-"T+\UO" '
```
[Try it online!](https://tio.run/##K6gsyfj/P8w8K0U7V9tBKchFKUXLyF9JW1cpRDsm1F9JQf3/fwA "Pyth – Try It Online")
```
V7jd+m+@"RD"d*2O"+-"T+\UO" '
V7 Perform the following 7 times:
m T Map d over 0-9:
O"+-" Choose + or - at random
*2 Double it
@"RD"d Choose R for even d, D for odd
+ Concatenate the previous two results
O" ' Choose space or ' at random
+\U Append to "U"
+ Append the previous result to the list of moves
jd Join the list on spaces, implicit print with newline
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~24~~ 23 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
7{ûRD5*môû+-w∞ ûU'1w╛╡n
```
[Try it online.](https://tio.run/##AS0A0v9tYXRoZ29sZv//N3vDu1JENSptw7TDuystd@KIniDDu1UnMXfilZvilaFu//8)
Could be 22 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) if we're allowed to output in lowercase instead of uppercase, by changing the `ûRD` to `╢x` (and `U'` to `u'`): [try it online.](https://tio.run/##AS0A0v9tYXRoZ29sZv//N3vilaJ4NSptw7TDuystd@KIniDDu3UnMXfilZvilaFu//8)
**Explanation:**
```
7{ # Loop 7 times:
ûRD # Push string "RD"
5* # Repeat it 5 times: "RDRDRDRDRD"
m # Map over each character,
ô # using the following six character as inner code-block:
û+- # Push string "+-"
w # Pop and push a random character from this string
∞ # Double it
# Push a space character " "
ûU' '# Push string "U'"
1w # Push a random integer in the range [0,1]
╛ # If this integer is truthy (thus 1):
╡ # Discard the right character of the string
n # Push a newline character "\n"
# (after the loop, the entire stack joined together is output
# implicitly as result)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
**Credit goes to Kevin Cruijssen for coming up with this way shorter program!**
```
„RDÞε„+-Ωº«}Tôε„U'ηΩª}7£»
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcO8IJfD885tBTK0dc@tPLTr0OrakMNbwAKh6ue2A4VW1ZofWnxo9///AA "05AB1E – Try It Online")
# How this?
```
„RDÞ # Push RDRDRDRDRDRDRDRDRDRD... as a list
ε } # For every R or D:
„+-Ω # Pick random from + and -
º # Double the sign
« # And join it to the R or D
Tô # Split the list into pieces of 10 elements
ε } # For each item in the list:
„U'ηΩ # Choose a random choice between U' & U
ª # Append it to the list
7£» # Join the first 7 lists with linefeeds
# Print the result at the end (implicitly)!
```
---
My old program:
# [05AB1E](https://github.com/Adriandmen/05AB1E), 36 bytes
```
8G„RD5×S"++ -- "3ôTи2ô€ΩøJ…U'U2ôΩªJ,
```
[Try it online!](https://tio.run/##AT0Awv9vc2FiaWX//zhH4oCeUkQ1w5dTIisrIC0tICIzw7RU0Lgyw7TigqzOqcO4SuKAplUnVTLDtM6pwqpKLP// "05AB1E – Try It Online")
# How that?
```
8G # Repeat 7 times the full code
„RD5× # Push "RDRDRDRDRD"
"++ -- "3ô # Push the list/array ["++ ", "-- "]
Tи2ô # Repeat the list 10 times
€Ω # Pick a random item from each list
S øJ J # Zip the random items with "RDRDRDRDRD"
# e.g => "R++ D-- R++ D-- R++ D-- R++ D-- R++ D-- "
…U'U2ôΩ # Pick random between "U'" and "U"
ª # Append the result to the last result
, # Print it with a linefeed
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 40 bytes
```
7"RD""35"≈*⌠"+-"Jτ+R⌡M╡⌠2"UU'"╡J@+' j⌡Mi
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/99cKchFScnYVOlRZ4fWo54FStq6Sl7nW7SDHvUs9H00dSFQyEgpNFRdCcj2ctBWV8gCSWT@/w8A "Actually – Try It Online")
```
"RD" # Push RD,
"35"≈* # and repeat it 35 times.
⌠ ⌡M # For each turn,
⌠"+-"J ⌡M # pick either + or -,
⌠ τ ⌡M # double it,
⌠ +R⌡M # and add it to the end of each turn.
7 ╡ # Split the list into 7 sublists (of length 10).
⌠ ⌡M # For each sublist,
⌠2"UU'"╡J ⌡M # pick either U or U',
⌠ @+ ⌡M # add it to the end of each turn,
⌠ ' j⌡M # and join with spaces.
i # Push each sublist to the stack.
# Implicitly output the stack joined with newlines.
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 86 bytes
A golfed version of [xnor's answer](https://codegolf.stackexchange.com/a/216302/83605), which he didn't approved. Perhaps, because his answer is in Python 2.
```
from random import*
for C in[choice]*7:print(*(c+C('+-')*2for c in'RD'*5),'U'+C("' "))
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P60oP1ehKDEvBUhl5hbkF5VocaXlFyk4K2TmRSdn5Gcmp8ZqmVsVFGXmlWhoaSRrO2uoa@uqa2oZgVQlA1WpB7moa5lq6qiHqgMlldQVlDQ1//8HAA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~78~~, 75 bytes
Saved **3 bytes** by modifying the jump in the third line and changing how the register was checked and decremented.
```
7_a*&"DR"d1. >x"-"v
>x"'"oao&:&?!;^\"+">$:o$:oo$" "od1&1-:&a%?.~~"U"o
.>51
```
New link:
[Try it online!](https://tio.run/##S8sszvj/3zw@UUtNySVIKcVQT0HBrkJJV6mMC0ipK@Un5qtZqdkrWsfFKGkr2alY5QNRvoqSglJ@iqGaoa6VWqKqvV5dnVKoUj6Xnp2p4f//AA "><> – Try It Online")
Old link: [Try it online!](https://tio.run/##S8sszvj/3zw@UUtNySVIKcVQT0HBrkJJV6mMC0ipK@Un5qtZqdkrWsfFKGkr2akZ6qqpWOUDUb6KkoJSfoohUDZR1V6vrk4pVCmfS8HO1FDv/38A "><> – Try It Online")
This code also runs in [\*><>](https://github.com/redstarcoder/go-starfish) (Starfish) because [\*><>](https://github.com/redstarcoder/go-starfish) is a super set of [><>](https://esolangs.org/wiki/Fish).
\*><>: [Try it online!](https://tio.run/##Ky5JLErLLM74/988PlFLTcklSCnFUE9Bwa5CSVepjAtIqSvlJ@arWanZK1rHxShpK9mpWOUDUb6KkoJSfoqhmqGulVqiqr1eXZ1SqFI@l56dqeH//wA "*><> – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 25 bytes
```
₀(‛RD5*ƛ‛+-℅d+;\U‛U'"℅JṄ,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%82%80%28%E2%80%9BRD5*%C6%9B%E2%80%9B%2B-%E2%84%85d%2B%3B%5CU%E2%80%9BU%27%22%E2%84%85J%E1%B9%84%2C&inputs=&header=&footer=)
## Explanation
```
₀(‛RD5*ƛ‛+-℅d+;\U‛U'"℅JṄ,
( For n
₀ in range(10):
‛RD Push "RD"
5* Repeat 5 times
ƛ ; Map:
‛+- Push "+-"
℅ Choose random
d Double
+ Concatenate top two
\U Push "U"
‛U' Push "U'"
" Join top two into a pair
℅ Choose random
J Join top two
Ṅ Join with spaces
, Print
```
[Answer]
# [Nim](http://nim-lang.org/), 129 bytes
```
import random
randomize()
for _ in 0..6:
var l=["U","U'"].sample
for i in 0..9:l="RD"[i mod 2]&["++","--"].sample&" "&l
echo l
```
[Try it online!](https://tio.run/##y8vM/f8/M7cgv6hEoSgxLyU/lwtCZValamhypeUXKcQrZOYpGOjpmVlxKZQlFink2EYrhSrpKIWqK8XqFSfmFuSkcimAFGZCFVpa5dgqBbkoRWcq5OanKBjFqkUraWsDdejqwnWoKSkoqeVwKaQmZ@Qr5Pz/DwA "Nim – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 27 bytes
```
⁵µ⁾RDẋ5;⁾+-XḤ¤$€“U“U'”X¤ṭ)G
```
[Try it online!](https://tio.run/##y0rNyan8//9R49ZDWx817gtyebir29QayNLWjXi4Y8mhJSqPmtY8apgTCsLqjxrmRhxa8nDnWk33//8B "Jelly – Try It Online")
## Explanation
```
⁵µ⁾RDẋ5;⁾+-XḤ¤$€“U“U'”X¤ṭ)G Main niladic link
⁵ 10 [implicitly casted to [1..10]]
µ ) Map:
⁾RD "RD"
ẋ5 Repeat 5 times
€ Map
$ (
; Join with
¤ (
⁾+- "+-"
X Choose random
Ḥ Unhalve (double)
¤ )
$ )
ṭ Append
¤ (
“U“U'” ["U", "U'"]
X Choose random
¤ )
G Format as a grid
```
] |
[Question]
[
# Summary
Videos which are sped up every time a particular word is said exist for everything from [the Bee Movie](https://www.youtube.com/watch?v=JMG1Nl7uWko) to the classic [Rick Roll](https://www.youtube.com/watch?v=ZXpThNX9IRc). The goal for this challenge is to figure out how much you'd have to slow down the sped-up video in order to match the duration of the original video.
For example, the original Bee Movie has a duration of 95 minutes. The sped up version is 5:40 or ~5.667 minutes. 95/5.667 = 16.76. We'd have to play the sped up version 16.76x slower in order for the overall duration to match the original movie.
# Inputs
Your program must take in 3 inputs:
1. The duration of the original video (Bee Movie was 95 minutes)
2. The speedup factor per occurence (Bee Movie was 15% or .15)
3. A list of timestamps of occurrences (Bee movie has more than I care to look up/list)
The exact way these are passed in is flexible: 3 separate parameters is my default assumption, but if you want to take in a single list of values and pop the duration/speedup factor off the front that's fine, or take a single string in JSON or whatever format floats your boat, etc.
For the duration: seconds, minutes, or some builtin duration type are all fine.
For the speedup factor of the bee movie, any of 15, .15, or 1.15 could be used to represent the 15% speedup.
You can assume the occurrences are ordered in the most convenient manner, but there *can* be duplicate values (such as multiple characters talking over one another in a movie).
# Output
A scaling factor to make the durations of the original and sped-up video match. The exact format is flexible.
# Examples
```
{"duration": 10, "speedup-factor": 2, "occurrences": [1,2,3,4,5,6,7,8,9]} -> {"slowdown-factor": 5.004887585532747}
{"duration": 500, "speedup-factor": 1.15, "occurrences": [1,2,3, ..., 497, 498, 499]} -> {"slowdown-factor": 65.21739130434779}
{"duration": 100, "speedup-factor": 3, "occurrences": [0]} -> {"slowdown-factor": 3}
{"duration": 100, "speedup-factor": 3, "occurrences": [0, 0, 0]} -> {"slowdown-factor": 27}
{"duration": 100, "speedup-factor": 100, "occurrences": [99.99]} -> {"slowdown-factor": 1.0000990098}
```
Notes: First two generated programmatically with `100/(sum(1/(2**i) for i in range(10)))` and `500/(sum(1/(1.15**i) for i in range(500)))`. 4th example: 3 \* 3 \* 3 = 27x speedup, occurring right at the start of the video. Last example calculated by hand with `100/(99.99 + .01/100)`
# Note
I've kept most of the examples fairly simple, but I believe they cover all the relevant edge cases (a program which solves all of them should be totally correct). If I've left things ambiguous or difficult to parse, let me know and I'll add comments!
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
lambda m,r,l:m/reduce(lambda u,x:u/r+x-x/r,l,m)
```
[Try it online!](https://tio.run/##fdbNahxXFIXReZ6ih1JSsWrvU/0nyJMoHjixjAWWY4RFnKdXeikeBAKB5jZU9TfpVfee@vLX149/fO7Lh19@ffn07vG39@92j8vT8un28ebp/v3z7/dX368@L99un2@efvr287eby/3l8frlz48Pn@53uf3y9PD56@7D1Y8Pn788f726vn65yvpmXXa13J2X3WnZHZfdYdntl9227OZya9nl7fUPV/v19Zd5k8utu@18@fF2PlmOloNFdN4sY6kllku4nRQnxUlxUpwUJ8VJcVKcFCfFUXFUHBVHxVFxVBwVR8VRcVQcFAfFQXFQHBQHxUFxUBwUB8VesVfsFXvFXrFX7BV7xV6xV2yKTbEpNsWm2BSbYlNsik0xilGMYhSjGMUoRjGKUVRRRRVVVFFFFVVUUUUUUUQRBaktiiiiiCKKVbEqVsWqWBWrYlWsilWxXophPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIv8zIP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zAP8zBHThw4b9y0YbNGTRo0Z8yUITNGTBgwX7x04bJFSxYsV6xUoTJFShQoT5w0YbJESRIkR4wUITJE@DqdX18yvA4Y8Ea2IWysGpRGn2FmPBk4Roih4Jh3cDuKHa6OSwegI80h5dhxkDgabHbb14a0xWwa28CD7VH18HmcPCDIIWLxR1/@w/97xco/r1jz@jK2/vfKsvP51/XvX3fn85vz@e313w "Python 2 – Try It Online")
Takes timestamps sorted in descending order.
The idea is to compute the video duration as a polynomial in the inverse speedup rate `1/r` using [Horner's method](https://en.wikipedia.org/wiki/Horner%27s_method) with coefficients given by the sorted timestamps. This avoids needing to explicitly take the differences of consecutive timestamps. We then divide the duration of the original video by the resulting duration to get the desired slowdown factor.
**53 bytes**
```
f=lambda m,r,l:l==[]or r/(l.pop()*(r-1)/m+1/f(m,r,l))
```
[Try it online!](https://tio.run/##fdbNahxXFIXReZ6ihi2nLdU@u/rP4CcRHjgkxgZJFsIh5OmVXkoGgUCguQ1d9U161b2nnv/88fX707y@fvn48Pnxl18/L4/7l/3Dh4ePH@8/fX9ZXu52D7fP3593N@92L@9zc/f4c@6@7N5uurl5/ePrt4fflnx4fvn29GP5snv37en59x@765Vd1tt1v4zl/rJfzvvltF@O@@WwX7b90uul/ZJPNz/tDuvbnbnN9dL9drnevF3OlpPlaBFdNkstY4nlGm5nxVlxVpwVZ8VZcVacFWfFWXFSnBQnxUlxUpwUJ8VJcVKcFEfFUXFUHBVHxVFxVBwVR8VRcVAcFAfFQXFQHBQHxUFxUBwUm2JTbIpNsSk2xabYFJtiU1RRRRVVVFFFFVVUUcUoRjGKUYxiFKMYxShGEUUUUURBaosiiiiiiGJVrIpVsSpWxapYFatiVazXoszLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLvMzLfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zMM8zJETB84bN23YrFGTBs0ZM2XIjBETBswXL124bNGSBcsVK1WoTJESBcoTJ02YLFGSBMkRI0WIDBG@Tee3lwyvAwa8kW0IG6sGpdFnmBlPBo4RYig45h3cjmKHq@PSAehIc0g5dhwkjgab3fa1IW0xm8Y28GB7VD18HicPCHKIWPzR1//w/16x8vcrVt9extb//rJffP71@z9f95fL7eXy6eYv "Python 2 – Try It Online")
An attempt to write the function fully recursively. While the new duration itself has a clean recursive expression, we want to get the slowdown factor which divides the original duration by the new duration, and this is messier to express recursively.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;ŻIṚḅ⁵ݤ÷@
```
A full program accepting `timestamps original-duration speedup-factor` which prints the necessary slowdown-factor.
**[Try it online!](https://tio.run/##ATYAyf9qZWxsef//O8W7SeG5muG4heKBtcSwwqTDt0D///9bMSwyLDMsNCw1LDYsNyw4LDld/zEw/zI "Jelly – Try It Online")**
### How?
Get a list of the durations of film separated by the occurrences (including any zero-length segments), reverse and convert from base slowdown-factor (where this slowdown-factor is the inverse of the given `speedup-factor`), then divide the `original-duration` by that.
```
;ŻIṚḅ⁵ݤ÷@ - Main link: timestamps S, original-duration T
; - concatenate (T) to (S) -> S+[T]
Ż - prefix with a zero (the start of the film) -> [0]+S+[T]
I - deltas -> [S[1]-0, S[2]-S[1], ..., S[n]-S[n-1], T-S[n]]
Ṛ - reverse -> [T-S[n], S[n]-S[n-1], ..., S[2]-S[1], S[1]-0]
¤ - nilad followed by link(s) as a nilad:
⁵ - 3rd argument = speedup-factor
İ - inverse -> 1/speedup-factor - call this F
ḅ - convert from base -> (T-S[n])×F^(n)+(S[n]-S[n-1])×F^(n-1)+...+(S[2]-S[1])×F^1+(S[1]-0)×F^0
@ - using swapped arguments (with implicit right argument T):
÷ - division -> T/((T-S[n])×F^(n)+(S[n]-S[n-1])×F^(n-1)+...+(S[2]-S[1])×F^1+(S[1]-0)×F^0)
- implicit print
```
[Answer]
# [Haskell](https://www.haskell.org/), 32 bytes
```
m%r=(m/).foldr(\x u->u/r+x-x/r)m
```
[Try it online!](https://tio.run/##fdbNThxXEIbhva@iF7E0KA101ff1nxRyI4QFcoxjZcZBA5ZY5NozqbfIIlKkSBa24C0w5@lzTv/2@PL75@Pxcjl9PN8dTrdXN09/HH89H355G75f//z99vzj2/Xb7fnqdHn9/PL6MtwN94eYbqZxSD7cR/1jHDQOHod5HJZxWMdhG4f94Wo8zFOXcRPz/6VVUNXXo4KoIiphJiqKqqKyqC75uXyf6rK6rC6ry@qyuqwuq1N1qk78wOpUnapTdapO1ak6V@fqXJ35n1Xn6lydq3N1rm6ubq5urm6ubuZXqG6ubq5urm6ubqluqW6pbqluqW7hd61uqW6pbqlurW6tbq1urW6tbq1uZVGqW6tbq9uq26rbqtuq26rbqtuq21i96rbq9ur26vbq9ur26vbq9ur26naWudeZhZ5Y6YmlnljricWeWO2J5Z5Y74kFn5h4p2GicVqnedqngVqoiTAKkCJbkwmcAqhAKqAKrAKsQCvgCrxC/QAwAVlgFqAFagFb4BbABXIBXbifGSbQC/gCvwAwEAwIA8MAMVCMuR8zJoAMJAPKwDLADDQDzsAzAI2ln0wmMA1QA9WANXANYAPZgDawjbUfZibgDXwD4EA4IA6MA@RAOWCOrZ9/JpAOqAPrADvQDrgD7wA8EI@9t0zvGTYN5ol5Yp6YJ@aJeWKemCfmGb3NmMA8MU/ME/PEPDFPzLP3ZW/M953JRO/N3py9O3t79v7sDYp5Yp6Yp3ozM4F5Yp6YJ@aJeWKemCfmiXm69z8TmCfmiXlinpgn5ol5Yp6Y59xHBhOYJ@aJeWKemCfmiXlinpjn0qcME5gn5ol5Yp6YJ@aJeWKemOfaBxMTmCfmiXlinpgn5ol5Yp6Y59ZnGROYJ@aJeWKemCfmiXlinpjn3sdfn38cgJgLc2EuzIW5MBfmwlyYK/rIZAJzYS7MhbkwF@bCXJgLc2WfskxgLsyFuTAX5sJcfSr3sdzn8vvBzEQfzX029@Hcp3Mfz5gLc2EuzOU@y5nAXJgLc2EuzIW5MBfmwlxzH/9MYC7MhbkwF@bCXJgLc2GupW8MJjAX5sJcmAtzYS7Mhbkw19qXDBOYC3NhLsyFuTAX5sJcmGvre4kJzIW5MBfmwlyYC3NhLsy191XWdxmXGebG3Jgbc2NuzI25MTfmjr7@mMDcmBtzY27MjbkxN@bG3Nk3JhOYG3NjbsyNuTE35sbcmFt9yTKBuTE35sbcmLvv5L6U@1bua/n9Xmaib@a@mvtu7ssZc2NuzI25MffcVzkTmBtzY27MjbkxN@bG3Jh76dufCcyNuTE35sbcmBtzY27MvfYLAxOYG3NjbsyNuTE35sbcmHvrdwwmMDfmxtyYG3NjbsyNuTH33q8l/YoV769Y6pex6b@fGQf@/Ovz//x1v@83fIeHD093h49XH06PX7/Vy93z@eu31@GH4f5pOA3n4Tj8ORxO43k8Xv103S@AD5e/Pj0dH7@8XK4/PT//DQ "Haskell – Try It Online")
Port of [my Python answer](https://codegolf.stackexchange.com/a/207815/20260).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 15 [bytes](https://github.com/abrudz/SBCS)
```
÷⊥⍥÷∘(⊃÷2-/,∘0)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qi2fYo7YJhv8Pb3/UtfRR71Ig3TFD41FX8@HtRrr6OkCOgeb/NKCSR719QNFD640ftU0E6gsOcgaSIR6ewf@NFNIUDA0ULBUsFMwVzBRMFUwUjBWMFAy5DPUMTYFyj3r2PurdbGpgwGUMVmmggMQCQS4QC8K3tNSztAQA "APL (Dyalog Extended) – Try It Online")
# [J](http://jsoftware.com/), 16 bytes
```
#.&.:%{.%2-/\,&0
```
[Try it online!](https://tio.run/##TYpBCsIwFET3OcVDaYvQfH/SRvsDrgRXrly7Ltgr9PBpqhsZZnjDzFIOQjdzy3Q9Sq72wv31fJSjtJKbVZroz@@@1XIqkZmgGBNXLiRGBiLBBQmpbknVf6SmG75P5Y92uZ1@3UzMNg "J – Try It Online")
Inline tacit functions that take the speedup on the left, and `duration,occurrences` on the right in descending order.
Both code use the same algorithm:
```
÷⊥⍥÷∘(⊃÷2-/,∘0)
∘( ) On the right argument,
,∘0 Append zero
2-/ Take pairwise differences
⊃÷ Divide each number above by the head
(division by zero is handled by system setting ⎕DIV←1,
which gives 0.)
⊥⍥÷ Take reciprocal of both args and do base conversion
÷ Take reciprocal of that
#.&.:%{.%2-/\,&0
\----/\--------/ 2-train, so apply the right part on the right arg
,&0 Append zero
2-/\ Take pairwise differences
{.% Divide each number above by the head
(division by zero gives built-in infinity,
whose reciprocal is again zero.)
&.:% Apply % (reciprocal) to both args
#. Base conversion
&.:% Undo %, which is the same as applying % again
```
[Answer]
# [J](http://jsoftware.com/), 20 bytes
Takes the speedup on the left, and the occurrences, length on the right. Calculates the speedup factor.
```
{:@]%%@[#.2-/\0|.@,]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q60cYlVVHaKV9Yx09WMMavQcdGL/a/43UkhT0DDUztSz1NRRMDTgMtQzNIUJmVgCBU0NDLiMgSIGOoYwFgiCeUAM5Fta6llagvgA "J – Try It Online")
### How it works
```
{:@]%%@[#.2-/\0|.@,] 2 f 50 100
0 ,] prepend 0: 0 50 100
|.@ reverse: 100 50 0
2-/\ differences: 50 50
%@[ 1/n: 0.5
#. to base: 75
{:@] last element:100
% 100/75: 1.3333
```
[Answer]
# [R](https://www.r-project.org/), 49 bytes
```
function(d,f,o)d/diff(c(0,o,d))%*%f^-c(0,seq(!o))
```
[Try it online!](https://tio.run/##RYyxDsIwDER3vqIMlWzkFifQIQh@haXGKEsNpHx/cJAQsiz5nu/uVe2xZlsKSL7ntVxixI1256Gr@l7m9gIhJUPZS1aFGZiMBLHf9Xodmiy3J2wNsSoEpkjhlLwDJmYKY5hcH9OXBCcH4v/Z0j74I21TGt1dPw "R – Try It Online")
Takes the original `d`uration, the speedup `f`actor, and the `o`currences.
Calculates the time between each occurrence `diff(c(0,o,d))`, then multiplies them with the appropriate speedup factors `f^-c(0,seq(!o))` and sums them as a dot product `%*%`. Finally divides `d` by that result.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
chQu+c-GHeQHEh
```
[Try it online!](https://tio.run/##K6gsyfj/PzkjsFQ7WdfdIzXQwxXI1zA0MNAz0FEw1jPQ5Io2iP2XX1CSmZ9X/F83BQA "Pyth – Try It Online")
Port of [@xnor's answer](https://codegolf.stackexchange.com/a/207815/91267) to [Pyth](https://github.com/isaacg1/pyth)
## Explanation
```
chQu+c-GHeQHEh
hQ : First element from first input
c : divided by
u : value got by reducing from left to right
E : the second input
h : with default value as first input
: on lambda G, H:
-GH : G - H
c eQ : divided by second element from first input
+ H : plus H
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~35~~ 33 bytes
```
s#/Fold[#/s+#2&,{##}-{##2,0}]&
```
[Try it online!](https://tio.run/##RU1LCsIwFNz3Gg@ycbTpT81CiRuXouuQRdAWC1ahrQsJuYQ38IQeISYiuJhh5s0MrzPjue7M2B6Nb1Z@eD9flG5vl5OidJhQzmCJ3DRQDu4084d7W49y37fXUX2j9U41irQKDa01k1LaxObIOASWWGCOCiUKhJNDYrNZVqHiHJu@Nw9FDKUQsJFCTsR0bBVhz8PDv8TPRhMhxEwIlzj/AQ "Wolfram Language (Mathematica) – Try It Online")
Takes input as `f[s][d,o]`, where `o` is a sequence of arguments in decreasing order.
[Answer]
# [Io](http://iolanguage.org/), 49 bytes
Port of xnor's Python answer.
```
method(m,r,l,m/l prepend(m)reduce(u,x,u/r+x-x/r))
```
[Try it online!](https://tio.run/##hdbNahxXFIXRuZ@ihhKpWLXPruqfQN4ks1gmBvkH2Qa/vaIlmySDhEBzG9T9adCr7j333cent8svvy6/Pb2///LHxzc379fH9WF9f/ewfHq8/3T/4fkvt4/3b77@fn/zdf22fr17/Onbz9/uHm9vn97eZHu9rctYHt59/nJzXZfLupzX5bQux7rs69Lnj9clt7efHt99@PLw4dWrtzfH9pLldY4f3X59LvfrxXK2nCz@w3W31DKWWJ7j/aK4KC6Ki@KiuCguioviorgozoqz4qw4K86Ks@KsOCvOirPipDgpToqT4qQ4KU6Kk@KkOCkOxaE4FIfiUByKQ3EoDsWh2BW7Ylfsil2xK3bFrtgVu6KKKqqooooqqqiiiipGMYpRjGIUoxjFKEYxiiiiiCIKWnsUUUQRRRSbYlNsik2xKTbFptgUm2J7Lsq8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zMu8zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mw3yYD/NhPsyH@TAf5sN8mA/zYT7Mh/kwH@bDfJgP82E@zIf5MB/mwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwzzMwxw5ceC8cdOGzRo1adCcMVOGzBgxYcB88dKFyxYtWbBcsVKFyhQpUaA8cdKEyRIlSZAcMVKEyBDhy3R@uWS4DhjwRrYhbKwalEafYWY8GThGiKHgmHdwO4odro5LB6AjzSHl2HGQOBpsdtvXhrTFbBrbwIPtUfXweZw8IMghYvFDP/@G/33fWv5x4cr3C1f/uqdt//f5unj967d@vH2/711fX69/f@vpTw "Io – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 11 bytes
*-4 bytes thanks to @KevinCruijssen's port of @JonathanAllan's Jelly answer*
```
ª0š¥RIzβ¹s/
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0CqDowsPLQ3yrDq36dDOYv3//w0NuKINdYx0jHVMdEx1zHTMdSx0LGO5jAA "05AB1E – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
¤UćV0š¥εyYNm/}OXs/
```
Explaination:
```
¤UćV0š¥εyYNm/}OXs/
¤U Extract tail and save duration in X
ćV Extract head and save speedup factor in Y
0š Prepand 0 to the timestamps list
¥ Deltas
ε } map
y foreach element
YNm factor ** index of element
/ element / (factor ** index of element) => this will be the duration of this section
O sum all up
Xs push duration before the result
/ division
```
### Input:
A list of numbers in the format: `[speedup_factor, ... timestamps_in_minutes ... , duration_in_minutes]`
### Output:
How much we need to slow down in minutes.
[Try it online!](https://tio.run/##yy9OTMpM/f//0JLQI@1hBkcXHlp6bmtlpF@ufq1/RLH@///RRjqGOkY6xjomOqY6ZjrmOhY6ljqGBrEA)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~74~~ 69 bytes
Saved 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
float f(d,s,o,n,a)float*o,s,a;{for(a=d;n--;)a=a/s+o[n]-o[n]/s;s=d/a;}
```
[Try it online!](https://tio.run/##XZLbbqMwEIbveQpkKRKQoTGnBdax9mLVp0hQ5QbYGlFTYRRFG/HsqW0OKsEyMP7@GY89c/H/XS6PR912bLBrpwQJHQhgrlnxOmUzcq@73mG0JML3icsoO8h9dxKFr18HSSQtD4yMj6@ei8FplT931Z/XTp6cYsKPguz33DWS2kE7uSsR8D/IRr8RgvbEC5eM1pTHUMnhTZ4Keg8hUiPAeATLNo9hHdYwAI1jSOAXpJBB/iQKtejZMzKLoMYTiDXIc8jXMN4ETCLztjBHnr/R/I3XWNXtq7oNVal9kheM4yxLkyxJojCNU5VtmEKgljHOczWzkVgmgtEHWJ90mSqkQUIjyf9XXb0c/jCZ3pLUhoZbGm5ptKXRlsZbGqv0Lh@s93qdAzrfXsPzLf@rZoLgpxkhpWxAEOuTceGU7t2ydeUbVfnmOG@xXM2yx2Krvmi0g13S@S6aAgSdD98URKGpLySdO0MJvI4u5VHWla6960JF1yooVFbtwGjN3qVz9StXR1ubsLZ38iwQXKE/Gd3xJSi0ZLTGxzc "C (gcc) – Try It Online")
Port of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python answer](https://codegolf.stackexchange.com/a/207815/9481).
] |
[Question]
[
This is how the Kolakoski sequence (OEIS [A000002](https://oeis.org/A000002)) is defined:
>
> The Kolakoski sequence is a sequence that contains `1` and `2`, and the `n`th element of the sequence is the length of the `n`th group of equal elements (run) in the sequence itself. The first 20 terms of the sequence and the respective lengths are:
>
>
>
> ```
> 1 2 2 1 1 2 1 2 2 1 2 2 1 1 2 1 1 2 2 1
> - --- --- - - --- - --- --- - --- --- -
> 1 2 2 1 1 2 1 2 2 1 2 2 1
>
> ```
>
> Essentially, the lengths of the groups of equal elements of the Kolakoski sequence is the Kolakoski sequence itself.
>
>
>
So far, so good, but that why should we restrict ourselves to `1` and `2`? We're not going to! Given two inputs, an array of positive integers `A` and an integer `N`, return the first `N` terms of the Kolakoski-like sequence defined by cycling through `A`. To get the grasp of it better, here is a worked example with the lengths of the newly added groups in brackets:
```
A = [2, 3, 1]
N = 25
2: [[2], 2 ]
3: [ 2 ,[2], 3 , 3 ]
1: [ 2 , 2 ,[3], 3 , 1 , 1 , 1 ]
2: [ 2 , 2 , 3 ,[3], 1 , 1 , 1 , 2 , 2 , 2 ]
3: [ 2 , 2 , 3 , 3 ,[1], 1 , 1 , 2 , 2 , 2 , 3 ]
1: [ 2 , 2 , 3 , 3 , 1 ,[1], 1 , 2 , 2 , 2 , 3 , 1 ]
2: [ 2 , 2 , 3 , 3 , 1 , 1 ,[1], 2 , 2 , 2 , 3 , 1 , 2 ]
3: [ 2 , 2 , 3 , 3 , 1 , 1 , 1 ,[2], 2 , 2 , 3 , 1 , 2 , 3 , 3 ]
1: [ 2 , 2 , 3 , 3 , 1 , 1 , 1 , 2 ,[2], 2 , 3 , 1 , 2 , 3 , 3 , 1 , 1 ]
2: [ 2 , 2 , 3 , 3 , 1 , 1 , 1 , 2 , 2 ,[2], 3 , 1 , 2 , 3 , 3 , 1 , 1 , 2 , 2 ]
3: [ 2 , 2 , 3 , 3 , 1 , 1 , 1 , 2 , 2 , 2 ,[3], 1 , 2 , 3 , 3 , 1 , 1 , 2 , 2 , 3 , 3 , 3 ]
1: [ 2 , 2 , 3 , 3 , 1 , 1 , 1 , 2 , 2 , 2 , 3 ,[1], 2 , 3 , 3 , 1 , 1 , 2 , 2 , 3 , 3 , 3 , 1 ]
2: [ 2 , 2 , 3 , 3 , 1 , 1 , 1 , 2 , 2 , 2 , 3 , 1 ,[2], 3 , 3 , 1 , 1 , 2 , 2 , 3 , 3 , 3 , 1 , 2 , 2 ]
C: [ 2 , 2 , 3 , 3 , 1 , 1 , 1 , 2 , 2 , 2 , 3 , 1 , 2 , 3 , 3 , 1 , 1 , 2 , 2 , 3 , 3 , 3 , 1 , 2 , 2 ]
```
Here is another worked example with a leading `1`:
```
A = [1, 2, 3]
N = 10
1: [[1]]
2: [ 1 ,[2], 2 ]
3: [ 1 , 2 ,[2], 3 , 3 ]
1: [ 1 , 2 , 2 ,[3], 3 , 1 , 1 , 1 ]
2: [ 1 , 2 , 2 , 3 ,[3], 1 , 1 , 1 , 2 , 2 , 2 ]
C: [ 1 , 2 , 2 , 3 , 3 , 1 , 1 , 1 , 2 , 2 ]
```
As you can see above, the final result was cut to `N = 10` elements. The `n`th element should be how long the `n`th equal-element group is, even if the element itself belongs in the group it refers to. As in the above case, the first `1` refers to the first such group which is just that `1`, and the first `2` refers to the second such group, which starts with it.
## Rules
* You may assume that `A` will never have two or more consecutive equal elements. `A` may contain an integer more than once, but the first and last elements will not be equal, and `A` will contain at least 2 elements (e.g. `[1, 2, 2, 3]`, `[2, 4, 3, 1, 2]` and `[3]` aren't going to be given). That's because if there were consecutive equal elements, the final result would've been an invalid prefix for such a sequence.
* You may assume `A` only contains positive integers (as such a sequence would be otherwise undefined).
* You may assume `N` is a non-negative integer (`N >= 0`).
* You can't return more terms than requested.
* Using any one of the [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/41024) is strictly forbidden.
* You may use any [reasonable I/O method](https://codegolf.meta.stackexchange.com/q/2447/41024).
* Your answer doesn't have to work beyond natural language limits, but [in theory your algorithm should work for arbitrarily large inputs and integers](https://codegolf.meta.stackexchange.com/a/8245/41024).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
## Test cases
```
[5, 1, 2], 0 -> []
[2, 3, 1], 25 -> [2, 2, 3, 3, 1, 1, 1, 2, 2, 2, 3, 1, 2, 3, 3, 1, 1, 2, 2, 3, 3, 3, 1, 2, 2]
[1, 2, 3], 10 -> [1, 2, 2, 3, 3, 1, 1, 1, 2, 2]
[1, 2], 20 -> [1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1]
[1, 3], 20 -> [1, 3, 3, 3, 1, 1, 1, 3, 3, 3, 1, 3, 1, 3, 3, 3, 1, 1, 1, 3]
[2, 3], 50 -> [2, 2, 3, 3, 2, 2, 2, 3, 3, 3, 2, 2, 3, 3, 2, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3, 2, 2, 3, 3, 2, 2, 2, 3, 3, 3, 2, 2, 3, 3, 2, 2, 2, 3, 3, 3, 2, 2, 2, 3, 3]
[7, 4], 99 -> [7, 7, 7, 7, 7, 7, 7, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 4, 4, 4, 4, 7, 7, 7, 7, 4, 4, 4, 4, 7, 7, 7, 7, 4, 4, 4, 4, 7, 7, 7, 7, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 4, 4, 4, 4, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 4]
[1, 2, 3], 5 -> [1, 2, 2, 3, 3]
[2, 1, 3, 1], 2 -> [2, 2]
[1, 3, 5], 2 -> [1, 3]
[2, 3, 2, 4], 10 -> [2, 2, 3, 3, 2, 2, 2, 4, 4, 4]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
Ṡωȯ↑⁰`Ṙ¢
```
Takes first the length, then the list.
[Try it online!](https://tio.run/##yygtzv6vcGhJVX5x3aOmxsyiQ9v@P9y54HznifWP2iY@atyQ8HDnjEOL/v//b8BlZMplZABCpgZclpZcQB4QGhr8jzbVMdQxiuWKNtIx1jEE0hCeoY4xRAxImuuYQMShYoZwlcY6plCdRkA1AA "Husk – Try It Online")
## Explanation
```
Ṡωȯ↑⁰`Ṙ¢ Inputs: n=9 and x=[2,1,3]
Ṡωȯ Apply the following function to x until a fixed point is reached:
Argument is a list, say y=[2,2,1,3,3,3]
¢ Cycle x: [2,1,3,2,1,3..
`Ṙ Replicate to lengths in y: [2,2,1,1,3,2,2,2,1,1,1,3,3,3]
↑⁰ Take first n elements: [2,2,1,1,3,2,2,2,1]
Final result is [2,2,1,1,3,2,1,1,1], print implicitly.
```
[Answer]
# Pyth, 14 bytes
```
u<s*V]M*QlGGvz
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=u%3Cs%2AV%5DM%2AQlGGvz&input=%5B1%2C%202%5D%0A20&test_suite_input=%5B5%2C%201%2C%202%5D%0A0%0A%5B%5D%0A%5B2%2C%203%2C%201%5D%0A25%0A%5B2%2C%202%2C%203%2C%203%2C%201%2C%201%2C%201%2C%202%2C%202%2C%202%2C%203%2C%201%2C%202%2C%203%2C%203%2C%201%2C%201%2C%202%2C%202%2C%203%2C%203%2C%203%2C%201%2C%202%2C%202%5D%0A%5B1%2C%202%2C%203%5D%0A10%0A%5B1%2C%202%2C%202%2C%203%2C%203%2C%201%2C%201%2C%201%2C%202%2C%202%5D%0A%5B1%2C%202%5D%0A20%0A%5B1%2C%202%2C%202%2C%201%2C%201%2C%202%2C%201%2C%202%2C%202%2C%201%2C%202%2C%202%2C%201%2C%201%2C%202%2C%201%2C%201%2C%202%2C%202%2C%201%5D%0A%5B1%2C%203%5D%0A20%0A%5B1%2C%203%2C%203%2C%203%2C%201%2C%201%2C%201%2C%203%2C%203%2C%203%2C%201%2C%203%2C%201%2C%203%2C%203%2C%203%2C%201%2C%201%2C%201%2C%203%5D%0A%5B2%2C%203%5D%0A50%0A%5B2%2C%202%2C%203%2C%203%2C%202%2C%202%2C%202%2C%203%2C%203%2C%203%2C%202%2C%202%2C%203%2C%203%2C%202%2C%202%2C%203%2C%203%2C%203%2C%202%2C%202%2C%202%2C%203%2C%203%2C%203%2C%202%2C%202%2C%203%2C%203%2C%202%2C%202%2C%202%2C%203%2C%203%2C%203%2C%202%2C%202%2C%203%2C%203%2C%202%2C%202%2C%202%2C%203%2C%203%2C%203%2C%202%2C%202%2C%202%2C%203%2C%203%5D%0A%5B7%2C%204%5D%0A99%0A%5B7%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%204%2C%204%2C%204%2C%204%2C%204%2C%204%2C%204%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%204%2C%204%2C%204%2C%204%2C%204%2C%204%2C%204%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%204%2C%204%2C%204%2C%204%2C%204%2C%204%2C%204%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%204%2C%204%2C%204%2C%204%2C%207%2C%207%2C%207%2C%207%2C%204%2C%204%2C%204%2C%204%2C%207%2C%207%2C%207%2C%207%2C%204%2C%204%2C%204%2C%204%2C%207%2C%207%2C%207%2C%207%2C%204%2C%204%2C%204%2C%204%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%204%2C%204%2C%204%2C%204%2C%204%2C%204%2C%204%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%207%2C%204%5D%0A%5B1%2C%202%2C%203%5D%0A5%0A%5B1%2C%202%2C%202%2C%203%2C%203%5D%0A%5B2%2C%201%2C%203%2C%201%5D%0A2%0A%5B2%2C%202%5D%0A%5B1%2C%203%2C%205%5D%0A2%0A%5B1%2C%203%5D%0A%5B2%2C%203%2C%202%2C%204%5D%0A10%0A%5B2%2C%202%2C%203%2C%203%2C%202%2C%202%2C%202%2C%204%2C%204%2C%204%5D&debug=0&input_size=3) or [Test suite](http://pyth.herokuapp.com/?code=qE%0Au%3Cs%2aV%5DM%2aQlGGvz&input=%5B1%2C+2%5D%0A20&test_suite=1&test_suite_input=%5B5%2C+1%2C+2%5D%0A0%0A%5B%5D%0A%5B2%2C+3%2C+1%5D%0A25%0A%5B2%2C+2%2C+3%2C+3%2C+1%2C+1%2C+1%2C+2%2C+2%2C+2%2C+3%2C+1%2C+2%2C+3%2C+3%2C+1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+3%2C+1%2C+2%2C+2%5D%0A%5B1%2C+2%2C+3%5D%0A10%0A%5B1%2C+2%2C+2%2C+3%2C+3%2C+1%2C+1%2C+1%2C+2%2C+2%5D%0A%5B1%2C+2%5D%0A20%0A%5B1%2C+2%2C+2%2C+1%2C+1%2C+2%2C+1%2C+2%2C+2%2C+1%2C+2%2C+2%2C+1%2C+1%2C+2%2C+1%2C+1%2C+2%2C+2%2C+1%5D%0A%5B1%2C+3%5D%0A20%0A%5B1%2C+3%2C+3%2C+3%2C+1%2C+1%2C+1%2C+3%2C+3%2C+3%2C+1%2C+3%2C+1%2C+3%2C+3%2C+3%2C+1%2C+1%2C+1%2C+3%5D%0A%5B2%2C+3%5D%0A50%0A%5B2%2C+2%2C+3%2C+3%2C+2%2C+2%2C+2%2C+3%2C+3%2C+3%2C+2%2C+2%2C+3%2C+3%2C+2%2C+2%2C+3%2C+3%2C+3%2C+2%2C+2%2C+2%2C+3%2C+3%2C+3%2C+2%2C+2%2C+3%2C+3%2C+2%2C+2%2C+2%2C+3%2C+3%2C+3%2C+2%2C+2%2C+3%2C+3%2C+2%2C+2%2C+2%2C+3%2C+3%2C+3%2C+2%2C+2%2C+2%2C+3%2C+3%5D%0A%5B7%2C+4%5D%0A99%0A%5B7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+4%2C+4%2C+4%2C+4%2C+7%2C+7%2C+7%2C+7%2C+4%2C+4%2C+4%2C+4%2C+7%2C+7%2C+7%2C+7%2C+4%2C+4%2C+4%2C+4%2C+7%2C+7%2C+7%2C+7%2C+4%2C+4%2C+4%2C+4%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+4%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+7%2C+4%5D%0A%5B1%2C+2%2C+3%5D%0A5%0A%5B1%2C+2%2C+2%2C+3%2C+3%5D%0A%5B2%2C+1%2C+3%2C+1%5D%0A2%0A%5B2%2C+2%5D%0A%5B1%2C+3%2C+5%5D%0A2%0A%5B1%2C+3%5D%0A%5B2%2C+3%2C+2%2C+4%5D%0A10%0A%5B2%2C+2%2C+3%2C+3%2C+2%2C+2%2C+2%2C+4%2C+4%2C+4%5D&debug=0&input_size=3)
### Explanation:
```
u start with G = input array
*QlG repeat input array
]M put every element into its own list
*V G repeat every list vectorized by the counts in G
s flatten
< vz take the first (second input line) numbers
and assign them to G until you reach fixed point
```
[Answer]
# Java 8, ~~151 + 19~~ ~~119~~ 115 bytes
```
a->n->{int c=0,l[]=new int[n],i=0,j;for(;i<n;i++)for(j=0;j<(c==i?a[i]:l[i])&c<n;j++)l[c++]=a[i%a.length];return l;}
```
[Try it online!](https://tio.run/##ZU/LTsMwELznK1aVQDFxrfI41XG4IXHg1GPkg3HdsMZ1Iscpqqp8e3CqAAfmsNLOzGpnrDqpddsZb/efEx67NkSwiWNDRMcOg9cRW8/uePZPTFzWDe8ONWin@h7eFHq4ZJDQRxUT/7Lcl@hjLenf/uqjaUygcBWqChoQMKl15dfVJXGgxYa6Wgpvvq4eLykmyvJDG3KOpedYFGRerNhwW@ZaCHxWNcqtS4Pc6mSxyeJqXRRSJOVGMWd8Ez8kDyYOwYPj45RKzIGXIkvuU4t7OKY6@S4G9E0tQYWmJ0u7GfPrOShuG6a6zp3zn6jy8kDhkUKaTyNZxPsNIb@3M3bnPpoja4fIuvQi5lis6Irwq2nMxukb "Java (OpenJDK 8) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~120~~ ~~114~~ 108 bytes
*-6 bytes thanks to plannapus*
```
function(A,N){i=inverse.rle
w=length
a=rle(A)
while(w(a$l)<N){a[[1]]=i(a)
a[[2]]=rep(A,l=w(a$l))}
i(a)[0:N]}
```
[Try it online!](https://tio.run/##TYxBDsIgFET3nMKFi/8TNIAaU1MWvUAvQFiQBiwJoQarLEzPjjRd6O69mcmk4nbtobhXHGY/Rehojx8vfXzb9LTHFCzJMth4n0diZFXokOTRV8hg9gHbujdKca2lB4Oksqic7KN@BbmNcCFrqdit10txMICgJ8qRiguSP2WbXekZadP8KrEGnGH5Ag "R – Try It Online")
Anonymous function; successively inverts the RLE, replacing the lengths `a[[1]]` with the inverted RLE, and the values `a[[2]]` with `A` replicated to a length equal to that of `a$l`.
[Answer]
# [Haskell](https://www.haskell.org/), 68 bytes
Many thanks to Laikoni and flawr for their help in debugging and golfing this answer in the PPCG Haskell chatroom, [Of Monads and Men](https://chat.stackexchange.com/rooms/66515/of-monads-and-men). Golfing suggestions welcome! [Try it online!](https://tio.run/##y0gszk7NyfmvoaxpG/NfQy9NU68kMTuVK00h0UGjyipe01ajykYl2lBPrypWU1s7JV8h00YXxI21Tq5MzklVSFRUzIQoSAOzY//nJmbmKdgqFBRl5pUoqCgYmSpHG@kY6xjG/v@XnJaTmF78Xze5oAAA "Haskell – Try It Online")
```
(.f).take
f a@(z:_)=(z<$[1..z])++do i<-[1..];cycle a!!i<$[1..f a!!i]
```
The first line is an anonymous function. The second line is the infinite list comprehension that produces our Kolakoski-like sequence.
**Explanation**
First, we define `z` as the head of `a` with `a@(z:_)`. Then, we initialize the sequence with `(z<$[1..z])`.
Then, from `1` onwards, `do i<-[1..]`, we append the following to the sequence: `cycle a!!i<$[1..f a!!i]`, which is the `i`-th member of `a` (cycled indefinitely) appended `f a!!i` times.
Finally, the anonymous function simply takes the first `n` terms of our Kolaskoski-like sequence.
[Answer]
# [Python 2](https://docs.python.org/2/), 123 bytes
```
x,y=input()
k=x[0]
t,j=[],0
if k==1:t,j=[k]+x[1]*[x[1]],2
while len(t)<y:t+=(j and t[j]or k)*[x[j%len(x)]];j+=1
print t[:y]
```
[Try it online!](https://tio.run/##TY7BbsMgEETP4Sv2UmHXHIDUikLKlyAOkUNqcIQtiyjw9S6YSO0Fzcy@2WVJYZw934b5ZiTGeIskSeuXZ2haNMmoqEaBOKk0ocjeYZKSiT2YdBcV05@qvJpw9Brtw8DD@Ca030mETjYOrv4GQTk9rzC1hXUfhYit1hfXSYaW1fqQEZH0lu@jeyYtWA/r1f@YhrFWoENYkzDRDFC@iQ4mDmYJYq/iMD7xpnoCjADXBChSnMAx@2x4j1TJc5Ado9WVQZXHt3wDfZYnAl9Zns//m/2OsL@9tZ0H1dSLvFYZ/QU "Python 2 – Try It Online")
] |
[Question]
[
This is a cake:
```
_========_
| |
+________+
| |
+________+
| |
+________+
```
It is 8 wide, 3 tall, and 1 deep.
You must write a program that makes a cake from 3 inputs. The first input controls how many underscores there are in the middle and `=`s on the top. Here's the first cake with a width of 10 instead of 8:
```
_==========_
| |
+__________+
| |
+__________+
| |
+__________+
```
The second input controls how tall the cake is. Here's the second cake with a height of 4 instead of 3:
```
_==========_
| |
+__________+
| |
+__________+
| |
+__________+
| |
+__________+
```
Note the repetition of the layers.
The third input controls how deep it is. That just how many `| |`s to include on the top. Here's the third cake with a depth of 2 instead of 1:
```
_==========_
| |
| |
+__________+
| |
+__________+
| |
+__________+
| |
+__________+
```
You can print trailing whitespace. Test cases:
Input: `3`, `3`, `3`
Output:
```
_===_
| |
| |
| |
+___+
| |
+___+
| |
+___+
```
(I hope I never get this cake)
Input: `3`, `2`, `1`
Output:
```
_===_
| |
+___+
| |
+___+
```
Input: `5`, `5`, `5`
Output:
```
_=====_
| |
| |
| |
| |
| |
+_____+
| |
+_____+
| |
+_____+
| |
+_____+
| |
+_____+
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~25~~, 20 bytes
```
2é_Àé=ÙÒ|èÙÒ+È_ÀäkÀÄ
```
[Try it online!](https://tio.run/##K/v/3@jwyvjDDYdX2h6eeXhSzeEVIEr7cAdIbEk2kGj5//@/5X@T/0YA "V – Try It Online")
Hexdump:
```
00000000: 32e9 5fc0 e93d d9d2 7ce8 d9d2 2bc8 5fc0 2._..=..|...+._.
00000010: e46b c0c4 .k..
```
Thanks to *@nmjmcman101* for saving three bytes, and reminding me of an old operator that saved another two bytes.
Explanation:
`a`, `b`, and `c` are the three arguments.
```
2é_ " Insert two '_' characters
Àé= " Insert 'a' '=' characters between them
Ù " Duplicate this line
Ò| " Replace this whole line with '|'s
è " *Hollow* this line (replace all the middle characters with spaces)
Ù " Duplicate this line
Ò+ " Replace this whole line with '+'s
È_ " *Hollow* this line again, but use '_' instead of spaces
Àäk " Make 'b' copies of this line and the line above it
ÀÄ " Make 'c' copies of this line
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ 26 bytes
```
Nγ←×γ_↑+↑N_×γ=‖BOγF⁻N¹C⁰±²
```
[Try it online!](https://tio.run/nexus/charcoal#VY0xD4IwEIV3fsWF6RpLQnGDuKiLA4SYOBtJam2CLSkF9dfXg6mM9733vgsXM0y@md6ddNixKmmdNh7L28Ah3aVbEOVXrV6eKvelEjsU3Sc7/LDtpxEFB8U45ASP9ouKA5H0sIxqO0vsOJRn@zHbfJU@rQOstSFL7CebYAzWFzmHRqqHl1gwVoUgkn1ShGwO2dj/AQ "Charcoal – TIO Nexus") Link is to verbose version of code. Takes parameters in the order width, depth, height. Explanation:
```
Nγ Input the width.
←×γ_ Print a set of _s that go at the bottom of each layer.
↑+ Print one of the +s that go on the left.
↑N Input the depth and print that many left |s.
_ Print the top left _.
×γ= Print the =s along the top.
‖BOγ Copy the left column to the right.
F Repeat:
⁻ ¹ One time fewer than:
N Input of the height:
C⁰±² Copy the whole cake up 2 characters.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ 31 bytes
```
'_'=¹×«Ć,'|¹úRóG=}²F='+'_¹×«Ć,
```
[Try it online!](https://tio.run/nexus/05ab1e#@68er257aOfh6YdWH2nTUa8BMncFHWk7tNndtvbQJjdbdW31eLj0//@mXEAIAA "05AB1E – TIO Nexus")
## Explanation
```
'_'=¹×«Ć,'|¹úRóG=}²F='+'_¹×«Ć, Full program
'_ Push literal '_'
'=¹× Push '=' w times
«Ć, Concat, enclose and print
'| Push literal '|'
¹ú Pad with w spaces in front
RĆ Reverse and ecnlose
³G } d - 1 times do:
= Print without consuming
²F h times do:
= Print without consuming
'+ Push literal '+'
'_¹× Push '_' w times
«Ć, Concat, enclose and print
```
[Answer]
## Mathematica, 167 bytes
```
c=Column;r=Row;t=Table;f=Flatten;c[c/@{r/@f[{{{"_",r@t["=",#],"_"}},t[{"|",r@t[" ",#],"|"},#3-1]},1],c/@f[{t[{r@{"|",r@t[" ",#],"|"},r@{"+",r@t["_",#],"+"}},#2]},1]}]&
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte switching from an addition to an XOR to translate between outer and inner columns, allowing for a 5 character lookup rather than having two `_` entries.
```
ṬṚ;⁹RḤṬḤ¤Wµ^9ẋ⁵;@;µZị“_+= |”Y
```
Full program taking three program arguments of `depth`, `height`, `width` and printing the cake.
**[Try it online!](https://tio.run/nexus/jelly#AUAAv///4bms4bmaO@KBuVLhuKThuazhuKTCpFfCtSsz4bqL4oG1O0A7wrVa4buL4oCcXysgPV984oCdWf///zL/NP84 "Jelly – TIO Nexus")**
### How?
```
ṬṚ;⁹RḤṬḤ¤Wµ^9ẋ⁵;@;µZị“_+= |”Y - Main link: depth, height (width is a program argument)
Ṭ - untruth [0,0,0,...1] such that the length is the depth
Ṛ - reverse [1,0,0,...0]
¤ - nilad followed by link(s) as a nilad:
⁹ - link's right argument, height
R - range [1,2,3,...,height]
Ḥ - double [2,4,6,...,2*height]
Ṭ - untruth [0,1,0,1,0,1,...,0,1] (length double height)
Ḥ - double [0,2,0,2,0,2,...,0,2]
; - concatenate [1,0,0,...,0,0,2,0,2,0,2,...,0,2]
- ...this is the form of a column of cake!
W - wrap in a list
µ - monadic chain separation, call that c
^9 - bitwise XOR c with 9 [8,9,9,...,9,9,11,9,11,9,11,...,9,11]
⁵ - program's 3rd argument, width
ẋ - repeat the augmented c width times
;@ - concatenate with a copy of c
; - concatenate a copy of c
µ - monadic chain separation call that sideways cake
Z - transpose the sideways cake to put it the right way up
“_+= |” - literal ['_','+','=',' ','|'] (cake decoration)
ị - index into (1 based and modular, so 8,9, and 11 are, mod 5,
3, 4, and 1 yielding '=', ' ', and '_')
Y - join with new lines
- implicit print
```
[Answer]
# PHP>=7.1, 104 Bytes
```
for([,$w,$h,$t]=$argv;$i<2*$h+$t;)echo str_pad($e="_|+"[$b=$i++<$t?$i>1:1+$_++%2],$w+1,"= _"[$b])."$e
";
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/983af2a1ab6ca8009ae723ab6b93c95c2702cd9e)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 62 bytes
```
->w,h,d{l="|#{' '*w}|
";"_#{?=*w}_
"+l*~-d+(l+"+#{?_*w}+
")*h}
```
[Try it online!](https://tio.run/nexus/ruby#S7ON@a9rV66ToZNSnWOrVKNcra6grlVeW8OlZK0Ur1xtbwvkxHMpaedo1emmaGvkaCtpA0XjgaLaXEqaWhm1/wtKS4oV0qJNdIAw9j8A "Ruby – TIO Nexus")
[Answer]
# [Haskell](https://haskell.org), 87 bytes
```
f w t d=["_=| +_\n"!!j|i<-0:([2..d]>>[2])++([1..t]>>[2,4]),j<-i:([1..w]>>[i+1])++[i,6]]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~51~~ 47 bytes
```
"_{ç'=}_"+WçA="
|{ç}|" +(B="
+{ç'_}+" +(´V çA+B
```
[Try it online!](https://tio.run/nexus/japt#@68UX314ubptbbySdvjh5Y62Slw1QIHaGiUFbQ0nIE8bJB1fqw3iH9oSpgBUo@30/7@ljoKxjoIhAA "Japt – TIO Nexus")
Input is taken in the order width, height, depth.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 108 bytes
```
?sdstsw95P61sc[lwsf[lcPlf1-dsf0<a]dsax]dsbx[_]p[[124P32sclbx[|]pld1-dsd0<j]dsjx43P95sclbx[+]plt1-dst0<h]dshx
```
[Try it online!](https://tio.run/##JcpBCsMgEIXhq2RfAppoICD0Cu4HKXamIkHawAhxkWt3bSd08xbv@wl7vzNx5WO1ftGMUA5OUNCXpEfipFwMxLHJPBs8wg6gJ@PnibHIcYa90BWScps0WzOzX@0fb4L1wqpcFsytdzPYYfm@PyNGzK8f "dc – Try It Online")
[Answer]
# [Röda](https://github.com/fergusq/roda), 65 bytes
```
a,b,c{d=" "*a;[`_${"="*a}_
`,`|$d|
`*(c-1),`|$d|
+${"_"*a}+
`*b]}
```
[Try it online!](https://tio.run/##K8pPSfyfFvM/USdJJ7k6xVZJQUkr0To6IV6lWskWyKyN50rQSahRSanhStDSSNY11ITytIEK4kEKtIESSbG1/3MTM/OquRQSbaMtdIx1DIEYAo2AbFMQjAVKamjWpCnE6wAhV@1/AA "Röda – Try It Online")
[Answer]
# [Java 7](http://openjdk.java.net/), ~~169~~ ~~164~~ 158 bytes
```
String f(int...a){String s="_",t="|",u="+";for(;a[0]-->0;s+="=",t+=" ")u+="_";s=s+"_";t="\n"+t+"|";u=t+"\n"+u+"+";for(;a[2]-->1;)s+=t;for(;a[1]-->0;)s+=u;return s;}
```
[Try it online!](https://tio.run/nexus/java-openjdk#fY7BasMwDIbPyVMInWzsmqZjJ@O9wU49dqV4XVICiRNsuWWkefbMbrpr0UHi06cfjfG7a89w7mwI8GlbN5VlMa4wkKXUrkP7A31asT351l0OR7D@EvhUFkW@gB4MuPr2OGdcJ7z/DVT3aoikxnRCnWO9atibTMVfGztZvTTeZapszMv6DjQsbZVSlk9PEgyeUJLBO8poUKBuBs@0PWyPm83HVgdh0CQhNUAeRdYf8PTlUGd8z0M0JKJAkednwC4HVJonmf5ZtYZmFrWvKXoHQc/LvPwB)
Ungolfed:
```
String f(int...a) // saves two bytes over int a, int b, int c
{
String s="_", t="|", u="+"; // set up the start of each row
for(; a[0]-->0; s+="=", t+=" ") // Uses the goes-to operator to fill the row
u+="_";
s += "_\n"; // adds the end of each row
t += "|\n";
u = t + u + "+\n"; // and combining t into u
for(; a[2]-->1; ) // add the top of the cake
s += t;
for(; a[1]-->0; ) // add the rest of the cake
s += u;
return s;
}
```
[Answer]
# Windows Batch, ~~211 180~~ 163 bytes
Golfed a total of ***48 bytes*** thanks to @Neil!
```
@for /l %%p in (1,1,%1)do @call set w= %%w%%
@echo _%w: ==%_
@for /l %%p in (2,1,%3)do @echo ^|%w%^|
@for /l %%p in (1,1,%2)do @echo ^|%w%^|&echo +%w: =_%+
@set w=
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 25 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
e =*¼_Oe↕¼|.⌡Qe╔*¼+.H«{Q;
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=ZSUyMCUzRColQkNfT2UldTIxOTUlQkMlN0MuJXUyMzIxUWUldTI1NTQqJUJDKy5IJUFCJTdCUSUzQg__,inputs=OCUwQTElMEEz)
Expects the input as width, depth, then height.
[Answer]
# Python 2, ~~124~~ ~~122~~ ~~120~~ ~~105~~ 92 bytes
```
w,t,d=input()
a="\n|"+w*" "+"|"
print"_"+w*"="+"_"+(d-1)*a+t*(a+"\n+"+w*"_"+"+")
```
-15 bytes by using STDIN instead of program arguments
-13 bytes by switching to Python 2 (for `input()`ing integers and `print` statement)
-12 bytes from Caird Coinheringaahing
[Try it online!](https://tio.run/##K6gsycjPM/r/v1ynRCfFNjOvoLREQ5Mr0VYpJq9GSbtcS0lBSVupRomroCgzr0RBKR4sZgsUA7I0UnQNNbUStUu0NBK1gRq0wZJACSDU/P/fWMdIxxBCAgA "Python 2 – Try It Online")
# Python 3, ~~124~~ ~~122~~ ~~120~~ 105 bytes
```
w,t,d=[int(input())for n in(1,2,3)]
a="\n|"+w*" "+"|"
print("_"+w*"="+"_"+(d-1)*a+t*(a+"\n+"+w*"_"+"+"))
```
[Try it online!](https://tio.run/nexus/python3#HYvBCoMwEETv@Yqwp2w2FaLnfImVEpBKDl0lhorgv2@3MpeZ9xgpn22tze7nbo7QwpzGws3p7HJdviNP@F6rZVvYxdCHASeTEzz5Ajo8WCC4wGz1f4LXzZIybW5@RPSZmneZ9EC3VKFBFJFBeok/)
If a full program is not required:
# Python 3, ~~87~~ 84 bytes
```
lambda w,t,d:"_"+w*"="+"_"+(d-1)*("\n|"+w*" "+"|")+t*("\n|"+w*" "+"|\n+"+w*"_"+"+")
```
[Try it online!](https://tio.run/nexus/python3#XYvNCsIwEITvPsWyp82PQtqb0CcxIpEQCdhtSYNF6LuvaY/OHGbmg0mDl3cYnzHAaquNV3ygWTUOaPZG8eyUJvS8HRga3lCZ@s88m2O0T7OSPM5TqbB8l9NcMldKpGnPRi6hvD43vitIUwGGzEDOdrZXTSK9dOJ@)
[Answer]
# Javascript (ES6), ~~161~~ 157 bytes
```
f=(w,h,d)=>{r=x=>x.repeat(w);_='_';m='+'+r(_)+'+';b='|'+r(' ')+'|';c=[_+r('=')+_];for(i=d-1;i--;)
c.push(b);for(i=h;i--;)
c.push(b+'\n'+m);return c.join`\n`}
console.log(f(8,3,1));
```
[Answer]
# [Python 2](https://docs.python.org/2/), 93 bytes
```
i,j,k=input()
l=["|"+" "*i+"|"]
for x in["_"+"="*i+"_"]+l*(k-1)+(l+["+"+"_"*i+"+"])*j:print x
```
[Try it online!](https://tio.run/nexus/python2#HckxCsAgEETR3lPIVuqaIqQLeBIRu8CqGBEDFrm70TDN8P4gHXQ0lMvThGTJWHgBgYMinM@x6668c8oW/HTzuweHSYm47RJFQjvDwpUQnFThLJVy432MQ899 "Python 2 – TIO Nexus")
[Answer]
# [Perl 5](https://www.perl.org/), 85 + 1 (-a) = 86 bytes
```
say"_".'='x($w=$F[0])."_\n".($l='|'.$"x$w."|\n")x($F[2]-1).("$l+".'_'x$w."+\n")x$F[1]
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2BoYP2/OLFSKV5JT91WvUJDpdxWxS3aIFZTTyk@Jk9JT0Mlx1a9Rl1PRalCpVxPqQYopglU5RZtFKtrqKmnoaSSow3UGq8OltYGSwNlDWP//zdWAMJ/@QUlmfl5xf91EwE "Perl 5 – Try It Online")
[Answer]
# JavaScript/ES6, 90 bytes
I just wrote a rough solution, and happened to beat the existing JS answer by a whopping 56 bytes. Then I golfed off 11 bytes.
```
(w,h,d,g=a=>a+a[1][r='repeat'](w)+a[0]+`
`)=>g('_=')+(l=g('| '))[r](d-1)+(l+g('+_'))[r](h)
```
Here's a demo.
```
var F = (w,h,d,f=a=>a+a[1][r='repeat'](w)+a[0]+`
`)=>f('_=')+(l=f('| '))[r](d-1)+(l+f('+_'))[r](h);
console.log(F(prompt('width') || 3, prompt('height') || 3, prompt('depth') || 3));
console.log(F.toString().length);
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 23 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
|*_⁷⇵×+×∔║│P
=×_eP⁸╷{1⁸
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTdDJXVGRjBBXyV1MjA3NyV1MjFGNSVENyslRDcldTIyMTQldTI1NTEldTI1MDIldUZGMzAlMEElM0QlRDdfJXVGRjQ1JXVGRjMwJXUyMDc4JXUyNTc3JXVGRjVCJXVGRjExJXUyMDc4,i=OCUwQTIlMEEz,v=1)
[Answer]
## Google Sheets, 89
Inputs A1, A2, A3.
* A4 - `_`
* A5 - (Discount 1 for `"`)
```
="|"&REPT(" ",A1)&"|
"
```
Final output (Discount 1 for `)`):
```
=A4&REPT("=",A1)&"_
"&REPT(A5,A3-1)&REPT(A5&"+"&REPT(A4,A1)&"+
",A2)
```
] |
[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/240225/edit).
Closed 2 years ago.
[Improve this question](/posts/240225/edit)
`[Sandbox](https://codegolf.meta.stackexchange.com/a/24186/98630)`
Your challenge is to write a program that when first run, will do one of the actions below at random with equal chances of both:
* A cat program
+ A standard cat program: read everything from `STDIN` and put it on `STDOUT` (or your language's closest equivalent).
* Do nothing and halt
+ This shouldn't output anything.
The behaviour is permanent - once the program chooses between the two options, it should do that no matter how much times you run the script. It's fine if this resets when you reboot.
Please provide an explanation on how to reset the program (which file to delete for example)
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes or equivalent) wins.
[Answer]
# Python 3, 94 bytes
```
from random import*
s=randint(0,1)*"print(open(0).read())"
open(__file__,"w").write(s)
exec(s)
```
[Try it online!](https://tio.run/##nclBDoMgEAXQ/ZyCshGMITbdtl6FUB0jSYUJTGM9PRWTXqCr///7T5eXguMSRVPmFFeRXJiO8CvFxC3kRwUfWPXdVbeSUu2RMKhem4RuUlpLOMHa2b/Q2k5uUpsteUaVNeAHxyNLIwbBmNnQDkA7LzHcfiDuwvhAbzbs4/9nqQjnhAt8AQ "Bash – Try It Online")
Picks one of `` or `print(open(0).read())` and replaces the contents of the file with it. Then, executes that code once.
To reset it, you will have to copy-paste this code into the file again, since it overwrites the file itself. This perseveres so long as the file exists and is not modified, so it is remembered through reboots and even if you move the file to another computer.
-5 bytes thanks to Jonathan Allan
(Also -5 thanks to Jakque by using `choice(["print(open(0).read())",""])` instead of `randint(0,1)*"print(open(0).read())"` - both are excellent golfs; I just chose the first one.)
[Answer]
# [R](https://www.r-project.org/), ~~37~~ 36 bytes
*Edit: -1 byte thanks to Giuseppe*
```
{q=rt(1,1)<0;function(x)if(q)cat(x)}
```
[Try it online!](https://tio.run/##lZHBboMwDIbvPIXFpCmRaDUm7ULHm@ySggOWwGmdVKyq@uwsMEZbaYft5lj29//@I6OvWnFYEzco5Xg5lhJUnuX6/WVnT1wFcqw@NVl11JUJsbyOTyAnBgoQWgRL4mNFPYISw7XruzNUrXMePewxDIgMcROegd3GHXSRTJw8Sz841cm9vErNvoq9lW8aQwwGLA6zgi8S60QRxO5r8aYvEylNM8o8HsoZuPsFeE0ikt0ANXYY8Nv2chtUrj9M3e5cJNKr@/XFCccH/IKdkQN1HaCIk0lEcFOjJcaH@VWseDi3/EvYC/UnkFsUoHpq2hAjnu/xJn6A8XPthBpi03XnxU29Oshg3arJWhTksN1u9S3X/D@5jl8 "R – Try It Online")
Function that acts randomly as cat or no-op on first call, and then stays with this behaviour forever (or until deleted).
---
# [R](https://www.r-project.org/), 83 bytes
```
if(!F)write(paste("F=",F<-sample(1:2,1)),".Rprofile");if(F<2)show(scan("stdin",""))
```
[Try it online!](https://tio.run/##DctBCoAgEADAt7SnXbBAj2VXH9APpJQEU3EFn29e5jZ1jOBxMdRraA6L5SmYE4TRK9uvRIdyV0ISCdiuUrMP0QEdcxmtiN/ckW@bELg9IYEAIBrjBw "R – Try It Online")
Full program: saves state into ".Rprofile" file in directory from which [R](https://www.r-project.org/) or `Rscript` is launched: delete this to reset program behaviour.
[Answer]
# [Haskell](https://www.haskell.org/), 89 bytes
This method uses no special files. In fact it doesn't store data anywhere.
To set up your `randomize_va_space` should be set to zero (linux).
You can check this with:
```
sysctl -anr "e_v"
```
I won't tell you *how* to set it to `0` since in general this should not be set to `0`, and setting it to `0` represents a possible security risk.
Don't play with your kernel unless you know what you are doing or have nothing to lose on the device.
```
import Unsafe.Coerce
main=([[interact id],[pure()]]>>=([0..7]>>))!!mod(unsafeCoerce(+))16
```
[Try it online!](https://tio.run/##Jcu9CoAgFEDhvaewzUshtdRUS8/QJA5SN5K8Gv48v0VtBw7fqeOF1pZi6PYhsdVFfaBYPIYNK9LGTVxK4xIGvSVmdtXKOwfkoNQ8v68TYnwLoK7J7zx//ue8AeiHUpAIKT4 "Haskell – Try It Online")
TIO is stuck on cat and I have no way to reset it. You can switch the `+` to a `:` to see a version that is stuck on the noop.
To reset it locally it should be enough to set the `randomize_va_space` to `2` run the program once and then set it back to `0`.
## Explanation
*More detailed explanation [here](https://codegolf.stackexchange.com/a/213793/56656)*
In Haskell, all complex objects including functions are internally represented as a pointer. This is a number in binary that "points" to a specific location in memory. This is because we want to pass these values by reference, since copying the whole thing is expensive, and since Haskell disallows mutation we can with no problem.
However simple objects like ints are passed by value since they are so small that copying them is about as expensive as copying a pointer would be. unsafeCoerce is a super unsafe function which just takes the raw bytes from one object and reinterprets it as the raw bytes for another type.
So if we use unsafeCoerce from a function to an `Int`, the resulting `Int` is just the value of the pointer to the object. And the value of that simple object is dependent only on where the complex object is located not anything about what it is.
When `randomize_va_space` is on, this means the value of `unsafeCoerce(+)` is a random multiple of 8. However when it's off, it is fixed to one value which depends on some factors about the machine.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 64 bytes
```
awk -va=$(awk '!/E/{$0=(systime()-$1)%88}1' /proc/uptime) 'a<44'
```
[Try it online!](https://tio.run/##S0oszvj/P7E8W0G3LNFWRQPEUlfUd9WvVjGw1SiuLC7JzE3V0NRVMdRUtbCoNVRX0C8oyk/WLy0ASWgqqCfamJio//9fnJ@bWpKRmZcOAA "Bash – Try It Online")
Here's how it works.
`AWK` is called with a variable `a` which is a floating point number greater than or equal to 0 and less than 88. So it uses the `a<44` test to get a 50/50 chance to decide what action to take. If that evaluates as true, then it prints STDIN to STDOUT. If it's false, it silently consumes STDIN.
The value of `a` is set by the inner `AWK` call. That logic read the first numeric value in `/proc/uptime`, which is the number of seconds since the system was booted. The it subtracts that "uptime" from the current date/time to get the boot time of the OS. Then it computes a modulo of 88 seconds to deal with the (very annoying) fact that the calculations aren't consistent at the seconds level.
Essentially it's using the boot time of the OS to decide whether or not to "cat" or "discard" the input. So it will make the same decision each time it's run until the system is rebooted.
[Answer]
# [Zsh](https://www.zsh.org), ~~29~~ 21 bytes
```
X=$[RANDOM%2]
f()>&$X
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhZbI2xVooMc_Vz8fVWNYrnSNDTt1FQiIHJ702xsbDLzCkpLuLCwIGpg5gAA)
A function which either does`>&1` (copy input to STDOUT) or `>&0` (write to STDIN, which doesn't work).
Can be shorter.
---
If using the PID as a source of randomness is allowed (which doesn't work on Attempt This Online because of how the sandbox works):
## Zsh, 11 bytes
```
f()>&$[$%2]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes
Anonymous lambda. Takes one or two dummy arguments. Requires 0-based indexing.
```
{6::∇a∘←?2⋄a:⍞}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6vNrKwedbQnPuqYAeTbGz3qbkm0etQ7r/Z/GpD/qLfvUVfzo941j3q3HFpv/KhtIlBncJAzkAzx8AwGquldw4WT0NXV5dJMLUosTlVI5BoApQA "APL (Dyalog Unicode) – Try It Online")
You can reset the program by erasing its global state `a`.
`{`…`}` "dfn":
`6::` if we hit a value error:
`a∘←` globally assign to `a`:
`?2` a random 0 or 1
`⋄` now try:
`a:` if `a` [is 1]:
`⍞` read STDIN [and implicitly return and print it]
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 149 bytes
Stores either `s` or `u` into the `user.a` extended attribute of the executable. `setxattr()` doesn't replace an already-existing value, so I just write the value and then retrieve it to see whether to cat the input (`s`) or not (`u`).
To reset the program, run `setfattr -x user.a {programname}`
```
main(a,v,s)char*v,*s;{char r[]="user.a";srand(time(0));s=r+rand()%2;setxattr(*v,r,s,1,1);getxattr(*v,r,s,1);if(*s&2)while(~(a=getchar()))putchar(a);}
```
[Try it online!](https://tio.run/##XY1BCsJADEWvIgUlGaPYbsOcRFyEcWwHbJFkWgXRq4@t7tw9Hv/xw64NoZRe0gBCExmGTtRN5IyfC670ePLVaFH3UrGpDGfIqY9wQGTzuv0aXDdsMT8kZ4W5VjKqqUZu/yVyuoCzTYP3Ll0jvEH8PFquABFv4w8F@VVKjpY/ "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES2020), browser, ~~56~~ 52 bytes
```
(localStorage.d||=Math.random())>.5&&alert(prompt())
```
Sets the `d` property of localStorage if it's undefined. Stacksnippets doesn't like setting localstorage, so run this in your console to see.
Full program. -4 thanks to tsh.
[Answer]
## Batch, 53 bytes
```
@if "%c%"=="" set/ac=%random%%%2
@if %c%==1 find/v""
```
Use `set c=` to reset the flag. Explanation: If `c` is empty, the first line sets `c` to a random value that is either `0` or `1`, then the second line copies STDIN to STDOUT only if `c` is `1`. I don't know why the builtin `find` command fails to find the empty string in any input, but it's consistent, so we can simply invert the condition, thus turning `find` into a `cat` program.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 48 bytes
```
BEGIN{a=systime()%2;getline a<"_";print a>"_"}
a
```
[Try it online!](https://tio.run/##SyzP/v/fydXd06860ba4srgkMzdVQ1PVyDo9tSQnMy9VIdFGKV7JuqAoM69EIdEOyK7lSvz/P8Q1OETB0y8gNAQA "AWK – Try It Online")
`systime()` is used to decide whether to print or not. State is saved in the file `_`. `getline` does not clobber variables if it doesn't read anything.
[Answer]
# Python 3, ~~66~~ 62 bytes
```
import random
if random.randint(1,2)==1:print(str(input("I")))
```
Gets a random value and if it's 1, it gets and prints user input. I just put an I (for input) because my Python interpreter allows you to give input even when not asked for.
[Answer]
# [Zsh](https://www.zsh.org/), 35 bytes
```
((RANDOM&1))&&p='<&0'&&<&0
<<<$p>$0
```
[Try it online!](https://tio.run/##qyrO@G@nkJtYmZSanFiiYGOjoO7q76b@X0MjyNHPxd9XzVBTU02twFbdRs1AXU0NSHLZ2NioFNipGPwHKuTiKijKzCtRSMssKi5RqFGoKs6AG8ZVlFqQCjTT0EChWgGiTL0ktbikWB1NoULtfwA "Zsh – Try It Online")
Randomly overwrites the file with either `<&0` (equivalent to `cat`) or nothing.
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~80~~ 60 bytes
```
global x;if x;else;x=randi(1:2);end;if x>1;input('','s');end
```
Will either do nothing, or whatever the user inputs to `ans=` (considered "STDOUT" for our purpose), then stick with that choice.
When first used a global variable (`x` here) is empty. Empty values evaluate to false. If `x` is false, it will set it to a random integer of either 1 or 2. This will then never evaluate false again, so the first part of the program will then never run again.
If `x` is 2, then the program will request user input (considered "STDIN" for our purpose). If `x` is 1, will do nothing at all.
---
Relies on the fact that a global variable is persistent once created, and will only reset if the user clears all variables ("reboots" for our purpose).
I would add a TIO link, but unfortunately that doesn't seem to want to handle global variables.
] |
[Question]
[
Given a positive integer \$n\$, your task is to find out the number of partitions \$a\_1+a\_2+\dots+a\_k=n\$ where each \$a\_j\$ has exactly \$j\$ bits set.
For instance, there are \$6\$ such partitions for \$n=14\$:
$$\begin{align}&14 = 1\_2+110\_2+111\_2&(1+6+7)\\
&14 = 10\_2+101\_2+111\_2&(2+5+7)\\
&14 = 10\_2+1100\_2&(2+12)\\
&14 = 100\_2+11\_2+111\_2&(4+3+7)\\
&14 = 100\_2+1010\_2&(4+10)\\
&14 = 1000\_2+110\_2&(8+6)\end{align}$$
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
### Test cases
```
n f(n)
-------
1 1
2 1
3 0
4 2
5 1
10 2
14 6
19 7
20 10
25 14
33 32
41 47
44 55
50 84
54 102
59 132
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ŒṗB§Ṣ⁼JƲ€S
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pzsdWv5w56JHjXu8jm161LQm@P/D3VsObX24Y9PDHYvCdA63q2i6//9vqKBgyGUEIowVFAy4TBQUjLhMQVxDAyDL0ETBjMvQUsGcy8hAwdCAy8hUwdCEy9hYwdiIy8RQwcScy8REwdSUy9RAwcIEAA "Jelly – Try It Online")
Brute force approach, we generate all partitions then count those that satisfy \$\operatorname{bitsum}(a\_j) = j\$. Times out for the \$n = 59\$ test case on TIO, and can handle a test suite going up to the \$n = 50\$ test cases
## How it works
```
ŒṗB§Ṣ⁼JƲ€S - Main link. Takes n on the left
Œṗ - Integer partitions of n
B - Convert everything to binary
Ʋ€S - Count for how many the following is true:
§ - Sum of bits for each
Ṣ - Sorted
⁼J - Is equal to [1, 2, ..., n] for some n?
```
[Answer]
# [Python 3](https://docs.python.org/3/), 74 bytes
```
f=lambda n,m=1:sum(f(n-i,m+1)for i in range(n+1)if i.bit_count()==m)+(n<1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XdBBDoIwEAXQuPUG7pq4aQMYBlpFYy_gJQyo1Sa2EISFZ3HDRu-kp5EwQg3b187_0z5exb265LZpnnWlguS9U_KamuyYEusbCZtbbaiiNtC-8YCpvCSaaEvK1J5P1LakFdGLTFf7Q17bijIpDfOo3QLDxM9kVpS6PVEUCGNkTmDaQzSGGCEcgCNEA4jxCISjG8A7WDpYd7BytTgCriYSKNxtEncSu1wOnXCXw7FJCLcdJicuR_Bf198TcB-II_yh_u-_)
-4 bytes suggested by loopy walt.
---
# [Python 3](https://docs.python.org/3/), 78 bytes
```
f=lambda n,m=1:sum(f(n-i,m+1)for i in range(n+1)if bin(i).count('1')==m)+(n<1)
```
[Try it online!](https://tio.run/##Xc9NDoIwEAXgvaeYxAVtQMPQ1r/Yw4BabWIHgrDw9JW0Sg3bL533Xrv38GhJeG/0s3bNtQYqnMbTa3TMMNrYwuXITduDBUvQ13S/MZrIGmgsMcu3l3akgWWYca0dzxmdkfuutxMahsA5rAFXP6iWICKUM8gI1QxqeYLl4gXKALsExwD7VBtPMNVUKopMS0QQkXIlBpEpR8YmpdK6mHxIOUp@u/6@EPegqPwH "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
ṄƛbṠs:ż⁼;∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuYTGm2LhuaBzOsW84oG8O+KIkSIsIiIsIjE0Il0=)
```
Ṅ # Integer partitions
ƛ ; # Map...
bṠ # Sums of binary
s # Sorted
⁼ # Equal to
:ż # 1..length?
∑ # Sum (count valid)
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 56 bytes
```
f(n,m=1)=!n+sum(i=1,n,if(sumdigits(i,2)-m,0,f(n-i,m+1)))
```
[Try it online!](https://tio.run/##FYpLCsMwDESvomZlkTFE@SyycC9SuggUB0FtTD6Lnt6VF2Jmnl7ZDvV7qZFCjS4jBeHwyP15J6dBkKHR2fjortfpFCP7hAHmekXqhZnrVsr35zL5J5VD82W1a6Mj05hBLwGNoAk0gxaQDHZWZTVufTQ2ta95c1OMLS3XN9c/ "Pari/GP – Try It Online")
A port of [tsh's Python answer](https://codegolf.stackexchange.com/a/240018/9288).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 99 bytes
```
(l=Length)@Select[Flatten[Permutations/@IntegerPartitions@#,1],Tr/@IntegerDigits[#,2]==Range@l@#&]&
```
[Try it online!](https://tio.run/##PcqxCsIwEIDhVykEisJBm1gHh8ANIggOQd1ChlCONJBESM9JfPYoDq7/92fPC2XPcfYt6LZJ@kIl8LLFGyWa2Z6SZ6ZiDdX85O/4KOuA58IUqBpfOf4SCpAO7vVPxxgir1aAclpffQmECUXv@mZqLNwNGAbsXhIU7GCCPcgR5ATyAGp8t/YB "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Åœʒ2вO{āQ}g
```
[Try it online](https://tio.run/##yy9OTMpM/f//cOvRyacmGV3Y5F99pDGwNv3/f0MTAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w61HJ5@aZHRhk3/1kcbA2vT/Ov@jDXWMdIx1THRMdQwNdAxNdAwtdYwMdIxMdYyBooY6JkAZAx1TIGkZCwA).
**Explanation:**
```
Ŝ # Get all lists of positive integers that sum to the (implicit) input
ʒ # Filter this list of lists by:
2в # Convert it to a binary-list
O # Sum each inner list together
{ # Sort it
ā # Push a list in the range [1,length] (without popping)
Q # Check if the two lists are the same
} # After the filter:
g # Pop and push the length to get the amount of remaining lists
# (which is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes
```
Nθ≔⁰η⊞υ⁰FL↨貫≔υζ≔⟦⟧υFΦ⊕θ⁼ι⊖Σ↨κ²Fζ⊞υ⁺κλ≧⁺№υθη»Iη
```
[Try it online!](https://tio.run/##RY@9jsIwEITry1NsuZZ8EiA6Ko4fCQlQBOXpCl8wsYXjENtLAeLZjU1AdB7PzH67lRKuaoWJcWXPFLbU/EuHHZsUU@91bXHAQSVVkldIHAbpfWwd4FraOij8EV5ix2HEGINb8fVqpeQ1Jd/y948DZf2sLrUJCbKylZONtEEeEpDDoiNhPGoOc/lx9tT0kFMPyZznlCuD91KlIZ99wzJjI849dqdrFTCbHGYt2ZCzmZQPuhel0@lrJnxAlYoxDsfx@2Ie "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
≔⁰η
```
Start with no partitions found.
```
⊞υ⁰
```
Start with `1` partition of `0` integers whose sum is therefore `0`.
```
FL↨貫
```
Loop over the potential lengths of the partitions.
```
≔υζ
```
Save the partitions found so far.
```
≔⟦⟧υ
```
Start collecting partitions of this length.
```
FΦ⊕θ⁼ι⊖Σ↨κ²
```
Loop over all integers up to `n` with the right number of bits set.
```
Fζ⊞υ⁺κλ
```
Add these integers to all of the previously found partitions.
```
≧⁺№υθη
```
Count how many equal `n`.
```
»Iη
```
Output the final total.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes
```
f=(n,m,i=1,w)=>n<i?!n:!(w^m)*f(n-i,-~m)+f(n,m,i-~i,-~w)+f(n,m,i+i,w)
```
[Try it online!](https://tio.run/##dY9NDoIwEEb3nAJ2rRRh@iNqRG9iQpCaGihGjOy4OmJaTSywaTLvTWe@ueWvvC0e6v6MdHMph0FmSJOaqAxIh7OjPqhToPcB6s41XkmkI0WivsahNG1R/6m7Xx2q8dtQNLptqnJdNVckEfgY@3Hsg/fP6QJnlicO55ZTh4uFOZDM9wM3fOPyneGpm9POgcQbX8cJ6/jUMWYco1PHwTiezjibT4ipEzbLdmaf4N@cMwuFPQ4YHd4 "JavaScript (Node.js) – Try It Online")
Very slow for `n>25`. Change `!(w^m)*f(...)` to [`(w^m?0:f(...))`](https://tio.run/##dZDNDoIwEITvPgXe2tAK/fOHiLyJCUFraqA1YuTGq1dNq4mrHPvNdmdmz/W97purudyodYej97pElnTElIwMuNzZranmtkDDvqvyQiNLDaFjh3GqwxwdX2D4vFPz/OcbZ3vXHhetOyGNWIJxkmUJm31zPsFF5DngMnIOuJrYw/L/80wGvoR8E/gK5ox7GAzEVRQkbCCCIKC1ZEGQ0EPGTErBctF8DT2UfKf6uUfswQT3Dw) may be faster but cost +1 byte.
[Answer]
# Haskell, ~~77~~ 74 bytes
```
import Data.Bits
m!0=1
m!n=sum[(m+1)!(n-i)|i<-[1..n],popCount i==m]
g=(1!)
```
[Try it Online!](https://tio.run/##FcsxDsMgDEDRPadwNlAbFPZ6abv0DBEDA6JWY4PA2Xp3mi5/efrv2D9p38cgrqUpPKNGdyftE88r@rOC/eDN8MXb2chC9ku3ZfPOSbjWUh/lEAVC5DBlNH62gyMJINRGpxiOFUx2Wl6iKadm4T/7NdjxAw)
-3 bytes thanks to Wheat Wizard
Port of [tsh's Python answer.](https://codegolf.stackexchange.com/a/240018)
[Answer]
# Python3, 156 bytes:
```
def f(n,i=1,c=0):
if c==n:yield
elif c<n:
for k in range(1,n-c+1):
if bin(k).count('1')==i and c+k<=n:yield from f(n,i+1,c+k)
g=lambda x:len([*f(x)])
```
[Try it online!](https://tio.run/##NU9LboMwEF13TvGUDXagkQ2mSVB8EpoFAUMtiEFAo@T01FbbzWh@7ze91q/RZadp3rbGtGiZS6yWSa0FLwi2Ra21K17WDA3BDGFxcf6CdpzRwzrMlesMk4l7r2MZQAiwm3Ws54d6/HYri2TEtbaoXIM67i//jGjn8f6rGXvNuOfU6aG635oKz2IwjpX7lj35lW9Bzga53W4nAUlpKBkgSAEp5WGUwndS4YPkGUdKBaSgNIdUlGXIUlIS6khKIc8pFzgpypX/8fAzZJZ67sMyDdY7/nSRz/JWLYuZV3SMPQpd7u/VxKxbE9i/P@69leLq0z1KeaVptiHuapZ1wRTATcS3Hw)
] |
[Question]
[
In Lisp style languages, a list is usually defined like this:
```
(list 1 2 3)
```
For the purposes of this challenge, all lists will only contain positive integers or other lists. We will also leave out the `list` keyword at the start, so the list will now look like this:
```
(1 2 3)
```
We can get the first element of a list by using `car`. For example:
```
(car (1 2 3))
==> 1
```
And we can get the original list with the first element removed with `cdr`:
```
(cdr (1 2 3))
==> (2 3)
```
Important: `cdr` will always return a list, even if that list would have a single element:
```
(cdr (1 2))
==> (2)
(car (cdr (1 2)))
==> 2
```
Lists can also be inside other lists:
```
(cdr (1 2 3 (4 5 6)))
==> (2 3 (4 5 6))
```
Write a program that returns code that uses `car` and `cdr` to return a certain integer in a list. In the code that your program returns, you can assume that the list is stored in `l`, the target integer is in `l` somewhere, and that all the integers are unique.
Examples:
Input: `(6 1 3) 3`
Output: `(car (cdr (cdr l)))`
Input: `(4 5 (1 2 (7) 9 (10 8 14))) 8`
Output: `(car (cdr (car (cdr (cdr (cdr (cdr (car (cdr (cdr l))))))))))`
Input: `(1 12 1992) 1`
Output: `(car l)`
[Answer]
# Common Lisp, 99
The following 99 bytes solution is a CL version of the nice [Scheme answer](https://codegolf.stackexchange.com/a/58876/903).
```
(defun g(l n &optional(o'l))(if(eql n l)o(and(consp l)(or(g(car l)n`(car,o))(g(cdr l)n`(cdr,o))))))
```
I originally tried to make use of `position` and `position-if`, but it turned out to be not as compact as I would have liked (209 bytes):
```
(lambda(L x &aux(p'l))(labels((f(S &aux e)(cons(or(position x S)(position-if(lambda(y)(if(consp y)(setf e(f y))))S)(return-from f()))e)))(dolist(o(print(f L))p)(dotimes(i o)(setf p`(cdr,p)))(setf p`(car,p)))))
```
### Expanded
```
(lambda
(l x &aux (p 'l))
(labels ((f (s &aux e)
(cons
(or (position x s)
(position-if
(lambda (y)
(if (consp y)
(setf e (f y))))
s)
(return-from f nil))
e)))
(dolist (o (print (f l)) p)
(dotimes (i o) (setf p `(cdr ,p)))
(setf p `(car ,p)))))
```
### Example
```
(funcall *fun* '(4 5 (1 2 (7) 9 (10 8 14))) 14)
```
The list is quoted, but if you really want, I can use a macro.
The returned value is[1]:
```
(CAR (CDR (CDR (CAR (CDR (CDR (CDR (CDR (CAR (CDR (CDR L)))))))))))
```
For tests, I used to generate a lambda form where `l` was a variable:
```
(LAMBDA (#:G854) (CAR (CDR (CDR (CAR (CDR (CDR (CDR (CDR (CAR (CDR (CDR #:G854))))))))))))
```
Calling this with the original list returns 14.
---
[1] `(caddar (cddddr (caddr l)))` would be nice too
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~170~~ ~~142~~ ~~125~~ ~~115~~ ~~114~~ ~~87~~ ~~84~~ ~~83~~ ~~75~~ ~~73~~ ~~70~~ ~~69~~ ~~68~~ 67 bytes
Yay, ~~less than 50% of~~ more than 100 bytes off my first attempt. :)
```
\b(.+)\b.* \1$
(
^.
l
\(
a
+`a *\)|\d
d
+`(.*[l)])(\w)
(c$2r $1)
```
To run the code from a single file, use the `-s` flag.
I'm still not convinced this is optimal... I won't have a lot of time over the next few days, I will add an explanation eventually.
[Answer]
# Pyth, 62 bytes
```
JvXz"() ,][")u?qJQG&=J?K}Quu+GHNY<J1)hJtJ++XWK"(cdr "\d\aG\)\l
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?input=%286%201%203%29%0A3&test_suite=0&code=JvXz%22%28%29%20%2C%5D%5B%22%29u%3FqJQG%26%3DJ%3FK%7DQuu%2BGHNY%3CJ1%29hJtJ%2B%2BXWK%22%28cdr%20%22%5Cd%5CaG%5C%29%5Cl&input_size=2&test_suite_input=%286%201%203%29%0A3%0A%284%205%20%281%202%20%287%29%209%20%2810%208%2014%29%29%29%0A8%0A%281%2012%201992%29%0A1) or [Test Suite](http://pyth.herokuapp.com/?input=%286%201%203%29%0A3&test_suite=1&code=JvXz%22%28%29%20%2C%5D%5B%22%29u%3FqJQG%26%3DJ%3FK%7DQuu%2BGHNY%3CJ1%29hJtJ%2B%2BXWK%22%28cdr%20%22%5Cd%5CaG%5C%29%5Cl&input_size=2&test_suite_input=%286%201%203%29%0A3%0A%284%205%20%281%202%20%287%29%209%20%2810%208%2014%29%29%29%0A8%0A%281%2012%201992%29%0A1)
### Explanation:
The first bit `JvXz"() ,][")` replaces the chars `"() "` with the chars `"[],"` in the input string, which ends up in a representation of a Python-style list. I evaluate it and store it in `J`.
Then I reduce the string `G = "l"` with `u...\l`. I apply the inner function `...` repeatedly to `G`, until the value of `G` doesn't change anymore and then print `G`.
The inner function does the following: If `J` is already equal to the input number, than don't modify `G` (`?qJQG`). Otherwise I'll flatten the the list `J[:1]` and check if the input number is in that list and save this to the variable `K` (`K}Quu+GHNY<J1)`). Notice that Pyth doesn't have a flatten operator, so this is takes quite a few bytes. If `K` is true, than I update J with `J[0]`, otherwise with `J[1:]` (`=J?KhJtJ`). And then I replace `G` with `"(cdr G)"` and replace the `d` the `a`, if `K` is true (`++XWK"(cdr "\d\aG\)`).
[Answer]
## Scheme (R5RS), 102 bytes
```
(let g((l(read))(n(read))(o'l))(if(pair? l)(or(g(car l)n`(car,o))(g(cdr l)n`(cdr,o)))(and(eq? n l)o)))
```
[Answer]
# CJam, 59
```
q"()""[]"er~{:AL>{0jA1<e_-_A(?j'l/"(car l)"@{2'dt}&*}"l"?}j
```
[Try it online](http://cjam.aditsu.net/#code=q%22()%22%22%5B%5D%22er~%7B%3AAL%3E%7B0jA1%3Ce_-_A(%3Fj'l%2F%22(car%20l)%22%40%7B2'dt%7D%26*%7D%22l%22%3F%7Dj&input=(4%205%20(1%202%20(7)%209%20(10%208%2014)))%208)
**Explanation:**
```
q read the input
"()""[]"er replace parentheses with square brackets
~ evaluate the string, pushing an array and a number
{…}j calculate with memoized recursion using the array as the argument
and the number as the memozied value for argument 0
:A store the argument in A
L> practically, check if A is an array
if A is a (non-empty) array, compare with an empty array
(result 1, true)
if A is a number, slice the empty array from that position
(result [], false)
{…} if A is an array
0j get the memoized value for 0 (the number to search)
A1< slice A keeping only its first element
e_ flatten array
- set difference - true iff the number was not in the array
_ duplicate the result (this is the car/cdr indicator)
A( uncons A from left, resulting in the "cdr" followed by the "car"
? choose the cdr if the number was not in the flattened first item,
else choose the car
j call the block recursively with the chosen value as the argument
'l/ split the result around the 'l' character
"(car l)" push this string
@ bring up the car/cdr indicator
{…}& if true (indicating cdr)
2'dt set the character in position 2 to 'd'
* join the split pieces using the resulting string as a separator
"l" else (if A is not an array) just push "l"
(we know that when we get to a number, it is the right number)
? end if
```
[Answer]
## PHP - 177 bytes
I've added some newlines for readability:
```
function f($a,$o,$n){foreach($a as$v){if($n===$v||$s=f($v,$o,$n))return
'(car '.($s?:$o).')';$o="(cdr $o)";}}function l($s,$n){echo f(eval(strtr
("return$s;",'() ','[],')),l,$n);}
```
Here is the ungolfed version:
```
function extractPhp($list, $output, $number)
{
foreach ($list as $value)
{
if (is_int($value))
{
if ($value === $number) {
return '(car '. $output .')';
}
}
else
{
$subOutput = extractPhp($value, $output, $number);
if ($subOutput !== null) {
return '(car '. $subOutput .')';
}
}
$output = '(cdr '. $output .')';
}
}
function extractLisp($stringList, $number)
{
$phpCode = 'return '. strtr($stringList, '() ','[],') .';';
$list = eval($phpCode);
echo extractPhp($list, 'l', $number);
}
```
[Answer]
# Haskell, ~~190~~ 188 bytes
`l "(4 5 (1 2 (7) 9 (10 8 14)))" 8`
evaluates to
`"(car (cdr (car (cdr (cdr (cdr (cdr (car (cdr (cdr l))))))))))"`
```
l(h:s)n=c$i(show n)s""""
i n(h:s)t l|h>'/'&&h<':'=i n s(t++[h])l|t==n='a':l|h=='('=j$'a':l|h==')'=j$tail$dropWhile(=='d')l|0<1=j$'d':l where j=i n s""
c[]="l"
c(h:s)="(c"++h:"r "++c s++")"
```
[Answer]
# Common Lisp, ~~168~~ 155 bytes
Some stupid recursion thing, it could probably be condensed a bit more:
```
(lambda(l e)(labels((r(l o)(setf a(car l)d(cdr l)x`(car,o)y`(cdr,o))(if(equal e a)x(if(atom a)(r d y)(if(find e l)(r d y)(if d(r d y)(r a x)))))))(r l'l)))
```
Pretty printed:
```
(lambda (l e)
(labels ((r (l o)
(setf a (car l) d (cdr l)
x `(car ,o) y `(cdr ,o))
(if (equal e a) x
(if (atom a)
(r d y)
(if (find e l)
(r d y)
(if d
(r d y)
(r a x)))))))
(r l 'l)))
```
] |
[Question]
[
Several months ago I had this question as a pre-screening puzzle for an interview. Recently when thinking about blog material, it popped in my head as a good example to use for solving a problem functionally. I'll post my solution to this as soon as I'm done writing my blog post.
NOTE: [This question was asked on StackOverflow a year ago](https://stackoverflow.com/questions/15474648/incremental-puzzle-in-c-sharp), and was downvoted after a few (incorrect) answers. I assume it was downvoted for being an obvious interview or homework question. Our answers here should be code golfed deep enough for someone not to think about using them!
---
In a race, you bet using the following strategy. Whenever you lose a bet, you double the value of the bet for the next round. Whenever you win, the bet for the next round will be one dollar. You start the round by betting one dollar.
For example, if you start with 20 dollars, and you win the bet in the first round, lose the bet in the next two rounds and then win the bet in the fourth round, you will end up with 20+1-1-2+4 = 22 dollars.
You are expected to complete the function, `g`, which takes two arguments:
1. The first argument is an integer `a` which is the initial money we amount we have when we start the betting.
2. The second argument is a string `r`. The ith character of outcome will be either 'W' (win) or 'L' (lose), denoting the result of the ith round.
Your function should return the amount of money you will have after all the rounds are played.
If at some point you don't have enough money in your account to cover the value of the bet, you must stop and return the sum you have at that point.
**Sample run**
```
1st round - Loss: 15-1 = 14
2nd round - Loss: 14-2 = 12 (Bet doubles)
3rd round - Loss: 12-4 = 8
4th round - Win: 8 + 8 = 16
5th round - Loss:16-1 = 15 (Since the previous bet was a win, this bet has a value of 1 dollar)
6th round - Loss: 15-2 = 13
7th round - Loss: 13-4 = 9
8th round - Loss: 9-8 = 1
```
The function returns `1` in this case
The winner is determined by least number of characters INSIDE of the implied function definition. Cooperate by language if desired. I know mine can be improved!
[Answer]
### GolfScript, 33 characters
```
{
1\{2$2$<!{1&{+1}{:b-b.+}if.}*;}/;
}:g;
```
*Examples ([online](http://golfscript.apphb.com/?c=ewoxXHsyJDIkPCF7MSZ7KzF9ezpiLWIuK31pZi59Kjt9LzsKfTpnOwoKCjEzICdMTExXTExMTCcgZyBwCjQgJ0xXV0xXTFdXV0wnIGcgcAo1ICdMTExXV1dMTFdMV1cnIGcgcAoyICdMVycgZyBwCg%3D%3D&run=true)):*
```
> 13 'LLLWLLLL'
6
> 4 'LWWLWLWWWL'
9
> 5 'LLLWWWLLWLWW'
2
> 2 'LW'
1
```
*Annotated code:*
```
1\ # prepare stack a b r
{ # for each char in r
2$2$<!{ # if a>=b
1& # take last bit of character (i.e. 0 for L and 1 for W)
{ # if W
+ # a <- a+b
1 # b <- 1
}{ # else
:b- # a <- a-b
b.+ # b <- 2*b
}if # end if
. # create dummy value
}* # end if
; # drop (i.e. either the dummy or the character)
}/ # end for
; # discard current bet value
```
[Answer]
# Python 2, ~~72~~ ~~68~~ 62 bytes
```
def g(a,s,n=1):
for c in s:
if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
return a
```
Call it like so: `g(15,'LLLWLLLL')`.
This simply loops through the string, changing the value of the money that we have based on the character.
Here is a sample program that runs tests on this function:
```
import random
def g(a,s,n=1):
for c in s:
if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
return a
for i in range(14):
s=''.join(('L','W')[random.randint(0, 1)] for e in range(random.randint(10, 15)))
print'g(%i,%s):'%(i,`s`),
print g(i,s)
```
Sample output:
```
g(0,'LLWWWWWWLWWWWW'): 0
g(1,'WLLWWWWWWWW'): 1
g(2,'WWWLLLWLLW'): 2
g(3,'LLLLWLWLWWWWLL'): 0
g(4,'LWWWWLWLWWW'): 12
g(5,'WWLWWLLWWW'): 12
g(6,'LLLWWWLLLLWLLWL'): 3
g(7,'WWLLWWLWLWLWLLL'): 7
g(8,'WLLLWWWWWLLWLL'): 2
g(9,'WWWLLWLLLLLWL'): 6
g(10,'LWWWWLLLWL'): 7
g(11,'WLLLLWLWWWW'): 5
g(12,'WLLWWLWWWL'): 17
g(13,'LLLWLLWLWLWLWW'): 6
```
With a little change to the tester, we can get the average profit of many runs:
```
import random
def g(a,s,n=1):
for c in s:
if a>=n:a,n=((a+n,1),(a-n,2*n))[c<'W']
return a
r=[]
for i in range(5000):
for i in range(1000):
s=''.join(('L','W')[random.randint(0, 1)] for e in range(random.randint(10, 15)))
r+=[i-g(i,s)]
a=0
for n in r:
a+=n
print float(a)/len(r)
```
Sample output (took quite a while, since we are calling the function `5000000` times):
```
-0.0156148
```
Edit: Thanks to Howard and Danny for further golfing.
EDIT: now the program checks for whether there is enough money to make the bet. This actually saves bytes.
[Answer]
### R, 95 characters
```
g=function(a,r){n=1;for(i in 1:nchar(r)){s=substr(r,i,i);if(s=='L'){a=a-n;n=n*2}else{a=a+n;n=1};if(n>a)break};a}
```
Indented:
```
g=function(a,r){
n=1
for(i in 1:nchar(r)){
s=substr(r,i,i)
if(s=='L'){
a=a-n
n=n*2
}else{
a=a+n
n=1
}
if(n>a)break
}
a
}
```
Usage:
```
> g(15,'LLWLLLL')
[1] 1
> g(20,'WLLW')
[1] 22
> g(13,'LLWLLLLWWLWWWLWLWW')
[1] 7
```
[Answer]
# J - 63 55 char
Now with the added bonus of not being incorrect! It's even exactly as long as before.
```
((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L')
```
Takes the starting amount of money as the left argument and the win/loss streak on the right.
Explanation: The program splits evenly into something like a composition of two functions, both detailed below. The first turns the win/loss streak into the values of the bets, with corresponding sign, and then the second actually figures out the answer given the initial money and this transformed win/loss streak.
```
;@('W'<@(2^i.@#);.1@,}:)*_1^=&'L' NB. win/loss as sole argument
_1^=&'L' NB. -1 for every L, +1 for W
<@( );.1 NB. split vector into streaks:
'W' ,}: NB. cut on wins, shift right by 1
2^i.@# NB. for each, make doubling run
;@( )* NB. unsplit, multiply by signs
(+/\@,(0{<#[)_,~|@]) NB. money on left, above result on right
|@] NB. absolute value of bets
_,~ NB. append infinity to end
+/\@, NB. partial sums with initial money
( < ) NB. 1 whenever money in account < bet
#[ NB. select those money values corresp. to 1s
0{ NB. take first such item
```
Note that we prepend the money to the bets before taking the partial sums, but we append the infinite bet to the end of the list of bet values. This is what shifts the value of the account overtop of the next bet, and using infinity allows us to always have the last element as a catch-all.
Usage:
```
15 ((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L') 'LLLWLLLL'
1
NB. naming for convenience
f =: ((+/\@,(0{<#[)_,~|@]);@('W'<@(2^i.@#);.1@,}:)*_1^=&'L')
20 f 'WLLW'
22
2 f 'LW'
1
13 f 'LLWLLLLWWLWWWLWLWW'
7
12 13 14 15 28 29 30 31 (f"0 _) 'LLWLLLLWWLWWWLWLWW' NB. for each left argument
6 7 0 1 14 15 39 40
```
[Answer]
# JavaScript (ECMAScript 6 Draft) - ~~62~~ ~~51~~ 50 Characters (in function body)
```
function g(a,r,t=0,b=1)
a>=b&&(c=r[t])?g((c=c>'L')?a+b:a-b,r,t+1,c||2*b):a
```
Defines a recursive function `g` with two arguments:
* `a` - the current amount of money you have; and
* `r` - the string of wins/losses.
And two optional arguments:
* `t` - the index of the current round of betting (initially `0`)
* `b` - the amount of money for the current bet (again initially `1`).
Ungolfed:
```
function g(a,r,t=0,b=1){ // declare a function g with arguments a,r,t,b where
// t defaults to 0 and b defaults to 1
c = r[t]; // get the character in the win/loss string for the current
// round.
if ( a>=b // check if we have enough money
&& c ) // and if the string has not ended
{
if ( c > 'L' ) // check if we've won the round
{
return g(a+b,r,t+1,1); // if so call g again adding the winnings and resetting the
// cost.
} else {
return g(a-b,r,t+1,2*b); // otherwise, subtract from the total money and double the
// cost.
}
} else {
return a; // If we've run out of money or got to the end then return
// the current total.
}}
```
# JavaScript (ECMAScript 6) - ~~61~~ ~~58~~ 54 Characters (in function body)
```
function g(a,r)
(b=1,[b=b>a?b:x>'L'?(a+=b,1):(a-=b,b*2)for(x of r)],a)
```
Explanation:
```
(b=1, // Initialise the cost to 1
[ // for each character x of r using array comprehension
b=
b>a?b // if we have run out of money do b=b
:x>'L'?(a+=b,1) // else if we've won collect the winnings and reset b=1
:(a-=b,2*b) // else subtract the cost from the total money and double
// the cost for next round.
for(x of r)] // Repeat for each character
// array.
,a) // Finally, return a.
```
**Tests**
```
console.log(g(0,'LLLLLWWLWWLW')) // 0
console.log(g(1,'WWWLLLWWWWLLWW')) //1
console.log(g(2,'LLWLWWWWWWWL')) //1
console.log(g(3,'WWWWWWWLLLWL')) //3
console.log(g(4,'LWWLWLWWWL')) //9
console.log(g(5,'LLLWWWLLWLWW')) //2
console.log(g(6,'LWLLLLWWLWWW')) //0
console.log(g(7,'WWLWWLLLWLWLW')) //4
console.log(g(8,'WWLWWLLWLWL')) //13
console.log(g(9,'WWWLLLWLLWLWWW')) //5
console.log(g(10,'WLWLLWWWWWWWL')) //18
console.log(g(11,'WLWLWLWLLLWLLW')) //17
console.log(g(12,'WWLWWWLLWL')) //17
console.log(g(13,'WWWWLWLWWW')) //21
console.log(g(15,'LLLW')) //16
console.log(g(15,'LLLL')) //0
console.log(g(14,'LLLL')) //7
console.log(g(2,'LW')) //1
console.log(g(2,'LL')) //1
console.log(g(2,'WLL')) //0
```
[Answer]
# Python, 74 bytes
```
def g(a,r,b=1):
for l in r:
if l>"L":a+=b;b=1
else:a-=b;b*=2
return a
```
I defined function g which takes a (the amount of money you have at start) and r (which is the results of the bets)
It initializes the amount of the first bet at 1.
Then for each result of the bets, if it is a win ("W" in r) you gain the money and bet comes back to 1. Else you lose the amount of the bet, and the amount for the next bet doubles.
Finally it returns the money you have.
You can use it like this:
```
print g(20,"WLLW") # 22
print g(15,"LLLWLLLL") # 1
```
I think this can be golfed furthermore.
[Answer]
# C, 107 characters
```
f(int a,char*r,int n){return*r&&n<a?*r<77?f(a-n,r+1,n*2):f(a+n,r+1,1):a;}g(int a, char*r){return f(a,r,1);}
```
I'm using a recursive function here, because most of the time the implementation is shorter. But I'm not quite sure if it is the case here, because I needed to make an additional wrapper function so my function does in fact only take 2 arguments. The third argument in function `f` is needed for the current bet (the accumulator).
Without the wrapper function this solution would only be 73 characters long, but you would need to pass an additional parameter with the value 1 (the inital bet) to get the proper result.
ungolfed:
```
f(int a,char*r,int n){
return *r&&n<a
?*r<77
?f(a-n,r+1,n*2)
:f(a+n,r+1,1)
:a;
}
g(int a,char*r){
return f(a,r,1);
}
```
[Answer]
# C, 90
```
g(int a,char*r){int c=1;while(*r){*r++%2?c=1,a++:(c*=2);if(c>a){c/=2;break;}}return++a-c;}
```
[Answer]
# Javascript, 63
```
function g(a,s){x=1;for(i in s)if(x<=a)s[i]>'L'?(a+=x,x=1):(a-=x,x*=2);return a}
```
Sample runs:
```
console.log(g(15, 'LLLWLLLL')); //1
console.log(g(20, 'WLLW')); //22
console.log(g(13, 'LLWLLLLWWLWWWLWLWW')); //7
```
[**JSFiddle w/ logging**](http://jsfiddle.net/98Prq/)
Ungolfed:
```
function g(a,s){
x=1; //bet starts at 1
for(i in s) //loop through win/lose string
if(x<=a) //check if we still have money to bet
s[i]>'L'?
(a+=x,x=1): //win: add the bet amount to your total, and reset bet to 1
(a-=x,x*=2); //lose: subtract the bet amount from your total, and double your bet
return a //return your money
}
```
[Answer]
# Javascript (*ES5*) 69 64 60 bytes within function
```
function g(a,r){b=1;for(i in r)b=b>a?b:r[i]>'L'?(a+=b,1):(a-=b,b*2);return a}
```
Variation: (*same length*)
```
function g(a,r,b){for(i in r)b=b?b>a?b:r[i]>'L'?(a+=b,1):(a-=b,b*2):1;return a}
```
Test cases: (*taken from plannapus's solution*)
```
g(15,'LLWLLLL'); // 1
g(20,'WLLW'); // 22
g(13,'LLWLLLLWWLWWWLWLWW'); // 7
```
[Answer]
# Haskell, 62
```
g a=fst.foldl(\(t,b)l->if l=='W'then(t+b,1)else(t-b,2*t))(a,1)
```
or with both arguments named (65 chars):
```
g a r=fst$foldl(\(t,b)l->if l=='W'then(t+b,1)else(t-b,2*t))(a,1)r
```
Note that `g a r = 1 + a + the number of Ws in r + the number of trailing Ls in r` (69):
```
g a r=a+1+l(filter(=='W')r)-2^l(takeWhile(/='W')(reverse r))
l=length
```
[Answer]
# Python 2 – 65 bytes
Now beaten by the current best Python solution, but I cannot not share it:
```
def g(r,a,b=1):
if r>"">a>=b:a=g(r[1:],*[(a+b,1),(a-b,b*2)][r[0]<"W"])
return a
```
As some other Python solutions, I use the function arguments for declaring `b` outside the function definition, but as the function is recursive, this actually serves some purpose other than golfing here.
I also needed to change the order of the function arguments in order for the [tuple unpacking into function arguments](https://stackoverflow.com/questions/1993727/expanding-tuples-into-arguments) to work.
In case you wonder, `r>"">a>=b` is short for `r and a>=b`.
[Answer]
# Ruby, 76 64 (in function body) bytes
EDIT :
improved the answer by removing 3 bytes :
```
n=1;r.each_char{|c|;c>'L'?(a+=n;n=1):(a-=n;n*=2);break if n>a};a
```
---
using func (82 bytes) :
```
def g(a,r);n=1;r.each_char{|c|;c>'L'?(a,n=a+n,1):(a,n=a-n,n*2);break if n>a};a;end
```
using lambda (76 bytes) :
```
g=->a,r{n=1;r.each_char{|c|;c>'L'?(a,n=a+n,1):(a,n=a-n,n*2);break if n>a};a}
```
the run :
```
p g.call(15, 'LLLWLLLL') # 1
p g.call(20, 'WLLW') # 22
p g.call(13, 'LLWLLLLWWLWWWLWLWW') # 7
```
[Answer]
# C#, 74 characters inside method
My very first attempt on this site...
```
int b=1;foreach(var c in r)if(b<=a){a+=c>'L'?b:-b;b=c>'L'?1:b*2;}return a;
```
Or, more readable:
```
int bet = 1;
foreach (var chr in r)
{ // these brackets are left out in short version
if (bet <= a)
{
a += chr > 'L' ? bet : -bet;
bet = chr > 'L' ? 1 : bet * 2;
}
}
return a;
```
Pretty naive, not that many tricks... mainly taking advantage of char being ordinal and string being enumerable. Saving a few characters by extraneous looping when player runs out of money.
[Answer]
# Golfscript, ~~51~~ ~~41~~ ~~36~~ 35 bytes
### Inner function
```
1\{@2$-@2*@(1&{@@+1@}*.3$3$<!*}do;;
```
This assumes that we start with a positive amount of money and that the win-loss string will be non-empty, so that at least one bet can be performed.
### Example
```
{
# Push initial bet amount.
1\
# STACK: Money Bet Outcomes
{
# Subtract bet amount from money.
@2$-
# STACK: Bet Outcomes Money
# Double bet amount.
@2*
# STACK: Outcomes Money Bet
# Remove first character from win-loss string and check if its ASCII code is odd.
@(1&
# STACK: Money Bet Outcomes Boolean
# If it is, we've won, so add the doubled bet amount to the money and push 1 as the
# new bet amont.
{@@+1@}*
# STACK: Money Bet Outcomes
# Duplicate win-loss string, bet amonut and money.
.3$3$
# STACK: Money Bet Outcomes Outcomes Bet Money
# If the next bet amount is less than our money and the win-loss string is not empty,
# repeat the loop.
<!*
# STACK: Money Bet Outcomes Boolean
}do
# STACK: Money Bet Outcomes
;;
# STACK: Money
}:f # Define function.
]; # Clear stack.
20 'WLLW' f
2 'LW' f
13 'LLWLLLLWWLWWWLWLWW' f
14 'LLWLLLLWWLWWWLWLWW' f
]p # Print results as array.
```
gives
```
[22 1 7 0]
```
[Try it online.](http://golfscript.apphb.com/?c=ewogICMgUHVzaCBpbml0aWFsIGJldCBhbW91bnQuCiAgMVwKICAjIFNUQUNLOiBNb25leSBCZXQgT3V0Y29tZXMKICB7CiAgICAjIFN1YnRyYWN0IGJldCBhbW91bnQgZnJvbSBtb25leS4KICAgIEAyJC0KICAgICMgU1RBQ0s6IEJldCBPdXRjb21lcyBNb25leQogICAgIyBEb3VibGUgYmV0IGFtb3VudC4KICAgIEAyKgogICAgIyBTVEFDSzogT3V0Y29tZXMgTW9uZXkgQmV0CiAgICAjIFJlbW92ZSBmaXJzdCBjaGFyYWN0ZXIgZnJvbSB3aW4tbG9zcyBzdHJpbmcgYW5kIGNoZWNrIGlmIGl0cyBBU0NJSSBjb2RlIGlzIG9kZC4KICAgIEAoMSYKICAgICMgU1RBQ0s6IE1vbmV5IEJldCBPdXRjb21lcyBCb29sZWFuCiAgICAjIElmIGl0IGlzLCB3ZSd2ZSB3b24sIHNvIGFkZCB0aGUgZG91YmxlZCBiZXQgYW1vdW50IHRvIHRoZSBtb25leSBhbmQgcHVzaCAxIGFzIHRoZQogICAgIyBuZXcgYmV0IGFtb250LgogICAge0BAKzFAfSoKICAgICMgU1RBQ0s6IE1vbmV5IEJldCBPdXRjb21lcwogICAgIyBEdXBsaWNhdGUgd2luLWxvc3Mgc3RyaW5nLCBiZXQgYW1vbnV0IGFuZCBtb25leS4KICAgIC4zJDMkCiAgICAjIFNUQUNLOiBNb25leSBCZXQgT3V0Y29tZXMgT3V0Y29tZXMgQmV0IE1vbmV5CiAgICAjIElmIHRoZSBuZXh0IGJldCBhbW91bnQgaXMgbGVzcyB0aGFuIG91ciBtb25leSBhbmQgdGhlIHdpbi1sb3NzIHN0cmluZyBpcyBub3QgZW1wdHksCiAgICAjIHJlcGVhdCB0aGUgbG9vcC4KICAgIDwhKgogICAgIyBTVEFDSzogTW9uZXkgQmV0IE91dGNvbWVzIEJvb2xlYW4KICB9ZG8KICAjIFNUQUNLOiBNb25leSBCZXQgT3V0Y29tZXMKICA7OwogICMgU1RBQ0s6IE1vbmV5Cn06ZgoKXTsgIyBDbGVhciBzdGFjay4KCjIwICdXTExXJyBmCjIgICdMVycgZgoxMyAnTExXTExMTFdXTFdXV0xXTFdXJyBmCjE0ICdMTFdMTExMV1dMV1dXTFdMV1cnIGYKCl1wICMgUHJpbnQgcmVzdWx0cyBhcyBhbiBhcnJheS4%3D "Web GolfScript")
[Answer]
## C#, 123
```
return q.Aggregate(new{b=1,c=w,x=1},(l,o)=>l.x<0?l:o=='W'?new{b=1,c=l.c+l.b,x=1}:new{b=l.b*2,c=l.c-l.b,x=l.c-l.b-l.b*2}).c;
```
[The .NET Fiddle](https://dotnetfiddle.net/oOO7fe)
[A blog post explaining](http://www.smokingcode.com/2014/04/solving-programming-puzzle-with-lambda.html)
[Answer]
# Java, 93 bytes (inside function)
-2 bytes thanks to ceilingcat
```
int b=1;for(int c:r.getBytes()){if(m<b)return m;if(c<87){m-=b;b*=2;}else{m+=b;b=1;}}return m;
```
[Try it online!](https://tio.run/##fY69rsIwDEb3PkXElPBTCcQVVzd0YS4TQwfEkJSAAk2KEhcJRXn24hTEdhlsy/bRp3MRdzG7HK993QjvyVZoGzIPAnRNtAXitaFpminZgdP2TBwLfbrIYs5PrRu@9Z/Lzwo2D1CeMhb0iZq1ZE5B5ywxHPd6/btiwcwKyeW4WPCoGq@CmaQdk2L8wH3Mbp1sUODtcW/1kRg0oy@F/UGwkO0eHpTJ2w7yG16hsTTJzn@mo7IsK6xyxBj/j1siVlXIVdi/ge88pAb4G7pImQMQY/8E)
[Answer]
# Ruby, 84 characters
```
def g(a,r,n=1)
return a if !r[0]||n>a
s=r[1..-1]
r[0]<?M?g(a-n,s,n*2):g(a+n,s,1)
end
```
Same approach as my other answer in C, but I wanted to try ruby for Code-Golfing. The advantage to the C version is that I don't need to create a wrapper function, I can simply use the default values for parameters.
[Answer]
# K, 76
```
g:{x+/-1_last'{(,1_*x),(("LW"!/:((2*;{1});(-:;::)))@\:**x)@\:x 1}\[(y;1;0)]}
```
.
```
k)g[15;"LLLWLLLL"]
1
k)g[20;"WLLW"]
22
k)g[50;"WLLLWLWLWLWLW"]
56
```
[Answer]
# Python, 86
```
def y(a,s):
for l in s.split('W'):
a+=1;k=2**len(l)
if k>a:return int(bin(a)[3:],2)
return a-k
```
I know this is nowhere near the shortest solution, but I wanted to demonstrate a different approach, that iterates over loss streaks rather than individual bets. `int(bin(a)[3:],2)` gives the integer with the most significant bit from the binary representation of `a` deleted, which is the amount of money the person will have after losing increasing powers of 2 until he or she can no longer bet, because a is currently 1 higher than his or her actual amount of money. This version assumes the initial capital is positive.
[Answer]
# C - ~~64~~ 59 (Inside function)
Yet another C answer. It takes advantage of the fact that the value of the variable stays on the stack. So this my fail with some compilers, but it did work properly wherever I tested. Also, I took the `%2` from tia to save a character. Sorry!
```
f(int s,char*r){
int a=1;
for(;*r&&(*r++%2?s+=a,a=1:s<a?0:(s-=a,a*=2)););
a=s;
}
```
[Answer]
## Batch - 212
```
@echo off&setlocal enabledelayedexpansion&set r=%2&set a=%1&set c=1&powershell "&{'%2'.length-1}">f&set/pl=<f
for /l %%a in (0,1,%l%)do if "!r:~%%a,1!"=="L" (set/aa-=!c!&set/ac*=2) else set/aa+=!c!&set c=1
echo %a%
```
Expample -
```
H:\uprof>bet.bat 15 LLLWLLLL
1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 38 bytes
```
V¬r@Z=WX<Z?X:Y¶'L?W=ZÑX-Z:(W=1X+Z}UW=1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VqxyQFo9V1g8Wj9YOlm2J0w/Vz1a0VgtWjooVz0xWCtafVVXPTE=&input=NQonTExMV1dXTExXTFdXJw==)
Probably needs some golfing :) But it seems to getting correct results.
**NOTE** This is a full program that is trivial to turn into a function by prepending `UV{`. The byte count inside the function will be the same.
Transpiled JS Explained:
```
// V: input string of W's and L's
V
// split V into an array of characters
.q()
// reduce
.r(function(X, Y, Z) {
return
// W contains the current bet,
// save it to a temp variable Z
Z = W,
// do we have enough to bet?
X < Z
// not enough to bet, return the previous amount
? X
// we can bet, did we lose this round
: Y === "L"
// we lost, increment bet and decrease holdings
? (W = Z * 2, X - Z)
// we won, reset bet and increase holdings
: (W = 1, X + Z)
},
// U: initial holdings
U,
// initialize bet to 1
W = 1
)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~68~~ 81 bytes
```
param($n,$s)$w=1;$s|% t*y|%{if($n-ge$w){$n+=(-$w,$w)[$_%2];$w/=(.5,$w)[$_%2]}};$n
```
[Try it online!](https://tio.run/##VZHLboMwEEX3/gorGordkjamSV/IUj@AVTeziFCUBaSRUjcKVKgifDv1C1wsJM@cuVzP2OfvtrzUn@XpNEAlu@G8v@y/GKgEag6tFBnU14g2t7/XqDtWurA8lNDyDtSdZEtoE51sYRelRQbtg2T3m0D6PgM19IRAU9ZNLck7I4yukjg3C9F@MU@opiKJUacGmw1Hnho1WmoKnj5aNfo/RrrWWmOZ/1Nu7GnOM7g@GeXUxEifjWvuPUNrLxPGcNbr1K9vz3Ghp0PLZg0L4bAt2bLnqffGMIbww81s/RjzzAzgydpdqsvMnWEIA0UTU8LHF9Fvuvj4UeqoDm8UGOy2q4K7QBR8QW6gohZSS/rhDw "PowerShell – Try It Online")
This challenge needs some very awkward assignments meaning I couldn't chain together one big update. It does use the fact that 'W' is 87 in ASCII and 'L' is 76 so modding by 2 gives you access to easy true/false values. `|% t*y` is the standard toCharArray shortcut and updating the wager using division turned out to be the cheapest way I could find (divides it either by a half on a loss (doubling it), or divides it by itself on a win (setting it to 1)).
Plus many bytes because I missed constraint. Will work on golfing down the patch
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
vDX@iy'WQiX+1UëXxU-
```
Port of [*@Howard*'s GolfScript answer](https://codegolf.stackexchange.com/a/26263/52210), so make sure to upvote him as well!
Note that 05AB1E has no functions, so this is a full program instead.
Takes the string input first, and the integer input second (newline delimited in STDIN).
[Try it online](https://tio.run/##yy9OTMpM/f@/zCXCIbNSPTwwM0LbMPTw6oiKUN3//318fMKB2IfL0BQA) or [verify some more test cases](https://tio.run/##lZA7DsIwDIavUmVhIEgNbyYYOmYBqXKlqlKLYOgCA1IFQ1cOwDU4BAM34SLFcRLTIhaGpsnn1@//eCq25b6pLpsoF89HUBx2Af5e11sglrmKmypKVuWlB@sy6av4eU/O8aCp61o2aSq01oCfFlJNMhl0wMgCACSAp5BjTsEnUSFdGd6GPqqpBgwLiVG6KTJVSJXLpL5gew99JrhsZP8p4MHIpq6bdr1IzKwNgSbM2/qcICEXlhJhgSpkShGKIlafrmBlq88uvqM305aw1fr74fdjPzpXY3LI3vG6zgee8SM0ZkXG/ewN).
**Explanation:**
```
v # Loop over each character `y` of the (implicit) input-string:
D # Duplicate the current integer
# (which is the implicit input-integer in the first iteration)
X@i # If the integer is larger than or equal to variable `X`:
# (NOTE: variable `X` is 1 by default)
y'WQi '# If the current character `y` is a 'W':
X+ # Increase the integer by `X`
1U # And reset variable `X` to 1
ë # Else (the current character `y` is an 'L' instead):
X - # Decrease the integer by `X`
xU # And set variable `X` to double its current value
# (the integer at the top of the stack is implicitly output after the loop)
```
] |
[Question]
[
In [FIPS-197](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf) (the [Advanced Encryption Standard](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard), known as AES), it is made heavy use of `SubBytes`, which could be implemented as
```
unsigned char SubBytes(unsigned char x) {
static const unsigned char t[256] = {
0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16};
return t[x];}
```
This function is not arbitrary; it is a reversible mapping, consisting of an inversion in a Galois Field followed by an affine transformation. All the details are in [FIPS-197](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf) section 5.1.1 or [here](http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf) section 4.2.1 (under a slightly different name).
One problem with implementation as a table is that it opens to so-called [cache-timing attacks](http://cr.yp.to/antiforgery/cachetiming-20050414.pdf).
Thus your mission is to devise an exact replacement for the above `SubBytes()` function, that exhibits constant-time behavior; we'll assume that's the case when nothing depending on the input `x` of `SubBytes` is used either:
* as an array index,
* as the control operand of `if`, `while`, `for`, `case`, or operator `?:`;
* as any operand of operators `&&`, `||`, `!`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `*`, `/`, `%`;
* as the right operand of operators `>>`, `<<`, `*=`, `/=`, `%=`, `<<=`, `>>=`.
The winning entry will be one with the lowest cost, obtained from the number of operators executed in the input-dependent data path, with a weight of 5 for unary operators `-` and `~` as well as for `<<1`, `>>1`, `+1`, `-1`; weight of 7 for all other operators, shifts with other counts, or adds/subs of other constants (type casts and promotions are free). By principle, that cost is unchanged by unrolling loops (if any), and independent of the input `x`. As a tie-breaker, the answer with the shortest code after removing whitespace and comments wins.
I plan to designate an entry as answer as early as I can in year 2013, UTC. I will consider answers in languages that I've some knowledge of, ranking them as a straight translation to C not optimized for size.
Apologies for the initial omission of `+1` and `-1` in the favored operators, of free casts and promotions, and ranking of size. Note that `*` is prohibited both when unary, and as multiplication.
[Answer]
## Score: 940 933 926 910, field tower approach
```
public class SBox2
{
public static void main(String[] args)
{
for (int i = 0; i < 256; i++) {
int s = SubBytes(i);
System.out.format("%02x ", s);
if (i % 16 == 15) System.out.println();
}
}
private static int SubBytes(int x) {
int fwd;
fwd = 0x010001 & -(x & 1); x >>= 1; // 7+5+7+5+ | 24+
fwd ^= 0x1d010f & -(x & 1); x >>= 1; // 7+7+5+7+5+ | 31+
fwd ^= 0x4f020b & -(x & 1); x >>= 1; // 7+7+5+7+5+ | 31+
fwd ^= 0x450201 & -(x & 1); x >>= 1; // 7+7+5+7+5+ | 31+
fwd ^= 0xce080d & -(x & 1); x >>= 1; // 7+7+5+7+5+ | 31+
fwd ^= 0xa20f0f & -(x & 1); x >>= 1; // 7+7+5+7+5+ | 31+
fwd ^= 0xc60805 & -(x & 1); x >>= 1; // 7+7+5+7+5+ | 31+
fwd ^= 0x60070e & -x; // 7+7+5+ | 19+
// Running total so far: 229
int p1;
{
int ma = fwd;
int mb = fwd >> 16; // 7+ | 7+
p1 = ma & -(mb&1); ma<<=1; // 7+5+7+5+ | 24+
p1 ^= ma & -(mb&2); ma<<=1; // 7+7+5+7+5+ | 31+
p1 ^= ma & -(mb&4); ma<<=1; // 7+7+5+7+5+ | 31+
p1 ^= ma & -(mb&8); // 7+7+5+7+ | 26+
int t = p1 >> 3; // 7+ | 7+
p1 ^= (t >> 1) ^ (t & 0xe); // 7+5+7+7+ | 26+
}
// Running total so far: 229 + 152 = 381
int y3, y2, y1, y0;
{
int Kinv = (fwd >> 20) ^ p1; // 7+7+
int w0 = Kinv & 1; Kinv >>= 1; // 7+5+
int w1 = Kinv & 1; Kinv >>= 1; // 7+5+
int w2 = Kinv & 1; Kinv >>= 1; // 7+5+
int w3 = Kinv & 1; // 7+
int t0 = w1 ^ w0 ^ (w2 & w3); // 7+7+7+
int t1 = w2 ^ (w0 | w3); // 7+7+
int t2 = t0 ^ t1; // 7+
y3 = t2 ^ (t1 & (w1 & w3)); // 7+7+7+
y2 = t0 ^ (w0 | t2); // 7+7+
y1 = w0 ^ w3 ^ (t1 & t0); // 7+7+7+
y0 = w3 ^ (t0 | (w1 ^ (w0 | w2))); // 7+7+7+7
}
// Running total so far: 381 + 24*7 + 3*5 = 564
int p2;
{
int ma = fwd;
p2 = ma & -y0; ma<<=1; // 7+5+5+ | 17+
p2 ^= ma & -y1; ma<<=1; // 7+7+5+5+ | 24+
p2 ^= ma & -y2; ma<<=1; // 7+7+5+5+ | 24+
p2 ^= ma & -y3; // 7+7+5+ | 19+
int t = p2 >> 3; // 7+ | 7+
p2 ^= (t >> 1) ^ (t & 0xe0e); // 7+5+7+7+ | 26
}
// Running total so far: 564 + 117 = 681
int inv8;
inv8 = 31 & -(p2 & 1); // 7+5+7+ | 19+
inv8 ^= 178 & -(p2 & 2); p2 >>= 2; // 7+7+5+7+7+ | 33+
inv8 ^= 171 & -(p2 & 1); // 7+7+5+7+ | 26+
inv8 ^= 54 & -(p2 & 2); p2 >>= 6; // 7+7+5+7+7+ | 33+
inv8 ^= 188 & -(p2 & 1); // 7+7+5+7+ | 26+
inv8 ^= 76 & -(p2 & 2); p2 >>= 2; // 7+7+5+7+7+ | 33+
inv8 ^= 127 & -(p2 & 1); // 7+7+5+7+ | 26+
inv8 ^= 222 & -(p2 & 2); // 7+7+5+7 | 26+
return inv8 ^ 0x63; // 7+ | 7+
// Grand total: 681 + 229 = 910
}
}
```
The structure is essentially the same as Boyar and Peralta's implementation - reduce inversion in GF(2^8) to inversion in GF(2^4), break it down into a linear prologue, a non-linear body, and a linear epilogue, and then minimise them separately. I pay some penalties for bit extraction, but I compensate by being able to do operations in parallel (with some judicious padding of the bits of `fwd`). In more detail...
### Background
As mentioned in the problem description, the S-box consists of an inversion in a particular implementation of the Galois field GF(2^8) followed by an affine transformation. If you know what both of those mean, skip this section.
An affine (or linear) transformation is a function `f(x)` which respects `f(x + y) = f(x) + f(y)` and `f(a*x) = a*f(x)`.
A field is a set `F` of elements with two special elements, which we'll call `0` and `1`, and two operators, which we'll call `+` and `*`, which respects various properties. In this section, assume that `x`, `y`, and `z` are elements of `F`.
* The elements of `F` form an abelian group under `+` with `0` as the identity: i.e. `x + y` is an element of `F`; `x + 0 = 0 + x = x`; each `x` has a corresponding `-x` such that `x + (-x) = (-x) + x = 0`; `x + (y + z) = (x + y) + z`; and `x + y` = `y + x`.
* The elements of `F` other than `0` form an abelian group under `*` with `1` as the identity.
* Multiplication distributes over addition: `x * (y + z) = (x * y) + (x * z)`.
It turns out that there are some quite severe limitations on finite fields:
* They must have a number of elements which is a power of a prime.
* They are isomorphic with all other finite fields of the same size (i.e. there's really only one finite field of a given size, and any others are just relabellings; call that field GF(p^k) where `p` is the prime and `k` is the power).
* The multiplicative group `F\{0}` under `*` is cyclic; i.e. there's at least one element `g` such that every element is a power of `g`.
* For powers greater than 1 there is a representation as univariate polynomials of order `k` of the field of the prime order. E.g. GF(2^8) has a representation in terms of polynomials of `x` over GF(2). In fact there's usually more than one representation. Consider `x^7 * x` in GF(2^8); it must be equivalent to some order-7 polynomial, but which? There are a lot of choices which give the right structure; AES chooses to make `x^8 = x^4 + x^3 + x + 1` (the lexicographically smallest polynomial which works).
So how do we compute an inverse in that particular representation of GF(2^8)? It's too chunky a problem to tackle directly, so we need to break it down.
### Field towers: representing GF(2^8) in terms of GF(2^4)
Instead of representing GF(2^8) with polynomials of 8 terms over GF(2) we can represent it with polynomials of 2 terms over GF(2^4). This time we need to choose a linear polynomial for `x^2`. Suppose we choose `x^2 = px + q`. Then `(ax + b) * (cx + d) = (ad + bc + acp)x + (bd + acq)`.
Is it easier to find an inverse in this representation? If `(cx + d) = (ax + b)^-1` we get the simultaneous equations
* `ad + (b + ap)c = 0`
* `bd + (aq)c = 1`
Let `D = [b(b+ap) + a^2 q]` and set `c = a * D^-1`; `d = (b + ap) * D^-1`. So we can do an inverse in GF(2^8) for the cost of a conversion to GF(2^4), an inverse and a few additions and multiplications in GF(2^4), and a conversion back. Even if we do the inverse by means of a table, we've reduced the table size from 256 to 16.
### Implementation details
To construct a representation of GF(4) we can choose between three polynomials to reduce `x^4`:
* `x^4 = x + 1`
* `x^4 = x^3 + 1`
* `x^4 = x^3 + x^2 + x + 1`
The most important difference is in the implementation of multiplication. For any of the three (which correspond to `poly` of 3, 9, f) the following will work:
```
// 14x &, 7x unary -, 3x <<1, 3x >>1, 3x >>3, 6x ^ gives score 226
int mul(int a, int b) {
// Call current values a = a0, b = b0
int p = a & -(b & 1);
a = ((a << 1) ^ (poly & -(a >> 3))) & 15;
b >>= 1;
// Now p = a0 * (b0 mod x); a = a0 x; b = b0 div x
p ^= a & -(b & 1);
a = ((a << 1) ^ (poly & -(a >> 3))) & 15;
b >>= 1;
// Now p = a0 * (b0 mod x^2); a = a0 x^2; b = b0 div x^2
p ^= a & -(b & 1);
a = ((a << 1) ^ (poly & -(a >> 3))) & 15;
b >>= 1;
// Now p = a0 * (b0 mod x^3); a = a0 x^3; b = b0 div x^3
p ^= a & -(b & 1);
// p = a0 * b0
return p;
}
```
However, if we choose `poly = 3` we can handle the overflow much more efficiently because it has a nice structure: there's no double-overflow, because the two inputs are both cubics and `x^6 = x^2 (x + 1)` is also cubic. In addition we can save the shifts of `b`: since we're leaving the overflow to last, `a0 x^2` doesn't have any set bits corresponding to `x` or 1 and so we can mask it with -4 instead of -1. The result is
```
// 10x &, 4x unary -, 3x <<1, 1x >>1, 1x >>3, 5x ^ gives score 152
int mul(int a, int b) {
int p;
p = a & -(b & 1); a <<= 1;
p ^= a & -(b & 2); a <<= 1;
p ^= a & -(b & 4); a <<= 1;
p ^= a & -(b & 8);
// Here p = a0 * b0 but with overflow, which we need to bring back down.
int t = p >> 3;
p ^= (t >> 1) ^ (t & 0xe);
return p & 15;
}
```
We still need to choose the values of `p` and `q` for the representation of GF(2^8) over GF(2^4), but we don't have many constraints on them. The one thing that matters is that we can get a linear function from the bits of our original representation to the bits of the working representation. This matters for two reasons: firstly, it's easy to do linear transformations, whereas a non-linear transformation would require optimisation equivalent in difficulty to just optimising the entire S-box; secondly, because we can get some side benefits. To recap the structure:
```
GF256 SubBytes(GF256 x) {
GF16 a, b, t, D, Dinv, c, d;
(a, b) = f(x); // f is linear
t = b + a * p;
D = b * t + a * a * q;
Dinv = inverse_GF16(D);
c = a * Dinv;
d = t * Dinv;
return finv(c, d); // finv is also linear
}
```
If the bits of `x` are `x7 x6 ... x0` then since the transform is linear we get `a = f({x7}0000000 + 0{x6}000000 + ... + 0000000{x0}) = f({x7}0000000) + f(0{x6}000000) + ... + f(0000000{x0})`. Square it and we get `a^2 = f({x7}0000000)^2 + f(0{x6}000000)^2 + ... + f(0000000{x0})^2` where the cross-terms cancel (because in GF(2), `1 + 1 = 0`). So `a^2` can also be computed as a linear function of `x`. We can augment the forward linear transform to get:
```
GF256 SubBytes(GF256 x) {
GF16 a, b, t, a2q, D, Dinv, c, d;
(a, b, t, a2q) = faug(x);
D = b * t + a2q;
Dinv = inverse_GF16(D);
c = a * Dinv;
d = t * Dinv;
return finv(c, d);
}
```
and we're down to three multiplications and one addition. We can also extend the multiplication code to do the two multiplications by `Dinv` in parallel. So our total cost is a forward linear transformation, an addition, two multiplications, an inverse in GF(2^4), and a back linear transformation. We can roll in the post-inverse linear transformation of the S-box and get that essentially for free.
The computation of the coefficients for the linear transformations isn't very interesting, and nor is the micro-optimisation to save a mask here and a shift there. The remaining interesting part is the optimisation of `inverse_GF16`. There are 2^64 different functions from 4 bits to 4 bits, so a direct optimisation requires lots of memory and time. What I've done is to consider 4 functions from 4 bits to 1 bit, place a cap on the total cost permitted for any one function (with a maximum cost of 63 per function I can enumerate all suitable expressions in under a minute), and for each tuple of functions do common subexpression elimination. After 25 minutes of crunching, I find that the best inverse possible with that cap has a total cost of 133 (an average of 33.25 per bit of the output, which isn't bad considering that the cheapest expression for any individual bit is 35).
I'm still experimenting with other approaches to minimise the inversion in GF(2^4), and an approach which builds bottom-up rather than top-down has yielded an improvement from 133 to 126.
[Answer]
## **Score: 980=7\*5+115\*7+7\*5+15\*7, Boyar and Peralta's minimization**
I found [*A new combinational logic minimization technique with applications to cryptology*](http://eprint.iacr.org/2011/332) by Joan Boyar and René Peralta, which (save for the C formalism) does what's required. The technique used to derive their equations is [patented](http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/8316338) by no less than the USA. I just did a straight C translation of [their equations](http://cs-www.cs.yale.edu/homes/peralta/CircuitStuff/AES_SBox.txt), kindly linked [here](http://cs-www.cs.yale.edu/homes/peralta/CircuitStuff/CMT.html).
```
unsigned char SubBytes_Boyar_Peralta(unsigned char x7){
unsigned char
x6=x7>>1,x5=x6>>1,x4=x5>>1,x3=x4>>1,x2=x3>>1,x1=x2>>1,x0=x1>>1,
y14=x3^x5,y13=x0^x6,y9=x0^x3,y8=x0^x5,t0=x1^x2,y1=t0^x7,y4=y1^x3,y12=y13^y14,y2=y1^x0,
y5=y1^x6,y3=y5^y8,t1=x4^y12,y15=t1^x5,y20=t1^x1,y6=y15^x7,y10=y15^t0,y11=y20^y9,y7=x7^y11,
y17=y10^y11,y19=y10^y8,y16=t0^y11,y21=y13^y16,y18=x0^y16,t2=y12&y15,t3=y3&y6,t4=t3^t2,
t5=y4&x7,t6=t5^t2,t7=y13&y16,t8=y5&y1,t9=t8^t7,t10=y2&y7,t11=t10^t7,t12=y9&y11,
t13=y14&y17,t14=t13^t12,t15=y8&y10,t16=t15^t12,t17=t4^t14,t18=t6^t16,t19=t9^t14,
t20=t11^t16,t21=t17^y20,t22=t18^y19,t23=t19^y21,t24=t20^y18,t25=t21^t22,t26=t21&t23,
t27=t24^t26,t28=t25&t27,t29=t28^t22,t30=t23^t24,t31=t22^t26,t32=t31&t30,t33=t32^t24,
t34=t23^t33,t35=t27^t33,t36=t24&t35,t37=t36^t34,t38=t27^t36,t39=t29&t38,t40=t25^t39,
t41=t40^t37,t42=t29^t33,t43=t29^t40,t44=t33^t37,t45=t42^t41,z0=t44&y15,z1=t37&y6,
z2=t33&x7,z3=t43&y16,z4=t40&y1,z5=t29&y7,z6=t42&y11,z7=t45&y17,z8=t41&y10,z9=t44&y12,
z10=t37&y3,z11=t33&y4,z12=t43&y13,z13=t40&y5,z14=t29&y2,z15=t42&y9,z16=t45&y14,z17=t41&y8,
t46=z15^z16,t47=z10^z11,t48=z5^z13,t49=z9^z10,t50=z2^z12,t51=z2^z5,t52=z7^z8,t53=z0^z3,
t54=z6^z7,t55=z16^z17,t56=z12^t48,t57=t50^t53,t58=z4^t46,t59=z3^t54,t60=t46^t57,
t61=z14^t57,t62=t52^t58,t63=t49^t58,t64=z4^t59,t65=t61^t62,t66=z1^t63,s0=t59^t63,
s6=t56^t62,s7=t48^t60,t67=t64^t65,s3=t53^t66,s4=t51^t66,s5=t47^t65,s1=t64^s3,s2=t55^t67;
return (((((((s0<<1|s1&1)<<1|s2&1)<<1|s3&1)<<1|s4&1)<<1|s5&1)<<1|s6&1)<<1|s7&1)^0x63;}
```
[Answer]
## Score: 10965
This uses the same principle of unrolling the array lookup. May require extra casts.
Thanks to ugoren for pointing out how to improve `is_zero`.
```
// Cost: 255 * (5+7+24+7) = 10965
unsigned char SubBytes(unsigned char x) {
unsigned char r = 0x63;
char c = (char)x;
c--; r ^= is_zero(c) & (0x63^0x7c); // 5+7+24+7 inlining the final xor
c--; r ^= is_zero(c) & (0x63^0x77); // 5+7+24+7
// ...
c--; r ^= is_zero(c) & (0x63^0x16); // 5+7+24+7
return r;
}
// Cost: 24
// Returns (unsigned char)-1 when input is 0 and 0 otherwise
unsigned char is_zero(char c) {
// Shifting a signed number right is unspecified, so use unsigned
unsigned char u;
c |= -c; // 7+5+
u = (unsigned char)c;
u >>= (CHAR_BITS - 1); // 7+
c = (char)u;
// c is 0 if we want -1 and 1 otherwise.
c--; // 5
return (unsigned char)c;
}
```
[Answer]
## Score: 9109, algebraic approach
I'll leave the lookup approach in case anyone can improve it drastically, but it turns out that a good algebraic approach is possible. This implementation finds the multiplicative inverse [using Euclid's algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Computing_a_multiplicative_inverse_in_a_finite_field). I've written it in Java but in principle it can be ported to C - I've commented the parts which would change if you want to rework it using only 8-bit types.
Thanks to ugoren for pointing out how to shorten the `is_nonzero` check in a comment on my other answer.
```
public class SBox
{
public static void main(String[] args)
{
for (int i = 0; i < 256; i++) {
int s = SubBytes(i);
System.out.format("%02x ", s);
if (i % 16 == 15) System.out.println();
}
}
// Total cost: 9109
public static int SubBytes(int x)
{
x = inv_euclid(x); // 9041
x = affine(x); // 68
return x;
}
// Total cost: 68
private static int affine(int s0) {
int s = s0;
s ^= (s0 << 1) ^ (s0 >> 7); // 5 + 7
s ^= (s0 << 2) ^ (s0 >> 6); // 7 + 7
s ^= (s0 << 3) ^ (s0 >> 5); // 7 + 7
s ^= (s0 << 4) ^ (s0 >> 4); // 7 + 7
return (s ^ 0x63) & 0xff; // 7 + 7
}
// Does the inverse in the Galois field for a total cost of 24 + 9010 + 7 = 9041
private static int inv_euclid(int s) {
// The first part of handling the special case: cost of 24
int zeromask = is_nonzero(s);
// NB the special value of r would complicate the unrolling slightly with unsigned bytes
int r = 0x11b, a = 0, b = 1;
// Total cost of loop: 7*(29+233+566+503+28) - 503 = 9010
for (int depth = 0; depth < 7; depth++) { // 7*(
// Calculate mask to fake out when we're looping further than necessary: cost 29
int mask = is_nonzero(s >> 1);
// Cost: 233
int ord = polynomial_order(s);
// This next block does div/rem at a total cost of 6*(24+49) + 69 + 59 = 566
int quot = 0, rem = r;
for (int i = 7; i > 1; i--) { // 6*(
int divmask = is_nonzero(ord & (rem >> i)); // 24+7+7
quot ^= (1 << i) & divmask; // 7+0+7+ since 1<<i is inlined on unrolling
rem ^= (s << i) & divmask; // 7+7+7) +
}
int divmask1 = is_nonzero(ord & (rem >> 1)); // 24+7+5
quot ^= 2 & divmask1; // 7+7+
rem ^= (s << 1) & divmask1; // 7+5+7+
int divmask0 = is_nonzero(ord & rem); // 24+7
quot ^= 1 & divmask0; // 7+7+
rem ^= s & divmask0; // 7+7
// This next block does the rest for the cost of a mul (503) plus 28
// When depth = 0, b = 1 so we can skip the mul on unrolling
r = s;
s = rem;
quot = mul(quot, b) ^ a;
a = b;
b ^= (quot ^ b) & mask;
}
// The rest of handling the special case: cost 7
return b & zeromask;
}
// Gets the highest set bit in the input. Assumes that it's always at least 1<<1
// Cost: 233
private static int polynomial_order(int s) {
int ord = 2;
ord ^= 6 & -((s >> 2) & 1); // 7+7+5+7+7 = 33 +
ord ^= (ord ^ 8) & -((s >> 3) & 1); // 7+7+7+5+7+7 = 40 +
ord ^= (ord ^ 16) & -((s >> 4) & 1); // 40 +
ord ^= (ord ^ 32) & -((s >> 5) & 1); // 40 +
ord ^= (ord ^ 64) & -((s >> 6) & 1); // 40 +
ord ^= (ord ^ 128) & -((s >> 7) & 1); // 40
return ord;
}
// Returns 0 if c is 0 and -1 otherwise
// Cost: 24
private static int is_nonzero(int c) {
c |= -c; // 7+5+
c >>>= 31; // 7+ (simulating a cast to unsigned and right shift by CHAR_BIT)
c = -c; // 5+ (could be saved assuming a particular implementation of signed right shift)
return c;
}
// Performs a multiplication in the Rijndael finite field
// Cost: 503 (496 if working with unsigned bytes)
private static int mul(int a, int b) {
int p = 0;
for (int counter = 0; counter < 8; counter++) { // 8*(_+_
p ^= a & -(b & 1); // +7+7+5+7
a = (a << 1) ^ (0x1b & -(a >> 7)); // +5+7+7+5+7
b >>= 1; // +5)
}
p &= 0xff; // +7 avoidable with unsigned bytes
return p;
}
}
```
[Answer]
## **Score: 256\*(7+(8\*(7+7+7)-(2+2))+5+7+7)=48640 (assuming loops unrolled)**
```
unsigned char SubBytes(unsigned char x) {
static const unsigned char t[256] = {
0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16};
unsigned char ret_val = 0;
int i,j;
for(i=0;i<256;i++) {
unsigned char is_index = (x ^ ((unsigned char) i));
for(j=0;j<8;j++) {
is_index |= (is_index << (1 << j)) | (is_index >> (1 << j));
}
is_index = ~is_index;
ret_val |= is_index & t[i];
}
return ret_val;}
```
Explanation:
Essentially an array lookup reimplemented using bitwise operators and always processing the entire array. We loop through the array, and xor `x` with each index, then use bitwise operators to logically negate the result, so we get 255 when `x=i` and 0 otherwise. We bitwise-and this with the array-value, so that the chosen value is unchanged and the others become 0. Then we take the bitwise-or of this array, thereby pulling out only the chosen value.
The two `1 << j` operations would go away as part of unrolling the loop, replacing them with the powers of 2 from 1 through 128.
[Answer]
## Score 1968 1692, using the lookup table
**Note: This solution doesn't pass the criteria, because of `w >> b`.**
Using the lookup table, but reading 8 bytes at a time.
3\*7 + 32 \* (6\*7 + 2\*5) + 7 = 692
```
unsigned char SubBytes(unsigned char x){
static const unsigned char t[256] = {
0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16};
unsigned long long *t2 = (unsigned long long *)t;
int a = x>>3, b=(x&7)<<3; // 7+7+7
int i;
int ret = 0;
for (i=0;i<256/8;i++) { // 32 *
unsigned long long w = t2[i];
int badi = ((unsigned int)(a|-a))>>31; // 7+7+5
w &= (badi-1); // +7+7
a--; // +5
ret |= w >> b; // +7+7
}
return ret & 0xff; // +7
}
```
[Answer]
## Table lookup and mask, score = 256 \* (5\*7+1\*5) = 10240
Uses table lookup with a mask to pick out only the result we want. Uses the fact that `j|-j` is either negative (when i!=x) or zero (when i==x). Shifting makes an all-one or all-zero mask which is used to select out only the entry we want.
```
static const unsigned char t[256] = {
0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16};
unsigned char SubBytes(unsigned char x) {
unsigned char r = 255;
for (int i = 0; i < 256; i++) {
int j = i - x;
r &= t[i] | ((j | -j) >> 31);
}
return r;
}
```
] |
[Question]
[
I've been developing some programs involving me fetching a vector from a url using Alpha-2 country codes (such as `GET /jp.svg` for Japan). Except, oh no! All the country data on my computer uses Alpha-3! That just won't do...
The task is simple: Take an Alpha-3 country code (e.g. `UKR`) and return its Alpha-2 equivalent (e.g. `UA`). And because my hard drive is smaller than the Vatican (and because this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")), the program must be as small as possible.
Codes can be found [here](https://komali.dev/countries/alpha.txt)
and below.
```
[["AFG", "AF"],["ALA", "AX"],["ALB", "AL"],["DZA", "DZ"],["ASM", "AS"],["AND", "AD"],["AGO", "AO"],["AIA", "AI"],["ATA", "AQ"],["ATG", "AG"],["ARG", "AR"],["ARM", "AM"],["ABW", "AW"],["AUS", "AU"],["AUT", "AT"],["AZE", "AZ"],["BHS", "BS"],["BHR", "BH"],["BGD", "BD"],["BRB", "BB"],["BLR", "BY"],["BEL", "BE"],["BLZ", "BZ"],["BEN", "BJ"],["BMU", "BM"],["BTN", "BT"],["BOL", "BO"],["BIH", "BA"],["BWA", "BW"],["BVT", "BV"],["BRA", "BR"],["VGB", "VG"],["IOT", "IO"],["BRN", "BN"],["BGR", "BG"],["BFA", "BF"],["BDI", "BI"],["KHM", "KH"],["CMR", "CM"],["CAN", "CA"],["CPV", "CV"],["CYM", "KY"],["CAF", "CF"],["TCD", "TD"],["CHL", "CL"],["CHN", "CN"],["HKG", "HK"],["MAC", "MO"],["CXR", "CX"],["CCK", "CC"],["COL", "CO"],["COM", "KM"],["COG", "CG"],["COD", "CD"],["COK", "CK"],["CRI", "CR"],["CIV", "CI"],["HRV", "HR"],["CUB", "CU"],["CYP", "CY"],["CZE", "CZ"],["DNK", "DK"],["DJI", "DJ"],["DMA", "DM"],["DOM", "DO"],["ECU", "EC"],["EGY", "EG"],["SLV", "SV"],["GNQ", "GQ"],["ERI", "ER"],["EST", "EE"],["ETH", "ET"],["FLK", "FK"],["FRO", "FO"],["FJI", "FJ"],["FIN", "FI"],["FRA", "FR"],["GUF", "GF"],["PYF", "PF"],["ATF", "TF"],["GAB", "GA"],["GMB", "GM"],["GEO", "GE"],["DEU", "DE"],["GHA", "GH"],["GIB", "GI"],["GRC", "GR"],["GRL", "GL"],["GRD", "GD"],["GLP", "GP"],["GUM", "GU"],["GTM", "GT"],["GGY", "GG"],["GIN", "GN"],["GNB", "GW"],["GUY", "GY"],["HTI", "HT"],["HMD", "HM"],["VAT", "VA"],["HND", "HN"],["HUN", "HU"],["ISL", "IS"],["IND", "IN"],["IDN", "ID"],["IRN", "IR"],["IRQ", "IQ"],["IRL", "IE"],["IMN", "IM"],["ISR", "IL"],["ITA", "IT"],["JAM", "JM"],["JPN", "JP"],["JEY", "JE"],["JOR", "JO"],["KAZ", "KZ"],["KEN", "KE"],["KIR", "KI"],["PRK", "KP"],["KOR", "KR"],["KWT", "KW"],["KGZ", "KG"],["LAO", "LA"],["LVA", "LV"],["LBN", "LB"],["LSO", "LS"],["LBR", "LR"],["LBY", "LY"],["LIE", "LI"],["LTU", "LT"],["LUX", "LU"],["MKD", "MK"],["MDG", "MG"],["MWI", "MW"],["MYS", "MY"],["MDV", "MV"],["MLI", "ML"],["MLT", "MT"],["MHL", "MH"],["MTQ", "MQ"],["MRT", "MR"],["MUS", "MU"],["MYT", "YT"],["MEX", "MX"],["FSM", "FM"],["MDA", "MD"],["MCO", "MC"],["MNG", "MN"],["MNE", "ME"],["MSR", "MS"],["MAR", "MA"],["MOZ", "MZ"],["MMR", "MM"],["NAM", "NA"],["NRU", "NR"],["NPL", "NP"],["NLD", "NL"],["ANT", "AN"],["NCL", "NC"],["NZL", "NZ"],["NIC", "NI"],["NER", "NE"],["NGA", "NG"],["NIU", "NU"],["NFK", "NF"],["MNP", "MP"],["NOR", "NO"],["OMN", "OM"],["PAK", "PK"],["PLW", "PW"],["PSE", "PS"],["PAN", "PA"],["PNG", "PG"],["PRY", "PY"],["PER", "PE"],["PHL", "PH"],["PCN", "PN"],["POL", "PL"],["PRT", "PT"],["PRI", "PR"],["QAT", "QA"],["REU", "RE"],["ROU", "RO"],["RUS", "RU"],["RWA", "RW"],["BLM", "BL"],["SHN", "SH"],["KNA", "KN"],["LCA", "LC"],["MAF", "MF"],["SPM", "PM"],["VCT", "VC"],["WSM", "WS"],["SMR", "SM"],["STP", "ST"],["SAU", "SA"],["SEN", "SN"],["SRB", "RS"],["SYC", "SC"],["SLE", "SL"],["SGP", "SG"],["SVK", "SK"],["SVN", "SI"],["SLB", "SB"],["SOM", "SO"],["ZAF", "ZA"],["SGS", "GS"],["SSD", "SS"],["ESP", "ES"],["LKA", "LK"],["SDN", "SD"],["SUR", "SR"],["SJM", "SJ"],["SWZ", "SZ"],["SWE", "SE"],["CHE", "CH"],["SYR", "SY"],["TWN", "TW"],["TJK", "TJ"],["TZA", "TZ"],["THA", "TH"],["TLS", "TL"],["TGO", "TG"],["TKL", "TK"],["TON", "TO"],["TTO", "TT"],["TUN", "TN"],["TUR", "TR"],["TKM", "TM"],["TCA", "TC"],["TUV", "TV"],["UGA", "UG"],["UKR", "UA"],["ARE", "AE"],["GBR", "GB"],["USA", "US"],["UMI", "UM"],["URY", "UY"],["UZB", "UZ"],["VUT", "VU"],["VEN", "VE"],["VNM", "VN"],["VIR", "VI"],["WLF", "WF"],["ESH", "EH"],["YEM", "YE"],["ZMB", "ZM"],["ZWE", "ZW"]]
```
## Rules
* Your answer must work with all countries and territories
* You may not fetch any data from the internet.
* Standard loopholes apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins.
Input/Output may be a string, list of characters, or list of character codes. Text case does not matter
## Test Cases
### Countries
```
USA -> US # United States
AUS -> AU # Australia
BIH -> BA # Bosnia and Herzegovina
ISL -> IS # Iceland
FSM -> FM # Micronesia
SYC -> SC # Seychelles
```
### Territories
```
UMI -> UM # US Minor Outlying Islands
SPM -> PM # Saint Pierre and Miquelon
GUF -> GF # French Guiana
ATF -> TF # French Southern Territories
HKG -> HK # Hong Kong
IOT -> IO # British Indian Ocean Territory
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 253 bytes
*Saved 1 byte thanks to @MatthewJensen*
Expects a string in upper case. Returns an array of 2 characters.
```
s=>["TKKYKGPR"[i="ATFCOMCYMMYTPRKSGSSPMSRBALAATABLRBENBIHMACESTGNBIRLISRSVNUKR".search(s)/3]||s[0],"FMYTPSMSXQYJAOEWELIA"[i]||s[2-Buffer(`Z&:^*Wf&*/1*EKe'(1#/.534aq>HI*"#0551(C=J@75%,.I>"!G0"2#1)%)(2p#/4@!&<`).every(n=>q-=n-32,q=parseInt(s,36)*5%1601)]]
```
[Try it online!](https://tio.run/##NVfRTtxWEH3nKzaLEnYRkAAhlZIure21r72@12t8r73sIqqgdGkSRUDYNFLV9A8q9aWP7X/0e/ID/QTqM2f6Ahx5fObMmblzzfurz1ebN/fv7j7t39z@uH64njxsJqcXw1CWy9LUzfDi3WQYhSyZu2Tp3DLUTemN97XzTRzZKApRbJs4reIid1GS@mD6Pxtb@MZ3VVs2w4PN@ur@zdvRZvz0@PLLl83Fs8u9YQYm7/z52XIWzdNFaouoTyXPj/bjn6@v1/ej16snL3/YXVw/2X16uJuW653R4fbTg5Pj51cfT/Nid7j97OTkcJRMZt9/c/J476A4HT4yz4ZH24fjx@PR0d320@ffP3ry7evxwfrz@v6X0c3k9OP@5Gb/@Gjv4@Tu6n6zLm4@jTZ7xy/GuyePD188OxxfXj68uti6GEaZGe71P4eXez2wEcC5ghjACpiu8GS64hPv8MQTVFOAKYGZA8wJCmErCIKAMwWS1BA0AhoFQu0I4gXAgqD1AK2CABAIVikAtcU5wmKvoAHICQyExhQaNygujgmshC0JUguQ6pMVgFKnFcCMwLUAFBoHeUI58VwI6EE/KwARwQIexKwn7lBC3KkceUIPOgNtHd0p5ggrlK2RPJXWI6oZFmdCwDbG0wKAxpc5HC3pQeLwTkLVSQS2hNqSugOgnH7@8c5SwzI8IXVIYGKgiUmOShOrQNioLS/R07wU0B@WHjiWkJyLAo5YkpQACYH4lmjYXBSo0DnYEqMAChJVMBcC5kkalJ3QxKSQeuhB3gDk@qSFvUmrldYAWqkMUsJuTytQT0k9nYF6ytZPnZwFapuK0ClVpwmGImU9qVkCULW3UOBpr6nOemB4FlJRnVJbv1QAOHxpwOyknKrMQk5GOVmDY5YxaSbaMmrLCnQhKzQMQjNSmxZtNGxjvQSo9dQHgEBgIrhjOBTGCWClJkVSQ23TFJVOCUyOPIYjZgp5hwpMg9YbVdCgwcYqQBsN22gsumBqFQpHDftjggB6YMRRYzQPKjWVOipJF0ogYexpHuBOToLcIWnOeroIXnesNJctluv0tqDOqaDwUF1woRQSVjCsmCKsYAmFHM2iUYAGF2cKhIBWFU7CnFLjLBQ0pJAFWVDoLELZM4bNarwzozuzFMXNyDabg2DGOSgj7KqS01vKrioZVhYIK9mS/lYDIFspBCVVlwsYUtLE0ggbvbYRWm9ple0g1HKUbYw8lnvUegnz@gTUtlEA1ZYtsQWOmaUcGzBIlmXb9hyAxrsSXjvdIVOsAEc5boGeOgp1Syx8t9QwHDNHbc5KmFWA4hzzOFlcjgPrAprl2CzXSBhVO7lynMpZ4slSCVIIddximVyHmVMFcMdxKFwCQxz3gaukhEoBPHDsj5M5cF63pQB67ebogmNPnSxvxzyVTEjFsKqBiRVVVzWKq9jgysLEyupVLbcmFVSJhFFbtRLAPFWBQ1uxP1WKpBWFVgbFVUbDJCndqTJMVZVpcTjOThXIiFWc0bmM/5wl1BHeqdng2uKur9nT2sOd2msY3qlZaS0m1kZHGVNVs/W1CK0ptJYG12xwnQgBy67llqmtEsCQOijAuNQ08UyWwxmTNrLsGlI3cwGsp5EJaehBI9d7o9e7RX9i5vFyN3rKKSuElZRjEzlMOiFy0zqa2H93Qo7uqkR2FcMWMm8LuuNlKDzDfIDxnvX4CEI9S/CyDzyTevn4aZRgiW77RK8pGO9VtRE2vcA6NMuXCoSt0HfA5rkCvFyHnu6spJ6VKjCwymhSj7H0Xi895El1bZRiiOaRDet5mHwrlbI/fiZ5eOn5BU6JXymQElL9KJEbPddKhYDjEhagDmxWmKG4QLYgn7qBbEGutkCCYFFCoDtBPnUD3QklpipQdZgLNT0IQcLYkiAXS6gUQE5olAD1BKcfWZI00TCstMCV1soBbJkU/3L0INIPZ/kI1gtZdq9hS1ov79De1mHIW@Zp5fy0NKRdoY0ty@7k@7rjXHcyOx2puwpCO5bQycXScQ4WFt1eZNpT@Xahb8sU7yxJsJJvihUVrKRZq74LW5dbB9e39@lV///T6OLqw93bq@O9gfw@uhwPJqeDX7cGgw/rT4P79WYwGVyPGDM@eH/77ma0szN@1T9/c3uzuf2wPvhw@9Pof44@fo8vTZRv8N1g599//vj615/9z53By8HO179/B8Fv44f/AA "JavaScript (Node.js) – Try It Online")
Or **250 bytes** with unprintable characters:
[Try it online!](https://tio.run/##NVftbtRWEBUgKEQVXwVVqlq0SoWyS0PKh0ol0FLZXvva63u9ju@1l90oEhHdFBBKIEuRqtI3qNQ//dm@R5@HF@gjUJ850z9Jjjw@c@bM3LnOy4N3B@tnJy9ev719dPzj6uPh@ON6/HhvM5TlojR1s7n3YrwZhSyZuWTh3CLUTemN97XzTRzZKApRbJs4reIid1GS@mD6Pxtb@MZ3VVs2mzvr1cHJs@fD9ejb@/vv36/37uxvb2Zg8s4/2V1Mo1k6T20R9ank@b3b8c@Hh6uT4dOH5754vPF9dm7j0pWNm9@kn5y/cubSxeufXYt2bwxHG6fPXL5@/cr5r7@6Nfj8@tlPL45unD61dfn01TNXLpy9cP5qfebStcGpc18@He2s3q1OfhkejR@/uT0@2n4zfn1wsl4VR2@H6@37D0a3vrt598Gdu6P9/Y@P9jb2NqPMbG73Pzf3t3tgI4AnCmIAK2CyxJPJkk@8wxNPUE0AJgRmBjAjKIStIAgCdhVIUkPQCGgUCLUjiOcAc4LWA7QKAkAgWKYA1BbnCIu9ggYgJzAQGlNo3KC4OCawErYgSC1Aqk@WAEqdVgBTAtcCUGgc5AnlxDMhoAf9oABEBHN4ELOeuEMJcady5Ak96Ay0dXSnmCGsULZG8lRaj6hmWJwJAdsYTwoAGl/mcLSkB4nDOwlVJxHYEmpL6g6AcvrhxzsLDcvwhNQhgYmBJiY5Kk2sAmGjtrxET/NSQH9SeuBYQvJEFHDEkqQESAjEt0TDZqJAhc7AlhgFUJCogpkQME/SoOyEJiaF1EMP8gYg1yct7E1arbQG0EplkBJ2e1KBekLqyRTUE7Z@4uQsUNtEhE6oOk0wFCnrSc0CgKq9hQJPe0212wPDs5CK6pTa@o0CwOFLA2Yn5VRlFnIyyskaHLOMSTPRllFbVqALWaFhEJqR2rRoo2Eb6wVArac@AAQCE8Edw6EwTgArNSmSGmqbpKh0QmBy5DEcMVPIO1RgGrTeqIIGDTZWAdpo2EZj0QVTq1A4atgfEwTQAyOOGqN5UKmp1FFJOlcCCWNP8wB3chLkDklz1tNF8LpjpblssVyntwV1TgWFh@qCC6WQsIJhxQRhBUso5GgWjQI0uNhVIAS0qnAS5pQaZ6GgIYUsyIJCpxHKnjJsWuOdKd2ZpihuSrbpDARTzkEZYVeVnN5SdlXJsLJAWMmW9FcaANlKISipupzDkJImlkbY6LWN0HpLq2wHoZajbGPksdyj1kuY1yegto0CqLZsiS1wzCzl2IBBsizbtk8AaLwr4bXTHTLBCnCU4@boqaNQt8DCdwsNwzFz1OashFkFKM4xj5PF5TiwLqBZjs1yjYRRtZMrx6mcBZ4slCCFUMctlsl1mDlVAHcch8IlMMRxH7hKSqgUwAPH/jiZA@d1Wwqg126GLjj21MnydsxTyYRUDKsamFhRdVWjuIoNrixMrKxe1XJrUkGVSBi1VUsBzFMVOLQV@1OlSFpRaGVQXGU0TJLSnSrDVFWZFofj7FSBjFjFGZ3J@M9YQh3hnZoNri3u@po9rT3cqb2G4Z2aldZiYm10lDFVNVtfi9CaQmtpcM0G14kQsOxabpnaKgEMqYMCjEtNE3dlOewyaSPLriF1MxPAehqZkIYeNHK9N3q9W/QnZh4vd6OnnLJCWEk5NpHDpBMiN62jif1HJ@TorkpkVzFsLvM2pztehsIzzAcY71mPjyDUswQv@8AzqZePn0YJFui2T/SagvFeVRth0wusQ7N8qUDYCn0HbJ4rwMt16OnOUupZqgIDq4wm9RhL7/XSQ55U10Yphmge2bCeh8m3Uin746eSh5een@OU@KUCKSHVjxK50XOtVAg4LmEO6sBmhSmKC2QL8qkbyBbkagskCBYlBLoT5FM30J1QYqoCVYeZUNODECSMLQlysYRKAeSERglQT3D6kSVJEw3DSgtcaa0cwJZJ8f9GDyL9cJaPYL2QZfcatqT18g7tbR2GvGWeVs5PS0PaJdrYsuxOvq87znUns9ORuqsgtGMJnVwsHedgbtHteaY9lW8X@rZI8c6CBEv5plhSwVKatey7sLG/sXN4fJIe9P88DfcOXr1@fnB/eyC/7@2PBuPHg183BoNXq7eDk9V6MB4cDhkz2nl5/OJouLU1etQ/f3Z8tD5@tdp5dfzT8H@OPn6bL42Vb/DDYOvff/748Nef/c@twcPB1oe/fwfBb6OP/wE "JavaScript (Node.js) – Try It Online")
## How?
### Groups
We categorize the Alpha-2 codes into 4 groups:
1. Codes made of the first two letters of the Alpha-3 code, e.g. `AFG`→`AF` (156 entries).
2. Codes made of the 1st and last letters of the Alpha-3 code, e.g. `ATG`→`AG` (71 entries).
3. Other codes whose 1st letter is the 1st letter of the Alpha-3 code, e.g. `UKR`→`UA` (12 entries).
4. Codes whose 1st letter is not the 1st letter of the Alpha-3 code, e.g. `CYM`→`KY` (8 entries).
### Initial lookup
We first test whether the input belongs to either group 3 or group 4 by looking for its position `i` into the following lookup string (without the spaces), divided by 3:
```
ATF COM CYM MYT PRK SGS SPM SRB ALA ATA BLR BEN BIH MAC EST GNB IRL ISR SVN UKR
\_____________________________/ \_____________________________________________/
group 4 group 3
```
### First letter
For the first letter, we attempt to get:
```
"TKKYKGPR"[i] // lookup string for group 4
```
If this is undefined, we use the first letter of the input.
### Second letter
For the second letter, we attempt to get:
```
"FMYTPSMSXQYJAOEWELIA"[i] // lookup string for groups 4 and 3
```
If this is undefined, we need to figure out whether we should use the 2nd or 3rd letter of the input.
We apply the following hash function to the input string:
```
q = parseInt(s, 36) * 5 % 1601
```
and test whether we can reach exactly \$0\$ by subtracting the ASCII codes minus \$32\$ of the corresponding data string from `q`:
```
`Z&:^*Wf&*/1*EKe'(1#/.534aq>HI*"#0551(C=J@75%,.I>"!G0"2#1)%)(2p#/4@!&<`
```
This is encoding the entries that belong to group 2.
For instance, `parseInt("JAM", 36)` is \$25006\$, which leads to:
$$q=(25006\times 5)\bmod 1601=125030\bmod 1601=152$$
Using the first four characters `Z&:^` of the data string, we find out that this is the sum of:
$$\operatorname{ord}(\text{"Z"})-32+\operatorname{ord}(\text{"&"})-32+\operatorname{ord}(\text{":"})-32+\operatorname{ord}(\text{"^"})-32\\=58+6+26+62$$
which means that `"JAM"` belongs to group 2 and the correct answer is `"JM"`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~238~~ 219 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¨I2ιн.•LS’αPñΔ•.•„Rà´θ≠…āñ©B—‚Ls¿ºÄ¿α>°%»^cýαƒ¸AbŒΓÝ€I†„{rʒKÓÎƶÿ}ιUƶ–ΔΓ5`Δ9Λº½P.÷ü)–\ÎÇÕ¡â"‚0’₁Ýá+_.n¯₅Èg«J¡þ&м£ñ:‡‘÷&´”тε?ʒ^÷δ“ ¥ΔàHÌAiìb0SĀ'WDî>ηOāß7|^î‘€'òê®ćM2¤γù£Œ∞Néä_}àŒ@‹Ó•3ôIlk₄%©èIнì.•TŠ+º°•2ô®èI¦)®•rá÷•₃в‹Oèu
```
[Try it online](https://tio.run/##FVBBS1thEPwrRYgiQpBIKfagTemhsbGRpsWLxDZSiigVlJ5U@PKaooLk8F4KbW3SlxhD0obo09RnrDGwk@TgYUn/wv6RuLnt7Mzu7M7G1rvk6vvBgCqREDf7raCYYjQu5jt7C/A4q3DYEpN/BZcafCUHrphyJwWPqk/FqOBHdIvadI00tdmbobMA/UusoMVez6arcLJrs4OcWLWIGB3Nb2/e2S/gINO7RHuXm296l2IczrLz8C1np/mIrqm1EISPm3EllpDBHr5SAcUR9ZrU08RKIYfCxHLwI52K9QX7H@jPnCpuR/s3dAzvsZiCmG/wR6khJvff4r@zd3YCPiv8@YBOOAv3OQ7Dq6glJ@MdM7b4DPUZ9mP6169HOwnUdVxPHsM5flO9szcfohJfoEnHXVv28y9RRWl5F27XfiKmCUcjmkIjsr4mVjpAVVQi/RZqw@Red90J/ehMyxAaVFeKyuOkBsVNFOAPw7U@9891TQyVT4NBOBq@Bw) or [verify all test cases](https://tio.run/##JVRdaxxVGP4rYaEtpSWUiIheNM7O9845M5M5M7vdVVONiBRFoUUh2MJ0rbSC9GITwa/EJK0l0RC7NTZNbQyck/SiF0P8C/NH4jzP3jzMPOd9n/fjvO/5/MYHC9c@Ov1ycbY1dXOqNbt4qjcXZ6r9k4PputwQqi5/rMapGVfLzS@oulzNzJrerZ7V367V5aOj22ast9p12Rj8JG7oQ/3c3NGH1fiyfnxG/zP/oTmoxi9H@pm1cDyqlsxKPdwO67JxXf3q@qtRZJbM/ZdPzeGtar94@bQul6rlaun196vlN6uf9XN9kE6bPfPifHPwrrlv7prv9brZaDWxLjWp1cPbZsWsX7g6/Zn@sx5@Y@59rP/oNBb/nj15oR@Y8Vt1uV6XP5i9s3q3Llf@G1Z/z74azZu9qvn9ZUr/Vi2btcB8Z10z2wuX1FF5rueYncvVXtLU9esbN@fNTuPepHzOPDG/652ju3JGP6z@Mvv6wfGovrcamy3z8Oots3Y8ersu981S06LXzO7ip5/Uwztn9JbZXDw5MNvoXH68dqGp6HHzOWN29U5zpB@d102Ajetm3eyhucOvT540MonZ/OL04uk7LcvzWxdblrCI7QadAb@VBMYO0E@AIfl8gvTKJkjLdg9YKGIOHLgNtgNFzIA@1NoZorQFGVfwe8DvGCgLYM7vhKdhAOwhbrubUwHfXR86YTJhaO9T06OlEzYYBcjNluBtCzZ22gX2yVteg7mNrOxAEGETRKhLWjaYK/S1IyDzsRP6Jj6RvglPM0S0Q@gHGaMUbcZKgeyGE8PS6cDSkcjToZpro2rX7zeoBHz9eA4MNV2FGt0cffAEFLwMN@JRxwtjMlDzC1SU9j3eEdC3kIMviS68HBex/ID2IfnMJgoiKvJFSjXk5udE5uYzlh/TqwAT5MghkPDqWsgz4MwEBSxDBc2QTOiQySY4R@SpnFiizyGnq2MhYicF33ERpZPgNLIwJxHnJArBpBm6EU1Oe4ge@bARFioVXaiJNuyFItPOiNAUIW5E5OiGKK7gxiPkKR3efg91yb4igxuRgoxAFMlpkTmqkBkZTr7s89uFmscNkg5ykDaiy5jKMeJK1istYoKcJac0Zu1xhqziFFFiwR2MoRzbZAbEELcWu/TyLTL08iJGwQ3G7EzCDqcW@FRgT1PlkiHPrNIMPUmplrK61OYpZz5ljSmncY63nHGKsoTI2rPJhgrkr7hHUcz@2@wAd02lOO3aUOixP4pVqxzZKgtqiver@Eqovs2NQLbKp003ItKG75XiBg0m@j4yUcrh1sBeRIiuOHuqYKwO4/YGRJdbT/0@TvMeLPMOouR8CXNuSi6gnPMlzCP0JE9omZPhtOfUzyPJV4VeBSan4O0UUcbXErF8zmGhyEt0tWD/iwEq6vL97LIP3Zgd47T3hMe68A70XVbNvR40Vbz3Pw).
**Explanation:**
There are five possible groups:
1. Those for which the first character is removed
2. Those for which the middle character is removed
3. Those for which the last character is removed
4. Those for which the last two characters are replaced with a different character, but the first character remains unchanged
5. Those for which all three characters are replaced with two different characters
My program does three steps:
1. Generate the five possible results above (in the order 1,2,4,5,3), and put them in a list:
```
¨ # (1) Remove the last character from the (implicit) input-string
I # (2) Push the input-string again
2ι # Uninterleave it into two parts: "abc" → ["ac","b"]
н # Only leave the first part
.•LS’αPñΔ• # (4) Push compressed string "aaeeijloqwxy"
... # See step 2 below
è # Modular 0-based index the result of step 2 into this string
Iн # Push the first character of the input-string
ì # Prepend it in front of the indexed character
.•TŠ+º°• # (5) Push compressed string "kykmkprs"
2ô # Split it into parts of size 2: ["ky","km","kp","rs"]
® # Push the index of step 2 again
è # Modular 0-based index it into this list
I # (3) Push the input-string again
¦ # Remove its first character
) # Wrap all five results on the stack into a list
```
[Try just step 1 online.](https://tio.run/##FVBLS0JhFPwrEZREIGJE1KIyWmTZgx60CS0jIoqCWlbwdSkqCBf3GvTSrj1ES6xbplmZcEZdtDjYXzh/xL52Z87McObMxtZCeGWp0aCU38vFeskt6iYwJeqcnQk4HNXwfyUqPgmbcvwux7aoZGUPDqUHRGnBRWCLyvSBfSqz00vPLfQZXESJnZpJ775w1WQLMTEyflHaGt/e/DFHYCFSy6O8y8WZWl6UxVG2Ouc52s2X9EGlCTcK@GrTxBwiOMQpJXDTrG95dDQx9hBDoj3kXqcnMQ5wtEyPw1rx3Vr/ols4PaISos5QaKWcqNivwW99P2YQBdbwqonuOQp7CCe@FWTCnqmKcs0OItvLhXH913XXThBZbdeRXXjBA2Urh6NeuuNXFOm2aspRfAxp3IV2YVfNflFFWLqiDuT8a6ti7LdQGil/vYTMf3PTVbtdf/SsRy9ylNUUJdsaDV/A9wc)
2. Check in which group the input belongs:
```
.•„Rà´θ≠…āñ©B—‚Ls¿ºÄ¿α>°%»^cýαƒ¸AbŒΓÝ€I†„{rʒKÓÎƶÿ}ιUƶ–ΔΓ5`Δ9Λº½P.÷ü)–\ÎÇÕ¡â"‚0’₁Ýá+_.n¯₅Èg«J¡þ&м£ñ:‡‘÷&´”тε?ʒ^÷δ“ ¥ΔàHÌAiìb0SĀ'WDî>ηOāß7|^î‘€'òê®ćM2¤γù£Œ∞Néä_}àŒ@‹Ó•
"# Push compressed string "atfmytspmsgscymcomprksrbatagnbalablrbihukrestirlsvnbenisrmacabwagoandarearmatgautbdibgdbhsblzbrbbrncafchlchncodcogcokcpvdnkeshflkfrofsmginglpgnqgrdgrlgufguyirqjamkazkorlbrlbymafmdgmdvmexmltmnemnpmozmtqniupakpcnplwpngpolprtprypyfsenslbslvsursvksweswzsyctcdtkmtunturtuvurywlf"
3ô # Split it into parts of size 3: ["atf","myt",...,"wlf","esh"]
I # Push the input-string
l # Convert it to lowercase
k # Get its index in this list (or -1 if not found)
₄% # Modulo-1000 to convert the -1 to 999
© # Store it in variable `®` (without popping)
```
[Try just step 2 online.](https://tio.run/##DVBLS0JRGPwrEahEIFJE1MIyWmTZgyLahJYRIUVBLks4XgwNwsW9N@il@SqwxLLMV5rwjbpwcai/8P0RO8thZpjHSXDXH9gfDOwsMiyS60hRWdb4MsXiuRNGifJzLEwWd54gtamBCLVlyUnvFvr27qElSz2dai5/V5cGEqwV3CyUNXl22teXYCDeq6AdkvXNXoWFIU1pTOxIc0reU4Naa3ZU0RxRxDbiiOKa0sgMqywHi1vWwkggPeqzH9MbaxeIHdDrolL8WH@blEVpmkWaxQ2qViqzSPxp8mumr3tRlQo@DNGTNJFawJUrgILfsdERtq15FJ2yuqp2PU6ee1FUdlXZhg@8ULETXR6jnPxEnbJdnWPJFeSR84WQ6uqzLOow1EXjKLuPDlmLWCg/GLg8rn8)
3. Use that to index into the quintuplet of possible results:
```
® # Push the index of step 2 again
•rá÷• # Push compressed integer 3503691
₃в # Convert it to base-95 as list: [4,8,20,91]
‹ # Check for each if its larger than the index
O # Sum to get the amount of truthy values
è # Use that to index into the result-quintuplet of step 1
u # Uppercase it for the potential lowercase characters
# (after which the result is output implicitly)
```
[Try just (the first portion of) step 3 online.](https://tio.run/##FZDNSkJRFIVfJQKTCCSKiBpYRoMsyyiiSWgZEVIU6LCE483QIBzca9Cf5l@BFZZm3SxN2EsdODjYK@wXsdNws9e39l7rMLjl8@/0bCyyLFIrSFNFfvJZmsVDM4wSFWZYJFhcu4LUoC9EqCFLdnq10LdnG3VZauv06fC1dGkgydqzk4VCU0eBjr4AA/H2BxohWV1rf7AwZEIaY5syMSFv6IvqyzaYqA2qxQbiiOKCMsj2q1vDLK5YCyOJzJDXdkAvrJ0itktP80rxM9CtUQ6lSRYZFpcwB6jCIvmryfepju6BKdV420f3MoH0HM4dfjz7hlebwro@i6Jdmm6V62782IOiwtXLVpTxSMVmdHGE8vINVcq1dI6lllBA3htCuqVPs6jCUBWNouLc32MtYqFCj5RBNoAMzP/ytJNuWcncvZ7D5fgD)
---
[See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•LS’αPñΔ•` is `"aaeeijloqwxy"`; `.•TŠ+º°•` is `"kykmkprs"`; `.•„Rà´θ≠…āñ©B—‚Ls¿ºÄ¿α>°%»^cýαƒ¸AbŒΓÝ€I†„{rʒKÓÎƶÿ}ιUƶ–ΔΓ5`Δ9Λº½P.÷ü)–\ÎÇÕ¡â"‚0’₁Ýá+_.n¯₅Èg«J¡þ&м£ñ:‡‘÷&´”тε?ʒ^÷δ“ ¥ΔàHÌAiìb0SĀ'WDî>ηOāß7|^î‘€'òê®ćM2¤γù£Œ∞Néä_}àŒ@‹Ó•` is `"atfmytspmsgscymcomprksrbatagnbalablrbihukrestirlsvnbenisrmacabwagoandarearmatgautbdibgdbhsblzbrbbrncafchlchncodcogcokcpvdnkeshflkfrofsmginglpgnqgrdgrlgufguyirqjamkazkorlbrlbymafmdgmdvmexmltmnemnpmozmtqniupakpcnplwpngpolprtprypyfsenslbslvsursvksweswzsyctcdtkmtunturtuvurywlf"`; `•rá÷•` is `3503691`; and `•rá÷•₃в` is `[4,8,20,91]`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 115 bytes (uses builtin libraries)
Turns out there's a builtin for everything! There was a restriction against using internet connectivity, so I'm not sure if the builtin data is allowed, but if so, it's the shortest.
```
If[#=="HMD"||#=="ANT"||#=="PSE",#~StringTake~2&,Association[#@"UNCode"->#@"CountryCode"&/@EntityList@"Country"]]@#&
```
This code doesn't work right on TIO due to using Mathematica's libraries. Also takes quite a while to run, but it does work for every test case, although I did have to hardcode in the three cases seen in the If statement.
[(Don't) try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zMtWtnWVsnD10WppgbEcvQLgbICgl2VdJTrgkuKMvPSQxKzU@uM1HQci4vzkzOB2vPzopUdlEL9nPNTUpV07YBs5/zSvJKiSrCAmr6Da15JZkmlT2ZxCVxKKTbWQVntfwDQwJLoNH2HarBtOkqOPo5AMjQYRHr6hyjVxv4HAA "Wolfram Language (Mathematica) – Try It Online")
Here's a cloud notebook with the code: <https://www.wolframcloud.com/obj/romanp/Published/CountryCodeConvert>
It should eventually return the correct values, but if it doesn't, you can copy the code and test it either in the cloud on a smaller test case or in a personal installation.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 241 bytes
```
≔⌕⪪”$⌊σ⎚✂↔¿^T”³θη¿⊕η§⪪KYKMKPRS²η«¿№⪪”$⌊´u⪫∕γ+T”³θΦθκ«§θ⁰≔⌕⪪”$‽∧⌕¤MÀ;S¦O⪫;¦⁻\I-→mxτ9”³θη¿⊕η§XQYJAOEWELIAη§θ⊕№⪪”$⌈“MONZ⦃§r\`>7∨M¹↘№κ➙@◨33✳¦z≕ςie�+ψΦ|J1ιν‴№²⌈o≧h⟦UE∧№›.G›dWS&σ∨⟧Jm∧‴>¦¦◧D@QJ∧#e↨⁷*+U‴∕b✂�\6j4)τ″?⎚9∧§6ρ⮌ζσ↗.B↨$]h↓¹NφX¡¹~⮌S₂7�Fm;”³θ
```
[Try it online!](https://tio.run/##hZFPj9MwEMXP6aeIekqkIiE4cho7tpP1347tZNPbqg00ImTZNiAktJ89ZKstsICE5JEszbzfm2fvj3en/f3dMM9wPvcfxoz34yHzn4d@yta01dRqh9IjWW/St/kmfVjqmL9b9e/TrBr3p@5TN07dITvmeepO/ThlMFXjoft2ZchWaunQL/o3z9puOHfp91XyxKD3XxbN8ywErtvgnfbC//S7cnk/TN0pe9ikH/MFklwpyUvbpf/60k/@EQgUQACikDBDqlIDZT6I5Yqq8uhrEyX@ETRJ/h91fbttb8CyhqkK1k@6i/Cy4V/b/Y56md4UICwEAaiBNBADKT0RBUFC1I6gIUVFXU2BB1rQUtHSUCuoLaiVhZFe1cJsuZIcrYjctVygElgI5URlRGwr3N6AlrCTFhVZTqsLoYtaq6DDVrNb7rU2TNudqaI2zoF0qnFGOGwdNc4qh0ED98z4lvp6cSQ@om92vmEhmhAxSB1iDcgito3izJe/vvHyJo@rx3kWBOdXX4cf "Charcoal – Try It Online") Link is to verbose version of code. Explanation (with compressed lookup tables redacted to `⪪”...”³`):
```
≔⌕⪪”...”³θη¿⊕η§⪪KYKMKPRS²η«
```
If the country is one of CYM, COM, PRK or SRB, then output KY, KM, KP or RS respectively, otherwise:
```
¿№⪪”...”³θΦθκ«
```
If the country is one of ATF, MYT, SPM or SGS, then output the second and third letters, otherwise:
```
§θ⁰
```
Output the first letter.
```
≔⌕⪪”...”³θη¿⊕η§XQYJAOEWELIAη
```
If the country is one of ALA, ATA, BLR, BEN, BIH, MAC, EST, GNB, IRL, ISR, SVN or UKR, then output the respective letter from XQYJAOEWELIA, otherwise:
```
§θ⊕№⪪”...”³θ
```
Output either the second or third letter of the input appropriately.
[Answer]
# [R](https://www.r-project.org/) + countrycode, ~~76~~ 74 bytes (using library)
*Edit: -2 bytes thanks to pajonk*
```
function(c)`if`(c=="ANT","AN",countrycode::countrycode(c,"iso3c","iso2c"))
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=f%3D%0Afunction(c)%60if%60(c%3D%3D%22ANT%22%2C%22AN%22%2Ccountrycode%3A%3Acountrycode(c%2C%22iso3c%22%2C%22iso2c%22))%0A%0Asapply(c(%22AFG%22%2C%22ALA%22%2C%22ALB%22%2C%22DZA%22%2C%22ASM%22%2C%22AND%22%2C%22AGO%22%2C%22AIA%22%2C%22ATA%22%2C%22ATG%22%2C%22ARG%22%2C%22ARM%22%2C%22ABW%22%2C%22AUS%22%2C%22AUT%22%2C%22AZE%22%2C%22BHS%22%2C%22BHR%22%2C%22BGD%22%2C%22BRB%22%2C%22BLR%22%2C%22BEL%22%2C%22BLZ%22%2C%22BEN%22%2C%22BMU%22%2C%22BTN%22%2C%22BOL%22%2C%22BIH%22%2C%22BWA%22%2C%22BVT%22%2C%22BRA%22%2C%22VGB%22%2C%22IOT%22%2C%22BRN%22%2C%22BGR%22%2C%22BFA%22%2C%22BDI%22%2C%22KHM%22%2C%22CMR%22%2C%22CAN%22%2C%22CPV%22%2C%22CYM%22%2C%22CAF%22%2C%22TCD%22%2C%22CHL%22%2C%22CHN%22%2C%22HKG%22%2C%22MAC%22%2C%22CXR%22%2C%22CCK%22%2C%22COL%22%2C%22COM%22%2C%22COG%22%2C%22COD%22%2C%22COK%22%2C%22CRI%22%2C%22CIV%22%2C%22HRV%22%2C%22CUB%22%2C%22CYP%22%2C%22CZE%22%2C%22DNK%22%2C%22DJI%22%2C%22DMA%22%2C%22DOM%22%2C%22ECU%22%2C%22EGY%22%2C%22SLV%22%2C%22GNQ%22%2C%22ERI%22%2C%22EST%22%2C%22ETH%22%2C%22FLK%22%2C%22FRO%22%2C%22FJI%22%2C%22FIN%22%2C%22FRA%22%2C%22GUF%22%2C%22PYF%22%2C%22ATF%22%2C%22GAB%22%2C%22GMB%22%2C%22GEO%22%2C%22DEU%22%2C%22GHA%22%2C%22GIB%22%2C%22GRC%22%2C%22GRL%22%2C%22GRD%22%2C%22GLP%22%2C%22GUM%22%2C%22GTM%22%2C%22GGY%22%2C%22GIN%22%2C%22GNB%22%2C%22GUY%22%2C%22HTI%22%2C%22HMD%22%2C%22VAT%22%2C%22HND%22%2C%22HUN%22%2C%22ISL%22%2C%22IND%22%2C%22IDN%22%2C%22IRN%22%2C%22IRQ%22%2C%22IRL%22%2C%22IMN%22%2C%22ISR%22%2C%22ITA%22%2C%22JAM%22%2C%22JPN%22%2C%22JEY%22%2C%22JOR%22%2C%22KAZ%22%2C%22KEN%22%2C%22KIR%22%2C%22PRK%22%2C%22KOR%22%2C%22KWT%22%2C%22KGZ%22%2C%22LAO%22%2C%22LVA%22%2C%22LBN%22%2C%22LSO%22%2C%22LBR%22%2C%22LBY%22%2C%22LIE%22%2C%22LTU%22%2C%22LUX%22%2C%22MKD%22%2C%22MDG%22%2C%22MWI%22%2C%22MYS%22%2C%22MDV%22%2C%22MLI%22%2C%22MLT%22%2C%22MHL%22%2C%22MTQ%22%2C%22MRT%22%2C%22MUS%22%2C%22MYT%22%2C%22MEX%22%2C%22FSM%22%2C%22MDA%22%2C%22MCO%22%2C%22MNG%22%2C%22MNE%22%2C%22MSR%22%2C%22MAR%22%2C%22MOZ%22%2C%22MMR%22%2C%22NAM%22%2C%22NRU%22%2C%22NPL%22%2C%22NLD%22%2C%22ANT%22%2C%22NCL%22%2C%22NZL%22%2C%22NIC%22%2C%22NER%22%2C%22NGA%22%2C%22NIU%22%2C%22NFK%22%2C%22MNP%22%2C%22NOR%22%2C%22OMN%22%2C%22PAK%22%2C%22PLW%22%2C%22PSE%22%2C%22PAN%22%2C%22PNG%22%2C%22PRY%22%2C%22PER%22%2C%22PHL%22%2C%22PCN%22%2C%22POL%22%2C%22PRT%22%2C%22PRI%22%2C%22QAT%22%2C%22REU%22%2C%22ROU%22%2C%22RUS%22%2C%22RWA%22%2C%22BLM%22%2C%22SHN%22%2C%22KNA%22%2C%22LCA%22%2C%22MAF%22%2C%22SPM%22%2C%22VCT%22%2C%22WSM%22%2C%22SMR%22%2C%22STP%22%2C%22SAU%22%2C%22SEN%22%2C%22SRB%22%2C%22SYC%22%2C%22SLE%22%2C%22SGP%22%2C%22SVK%22%2C%22SVN%22%2C%22SLB%22%2C%22SOM%22%2C%22ZAF%22%2C%22SGS%22%2C%22SSD%22%2C%22ESP%22%2C%22LKA%22%2C%22SDN%22%2C%22SUR%22%2C%22SJM%22%2C%22SWZ%22%2C%22SWE%22%2C%22CHE%22%2C%22SYR%22%2C%22TWN%22%2C%22TJK%22%2C%22TZA%22%2C%22THA%22%2C%22TLS%22%2C%22TGO%22%2C%22TKL%22%2C%22TON%22%2C%22TTO%22%2C%22TUN%22%2C%22TUR%22%2C%22TKM%22%2C%22TCA%22%2C%22TUV%22%2C%22UGA%22%2C%22UKR%22%2C%22ARE%22%2C%22GBR%22%2C%22USA%22%2C%22UMI%22%2C%22URY%22%2C%22UZB%22%2C%22VUT%22%2C%22VEN%22%2C%22VNM%22%2C%22VIR%22%2C%22WLF%22%2C%22ESH%22%2C%22YEM%22%2C%22ZMB%22%2C%22ZWE%22)%2Cf))
Seemingly the [R](https://www.r-project.org/) 'countrycode' library is more comprehensive than [Mathematica's "CountryCode" builtin](https://codegolf.stackexchange.com/a/246802), although still not perfect and requiring "ANT" to be hard-coded.
[Answer]
# [Perl 5](https://www.perl.org/) `-MLocale::Country -pl`, 48 bytes
```
$_=country_code2code($_,'alpha-3','alpha-2')||an
```
[Try it online!](https://tio.run/##NVTLbhQxELzXd0QKSOQSxCUSJ67wDZFfY3vtth0/ZjKjfDtLIcSht7ury55@eZvr@dv9/vD63dRVZj9fTbXu@e/Pp4fXL48qt6Cevj7@t54fP398qHK/q2KhuoPaPNSkRAWVNTGBKhPKV@LEOmOD2CK2BpQ@yCN@OegYoLuG9hbaZehN0e7QgWIjsQKdBVoWebQrOZ2cMKAn/X1CH/Qz@fmCUQXGJDB72hu1hwkOJu60iYcMI52aPN5leoRZGqYx/k78bDDMy7oFe4uwJcGKgq0Ceyk4s@DGhPMndYDjeTca3AzYYsHGM1tO2Fjv1itFwSsNrzt8t/Cuwq8Nnud9YCwy1jO8UPO8zw2@vBEzGH7ATyGfUhhfJ0LyCGIR2PvQd4QZEVZBtBTeE0dHFNqMxzqJvVHoD8Y4i5s7cVOCW@24tYLE/iZ/IQVBiqyfdaai0HpCIicdkz0hpi5kVZF1QTYKOTrkRM268iA@F/J6R97/YidEdYipEKsgxdHfaHsI@y/JQnKEcA5SiClD3SDzDdInhDVIpuauiN0hB7nuHXLSrxcK8y8mo7iOsiUUr1CiQckWhTmXxlhfxChXRmU/Gveikd/ODY3fbMyjqYTGHRhN0AzjnGUbjnqi5YP6xJua6NyFXhcG97Qzp859G4o@d32cnBN7Pw7HeTUM7tXYKTehTuQQZ52DfR7s7Vi0h8WY5Oad5@kfFyZ7Og3f09ww@W4md2PeEmbKmHlQCybnPCuFd8xJztoxD/rcy5U6FvuwJGINaua@Lo2d@e@Gwu/vnj5nvBfBzrd45A0H9/R0wt5OXJzRxT28WMvv2masZdyffv2sRmX38vLj37/D/anlPw "Perl 5 – Try It Online")
The ANT->AN mapping isn't in Perl's list, so it's hardcoded.
[Answer]
# [Whython](https://github.com/pxeger/whython), 370 bytes
```
lambda c:"AABBBKMKETGIIKYRPSGU"[p:="ALAATABLRBENBIHCYMMACCOMESTATFGNBIRLISRPRKMYTSRBSPMSVNSGSUKR".index(c)//3]+"XQYJAYOMEFWELPTSMISA"[p]?c[0]+c[1+(c in"ATGARMAUTABWBHSBGDBRBBLZBRNBDIANDAGOCPVCAFTCDCHLCHNCOGCODCOKDNKSLVGNQFLKFROGUFPYFGRLGRDGLPGINGUYIRQJAMKAZKORLBRLBYMDGMDVMLTMTQMEXFSMMNEMOZNIUMNPPAKPLWPLPNGPRYPCNPOLPRTMAFSENSYCSVKSLBSURSWZSWETUNTURTKMTUVURYWLFESHARE")]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZfRjuU4EYbF7Ui8w9nDTTcD7AI3qKURSpzE8YntuG0np5OhL5ZeWjsSzK5Gg2g0mifhZiSEeCdehRuc-nzBaKSjv12u-uuvctn5x7__9v3fP37_w_sv_3x-84d__fXj8y9_95-ffPjzt3_543ffnp7uzk3Ttu3kpj5rY6YthqSX89sf796cG9s0uWltbHvfmlFtzjVKza5PucmDLn-L1qQY4uS2nGKbgkurTzotUzz_6t377_70cvN0-_XXv318fX643y7NVvYO196GnJxJTYny-Punt988vn56--vXN0-nd-_PTdZNdM1S4l7bMbW6a2Pb2r2Nvu1M47tGzyqsqhmy6tRo1ejVrNXcqXnq_JTsqv39YKchznoZwjboaHXstA3aeL1sJt5fGjc1-zRH25b_m-u061Zns8v3rn8YknO-d_PuzeJ8CM0U7DXY4HWIW1A-zDbE7Joh9T5tKq0lZpuWmK57uvZ58XmJeXJ5WZe4Xe3Qp7GJ_fn2sUr_0_92pzenT69O52bQ57vj5_yLA9lG0ENFrSArqNtlrdtZS07WEsh3gjqQngXNIINPA8qg-4qIrkERFCsiggO1V0FX0JIELRVlQRm094LgWcp3oDZVFAWNIC2sW1iXEgtqQRbLDdRbQX1d2wXVCL0XdAG5RRCs28wazNoZL-hSmllQA7qKLi35tatk1K6VGWvosmrhuaKZmcXSVJ-ReL7mRw5YtgNeqHTpY0FUZRpF6wldlJN9ihxUIz4VPEvbC4JZOY2yb6uWg6wRoRyNA2XULadE1mxF-ITnOEndx0lQOd4HcmSkHuBCRyo1CVIg9FTVcoZLZT2LT6UrEi6qcpnxQjwVRQmFusqQH7qMUdBY1xZRXi019yCo5k7XKXqiDAE5K0ToLhKho0M6xzmCZwfrjhx6Jd3Tk1-vN0HkUKbKgRLKlwFzIM056smhh2cZjYLo1j5Ln_X0YJlKBxpgVgaUIKIP8BzgORip0WCqpbAeiFCmmkSn0mXAHSjUGZIFZZBuRDNN92gHInfdS3QNz66X3DuQHiWepiO1YR9cdJQO0ZVLlC7QtiKptKbSZeIKCpW1aK2pn84gdNForXWNJ7lrX7Um-rV6wZK6j1k0G_EyOok-kt_aSB1Wch-ZkWPt-UUijHAxSXIwTCmDpcHSdGJpyMhwwk2sSLrA3FeEFxQ0DktXI8g5MqhkmMIG1uUuOtAFy0uQfRc0u_SS7QWfl1m8XOiXcoHJiaPnJ-bghOVkxHKiYuV2FoTPCS8TOUxXUWlC3UnjkzrYRjrEoqBdhbXlBNhW4lnmtU1YpromEWysSHKwVMwaOakWZjZL11mUsMuDIKriJqmDq3Opk4niYOauUncHa7fJLeO2aikn1cHTWSxtRZKtI55jKjq6vNz9gqimi1iSg-PGc5XZJmtb9dILa8eMHLiZB1e5iGaO7nFKVHLMF-fJyFckujjq5-gXl-pMBlGH8i4RRN0dt4UjnqeXPJY-irqeHHyQbD1d4K2o69Gl8dzhcPEKS3j6HUQ8b-T0e-rne4nuYe21ZOt1tSQ6mvlBetAPNVuZDK5yoSM9fT1zcmYyKo8vmW50QXmHCaLuIYlmIVVL2RfIPaBu0PUESA8GOiTAOsA60AWBLijPO0EoEbjjgq1eRKWQK5LOCqh7z7S5J3pkmkYixBlEfpFeiugSeXnE-vKwUr-WeIl7OsFs8mI5wcwqTmPtJe5-h7rlES7M6hxUzEEsr_TnFc0S3ZOwTFmqksgvNcI6kVFiviSiJ15rsXrZpCcSEZKVqqSag8ZnvUVXqWaaKsKnqfvEZ2KiJG7mhGY7-e2VixYFdY2epJMTqE8Sr6-TaEKlGo9ZnjiN5cEuiPqlC_G4fctLXtBeERlRTTXy1hhr7nihs_JVImSqmS-SbcZn5gWf8Zm5YTNespWMMpplXvAZzfIkPZjJIc9EQJecsaRimVst-4qEWY7Vi-SXqXSme7KqljIxMxNz4RQvRD--4w6E8sdnzDEn6iuBOa-p2JLYh_KLk9OxEG_h_C2otOxS6QUlVr4fVs7DSp-tRFi9sF7JaOVWW-mX8mElnTzUuvPOQs-tl30bXnbePTtcdqq5HzX6_Or5hw-nl_LVeeruXp3ePZ-eb15uT1-9OXVvXx7LX04_fnj3_uPN8_nTy-e706dj9fNXp5tPx_Lnn9-eb4tJ2XXAY9dL-ZI9vS4_v3m8q1vPP_v_f-dbvgG_fOH3fw)
Improvable
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 217 bytes
```
Ṫ⁰y_«⌐ƈḣAɾǑP««∷Þ≤¦HU¤żǑ₄°ṅ›⌐7İḊṖİAs§dĖy'ΠA‹Ḃ»&ḃO꘍∴øð∷|6@¢⌊⁰ė‟~R¨ėṁPO∨{P
∵ḊĠɾm≬¾hṁw⁰Ṫ±√≠a›λḣY꘍≥jzm2⁋]Ẇ+₆↔√„eK⟩Ǒo→ġ≬e¦ŀMEt@y≬Dḭ^₀P≤∆₌»-⇩&λƈḟf!ßǎsGʁż℅÷}yǎġ∴fǒ¥¶ẇæ¬‛C↵⟩ḃXʀ£ƒz~≤ḃuȧ⌊«3ẇ⁰ɽḟk1%:£i⁰hp«∞τjḊ§«2ẇ¥i⁰ḢW¥»?Ṫ4»₁τ<∑i⇧
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuarigbB5X8Kr4oyQxojhuKNByb7HkVDCq8Kr4oi3w57iiaTCpkhVwqTFvMeR4oKEwrDhuYXigLrijJA3xLDhuIrhuZbEsEFzwqdkxJZ5J86gQeKAueG4gsK7JuG4g0/qmI3iiLTDuMOw4oi3fDZAwqLijIrigbDEl+KAn35SwqjEl+G5gVBP4oioe1BcbuKIteG4isSgyb5t4omswr5o4bmBd+KBsOG5qsKx4oia4omgYeKAus674bijWeqYjeKJpWp6bTLigYtd4bqGK+KChuKGlOKImuKAnmVL4p+px5Fv4oaSxKHiiaxlwqbFgE1FdEB54omsROG4rV7igoBQ4omk4oiG4oKMwrst4oepJs67xojhuJ9mIcOfx45zR8qBxbzihIXDt315x47EoeKItGbHksKlwrbhuofDpsKs4oCbQ+KGteKfqeG4g1jKgMKjxpJ6fuKJpOG4g3XIp+KMisKrM+G6h+KBsMm94bifazElOsKjaeKBsGhwwqviiJ7PhGrhuIrCp8KrMuG6h8KlaeKBsOG4olfCpcK7P+G5qjTCu+KCgc+EPOKIkWnih6ciLCIiLCJDWU0iXQ==) or [Run all the test cases](https://vyxal.pythonanywhere.com/#WyJqIiwixpsiLCLhuapueV/Cq+KMkMaI4bijQcm+x5FQwqvCq+KIt8Oe4omkwqZIVcKkxbzHkeKChMKw4bmF4oC64oyQN8Sw4biK4bmWxLBBc8KnZMSWeSfOoEHigLnhuILCuybhuINP6piN4oi0w7jDsOKIt3w2QMKi4oyK4oGwxJfigJ9+UsKoxJfhuYFQT+KIqHtQXG7iiLXhuIrEoMm+beKJrMK+aOG5gXfigbDhuarCseKImuKJoGHigLrOu+G4o1nqmI3iiaVqem0y4oGLXeG6hivigobihpTiiJrigJ5lS+KfqceRb+KGksSh4omsZcKmxYBNRXRAeeKJrEThuK1e4oKAUOKJpOKIhuKCjMK7LeKHqSbOu8aI4bifZiHDn8eOc0fKgcW84oSFw7d9eceOxKHiiLRmx5LCpcK24bqHw6bCrOKAm0PihrXin6nhuINYyoDCo8aSen7iiaThuIN1yKfijIrCqzPhuoduyb3huJ9rMSU6wqNpbmhwwqviiJ7PhGrhuIrCp8KrMuG6h8KlaW7huKJXwqXCuz/huao0wrvigoHPhDziiJFp4oenIiwiO1rGm2AgPT4gYGoiLCJbXCJVU0FcIiwgXCJBVVNcIiwgXCJCSUhcIiwgXCJJU0xcIiwgXCJGU01cIiwgXCJTWUNcIiwgXCJVTUlcIiwgXCJTUE1cIiwgXCJHVUZcIiwgXCJBVEZcIiwgXCJIS0dcIiwgXCJJT1RcIl0iXQ==) or [Try it on every country code](https://vyxal.pythonanywhere.com/#WyJqIiwixpsiLCLhuapueV/Cq+KMkMaI4bijQcm+x5FQwqvCq+KIt8Oe4omkwqZIVcKkxbzHkeKChMKw4bmF4oC64oyQN8Sw4biK4bmWxLBBc8KnZMSWeSfOoEHigLnhuILCuybhuINP6piN4oi0w7jDsOKIt3w2QMKi4oyK4oGwxJfigJ9+UsKoxJfhuYFQT+KIqHtQXG7iiLXhuIrEoMm+beKJrMK+aOG5gXfigbDhuarCseKImuKJoGHigLrOu+G4o1nqmI3iiaVqem0y4oGLXeG6hivigobihpTiiJrigJ5lS+KfqceRb+KGksSh4omsZcKmxYBNRXRAeeKJrEThuK1e4oKAUOKJpOKIhuKCjMK7LeKHqSbOu8aI4bifZiHDn8eOc0fKgcW84oSFw7d9eceOxKHiiLRmx5LCpcK24bqHw6bCrOKAm0PihrXin6nhuINYyoDCo8aSen7iiaThuIN1yKfijIrCqzPhuoduyb3huJ9rMSU6wqNpbmhwwqviiJ7PhGrhuIrCp8KrMuG6h8KlaW7huKJXwqXCuz/huao0wrvigoHPhDziiJFp4oenIiwiO1rGm2AgPT4gYGoiLCJbJ0FGRycsICdBTEEnLCAnQUxCJywgJ0RaQScsICdBU00nLCAnQU5EJywgJ0FHTycsICdBSUEnLCAnQVRBJywgJ0FURycsICdBUkcnLCAnQVJNJywgJ0FCVycsICdBVVMnLCAnQVVUJywgJ0FaRScsICdCSFMnLCAnQkhSJywgJ0JHRCcsICdCUkInLCAnQkxSJywgJ0JFTCcsICdCTFonLCAnQkVOJywgJ0JNVScsICdCVE4nLCAnQk9MJywgJ0JJSCcsICdCV0EnLCAnQlZUJywgJ0JSQScsICdWR0InLCAnSU9UJywgJ0JSTicsICdCR1InLCAnQkZBJywgJ0JESScsICdLSE0nLCAnQ01SJywgJ0NBTicsICdDUFYnLCAnQ1lNJywgJ0NBRicsICdUQ0QnLCAnQ0hMJywgJ0NITicsICdIS0cnLCAnTUFDJywgJ0NYUicsICdDQ0snLCAnQ09MJywgJ0NPTScsICdDT0cnLCAnQ09EJywgJ0NPSycsICdDUkknLCAnQ0lWJywgJ0hSVicsICdDVUInLCAnQ1lQJywgJ0NaRScsICdETksnLCAnREpJJywgJ0RNQScsICdET00nLCAnRUNVJywgJ0VHWScsICdTTFYnLCAnR05RJywgJ0VSSScsICdFU1QnLCAnRVRIJywgJ0ZMSycsICdGUk8nLCAnRkpJJywgJ0ZJTicsICdGUkEnLCAnR1VGJywgJ1BZRicsICdBVEYnLCAnR0FCJywgJ0dNQicsICdHRU8nLCAnREVVJywgJ0dIQScsICdHSUInLCAnR1JDJywgJ0dSTCcsICdHUkQnLCAnR0xQJywgJ0dVTScsICdHVE0nLCAnR0dZJywgJ0dJTicsICdHTkInLCAnR1VZJywgJ0hUSScsICdITUQnLCAnVkFUJywgJ0hORCcsICdIVU4nLCAnSVNMJywgJ0lORCcsICdJRE4nLCAnSVJOJywgJ0lSUScsICdJUkwnLCAnSU1OJywgJ0lTUicsICdJVEEnLCAnSkFNJywgJ0pQTicsICdKRVknLCAnSk9SJywgJ0tBWicsICdLRU4nLCAnS0lSJywgJ1BSSycsICdLT1InLCAnS1dUJywgJ0tHWicsICdMQU8nLCAnTFZBJywgJ0xCTicsICdMU08nLCAnTEJSJywgJ0xCWScsICdMSUUnLCAnTFRVJywgJ0xVWCcsICdNS0QnLCAnTURHJywgJ01XSScsICdNWVMnLCAnTURWJywgJ01MSScsICdNTFQnLCAnTUhMJywgJ01UUScsICdNUlQnLCAnTVVTJywgJ01ZVCcsICdNRVgnLCAnRlNNJywgJ01EQScsICdNQ08nLCAnTU5HJywgJ01ORScsICdNU1InLCAnTUFSJywgJ01PWicsICdNTVInLCAnTkFNJywgJ05SVScsICdOUEwnLCAnTkxEJywgJ0FOVCcsICdOQ0wnLCAnTlpMJywgJ05JQycsICdORVInLCAnTkdBJywgJ05JVScsICdORksnLCAnTU5QJywgJ05PUicsICdPTU4nLCAnUEFLJywgJ1BMVycsICdQU0UnLCAnUEFOJywgJ1BORycsICdQUlknLCAnUEVSJywgJ1BITCcsICdQQ04nLCAnUE9MJywgJ1BSVCcsICdQUkknLCAnUUFUJywgJ1JFVScsICdST1UnLCAnUlVTJywgJ1JXQScsICdCTE0nLCAnU0hOJywgJ0tOQScsICdMQ0EnLCAnTUFGJywgJ1NQTScsICdWQ1QnLCAnV1NNJywgJ1NNUicsICdTVFAnLCAnU0FVJywgJ1NFTicsICdTUkInLCAnU1lDJywgJ1NMRScsICdTR1AnLCAnU1ZLJywgJ1NWTicsICdTTEInLCAnU09NJywgJ1pBRicsICdTR1MnLCAnU1NEJywgJ0VTUCcsICdMS0EnLCAnU0ROJywgJ1NVUicsICdTSk0nLCAnU1daJywgJ1NXRScsICdDSEUnLCAnU1lSJywgJ1RXTicsICdUSksnLCAnVFpBJywgJ1RIQScsICdUTFMnLCAnVEdPJywgJ1RLTCcsICdUT04nLCAnVFRPJywgJ1RVTicsICdUVVInLCAnVEtNJywgJ1RDQScsICdUVVYnLCAnVUdBJywgJ1VLUicsICdBUkUnLCAnR0JSJywgJ1VTQScsICdVTUknLCAnVVJZJywgJ1VaQicsICdWVVQnLCAnVkVOJywgJ1ZOTScsICdWSVInLCAnV0xGJywgJ0VTSCcsICdZRU0nLCAnWk1CJywgJ1pXRSddIl0=)
Port of 05AB1E.
## How?
```
Ṫ⁰y_«⌐ƈḣAɾǑP««∷Þ≤¦HU¤żǑ₄°ṅ›⌐7İḊṖİAs§dĖy'ΠA‹Ḃ»&ḃO꘍∴øð∷|6@¢⌊⁰ė‟~R¨ėṁPO∨{P
∵ḊĠɾm≬¾hṁw⁰Ṫ±√≠a›λḣY꘍≥jzm2⁋]Ẇ+₆↔√„eK⟩Ǒo→ġ≬e¦ŀMEt@y≬Dḭ^₀P≤∆₌»-⇩&λƈḟf!ßǎsGʁż℅÷}yǎġ∴fǒ¥¶ẇæ¬‛C↵⟩ḃXʀ£ƒz~≤ḃuȧ⌊«3ẇ⁰ɽḟk1%:£i⁰hp«∞τjḊ§«2ẇ¥i⁰ḢW¥»?Ṫ4»₁τ<∑i⇧
# ^ full program
Ṫ # Remove the last character of the (implicit) input
⁰ # Push the input again
y # Uninterleave, push a[::2] and a[1::2] to the stack
_ # Pop so a[1::2] is removed. Stack: a[:-1], a[::2]
«⌐ƈḣAɾǑP« # Push compressed string "aaeeijloqwxy"
«∷Þ≤¦HU¤żǑ₄°ṅ›⌐7İḊṖİAs§dĖy'ΠA‹Ḃ»&ḃO꘍∴øð∷|6@¢⌊⁰ė‟~R¨ėṁPO∨{P
∵ḊĠɾm≬¾hṁw⁰Ṫ±√≠a›λḣY꘍≥jzm2⁋]Ẇ+₆↔√„eK⟩Ǒo→ġ≬e¦ŀMEt@y≬Dḭ^₀P≤∆₌»-⇩&λƈḟf!ßǎsGʁż℅÷}yǎġ∴fǒ¥¶ẇæ¬‛C↵⟩ḃXʀ£ƒz~≤ḃuȧ⌊«
# Push compressed string "atfmytspmsgscymcomprksrbatagnbalablrbihukrestirlsvnbenisrmacabwagoandarearmatgautbdibgdbhsblzbrbbrncafchlchncodcogcokcpvdnkeshflkfrofsmginglpgnqgrdgrlgufguyirqjamkazkorlbrlbymafmdgmdvmexmltmnemnpmozmtqniupakpcnplwpngpolprtprypyfsenslbslvsursvksweswzsyctcdtkmtunturtuvurywlf"
3ẇ # Split into chunks of 3: ["atf", "myt", "spm", ..., "ury", "wlf"]
⁰ɽ # Push the input and lowercase it
ḟ # Find its index in the list (-1 if not found)
k1% # Modulo 1000 to convert -1 to 999
:£ # Store in the register without popping
i # Index this into the string pushed earlier ("aaeeijloqwxy")
⁰h # Push the first character of the input
p # Prepend it
«∞τjḊ§« # Push compressed string "kykmkprs"
2ẇ # Split into chunks of two
¥ # Push the contents of the register
i # Index this into the list
⁰Ḣ # Push the input without the first character
W # Wrap these five values on the stack into a list
¥ # Push the contents of the register
»?Ṫ4» # Push compressed integer 4082091
₁τ # Convert to base 100 list: [4, 8, 20, 91]
< # For each item, is the register (pushed earlier) less than it?
∑ # Sum this to get the amount of integers that the register is less than
i # Index this into the list pushed earlier
⇧ # Uppercase
```
] |
[Question]
[
## Challenge
Given a base \$1 < b < 10\$ and an index \$t \ge 1\$, output term \$x\_t\$, defined as follows:
* \$x\_1 = 11\_{10}\$
* \$x\_{i+1}\$ is obtained by converting \$x\_i\$ to base \$b\$ and then reinterpreting its digits in base \$10\$
* Output should be in base \$10\$
A walk through for base 5, term 5 would be:
* \$x\_1 = 11\_{10}\$.
* \$11\_{10} = 21\_{5}\$ so \$x\_2 = 21\_{10}\$.
* \$21\_{10} = 41\_{5}\$ so \$x\_3 = 41\_{10}\$.
* \$41\_{10} = 131\_{5}\$ so \$x\_4 = 131\_{10}\$.
* \$131\_{10} = 1011\_{5}\$ so \$x\_5 = 1011\_{10}\$.
* We output the string `"1011"` or the integer `1011`.
## Test Cases
Note: these are one indexed
```
base 2, term 5 --> 1100100111110011010011100010101000011000101001000100011011011010001111011100010000001000010011100011
base 9, term 70 --> 1202167480887
base 8, term 30 --> 4752456545
base 4, term 13 --> 2123103032103331200023103133211223233322200311320011300320320100312133201303003031113021311200322222332322220300332231220022313031200030333132302313012110123012123010113230200132021023101313232010013102221103203031121232122020233303303303211132313213012222331020133
```
## Notes
* Standard loopholes are not allowed
* Any default I/O method is allowed
* You may use different indexes (such as 0-indexed, 1-indexed, 2-indexed, etc) for \$t\$
* You may output the first \$t\$ terms.
* As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), **shortest code wins for that language**
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 40 bytes
*Thanks to @Neil for saving 5 bytes on this version and 2 bytes on the BigInt version*
Takes input as `(t)(base)`, where \$t\$ is 1-indexed.
```
n=>g=(b,x=11)=>--n?g(b,+x.toString(b)):x
```
[Try it online!](https://tio.run/##VchJCoAwDADAuy9p0IriwQVSH@EL6lYqkogW6e9jrx5nDvvaZ7n9FTTxusmOQmgcqrmIWNeARmsaXWIey8BTuD0lAQxRFqaHz6082aldtRWoHiD7b5O2A5AP "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 48 bytes (BigInt version)
Takes input as `(t)(base)`, where \$t\$ is 1-indexed. Returns a BigInt.
```
n=>g=(b,x=11n)=>--n?g(b,BigInt(x.toString(b))):x
```
[Try it online!](https://tio.run/##ZcjBCoJAEAbge08yP7TSplEJY9Cts0@gpsuGzIQusW@/7VU8ft@n@3XrsPhvMKLvMU2chBvH1B8jWyvgxhh5uOyndy8JFIugbVi85ANQxzSorDqPxayOJrqAzsBhm9cT6L7bMu9tt7YEVUD6Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
>IF¬πB
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fztPt0E6n//8tucwNAA "05AB1E – Try It Online")
**Explanation**
```
> # increment <base>
IF # <term> times do:
¬πB # convert from base-10 to base-<base>
```
Note that there is no need to explicitly start the sequence at **11**.
Starting at `base+1` and doing an extra iteration will result in the first iteration giving **11**.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
ÆB=sV n
B
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xkI9c1YgbgpC&input=MAo5)
```
(Two inputs, U and V)
Æ Range [0..U)
B= For each, set B (B is preinitialized to 11) to
sV B's previous value converted to base-V
n and back to base-10
B Print out B's final value
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
!¬°odB¬π‚Üí
```
[Try it online!](https://tio.run/##yygtzv6fm18erOP2qKnxv@KhhfkpTod2Pmqb9P///2gNIx0zTR0NSx1zQyBloWMMokx0DE00YwE "Husk – Try It Online") This version is 2-indexed; it takes the two inputs \$b\$ and \$t\$ as arguments.
### Explanation
```
!¡odB²→²⁰ (Written with explicit arguments; let B and T denote them.)
! ⁰ Take element T of
¬° the function repeatedly applied to
→² B + 1:
o B² Convert to base B
od then convert to decimal.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes
```
bÔí°Nest[FromDigits[#~IntegerDigits~b]&,11,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@n9pIV@qcUl0W5F@bkumemZJcXRynWeeSWp6alFEH5dUqyajqGhjnKs2v@Aosy8kuhqZeVaXbu0aOXYaGWj2Fg1BweHaq5qUx2TWh2uaiMIZaljZgmiLXSMwLSJjqFRLVftfwA "Wolfram Language (Mathematica) – Try It Online")
Call with `f[base][t]`. 0-indexed.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 67 bytes
```
.+,(\d+)
11,$1*
"$+"{`^\d+
*
)+`(?=_.*,(_+))(\1)*(_*)
$#2*_$.3
,_+
```
[Try it online!](https://tio.run/##DcgrDoAwDABQ32OMiv6ypHwk4SILHQkIDILgOPzgyXcfz3lt3lpWo7Irg7uhCyTU9Nb1LxBgrbTMkcUolJmKs1AIA3a9BOYBLBRaG236AA "Retina – Try It Online") Takes comma-separated inputs \$t\$ (0-indexed) and \$b\$. Does all of its calculations in unary so times out for large numbers. Explanation:
```
.+,(\d+)
11,$1*
```
Initialise \$x\_0=11\$ and convert \$b\$ to unary.
```
"$+"{`
```
Repeat \$t\$ times.
```
^\d+
*
```
Convert \$x\_i\$ to unary.
```
)+`(?=_.*,(_+))(\1)*(_*)
$#2*_$.3
```
Convert to base \$b\$.
```
,_+
```
Delete \$b\$ from the output.
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
def f(b,n):h=lambda x:x and x%b+10*h(x/b);return n and h(f(b,n-1))or 11
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0knT9MqwzYnMTcpJVGhwqpCITEvRaFCNUnb0EArQ6NCP0nTuii1pLQoTyEPLJWhAdaka6ipmV@kYGj4v6AoM68EaJKpjokmF4xjoWNkieCZ6Bgaaf4HAA "Python 2 – Try It Online")
0-indexed.
[Answer]
# [Clojure](https://clojure.org/), 109 bytes
*Credit to MilkyWay90 for removing 10 bytes by spotting unnecessary spaces*
*Credit to Embodiment of Ignorance for another byte from another unnecessary space*
**Golfed**
```
(defn f([b t](f b t 11))([b t v](if(= t 1)v(f b(dec t)(read-string(.(new BigInteger(str v))(toString b)))))))
```
**Ungolfed**
```
(defn f
([base term] (f base term 11))
([base term value] (if (= term 1)
value
(f base (dec term) (read-string (. (new BigInteger (str value)) (toString base)))))))
```
I think the main place bytes could be saved is the expression for... *reradixing?* whatever that would be called. Specifically:
```
(read-string (. (new BigInteger (str value)) (toString base)))
```
[Answer]
# [Perl 6](http://perl6.org/), 28 bytes
```
{(11,+*.base($^b)...*)[$^t]}
```
[Try it online!](https://tio.run/##FcjRCoIwAEDRX7nIkM1sOC01SH8kFBTck6GoLzL27csez1mnbS7D9yS2NMFJY9Jbosdhn6ToR6W1TtRH9Efng2MfTqKrU66haXFWir@Ou1E@wmOXjXfOkxdVRk2R8cAUbfgB "Perl 6 – Try It Online")
The index into the sequence is zero-based.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
```
‘b³Ḍ$⁴¡
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//4oCYYsKz4biMJOKBtMKh////Nf80 "Jelly – Try It Online")
A full program that takes \$b\$ as first argument and 1-indexed \$t\$ as its second argument. Returns the integer for the relevant term (and implicitly prints). Uses the observation by @Emigna regarding starting with \$b + 1\$.
### Explanation
```
‘b³Ḍ$⁴¡ | Main link: first argument b, second argument t
‘ | b + 1
$⁴¡ | Repeat the following t times
b³ | Convert to base b
Ḍ | Convert back from decimal to integer
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 13 bytes
```
{y(10/x\)/11}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqrpSw9BAvyJGU9/QsPZ/WrSFtZFl7H8A "K (ngn/k) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
uijGQTEh
```
[Try it online!](https://tio.run/##K6gsyfj/vzQzyz0wxBXIMuUyBQA "Pyth – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 87 bytes
```
n=>m=>{int g=11;for(var s="";m-->0;g=int.Parse(s),s="")for(;g>0;g/=n)s=g%n+s;return g;}
```
Saved 5 bytes thanks to @KevinCruijssen
[Try it online!](https://tio.run/##VYoxC8IwEIV3f0UoCDls1Dq1nJfRycHNuYQ0ZOgVcqmL@NtjuggOD977vufEOInltrK7Rs7tr9RYO1FhsjPZd50qUNfhtCT9GpMSahqcjbFnDFTt8TEm8Vqg3QxsNwybPBGDUNjzQTD5vCZWAT8Fd88Us79H9nrSA@huAPiHPehLX2H5Ag "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 270 bytes
```
++<<++<,+++<-[----->-<]<,,[<-----[->++++++++++<]++>[-<+>],]<[>>>>>>[<<<[->>+<<]>>>>>]<<[[>+<-]>>[-[<++++++++++>-]>+>]<[<<]>>[-<<+>>>+<]>>[-[<-[>>+>>]>>[+[-<<+>>]>[-<]<[>]>++>>>]<<<<<-]+>[-<+<+>>]<<[->>+<<]>>>]<[-]<[[-<+>]<<]<]<[->>+<<]<-]>>>>[>>]<<[>-[-----<+>]<----.<<]
```
[Try it online!](https://tio.run/##VU/BqgIwDPuVd@/iyXcL/ZHSgwqCCB4Ev3@m3VAMdCxdknbn5@n2uL4u9znNSNUwHQgUHEyOEWwWcPuAaeYBmudIhjeCpFSupOxGiocoRAPBr9/VkpfRUgUpqYxbCCWqUcz2Y5aqRsloK1tArjVa8TNdUqjWjmqVd7/2PopeFt@/bV1dDpLM@f93fAM "brainfuck – Try It Online")
0-indexed. The number of iterations is assumed to be at most 255.
## Explanation
The tape is laid out as follows:
```
num_iterations 0 0 base digit0 0 digit1 0 digit2 ...
```
Each digit is actually stored as that digit plus 1, with 0 reserved for "no more digits". During the base conversion, the digits currently being worked on are moved one cell to the right, and the base is moved to the left of the current working area.
```
++<<++ Initialize initial value 11
<,+++<-[----->-<] Get single digit as base and subtract 48 to get actual number
<,,[<-----[->++++++++++<]++>[-<+>],] Read multiple digits as number of iterations
< Go to cell containing number of iterations
[ For each iteration:
>>>>>> Go to tens digit cell
[<<<[->>+<<]>>>>>] Move base to just before most significant digit
<< Return to most significant digit
[ For each digit in number starting at the left (right on tape):
[>+<-] Move digit one cell to right (to tell where current digit is later)
>>[-[<++++++++++>-]>+>] Multiply each other digit by 10 and move left
<[<<]>> Return to base
[-<<+>>>+<] Copy base to just before digit (again) and just before next digit to right (left on tape)
>>[ For each digit at least as significant as this digit:
-[<-[>>+>>]>>[+[-<<+>>] Compute "digit" divmod base
>[-<]<[>]>++ While computing this: add quotient to next digit; initialize digit to "1" (0) first if "0" (null)
>>>]<<<<<-] End of divmod routine
+>[-<+<+>>] Leave modulo as current digit and restore base
<<[->>+<<] Move base to next position
>>>
]
<[-]< Delete (now useless) copy of base
[[-<+>]<<]< Move digits back to original cells
] Repeat entire routine for each digit
<[->>+<<] Move base to original position
<- Decrement iteration count
]
>>>>[>>]<<[>-[-----<+>]<----.<<] Output by adding 47 to each cell containing a digit
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
≔11ζFN≔⍘IζIηζζ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DydBQSUehStOaKy2/SEHDM6@gtMSvNDcptUhDU1MBqsgpsTg1uKQoMy9dwzmxuESjSlNHAczI0NSEaA4ASoLErf//N@Ey@q9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs as \$t\$ (0-indexed) and \$b\$. Explanation:
```
≔11ζ
```
\$x\_0=11\$.
```
FN
```
Loop \$b\$ times.
```
≔⍘IζIηζ
```
Calculate \$x\_i\$.
```
ζ
```
Output \$x\_t\$.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes
```
(b,n)->x=11;for(i=2,n,x=fromdigits(digits(x,b)));x
```
[Try it online!](https://tio.run/##LcfRCoMgGIbhW/noyB9@YdZiG2E3Eh7YhiE4E9eBu3pXo6P3eZPNXi6pOmhUMXMkORat1ODWLLxuOXLRLq/vl1/89hFnCs9ENJRqUwpfYSFHpOzjtrM5psHThiAcwxIxpqln9GZHe/bBuF0O3BndH1eG6oyh@gM "Pari/GP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 59 bytes
```
f(t,b){t=t?c(f(t-1,b),b):11;}c(n,b){n=n?c(n/b,b)*10+n%b:0;}
```
[Try it online!](https://tio.run/##FclBCoAgEEDRfccQgrGUFGqTSBdpkxOGi4YId@LZbYK/eXzUF2JrEbIKsmSfNwSGtkxutdZVBPoneeJJU2AM1ozUh9W42u4jEcjSPW@iHEH0505CRZjVIqXravsA "C (gcc) – Try It Online")
[Answer]
# [Groovy](http://groovy-lang.org/), 45 bytes
```
a,b,c=11->a--?f(a,b,a.toString(c as int,b)):c
```
[Try it online!](https://tio.run/##Sy/Kzy@r/J9mW/0/USdJJ9nW0FDXLlFX1z5NA8RP1CvJDy4pysxL10hWSCxWyMwr0UnS1LRK/l/LxVUAFC/JyVNI0zDVMdVE4lromGv@BwA "Groovy – Try It Online")
Port of @Arnauld's answer
[Answer]
# [PHP](https://php.net/), ~~83~~ 75 bytes
```
function c($b,$t,$v=11){return $t==1?$v:c($b,$t-1,base_convert($v,10,$b));}
```
[Try it online!](https://tio.run/##7VPBjtowED3HXzGKciCrwHrGyYaWpnvooYeVupfeaFRBagTSNkGJ4bLi2@mMbXb7BT01GHv83sx7E0Yc98frp8cj77tT37nD0EM3y7ZF5ors3CDmr6N1p7GHzDUNPmbnj5GeY7HdTPZnN/RnO7pZdi5QF9k2z1eXq7q/U9/t5OALp0yqeXuUkiKgApwdf0MF8/lnQNRaljxyxIsW1F88GG46BCENY7IvfSvxD8Ytghh8P0TfWgdj0oQPdbnUy2UdMpYxw4SMsq6orB6qsgp0GWk0niYkg9poQ7wbw3pae8QwgkSGJCKGDaIhacRwTLJQQEIjIStokUHhGUNRkkKWYA05fQZHXMOcnJIvhsZbc5r2IGvyb0E@kF08hWNzI@/rG0Rf4JvgkOWkSPqSHqSOxIY/LK3jIvRK/PUuvjcuZQGj7u6VyjoZNjSwVsm6KoBXKu5pWzBAEfgHsw6GPOtai@PfQw4UD9kI9T7dgPN00TD@f6xhrGmr2pVSu2G0m24PszjhzQQ@yuFVJdlop9OL47FvA7/WbRH4Nbb5SiWHHVfespomctT68sR2@wHS56cffcq5F5XYF/6fvTPfBgfPTwv4ymcKC7gpLfh26CdnN79g2AUqCgt3k7tc/wA "PHP – Try It Online")
This one will only work work with "small" numbers (e.g. not test cases 1 and 4)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
0-indexed. Takes `t` as the first input, `b` as the second.
```
_ìV ì}gBìC
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X%2bxWIOx9Z0LsQw&input=MjkKOA)
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 8 bytes
```
Bd
11@↑ₓ
```
[Try it online!](https://tio.run/##S0/MTPz/3ymFy9DQ4VHbxEdNk///N7LksgAA "Gaia – Try It Online")
Takes 0-based `iterations` then `base`.
```
Bd | helper function: convert to Base b (implicit) then convert to base 10
| main function:
11 | push 11
@ | push # of iterations
↑ₓ | do the above function (helper function) that many times as a monad
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
Zero-indexed.
```
->b,n,x=11{n.times{x=x.to_s(b).to_i};x}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cuSSdPp8LW0LA6T68kMze1uLrCtkKvJD@@WCNJE0Rn1lpX1P4vKC0pVkiL1kotS8zRUInXjP0fbaRjEssVbaljZhmrnJeZnMoVbaJjaBT7L7@gJDM/r/i/bh4A "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-Mbigint -pa`, 65 bytes
```
$\=11;map{$p=$\;$\%=0+"@F";$\=($p%"@F").$\while$p/=0+"@F"}2..<>}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxtbQ0Do3saBapcBWJcZaJUbV1kBbycFNCci01VApUAWxNfVUYsozMnNSVQr0odK1Rnp6Nna11f//m3IZ/csvKMnMzyv@r@trqmdgaACkkzLTM/NK/usWJAIA "Perl 5 – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 16 bytes
```
11\~{base""*~}+*
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/39Awpq46KbE4VUlJq65WW@v/fxMFUwA "GolfScript – Try It Online")
The input is `t` (0-indexed) and then `b`.
```
11 # x_1
\~ # Parse the inputs to integers
{base""*~}+ # Add b to the beginning of this block to get {b base""*~}
{b base""*~} # This block goes from x_n to x_(n+1)
b base # Convert to base b
""* # Join the digits with "" between them
~ # Parse it to an integer
* # Execute this block t times
```
] |
[Question]
[
Challenge Taken from my university code challenge contest
This is actually Day 0 but yesterdays' challenge was too easy and can be a dupe of another question here.
---
Tetris is a video game that became popular in the 80s. It consists of placing a series of pieces with different shapes that fall on a board, so that they fit in the most compact way possible.
In this problem we will assume a sequence of pieces that fall, each in a certain position and with a certain orientation that can not be changed. The pieces are piled up as they fall and the complete rows are not eliminated (as in the original game). The objective is to determine the final height of each column of the board after all the pieces fall.
There are a total of 7 different pieces, shown in the figure:
[](https://i.stack.imgur.com/Houek.png)
**Challenge**
Given a list of pieces, output the height of all the columns from the board after all pieces falls
A piece consists of three numbers: I, R and P. The first number, I, is the identifier of the piece (a number between 1 and 7, in the same order as in the figure). The second number, R, is the rotation of the piece. It can take the values ​​0, 90, 180 or 270 and represents the angle of rotation of the piece in the anti-clockwise direction. The third number, P, indicates the position of the piece. Represents the column on the left occupied by the piece (this can be 1 or 0 Index. Please specify).
**Example and Test case (1 Index)**
* Given `[[1, 0, 1], [4, 0, 1], [5, 90, 4]]`
[](https://i.stack.imgur.com/GuLzB.png)
* Output `[3, 3, 1, 3, 2]`
---
* Given `[[6, 270, 4], [1, 180, 5], [1, 90, 6], [7, 0, 4]]`
[](https://i.stack.imgur.com/V9d8B.png)
* Output `[0, 0, 0, 9, 9, 8, 3, 3]`
---
* Given `[[3,0,1],[3,180,3]]` Output `[1,1,4,4,4]`
* Given `[[2,180,1],[2,0,3]]` Output `[2,2,4,3,3]`
**Notes**
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
* Row/Column can be 1 or 0 Index. Please specify.
* You can redefine input values (maybe you want to call piece 1 as A, etc..). In that case please specify
**Questions**
* Can we use any 4 distinct values instead of an angle in degrees?: *Yes*
* Are we supposed to handle "holes" if a piece doesn't exactly fit over the previous ones?: *Yes*
* Is the height or the width of the board bounded? *No. Neither the width nor the height are bounded*
---
Thanks @Arnauld for the images and the test cases \*.\*
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~ 286 284 270 ~~ 266 bytes
Pieces and positions are 0-indexed. Angles are in \$[0..3]\$.
```
a=>a.map(([p,r,x])=>(g=y=>y>3?g(+!Y--):b[Y+y]&(m[y]=('0x'+`717433667233ff4717333327661${1e12+0x5e7056a566ffff57efa65n.toString(4)}`[(p*2+r*56+y*99+13)%113])<<x)?m.map(v=>(g=x=>v&&g(x+1,H[x]=v&1?Y:~~H[x],v>>=1))(0,b[++Y]|=v)):g(y+1))(Y=a.length*4),m=[b=[-1]],H=[])&&H
```
[Try it online!](https://tio.run/##XY7NboMwEITvfYtKLbHxgjDGRoli55p7T8iyFJMCTRV@RBACtc2rUwf11NnDaHb3k@bTjvZ27i/dEDTte7GUcrFS2bC2HUK6gx4mg6VClZylmhU7VIg8Z0GAd7nOyGw8VOvZSLSJpg05pTRNGBMijRkry8RF5hSnQtCXL1rQmEQTL9KIC8uFKJ14WpRW8CYc2rehvzQVSvDPSaPOj0nvc0Fmf7sllOFXSpnB@/2ED/XablxbTVKNnlehiVA46snI0aOHbHe/PwKMSkmKMYog14Rk5luOGO8qNJPHNpM2vBZNNXz4CYZa6lzqgBoDR6kN9rzjcm6bW3stwmtboRJpHYEbA5r9eQIUmDEYP/3/5MDcBRwRQ7I6Be5cOHIlll8 "JavaScript (Node.js) – Try It Online")
or [try an enhanced version](https://tio.run/##TU/bbtswDH3vV3jAZpORolqWL2hQKU8D8t4nQxBQJZXdFIltOIZhY1s/Y9j37UcyOdiwkg@HhzwED9/saC@H/tgN66Z9cddKXq1Ulp1tB6A72tPJoFRQy1mqWYltDeRTuV7jZq9LMpsQzno2EqJ4ishzwYtUiDwvEiGqKvVU@EiKPOefv3HHExJPmSviLLdZnlc@ssJVNs8aNrRPQ39sakjxx7OGbpWQfpXlZF49PBAu8AvnwuDj44Tb883deHM1STWGYQ0T4XSnJyPHkG/Lzfv7QuiolOSIENO9JqQ03@WIuKlhJku3lJadXFMPr6sU6VnqvdRrbgzdSW0wDHfXwV2GQAY2kCqAna8qsEiDPevd6PqLA2RV23@1h1doFs2hbS7tybFTW4NmjPmuUiqI8f97Cfrl7mQPDu7ZfU2D22IU/P75K9KNQdbZl6fB9gOIBM2HQ2/tsYEoQvQGPt7ZId7dLUZB65j6NFSLv5hSToUx@G@eUeE59bqEpjfkNPOYe/2iu/4B) that also displays the final board.
### Shape encoding
All pieces are stored as exactly 4 nibbles (4x4 bits) with the rows sorted in reverse order and the leftmost pixel mapped to the least significant bit. In other words, the binary representation of the shape is mirrored both vertically and horizontally.
Example:
[](https://i.stack.imgur.com/aMY9Z.png)
### Hash function and lookup table
Given a piece \$p \in [0..6]\$, a rotation \$r \in [0..3]\$ and a row \$y \in [0..3]\$, we use the following hash function to get the index \$n\$ of the corresponding bitmask from a lookup table:
$$n=(2p+56r+99y+13)\bmod 113$$
Only the first \$82\$ entries are explicitly stored. Everything else is set to \$0\$.
These entries are packed as:
```
`717433667233ff4717333327661${1e12+0x5e7056a566ffff57efa65n.toString(4)}`
```
which expands to the following 82 nibbles:
```
"717433667233ff47173333276611000000000000113213001112221112123333333311133233221211"
```
Using hexadecimal in the final format is only required for the two horizontal representations of the \$I\$ piece, hence the `"ff"` in the above string.
The parameters of the hash function were brute-forced in a way that optimizes leading and trailing zeros. The fact that the string can be compressed some more by using `1e12` for the zeros in the middle and a conversion from base-16 to base-4 for the right part is just a welcome but unexpected side effect. :-)
[**Here is a demonstration**](https://tio.run/##ZVBdToNAEH7nFPOAAUql/C6pVS9BfFITNnRpsLi7WdCUkO2zJ/AcnsGjeBEcaJumOi@zO9/PfJkX@k6bQlWyveZizYYhgzvI0yCNo4iQNIyisozxG2GFKSGB2QcsCF1/l7DUTwhNCCmxkpSVlCTca0XWqopv7NjR@cowCsEbUTOvFhs7f@CSFlu2hlqI7ZuEZqLePHGzz/QTzx0UlELZEkP4K5BwCyk213WgNwBGSB0ghVCM7QQBXCySFSsYMs1e6jko0dK2EnwaKJjB0tffX9O2UTnadgfb7mDbnW0BRhkmmkEILozqhOCjG22W@AgiB64gCKLVkf/abFGx39uWv7OQkD3yZ@cEXqT0d2aP7PPNAuJo@DMLHU8xWdOC2QtvsZmPee7B8n4@P6zR2ZN0nbVUtXY8x7GFZz9u0//uMgHa0MPwCw) of the unpacking process for all pieces and all rotations.
### Commented
```
a => a.map(([p, r, x]) => ( // for each piece p with rotation r and position x:
g = y => // g = recursive function taking y
y > 3 ? // if y is greater than 3:
g(+!Y--) // reset y to 0, decrement Y and try again
: // else:
b[Y + y] & ( // test if we have a collision of the board with
m[y] = // the y-th row m[y] of the current piece
('0x' + `717...`[ // which is extracted from a lookup table
(p * 2 + r * 56 + // using the hash function described in the
y * 99 + 13) % 113 // previous paragraph
]) << x // and shifted to the left according to x
) ? // if we have a collision:
m.map(v => ( // we iterate again on the piece rows stored in m[]
g = x => // g = recursive function taking x
v && // if v is not equal to 0:
g( // do a recursive call:
x + 1, // increment x
H[x] = // update the height at x:
v & 1 ? // if this bit is set:
Y // set it to Y
: // else:
~~H[x], // leave it unchanged or force it to 0
// if it was still undefined
v >>= 1 // shift v to the right
) // end of recursive call
)(0, // initial call to g with x = 0
b[++Y] |= v) // increment Y and copy the piece row to the board
) // end of map()
: // else (no collision):
g(y + 1) // do a recursive call to test the next row
)(Y = a.length * 4), // initial call to g with y = Y = 4 * the number of pieces
// (assuming the worst case: piled vertical I pieces)
m = [b = [-1]], H = [] // initialize m[], b[] and H[]
// we set a full line at the bottom of b[]
) && H // end of map(); return H[]
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~[253](https://tio.run/##hVDRjtsgEHzPV6xSRTLxpjEGV44w/RHXD5gcV6QcsS6pWsXi1@suXKq0D9dKeBlmdvEMdmdPJjwvy7Xw4bo1mOqYKlg2u/NrouHWD70c9DxLHnEWUmDdEuCiqrE@CIJNTbA9EJK8rZHLA/KmIjH319gIPFRUUy/nvEJecfpovOUxosOAE3pldzs1liX9WfOuK7ZjWbO9UE4HfevpVA65btygsjc96Ur5TruNVJN2L@ZHMaFJPZ56y7CRjIW9lrlbebr9TRz0lMWsxbh88MGevh2foLtcj/788evn1SoFfzE@FAzmFUA6mr4ZQMMc1Z0Y6WFEpmDmCBWtiDBXD1gjkCAi5JlrYRDyS7ORWJY4spYp8HRPpWjr4OJvT2dXGLa/o61hCsrSv3kBmF5pwhXrjYc1ki8/5Lvi6iF9CWvi7kZt3/7t/PiH809kJXnEHIIcyzuk1SQocp5HCPs7xJF6/xfCPkLYf4Ww74eIy0/rTub5suy@/wI)~~ ~~[239](https://tio.run/##hVBdj5swEHzPr1ilioRhaTA2Fci4f4TyYJzz1VLOqS45tQTx149bfKlyfWgrPnZ2Zr3MYHN7NOFxWS5JajAd0LLJnZ4THy5w7Xo9SV6XyGWDvCqwbFDIEiuBTUFvgZzzAnnB6SmxrDnJgioWdHGxco2ITVVSUzcRSz6jw4AjemXzXA1ZRh/VvG2TOk8HthfK6aCvXUpKKrO17Fyvoi896kL5VrudVKN2T@ZXMqJZR32W9VnYScbCXss4rTytfxd7PUYxavO8fPLBHl8OD9CeLwd/@vz962azhn4yPiQMpg3A2pqu6kHDNKsbMXR9JyIFk0Ao6J4Rpi93KBE4gpghnrkkBmH9nSkbiGUrR9YiBZ72FIpKC2d/fTi5xLD9DaWGKcgy/@4F4McznXDJdudhi@TL93HXvLlL38KWuJtR29V/Oj98cF6SldUjxhDUyRsk59UKq5jnHsL@DnGg2f@FsPcQ9l8h7N9DzMurdUfzeF7yn28)~~ ~~[221](https://tio.run/##hZDdTuMwEIXv@xSjoErxT7Y/SVElx4hF7N1eFNRUQJoLx63BUnGrtmg3jfIMPBsvRLDTosIFIEWa45OZ8XcsA7kQ5r6utz4WFOdUolI@iDXecW8ySq4vkmw0@f00ujtPbiaX8yt1fjuehsnf5OX55XnaP/0zHzt1Pb69clWPPKaWa1@bLSi6ooYWVDMZBCwnBJWK9@LYHwY4R52QrTi2Lh4SV9oK95nihu/SVdbsKLjmXaZjrtoRK7h6FP/9gorUdmtCMmLaEUKmwyPWDJHefoxpe5uz0b4144VrZVVVn2gjF0@zOcSb7Uwvfz2ctVqO9FFo4yMoWwDuKNJBBhzKih2MPM3SsLGgDCl07VdRKE@PMqLQoxBW0MxsfUHBvQFGuXWR8yxaY4G2e7rMlhg2ejdfKl@gzkFhgRgQovcsAKu1nVC@19bgUculs2ZX1Tr@mhrPegdQmQ4/k88@kPctimOkTQh7ig7Skg@cHDR5jiHke4iZ7f0phDyGkN@FkF@HqOpXqRbiflMH/94A)~~ 212 bytes
```
t(*a,*b,c){char*z="VP\225TBUIUVAaUZ@AWVDeTf@EVWhUüòéEQVüòÄRTYTüòâUU";for(size_t*p,f,n,y,i;c--;b++){f=1<<(8-*b)/3;p=z+*b++*8+*b++%f*2;f=n=*p;for(y=i=0;i<=f%4;y=fmax(y,a[*b+i++]+n%4))n/=4;for(;i--;a[*b+i]=y+n%4)n/=4;}}
```
[Try it online!](https://tio.run/##hZDPb9MwFMfFtX8A56egSrbj0K5NUSXHaEPssNuYmkyQRchx6tVSl1ZtJkijSFy5cN6Nf5G/gPLiFZUdAMnSe/6@H/5@rAO9VOXt/oUt9fK@mEO0rYpibl4uXu8rwhRnOde00Qu1YTvpJZc3o9Fk9ia@iJMzFX84PbtO3s5n5vQ8uX62iH98f/j2/PxdgvHL1ez9DOPXOPaEWW3I1u7mHyu25oaXvOZW6CAQue/TxsiTKCLTgOV0MBZrufMZ6mzqQt@wkTCylGzt1tTSyqGwkTT9UNTS3KnPpOYqxV7r@5lf9kNKy4EMXbew@MhjMZO1K7pa2z4ltisE7vVsWcGdsiWh0PQAuqtKJxlIaFpxEPI0S8dOgmbMYYin5dC8OqYhhxMO4xbcTEUUB4KTjOao0k5Da04Ci3uGAkME3f@sDFF0cMiYogJ83z56AVhvcMIQr2/B4@jLZm5X2zuWbkoPtYNRnU6fOi/@cD5CK51H7iDwFh5SdD7p0onjOULo3xAF9v4PQh8h9L8g9N8h2v1PbZbqdrsPPv0C "C (clang) – Try It Online")
p.s. Actually the code size is 221 bytes (but 212 chars) because of UNICODE chars coded in UTF-8. But **tio.run** treats it as 212 byte code...
Code size on my computer is 209 chars (218 bytes). But I couldn't replace `\225` by visible char in **tio.run** üòû
## Ungolfed code
```
// a - output array (must be zeroed), b - array of block info, c - number of blocks
// Figure codes: 2->0, 3->1, 6->2, 1->3, 5->4, 7->5, 4->6 (0,1 are L-figures, 2 is is T-figure, 3 is a line 1x4; 4,5 are zigzags; 6 is a cube 2x2)
// Vertical and horizontal positions are zero-indexed, angles = 0..3
t(*a,*b,c)
{
char*z="VP\225TBUIUVAaUZ@AWVDeTf@EVWhUüòéEQVüòÄRTYTüòâUU"; // UTF-8
//char*z="VP\225TBUIUVAaUZ@AWVDeTf@EVW\1hUüòé\26EQVüòÄRTYTüòâUU"; // 3 bytes longer (use it if you can't copy previous string correctly) :)
// Blocks
for(size_t*p,f,n,y,i;c--;b++){
f=1<<(8-*b)/3; // number of figure variants
p=z+*b++*8+*b++%f*2;
// Get top base line position (y)
f=n=*p; // figure width, TBLs and HATs
for(y=i=0;i<=f%4;
y=fmax(y,a[*b+i++]+n%4))
n/=4;
// Add heights (HATs)
for(;i--;
a[*b+i]=y+n%4)
n/=4;
}
} // 215 chars (224 bytes)
```
## Description
Let's found top base line (**TBL**) of each figure and describe it as a number of cells below TBL for each horizontal position. Also let's describe number of cells (height) above TBL (**HAT**).
E.g.:
```
________ ________
_[]_____ HAT = 1,0,0 [][][] HAT = 0,0,0 ___[][]_ HAT = 0,1,1 [][][] HAT = 0,0,0
[][][] TBL = 1,1,1 [] TBL = 2,1,1 [][] TBL = 1,1,0 [] TBL = 1,2,1
```
Let's describe TBLs and HATs for each figure and each rotation angle:
```
Width TBLs HATs
----- ------- -------
L-figures:
3 1 1 1 1 0 0 // 0°
2 1 1 0 2 // 90°
3 1 1 2 0 0 0 // 180°
2 3 1 0 0 // 270°
3 1 1 1 0 0 1 // 0°
2 1 3 0 0 // 90°
3 2 1 1 0 0 0 // 180°
2 1 1 2 0 // 270°
T-figure:
3 1 1 1 0 1 0 // 0°
2 1 2 0 1 // 90°
3 1 2 1 0 0 0 // 180°
2 2 1 1 0 // 270°
Line:
4 1 1 1 1 0 0 0 0 // 0°, 180°
1 4 0 // 90°, 270°
Zigzags:
3 1 1 0 0 1 1 // 0°, 180°
2 1 2 1 0 // 90°, 270°
3 0 1 1 1 1 0 // 0°, 180°
2 2 1 0 1 // 90°, 270°
Cube:
2 2 2 0 0 // any angle
```
Now we should encode these numbers as a sequences of 2 bits and put into an array (replacing `4 0` by `3 1` for 90° angle of "line" to fit in 2 bits – result will be the same; and decrease widths by 1).
We'll encode in order: **width** (in 2 LSB), **TBLs**, **HATs** (backward for backward loop).
E.g. `2 2 1 1 0` for 270° angle of T-figure will be encoded as `1 0 1 2 1` (last *1* is *width-1*): `0b0100011001 = 281`.
**updated 12.02:**
a) I've converted an array to a string and saved 18 chars (you can see previous [239 bytes code](https://tio.run/##hVBdj5swEHzPr1ilioRhaTA2Fci4f4TyYJzz1VLOqS45tQTx149bfKlyfWgrPnZ2Zr3MYHN7NOFxWS5JajAd0LLJnZ4THy5w7Xo9SV6XyGWDvCqwbFDIEiuBTUFvgZzzAnnB6SmxrDnJgioWdHGxco2ITVVSUzcRSz6jw4AjemXzXA1ZRh/VvG2TOk8HthfK6aCvXUpKKrO17Fyvoi896kL5VrudVKN2T@ZXMqJZR32W9VnYScbCXss4rTytfxd7PUYxavO8fPLBHl8OD9CeLwd/@vz962azhn4yPiQMpg3A2pqu6kHDNKsbMXR9JyIFk0Ao6J4Rpi93KBE4gpghnrkkBmH9nSkbiGUrR9YiBZ72FIpKC2d/fTi5xLD9DaWGKcgy/@4F4McznXDJdudhi@TL93HXvLlL38KWuJtR29V/Oj98cF6SldUjxhDUyRsk59UKq5jnHsL@DnGg2f@FsPcQ9l8h7N9DzMurdUfzeF7yn28)) :))
b) More optimization, code is shrinked by 9 chars.
*This is my last attempt (I think so, lol!)* üòÄ
[Answer]
# Common Lisp, 634 bytes
```
(let((w(make-hash-table))(r 0))(defun z(c)(or(gethash c w)0))(defun x(c v)(setf r(max r c))(setf(gethash c w)v))(defun m(s)(dolist(c s)(apply(lambda(n u p)(let*((i(let*((j'(2 2 2))(k'(3 3))(l'(2 3))(m'(3 2))(o(case n(1(list'(1 1 1 1)'(4)))(2(list j k'(1 1 2)'(3 1)))(3(list j'(1 3)'(2 1 1)k))(4(list'(2 2)))(5(list'(2 2 1)l))(6(list j l'(1 2 1)m))(7(list'(1 2 2)m)))))(setf(cdr(last o))o)))(o(nth(+ u 2)i))(b(nth u i))(s(length o))(d 0)(h 0))(dotimes(i s)(let*((w(nth i b))(g(z(+ i p)))(m(+ g w)))(when(> m d)(setf d m)(setf h(- g(-(apply'max b)w))))))(dotimes(i s)(x(-(+ s p)i 1)(+(nth i o)h)))))c))(dotimes(i r)(print(z (+ i 1))))))
```
## Verbose
```
(defun circular (list)
(setf (cdr (last list)) list))
(defun get-piece (piece-number)
(circular (case piece-number
(1 (list '(1 1 1 1)
'(4)))
(2 (list '(2 2 2)
'(3 3)
'(1 1 2)
'(3 1)))
(3 (list '(2 2 2)
'(1 3)
'(2 1 1)
'(3 3)))
(4 (list '(2 2)))
(5 (list '(2 2 1)
'(2 3)))
(6 (list '(2 2 2)
'(2 3)
'(1 2 1)
'(3 2)))
(7 (list '(1 2 2)
'(3 2))))))
(let ((world (make-hash-table))
(rightmost-column 0))
(defun get-world-column (column)
(or (gethash column world) 0))
(defun set-world-column (column value)
(setf rightmost-column (max rightmost-column column))
(setf (gethash column world) value))
(defun drop-piece (piece-number rotation position)
(let* ((piece (get-piece piece-number))
(top (nth (+ rotation 2) piece))
(bottom (nth rotation piece))
(size (length top))
(max-combined-height 0)
(contact-height 0))
(dotimes (i size)
(let* ((down-distance (nth i bottom))
(height (get-world-column (+ i position)))
(combined-height (+ height down-distance)))
(when (> combined-height max-combined-height)
(setf max-combined-height combined-height)
(setf contact-height
(- height
(- (apply #'max bottom)
down-distance))))))
(dotimes (i size)
(set-world-column (- (+ size position) i 1)
(+ (nth i top) contact-height)))))
(defun drop-pieces (pieces)
(dolist (piece pieces)
(apply #'drop-piece piece)))
(defun print-world ()
(loop for i from 1 to rightmost-column
do (print (get-world-column i)))))
(defun play-tetris (pieces)
(drop-pieces pieces)
(print-world))
```
[Test it](https://rextester.com/KTOVE5949)
The pieces are circular-lists of lists of numbers. These sub-lists each represent a side of the shape, the numbers indicating how far they are from the opposite side. They are left to right when that side is on the bottom, right to left when on top, top to bottom when on left, and bottom to top when on right. These design choices eliminate the need to write code for rotation. Unfortunately, the lack of rotation code does not seem to have made up for the lengthy shape representations, or the somewhat complicated logic I used for calculating new column heights.
Rotation is a non-negative integer. 0=0 degrees, 1=90 degrees, 2=180 degrees, 4=270 degrees
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 308 bytes
```
a=>{var o=new int[a.Max(x=>x.Item3+4)];foreach(var(i,r,p)in a){var b="\"4TqzŒ¬™!\0
\0HSš √ì\0$\n\0!“A“š
š@";int m=0,n=b[i],t=0,u=n/8+r%(n%8),v=b[u*=2]<<8|b[u-1];for(;t<v/8%8;m=m>n?m:n)n=o[p+t]+v%8-(n=(u=v>>6+3*t++)/2&1)-(n&u);for(;t-->0;)o[p+t]=m-(n=(u=v>>6+3*t)/4&1)-(n&u);}return o;}
```
[Try it online!](https://tio.run/##lZC/TsMwEMaFBAgQE906mYgimzjNX1AgdYAFAYIJJIY0Q6hS8BAHghMqoG/A1o1H4DHCg5VLUgFiAuVsf/bd/b5TBg/a4IFPj3Ix6GEuJJ0tEoTVEYT@kE0j5j8XUYZSJuJHVD1H3fNohEfMH3VPZJzYqkNCb5hmcTS4xVCKOc3oHeECRaRuvWZKX3Eu75/K1/J9vW@s9o328cVc@TbfWmwvf0zgutHqizU418vJUvuwnEAStVbLt4PWguKBKUqYQQW7DnhIJcicCd1Vsw4WHZfQAhL5FrPCXs99AamZ9UDYk71Cdzuul7DEF/vJniCCpcGdKkO16LgaFgznrPD9HdXekqpKdGvTJPC8mZMZQNN8wyNND0t@dRDd@a4fZ7HMM4FSbzz1VnQdBTZFEGa9W@HKVcZlfMZFjC9kxsVN9zTlAisUKXSI4ecG4TM2KKqCUGx/KadhkDEhpAHPqijarcOtHey/OWw3xcCFfosip1HgsA1qp8b@9DLrnNPE3ywsatBqcIvC9wNlNYb/mdYERIUyATlDTT8B "C# (Visual C# Interactive Compiler) – Try It Online")
OK - That was madness... I submitted an answer that used run-of-the-mill code-golf techniques. But when I saw what others were submitting, I realized there was a better way.
Each `(shape, rotation)` tuple is encoded into a C# string literal with duplicates removed. The encoding process captures each of these configurations in 2 bytes.
The lowest 3 bits store height and the next 3 store width. Since each of these values is never more than 4, they can be read directly from the 3 bits without any conversion. Here are some examples:
```
W H
010 010 (2x2)
010 011 (2x3)
001 100 (1x4)
011 010 (3x2)
100 001 (4x1)
```
Next, each column is stored in 3 bits. The most useful thing for me to store was the number of missing squares from the top and bottom of the column.
```
// missing squares per column
+------ 0 top / 0 bottom
|+----- 0 top / 1 bottom
||+---- 0 top / 1 bottom
|||
HHH (L-Shape) HH (Jagged-Shape)
H HH
|||
1 top / 0 bottom ----+||
0 top / 0 bottom -----+|
0 top / 1 bottom ------+
```
There is never more than 2 squares missing from the top or bottom, and there is never more than 1 square missing from both at the same time. Given this set of constraints, I came up with the following encoding:
```
// column encoding of missing squares per column
000: none missing
100: 1 missing on top
101: 2 missing on top
010: 1 missing on bottom
011: 2 missing on bottom
110: 1 missing on top and bottom
```
Since we have to account for at most 3 columns with missing squares above or below, we can encode each `(shape, rotation)` tuple in 15 bits.
```
C3 C2 C1 W H
000 000 000 010 010 - 2x2 with no missing squares
000 000 000 100 001 - 4x1 with no missing squares
100 000 100 011 010 - 3x2 with missings square on top of columns 1 and 3
000 110 000 010 011 - 2x3 with missing squares on top and bottom of column 2
```
Lastly, duplicate shapes have been removed. The follow example show how multiple `(shape,rotation)` tuples can produce duplicate outputs for the same shape at different rotations:
```
// Square
HH (0, 90, 180, 270)
HH
#-------------------------------#
// ZigZag
HH (0, 180) H (90, 270)
HH HH
H
#-------------------------------#
// T
H (0) HHH (180)
HHH H
H (90) H (270)
HH HH
H H
```
All unique outputs are determined and saved to a `byte[]` and converted to a C# string literal. In order to quickly lookup where a shape is based on `I` and `R`, the first 7 bytes of the array consist of an encoded lookup key.
Below is a link to the program that I used to compress the pieces.
[Try it online!](https://tio.run/##pVRdb9pIFH3Gv2IUaVtPIMRmadplPKnavuahUiutVMcPthnCBPBY9hBgC789e@/M2IaWVt1tkMj43HPPnPuB8/oqr@Xz8/U1KSdkKmaykFqqgqgZqedpKWrvKa1IyQuxIbLQcYKfrx6BvyPIAg6Ex3BgPoeBwd2/n/KDQeBo36j8sgYotOz/qxGeV/gPHn6g0Fb3axrB79dxRiM41Tgwz4O5B0EwIYUidZnmMG5AQkRCC5A0U0/CouGEjBytg4PwiJyJpdpY9JjcwqElm2SSFlMXwdBsXeRm87QildKpBoJdQfJXAJv5UAnrTk6g6nKtbdBzHah8dyCS2m4AVU2IWuuOi7CjqXajZRwkwztRPOg54KzJFWk@J0ulSiK1qFJjLZ1OoXKwt0GXqqFiIbkqJVSq52C7LCtVVhJLeEqXa0FmlVoR2dDhUmXlc7FcGnSmjH@y5cFgx7aRcobYtt@n3XBVvE06341p1sZRZscDtouaINuBQBtvNOJdwiV8xc09V9ur0OkczHcl9LqCtwDzDp53J2sdZTstbvGrNg46zKfMMsDUrZrNjuKInIRXanomjFO1k4Z1WcjioV0Gr2mMhKpk9JpJ1w98KcGW1G03xsY@wjUvY2memuRHSH6MxuyxbSaic1676gcbXndLwFpGxuf7zeUbdjKiBYxoxRbR5sWLBWgujgaEYa1KIJBMabjU4Vie@XmY7S69blisjgFI4kUShQxOIHYuCdROk@ZXAMHIbCKcjxJX3Ael2@DteBLQvQ9BOI/MGfFwj0j4NgSkScn2fBVF/k3/z8sFPVkDaHH8mPDMgh8rKNHPHKXmlV@bM5Jx8sN306lvdmT4Qa0LfT0yYewLTN4cZ8Q3okHCuTmECSW2gUDhoZEjYlmLM9xRQjvq6IjaoePGD66a8QMH@v02oJ/TfcgIb@q19dlCUMLURP3sj9GrG0p/FL2GaMc44C/HNuyDKp5EpYef1fu0FjfjTxrgB9eoz@pdVaU7n2Ka5aP19gH7Cg@42f/IshRTsOnKMz6GX2RpSAN/NVCU3zo7q73vq/6YXr4BZcsEH3mq7b0Oam@3N4g6T@0VF/cXFwx/fuZFZXKgQ7JwJqj31evlc0jJgezjicKS9HBmgHDy8j54Sb1er1Hso@R9AJq9driOeHGGaG7/jlmcYRYN8TSS45vrhImKf1fwMr@ThfBdiLLn538B "C# (Visual C# Interactive Compiler) – Try It Online")
Less golfed and commented code:
```
// a: input list of (i,r,p) tuples
a=>{
// create an output array that 4 more than
// the largest position. this may result
// in some trailing 0's
var o=new int[a.Max(x=>x.Item3+4)];
// iterate over each (i,r,p) tuple
foreach(var(i,r,p)in a){
// escaped string
var b="\"4Tqzª!\0\0HS Ó\0$\n\0!A @";
// declare several variables that will be used later
int m=0,n=b[i],t=0,
// u is the decoded index into b for the current (i,r) pair
u=n/8+r%(n%8),
// convert 2 bytes from b into an encoded (shape,rotation) pair
v=b[u*=2]<<8|b[u-1];
// iterate over the columns, determining the top of the current
// piece. The formula here is:
// piece_top = max(column_height + shape_height - shape_space_bottom)
for(;t<v/8%8;m=m>n?m:n)
n=o[p+t]+v%8-(n=(u=v>>6+3*t++)/2&1)-(n&u);
// iterate over the columns again, saving the the new height
// in each column. The formula here is:
// new_column_height = piece_top - shape_space_top
for(;t-->0;)
o[p+t]=m-(n=(u=v>>6+3*t)/4&1)-(n&u);
}
return o;
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 98 bytes
```
Fθ«≔§⪪§⪪”)¶∧↷"e«↨U∧0%3;D∧⁼~h⊟⁵h/₂dΦ↗(EF”2⊟ι1⊟ιη≔⊟ιζW‹Lυ⁺ζLη⊞υ⁰≔⌈Eη⁻§υ⁺ζλ﹪Iκ³εFLη§≔υ⁺ζκ⁺ε⊕÷I§ηκ³»Iυ
```
[Try it online!](https://tio.run/##bVBNT8MwDD2zX2H1lEpByte6IU4TXCYxaRLHqodqDUu0NB1tOqYhfntx6MYAkYPt92w/29mYst00pRuGl6YF8prC@@Rm0XV268kiLH2lj@R572z4gxKGj98JiZZlXCnJs7lgTPJ5xqVSPGNCSsGk4rPoGFdYhShTQiGSs4RCIpKUwrrZE5tikPBf0KT336uMJIVT5N6MdRrIk@46NH4bDOljo@s7cqJwpkyKD9Z9h1kK7IfYqjzauq/R74mhsLIeGy/n9VchF7dYNVXvGvJQdoHsEMs0sjrKff3YdRqM8v8I7S7baQpLv2l1rX3QFVn68GgPttKj/KXTxI7zKJzzMVm31oexpkdmGPI8l5inMC0o5IqCwAtjOKXAzyFmGYWsKIrh9uA@AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of [P, R, I] values, where I is from 0 to 6, R is from 0 o 3 and P is also 0-indexed. Explanation:
```
Fθ«
```
Loop over the input pieces.
```
≔§⪪§⪪”)¶∧↷"e«↨U∧0%3;D∧⁼~h⊟⁵h/₂dΦ↗(EF”2⊟ι1⊟ιη
```
Extract the description of the current piece and rotation. (See below.)
```
≔⊟ιζ
```
Extract the position.
```
W‹Lυ⁺ζLη⊞υ⁰
```
Ensure that there is enough horizontal room to place the piece.
```
≔⌈Eη⁻§υ⁺ζλ﹪Iκ³ε
```
Ensure that there is enough vertical room to place the piece.
```
FLη§≔υ⁺ζκ⁺ε⊕÷I§ηκ³
```
Calculate the new heights of the affected columns.
```
»Iυ
```
When all the pieces have been processed, output the final list of column heights on separate lines.
The compressed string represents the original string `00001923001061443168200318613441602332034173203014614341642430137`. Here the `2`s are `I` separators and the `1`s are `R` separators. The pieces therefore decode as follows:
```
P\R 0 1 2 3
0 0000 9
1 300 06 443 68
2 003 86 344 60
4 33
5 034 73
6 030 46 434 64
7 430 37
```
Missing `R` values are automatically filled cyclically by Charcoal. Each digit then maps to two values, overhang and total height, according to the following table:
```
\ O H
0 0 1
3 0 2
4 1 2
6 0 3
7 1 3
8 2 3
9 0 4
```
The overhang and total height relate to the column heights as follows: Given a piece that we want to place at a given position `e`, it may be possible to place the piece even though one of the columns is taller than `e`. The amount of spare space is given by the overhang. The new height of the column after placing the piece is simply the placed position plus the total height.
Example: Suppose we start by placing a `5` piece in column 1. Since there is nothing else yet the piece is therefore placed at position 0 and columns 1 and 3 now have height 1 while column 2 has height 2. We then want to place a `6` piece with `1` rotation in column 0. Here we can actually place this piece at position 0; although column 1 has a height of 1, the piece has an overhang of 1, and so there is enough space to place it. Column 0 ends up with a height of 2 and column 1 ends up with a height of 3.
] |
[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/132834/edit).
Closed 6 years ago.
[Improve this question](/posts/132834/edit)
### Description
There have been quite a few other challenges concerning these numbers before, and I hope this one is not among them.
The *n* th triangular number equals the sum of all natural numbers up to *n*, simple stuff. There are a [wikipedia page](https://en.wikipedia.org/wiki/Triangular_number) and an [entry at OEIS](https://oeis.org/A000217), for those who wish to inform themselves further.
Now, Gauss found out that every natural number may be expressed as a sum of three triangular numbers (these include `0`), and it is fine to have one number more than once, e.g. `0 + 1 + 1 = 2`.
### Challenge
Your task is to write a program or function, given a natural number (including `0`), prints three triangular numbers that sum up to the argument. You may print the numbers separeted by spaces, as an array, or by another method you like. However, it is **forbidden** to use any builtin functions to directly get an array, a range or any other form of collection containing a list of triangular numbers (for instance a single atom that yields the range).
### Test cases
```
9 -> 6 + 3 + 0 or 3 + 3 + 3
12 -> 6 + 6 + 0 or 6 + 3 + 3 or 10 + 1 + 1
13 -> 6 + 6 + 1
1 -> 1 + 0 + 0
0 -> 0 + 0 + 0
```
Note: If there is more than one possible combination, you may print any or all, but you must print any combination only once, eliminating all combinations that are a result of rearranging other combinations.
I'd really appreciate a try-it link and an explanation, I really love to see how you solve the problem ;)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard loopholes apply. May the shortest answer in bytes win!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
Code:
```
ÝηO3ãʒOQ}¬
```
Explanation:
```
Ý # Compute the range [0 .. input]
η # Get the prefixes
O # Sum each prefix to get the triangle numbers
3ã # Cartesian repeat 3 times
ʒ } # Keep elements that
OQ # have the same sum as the input
¬ # Retrieve the first element
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//8Nxz2/2NDy8@Nck/sPbQmv//LQE "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 99 bytes
```
from random import*
n=input()
while 1:b=sample([a*-~a/2for a in range(n+1)]*3,3);n-sum(b)or exit(b)
```
[Try it online!](https://tio.run/##FYtLDkAwFAD3TtFlW0R8VsRJxOKJ4iX62lQFG1evWs0sZuzjN0NVCIszmjmgOQK1Nc7LhHoke3oukmvDXbGynfoDtN0VH0DmLxTVYhwDhvSvq@KUlmKUdVaLjvLj1HwSMVA3@mghNB8 "Python 2 – Try It Online")
I'm pretty amazed this is shorter than `itertools` or a triple list comprehension! It (eventually) spits out a random answer every time you run it.
Two 102s:
```
n=input();r=[a*-~a/2for a in range(n+1)];print[(a,b,c)for a in r for b in r for c in r if a+b+c==n][0]
def f(n):r=[a*-~a/2for a in range(n+1)];return[(a,b,c)for a in r for b in r for c in r if a+b+c==n][0]
```
itertools looks to be 106:
```
from itertools import*;lambda n:[x for x in product([a*-~a/2for a in range(n+1)],repeat=3)if sum(x)==n][0]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
0r+\œċ3S=¥Ðf
```
[Try it online!](https://tio.run/##y0rNyan8/9@gSDvm6OQj3cbBtoeWHp6Q9v9w@6OmNUcnPdw5A0hH/v9vqWNopGNorGOoYwAA "Jelly – Try It Online")
## How it works
```
0r+\œċ3S=¥Ðf input: n
0r [0 1 ... n]
+\ cumsum
œċ3 combinations of 3 elements, with repetition
Ðf filter on
S sum
= equals n
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
⟦⟦ᵐ+ᵐj₃⊇Ṫ.+?∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZUD0cOsEbSDOetTU/Kir/eHOVXra9o86lv//b/k/CgA "Brachylog – Try It Online")
## How it works
```
⟦⟦ᵐ+ᵐj₃⊇Ṫ.+?∧ input: n
⟦ [0 1 ... n]
⟦ᵐ [[0] [0 1] [0 1 2] ... [0 1 ... n]]
+ᵐ [0 1 3 ... n(n+1)/2]
j₃ [0 1 3 ... n(n+1)/2 0 1 3 ... n(n+1)/2 0 1 3 ... n(n+1)/2]
⊇ is a superset of
Ṫ a list of three elements
. which is the output
+? which sums up to be the input
```
[Answer]
## Haskell, ~~66~~ 59 bytes
Thanks for allowing to output all solutions, that was fascinating distraction!
I was so happy to not need to extract one solution and be able to just give them all that I didn't notice the cost that comes from avoiding permuted solutions. @Lynn's remark explained that to me and let me save 7 bytes.
```
f n|l<-scanl(+)0[1..n]=[(a,b,c)|c<-l,b<-l,a<-l,a+b+c==n]!!0
```
This binds more than enough triangular numbers to `l` and checks all combinations.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~63~~ 59 bytes
```
.+
$*
^((^1|1\2)*)((1(?(4)\4))*)((1(?(6)\6))*)$
$.1 $.3 $.5
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLK05DI86wxjDGSFNLU0PDUMNew0QzxkQTzjPTjDED8VS4VPQMFVT0jIHY9P9/Sy5DIy5DYy5DLgMA "Retina – Try It Online") Link includes test cases. `(1(?(1)\1))*` is a generalised triangular number matcher, but for the first triangular number we can save a few bytes by using `^` for the initial match.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 18 bytes
```
Q:qYs3Z^t!sG=fX<Y)
```
This outputs the first result in lexicographical order.
Try it at [**MATL Online!**](https://matl.io/?code=Q%3AqYsOh3Z%5Et%21sG%3DfX%3CY%29&inputs=13&version=20.2.0)
### Explanation
```
Q % Implicitly input n. Add 1
: % Range (inclusive, 1-based): gives [1 2 ... n+1]
q % Subtract 1 (element-wise): gives [0 1 ... n]
Ys % Cumulative sum
3Z^ % Cartesian power with exponent 3. Gives a matrix where each row is a
% Cartesian tuple
t % Duplicate
!s % Sum of each row
G= % Does each entry equal the input?
f % Find indices that satisfy that condition
X< % Minimum
Y) % Use as row index into the Cartesian power matrix. Implicitly display
```
[Answer]
# [PHP](https://php.net/), 351 bytes
```
$r=[];function f($a=[],$c=0){global$argn,$t,$r;if($c<3){$n=$argn-array_sum($a);$z=array_filter($t,$f=function($v)use($n,$c){return$v>=$n/(3-$c)&&$v<=$n;});foreach($z as$v){$u=array_merge($a,[$v]);if(($w=$n-$v)<1){if(!$w){$u=array_pad($u,3,0);sort($u);if(!in_array($u,$r)){$r[]=$u;}}}else f($u,$c+1);}}}for($t=[0];$argn>$t[]=$e+=++$i;);f();print_r($r);
```
[Try it online!](https://tio.run/##TZDdaoRADIXv@xS7S1gmqFQRejPO9kFEZGrHH3BHiTMuXfHZbbQt9DIn5zucZGzHLXsf2/EFNDVWXZK3i9yAVF7I2tvKdYM91QI0CyFUKsal6YcP3R/2EFwIJDs2VFmKC1h16JEm0l/l5O9MooSn@hHqrneGxE7V6i9ewIx@MgI4rsKFjPNkYb4psK8ijVi7XmHOeJQrynogo6tWwPOkJyYX8L/hd0MNp@gwh7nAvZSAB1MRu7IEFxbO8PgHjPpTgA/TMEY5DeR4OLBzZ8vDsW@BkBHKCwVerutq@snsD@FNFSS4S1yJT1J5XMjj@hu43W4CFQTQSe4sUI7UWVeykVBu2zc "PHP – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 119 bytes
```
lambda n:[l for l in combinations_with_replacement([(t**2+t)/2for t in range(n)],3)if sum(l)==n]
from itertools import*
```
[Try it online!](https://tio.run/##FcxBCoMwEEDRfU8xyyQVSnVXyEmsSLRJHUhmwjil9PSpbv7u/frTjWloyT9bDmV5BaDHmCGxQAYkWLksSEGRaZ@/qNssseawxhJJzWjUuf6q9tafQk8hgd7RkJ26wWKC/VNMtt7TdEnCBVCjKHPeAUtlUdeq4LG69x2ko9a2Pw "Python 3 – Try It Online")
**Thanks to @WheatWizard for saving 12 bytes!**
[Answer]
# C/C++ - 197 bytes
```
#include<stdio.h>
#define f(i,l,u) for(int i=l;i<=u;i++)
int t(int n){return n>1?n+t(n-1):n;}
int c(int n){f(a,0,n)f(b,a,n)f(c,b,n)if(t(a)+t(b)+t(c)==n)return printf("%d %d %d\n",t(a),t(b),t(c));}
```
Blow by blow:
```
#include<stdio.h>
```
Needed for printf. Could be elided for certain versions of C
```
#define f(i,l,u) for(int i=l;i<=u;i++)
```
Space saving for loop.
```
int t(int n){return n>1?n+t(n-1):n;}
```
Recursive triangle evaluator.
```
int c(int n){f(a,0,n)f(b,a,n)f(c,b,n)if(t(a)+t(b)+t(c)==n)return printf("%d %d %d\n",t(a),t(b),t(c));}
```
This guy does the heavy lifting. Three nested for loops iterate a, b, c from 0 to n, note that b and c each iterate from the previous value up to n. It's not strictly necessary to trim iteration like that since the `return` coming in a minute solves the "duplicate" problem.
At the inner level, if the sum of the three triangle numbers `==` the desired value, print the triangles and return.
You can legally remove the `return` keyword and convert the return type of c to void to save a few more bytes and print all possible solutions. It is for this reason that iterations are limited, if all loops ran from `0` to `n` it would cause duplicates.
[Answer]
# Mathematica, 63 bytes
```
(t=#;#&@@Select[Table[i(i+1)/2,{i,0,t}]~Tuples~{3},Tr@#==t&])&
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 26 bytes
```
{_),[{\_@+}*]3m*_{:+}%@#=}
```
Port of my MATL answer. This is an anonymous block that expects the input on the stack and replaces it by the output array.
[**Try it online!**](https://tio.run/##S85KzP1vaPy/Ol5TJ7o6Jt5Bu1Yr1jhXK77aSrtW1UHZtvZ/XcF/AA "CJam – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 66 bytes
```
n=scan();b=expand.grid(rep(list(cumsum(0:n)),3));b[rowSums(b)==n,]
```
Brute force algorithm; reads `n` from stdin and returns a dataframe where each row is a combination of 3 triangular numbers that add up to `n`. If necessary, I can return only the first row for +4 bytes.
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOsk2taIgMS9FL70oM0WjKLVAIyezuEQjuTS3uDRXw8AqT1NTx1gTqC66KL88GCiqkaRpa5unE/vf@D8A "R – Try It Online")
[Answer]
# Java 8, 164 bytes
```
n->{int t[]=new int[n+1],i=0,j=0;for(;i<=n;)if(Math.sqrt(8*i+++1)%1==0)t[j++]=i-1;for(int a:t)for(int b:t)for(int c:t)if(a+b+c==n)return new int[]{c,b,a};return t;}
```
**Explanation:**
[Try it here.](https://tio.run/##pZDBbsMgDIbvfQouk2AkKNku6xiT9gDtpccqB0LJRpY6GXE6VVGePSNpKu3cSiB@jD/j36U@6bhuLJSH79FUum3JRjvoV4Q4QOsLbSzZTtc5sM@IoeEkwGSIDWGH1aJGZ8iWAFFkhPi9n1JCsgL7O2PA0yxyKolKlcii9lS6NwWSuYJuNH6J9scjfXl0nPOUPaRKJQz3JeeZcnE6A1NF/YrsqvN/2gQdKmmec6MUMG@x80Cun2e9ifJID3KJoxxGeem86fIqdL4YONXuQI7BPt2hd/AZ3Gp28b47t2iPou5QNOEJK6BlGJ3o0FXiw3t9bgXWF4yCMHTN2DyiG9D06Q72@Q72djRZ0GE1jH8)
```
n->{ // Method with int parameter and int-array return-type
int t[]=new int[n+1], // Create an int-array to store triangular numbers
i=0,j=0; // Two index-integers
for(;i<=n;) // Loop (1) from 0 to `n` (inclusive)
if(Math.sqrt(8*i+++1)%1==0)
// If `i` is a triangular number
t[j++]=i-1; // Add it to array `t`
// End of for-loop (1) (implicit / single-line body)
for(int a:t) // Loop (2) over the triangular numbers
for(int b:t) // Inner loop (3) over the triangular numbers
for(int c:t) // Inner loop (4) over the triangular numbers
if(a+b+c==n) // If the three triangular numbers sum equal the input
return new int[]{c,b,a};
// Return these three triangular numbers as int-array
// End of loop (4) (implicit / single-line body)
// End of loop (3) (implicit / single-line body)
// End of loop (2) (implicit / single-line body)
return t; // Return `t` if no sum is found (Java methods always need a
// return-type, and `t` is shorter than `null`;
// since we can assume the test cases will always have an answer,
// this part can be interpret as dead code)
} // End of method
```
[Answer]
# JavaScript, 108 bytes
```
r=[],i=a=b=0
while(a<=x)r.push(a=i++*i/2)
for(a=0;a<3;){
b=r[i]
if(b<=x){
x-=b
a++
console.log(b)}
else i--}
```
### Explanation
`x` represents the input
`while(a<=x)r.push(a=i++*i/2)` Creates an array of all triangular numbers up to x
The `for` loop prints the highest triangular number less than `x`, then subtracts that number from `x`, for three iterations. (basically a greedy algorithm)
[Answer]
# Pyth, 19 bytes
I am *so* out of practise with Pyth, it's untrue :/
```
hfqQsT.C*3+0msSdSQ3
```
Try it out [here](https://pyth.herokuapp.com/?code=hfqQsT.C%2a3%2B0msSdSQ3&input=13&debug=0).
```
hfqQsT.C*3+0msSdSQ3 Implicit: Q=input()
SQ Range 1-n
m Map the above over d:
Sd Range 1-d
s Sum the above
Yields [1,3,6,10,...]
+0 Prepend 0 to the above
*3 Triplicate the above
.C 3 All combinations of 3 of the above
f Filter the above over T:
sT Where sum of T
qQ Is equal to input
h Take the first element of that list
```
[Answer]
# [J](http://jsoftware.com/), 36 bytes
```
((2!1+$@]#:0({I.@,)=)]+/+/~)2!1+i.,]
```
[Try it online!](https://tio.run/##y/r/P03B1kpBQ8NI0VBbxSFW2cpAo9pTz0FH01YzVltfW79OEySTqacTy8WVmpyRr6BhnaapZKAQq2CpYGikYGisYKhg8P8/AA "J – Try It Online")
[Answer]
# Ruby ~~61~~ ~~57~~ 55 bytes
Inspired by Lynn's Python [answer](https://codegolf.stackexchange.com/a/132852/65905). It generates random triplets until the desired sum is achieved:
```
->n{x=Array.new 3{(0..rand(n+1)).sum}until x&.sum==n;x}
```
It requires Ruby 2.4. In Ruby 2.3 and older, it's a syntax error, and `Range#sum` isn't defined. This longer version (64 bytes) is needed for Ruby 2.3:
```
->n{x=Array.new(3){(a=rand(n+1))*-~a/2}until x&.inject(:+)==n;x}
```
Here's a small test:
```
f=->n{x=Array.new 3{(0..rand(n+1)).sum}until x&.sum==n;x}
# => #<Proc:0x000000018aa5d8@(pry):6 (lambda)>
f[0]
# => [0, 0, 0]
f[13]
# => [0, 3, 10]
f[5]
# => [3, 1, 1]
f[27]
# => [21, 3, 3]
f[27]
# => [0, 21, 6]
f[300]
# => [3, 21, 276]
```
[Try it online with Ruby 2.3!](https://tio.run/##KypNqvyfZvtf1y6vusLWsagosVIvL7Vcw1izWiPRtigxL0UjT9tQU1NLty5R36i2NK8kM0ehQk0vMy8rNblEw0pb09Y2z7qi9n@BQlq0Qaw1iDKEUkYQ2sg89j8A "Ruby – Try It Online")
[Answer]
# Javascript (ES6), 108 bytes - fixed
Takes an integer as an input, outputs an array `[a, b, c]` containing a sorted list of triangle numbers `a + b + c = x`, where `a` is the largest triangle number less than or equal to the input, and `b` is the largest triangle number less than or equal to the input minus `a`.
```
x=>{t=[0],t.f=t.forEach,i=j=k=0;for(;j<x;t[i]=j+=i++);t.f(a=>t.f(b=>t.f(c=>a+b+c==x?k=[a,b,c]:0)));return k}
```
## Explanation
```
x=>{
t=[0], // initialize an array of triangle numbers
t.f=t.forEach, // copy forEach method into t.f,
// saves a net of 4 bytes
i=j=k=0;
for(;j<x;t[i]=j+=i++); // populate t with all triangle numbers that
// we could possibly need
t.f( // loop over all t
a=>t.f( // loop over all t
b=>t.f( // loop over all t
c=>a+b+c==x?k=[a,b,c]:0 // if a+b+c = x, set k = [a,b,c], else noop
// using a ternary here saves 1 byte vs
// if statement
// iterating over t like this will find all
// permutations of [a,b,c] that match, but
// we will only return the last one found,
// which happens to be sorted in descending order
)
)
);
return k
}
```
```
const F = x=>{t=[0],t.f=t.forEach,i=j=k=0;for(;j<x;t[i]=j+=i++);t.f(a=>t.f(b=>t.f(c=>a+b+c==x?k=[a,b,c]:0)));return k};
$('#output').hide();
$('#run').click(() => {
const x = parseInt($('#input').val(), 10);
if (x >= 0) {
$('#input').val(x);
const values = F(x);
$('#values').text(values.join(', '));
$('#output').show();
}
else {
$('#output').hide();
alert('You must enter a positive integer');
}
});
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter a value: <input type="text" id="input" />
<br />
<button id="run">Get triangle numbers</button>
<br />
<span id="output">Triangle numbers are: <span id="values"></span></span>
```
] |
[Question]
[
Write a program that terminates without an error.
If any single byte is substituted by any other byte the program should output
```
CORRUPTED
```
* Do not read your source code from a file
* Your program should not produce any other output
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins.
**Edit:** removed "NOT CORRUPTED" requirement
[Answer]
# [A Pear Tree](http://esolangs.org/wiki/A_Pear_Tree), 76 bytes
```
$@='NOT ';print"$@CORRUPTED"__DATA__ =®®”print"$@CORRUPTED"__DATA__ =®®”Ê®›~
```
This program contains a few stray octets that aren't valid UTF-8. As such, it's shown as it looks in Windows-1252. (By default, if A Pear Tree sees a non-ASCII octet in a string literal or the like it treats it as an opaque object and doesn't try to understand it beyond being aware of what its character code is; this behaviour can be changed via an encoding declaration but the program doesn't have one. So the program is logically in "unspecified ASCII-compatible character set". All the non-ASCII octets are in comments anyway, so it doesn't really matter.)
## Explanation
A Pear Tree checksums the program, looking for the longest substring that has a CRC-32 of `00000000`. (If there's a tie, it picks the octetbetically first.) Then the program gets rotated to put it at the start. Finally, the program gets interpreted as a language that's almost a superset of Perl, defining a few things that are undefined in Perl to work the same way as in Python (and with a few minor changes, e.g. `print` prints a final newline in A Pear Tree but not in Perl). This mechanism (and the language as a whole) was designed for [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'") and [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") problems; this isn't the former, but it's definitely the latter.
In this program, we have two notable substrings that CRC-32 to `00000000`; the entire program does, and so does `print"$@CORRUPTED"__DATA__ =®®` by itself (which appears twice). As such, if the program is uncorrupted, it'll set `$@` to `NOT` and then print it followed by `CORRUPTED`. If the program is corrupted, then the CRC-32 of the program as a whole will fail to match, but one of the shorter sections will remain uncorrupted. Whichever one is rotated to the start of the program will just print `CORRUPTED`, as `$@` will be the null string.
Once the string's been printed, `__DATA__` is used to prevent the rest of the program running. (It crosses my mind writing this that `__END__` could be used instead, which would clearly save two bytes. But I may as well post this version now, because I've spent a bunch of time verifying it, and a modified version would have to be re-verified due to the CRC changes; and I haven't put a huge amount of effort into golfing the "payload" yet, so I want to see if anyone has other improvements in the comments that I can incorporate at the same time. Note that `#` doesn't work in the situation where a character is corrupted into a newline.)
You might be wondering how I managed to control the CRC-32 of my code in the first place. This is a fairly simple mathematical trick based on the way that CRC-32 is defined: you take the CRC-32 of the code, write it in little-endian order (the reverse of the byte order that's normally used by CRC-32 calculation programs), and XOR with `9D 0A D9 6D`. Then you append that to the program, and you'll have a program with a CRC-32 of 0. (As the simplest example possible, the null string has a CRC-32 of 0, thus `9D 0A D9 6D` also has a CRC-32 of 0.)
## Verification
A Pear Tree can handle most sorts of mutations, but I'm assuming "changed" means "replaced with an arbitrary octet". It's theoretically possible (although unlikely in a program this short) that there could be a hash collision somewhere that lead to the wrong program running, so I had to check via brute force that all possible octet substitutions would leave the program working correctly. Here's the verification script (written in Perl) that I used:
```
use 5.010;
use IPC::Run qw/run/;
use warnings;
use strict;
undef $/;
$| = 1;
my $program = <>;
for my $x (0 .. (length $program - 1)) {
for my $a (0 .. 255) {
print "$x $a \r";
my $p = $program;
substr $p, $x, 1, chr $a;
$p eq $program and next;
alarm 4;
run [$^X, '-M5.010', 'apeartree.pl'], '<', \$p, '>', \my $out, '2>', \my $err;
if ($out ne "CORRUPTED\n") {
print "Failed mutating $x to $a\n";
print "Output: {{{\n$out}}}\n";
print "Errors: {{{\n$err}}}\n";
exit;
}
}
}
say "All OK! ";
```
] |
[Question]
[
I noticed that my car's odometer was at 101101 when I got to work today. Which is a cool number because it's binary (and a palindrome, but that's not important). Now, I want to know when the next time I'll have a binary odometer reading. I can't read the odometer while I'm driving, because that would be dangerous, so it'll have to be binary either when I get to work or get home.
There's really bad traffic on the way to and from my office, so I have to take a different route each day.
For the purposes of this challenge, a day is a round trip and starts with my commute to work.
You'll need to take the initial reading of the odometer and a 10 element sequence representing the amount of miles each way. This sequence should be repeated until you get to a binary odometer reading. You should then output the number of days it takes until we get to a binary reading.
Both the milage for the route and the odometer reading will be positive integers. The count of days will either be `x` or `x.5`, so your output of the day count needs to support floating point for half days. If the day count is an integer, you don't need to output the `.0`. The odometer will always eventually reach a binary state.
Any form of input/output is acceptable and [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?lq=1) are disallowed.
Test cases:
```
101101, [27, 27, 27, 27, 27, 27, 27, 27, 27, 27] == 165.0
1, [13, 25, 3, 4, 10, 8, 92, 3, 3, 100] == 22.5
2, [2, 3, 1, 2, 7, 6, 10, 92, 3, 7] == 2.0
```
[Answer]
# Javascript, ~~68~~ ~~63~~ ~~61~~ ~~60~~ 52 bytes
5 bytes off thanks [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions). ~~2~~ ~~3~~ 11!! bytes off thanks [@NotthatCharles](https://codegolf.stackexchange.com/users/13950/not-that-charles).
```
f=(i,a,m=0)=>/[^01]/.test(i+=a[m++%10])?f(i,a,m):m/2
```
[Test here.](http://vihan.org/p/esfiddle/?code=f%3D(i%2Ca%2Cm%3D0)%3D%3E%2F%5B%5E01%5D%2F.test(i%2B%3Da%5Bm%2B%2B%2510%5D)%3Ff(i%2Ca%2Cm)%3Am%2F2%0A%0A%0AF%3D(i%2Ca)%3D%3Ealert(f(i%2Ca))%0A%0AF(101101%2C%5B27%2C27%2C27%2C27%2C27%2C27%2C27%2C27%2C27%2C27%5D)%0AF(1%2C%5B13%2C25%2C3%2C4%2C10%2C8%2C92%2C3%2C3%2C100%5D)%0AF(2%2C%5B2%2C3%2C1%2C2%2C7%2C6%2C10%2C92%2C3%2C7%5D))
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~29~~ ~~26~~ 25 bytes
```
`tvyyYs+V50<!A~]xx1Mf1)2/
```
Input format is
```
[27; 27; 27; 27; 27; 27; 27; 27; 27; 27]
101101
```
*EDIT (June 10, 2016): The following link replaces `v` by `&v` (**26 bytes**) to adapt to changes in the language*
[**Try it online!**](http://matl.tryitonline.net/#code=YHQmdnl5WXMrVjUwPCFBfl14eDFNZjEpMi8&input=WzI3OyAyNzsgMjc7IDI3OyAyNzsgMjc7IDI3OyAyNzsgMjc7IDI3XQoxMDExMDEK)
```
` ] % do---while loop. Exit loop when top of stack is falsy
t % duplicate. Takes first input (array) first time
v % concat vertically (doubles length of array)
yy % copy top two. Takes second input (todasy's value) first time
Ys % cumulative sum of (repeated) miles each way
+ % add to today's value
V % convert each number to a string
50<!A % true for strings than only contain '01 ' (ASCII less than 50)
~ % negate. This is the loop condition
xx % delete stack contents
1M % push again array that tells which strings only contain '01 '
f1) % pick index of first true entry
2/ % divide by 2
```
[Answer]
# Jelly, ~~22~~ ~~17~~ 16 bytes
```
RịS+³DṀ=1
Ṡç1#SH
```
[Try it online!](http://jelly.tryitonline.net/#code=UuG7i1MrwrNE4bmAPTEK4bmgw6cxI1NI&input=&args=MQ+WzEzLCAyNSwgMywgNCwgMTAsIDgsIDkyLCAzLCAzLCAxMDBd)
### How it works
```
Ṡç1#SH Main link. Left input: n (initial reading). Right input: A (distances)
Ṡ Compute the sign of n. Since n is positive, this returns 1.
ç Apply the helper link to 1, 2, 3, ... until...
1# one match is found. Return the match in an array.
S Compute the sum of the array. This yields the match.
H Halve the result.
RịS+³DṀ=1 Helper link. Left argument: k (integer). Right argument: A (distances)
R Range; yield [1, ..., k].
ị Retrieve the elements of A at those indices.
Indexing in modular in Jelly.
S Compute the sum of the retrieved distances.
+³ Add n (left input) to the sum.
D Convert the sum to base 10.
Ṁ Get the maximum digit.
=1 Compare it with 1.
```
[Answer]
## Lua, 108 Bytes
First time using the repeat..until loop in a codegolf!
```
function f(o,t)i=0repeat i,o=i+1,(o+t[i%#t+1]).."."o=o:sub(1,o:find("%.")-1)until tonumber(o,2)print(i/2)end
```
### Ungolfed
```
function f(o,t) -- o can either be a number or a string, t is a table
-- call it like f(2,{27,14,5...})
i=0 -- initialise the travel count
repeat -- proceed like a do..while in C
i,o=i+1,(o+t[i%#t+1]).."."-- increment i, and add t[i] to the odometer
o=o:sub(1,o:find("%.")-1) -- remove the decimal part of the odometer
until tonumber(o,2) -- tries to convert o from binary to decimal
-- return nil (and repeat the loop) if it can't
print(i/2) -- print i/2 which is the number of days for i travels
end
```
After the first loop, `o` will have a decimal part because of `tonumber`, I had to remove it... And to add it for the first case, that's why I concatenate it with a `"."`.
[Answer]
# Java, 112 ~~miles~~ bytes
```
float c(int r,int[]d){float y=0;for(int i=0;;i%=d.length){y+=.5;r+=d[i++];if((""+r).matches("[01]+"))return y;}}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 31 bytes
Code:
```
0IE\[²vs>sy+D§'aT«-""Qi\2/?}Ž}Ž
```
~~Somehow, the code doesn't stop running (and I can't figure out why)~~. Apparently I forgot that there are three loops going on instead of 2. So it would still get into an infinite loop...
[Try it online!](http://05ab1e.tryitonline.net/#code=MElFXFvCsnZzPnN5K0TCpydhVMKrLSIiUWlcMi8_fcW9fcW9&input=MQpbMTMsIDI1LCAzLCA0LCAxMCwgOCwgOTIsIDMsIDMsIDEwMF0)
[Answer]
## PowerShell, ~~84~~ ~~73~~ ~~67~~ ~~59~~ 57 bytes
```
param($a,$b)do{$a+=$b[$i++%10]}until(!+($a-replace1))$i/2
```
Takes input `$a` and `$b`, expecting `$b` to be an explicit array of mileages (e.g., `.\binary-car.ps1 1 @(13,25,3,4,10,8,92,3,3,100)`). We then enter a `do`/`until` loop. Each iteration, we increment `$a` with the mileage in `$b` at position `$i++ % 10` so that we continually loop through the array. This will start at zero since for the first loop the `$i` is not initialized, and so evaluates to `$null`, which equates to `0` in this context, and it's only *after* that evaluation that the `++` occurs.
Then, the `until` statement checks if our number is only `0` and `1` by first `-replace`ing all `1` with nothing, casting that back as an integer with `+`, and then taking the Boolean-not with `!`. If it evaluates true, we'll finish the loop, output `$i / 2`, and terminate the program.
**Explanation for the loop conditional --** In PowerShell, any non-zero integer is `$true`, and any non-empty string is also `$true`. For example, `231145` (an integer) will change to `"2345"` (a string) after the `-replace`, which will integer-cast as `2345` (an integer), the `!` of which is `$false`. However, `101101` (an integer) will change to `"00"` (a string) which will cast as `0` (an integer), the `!` of which is `$true`. If we didn't have the `+`, the `"00"` will `!` to `$false` since it's a non-empty string.
Edit - Saved 11 bytes by swapping equality-on-length for strictly-zero
Edit 2 -- Saved another 6 bytes by realizing that `$b.count` will always be `10` ...
Edit 3 -- Saved another 8 bytes by using do/until instead of for
Edit 4 -- If the object being `-replace`d is an integer value, don't need quotes, saving another 2 bytes
[Answer]
# Ruby, 58
Nothing special. Just a cycle...
```
->s,a,i=0{a.cycle{|e|i+=0.5;break i if/[2-9]/!~'%d'%s+=e}}
```
[Answer]
# Mathematica, 92 bytes
```
(y=1;x=#+#2[[1]];While[!StringMatchQ[ToString@x,{"0","1"}..],x+=#2[[y++~Mod~10+1]]];N@y/2)&
```
Yep.
Input is the odometer and a list of times. Output is the day count.
[Answer]
# PHP, ~~102~~ 98
```
function f($i,$s){while(1)foreach($s as$v){$d+=.5;$i+=$v;if(preg_match('/^[01]+$/',$i))return$d;}}
```
Ungolfed Version
```
function f($i,$s) {
$d = 0;
while(true) {
foreach($s as $v) {
$d += 0.5;
$i+=$v;
if(preg_match('/^[0|1]+$/', $i)) {
return $d;
}
}
}
}
```
PHP Notices can be removed of extra cost of 4 characters `$d = 0;` in golfed version.
Example
```
$i = 101101;
$s = [27, 27, 27, 27, 27, 27, 27, 27, 27, 27];
f($i,$s);
```
[Answer]
# Pyth, ~~36~~ ~~32~~ 30 bytes
```
Jvz.V0=J+J@QbI<ssM{`J2KbB;chK2
```
[Try it here!](http://pyth.herokuapp.com/?code=Jvz.V0%3DJ%2BJ%40QbI%3CssM%7B%60J2KbB%3BchK2&input=1%0A%5B13%2C+25%2C+3%2C+4%2C+10%2C+8%2C+92%2C+3%2C+3%2C+100%5D&test_suite=1&test_suite_input=101101%0A%5B27%2C+27%2C+27%2C+27%2C+27%2C+27%2C+27%2C+27%2C+27%2C+27%5D%0A1%0A%5B13%2C+25%2C+3%2C+4%2C+10%2C+8%2C+92%2C+3%2C+3%2C+100%5D%0A2%0A%5B2%2C+3%2C+1%2C+2%2C+7%2C+6%2C+10%2C+92%2C+3%2C+7%5D&debug=0&input_size=2)
### Explanation
```
Jvz.V0=J+J@QbI<ssM{`J2KbB;chK2 # Q = input sequence
Jvz # assign starting value to J
.V0 # Start an infinite loop iterating over b starting at 0
=J # Set J to
+J # the sum of J
@Qb # and the value at Q[b % len(q)]
I # if
< 2 # lower than 2
{`J # Remove duplicate digits from J
ssM # Map the remaning digits back to integers and sum them
KbB # if the above evals to true, save b to K and leave the loop
; # End loop body
hK # Increment K because we missed one loop increment
c 2 # and divide it by 2 to get the days
```
[Answer]
# C Sharp, 180.
Dear lord C# is long.
```
using System.Text.RegularExpressions;class a{double c(int a,int[]b){var d=0.5;a+=b[0];var i=1;while(!Regex.IsMatch(a.ToString(),"^[01]+$")){a+=b[i];i+=1;i=i%10;d+=0.5;}return d;}}
```
] |
[Question]
[
Write code to determine who wins a four-card trick in a game of [Spades](http://en.wikipedia.org/wiki/Spades). Fewest bytes wins.
The input is a string that lists the four cards played in sequence like `TH QC JH 2H` (Ten of Hearts, Queen of Clubs, Jack of Hearts, Two of Hearts). A card is given by two characters: a suit from `CDHS` and a value from `23456789TJQKA`. You are guaranteed that the input is valid and the cards are distinct.
You should output a number 1, 2, 3, or 4 for the winner of the trick. In the example `TH QC JH 2H`, the jack of hearts wins the trick, so you should output 3.
Your input and output must be exactly as described, except trailing newlines are optional.
Here are the Spades rules for winning a trick. The winning card is the highest card of the four, with some caveats. Spades is the *trump suit*, so any spade outranks any non-spade. The suit of the first card played is the *lead suit*, and only cards of that suit or spades are eligible to win the trick. Cards of the same suit are compared by their values, which are given in increasing order as `23456789TJQKA`.
Test cases:
```
TH QC JH 2H
3
KC 5S QS 9C
3
QD 2D TD 5D
1
9S 5D AD QS
4
3D 4C 3H JH
1
9S 4S TS JS
4
5H 9H 2C AD
2
5S 4C 3H QD
1
2H 2S KH AH
2
```
[Answer]
# Pyth, ~~28~~ ~~27~~ 25 bytes
```
J"KTAZ"hxcz)eo_XN+@z1JJcz
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=J%22KTAZ%22hxcz)eo_XN%2B%40z1JJcz&input=5S+4C+3H+QD&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=Fz.zJ%22KTAZ%22hxcz)eo_XN%2B%40z1JJcz&input=ignore+first+line%0ATH+QC+JH+2H%0AKC+5S+QS+9C%0AQD+2D+TD+5D%0A9S+5D+AD+QS%0A3D+4C+3H+JH%0A9S+4S+TS+JS%0A5H+9H+2C+AD%0A5S+4C+3H+QD%0A&debug=0) (first 4 chars are the test suite construct)
Thanks to @isaacg for a trick, which saved 2 chars.
The main idea is to modify chars of each hand such a in way, that the winning hand has the maximal value.
The values of the hands `23456789TJQKA` is already nearly sorted. I just have to replace `T` with `A`, `K` with `T` and `A` with `Z`, resulting with `23456789AJQSZ`.
The order of suits `CDHS`are for the most not really important. `S`, the most powerful suit, which is already the maximal value. Important is to give the suit of the first hand the second most powerful value. So I translate this suit into `K`.
All hands also have to be read reverse, since the suit is more powerful than the value.
```
implicit: z = input string
J"KTAZ" J = "KTAZ"
o cz orders the hands N of split(z) by:
_ the reversed of
XN+@z1JJ N, where the values z[1]+J are replaced by J
e last element (winning hand)
xcz) index of the winning hand in split(z)
h + 1
```
[Answer]
# CJam, ~~34~~ 33 bytes
```
lS/_{)2$0='S+\#\"TQKA"_$er+}$W>#)
```
**Algorithm**
The logic is simple. I have a custom sort going on, in which I first give priority to the second character representing the suit. In this, Spades gets the highest priority and then the first thrown suite. Rest all are `-1`. Then I sort on the first character with swapping of `T` with `A` and `Q` with `K` to have lexical sorting.
**Code explanation**
First off, lets see what is the lexical order of the face values of the cards:
```
"23456789TJQKA"$
```
>
> 23456789AJKQT
>
>
>
So, all numbers are at correct position. `J` is also at correct position. We need to swap `K` and `Q` and `J` and `A` to get lexical order.
```
lS/_{)2$0='S+\#\"TQKA"_$er+}$W>#)
lS/ "Read an input line and split on spaces";
_{ }$ "Copy the array and sort it using this custom logic";
) "Take off the last character of each hand.";
2$0= "Get the suit of the first hand";
'S+ "Add Spades suit to it";
\# "Get the index of the current hand suit.
1 for Spades, 0 for first hand suit, -1 otherwise";
\ "Put face value of this hand on top of stack";
"TQKA" "Put string TQKA on stack";
_$ "Copy and sort. This essentially reverses the string
TQKA to form AKQT. This is 1 byte shorter than _W%";
er+ "Swap T with A and K with Q and add to the
suit index calculated previously";
"After the above tuple, sorting will automatically
convert the tuple to string and sort lexically";
W> "Get the array containing only the last element";
#) "Get the index of this hand in original set and
increment to convert it to 1 based";
```
[Try it online here](http://cjam.aditsu.net/#code=lS%2F_%7B)2%24s1%3D'S%2B%5C%23%5C%22TQKA%22_%24er%2B%7D%24W%3E%23)&input=5H%209H%202C%20AD)
[Answer]
# JavaScript (ES6), 112
Scan the list and return the position of the highest value found.
Run snippet to test (in Firefox)
```
F=t=>t.split(' ').map((c,i)=>(n='23456789TJQKA'.search(c[0])+(c[1]>'H'?40:c[1]==t[1]&&20))>m&&(m=n,r=i+1),m=0)|r
C.innerHTML=['TH QC JH 2H','KC 5S QS 9C','QD 2D TD 5D','9S 5D AD QS','3D 4C 3H JH','9S 4S TS JS','5H 9H 2C AD','5S 4C 3H QD'].map(h=>h+' -> '+F(h)).join('\n')
```
```
<pre id=C></pre>
```
[Answer]
# Perl, 73 bytes
```
#!perl -pl
/\B./;s/$&/P/g;y/TKA/IRT/;$_=reverse;@a=sort split;/$a[-1]/;$_=4-"@-"/3
```
Try [me](http://ideone.com/DF2wkP).
Converts the card names so the game value order follows the alphabetical order, then picks the highest by sorting and looks for it in the original string for position.
[Answer]
# Ruby, 59+2=61
With command-line flags `na`, run
```
p (1..4).max_by{|i|$F[i-1].tr($_[1]+'SJQKA','a-z').reverse}
```
[Answer]
# J, 47 bytes
```
1+[:(i.>./)_3+/\16!@-]i.~'SXAKQJT9876543'1}~1&{
```
Usage:
```
(1+[:(i.>./)_3+/\16!@-]i.~'SXAKQJT9876543'1}~1&{) 'TH QC 9S 8S'
3
```
Method:
* For every input char we assign a value based in its position in the `'S[second char of input]AKQJT9876543'` string. Non-found chars get the value `last position + 1` implicitly. Further characters have much less value (`value=(16-position)!`).
* Compute the sum for the 3 input-char triplet and one duplet (e.g. `TH_` `QC_` `9S_`and `8S`).
* Choose the 1-based index of the maximal value.
(J unfortunately can't compare chars or strings directly. It can only check for their equality which ruled out some other approaches for this challenge.)
[Try it online here.](http://tryj.tk/)
[Answer]
**C#, 237**
```
using System;namespace S{class P{static void Main(string[] a){var V="23456789TJQKA";int x=0;int y=0;var z=a[0][1];for(int i=0;i<4;i++){int q=V.IndexOf(a[i][0])+2;var w=a[i][1];q*=w==z?1:w=='S'?9:0;if(q>y){x=i;y=q;}}Console.Write(x+1);}}}
```
How it works:
Iterate each hand to calculate the "value" of the card.. store the highest valued index.
A cards value is determined as the rank of the card multiplied by 0 if it is not a spade or the opening suit, 1 if it is the opening suit and 9 if it is a spade but not the opening suit.
(9 choosen b/c 2\*9=18> A=14 & 9 is a single char)
[Answer]
# Pyth, 36 33 bytes
```
KczdhxKeo,x,ehK\SeNXhN"TKA""AYZ"K
```
Fairly straightforward approach, uses sorting with a custom key function, then finds the index of the highest value.
[Answer]
# Pyth, 31 bytes
```
hxczdeo}\SNo}@z1Zox"TJQKA"hNScz
```
[Try it here.](https://pyth.herokuapp.com/?code=hxczdeo%7D%5CSNo%7D%40z1Zox%22TJQKA%22hNScz&input=5S%204C%203H%20QD&debug=0)
How it works:
The proper way to read this procedure is back to front. The procedure sorts the desired card to the end of the list, then pulls it out and finds its index in the original list.
* `cz`: This generates the list of card strings. `c`, chop, is normally a binary function (arity 2), but when called on only one input, serves as the `.split()` string method.
* `S`: This applies the normal sorting behavior, which sorts lower numbered cards before higher ones.
* `ox"TJQKA"hN`: This orders the cards by the index (`x`) in the string `"TJQKA"` of the first letter of the card (`hN`). For cards with numbers, the first letter is not found, giving the result `-1`. Since Pyth's sorting function is stable, the numbered cards' order is not affected.
* `o}@z1Z`: Next we order by whether the suit of the first card played (`@z1`) is in the card in question. Since `True` sorts behind `False`, this sends cards of the lead suit to the back.
* `o}\SN`: This is the same as the sort before, but it sorts on whether the letter `S` is in the card, sending spades to the back.
* `hxczde`: This extracts the last card sorted this way (`e`), finds its index in the list of cards (`xczd`) and increments by 1 (`h`), giving the desired player location.
[Answer]
# Python, 172 bytes
```
l=input().split(" ")
s="23456789TJQKA"
h=l[0]
for c in l:
if c[1] not in [h[1],"S"]:
continue
if s.index(h[0])>s.index(c[0]):
continue
h=c
print(l.index(h)+1)
```
There wasn't a Python answer here, so I fixed that :)
Simply compares the cards, discarding them if they are of a different suit to the current highest (and not a spade), then if they are of a lower value. At the end, simply get the highest card, and add 1 to its index.
] |
[Question]
[
To shuffle a string \$s\$, Alice applies the following algorithm:
* She takes the ASCII code of each character, e.g. `"GOLF"` → \$[ 71, 79, 76, 70 ]\$
* She sorts this list from lowest to highest: \$[ 70, 71, 76, 79 ]\$
* She reduces each value modulo the length of the string (4 in this case), leading to the list \$A = [ 2, 3, 0, 3 ]\$
* For each character at position \$n\$ (0-indexed) in the original string, she exchanges the \$n\$-th character with the \$A[n]\$-th character:
+ exchange \$s[0]\$ with \$s[2]\$: `"GOLF"` is turned into `"LOGF"`
+ exchange \$s[1]\$ with \$s[3]\$: `"LOGF"` is turned into `"LFGO"`
+ exchange \$s[2]\$ with \$s[0]\$: `"LFGO"` is turned into `"GFLO"`
+ exchange \$s[3]\$ with \$s[3]\$: this one doesn't change anything
She then sends the shuffled string `"GFLO"` to Bob.
## Task
Your task is to help Bob understand Alice's message by applying the reverse algorithm: given a shuffled string as input, output the original string.
The input string is guaranteed to contain only printable ASCII characters (codes 32 to 126).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins.
## Test cases
**Input:**
```
AAA
GFLO
ron'llckR'o
Br b,!mn oGognooid
eAies a.turel vee.st hnrw .v
```
**Output:**
```
AAA
GOLF
Rock'n'roll
Good morning, Bob!
As we travel the universe...
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
tStn\Q!tfhP!"t@)@P(
```
[Try it online!](https://tio.run/##y00syfn/vyS4JC8mULEkLSNAUanEQdMhQOP/f/VUx8zUYoVEvZLSotQchbLUVL3iEoWMvKJyBb0ydQA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L8kuCQvJlCxJC0jQFGpxEHTIUDjf6xLyH91R0dHdS51dzcffyBVlJ@nrp6Tk5wdpK6eD@Q7FSkk6Sjm5inku@en5@XnZ6YABVMdM1OLFRL1SkqLUnMUylJT9YpLFDLyisoV9MrUAQ).
### Explanation
The reverse algorithm is the same as the direct one just applying the swapping steps in reverse order.
```
t % Input (implicit): string s of length N (row vector of chars of size 1×N)
S % Sort (by ASCII codes)
tn % Duplicate, number of elements: gives N
\ % Modulo (of ASCII codes), element-wise. Gives a 1×N numeric vector
Q % Add 1 (because MATL uses 1-based indexing)
! % Transpose into a column vector, of size N×1
tf % Duplicate, find. Gives the N×1 column vector [1; 2; ...; N]
h % Concatenate horizontally. Gives an N×2 matrix
P % Flip vertically (for N=1 flips horizontally, but that still works)
! % Transpose into a 2×N matrix
!" % For each column
t % Duplicate the (partially processed) string: (*)
@ % Push current column: 2×1 vector of the form [s(k); k]: (**)
) % Read elements (**) from string (*). Gives 2×1 char vector: (***)
@P % Push current column, flip: gives [k; s(k)]: (****)
( % Write (***) into (*) at positions (****)
% End (implicit)
% Display (implicit)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
≔⪪S¹θW⌊⁻θυF№θι⊞υιWυ«≔℅⊟υι≔§θιη§≔θι§θLυ§≔θLυη»↑θ
```
[Try it online!](https://tio.run/##bY@/DoIwEMZneYpza5M6uOqEDoZEIwnxARCQXlKuUFo1MT57BVFkcLjcn9933@UymZpMp8r7sG2xJJbUCi2LqHY2sQapZFzAsouGr4ObRFUAOyBh5ao@u5Y1AhznHC7awFY7sv0EOcSulcz15bjoODyC2efS0eRIqWKxrjvAB@EXhjaivLgPVgLkD02JgEm3L6i0srf6Kx7x4PYM4u47y1an@v2b9xsDZzGvCPROl6Q15oFfXNUL "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪S¹θ
```
Split the input string into characters.
```
W⌊⁻θυF№θι⊞υι
```
Sort them in ascending order.
```
Wυ«
```
Process the sorted characters.
```
≔℅⊟υι
```
Get the ASCII code of the next character in reverse order.
```
≔§θιη§≔θι§θLυ§≔θLυη
```
Swap the character at the current index with the character at that position (cyclically reduced modulo the length of the string).
```
»↑θ
```
Output the final character array vertically so it prints as a string.
[Answer]
# [J](http://jsoftware.com/), 34 32 31 bytes
```
<(C.>)/@,~i.@#;&~./@,.#|3 u:/:~
```
[Try it online!](https://tio.run/##RYnNCoJAGEX3PsUtoS/BPoN20w9Ogm6EwDcoG9OyGRh/2oSvbq5yceCee57jkqnAUYDgYwsxsWFEWRqPh3XEJy8I/aHi0N2vBp42u98dOhGIYfQcR@WlQQGSUtJfkji9zGaNJqrr/JURmfk@W9z8xVvDJOahjanuc1OyUg2u3HZW1eiV4qZFqe0H3JMz/gA "J – Try It Online")
Uses [Luis Mendo's insight](https://codegolf.stackexchange.com/a/239790/15469) "The reverse algorithm is the same as the direct one just applying the swapping steps in reverse order."
After that, we turn the problem into a single fold of all the swaps, using J's "Permute" verb `C.`, which can implement swaps directly. The only hiccup is that it doesn't allow self swaps, so we have to turn cases like `3 3 C. 'GOLF'` into `3 C. 'GOLF'`, which we do by call unique `&~.` while creating the swap pair.
[Answer]
# [R](https://www.r-project.org/), 104 bytes
```
function(s){i=sort(v<-utf8ToInt(s))%%(n=nchar(s))+1
for(j in n:1)v[rev(w)]=v[w<-c(j,i[j])]
intToUtf8(v)}
```
[Try it online!](https://tio.run/##RY2xCoMwEEB3vyIIwoVWwa0UM3TsbidxELlgRC5wuZxD6bdbO3V8b3iPj0xpyd5v6A6faZYQCZJ9B5ciC2hXZ/G3Pj5JTm2rCsjRvEz8o0tb@MiwmkCG7q3VgVFht6PTYe/qGdZrGNbRjkUg6ePrLIHaz/8JJT4CJjM1khk3o4hNErMQ76bR0hbHFw "R – Try It Online")
[Answer]
# Python3, 155 bytes:
```
def g(s,x,l):
for i in range(l):h=s[(j:=(l-1-i))];s[j]=s[x[j]];s[x[j]]=h;
def f(s):
s=[*s];g(s,[ord(i)%(t:=len(s))for i in sorted(s)],t);return''.join(s)
```
[Try it online!](https://tio.run/##VY0xT8MwFIT3/IpHJWQbpZEQC0rkIR3aBQmJNcpQyEvi1LwXPZtSfn1wGKoyne670938E0emp@dZlqXDHgYd8kvuTZlBzwIOHIEcaUCd2GhDo6fSar993Dpj2io0U5vgJclq/tSOVbZO9TqsM8E2D6Gt1uGGpdPO3OtYWo@UcnM9CSwRu4TaPJpKMH4JKVVM7NbeMoujqHut6rpWxmRXf9i/vN6CjTAp7z9Ob4o3t3wn8J7ffRLwgQdidt2/GGuHAY5F@kUPZ8QiRBhJvqE4p@LyCw)
[Answer]
# [Scala](http://www.scala-lang.org/), 101 92 bytes
```
s=>(s.sorted.map(_%s.size).zipWithIndex:\s){case((c,i),b)=>b.updated(c,b(i))updated(i,b(c))}
```
Saved 9 bytes thanks to @user.
Straightforward monadic-style implementation:
* `(s.sorted.map(_%s.size).zipWithIndex:\s)` creates the array "`A`" and traverses its elements (incl. corresponding index) from right to left via folding (`:\` = `foldRight`, accumulator initialized by input string `s`)
* `{case((c,i),b)=>b.updated(c,b(i))updated(i,b(c))}` updates the accumulator value `b` by swapping `b(i)` and `b(c)`. This part is quite verbose, since there is no `b.swap(c,i)` built-in.
[Try it online!](https://tio.run/##bVJha9swEP2eX3EVGbHA1Q8Ic8AtbRh0BNyNfSkM2T4nWhXJk2Q3NMtvz652bJMxfxC6d@8e757sC6nl2ea/sAjw3fhdU1UaAQ8BTekhrWs4zgBKrKAZukt4Dk6ZLSSr8Xb2ySrywlsXsBR7WUc/P1Gp3pGLd1X/UGH3xZR4WL54fiykxygqYsXjnCerXDR1KWmOoDxSnA@lorLg/HQGaKUmU3Jfa/SQwDP@jsgWAEvTlMHtqr/EPbZ@fNr04Hrz9DigzpqF1sVrtrB9M7PF68IsnNV64Nw5yOObvQG7tltjrSovOtaWsLfO0LIx3Nn8ZpjAVJEjKULjUEOLKHyAnXFvINqLMQ9vCMHJlghhhxSkatF5FEIwEuEzOirruqABokvKZTwlXnL4fDvu39GmXkovl0z1OM@Jd4LjB7mbqOmlgjZ9bgCeMXa5wp/5UVUQ/aOZXBlg95sse7j/xgC1R2APWbbJ2GmUGJhLuPrmAz4SJ1GI8FDTj0fyS5hP@H@psgiN1PxDfn5ldGTTQhS@U/VX6bbKdHgXwux0/gs "Scala – Try It Online")
[Answer]
# Python 3, 143 bytes
```
def u(i):
m=len(i);p=list;i=p(i);a=[x%m for x in sorted(p(map(ord,i)))]
for l in range(1-m,1):i[-l],i[a[-l]]=i[a[-l]],i[-l]
return''.join(i)
```
I found it easiest to transform the input to a list and then back again, but I wouldn't be surprised if there is a more compact way to accomplish this.
[Try it online!](https://tio.run/##VY0xa8MwEIV3/4proEgCxRC6lAQN7pAsgUJX48GtL8mlkk6c5TT99a4daEmne@@7D176zieOT89JxrHDAwyazLqA4DzGKW6S89TnDbk0t9bV18cABxa4AkXoWTJ2OunQJs3SWTLGNMVN8LMgbTyiXi2DXZk11UvfWKrb@TbuN9gbL0AwDxKVKs9M8/aYhGLWg1ZVVSljir@@2@5f78FCOCrvPz7fFC/u@YvAu30IEXjHx8hM3b83VoQ9tOW0ix4uiGWf4RTlC8rLJI4/ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 30 bytes
```
:C₌sL:‹£%Ṙ(:¥n"İn¥"$Z÷→÷Ȧ←÷Ȧ&‹
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI6Q+KCjHNMOuKAucKjJeG5mCg6wqVuXCLEsG7CpVwiJFrDt+KGksO3yKbihpDDt8imJuKAuSIsIiIsImVBaWVzIGEudHVyZWwgdmVlLnN0IGhucncgLnYiXQ==)
What a mess of 30 bytes. Probably gonna be outgolfed by better stack control.
## Explained
```
:C₌sL:‹£%Ṙ(:¥n"İn¥"$Z÷→÷Ȧ←÷Ȧ&‹
: # Push two copies of the input string
C # and get the character code of each letter in the second copy
₌sL # push that sorted and it's length (parallel apply)
:‹£ # place the length of the string - 1 into the register - this will keep track of the nth character we're getting
%Ṙ # reverse the list of each character code modulo the length of the string - this gets us our modulo indices (A[n])
( # for each index n in that list:
: # The top of the stack is the first copy of the input string from earlier - we want to preserve this because we're modifying it with assignment, so make another copy to extract characters from
¥n"İ # that string's (register)th and nth character
n¥" # push the list [n, register]
$Z # and then push zipped([n, register], [(register)th char, nth char]) - this allows us to create a list of [index to assign, character to assign]
÷→ # Place the last pair into the ghost variable for a bit, as we need to focus on the first pair of assignment.
÷Ȧ # string[n] = (register)th char
←÷Ȧ # string[register] = nth char
&‹ # Increment the register to swap the next character position.
# After all that, the final string is implicitly printed.
```
[Answer]
# [Lua](https://www.lua.org/), ~~231~~ 220 bytes
```
s=...t={}s:gsub(".",load('table.insert(t,(...):byte())u=s.sub'))table.sort(t)for i=#t,1,-1 do a=t[i]%#t+1 i,j=math.min(a,i),math.max(a,i)s=u(s,1,i-1)..u(s,j,j)..u(s,i+1,j-1)..(i~=j and u(s,i,i)..u(s,j+1)or"")end print(s)
```
[Try it online!](https://tio.run/##LY5NasMwEIWvMjiEaLAyoG1Ai56jdCFjtRnhyEUzShtKe3VVcbJ7P9@Dt9TQmngiUv/zK6cPqZMZaLDLGmZz0DAtkThLLGrUms7habppNIjVC3X6gPigZL0z@L4WYL9T6@zRwbxC8PrKb/udjg7YJn8JeqYLZxMso3248L058dVIH/LRIdFdJ5ueikdn05Yb/vMJQp5hy/vuyY4O1zIMGHv1WTirEWytxReOAoG0lrjANfarCudcvoCu/w "Lua – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 82 bytes
```
lL∧L⟦₅R⁰∧?oạ%ᵐ↙L;R⁰z↔I∧?g,I↰ˡ↙1c
g;R⁰z{[[X,[A,B]],R]∧(A R∧X∋↙B.∨B R∧X∋↙A.∨X∋↙R.)}ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P8fnUcdyn0fzlz1qag161LgByLPPf7hroerDrRMetc30sQYJVj1qm@IJkknX8XzUtuH0QqCMYTJXOkSyOjo6QifaUccpNlYnKBaoTMNRIQhIRTzq6AYqdNJ71LHCCVnEESQCZQfpadYCrfr/X8mpSCFJRzE3TyHfPT89Lz8/M0XpfxQA "Brachylog – Try It Online")
I couldn't find any reasonable way to swap 2 elements by index in Brachylog, so the second line is a verbose and ugly implementation of that.
Since Brachylog is prolog based, I could have applied the transform forwards and let it calculate the inverse automatically, but it was easier to just reverse the list.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ç{Dg%ā<øRvDyèyRǝ
```
[Try it online](https://tio.run/##yy9OTMpM/f//cHu1S7rqkUabwzuCylwqD6@oDDo@9/9/dzcffwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2ly//D7dUu6apHGm0O7wgqc6k8vKIy6Pjc/7U6/x0dHbnc3Xz8uYry89RzcpKzg9TzuZyKFJJ0FHPzFPLd89Pz8vMzU7hSHTNTixUS9UpKi1JzFMpSU/WKSxQy8orKFfTKAA).
The shuffle method described in the challenge description would be this:
```
Ç{Dg%ā<øvDyèyRǝ
```
[Try it online](https://tio.run/##yy9OTMpM/f//cHu1S7rqkUabwzvKXCoPr6gMOj73/393fx83AA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2ly//D7dUu6apHGm0O7yhzqTy8ojLo@Nz/tTr/HR0dudz9fdy4gvKTs9Xz1Ivyc3K43PPzUxRy84vyMvPSdRSc8pMUuRyLFcpTFUqKEstScxRKMlIVSvMyy1KLilP19PQA).
And the top program simply reverses the list of indices to unshuffle.
We can add a trailing `=` after the programs above to see the intermediate steps: [try it online](https://tio.run/##yy9OTMpM/f//cHu1S7rqkUabwzvKXCoPr6gMOj7XlqvW5dA2ey4kuSCE5P//7v4@bgA).
**Explanation:**
```
Ç # Convert the (implicit) input to a list of codepoint-integers
{ # Sort them from lowest to highest
Dg # Duplicate, pop and push the length
% # Modulo the codepoints by this length
ā # Push a list in the range [1,length] (without popping)
< # Decrease each by 1 to make the range [0,length)
ø # Create pairs of the two lists
R # Reverse this list of pairs
v # Loop over each pair of indices `y` of this list:
D # Duplicate the current string
# (which is the implicit input in the first iteration)
yè # Pop one string, and get the character-pair at indices `y`
yRǝ # Insert them at back in the string at the reversed indices-pair `y`
# (after the loop, the resulting string is output implicitly)
```
The swapping portion is taken from [my answer here](https://codegolf.stackexchange.com/a/236367/52210).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
->s{r=0;s.bytes.sort.reverse.map{|c|s[c],s[r]=s[r-=1],s[c%=s.size]};s}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664usjWwLpYL6myJLVYrzi/qESvKLUstag4VS83saC6JrmmODo5Vqc4uijWFkjo2hqCOMmqtkDFmVWpsbXWxbX/CxTSopWK8vPUc3KSs4PU85Vi/wMA "Ruby – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~36~~ 34 bytes
```
{x{x[y]:x@|y;x}/|+(!#x;(#x)!x@<x)}
```
[Try it online!](https://ngn.codeberg.page/k#eJx9kEGLwjAQhe/zK1JdqLLawnrY3WYP1oOyIAhei2CtSVsaM26S1hR1f/um60UQvEyYmczjfY9HZ3u2SbuJ7PTSUnsNL68Dr2/poG+Hnp1+2eEVwETnl6T9VREnhFi6xYoOtjwtBbW0pWq4uYJJenEc9+h/3XTtYr5cuX6xWs5vA4XSFyKr1j66+Rqzype+QiFu65kiu5F3kAQXmEvEct9dI+7JAZUsZT4iM9x5t88sLpkmaWBqxQRpGAu0IYVUJxI0nQlNTowYlTZuawpGalk2TGkWBIETAAihMOaoozDMcM9yFNwJpFnFbFakMmdBhofwp2balCh1+Db5fP+YhJoJPq6lLmrOhXM01ka5RwN8y2NtIgBHDx043MHCIxk88w+wqs2dnAsQ7tKCx0zgGS/AH1Xwm4k=)
As with the other answers, applies the swaps in the opposite order.
* `(...;(#x)!x@<x)` mod the sorted ASCII character codes by the length of the input
* `(!#x;...)` generate indices from 0..len(input)
* `|+` transpose this pair of lists into a list of pairs, then reverse its order
* `x{...}/` set up a fold, seeded with `x` (the original input), and this list of pairs indicating the order of the swaps
+ `{x[y]:x@|y;x}` swap the pair of elements of this current iteration, returning the modified list
] |
[Question]
[
We can roll up the natural numbers in a rectangular spiral:
```
17--16--15--14--13
| |
18 5---4---3 12
| | | |
19 6 1---2 11
| | |
20 7---8---9--10
|
21--22--23--24--25
```
But now that we have them on a rectangular grid we can unwind the spiral in a different order, e.g. going clockwise, starting north:
```
17 16--15--14--13
| | |
18 5 4---3 12
| | | | |
19 6 1 2 11
| | | |
20 7---8---9 10
| |
21--22--23--24--25
```
The resulting sequence is clearly a permutation of the natural numbers:
```
1, 4, 3, 2, 9, 8, 7, 6, 5, 16, 15, 14, 13, 12, 11, 10, 25, 24, 23, 22, 21, 20, 19, 18, 17, ...
```
Your task is to compute this sequence. ([OEIS A020703](https://oeis.org/A020703), but spoiler warning: it contains another interesting definition and several formulae that you might want to figure out yourself.)
**Fun fact:** all 8 possible unwinding orders have their own OEIS entry.
## The Challenge
Given a positive integer `n`, return the `n`th element of the above sequence.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test Cases
```
1 1
2 4
3 3
4 2
5 9
6 8
7 7
8 6
9 5
100 82
111 111
633 669
1000 986
5000 4942
9802 10000
10000 9802
```
For a complete list up to and including `n = 11131` [see the b-file on OEIS](https://oeis.org/A020703/b020703.txt).
[Answer]
# Japt, ~~20~~ ~~19~~ 16 bytes
```
V=U¬c)²-V *2-U+2
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=MStVrGMgsi0oVS0oVawtMSBjILI=&input=MTAwMDA=)
Based on the observation that
>
> F(N) = ceil(N^.5) \* (ceil(N^.5)-1) - N + 2
>
>
>
Or, rather, that
>
> F(N) = the first square greater than or equal to N, minus its square root, minus N, plus 2.
>
>
>
I don't know if this explanation is on the OEIS page, as I haven't looked at it yet.
[Answer]
# Jelly, ~~11~~ 10 bytes
```
’ƽð²+ḷ‘Ḥ_
```
Another Jelly answer on my phone.
```
’ƽð²+ḷ‘Ḥ_ A monadic hook:
’ƽ Helper link. Input: n
’ n-1
ƽ Atop integer square root. Call this m.
ð Start a new dyadic link. Inputs: m, n
²+ḷ‘Ḥ_ Main link:
²+ḷ Square m, add it to itself,
‘ and add one.
Ḥ Double the result
_ and subtract n.
```
Try it [here](http://jelly.tryitonline.net/#code=4oCZw4bCvcOwwrIr4bi34bikKzJf&input=&args=MTAw).
[Answer]
# Julia, 28 bytes
```
n->2((m=isqrt(n-1))^2+m+1)-n
```
This is a lambda function that accepts an integer and returns an integer. To call it, assign it to a variable.
We define *m* to be the largest integer such that *m*2 ≤ *n*-1, i.e. the integer square root of *n*-1 (`isqrt`). We can then simplify the OEIS expression 2 (*m* + 1) *m* - *n* + 2 down to simply 2 (*m*2 + *m* + 1) - *n*.
[Try it online](http://goo.gl/rwF4hG)
[Answer]
# CJam, 14 bytes
```
qi_(mQ7Ybb2*\-
```
Using Alex's approach: `2*(m^2+m+1)-n` where `m = isqrt(n-1)`.
[Answer]
## ES7, ~~31~~ ~~28~~ 26 bytes
```
n=>(m=--n**.5|0)*++m*2-~-n
```
I had independently discovered Alex's formula but I can't prove it because I wasn't near a computer at the time.
Edit: Saved 3 bytes partly thanks to @ETHproductions. Saved a further 2 bytes.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~25~~ ~~19~~ 14 bytes
```
{2⊥⍨3⍴⌊√⍵-1}-⊢
```
-6 bytes from Adám.
-5 bytes from Bubbler.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qHeuQqJGnqatkZZGWk5@fpFGcWFRiUaerqGmprahpha6mG6ettH/aqNHXUsf9a4wftS75VFP16OOWY96t@oa1uo@6lr0P@1R24RHvX2Pupof9a4BKji03vhR28RHfVODg5yBZIiHZ/D/NAVDrjQFIyA2BmITIDYFYjMQbWBgAKQsLQxAsoZAngEA "APL (Dyalog Extended) – Try It Online")
A direct implementation of the last function mentioned on the OEIS page:
\$a(n)=2×\Big(\big\lfloor\sqrt{n-1}\big\rfloor+1\Big)×\big\lfloor\sqrt{n-1}\big\rfloor-n+2\$
## Explanation:
```
{(2-⍵)+2×(1+⌊√⍵-1)×⌊√⍵-1} ⍵ → n
⌊√⍵-1 floor of root of n-1
(1+⌊√⍵-1)× times 1 + floor of root of n-1
2× times 2
(2-⍵) plus 2-n
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qHeuQqJGnqatkZZGWk5@fpFGcWFRiUaerqGmprahpha6mG6ettH/ag0j3Ue9WzW1jQ5P1zDUftTT9ahjFlAAqODwdCRe7f@0R20THvX2PepqftS75lHvlkPrjR@1TXzUNzU4yBlIhnh4Bv9PUzDkSlMwAmJjIDYBYlMgNgNiQwMgAAA "APL (Dyalog Extended) – Try It Online")
[Answer]
# Pyth, 21 bytes
```
K2-h+^.E@QKK^t.E@QKKQ
```
[Try it online!](http://pyth.herokuapp.com/?code=K2-h%2B%5E.E%40QKK%5Et.E%40QKKQ&input=8&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A100%0A111%0A633%0A1000%0A5000%0A9802%0A10000&debug=0)
Nothing fancy going on. Same method as in the JAPT answer.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes
```
-1$r$[I*I+I+1=*2-?=.
```
This uses the same technique as pretty much all other answers.
### Explanation
```
-1 § Build the expression Input - 1
$r § Square root of Input - 1
$[I § Unify I with the floor of this square root
*I+I+1 § Build the expression I * I + I + 1
=*2-? § Evaluate the previous expression (say, M) and build the expression
§ M * 2 - Input
=. § Unify the output with the evaluation of M * 2 - Input
```
A midly interesting fact about this answer is that it is easier and shorter to use `=` rather than parentheses.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~16~~ 13 bytes
```
qX^Y[tQ*Q2*G-
```
Based on [Lynn's CJam answer](https://codegolf.stackexchange.com/a/70805/36398).
[**Try it online!**](http://matl.tryitonline.net/#code=cVhea3RRKlEyKkct&input=MTAw) (`Y[` has been replaced by `k` according to changes in the language)
```
q % input n. Subtract 1
X^ % square root
Y[ % floor
tQ % duplicate and add 1
* % multiply
Q % add 1
2* % multiply by 2
G- % subtract n
```
---
This uses a different approach than other answers (**16 bytes**):
```
6Y3iQG2\+YLt!G=)
```
It explicitly generates the two spiral matrices (actually, vertically flipped versions of them, but that doesn't affect the output). The first one is
```
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23 24 25
```
and the second one traces the modified path:
```
25 10 11 12 13
24 9 2 3 14
23 8 1 4 15
22 7 6 5 16
21 20 19 18 17
```
To find the `n`-th number of the sequence it suffices to find `n` in the second matrix and pick the corresponding number in the first. The matrices need to be big enough so that `n` appears, and should have *odd* size so that the origin (number `1`) is in the same position in both.
**[Try it online](http://matl.tryitonline.net/#code=UUcyXCsgNlkzWUx0IUc9KQ&input=MTAw)** too! (`6Y3` has been moved according to changes in the language)
```
6Y3 % 'spiral' string
i % input n
QG2\+ % round up to an odd number large enough
YL % generate spiral matrix of that size: first matrix
t! % duplicate and transpose: second matrix
G= % logical index that locates n in the second matrix
) % use that index into first matrix
```
] |
[Question]
[
Write a program that translates ASCII text to [braille](https://en.wikipedia.org/wiki/Braille) output. Requirements:
* Input may come from stdin, command line, or some other external input source.
* Output should be recognisable as braille, the form of output is up to you. An example would be `o` for a raised dot and `.` for a non-raised dot. Textual pattern representation such as `1-3-4` is not acceptable. Long line wrapping is not required.
* Only the 26 alphabet characters and space are required for a minimal solution. All input characters not supported by your solution should be ignored.
Scoring is by number of characters in the source code. Penalties and bonuses are:
* +50 penalty for using [Unicode braille characters](https://en.wikipedia.org/wiki/Braille_Patterns) as output.
* -50 bonus for supporting capitals, numbers, and punctuation.
* -200 bonus for supporting ligatures and one-letter contractions from [English (Grade-2) Braille](https://en.wikipedia.org/wiki/English_Braille). (Will make this a separate challenge since it's quite a different problem.)
Sample invocation and output (minimal solution):
```
$ braille Hello world
o . o . o . o . o . . . . o o . o . o . o o
o o . o o . o . . o . . o o . o o o o . . o
. . . . o . o . o . . . . o o . o . o . . .
```
[Answer]
## Python, 162
```
l=map((" a c,bif/e d:hjg'k m;lsp o n!rtq%12s. w -u x v z y"%'').find,raw_input().lower())
for i in 1,4,16:print' '.join('.o.o ..oo'[(n&i*3)/i::4]for n in l)
```
Currently supports lowercase letters and some punctuation, but it's still a work in progress.
Example:
```
$ python braille.py
Hello, world!
o . o . o . o . o . . . . . . o o . o . o . o o . .
o o . o o . o . . o o . . . o o . o o o o . . o o o
. . . . o . o . o . . . . . . o o . o . o . . . o .
```
[Answer]
# Python - 90 75 + 50 = 125
Use lower case letters.
```
for l in input():
a=ord(l)-96
if a<0:a=0
print("⠀⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵"[a],end="")
```
One-liner (thanks to ɐɔıʇǝɥʇuʎs)
```
for l in input():print("⠀⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵"[max(0,ord(l)-96)],end="")
```
[Answer]
# BBC Basic 103 ASCII characters or 92 tokens
```
A$="HXIKJY[ZQShxikjy{zqsl|Wmon"FORK=1TO26A=ASC(MID$(A$,K))VDU23,K+96,A AND9;0,A/2AND9;0,A/4AND9;:NEXT
```
Possibly not quite what the OP intended, this redefines the font for the lowercase characters. `VDU 23,n,a,b,c,d,e,f,g,h` assigns an 8x8 bitmap to character n, consisting of eight bytes. Following a parameter with a semicolon instead of a comma causes it to be treated as a two-byte little-endian number.
The braille patterns for letters `a` through `z` are stored in A$, according to the following bit pattern. This is extracted by masks with 9=binary`1001` and rightshifts (division by 2 and 4 is used as standard BBC basic has no shift operator.)
```
8 1
16 2
32 4
```
**Ungolfed code**
```
A$="HXIKJY[ZQShxikjy{zqsl|Wmon"
FORK=1TO26
A=ASC(MID$(A$,K))
VDU23,K+96,A AND9;0,A/2AND9;0,A/4AND9;
NEXT
```
**Usage example**
This is done in screen mode 6 for clarity (type MODE6 as soon as you open the command line emulator.)
Actually, after running the code, any lowercase letters (including keyboard input) appear in Braille.

Emulator at <http://bbcbasic.co.uk/bbcwin/bbcwin.html>.
See also this similar answer of mine: <https://codegolf.stackexchange.com/a/28869/15599>
[Answer]
# C, 269
```
#define C char
#define O*p++=(*t&1)*65+46;*t>>=1;
main(int c,C**v){C b[99]={1,5,3,11,9,7,15,13,6,14},o[99],*q=o,*p=v[1],*t;while(c=*p++)*q++=c=='w'?46:c>='a'&&c<='z'?c-='a'+(c>'w'),b[c%10]|(c>9)*16|(c>19)*32:0;for(c=3;c;c--){p=b;for(t=o;t<q;t++){O;O*p++=32;}puts(b);}}
```
This implementation requires that its argument, if it contains spaces, must be quoted:
```
# braille "hello world"
```
[Answer]
# Bash + coreutils
### Minimal solution - lowercase only, 83 (33 unicode chars + 50 penalty):
```
tr a-z ⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠭⠽⠵⠺
```
### Capitals, numbers and punctuation, 120 (120 unicode chars + 50 penalty - 50 bonus):
```
a=⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠭⠽⠵⠺
sed 's/\([0-9]\)/⠼&/g;s/\([A-Z]\)/⠠&/g'|tr ",;':\-⎖.!“?”()/a-zA-Z1-90" ⠂⠆⠄⠒⠤⠨⠲⠖⠦⠦⠴⠶⠶⠌$a$a$a
```
Example output:
```
$ echo {A..Z} {a..z} {0..9} ".,;:" | ./braille.sh
⠠⠁ ⠠⠃ ⠠⠉ ⠠⠙ ⠠⠑ ⠠⠋ ⠠⠛ ⠠⠓ ⠠⠊ ⠠⠚ ⠠⠅ ⠠⠇ ⠠⠍ ⠠⠝ ⠠⠕ ⠠⠏ ⠠⠟ ⠠⠗ ⠠⠎ ⠠⠞ ⠠⠥ ⠠⠧ ⠠⠭ ⠠⠽ ⠠⠵ ⠠⠺ ⠁ ⠃ ⠉ ⠙ ⠑ ⠋ ⠛ ⠓ ⠊ ⠚ ⠅ ⠇ ⠍ ⠝ ⠕ ⠏ ⠟ ⠗ ⠎ ⠞ ⠥ ⠧ ⠭ ⠽ ⠵ ⠺ ⠼⠚ ⠼⠁ ⠼⠃ ⠼⠉ ⠼⠙ ⠼⠑ ⠼⠋ ⠼⠛ ⠼⠓ ⠼⠊ ⠲⠂⠆⠒
$
```
[Answer]
# CJam - 51
```
q{i32%"@`hptdx|lX\bjrvfz~nZ^ck]swg"=i2b1>2/}%zSf*N*
```
Try it at <http://cjam.aditsu.net/>
Example input:
```
braille is strange
```
Example output:
```
10 10 10 01 10 10 10 00 01 01 00 01 01 10 10 11 11 10
10 11 00 10 10 10 01 00 10 10 00 10 11 11 00 01 11 01
00 10 00 00 10 10 00 00 00 10 00 10 10 10 00 10 00 00
```
It only supports lowercase letters and space. Other characters are mapped to supported characters (in particular uppercase letters to lowercase).
**Explanation:**
Braille characters are encoded using 1 for a raised dot and 0 for a non-raised dot, left to right and top to bottom. This gives 6 base-2 digits; a 1 is prepended to avoid stripping leading zeros, then the number is converted to base 10 then to the corresponding ASCII character.
Example: t -> ⠞ -> 01/11/10 -> 1011110 -> 94 -> ^
The program converts back each character to the triplet of pairs of bits (such as `[[0 1][1 1][1 0]]`) obtaining a matrix of bit pairs. The matrix is then transposed and separators are added (spaces within rows, newlines between rows).
`q` reads the input into a string = array of characters
`{…}%` applies the block to each character
`i32%` gets the ASCII code mod 32 (space->0, a->1, b->2, z->26)
`"@`hptdx|lX\bjrvfz~nZ^ck]swg"` is a string containing the braille characters encoded as explained before
`=` gets the corresponding encoded braille character from the string
`i2b` gets the ASCII code then converts to base 2 (obtaining an array of 7 digits)
`1>` removes the leading 1 digit
`2/` splits the array into (3) pairs
`z` transposes the matrix
`Sf*` joins each row with spaces
`N*` joins the rows with newlines
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 81 + 50 - 50 = 81 bytes
```
(i,'⠚⠁⠃⠉⠙⠑⠋⠛⠓⠊⠲⠂⠒⠆⠦⠖ ',⍨i←'⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵')[(⎕A,⎕C⎕A,⎕D,'.,:;?! ')⍳⍞]
```
Try it online uses Dyalog 17, so `⎕C` is not supported in it. The alternative, `819⌶` (suggested by [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima)), has been used for demonstration purposes.
Braille symbols taken from [dcode.](https://www.dcode.fr/braille-alphabet)
## Explanation
```
⍳⍞ Find index of each character of the input in the string..
(⎕A,⎕C⎕A,⎕D,'.,:;?! ') A-Z, a-z, 0-9, and punctuation.
[ ] Pick characters from those indices..
(i,'⠚⠁⠃⠉⠙⠑⠋⠛⠓⠊....⠧⠺⠭⠽⠵') In the braille representation of the Alphanumeric and punctuation characters.
(last line is shortened to take up less space.)
```
[Try it online!](https://tio.run/##fY49TgJRAIR7TvGoHiQPI/gDaGFMLLyBhaEg2cVs8sIaY6GlGkDFRdGgUSNOg9DYaLQw8TLfRdbVAzjFzNfMZJq7vhQcNn28UwoP9sN2EAYppz3TSguRs@gBHaETdIbu0RD10SO6QefoDR2ja9RFL@jWWEcyi@he2X972WoH9VCCntAIXaJndIcGaIwmaIq@0Cv6Rh@2uF1gMFp3tXKdi88/zGzD2Tm3srqWN7ZI8k4ybvy@T1u5zShTLsvQ@9hsxXs@yJtyZWFxablaq8//AA "APL (Dyalog Extended) – Try It Online")
[Answer]
# PHP, 331
```
<?php $d=split("/",gzinflate(base64_decode("NYzBDQBACIM26o3G/r+LRf2QYAOZe4SCLKgU7A9lEWVOzrQVrAiwghWhLKLMyZlawTTGMIYxPg==")));$d[-65]="......";$i=str_split(preg_replace("/[^a-z ]/","",trim(fgets(STDIN))));$o=["","",""];$S="substr";foreach($i as $c){$v=ord($c)-97;for($x=0;$x<3;$x++)$o[$x].=$S($d[$v],$x*2,2)." ";}echo join($o,"\n");
```
No bonuses for now.
[Answer]
# JavaScript - 286
```
w=prompt().split('');for(i=0;i<w.length;i++){z=w[i];o="o",p=".";b=[1,5,3,11,9,7,15,13,6,14];e=[c="",1,3];g=z.charCodeAt(0)-97;if(g>22)g--;f=e[g/10|0];d=b[g%10];if(g==22){d=14;f=2;}c+=d&1?o:p;c+=d&2?o:p;c+="\n";c+=d&4?o:p;c+=d&8?o:p;c+="\n";c+=f&1?o:p;c+=f&2?"o\n":".\n";console.log(c);}
```
First attempt. No bonuses.
[Answer]
# C, ~~249~~ 244
```
#define B?111:46
#define P(a,b)printf("%c%c ",a B,b B):
a,i;main(int c,char**v){for(char*p;p=v[1],a<3;puts(""),++a)while(i=*p++)i==32?P(0,0)i/97&122/i?c=(i+=(i==119)*17-97-(i>119))%10,a?a^1?P(i/10%3,i/20)P(c>4|c==1,c/3&&c%3-2)P(c<8,5*c/8%2)0;}
```
Input is a command-line argument, which must be escaped or quoted if the string contains spaces. Supported characters are lowercase letters and space. Unsupported characters are silently dropped.
**Edit:** Shaved 5 bytes by simplifying a condition
[Answer]
## perl, 195+2-50=147
**This handles capital, number and punctuation, without relying on unicode** (195 bytes + 2 bytes (for `-pl`) - 50 bonus)
```
~s/([A-Z])/|$1/g,~s/(\d)/#$1/g,tr/1-90/a-ij/;for$i(1,2,4){map{for$j(1,8){$s.=index(" a,b'k;l^cif/msp_e:h*o!r_djg_ntq|_?_-u(v_____x____._)z\"___w_#y",l$
"}$_=$s
```
With indentation:
```
~s/([A-Z])/|$1/g,
~s/(\d)/#$1/g,
tr/1-90/a-ij/;
for$i(1,2,4){
map{
for$j(1,8){
$s.=index(" a,b'k;l^cif/msp_e:h*o!r_djg_ntq|_?_-u(v_____x____._)z\"___w_#y",lc($_))&$j*$i?o:_
}
$s.=_
}split//;
$s.="
"}
$_=$s
```
Sample output
```
perl -pl brail.pl
Hello, 99!
___o__o__o__o__o_________o__o__o__o____
___oo__o_o__o___o_o______o_o___o_o__oo_
_o_______o__o__o________oo____oo____o__
```
[Answer]
# Javascript ES6 - 282 309 297 283 270 - 50 = 232 259 233 220 bytes
This would be shorter, but checking for capital letters *hurt*.
```
f=_=>{z='toLowerCase';k=(a,b)=>a%b>~-b/2?1:0;t=(a,b)=>k(a,b)+`${k(a,b/2)} `;b=c=d='';for(v of _){v==v[z]()?0:(b+=0,c+=0,v=v[z](d+=1));$=` ,'-";9015283467@./+^_>#i[s!jwt)a*kue:ozb<lvh\\r(c%mxd?nyf$p&g]q=`.search(v);b+=t($,64);c+=t($,16);d+=t($,4)}alert(`${b}
${c}
${d}`)}
```
**EDIT:** Thanks to mbomb007 for saving me two bytes - unfortunately, I found that a little bit of previous golfing had ruined everything, so I had to add 27 characters back in.
**EDIT:** Aaand 12 bytes saved by moving the spaces.
**EDIT:** Realized it was silly to output as characters, and saved quite a few bytes. I also saved a few characters by swapping k=(a,b)=>a%(2\*b)>b-1?1:0 for k=(a,b)=>a%b>~-b/2?1:0.
] |
[Question]
[
Choose Your Own Adventure books are a form of interactive literature where the reader must
make decisions that affect the outcome of the story. At certain points in the story, the
reader has multiple options that can be chosen, each sending the reader to a different page
in the book.
For example, in a fantasy setting, one might have to decide on page 14 whether to venture
into a mysterious cave by "jumping" to page 22, or to explore the nearby forest by jumping
to page 8. These "jumps" can be expressed as pairs of page numbers, like so:
```
14 22
14 8
```
In most cases, there are many endings to the story but only a few good ones. The goal is to
navigate the story to reach a good ending.
**Task:**
Given a list of "jumps" for a given book, your task is to determine a route that will lead
to a specific ending. Since this is fairly easy, the true challenge is to do it in as few
characters as possible.
This is **code golf**.
**Sample input (where 1 is the start and 100 is the goal):**
```
1 10
10 5
10 13
5 12
5 19
13 15
12 20
15 100
```
**Sample output:**
```
1 10 13 15 100
```
**Sample input:**
```
15 2
1 4
2 12
1 9
3 1
1 15
9 3
12 64
4 10
2 6
80 100
5 10
6 24
12 80
6 150
120 9
150 120
```
**Sample output:**
```
1 15 2 12 80 100
```
**Notes:**
* The list of jumps will be input by the user, either from a file or stdin. You may choose whichever is most convenient.
* The input will contain 1 jump per line, with the origin and destination separated by a single space.
* The lines in the input are not guaranteed to be in any specific order.
* A successful path will start at page 1 and end at page 100.
* You may assume there is at least 1 path to the goal. You do not need to find all paths, nor do you need to find the shortest. Just find at least one.
* The smallest page number will be 1. There is no limit to the largest page number. (You can assume that it will fit in the range of an int.)
* Loops may exist. For example, the list may have jumps from page 5 to 10, 10 to 19, and 19 to 5.
* There may be dead-ends. That is, a destination page might not have anywhere to jump to.
* Conversely, there may be unreachable pages. That is, an origin page might not be the destination of any jumps.
* Not all page numbers between 1 and 100 are guaranteed to be used.
* Your output should consist of a valid route of page numbers, starting with 1 and ending at 100, separated by spaces.
Remember, this is code golf, so the shortest solution wins!
**EDIT:** Added another sample for testing.
[Answer]
## Python, 232 213 157 143 135 132 chars (shortest path)
This implementation can handle all of the edge cases described (loops, dead ends, orphan pages etc.) and guarantees that it will find the shortest route to the ending. It is based on Djikstra's shortest path algorithm.
```
import sys
l=[k.split()for k in sys.stdin]
s={"100":"100"}
while"1"not in s:
for i,j in l:
if j in s:s[i]=i+" "+s[j]
print s["1"]
```
[Answer]
### Golfscript, 58 57 chars
```
~]2/.,{:A{){=}+{0=}\+A\,\`{\+}+/}/]A+}*{)100=\0=1=*}?' '*
```
**Warning**: this is super-inefficient. It works by repeatedly squaring the adjacency matrix and then looking for a route; if there are `E` edges in the graph then it will find every path of length up to 2E (and the shorter ones it will find lots of times). It should give you a result for the first test case in a reasonable time, but if you want to try the second one make sure that you've got a few gigs of memory free and go for a long walk.
If you want a reasonably efficient solution then I offer at 67 chars:
```
~]2/:A,[1]]({A{{{?)}+1$\,,}%~!*},{({\-1==}+2$?\[+]+}/}*{100?)}?' '*
```
[Answer]
## Javascript: 189 Characters
This is a recursive solution that finds the shortest path through the adventure.
**Code-Golfed:**
```
a=prompt().split('\\n');b=0;while(!(d=c(b++,1)));function c(e,f,i,g){if(e>0)for(i=0;h=a[i++];){g=h.split(' ');if(g[0]==f){if(g[1]==100)return h;if(j=c(e-1,g[1]))return g[0]+' '+j}}}alert(d)
```
To test (**WARNING: infinite loop for bad input!**):
1. Copy one of the following input strings (or use a similar format to choose your own choose your own adventure):
* `1 10\n10 5\n10 13\n5 12\n5 19\n13 15\n12 20\n15 100`
* `15 2\n1 4\n2 12\n1 9\n3 1\n1 15\n9 3\n12 64\n4 10\n2 6\n80 100\n5
10\n6 24\n12 80\n6 150\n120 9\n150 120`
2. Paste that into the [test fiddle](http://jsfiddle.net/briguy37/nKEZW/)'s prompt.
**Formatted and Commented code:**
```
//Get Input from user
inputLines = prompt().split('\\n');
//Starting at 0, check for solutions with more moves
moves = 0;
while (!(solution = getSolution(moves++, 1)));
/**
* Recursive function that returns the moves string or nothing if no
* solution is available.
*
* @param numMoves - number of moves to check
* @param startPage - the starting page to check
* @param i - A counter. Only included to make this a local variable.
* @param line - The line being tested. Only included to make this a local variable.
*/
function getSolution(numMoves, startPage, i, line) {
//Only check for solutions if there are more than one moves left
if (numMoves > 0) {
//Iterate through all the lines
for (i=0; text = inputLines[i++];) {
line = text.split(' ');
//If the line's start page matches the current start page
if (line[0] == startPage) {
//If the goal page is the to page return the step
if (line[1] == 100) {
return text;
}
//If there is a solution in less moves from the to page, return that
if (partialSolution = getSolution(numMoves - 1, line[1])) {
return line[0] + ' ' + partialSolution;
}
}
}
}
}
//Output the solution
alert(solution);
```
To test (**WARNING: infinite loop for bad input!**):
1. Copy one of the following input strings (or use a similar format to choose your own choose your own adventure):
* `1 10\n10 5\n10 13\n5 12\n5 19\n13 15\n12 20\n15 100`
* `15 2\n1 4\n2 12\n1 9\n3 1\n1 15\n9 3\n12 64\n4 10\n2 6\n80 100\n5
10\n6 24\n12 80\n6 150\n120 9\n150 120`
2. Paste that into the [test fiddle](http://jsfiddle.net/briguy37/DVLdA)'s prompt.
[Answer]
## Ruby 1.9, 98
```
j=$<.map &:split
f=->*p,c{c=='100'?abort(p*' '):j.map{|a,b|a==c&&!p.index(b)&&f[*p,b,b]}}
f[?1,?1]
```
Ungolfed:
```
$lines = $<.map &:split
def f (*path)
if path[-1] == '100' # story is over
abort path.join ' ' # print out the path and exit
else
# for each jump from the current page
$lines.each do |from, to|
if from == path[-1] && !path.include?(to) # avoid loops
# jump to the second page in the line
f *path, to
end
end
end
end
```
[Answer]
## Perl, 88 chars
basically a perlized version of Clueless' entry; pre-matches and post-matches are fun :)
```
@t=<>;%s=(100,100);until($s{1}){for(@t){chomp;/ /;$s{$`}="$` $s{$'}"if$s{$'}}}print$s{1}
```
[Answer]
# Python - ~~239~~ ~~237~~ 236
```
import sys
global d
d={}
for i in sys.stdin:
a,b=[int(c) for c in i.split(' ')]
try: d[b]+=[a]
except: d[b]=[a]
def f(x,h):
j=h+[x]
if x==1:
print ''.join([str(a)+" " for a in j[::-1]])
exit()
for i in d[x]:
f(i,j)
f(100,[])
```
unfortunately, this tail-recursive solution is vulnerable to loops in the "story"...
**Usage**: cat ./test0 | ./sol.py
Output for test case 1:
```
1 10 13 15 100
```
Output for test case 2:
```
1 15 2 12 80 100
```
[Answer]
## Scala 2.9, 260 256 254 252 248 247 241 239 234 227 225 212 205 characters
```
object C extends App{var i=io.Source.stdin.getLines.toList.map(_.split(" "))
def m(c:String):String=(for(b<-i)yield if(b(1)==c)if(b(0)!="1")m(b(0))+" "+b(0)).filter(()!=).mkString
print(1+m("100")+" 100")}
```
Ungolfed:
```
object Choose extends App
{
var input=io.Source.stdin.getLines.toList.map(_.split(" "))
def findroute(current:String):String=
(
for(branch<-input)
yield
if(branch(1)==current)
if(branch(0)!="1")findroute(branch(0))+" "+branch(0)
).filter(()!=).mkString
print(1+findroute("100")+" 100")
}
```
Usage:
Compile with `scalac filename` and run with `scala C`. Input is taken via `STDIN`.
To run on ideone.com, change `object C extends App` to `object Main extends Application` to run it as Scala 2.8.
[Answer]
## PHP, 166 146 138 chars
```
$a[]=100;while(1<$c=$a[0])for($i=1;$i<$argc;$i++){list($p,$q)=explode(' ',$argv[$i]);if($q==$c)array_unshift($a,$p);}echo implode(' ',$a);
```
Ungolfed :
```
$a[]=100;
while(1<$c=$a[0])
for($i=1;$i<$argc;$i++){
list($p,$q)=explode(' ',$argv[$i]);
if($q==$c)array_unshift($a,$p);
}
echo implode(' ',$a);
```
Usage :
```
php golf.php "1 10" "10 5" "10 13" "5 12" "5 19" "13 15" "12 20" "15 100"
```
[Answer]
I would put all of them into a 2d array and search all items with multiple loop, if they can reach the last item then I would collect related items in order into another results array, and from results I would choose an array which one is smaller.
EDIT => JAVA:I have also used recursive function, full code below;
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Jumper {
static int x = 0;
public static ArrayList<ArrayList<String>> c = new ArrayList<ArrayList<String>>();
public static void main(String[] args) throws IOException {
//Read from line and parse into array
BufferedReader in = new BufferedReader(new FileReader("list.txt"));
ArrayList<String> s = new ArrayList<String>();
String line = null;
while ((line = in.readLine()) != null){s.add(line);}
c.add(new ArrayList<String>());
//When you get all items forward to method
checkPages(0, s,Integer.parseInt(s.get(0).split(" ")[0]),Integer.parseInt(s.get(s.size()-1).split(" ")[1]));
}
public static void checkPages (int level,ArrayList<String> list,int from, int dest){
if(level <= list.size()){
for(int i=level;i<list.size();i++){
int a = Integer.parseInt(list.get(i).split(" ")[0]);
int b = Integer.parseInt(list.get(i).split(" ")[1]);
if(a == from){
c.get(x).add(list.get(i));
if(b==dest){
c.add(new ArrayList<String>());
x++;
}else{
checkPages(i, list, b,dest);
c.get(x).remove(list.get(i));
}
}
}
}
}
}
```
] |
[Question]
[
The Dutch system for naming one's ancestors is a lot more interesting than the English version. For English, the sequence goes "parent", "grandparent", "great-grandparent", "great-great-grandparent", "great-great-great-grandparent"; and in Dutch those terms are "ouder", "grootouder", "*over*grootouder", "*bet*overgrootouder", "*stam*ouder". And so it [continues](https://www.nazatendevries.nl/Genealogie/Achtergronden/Namen%20van%20voorouders.html) with a non-positional mixed-radix counting system that produces unique names for up to 513 generations.
To not make this a mere string compression challenge, you can use the initials for each keyword. The pattern is like this:
| Generation | Full Dutch name | Initialism (return this) | Note |
| --- | --- | --- | --- |
| 1 | proband | | Return nothing (whitespace allowed) |
| 2 | ouder | O | |
| 3 | grootouder | GO | |
| 4 | overgrootouder | OGO | |
| 5 | betovergrootouder | BOGO | |
| 6 | oudouder | OO | 2 with prefix "oud" |
| 7 | oudgrootouder | OGO | 3 with prefix "oud" |
| 8 | oudovergrootouder | OOGO | 4 with prefix "oud" |
| 9 | oudbetovergrootouder | OBOGO | 5 with prefix "oud" |
| 10 to 17 | stamouder to stamoudbetovergrootouder | SO to SOBOGO | 2 to 9 with prefix "stam" |
| 18 to 33 | edelouder to edelstamoudbetovergrootouder | EO to ESOBOGO | 2 to 17 with prefix "edel" |
| 34 to 65 | voorouder to vooredelstamoudbetovergrootouder | VO to VESOBOGO | 2 to 33 with prefix "voor" |
| 66 to 129 | aartsouder to aartsvooredelstamoudbetovergrootouder | AO to AVESOBOGO | 2 to 65 with prefix "aarts" |
| 130 to 257 | opperouder to opperaartsvooredelstamoudbetovergrootouder | OO to OAVESOBOGO | 2 to 129 with prefix "opper" |
| 258 to 513 | hoogouder to hoogopperaartsvooredelstambetovergrootouder | HO to HOAVESOBOGO | 2 to 257 with prefix "hoog" |
### Challenge
Take a number between 1 and 513 inclusive. Return the appropriate abbreviated Dutch ancestor term; case doesn't matter. It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins!
### Test cases
```
input;output
1;
2;O
4;OGO
6;OO
9;OBOGO
267;HSGO
513;HOAVESOBOGO
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes
```
7ŒPUṢị“OSEVAOH”p“OGOB”UƤ¤⁶;ị@
```
* [Try it online!](https://tio.run/##y0rNyan8/9/86KSA0Ic7Fz3c3f2oYY5/sGuYo7/Ho4a5BSCeu78TkBl6bMmhJY8at1kD1Tj8///fyMwcAA "Jelly – Try It Online")
* [Test suite](https://tio.run/##y0rNyan8/9/86KSA0Ic7Fz3c3f2oYY5/sGuYo7/Ho4a5BSCeu78TkBl6bMmhJY8at1kD1Tj8twZKKOjaKQAlrA@3c5kaGh9uf9S0JvI/AA "Jelly – Try It Online")
A full program taking an integer argument and outputting a string to STDOUT. When called as a link, will produce a list of two strings (other than for 1); these are implicitly concatenated when run as a full program.
## Explanation
```
7ŒP | Power set of 1..7
U | Reverse each list
Ṣ | Sort
ị“OSEVAOH” | Index into "OSEVAOH"
p“OGOB”UƤ¤ | Cartesian product with reversed prefixes of "OGOB"
⁶; | Prefix with space, to handle the proband case
ị@ | Index the original link argument into this
```
[Answer]
# [Python](https://www.python.org), 72 bytes
```
f=lambda i:i>5and"OSEVAOH"[m:=len(bin(i-2))-5]+f(i-(4<<m))or"BOGO"[5-i:]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PdJscxJzk1ISFTKtMu1ME_NSlPyDXcMc_T2UonOtbHNS8zSSMvM0MnWNNDV1TWO104BMDRMbm1xNzfwiJSd_d3-laFPdTKtYqHmaaflFCpkKmXkKRYl56akahjpGBoaaVlwKQFBQlJlXopGpowA0RFMTogHmEAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes
```
_2d4+Ø.Ub"ؽU“OGOB“OSEVAOH”x"FUḣ’
```
[Try it online!](https://tio.run/##y0rNyan8/z/eKMVE@/AMvdAkpcMzDu0NfdQwx9/d3wlEBbuGOfp7PGqYW6HkFvpwx@JHDTP/mxoaH25/1LQm8j8A "Jelly – Try It Online")
This is... not good...
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
¿⊖θ«⮌ΦOSEVAOH&⁴÷⁻θ²X²κ✂BOGO﹪⁻¹θ⁴
```
[Try it online!](https://tio.run/##Ncw9C8IwFIXhWX9F6HQDcbAUHZxa6tdQUhTcS3LFizGhadoO4m@PpeiZz/OqR@OVa0yMdGdQovL4QhtQQ8s5ey8XtScb4IID@g7hQCagh0Re97dcnhLBCgojdZhbDZlgZxtKGkgjVGT7DlrBUi5Y7cZJpYI9@bzdv3s1pBCSQh7l1Kqc7o370bVg7USz@f6JMd1s42owXw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
¿⊖θ«
```
Do nothing if the input is `1`.
```
⮌ΦOSEVAOH&⁴÷⁻θ²X²κ
```
Work out which prefixes to output according to the binary representation of `(n-2)//4`.
```
✂BOGO﹪⁻¹θ⁴
```
Work out how much of betovergrootouder to output.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
n=>[...'HOAVESOBOGO'].filter(x=>i-->2?n>0&n>>i:n%4>i+1,i=9,n-=2)
```
[Try it online!](https://tio.run/##Dcm9CsIwEADgp9E25AdT6qD1ThREtwyCiziUmshJuEhaxLePXb7le/fffhwyfSbN6elLgMKAd2NMdXGH2@nqju7sqocJFCef6x8gaY3NnnG1ZETa8qJFklYRbBRraEQJKddEYDui3dq2nZREYkg8puhNTK85VZgRovwB "JavaScript (Node.js) – Try It Online")
Returns array
# [JavaScript (Node.js)](https://nodejs.org), 75 bytes
```
f=(n,i=7)=>i--?n-1>4<<i?'OSEVAOH'[i]+f(n-(4<<i),i):f(n,i):'BOGO '.slice(-n)
```
[Try it online!](https://tio.run/##FcuxCsIwEADQX3HLHckVAhWhTVoURLcMgos4lJiUk5JII/5@pOuD955@U/Erf76U8ivUGi0kxfaAdmCiMZEeWmN4FO52vh/dVTz4KSMkgo1RMXZxG9iJk7u4nWjKwj4AJawxr8BW92z2uu2lZPQ5lbyEZskzsIrAiPUP "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 78 bytes
```
g n|n<6=drop(5-n)"BOGO"
g n=[p:g(n-2^s)|(p,s)<-zip"HOAVESO"[8,7..],2^s+1<n]!!0
```
[Try it online!](https://tio.run/##XZBNa4NAEIbv/orJUoLiB9k1GlvcQwIhuXkI5CIWhFQrTbcSe5CS/25nxzasXpZnZt5n2dn3svt4u16HoQZ1V2ksL7ev1o585bBddsiYhX2Zty@1rXzx2jl3u/U6J/V/mpYds@15f8pYnnibICg8nLs8VcVisRoq4CCBMasCoSHTFGo6EK6pOXKkefdXxDQg3BiZZGyPxTMV/4aCOwBfQSoRl0s8kICTfWLgulCBrcCnkAvCeTjJzAnpgfupk0yccD1zYnr9eeJgyHTieOpwQQtsJw6GDIeHs31ENP6G6eiQ4Yhotk/EaZ@j6egQOdZn2Sgct7dGfcMTlOoCOdTQg5QY7vHCHlIfch4EeFFRWMMv "Haskell – Try It Online")
[Answer]
# [Scala 3](https://www.scala-lang.org/), 121 bytes
A port of [@mousetail's Python answer](https://codegolf.stackexchange.com/a/268820/110802) in Scala.
---
```
def f(i:Int):String={if(i>5){val m=Integer.toBinaryString(i-2).size-3;"OSEVAOH"(m)+f(i-(4<<m))}else"BOGO".substring(5-i)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LU_BSsNAEL33K4Y97RA21NaCxERoUdSD5FD0UnrY1k0YSXZld6vEkC_x0ote_KL-jZukMwzDzHtvePP96_aykvO_DRPafEqr2faUmd2b2nt4kqShnQC8qgLqMHBpS5fA0lrZbNbeki63mMCzJg9ZYAYqwM_BF-Lq1PSiglPyqD0mIzlrKWxuFth-yArqLECqVDb2ZkVa2mZkcRIzjB19KTG_Zvn67mWZPzBeYxTEgl-maY3Yqcoptsrvcxa7w86NyoUg7M4Gbgc3hbHACVIBF-ANzKZTHF7q4z1ofKUDHAELGfV-EQe0m_R1vnU8jv0f)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•1<P“Ï•6Ýæíè"ogob"ηíâ€S¯šI<è
```
Port of [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/268826/52210), so make sure to upvote that answer as well.
Output as a list of lowercase characters.
[Try it online](https://tio.run/##yy9OTMpM/f9f71HDIkObgEcNcw73A5lmh@ceXnZ47eEVSvnp@UlK57YD2YseNa0JPrT@6EJPm8Mr/v83MjMHAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9qaOzqZ6@k8KhtkoKSvd9/vUcNiwxtAh41zDncD2SaHZ57eNnhtYdXKOWn5ycpndsOZC961LQm@ND6owv9bA6v@K/zHwA).
A port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/268822/52210) would be 1 byte longer:
```
≠.•1<P“Ï•IÍ4÷bRÏR.•ÇF•$-4%.$«×
```
Outputs as a lowercase string.
[Try it online](https://tio.run/##yy9OTMpM/f//UecCvUcNiwxtAh41zDncD2R6Hu41Obw9KehwfxBI5nC7G5BU0TVR1VM5tPrw9P//jczMAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/W9qaOzqZ6@k8KhtkoKSvd//R50L9B41LDK0CXjUMOdwP5Dpd7jX5PD2pKDD/UEgmcPtbiB5P10TVT2VQ6sPT/@v8x8A).
**Explanation:**
```
6Ý # Push list [0,1,2,3,4,5,6]
æ # Pop and push the powerset of this
í # Reverse each inner list
.•1<P“Ï• è # Index each inner value into compressed string "osevaoh"
"ogob" # Push this string
η # Pop and push its prefixes
í # Reverse each prefix
â # Cartesian power of the two lists to get all possible pairs
€ # Map over each pair:
S # Convert the pair of strings to a flattened list of characters
¯š # Prepend an empty list
I # Push the input
< # Decrease it by 1 to make it 0-based
è # Index it into the list of lists of characters
# (after which it is output implicitly)
```
```
≠ # Check if the (implicit) input is NOT 1
# (0 if input=1, 1 otherwise
.•1<P“Ï• # Push compressed string "osevaoh"
IÍ # Push the input, and decrease it by 2
4÷ # Integer-divide it by 4
b # Convert it to a binary string
R # Revert it
Ï # Keep the characters in "osevaoh" at the truthy bits
R # Reverse that string
.•ÇF• # Push compressed string "bogo"
$ # Push 1 and the input
- # Subtract the input from the 1
4% # Modulo 4
.$ # Remove that many leading characters from "bogo"
« # Append the two substrings together
× # Repeat this string the input==1 check amount of times
# (so input=1 becomes an empty string)
# (which is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•1<P“Ï•` is `"osevaoh"` and `.•ÇF•` is `"bogo"` (Minor note: `"ogob"` and `.•4ā:•` are the same length, so no use compressing it.)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~85~~ 70 bytes
```
.+
$*G
G$
G$
O
G{8}
S
GGGG
O
SS
E
EE
V
VV
A
AAAA
H
AA
O
GGG
BOG
GG
OG
```
[Try it online!](https://tio.run/##FYs7CoAwFAT7OUcEURD8a6kQnl2KQGotLGwsxE48e3wOLMvC7LXfx7nFJJU1FjkmE8TwxyHP8OIRRZf3WKwlEAITk8Ki9YsqzE6f6kmMJRUNHSNV19OW9Qc "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*G
G$
G$
O
```
Convert to unary using `G`s, subtract 1 to correct for the input being 1-indexed, then replace any last `G` with `O`, so it doesn't accidentally get converted below.
```
G{8}
S
GGGG
O
SS
E
EE
V
VV
A
AAAA
H
AA
O
```
Handle the `HOAVESO` prefixes, starting with `S` and working back to `H`, then finish with the `O`s (because `134` should become `OOO` and not `OS` or `HO`). Edit: Saved 15 bytes thanks to @Ausername.
```
GGG
BOG
GG
OG
```
Fix up any remaining multiple `G`s.
I tried this in Retina 1 but unfortunately cyclic transliteration just crashes out if the input is empty which is a shame as that's a legal output.
132 bytes to translate into Dutch:
[Try it online!](https://tio.run/##HcxRCsIwEATQ/zlHBVEQNm2jnsBbiCkJVdBu2cb@SM4eR2FZHrvDWMqPKdTN9nKrhz2aHa7SYDYdwhQhtL5jMsjH9b7grjrS4k4FOs//h@8KQrC80K0rWFV/Z2E8xfQkGV5yeFGMso@9giFlbo6uyQiMppprFTh08DjD@SN6ab8 "Retina 0.8.2 – Try It Online") Link includes test cases. Note: Based on my previous 85-byte solution.
[Answer]
# [Retina](https://github.com/m-ender/retina), 54 bytes
```
11$
O
1(1)(?<1>\1\1)+
$#1
Y^`11d`G\O_B\OS\E\VA\O\H
G$
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sKLUkMy9xwTJVDS0N94SlpSVpuhY3zQwNVbj8uQw1DDU17G0M7WIMYww1tblUlA25IuMSDA1TEtxj_OOdYvyDY1xjwhxj_GM8uNxVuJYUJyUXb9B0T-DSAyrWM-CsUVDRNYKYueAWs4YhlyEIQQk4hcIaBaNhMdIBJMcAAA)
Input in unary
## Explanation
So, given input \$n\$, this challenge is mostly to convert \$n-2\$ to binary.
---
```
11$
O
```
Replace the last two `1`s with an `O`. So we have \$n-2\$ (in unary) followed by `O`. (There will be a special case for input 1)
---
```
1(1)(?<1>\1\1)+
$#1
```
The regex matches any power of 2 that is ≥ 4, then we replace those with their log2.
This results in a list of digits 8~2 corresponding to the binary representation of \$n-2\$, followed by 0~3 `1`s representing the remainder of \$(n-2) \div 4\$ , followed by `O`.
For example if \$n = 269\$ (i.e. \$n-2 = 267 = 100001011\_2 = 2^8 + 2^3 + 3\$), the result is `83111O`
---
```
Y^`11d`G\O_B\OS\E\VA\O\H
```
From right to left, process each character as follows:
| Character | Output |
| --- | --- |
| First occurrence of `1` | `G` |
| Second occurrence of `1` | `O` |
| `0` (won't happen, but removing this mapping costs 1 byte so...) | Remove |
| Third occurrence of `1` | `B` |
| `2` | `O` |
| `3` | `S` |
| `4` | `E` |
| `5` | `V` |
| `6` | `A` |
| `7` | `O` |
| `8` | `H` |
| Other | Unchanged |
---
```
G$
```
The only thing left to do is to deal with \$n=1\$, which end up as a single `G`. Since any other valid input ends with an `O`, we can special case \$n=1\$ by "removing the last character if it is `G`"
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 93 bytes
```
say+(map{(O,S,E,V,A,O,H)[--$i]x$_}(sprintf"%07b",$_/4)=~/./g),substr BOGO,3-($_&3)if($_-=2)+1
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJbIzexoFrDXydYx1UnTMdRx1/HQzNaV1clM7ZCJb5Wo7igKDOvJE1J1cA8SUlHJV7fRNO2Tl9PP11Tp7g0qbikSMHJ391fx1hXQyVezVgzMw1I69oaaWob/v9v@S@/oCQzP6/4v66vqZ6BocF/3bwcAA "Perl 5 – Try It Online")
] |
[Question]
[
Given an integral polynomial \$p\$, determine if \$p\$ is a square of another integral polynomial.
An *integral polynomial* is a polynomial with only integers as coefficients.
For example, \$x^2+2x+1\$ should gives truthy, because \$x^2+2x+1 = (x+1)^2\$.
On the other hand, \$2x^2+4x+2\$ should gives falsy: \$2x^2+4x+2 = (\sqrt{2}x+\sqrt{2})^2\$. but \$\sqrt{2}x+\sqrt{2}\$ is not an integral polynomial.
## Input
A polynomial, in any reasonable format. For example, the polynomial \$x^4-4x^3+5x^2-2x\$ may be represented as:
* a list of coefficients, in descending order: `[1,-4,5,-2,0]`;
* a list of coefficients, in ascending order: `[0,-2,5,-4,1]`;
* a list of pairs of `(coefficient, degree)`, in any order: `[(1,4),(-4,3),(5,2),(-2,1),(0,0)]`;
* a map with degrees as keys and coefficient as values: `{4:1,3:-4,2:5,1:-2,0:0}`;
* a string representation of the polynomial, with a chosen variable, say `x`: `"x^4-4*x^3+5*x^2-2*x"`;
* a built-in polynomial object, e.g., `x^4-4*x^3+5*x^2-2*x` in PARI/GP.
## Output
A value representing whether the polynomial is a square. You can choose to
* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Testcases
Here I use coefficient lists in descending order:
### Truthy
```
[]
[25]
[1,2,1]
[1,2,1,0,0]
[1,4,0,-8,4]
[4,28,37,-42,9]
[4,0,-4,4,1,-2,1]
[1,-12,60,-160,240,-192,64]
```
### Falsy
```
[-1]
[24,1]
[1,111]
[2,4,2]
[1,2,1,0]
[1,3,3,1]
[1,-4,5,-2,0]
[4,0,-4,4,1,2,1]
[1,-9,30,-45,30,-9,1]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 102 bytes
```
a=>a.some(n=>(b[j=i]=b.map(m=>n-=m*~~b[j--])|b[0]?n/2/b[0]:n**.5)%(1/a[i+i++]?1:1/0)!=0,b=[],i=0)|1&~i
```
[Try it online!](https://tio.run/##VVDLTsMwELznK8wBaqdrx3YTIK2cnrhwgAPHEKlOScFV81ASRZUo/fVgRxSEVtqdnZmdw@71oLtta5qeVvVbMe7UqFWiWVeXBa5UgvN0r0ymclbqBpcqqagq/fPZ0pRm5JSnPFtXgQwcWFa@zyJyjUWgUzM383m2FksRcHKlOOQqzcAoTk7i5mzGHim08eyVl8rINgESxGUCByeEIO9hcQc0lBBPO7cYQmugFzcVEm4tLWyToQOxJUKrUWeQ1i3/Yie0sPVzHELkovj/8N/sGBaOjKYRO3bD@taUmLCuOZgez16rGZl@c0QqQY8vz0@s0W1X4CMhK69nu7p90NsPPDj500NoW1ddfSjYoX7HOzwQQIM1fpHV@A0 "JavaScript (Node.js) – Try It Online")
Input a list of coefficients, in descending order. The list should either contain only a zero or the first value in the list should be non-zero.
I *believe* it is correct. But I cannot *prove* it with my math knowledge. It at least passed all testcases.
[Answer]
# Python3, 289 bytes:
```
R=range
def m(a,b):
r={}
for x,y in a:
for j,k in b:r[y+k]=r.get(y+k,0)+x*j
return[(r[i],i)for i in r]
def c(d,k=[]):
if[]==d:yield k;return
for x in R(abs(d[0][0])+1):
for e in R(d[0][1]+1):
for i in[1,-1]:yield from c(d[1:],k+[(i*x,e)])
f=lambda x:any(x==m(i,i)for i in c(x))
```
[Try it online!](https://tio.run/##lY/NbsMgDMfP4ylQLzENVCFtpSoTL9ErQxNpSEfzKZpNiaY9e0aSdt2OA4SN7T8/ux26t6beHlo3jkfhdH02KDM5rkDTlCQIO/H5hXDeONzTAdsaax@c3xdaTO80cXIICyXc5mw68C6NSNivL15rundXS3DSKmrJJLKTxKmZcYKMFkKqCWNzqYTIksGaMsPF8yK9gSfNEXR6hUxGyh8ScnJvwyzZOcPVLYHvLMkp4@r2be6aaqJKnihahBLsuqeGKIJyUeoqzTTuE10P0AtRgf3d8gl6QkZbtY3rsL52qH0oJPTTgKWpfRGzjD9kR1iiRKGf2Gq1kgrJeO8vTmPK75ZGNJr9nffYge6UL91c29J2ELzUgZ/sqXW27iCHFnwTG58xTpev5kOXYIlfaCkIWLCOI/IXyhYS55ONPSV@kGdv6/dSw3Z0T1ns4/9vYfwG)
Basic brute force.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~33~~ 32 bytes
```
h√d£0¾ȦλȮḂÞ•-¥/J;RI÷?₂J†^¥J:⌊=JA
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJo4oiaZMKjMOKfqOKfqcimzrvIruG4gsOe4oCiLcKlL0o7UknDtz/igoJK4oCgXsKlSjrijIo9SkEiLCIiLCJbNCwwLC00LDQsMSwyLDFdIl0=)
–1 per [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a).
## How?
We find the square root of the polynomial [using its power series](https://math.stackexchange.com/a/920756/680415), checking if the result has several integers followed by zeroes, plus additional checks.
```
# stack (top ->)
h # head p0
√ # square root sqrt(p0)
d # double 2sqrt(p0)
£ # set register = 2k
0¾Ȧ # top[0] = [] [[],p1,…,p(2n)]
λ # λ(acc,cur) acc cur
# = [a1,…,an] p(n+1)
Ȯ # over [a1,…,an] p(n+1) [a1,…,an]
Ḃ # dup and reverse [a1,…,an] p(n+1) [a1,…,an] [an,…,a1]
Þ• # dot product [a1,…,an] p(n+1) a1an+…+ana1
- # subtract [a1,…,an] p(n+1)-a1an-…-ana1
¥ # push register [a1,…,an] p(n+1)-a1an-…-ana1 2k
/ # divide [a1,…,an] (p(n+1)-a1an-…-ana1)/2k
# = [a1,…,an] a(n+1)
J; # join [a1,…,an,a(n+1)]
R # reduce [a1,…,a(2n)]
I # halve [[a1,…,an],[a(n+1),…,a(2n)]]
÷ # split to stack [a1,…,an] [a(n+1),…,a(2n)]
? # push input [a1,…,an] [a(n+1),…,a(2n)] [p0,…,p(2n)]
₂ # length even? [a1,…,an] [a(n+1),…,a(2n)] 0
J # join [a1,…,an] [a(n+1),…,a(2n),0]
† # vectorized not [a1,…,an] [1,…,1]
# [if perfect square, then a(n+1) = … = a(2n) = 0,
# and the length of input, 2n+1, would be odd]
^ # flip stack [1,…,1] [a1,…,an]
¥ # push register [1,…,1] [a1,…,an] 2k
J # join [1,…,1] [a1,…,an,2k]
: # dup [1,…,1] [a1,…,an,2k] [a1,…,an,2k]
⌊ # floor [1,…,1] [a1,…,an,2k] [a1,…,an,2k]
= # equal? [1,…,1] [1,…,1]
# [if perfect square, then a0 = 2k, … , an would
# all be integers]
J # join [1,…,1]
A # all truthy? 1
```
[Answer]
# [Python](https://www.python.org) NumPy, 103 bytes
```
lambda a:any(poly1d(rint((a[0]**.5*poly(sort(around(roots(a),7))[::2])).real))**2-a)
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY9LboMwEIb3nMJL2xoQGNMEpJyEsnAFtEjGtgxE4izdRKrafY-T23QMSap2LHnG3_zz8PuXW-c3ay4f_en5c5n7-Hh91Wp8aRVRlTIrdVavWUv9YGZKVZ02nCcFD5RO1s9UebsYzFs7T1QxODBWV5VoGEt8pzRjnItYsaj3diRmGd1KhtFhJb-Ns731RJPBEOs6Q9OtrtWD6SbKqoigDT3RyTT7wd1JMHXqzkpTzR7EbVv2uMbOOj111b8s28dert_4l6gWBV4ZCMjuHlIICQniCPkBYimg3N4pxiBREN_VcSbgCXGGl5AhKBHIJorqOCgEysVv3y3K8dyqJRShV_q3-6N5CXmAxeZKpPvmPw)
Inverted output: False for squares and True for non squares.
Direct approach using roots/linear factors. Floating point issues may lurk at some point (but not with the given test cases).
Basically, we take every other root, multiply corresponding linear factors and the square root of the leading coefficient, discard imaginary and fractional components, square and compare to the input.
For those not familiar with legacy numpy polynomials:
`roots` takes a vector coefficients and returns tthe vector of roots. `poly` takes a vector of roots and returns the vector of coefficients of the monic polynomial with the given roots (with multiplicity). `poly1d` takes a vector of coefficients and returns a polynomial object. This changes semantics of basic algebraic operations.
## [Python](https://www.python.org) NumPy, 149 bytes
```
lambda l,a:all([any(poly1d(rint((fft.ifft(fft.fft(a)**.5*(1-2*int_([*bin(i)[3:]]))))[:l//2+1].real))**2-a)for i in r_[1<<l:2<<l]])
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LboMwEN1zCi9tahNsoA0oOYmLIkfBqqXBIEIicZCuuolUtfseJ7fpmHyqZizNPL958zz--O6n8a3zp0-7fv06jFYsz-9g2u3OEOCmMgBUGz_RvoNJ7ujg_EiptWPiMM0gVMPiOCliKoWKUbGhOt46Tx3TWVXXDENXsFioJ1knQ2OAoV4Jw2w3EEecJ8NGy9UKKoUJByI7dC3xh7afiGv7bhjj63LHMAJhpOsbT1MW_HbgfLOnrIoIhrMEkv04uP7GhDDr5miAArsz_fwZSwF9DOOGXVoN7JvqQcQur5_OPzqtI60KTJIrLm-Vpzw0cq6WPHvhIle8nO8pYp6jQNzUQir-jLTEpPIASiTyOoq0CAqFcvXnO6MMz3U650XwSv-7381LngWymEuJ7GXzXw)
Inverted output. Takes the number of coefficients and the coefficient list.
This computes the square root directly in the Fourier domain. Unfortunately, for each Fourier coefficient we have to check both signs, making this approach more complicated than I had hoped.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/language/), ~~58 68 64~~ 55 bytes
thanks @Steffan for the byte correction, and the suggestions
thanks @alephalpha
```
Tr[Last/@Mod[a=FactorList@#,2]]<2&&EvenQ[2√a[[1,1]]]&
```
This code factorizes the input polynomial and checks if the exponent of all factors is even and if the square root of the integer factor is an integer.
[Try it online!](https://tio.run/##dVHRaoMwFH3vV4QWZIOITRrbOREy2ITBHlbYW/EhdNoK04LejQ0R@rhv6P5u/RB7E7XzYQ0h3Jx77rnnJpmCbZwpSNeqSYLmLn@V8uEjzpeOvFJBqNawK57SEuTk@rg/cN@n/Lj/sazHHOJNXCzl7/dBYYZRpvEGinfYfpGAjEhY7LL7dJNCuZpQ8hkRiziSVFVNScVdfTJKOCVsEFIyxd0BgqIKLoTsG7xqGDGO8WyBmMAKrwM1R5gSLLQHqjbjncxcc5g@uTChh5m5qGt/lKi3Upu@ZNk2alz8yTLWQqYlb0HTpR@j483MPptBstv6m/5nvLd65ntYbhhuF3haDB0/F2kOq/FL@9wQl1DejmniyPYDop4QmskGeTNq1JwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 122 bytes
```
->b{w=b.sum &:abs;(z=*-w..w).product(*[z]*k=b.size/2).any?{|c|x=-1;b==b.map{(0..x+=1).sum{|y|(a=c[x-y])&&c[y]?c[y]*a:0}}}}
```
[Try it online!](https://tio.run/##TUzBDsIgFLv7FTstgPAc03jYgvsQwgHQJcZMl81lY@C3I0s82OY1afvSYTIutiKyi/GzMDBOXZZX2ow1WgVhM8CMoR9e18m@EZGrIo/t677eDiUG/XSNDzYsgvHaiNR0uveoAFj2guNtzQcXkBZWLswpnOdWOtVsQnRVfBJin7VSclpSrtTuZ46Jf/ZEz@lSEL8 "Ruby – Try It Online")
Sheer brute force.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes
```
﹪Lθ²F⟦§θ⁰↨θΠ⊗⊕↔θ⟧«≔×⁰↨ι⁴ζFLζ«§≔ζκ¹§≔ζꬋιX↨²ζ²»¿⁻ιX↨²ζ²⎚
```
[Try it online!](https://tio.run/##fU89a8MwEJ3tX3HjCRSwjSmETm67BJLgIZvx4NhKIqpIRJLb4JLfrpyMu5XeoHvo3sddf@lsbzoVQm2l9rgzw6gMboU@@wveGIeCsdf0ZCxgU/mNHsQdbxwymrx1TkRcWxL1Hj/MeFRiwI3urbgK7QlXR2fU6InHYrUMftKkck6eNR7kVTjMFiPJoWTkOlFcMuctS0xsFi2q3x0mDp8c8kj@c7I3ngyci761@RYW55QiBsxHxbOSR5rIE@BO6vEfJrwr0VkkwSOEpsn5Ki/4S0aNnqKMYE0fZduG1Zd6Ag "Charcoal – Try It Online") Link is to verbose version of code. Does not support empty lists (use `[0]` instead). Outputs a Charcoal boolean, i.e. `-` if it thinks the polynomial is a square, nothing if not. Explanation: Since @tsh beat me to my original algorithm I've gone for this approach instead but I can only prove that it has no false negatives. If someone can come up with a counterexample I'll delete this answer pending a rewrite using @tsh's approach. Edit: A counterexample was found, but @Nitrodon's claim is that only polynomials of odd degree can be counterexamples, so I've spent 5 bytes checking that the polynomial is of even degree. Edit: Another counterexample was found, so I've spent 6 bytes checking that the leading coefficient is a perfect square.
```
﹪Lθ²
```
Output a `-` if the polynomial is of even degree.
```
F⟦§θ⁰↨θΠ⊗⊕↔θ⟧«
```
Calculate a very large integer given by taking the absolute values of all of the coefficients, incrementing and doubling them, and then taking the product. Evaluate the polynomial at this value. Loop over the leading coefficient of the polynomial and the result.
```
≔×⁰↨ι⁴ζFLζ«§≔ζκ¹§≔ζꬋιX↨²ζ²»
```
Perform a binary search for the nearest integer to the square root of this value.
```
¿⁻ιX↨²ζ²⎚
```
If its square does not equal the value, clear the output.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ærm2ÆṛJ}¹?×AṪ½Ɗ×þ`ŒdṙLƊṚ§⁼
```
A monadic Link that accepts a non-empty list of coefficients ordered by degree\* and yields `1` if the input represents the square of an integer polynomial, or `0` if not.
\* i.e. the reverse order to the examples in the question, and \$0\$ being `[0]` rather than `[]`
**[Try it online!](https://tio.run/##AUoAtf9qZWxsef//w4ZybTLDhuG5m0p9wrk/w5dB4bmqwr3GisOXw75gxZJk4bmZTMaK4bmawqfigbz///9bMSwtMiwxLDQsLTQsMCw0XQ "Jelly – Try It Online")**
### How?
Same approach as loopy walt's [Python answer](https://codegolf.stackexchange.com/a/246544/53748):
* get the polynomial with every other root of the polynomial defined by the input
* rescale using the square root of the coefficient of the highest degree in the input
* get the coefficients of the square of that polynomial
* check if that is equal to the input
Just a little fiddly when the input defines a constant since we find no roots whereupon finding coefficients would error (this is why `J}¹?` is there).
```
Ærm2ÆṛJ}¹?×AṪ½Ɗ×þ`ŒdṙLƊṚ§⁼ - Link: list of coefficients, C
Ær - get the roots of the polynomial P defined by C
m2 - modulo-2 slice
? - if...
¹ - ...condition: no-op (falsey if P is just a constant)
Æṛ - ...then: get polynomial coefficients
} - ...else: use the right argument (implicitly C) with:
J - range of length (in this case that's [1])
(call this list NewCoefficients)
Ɗ - last three links as a monad - f(C):
A - absolute values
Ṫ - tail (absolute of coefficient of highest degree)
½ - square root
× - (NewCoefficients) multiplied by (that)
` - use as both arguments of:
þ - table of:
× - multiplication
Ɗ - last three links as a monad - f(X=that)
Œd - anti-diagonals of X (starts with main, sweeps South-East)
(has the effect of grouping product coefficients by degree)
L - length of X
ṙ - rotate (the anti-diagonals) left by (length of X)
(ensures that the groups are sorted by degree descending)
Ṛ - reverse
§ - sums (sum each group of like-degree product coefficients)
⁼ - equals C?
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 8 bytes
```
issquare
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVBLCsIwEKU3CV01MIFmmmqz0DO4L0WysFIomv4WnsVNQUTP5GmcNLWKBN689zIzD-b6sKat9kc73kq2uQ99KbJn1XXNYNqDl68gMNbWl8gwsWW2rU59tDvXkeEsdE7IyllzDizPCwJMHUpAkAuBGGIvFFGRgXJKAWaQrEEoBO0N-lTUI0Es40IirMiXBKgc0WRMC8TcIuVEkCbxJ9PThN5nlYLUbY7_wr5ZGhLnplPRZBfcX2IcfX0D)
A boring built-in. Return `1` for truthy and `0` for falsy.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 68 bytes
```
p->p&&for(i=!r=(abs(Vec(p)[1])^.5\/1)*x^d=#p\2,d,r+=(q=p-r^2)\r/2)+q
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVDLTsMwEFT_xBSpsumaxhsHkoN74gM4cckDBUpQpIpuTZHgW7hEQohvgq9hHZeCkKXZmfHurLSvH9T6_vqehrdOuPenXafzzwvSS5rNuo2XvTvyTrY3j_Lq7laSKk2tmtOsWhh18tys3DFVCCvwcye3jrRvUFV-gWq-jVlfk0lLtH6RrdBLQb5_2MnLzVq2SkyDMxXdXisFoixrBswCGkAwBwIJJFFYpjoHG5QFzCE9B20Rimjwp-UeA_owrg3CGfuGAW0gBRtjgN63GDMS5En8szPSlN9PlIUsJCf_lv3uKiANbjaWgu1axUsMQ6zf)
Return `0` for truthy and `1` for falsy.
Basically a port of [@tsh's JavaScript answer](https://codegolf.stackexchange.com/a/246533/9288). Interestingly, the loop body `r+=(p-r^2)\r/2` looks very similar to the formula of calculating the square root of a real number using Newton's method.
[Answer]
# [Mathematica](https://www.wolfram.com/wolframscript/), 144 bytes
Based on Factorization of polynomials.
The critical function used here is `FactorList[expr, GaussianIntegers -> False]`
---
Golfed version(It can be golfed much more). [Try it online!](https://tio.run/##fZFfS8MwFMXf9yliB3uQFJusU7tamTg7BgpO9xaCxpluha7VNJVK2b56TdLWPyiWEE5@nHtzbrplcsO3TMYrVl8mnAlizZLsiSWPhxb164iUD3Qc3GTPRcJJxXZwHpF5Kvmai8WkhHdcFiIlB/evBRM8FJwrSqnPgpCtZCau41ySEs5YkecxS9vK3D53qK86MUIQRJSeYcgCtp@K7GWPqH@RJEtRcMLg1RtPF6RPCKaUDiitpSjk5h0EIBTZdhqvY5mTPgQlBQNwNAFVtYOgwiO9IwgwBOibhMCBoAf057TYNcw@VUoTdcRKD08Uc1WJ10LtcY1b1di469I1t5FCx9qE9I5dIz0N3d3O70Usyf8LbZtG2P2Ki1CDzJ24gc2d3SStcWjWZxDlHjUJnb@i/07uqXpjGbXC091U5lsRp5JYy@bBJc9lPrYgiHTi5i/QzhOa8X5azMi0/gA)
```
f[x_]:=Module[{a},If[IntegerQ@x,Return[!SquareFreeQ@x]];a=FactorList[x,GaussianIntegers->0];If[a[[1,1]]<2,a=a~Drop~1];AllTrue[a,EvenQ[#[[2]]]&]]
```
Ungolfed version. [Try it online!](https://tio.run/##dVHRaoMwFH3vV4QWZIOITRrbOREy2ITBHlbYW/EhdNoK04LejQ0R@rhv6P5u/RB7E7XzYQ0h3Jx77rnnJpmCbZwpSNeqSYLmLn@V8uEjzpeOvFJBqNawK57SEuTk@rg/cN@n/Lj/sazHHOJNXCzl7/dBYYZRpvEGinfYfpGAjEhY7LL7dJNCuZpQ8hkRiziSVFVNScVdfTJKOCVsEFIyxd0BgqIKLoTsG7xqGDGO8WyBmMAKrwM1R5gSLLQHqjbjncxcc5g@uTChh5m5qGt/lKi3Upu@ZNk2alz8yTLWQqYlb0HTpR@j483MPptBstv6m/5nvLd65ntYbhhuF3haDB0/F2kOq/FL@9wQl1DejmniyPYDop4QmskGeTNq1JwA)
```
Clear["Global`*"];
f[expr_] := Module[{fl},
If[IntegerQ@expr, Return[Not@SquareFreeQ[expr]]];
fl = FactorList[expr, GaussianIntegers -> False];
If[fl[[1, 1]] == 1, fl = Drop[fl, 1]];
AllTrue[fl, EvenQ[#[[2]]] &]]
truthy = FromDigits[#, x] & /@ {{}, {25}, {1, 2, 1}, {1, 2, 1, 0,
0}, {1, 4, 0, -8, 4}, {4, 28, 37, -42, 9}, {4, 0, -4, 4, 1, -2,
1}, {1, -12, 60, -160, 240, -192, 64}};
falsy = FromDigits[#, x] & /@ {{-1}, {24, 1}, {1, 111}, {2, 4, 2}, {1,
2, 1, 0}, {1, 3, 3, 1}, {1, -4, 5, -2, 0}, {4, 0, -4, 4, 1, 2,
1}, {1, -9, 30, -45, 30, -9, 1}};
Print["Truthy tests:", f /@ truthy]
Print["Falsy tests:", f /@ falsy]
```
] |
[Question]
[
## Input
An \$m\$ by \$n\$ binary matrix, with \$m\$ and \$n\$ both at least 2.
Think of the ones as gobs of melted cheese, which stretch as we expand the matrix horizontally and vertically.
More precisely...
## Output
A \$2m-1\$ by \$2n-1\$ binary matrix, constructed as follows...
First insert rows of zeros between the rows, and insert columns of zeros between the columns. For example, consider the input:
```
0 1 1
1 0 1
1 0 0
```
After we insert the zeros:
```
0 0 1 0 1
0 0 0 0 0
1 0 0 0 1
0 0 0 0 0
1 0 0 0 0
```
To make it extra clear what we're doing, here is the same matrix with the *new* zeros visualized as `#`:
```
0 # 1 # 1
# # # # #
1 # 0 # 1
# # # # #
1 # 0 # 0
```
Now, for each new `0` (or `#` in our visualization), if is between two ones (horizontally, vertically, or diagonally), convert it to a 1:
```
0 # 1 1 1
# 1 # 1 1
1 # 0 # 1
1 # # # #
1 # 0 # 0
```
Or, exiting our visualization and converting `#` back to `0`:
```
0 0 1 1 1
0 1 0 1 1
1 0 0 0 1
1 0 0 0 0
1 0 0 0 0
```
And that is the actual, final result you return.
## Rules
* This is code golf with standard site rules
* You may take input in any reasonable format (array of arrays, built-in matrix type, single flat list, etc)
+ With one exception: you may not take a list of the coordinates of the ones.
+ This exception applies to the output as well: you must output all of the zeros and ones in some reasonable form.
* You may optionally take \$m\$ and \$n\$ as a second argument
* You can do I/O using images, so long as there is a 1-1 mapping with the matrix entries.
## Brownie Points
* Solution using images for I/O.
* J solution under 47 bytes.
## Test Cases
```
1 0
0 1
->
1 0 0
0 1 0
0 0 1
1 1
0 1
->
1 1 1
0 1 1
0 0 1
1 1
1 1
->
1 1 1
1 1 1
1 1 1
1 1
0 0
->
1 1 1
0 0 0
0 0 0
1 1 0 1 0 1
1 0 0 1 0 0
0 1 0 0 1 0
0 1 0 0 1 1
1 0 1 0 0 0
->
1 1 1 0 0 0 1 0 0 0 1
1 1 0 0 0 0 1 0 0 0 0
1 0 0 0 0 0 1 0 0 0 0
0 1 0 0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0 1 1 0
0 0 1 0 0 0 0 0 1 1 1
0 1 0 1 0 0 0 0 0 0 0
1 0 0 0 1 0 0 0 0 0 0
```
[Answer]
# [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/), ~~97~~ 70 bytes
```
lambda m:abs(diff(diff(kron(m,1j**eye(2))),1,0))>=2
from numpy import*
```
[Try it online!](https://tio.run/##ZY29DoIwFEZ3nqJjSzq0upHohquLGzJUaWOV/uRSVJ4eQWgU/ZI296TfPfVduDi77tXm2NfCnCqBTCZODa60UtN1A2exofyaprKTeEUIoZwyQrabVaLAGWRb4zukjXcQ0j5AlyVoyOOia4kO0MqJx3jQNmCF5V3UWFvfBjz4SCKfZ@kDyve7HMBBhrxomr4oho9KWjDKyzIZif8R/3ljkSibzrvDZpptkRcUmxN/e6LlM7/7s2@5HzvlCw "Python 3 – Try It Online")
The basic idea is this: Expand each element into a 2-by-2 block, then look at each 2-by-2 square (overlapping) in the resulting matrix; each square should correspond to a 1 iff it contains a pair of diagonally opposite 1s.
The implementation works a bit differently. `kron` expands each 1 into `1j**eye(2)`, which is
\$ \begin{array}{|c|c|} \hline i & 1 \\ \hline 1 & i \\ \hline \end{array} \$, and taking `diff` in both directions is equivalent to a sum with multipliers \$ \begin{array}{|c|c|} \hline 1 & -1 \\ \hline -1 & 1 \\ \hline \end{array} \$ on each 2-by-2 square (overlapping). Then, each square contains two diagonally opposite nonzero values iff its result has real or imaginary component at least 2 in absolute value, which with integer components is equivalent to its own absolute value being at least 2.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ ~~38~~ ~~19~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2F€Dø€ü2}εε`RøPà
```
-19 bytes porting [*@m90*'s Python answer](https://codegolf.stackexchange.com/a/245610/52210), so make sure to upvote him/her as well!
-3 bytes thanks to *@m90*.
[Try it online](https://tio.run/##yy9OTMpM/f/fyO1R0xqXwzuA5OE9RrXntp7bmhB0eEfA4QX//0dHG@oY6hhAcKxONIiG8AyAPCgLRKLwYCohfIPYWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lotw6Xkn9pCYyv9N/I7VHTGpfDO4Dk4T1Gtee2ntuaEHR4R8DhBf@V9MKA6g9ts/8fHR1tqGMQqxNtoGMYG6ujAOIaYnIN0WUN4FwdAwgGqzKA8qAmwvgoPJhKCB9uEMIYA5ihsbGxAA) or [try it online with step-by-step debug lines](https://tio.run/##VU@7TsNAEOz5ipHrQ7JdmoKCgESHktKyxNpZx6c4d6fLJXJDw5fwAbRBkaCK@3wEP2LuYghQ7GN2RzO7ek2l5GGI7pXZuAyROLyLw9v1RTRzbJBkuO0MqTmYqgZbajcMp0FIuxRlq6vlFcLaNaxQWSbH0Fu2LRkj1eKXtoauAwusnLSMFTkru2CY3n0@v076vc/9R/o0@WOfZrhpuFqi1na8QNZg6WXsSWtFUmEuaaEVtfCc04C8w@V5St6s1K4Jv0TiuDvuHqf9/qF/Kfynw5DniUhEPEYh8lBHFHv03YX8D/0wRxwXxRc).
**Explanation:**
```
2F # Loop 2 times:
€D # Duplicate each value in the current list
ø # Zip/transpose; swapping rows/columns
€ # For each inner list:
ü2 # Create overlapping pairs
} # Close the loop
# (we now have overlapping 2x2 blocks of the input-matrix after that has been
# expanded to 2x2 for each individual value)
ε # Map over each list of blocks:
ε # Map over each 2x2 block:
` # Pop and push both pairs separated to the stack
# STACK: [[a,b],[c,d]] → [a,b] and [c,d]
R # Reverse the top pair
# STACK: [a,b] and [d,c]
ø # Create pairs of these two pairs
# STACK: [[a,d],[b,c]]
P # Take the product of each inner pair to check if both are 1
# STACK: [a*d,b*c]
à # Take the maximum to check if either was truthy
# (so whether the diagonal or anti-diagonal of the 2x2 block were both 1s)
```
---
**Original ~~45~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
2Føε0ìSĆ]2Fø€ü3}εε2FøíÐÅsˆÅ\ˆ}¯ειPà}à´
```
[Try it online](https://tio.run/##yy9OTMpM/f/fyO3wjnNbDQ6vCT7SFgviPGpac3iPce25ree2griH1x6ecLi1@HTb4daY0221h9YDJXYGHF5Qe3jBoS3//0dHG@oY6hhAcKxONIiG8AyAPCgLRKLwYCohfIPYWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lotw6Xkn9pCYyv9N/I7fCOc1sNDq8JPtIWC@I8alpzeI9x7bmt57aCuIfXHp5wuLX4dNvh1pjTbbWH1gMldgYcXlB7eMGhLf@V9MKARh7aZv8/OjraUMcgVifaQMcwNlZHAcQ1xOQaossawLk6BhAMVmUA5UFNhPFReDCVED7cIIQxBjBDY2NjAQ) or [try it online with step-by-step debug lines](https://tio.run/##VVC9TsMwGNx5ik@dQApq0jBlYaBCYkMqW8ngNl8bC8cOttOWoQtSO/MIfYAiFopAZYrZKvUheJHgNA1qZfnnpPPdfScU6VEsisYNTzMdQMPJ107@cXnS6GhMwQugk0kpMh4Bkn4MI8IyhDHVMbiqpLeuzed25Zpl52ceto8@twK4kkg0ghihZCRNKR@CP/Ghx0T/QYEYgI4REqIlndRiv89L8@1P2wdCfgB3knA1EDKpYvyLgBZA4DEjUqPeCUqaMtQKThMaRQxBinGzL1iW8GZEyVBwwpqEa3peo7PSebvarkp382pezExt5mZ2v5lP87f8PTyMcmFnitH62ixVFDoAtHWgrGapTKkCwuzs0RN4DlgqtYnUvsmyhV2PliQResKW6dUh7Pq6NYupWYS2zKLodj3Hc9xqh063vCvkWrR/lecRqpkVdsPwDw).
**Explanation:**
Step 1: Surround each value with 0s (including a border of 0s around the entire matrix, unlike the challenge description):
```
2F # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
# (which will use the implicit input-matrix in the first iteration)
ε # Map over each inner list:
0ì # Prepend a 0 in front of each digit
S # Then convert it to a flattened list of digits
Ć # Enclose; append its own head (for the trailing border of 0s)
] # Close both the inner map and outer loop
```
Step 2: Create overlapping 3x3 blocks of this matrix:
```
2F # Loop 2 times again:
ø # Zip/transpose; swapping rows/columns
€ # For each inner list:
ü3 # Create overlapping triplets
} # Close the loop
```
Step 3: Transform each 3x3 block to a quartet of triplets of its middle row; middle column; main diagonal; and main anti-diagonal:
```
ε # Map over each list of blocks:
ε # Map over each 3x3 block:
2F # Loop 2 times:
øí # Rotate the 3x3 block 90 degrees clockwise:
ø # Zip/transpose; swapping rows/columns
í # Reverse each inner row
Ð # Triplicate this 3x3 block
Ås # Pop one, and push its middle row
ˆ # Pop and add this triplet to the global array
Å\ˆ # Do the same for the main diagonal
}¯ # After the loop: push the global array
```
Step 4: Check if either the middle is already 1, or if any sides of a middle row/column/diagonal/anti-diagonal are both 1:
```
ε # Map over the list of triplets:
ι # Uninterleave it from [a,b,c] to [[a,c],[b]]
P # Take the product of each inner list: [a*c,b]
à # Pop and push the maximum
}à # After the map: pop and push the maximum
´ # And clear the global array
# (after which the result is output implicitly)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 82 bytes
```
m->matrix(2*#m~-1,2*#m-1,x,y,m[i=x++\2,j=y++\2]*m[k=i+x%2,l=j+y%2]||m[i,l]*m[k,j])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY5BCoMwFESvIhYhmi8krkol7rsqdGtDcWOJNRIkQgTpRboRSumqB-ptGo2Ci2TeZOZ_8vyoohXXmxpfpcfenS7j_e8s40wWuhUGJdFOPmIKk1ox0IPMBTMYXxKoWD8pj2R-ZwKbIIGaVbgPEj4Mtgb1HEHFw2Xzt1Cq7pH04sxTrWg08o_NwQ9T5xSSKyL_1OltUtosBC_PKZCUAOWWKdAt0u0rWRCIO-l0O57nV7dh13GO8PXT4-j0Dw)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 45 bytes
A port of [@m90's Python (NumPy) answer](https://codegolf.stackexchange.com/a/245610/9288).
```
@(m)abs(diff(diff(kron(m,[i,1;1,i])),1,2))>=2
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKunp/ffQSNXMzGpWCMlMy0NQmQX5edp5OpEZ@oYWhvqZMZqauoY6hhpatrZGv1P04g21DGwNtAxjNXkAnMMUTmGqDIGcI6OAQRbg0gIG2wOjIfEhqiB8IAG/AcA "Octave – Try It Online")
---
# [Octave](https://www.gnu.org/software/octave/), 70 bytes
-5 bytes thanks to @Luis Mendo.
```
@(m)(n=kron(m,e(2)))(i=1:end-1,j=1:end-1)&n(i+1,j+1)|n(i,j+1)&n(i+1,j)
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKunp/ffQSNXUyPPNrsoP08jVydVw0hTU1Mj09bQKjUvRddQJwvG0lTL08jUBgpoG2rWAJlgBkxM83@aRrShjoG1gY5hrCYXmGOIyjFElTGAc3QMINgaRELYYHNgPCQ2RA2EBzTgPwA "Octave – Try It Online")
## how
Takes `m = [0 1 1; 1 0 1; 1 0 0]` as an example:
```
octave:1> m = [0 1 1; 1 0 1; 1 0 0]
m =
0 1 1
1 0 1
1 0 0
octave:2> n = kron(m,e(2)) # Repeats each element by 2x2
n =
0 0 1 1 1 1
0 0 1 1 1 1
1 1 0 0 1 1
1 1 0 0 1 1
1 1 0 0 0 0
1 1 0 0 0 0
octave:3> n11 = n(1:end - 1, 1:end - 1)
n11 =
0 0 1 1 1
0 0 1 1 1
1 1 0 0 1
1 1 0 0 1
1 1 0 0 0
octave:4> n12 = n(1:end - 1, 2:end)
n12 =
0 1 1 1 1
0 1 1 1 1
1 0 0 1 1
1 0 0 1 1
1 0 0 0 0
octave:5> n21 = n(2:end, 1:end - 1)
n21 =
0 0 1 1 1
1 1 0 0 1
1 1 0 0 1
1 1 0 0 0
1 1 0 0 0
octave:6> n22 = n(2:end, 2:end)
n22 =
0 1 1 1 1
1 0 0 1 1
1 0 0 1 1
1 0 0 0 0
1 0 0 0 0
octave:7> (n11 & n22) | (n12 & n21)
ans =
0 0 1 1 1
0 1 0 1 1
1 0 0 0 1
1 0 0 0 0
1 0 0 0 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
żḢS€E?ƝẎ)Z$⁺Ạ€€
```
A monadic Link that accepts a list of lists of `1`s and `0`s and yields a list of lists of `1s` and `0`s.
**[Try it online!](https://tio.run/##y0rNyan8///onoc7FgU/alrjan9s7sNdfZpRKo8adz3ctQAoBET/H@7e8nDHJiAr7HC7@///hgqGCgYQzAUiIWwDLigNIpHYEDUQngEA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///onoc7FgU/alrjan9s7sNdfZpRKo8adz3ctQAoBET/H@7e8nDHJiAr7HC7O9fRyQ93Lj7cDuRmnZz@qHHfoW2Htv3/b6hgwGWgYMjFZQgk4AxDhIgBmKFgAMFcIBLCBuuD8ZDYEDUQngEA "Jelly – Try It Online").
### How?
The basic idea is to insert a value, `f(left,right)`, between each neighbouring pair, `[left,right]`, of each row then to transpose, and then to repeat the same thing again (insert values, transpose).
In order to handle the diagonal requirement, we must have an `f(left,right)` that maintains the necessary information between the steps. That is, when neighbours are not equal we need to remember which one was a one during the first pass and have those values work for us during the second pass.
The code below implements `f(left,right)` as "if `left` equals `right` then yield `left` else yield the sum of each of `[left,right]`" (`ḢS€E?`). This means that the first pass can yield `[1,0]` or `[0,1]` (to be treated as `0`s in the end) in addition to `0` and `1`, and the second pass can then yield `[1,1]` too (to be treated as a `1` in the end).
```
żḢS€E?ƝẎ)Z$⁺Ạ€€ - Link: list of list of 1s and 0s, M
$⁺ - do this twice - f(Current=M):
) - for each Row in Current:
Ɲ - for neighbouring pairs of elements in Row:
? - if...
E - ...condition: equal?
Ḣ - ...then: head
first pass: [0,0]->0
[1,1]->1
second pass: [ 0 , 0 ]-> 0
[ 1 , 1 ]-> 1
[[1,0],[1,0]]->[1,0]
[[0,1],[0,1]]->[0,1]
S€ - ...else: sum each
first pass: [0,1]->[0,1]
[1,0]->[1,0]
second pass: [ 0 , 1 ]->[0,1]
[ 0 ,[0,1]]->[0,1]
[ 0 ,[1,0]]->[0,1]
[ 1 , 0 ]->[1,0]
[ 1 ,[0,1]]->[1,1]
[ 1 ,[1,0]]->[1,1]
[[0,1], 0 ]->[1,0]
[[0,1], 1 ]->[1,1]
[[0,1],[1,0]]->[1,1]
[[1,0], 0 ]->[1,0]
[[1,0], 1 ]->[1,1]
[[1,0],[0,1]]->[1,1]
ż - zip Curent and those together
Ẏ - tighten (flattens by one level, to counter the zip)
Z - transpose
Ạ€€ - all? for each element in each row
0->0 1->1 [0,1]->0 [1,0]->0 [1,1]->1
```
---
Implementing `f(left,right)` as a hash function, with Jelly's `ḥ` built-in, I've only found a 16:
```
ż⁽7&,14ḥ$ƝẎ)Z$⁺Ḃ
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
WS⊞υιE⊖⊗Lυ⭆⊖⊗Lθ⌈E²⌊E²§§υ⊘⁺ιπ⊘⁺λ¬⁼νπ
```
[Try it online!](https://tio.run/##hY7LCsIwEEX3/YosJxAhdduVUEHBSsEviG1oA9P0ldT@fRxTlO6cWRzmcrhM1aqp6hWG8GoNagZXO3j3cJOxDXDOSj@34AUzPEtKCh0UaoBcV5PutHW6hrz3TyTetG0cuZxzwbaCP@oY1UKtpvNd7D3Saez@PLmrrfUKX9IrF4ULlZToZzCCDbFlH6Jg997BefQKZ7Cb8psshDSVtEkqCTKRkRs@IVEm4bDgGw "Charcoal – Try It Online") Link is to verbose version of code. Takes I/O as a list of newline-terminated strings of `0`s and `1`s. Explanation:
```
WS⊞υι
```
Input the binary matrix.
```
E⊖⊗Lυ⭆⊖⊗Lθ⌈E²⌊E²§§υ⊘⁺ιπ⊘⁺λ¬⁼νπ
```
Loop over the dimensions of the expanded matrix, calculating the positions of the possible adjacent `1`s, and for each output `1` if one pair of positions is both `1`. This is equivalent to the following operations, starting with:
```
WX
YZ
```
This first gets expanded by duplication, i.e.
```
ABC WWX
DEF=WWX
GHI YYZ
```
Then for each position in the grid, two pairs of cells are checked: the cell itself and the one diagonally below right, and the cells below and to the right:
```
A -> AE | BD = WW | WW = W
B -> BF | CE = WX | XW = WX
D -> DH | EG = WY | WY = WY
E -> EI | FH = WZ | XY as desired
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-xP`, 25 bytes
```
{MX B*R_MPaZb}MP_WV_MaWVa
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSbkWAUuyCpaUlaboWO6t9IxSctILifQMSo5JqfQPiw8PifRPDwxIh8lBle6OVoqMNrA2tDWOtow2tDeC0QWws3CwA)
### Explanation
Port of [Neil's Charcoal answer](https://codegolf.stackexchange.com/a/245605/16766).
```
{MX B*R_MPaZb}MP_WV_MaWVa
a First command-line input (eval'd as list due to -x flag)
WVa Weave with itself (double each row)
M Map to each row:
_WV_ Weave with itself (double each column)
{ }MP Map to each pair of rows:
aZb Zip the two rows together
MP Map to each pair of [upper lower] pairs (i.e. 2x2 submatrix):
R_ Reverse the first pair
B* Multiply itemwise by the second pair
MX Maximum (1 if either product is 1, 0 otherwise)
```
] |
[Question]
[
### Introduction
This challenge is inspired by the Meta Stack Exchange question [The longest consecutive days streak](https://meta.stackexchange.com/q/362489/295232); it turns out that the URL `https://codegolf.stackexchange.com/users/daily-site-access/[user id]`, where the last number is your user ID (found in the URL of your profile) contains information about which days you visited the site, in the following format:
```
var visited = {2015:{6:{3:1,8:1,12:1,13:1,18:1,19:1,21:1,22:1,23:1,24:1,26:1},7:{7:1,8:1,9:1,10:1,11:1,12:1,14:1,16:1,19:1,21:1,23:1,27:1,28:1,29:1,30:1},8:{1:1,2:1,3:1,5:1,7:1,17:1,19:1,23:1,26:1,28:1,30:1},9:{5:1,6:1,7:1,14:1,22:1,25:1,29:1,30:1},10: ...
```
(When viewed in a browser, the document seems empty; try viewing the source instead. Unless you are a ♦ moderator, you can only see this information for your own account.)
The string has a rather peculiar format but presumably it's an easy way to populate the calendar:
[](https://i.stack.imgur.com/l2hIR.png)
The information can be used to calculate the longest consecutive days streak, i.e. the one that determines if you get the [Fanatic badge](https://codegolf.stackexchange.com/help/badges/23/fanatic). The linked question has a working JavaScript example by user @ShadowWizard.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply: the shortest code wins.
### Input
A string with the exact format provided by Stack Exchange, e.g. `{2015:{6:{3:1}}}`. Top level keys are years, second level keys are months, third level keys are days. All values are `1`. You may assume the dates are not earlier than July 31st, 2008, which is when the [first Stack Overflow question](https://stackoverflow.com/questions/1/where-oh-where-did-the-joel-data-go) was posted. You may also assume there's at least one day in the input; the information is only provided to registered users, who must have visited the site at least once.
### Output
The length of the longest streak, i.e. consecutive days in the input. You may choose to return it as a number or a string.
### Test cases
(besides your own streak on CGCC of course; you should be able to verify if you're eligible for the Enthusiast and Fanatic badges or not)
| Input | Output |
| --- | --- |
| `{2015:{6:{3:1}}}` | 1 |
| `{2015:{6:{3:1}},2016:{6:{3:1}}}` | 1 |
| `{2015:{6:{3:1},7:{3:1}}}` | 1 |
| `{2015:{6:{3:1,5:1}}}` | 1 |
| `{2015:{6:{3:1,4:1}}}` | 2 |
| `{2015:{2:{28:1},3:{1:1}}}` | 2 |
| `{2016:{2:{28:1},3:{1:1}}}` | 1 |
| `{2016:{1:{30:1},2:{1:1}}}` | 1 |
| `{2016:{4:{30:1},5:{1:1}}}` | 2 |
| `{2016:{4:{30:1},6:{1:1}}}` | 1 |
| `{2016:{12:{31:1}},2017:{1:{1:1}}}` | 2 |
| `{2016:{12:{31:1}},2018:{1:{1:1}}}` | 1 |
| `{2016:{11:{29:1},12:{30:1,31:1}},2017:{1:{1:1,2:1,4:1}}}` | 4 |
| `{2100:{2:{28:1},3:{1:1}}}` | 2 |
| `{2400:{2:{28:1},3:{1:1}}}` | 1 |
[Answer]
# [Python 2](https://docs.python.org/2/), ~~186 184 179 177 173 172~~ 162 bytes
-10 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)! (avoiding use of `.items`)
```
x=input()
from datetime import*
a=sorted(date(y,m,d)for y in x for m in x[y]for d in x[y][m])
print max(map(len,`[d+timedelta(1)in a for d in a*2]`.split('s')))/6
```
**[Try it online!](https://tio.run/##PY1hC4MgEIa/9yv8ljbZOhuNCf2SCBI0JqRJOUik3950sMEd9773vMe54F@LZee5d9q6t8ekmNbFICm88toopI1bVl8VotvSVBJnggM1VJJpWVFA2qIdZWm@sg9DNvJnejOQwq3aemTEjo1weFaWjr285AdSzV5gICkt0P9QVGwYr5ubtcflVhJCbu15RlZDyyMAj@zJ4aDAeGxqDrSBZA@a@CPxXEBZ6nteHx8 "Python 2 – Try It Online")** Or see the [test-suite](https://tio.run/##hZDhaoMwFIV/16cI7IdJFzYTre2EPkknNDQpDRgVmzFF@uzupkNXu2qDYC7nu@fk3rKxpyLn3aGQauv7/mdXb3VefllMvGNVGCSFVVYbhbQpi8ouPbE9w19J7BTcUEMlORYVapDOUY3c1VyvuyZ1heyLnUmJV1Y6t8iIGhtR4kzldL@Try5AqswKzAjQAg2NYsnT/du5zLTF/tknhLzHHbzT@z7pTCGWeAiOqtUBuxFI1/KArZI2TtowYZfLZeHOC1ow706hUMZ34AOOrucBupqLodFI5b3K4ds49zBp2a37LxHPEKwnGCQEjuBTRNQTq6mUgYgnU8A9ZP3C1tfYgby1GoObf@CfIwj8w4VeWyCePgiAqfrtQXMEzSwIniwumiXGIz2PhaZF9AM "Python 2 – Try It Online").
### Huh, how?
In Python 2 `input` implicitly attempts an `eval` on the string which, in this case, will produce a nested dictionary.
`a` is then a list of the dates in order (`sorted(...)`), this is formed by inspecting the nested dictionaries in a nested `for` loop, and passing the resulting parts of the dates to `date(year, month, day)`.
`[d+timedelta(1)in a for d in a*2]` forms a list of `boolean`s which identify whether the next date is present for each date in the sorted dates repeated twice, `a*2`.
Note that the final value of `a` will always be `False`. The reason for repeating `a` is to avoid something later (see the final paragraph).
``[...]`` gets the Python string representation (AKA `repr`) of that list - for example, something like `"[False, True, True, False, False, False, True, True, False, False]"` for an input with three consecutive dates between two others.
`.split('s')` splits the resulting string at occurrences of the `'s'` character - so for the above, that would be `['[Fal', 'e, True, True, Fal', 'e, Fal', 'e, Fal', 'e, True, True, Fal', 'e, Fal', 'e]']`.
`map(len,...)` simply gives us a list of the lengths of the strings in the above list - so for the above, that would be `[4, 18, 6, 6, 18, 6, 2]`.
`max(...)` gives the maximum value of that list - so for the above, that would be `18`.
To find the number of consecutive days we want to count how many `True`s there were in that longest section and then add one. In the above example, we can simply divide by six (the length of either `'True, '` or `'e, Fal'`), hence the `/6` at the end.
If the longest run of consecutive dates is at the left of the sorted dates we'd get something like `'[True, True, Fal'` (or `'[Fal'` when no dates at all are consecutive), which would be two shy of what we need, so if we were to perform all of this across `a` rather than `a*2` we'd need to add two before performing the integer division (e.g. `(...+2)/6`). This wouldn't affect any other results but costs one more byte than simply repeating `a` with `a*2`, whereupon we'll get the longer string later on - this is guaranteed by the fact that `d+timedelta(1)` for the maximal `d` will give `False`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~45~~ 43 bytes
*Thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for pointing out a mistake, now corrected.*
```
j':1?'0YXU2e"@Y:wXHx2e"H@Y:g3$YO]]vtf-FT#XM
```
[Try it online!](https://tio.run/##y00syfn/P0vdytBe3SAyItQoVckh0qo8wqMCyPIAMtONVSL9Y2PLStJ03UKUI3z//682MjA0s6o2NLSqNrK0MqzVMTSyqjY2sDLUMTYEcmt1gPLmQHkQMtQxAmITkHAtAA) Or [verify all test cases](https://tio.run/##y00syfmf8D9L3crQXt0gMiLUKFXJIdKqPMKjAsjyADLTjVUi/WNjy0rSdN1ClCN8/7uE/K82MjA0tao2s6o2tjKsra3lQhPQAXLNcMvrmGOX0DHFJmiCImgERBYgM4ytqg0RMmb4ZAyBBhmAZIzQZUxgMqY4ZcwwTAOaYmwI86Y52Hh8KiywqQCKGFmCjAerBVqkg8VIoHuRvG9oYIDDkybYZQA).
### How it works
```
j % Input as (unevaluated) string
':1?' % Push this string. Will be interpreted as regexp
0 % Push 0. Will be interpreted as character 0 (equivalent to space)
YX % Regexprep: replace ':' or ':1' by character 0
U % Evaluate string. Gives nested cell array
2e % Reshape as a 2D cell array with 2 rows (in column major order)
" % For each column. Each column contains a year and a (nested) cell array
@ % Push current column, as a cell array
Y: % Unbox: pushes year, then the cell array
w % Swap
XHx % Copy to clipboard H and delete
2e % Reshape cell array as a 2D cell array with 2 rows
" % For each column. Each column contains month and a cell array (of days)
H % Push year from clipboard
@ % Push current column, as a cell array
Y: % Unbox: pushes month, then the cell array of days
g % Convert cell array to numerical vector of days
3$YO % 3-input datenum: converts year, month, days to serial date numbers
] % End
] % End
v % Concatenate stack into numerical vector of serial date numbers
tf % Duplicate, find. Gives vector of the same size containing 1, 2, 3...
- % Subtract, element-wise
FT#XM % Second output of mode function: number of repetitions of the mode
% Implicit display
```
[Answer]
# JavaScript (ES6), 122 bytes
*Thanks to @tsh for a bug fix and some optimizations*
```
o=>(D=k=1,M=g=(o,c)=>Object.keys(o).map(c))(o,y=>g(Y=o[y],m=>g(Y[m],d=>M>(D-(D=Date.UTC(y,m-1,d))<-1e8?k=1:++k)?0:M=k)))|M
```
[Try it online!](https://tio.run/##rdNNT4MwGMDxu59ixzZ7YJS3IbHs4K7Eix7MsgNCtzjGurjFhCCfHR9YWGIErArhACH8eP6h3UXv0Sl@ez2etYNMRLXhleQBWfKUMwj5lhMJMeXBw8tOxGc9FfmJSKpn0ZHElOLDnAdb8szlKl9D1lyvsjUkPAhR0RBaRmehPz3ekxwyjUFC6Z3GhLfAD/jTaUoXhh/ylFL6EVaxPJzkXuh7uSUbUpgGc/zC9QvLZ2VZThQPSiez2YTdDGqAt64KrqLBXHVGBQ0c5VoVzf6lZnZrJp5enWr5BVMh@zX3zxrr1hiWGrVmjqHZreaMUXrV3FFKsdBi7fqdN@mD6uBsXzVPVeubDd82b@vUxsVo6BgV/1G7Ji@a/U1jhjHierP/of24s@q9CggDdgMz@uSLZlWf "JavaScript (Node.js) – Try It Online")
### Commented
```
o => ( // o = input object
D = // D = previous day, as an integer
k = 1, // k = streak length
M = // M = maximum streak length
g = (o, c) => // g is a helper function which applies a callback
Object.keys(o).map(c) // function c to each key of an object o
)( // 1st call to g with ...
o, // ... the input object o
y => // for each year y,
g( // do a 2nd call to g with ...
Y = o[y], // ... the object of months o[y]
m => // for each month m,
g( // do a 3rd call to g with ...
Y[m], // ... the object of days Y[m]
d => // for each day d,
M > ( // test whether M is greater than the updated k
D - ( // subtract from D ...
D = Date.UTC( // ... the new D corresponding to
y, m - 1, d // this year, this month and this day
) //
) < -1e8 ? // if the difference is less than -10**8 ms:
k = 1 // reset k to 1
: // else:
++k // increment k
) ? // if M is greater than the new value of k:
0 // do nothing
: // else:
M = k // update M to k
) // end of 3rd call
) // end of 2nd call
) | M // end of 1st call; return M
```
] |
[Question]
[
Let us say that we have a particular set of functions on strings. These functions are kind of like fill in the blanks or madlibs, except that they only take one input and use that to fill in all of their blanks. For example we might have a function that looks like
```
I went to the ____ store and bought ____ today.
```
If we applied this function to the string `cheese` the result would be:
```
I went to the cheese store and bought cheese today.
```
We can represent these functions as a non-empty list of strings, where the blanks are simply the gaps in between strings. For example our function above would be:
```
["I went to the ", " store and bought ", " today."]
```
With this representation there is only one representation for every function of this sort and only one function for each representation.
A really neat thing is that the set of such functions is closed under composition. That is to say composition of two of our functions is always another one of these functions. For example if I compose our function above with
```
["blue ", ""]
```
(the function that prepends `blue` to the input)
We get the function:
```
["I went to the blue ", " store and bought blue ", " today."]
```
These can get a little more complex though. For example if we compose the first function with
```
["big ", " and ", ""]
```
The result is
```
["I went to the big ", " and ", " store and bought big ", "and", " today."]
```
## Task
Your task is to take two functions as described as non-empty lists of strings and output their composition as a non-empty list of strings.
For the purpose of this challenge a list can be any ordered container that permits
duplicates and a string may be a native string type, a list of characters or a list of integers.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") answers will be scored in bytes with fewer bytes being better.
## Test cases
```
["","xy"] ["ab",""] -> ["ab","xy"]
["x","y","z"] ["a","b"] -> ["xa","bya","bz"]
["xy"] ["ab"] -> ["xy"]
["","",""] ["a",""] -> ["a","a",""]
["x",""] ["","",""] -> ["x","",""]
["x","y","z"] ["a","b","c"] -> ["xa","b","cya","b","cz"]
["x","x","x"] ["a"] -> ["xaxax"]
["w","x","y","z"] ["ab","cd","e"] -> ["wab","cd","exab","cd","eyab","cd","ez"]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
j0j@ṣ0
```
A dyadic Link accepting the *first* function representation on the *right* and the *second* function representation on the *left* which yields the resulting function representation. Each function representation is a list of lists of characters (Jelly has no other strings).
**[Try it online!](https://tio.run/##y0rNyan8/z/LIMvh4c7FBv8PLz866eHOGf//RyslJinpKCnFAllAuqJSKRYA "Jelly – Try It Online")** (the full-program arguments are given in Python notation; strings become lists. The footer shows a Python representation of the Link's output.)
Here is a [test-suite](https://tio.run/##y0rNyan8/z/LIMvh4c7FBv8PL3fQz3J41LTmUeM@JaWsRw1zdYDcxn3RsZqR//9HR0crKekoVVQqxepEKyUmAdlKsbFcOkDhCiC7EoirIFJAVhJcCq4cKgDSBtIJVYhsBFgQJo/bZB2lZGRpCIZIQ4XLocJIOsHaUoBEKkhRLAA "Jelly – Try It Online") which reformats the Link's output like the inputs.
### How?
Takes advantage of Jelly's mixed type lists to allow the entire domain of representations (any list of lists of characters) by using the integer zero as a place-holder:
```
j0j@ṣ0 - Link: b, a e.g. b = [['a','b'],['c','d'],['e']]
- ...and a = [['w'],['x'],['y'],['z']]
(i.e. test-case ["w","x","y","z"] ["ab","cd","e"])
j0 - join b with zeros ['a','b',0,'c','d',0,'e']
j@ - join a with that ['w','a','b',0,'c','d',0,'e','x','a','b',0,'c','d',0,'e','y','a','b',0,'c','d',0,'e','z']
ṣ0 - split at zeros [['w','a','b'],['c','d'],['e','x','a','b'],['c','d'],['e','y','a','b'],['c','d'],['e','z']
(i.e.: ["wab","cd","exab","cd","eyab","cd","ez"])
```
---
If we needed to deal with any of Jelly's mixed lists (including those of any depth or shape) we could use this eight byter: `j,©⁹jœṣ®` which uses the paired arguments as the place-holder.
[Answer]
# [Haskell](https://www.haskell.org/), 78 bytes
```
(a:b:r)#t@(x:s)|s>[]=(a++x):init s++((last s++b):r)#t|z<-a++x++b=(z:r)#t
x#_=x
```
[Try it online!](https://tio.run/##hU/tCoMgFP2/pxDbD6N6gVhj7xExbAWLtTYySKV3b9dbhrXGEuV0rufDOxePsq7HkfE4j1vf6y5MxsIfxDnNEsaDQPpx1VQdEUHAWM0FotzHu4M@ReYKEAnTSB2kd03k@ORVQxJSvA7k3VZNR44kpTSkUtGMeIB5Dn@A118U2ZG56GolcAq2tnrA@UqPWom8wlNvHJzoba7rsAk2NbGpTf1RGibTdNt6li4@e5l2@P/FIb0tHs6LDa8WpL@dpm2d9ltwWGtlPytXPTCigKMEBpW9w0kHKwebTuMH "Haskell – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~60~~ 58 bytes
```
lambda a,b:(v:='&'.join(a+b)+'$').join(b).join(a).split(v)
```
An unnamed function accepting two lists of strings, `a` and `b`, which returns a list of strings.
**[Try it online!](https://tio.run/##LcdBDoIwEADAr/Rg3N3QcPFiSHgJctiF1tZg29SK8fUloKfJpG9xMVyuKVfb3@rCT5lZsZYO166HM7SP6ANyI9TACehX@cvUvtLiC65UU/ahoMUBWCbQCmZjd@7Ow6jVADGY/eUTD1w2x218ZxiJ6gY "Python 3.8 (pre-release) – Try It Online")** Or see the [test-suite](https://tio.run/##fY9ND4IgGMfP@ikYa8EzyUuX5mZfRD1A5qIVMnOmfXlChJmXDg/wf/nB0FN/a9XxpDvT5KV58KeoOeJMZHTIcrIn6b2VivJEQEJ2BBYp/M4hfemH7OkApmk7yyGBpEI0jmiBMcPjhCuGCsyFFbgC5oLRisnOx4f2KNZwRYI1szMeypuLFjtU/r3A8GVTWMYXQvD2wS/t0NouV1eDLI50J1VP5/8yREp1OBOGGqfBGQTMFw "Python 3.8 (pre-release) – Try It Online").
### How?
First forms a separator string, `v`, which cannot be found inside `a` or `b`. Then forms a string by joining up the strings in `b` with copies of `v`. Then forms a string by joining up the strings in `a` with copies of that. Finally splits that string at instances of `v` to give a list of strings.
While ensuring `v` is not in `a` or `b` we must also ensure that `v` wont make us split early in the case where all the strings in `a` and `b` are equal. To do so we form `v` by joining all the strings in both lists with instances of a string (here `'&'`) and add an extra, different character (here `'$'`). Note that doing either in isolation is not enough as all strings in the inputs could equal the chosen character.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), [~~4~~ ~~15~~ ~~19~~ ~~9~~ 11](https://www.youtube.com/watch?v=hlv672jqbtE) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
«TýR©ý¹sý®¡
```
Unlike the Jelly answer, 05AB1E's string `"0"`, integer `0`, and float `0.0` are all (somewhat) equal, so I can't split/join by an integer. This is why we had the +15 bytes as workarounds, although I've golfed it back to 9 bytes now. Thanks to *@JonathanAllan* for finding 2 bugs.
[Try it online](https://tio.run/##yy9OTMpM/f//0OqQw3uDDq08vPfQzmIgse7Qwv//o5XKlXSUKoC4EoirlGK5opUSk4DM5BQgkaoUCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCsUtoscvRBf8PrbY8vPfQysN7I4qB9LpDC//r/I@OjlZS0lGqqFSK1YlWSkwCspViY3UUgMIVQHYlEFdBpICsJLgUXDlUAKQNpBOqENkIsCBMHrfJOkrJyNIQDJGGCpdDhZF0grWlAIlUmKKSjMxiIB9MgAwuSS0uAat1BHKcgNgZiF2A2BWI3bA4H9WlMXlADowASaMKQBQZGgC5MAKkyMAQyIYRsbGxAA).
**Explanation:**
```
« # Merge the two (implicit) input-lists together
Tý # Then using a "10" delimiter join all strings together
R # Reverse this string
© # Store this string in variable `®` (without popping)
ý # Use this string as delimiter to join the second (implicit) input-list
¹sý # Then join the first input-list by this entire string
®¡ # And split it back on variable `®` so it's the expected list of strings
# (after which this result is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~62~~ 61 bytes
```
""<>#&/@Flatten[#~(R=Riffle)~I/.I->#2~R~I]~SequenceSplit~{I}&
```
[Try it online!](https://tio.run/##dYxPC4IwGMbvfox3IAUzoXOKp2C30KN4mLbRQKVikTa2r76mLvHS4X15@D1/OipvrKNSNNTyxAKcUhTG2bmlUrK@RGaXJ7ngvGV7Q@IDiVJ0NLkhlSnY48X6hhX3VkijiA7t5Sl6WaIo5VmGKjejAqUAMAwjaKyA1k6D1njCg9Oju89iOVWv1hr3YKpNTR/cTszw5/9fxtBs7eUW2@O3x5vmXLu6x1wo0PYL "Wolfram Language (Mathematica) – Try It Online")
-1 thanks to [Roman](https://codegolf.stackexchange.com/questions/188904/composing-fill-in-the-blanks/188941#comment452512_188941)
---
Though it's not a valid output, this returns a function that actually does the job.. (34 bytes)
```
(g=a""<>a~Riffle~#&)[#]@*g[#2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPdNvH9pIVKSjZ2iXVBmWlpOal1ymqa0cqxDlrp0cpGsWr/A0szU0scAooy80qilXXtNNIcHJQ1HZTi45Vi1fQdqrmqq5WUdJQqKpVqdaqVEpOAbKXaWh2QcAWQXQnEVRApICsJLgVXDhUAaQPphCpENgIsCJPHbbKOUjKyNARDpKHC5VBhJJ1gbSlAIhWoiKv2PwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
Adapts [Jonathan's approach](https://codegolf.stackexchange.com/a/188923/58974).
```
qVqN²)qN
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cVZxTrIpcU4&input=WyJ3IiwieCIsInkiLCJ6Il0gWyJhYiIsImNkIiwiZSJdCi1R)
```
qVqN²)qN :Implicit input of arrays U & V (N=[U,V])
q :Join U with
Vq : V joined with
N² : Push 2 to N (modifying the original), which gets coerced to a string
> e.g., N=[["a","b"],["c","d"]] -> N=[["a","b"],["c","d"],2] -> "a,b,c,d,2"
) :End join
qN :Split on the modified N, which, again, gets coerced to a string
> e.g., N=[["a","b"],["c","d"],2] -> "a,b,c,d,2"
```
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
[a]#(c:d)=(a++c):d
(a:b)#c=a:b#c
[a]%b=[a]
(a:b)%c=[a]#c#(b%c)
```
[Try it online!](https://tio.run/##JYpdCoAgEITfPcZugmInEDyJ@LBuQVFJVNDP5W0jGL75GGagfernudZICQ37zgZDzrH1nTLks0UOUshKDjoH4b9r/hwZTdZs60JjCes2lqOJcN3QguR8IOn4GWUBQ6ov "Haskell – Try It Online")
Here is my Haskell answer. It works on any type of list.
[Answer]
# [J](http://jsoftware.com/), ~~44~~ ~~43~~ ~~42~~ 29 bytes
```
_<;._1@,(;@}:@,@,.(,_&,)&.>/)
```
[Try it online!](https://tio.run/##fZDBDoIwDIbvPEXjgbJkTL2OaUhMPHnyBQggoF48spH47NjBBuNilo61fP/fde9xJxA6OElA4HAASZEKuNxv17FQmSiOOU@y/CtznnOR8CLmLBbnPRtZFLVW18VCJqWIX4LqVGzq5wcSLCvMUBtkkEpKfdLC/Ac9p0vKKkM7YDV4XFPRUAxOYhkv4VKtxsrbKuvrCEJIwjL/xeAWOGXOMxToCVxZvZBOFd7YCiorqM0m@z8AAZshSlqhYA43zdKvnx6sftDW6OBsgvPSt3c2Ye8Vw/EH "J – Try It Online")
*-13 bytes thanks to miles!*
This approach uses integers and is due to miles.
# original approach with strings
```
g=.[:}.@,,.
f=.(<@0<@;;._1@,];@g<"0@[)<@0<@g]
```
[Try it online!](https://tio.run/##fZBBDoMgEEX3noJ0M5pQYreCCfcwphGrNt10KZj07HRA0OmmISAf3//D8PJ@aUXXfITmXBRzK0qla6WlFPeb5r3Ui7rUuqvi6dL7opjG55uVMBiQYB1U7NqgzGJm@x/InB1QGYcrA7Nl3OKhw7klS2CyhTfqDFY5VoXcRCCClkrmL5BbQFQpkxpsBE/WHmRy0RsHgwmG0f2o/w0g8NPEgIMa9pm6Oeqt8cHGBy6TJXtH9kfdNcXQ2icG/gs "J – Try It Online")
*Note: I've adjusted -3 off the TIO to account for `f=.`*
Uses Jonathan Allen's method, adapted for J.
This was surprisingly difficult to golf, since J doesn't have a built in "join" method, and I'd be curious to see if it can be improved significantly.
`g` is helper verb that gives us "join"
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~85~~ 79 bytes
```
([a,...b],[c,...d])=>b.map(e=>r.push(r.pop(r.push(r.pop()+c,...d))+e),r=[a])&&r
```
[Try it online!](https://tio.run/##fY1NDsIgEIX3nqKZRcOkyAUMvQhhAZT6k1oIVNN6eZTW2Bh/NjPv5X0z76SuKppw9MO2d41NLU9EKMoY05IKk0UjkdeanZUnlteB@Us8kMdynrwZrBYcsbJIAxdKYlmGtDOuj66zrHN70hIBQAsYJ5C0EKB0diARNx/cmKMpj9sTzlr/gNeHX/O5Zq56ffrTulDrDWK6Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript, 37 bytes
[Also](https://codegolf.stackexchange.com/a/188932/58974) adapts [Jonathan's approach](https://codegolf.stackexchange.com/a/188923/58974).
```
a=>b=>a.join(b.join(a+=b+0)).split(a)
```
[Try it online](https://tio.run/##fY9BDoMgEEX3nsKwgmhJL4C7noKwAMRWY8QIaaGXpwi2GhddDHzmvz8TBv7kRi79bC@TblXoSOCkEaTheND9BEW@eEVEdUUIm3nsLeQoWGWsIZQWZUkBqIHzgNUUcBE1YEXUyXHx6WO9sxuVOLq/0N5b8@uIDT/NSv0v8ndLDeSJyJWJ3XltziGfwm081MqxIv0Vd3q5cfmAkLraM0QaqSejR4VHfYcddAh6hFD4AA)
[Answer]
# Perl 5 (`-lp`), 20 bytes
As @JonathanAllan commented, this is a full-program using, for IO, a tab as a list separator and a newline to separate the two lists.
```
chop($n=<>);s/ /$n/g
```
[TIO](https://tio.run/##PYrLCoAgFAXX536Hi1qEq1Y9/kVNKhCVDLI@vptBxGyGOSfazbXMZgmxEn7ox7pLElJ4OTMraMo4cZHSIOSTAFIo7ZVvgYYpXiBFB/6/mWDpDnFfg0/cuPgA)
the tab and newline were chosen because more convenient to check test cases, otherwise could be changed to non-printable characters `\1` and `\2`.
(`-02l012p`)
```
chop($n=<>);s//$n/g
```
[TIO](https://tio.run/##PYpJCoAwEATpeYsHPUhU8OTylyQGFUISVHB5vGMEkboU1R3MYmtmPfmQJq5r@6xZBUTixMgsoejAiYukAuE4CSCJ2F75Fijo6BGStOP/6wGGbh@22buV86KyRVmFBw)
How it works,
* `-02` : to set input record separator to `\2`
* `-l` : to remove input separator from default argument `$_` and to add output record separator to default output
* `-012` : to set output record separator to `\012` (`\n`) so that output is easier to check
* `-p` : to print default argument
* `$n=<>;` : to read next record and to assign to `$n`
* `chop$n;` : to remove separator from `$n`
* `s/\x1/$n/g` : to replace all occurences of `\1` with `$n`
[Answer]
# JavaScript (ES6), ~~62~~ 59 bytes
*Saved 3 bytes thanks to @Shaggy*
This is a fixed version of [Luis' answer](https://codegolf.stackexchange.com/a/188905/58563) (now deleted) to support all characters.
```
a=>b=>a.map(e=escape).join(b.map(e)).split`,`.map(unescape)
```
[Try it online!](https://tio.run/##jZBBDoIwEEX3nsJ01SYVTwAXMSYUrAaClAhK20O4ducNPJs3wKGt2pBihLT5zJ8@fqdkF9bmp6LpVrXY8WEfDyxOsjhh0ZE1mMe8zVnDSVSKosaZLRIStU1VdClNTeFcu64hF3UrKh5V4oD3eIMQRVKhLQHJMvgASZaTZ71eOndsXUwREgwFSzsMyGyKMQhpLGV2HQJ9gwRS@KBQjDG8ye8yzN8ETNsQvIolfGhhhnz7/02DotxHedMYLfVRegZolwPOZmLwBgC9A/ipzN92sHGLM4DeK0tPK0/r8OTp8367WjaoB/01u3eDOzO8AA "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Take a positive integer \$k\$ as input. Start with \$n := 1\$ and repeatedly increase \$n\$ by the largest integer power of ten \$i\$ such that \$i \le n\$ and \$i + n \le k\$.
Repeat until \$n = k\$ and return a list of all intermediate values of \$n\$, including both the initial \$1\$ and the final \$k\$.
During this process, growth will initially be limited by the former inequality, and only afterwards by the latter; the growth will take the form of an initial "expansion" period, during which \$n\$ is increased by ever-larger powers, followed by a "contract" period, during which \$n\$ is increased by ever-smaller powers in order to "zoom in" on the correct number.
## Test Cases
```
1 => [1]
10 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
321 => [1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 20, 30, 40, 50, 60, 70, 80, 90,
100, 200, 300, 310, 320, 321]
1002 => [1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 20, 30, 40, 50, 60, 70, 80, 90,
100, 200, 300, 400, 500, 600, 700, 800, 900,
1000, 1001, 1002]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins.
[Answer]
# [Haskell](https://www.haskell.org/), 72 68 64 63 bytes
```
f=(1!)
c!t|t==c=[c]|t>c=c:(c+10^(pred.length.show.min c$t-c))!t
```
[Try it online!](https://tio.run/##DcfRCkAwFADQd19xVx62ZBlv6voRUbrGZGZxy4t/H@ftuOnerfcpLSiNUBkJfhmRsKfh5Y6QWkmFqUYZLztrb8PKTt/ufPSxBaCcS1JKcDqmvwjx2gJDDgs0tUkf "Haskell – Try It Online")
Thanks Sriotchilism O'Zaic for -4 bytes!
### Usage
```
f 321
[1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,200,300,310,320,321]
```
### Explanation
```
c!t -- c=current number, t=target number
|t==c=[c] -- Target is reached, return last number
|t>c=c:(c+10^(pred.length.show.min c$t-c))!t
c: -- Add current number to list
min c$t-c -- The minimum of the current number, and the difference between the current number and the target
length.show. -- The length of this number
pred. -- Minus 1
10^( ) -- Raise 10 to this power
c+ -- Add that to the current number
( )!t -- Recursion
```
[Answer]
# JavaScript (ES6), 50 bytes
```
f=n=>n?[...f(n-(1+/(^10)?(0*$)/.exec(n)[2])),n]:[]
```
[Try it online!](https://tio.run/##Hc2xDoIwEADQ3a@4gYQ7bUuLmwaY/IqmBlKLQsjVgDEmhG@vxu1tb@ze3eLn4fmSHG8hpb7iqubGKqV6ZInmUODVaGpQ7zMqVPgEj0y2dESC3cm6dLZGgNECjuUfunQ71cf50vkHMlQ1@MhLnIKa4h3bbOUNpKwhW38DqTEOjDnktLVE6Qs "JavaScript (Node.js) – Try It Online")
## How?
### Theory
The following steps are repeated until \$n=0\$:
* look for the number \$k\$ of trailing zeros in the decimal representation of \$n\$
* decrement \$k\$ if \$n\$ is an exact power of \$10\$
* subtract \$x=10^k\$ from \$n\$
### Implementation
The value of \$x\$ is directly computed as a string with the following expression:
```
+---- leading '1'
|
1 + /(^10)?(0*$)/.exec(n)[2]
\____/\___/
| |
| +---- trailing zeros (the capturing group that is appended to the leading '1')
+--------- discard one zero if n starts with '10'
```
**Note**: Excluding the leading `'10'` only affects exact powers of \$10\$ (e.g. \$n=\color{red}{10}\color{green}{00}\$) but does not change the number of captured trailing zeros for values such as \$n=\color{red}{10}23\color{green}{00}\$ (because of the extra non-zero middle digits, `'10'` is actually not matched at all in such cases).
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
```
f=lambda k,n=1:n<k and[n]+f(k,n+10**~-len(`min(n,k-n)`))or[n]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVsnz9bQKs8mWyExLyU6L1Y7TQMopG1ooKVVp5uTmqeRkJuZp5Gnk62bp5mgqZlfBFTzv6AoM69EIU3DUJMLzjRAsI2NUCQMjDT/AwA "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~48~~ 41 bytes
```
->\k{1,{$_+10**min($_,k-$_).comb/10}...k}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX9cuJrvaUKdaJV7b0EBLKzczT0MlXidbVyVeUy85PzdJ39CgVk9PL7v2f3FipUKahqGmNReUZQBnGhshCxsYaVr/BwA "Perl 6 – Try It Online")
### Explanation:
```
->\k{ } # Anonymous code block taking k
1, ...k # Start a sequence from 1 to k
{ } # Where each element is
$_+ # The previous element plus
10** # 10 to the power of
.comb # The length of
min($_,k-$_) # The min of the current count and the remainder
/10 # Minus one
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function. Prints numbers on separate lines to stdout.
```
{⍺=⍵:⍺⋄⍺∇⍵+10*⌊/⌊10⍟⍵,⍺-⎕←⍵}∘1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR7y7bR71brYD0o@4WENnRDuRrGxpoPerp0gdiQ4NHvfOBQjpASd1HfVMftU0A8mofdcww/J8G5vQBRT39H3U1H1pv/KhtIpAXHOQMJEM8PIP/pykYcunq6nIBaQMow9gIIWRgBAA "APL (Dyalog Unicode) – Try It Online")
`{`…`}∘1` anonymous infix lambda with 1 curried as initial \$n\$:
`⍺=⍵` if \$k\$ and \$n\$ are equal:
`⍺` return (and implicitly print) \$k\$
`⋄` else:
`⎕←⍵` print \$n\$
`⍺-` subtract that from \$k\$
`⍵,` prepend \$n\$
`10⍟` \$\log\_{10}\$ of those
`⌊` floor those
`⌊/` minimum of those
`10*` ten raised to the power of that
`⍵+` \$n\$ plus that
`⍺∇` recurse using same \$k\$ and new \$n\$
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1[=ÐIαD_#‚ßg<°+
```
Port of [*@PaulMutser*'s (first) Haskell answer](https://codegolf.stackexchange.com/a/182584/52210), so make sure to upvote him!!
[Try it online](https://tio.run/##yy9OTMpM/f/fMNr28ATPcxtd4pUfNcw6PD/d5tAG7f//jY2MAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6mj5F9aAuHo/DeMtj08ofLcRpd45UcNsw7PT7c5tEH7f@2hbfb/ow11DA10jI2MgZSBUSwA).
Outputs the numbers newline delimited.
If it must be a list, I'd have to add 3 bytes:
```
X[DˆÐIαD_#‚ßg<°+}¯
```
[Try it online](https://tio.run/##AScA2P9vc2FiaWX//1hbRMuGw5BJzrFEXyPigJrDn2c8wrArfcKv//8zMjM) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f@IaJfTbYcnVJ7b6BKv/Khh1uH56TaHNmjXHlr/X@fQlv/RhjqGBjrGRsZAysAoFgA).
**Explanation:**
```
1 # Push a 1 to the stack
[ # Start an infinite loop
= # Print the current number with trailing newline (without popping it)
Ð # Triplicate the current number
Iα # Get the absolute difference with the input
D # Duplicate that absolute difference
_ # If this difference is 0:
# # Stop the infinite loop
‚ß # Pair it with the current number, and pop and push the minimum
g<° # Calculate 10 to the power of the length of the minimum minus 1
+ # And add it to the current number
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
1µ«³_$DL’⁵*$+µ<³$п
```
[Try it online!](https://tio.run/##y0rNyan8/9/w0NZDqw9tjldx8XnUMPNR41YtFe1DW20ObVY5POHQ/v9ABQYGxgA "Jelly – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 51 bytes
```
Union@NestList[#+10^Floor@Log10@Min[s-#,#]&,1,s=#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PzQvMz/PwS@1uMQns7gkWlnb0CDOLSc/v8jBJz/d0MDBNzMvulhXWUc5Vk3HUKfYFkj/DyjKzCtR0HdI13dQqDbUMTTQMTYCUQZGtf//AwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## Batch, 131 bytes
```
@set/an=i=1
:e
@if %n%==%i%0 set i=%i%0
@echo %n%
:c
@set/an+=i
@if %n% leq %1 goto e
@set/an-=i,i/=10
@if %i% neq 0 goto c
```
Takes input as a command-line parameter and outputs the list of numbers to STDOUT. Explanation:
```
@set/an=i=1
```
Start with `n=1` and `i=1` representing the power of 10.
```
:e
@if %n%==%i%0 set i=%i%0
```
Multiply `i` by 10 if `n` has reached the next power of 10.
```
@echo %n%
```
Output the current value of `n`.
```
:c
@set/an+=i
@if %n% leq %1 goto e
```
Repeat while `i` can be added to `n` without it exceeding the input.
```
@set/an-=i,i/=10
```
Restore the previous value of `n` and divide `i` by 10.
```
@if %i% neq 0 goto c
```
If `i` is not zero then try adding `i` to `n` again.
[Answer]
# [R](https://www.r-project.org/), 67 65 bytes
-2 bytes thanks to Giuseppe
```
k=scan();o=1;i=10^(k:0);while(T<k)o=c(o,T<-T+i[i<=T&i+T<=k][1]);o
```
Pretty simple. It takes a set of powers of 10 beyond what would be needed in reverse order `i`.
(I would prefer to use `i=10^rev(0:log10(k))` instead of `i=10^(k:0)` since the latter is computationally ineffecient, but golf is golf!).
Then in a while loop, applies the conditions to `i` and takes the first (i.e. largest); updates `n`, and appends to output
[Try it online!](https://tio.run/##K/r/P9u2ODkxT0PTOt/W0DrT1tAgTiPbykDTujwjMydVI8QmWzPfNlkjXyfERjdEOzM608Y2RC1TO8TGNjs22jAWqO2/JRD85wIA "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
1+«ạæḟ⁵«Ɗɗ¥Ƭ
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//MSvCq@G6ocOm4bif4oG1wqvGismXwqXGrP///zEwMDI "Jelly – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 27 bytes
```
Wa>Po+:y/t*Y1Ty>o|o+y>ay*:t
```
[Try it online!](https://tio.run/##K8gs@P8/PNEuIF/bqlK/RCvSMKTSLr8mX7vSLrFSy6rk////xkYmAA "Pip – Try It Online")
In pseudocode:
```
a = args[0]
o = 1
print o
while a > o {
y = 1
till y > o || o + y > a
y *= 10
o += y / 10
print o
}
```
I'm pretty pleased with the golfing tricks I was able to apply to shorten this algorithm. By initializing, updating, and printing stuff in the loop header, I was able to avoid needing curly braces for the loop body. There's probably a golfier algorithm, though.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
```
ÆT±ApTmTnU)sÊÉÃf§U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xlSxQXBUbVRuVSlzysnDZqdV&input=MzIx)
```
ÆT±ApTmTnU)sÊÉÃf§U :Implicit input of integer U
Æ :Map the range [0,U)
T± : Increment T (initially 0) by
A : 10
p : Raised to the power of
Tm : The minimum of T and
TnU : T subtracted from U
) : End minimum
s : Convert to string
Ê : Length
É : Subtract 1
à :End map
f :Filter
§U : Less than or equal to U
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~123~~ 122 bytes
```
m=>{var a=new[]{1}.ToList();int s;for(;(s=a.Last())<m;)a.Add(s+(int)Math.Pow(10,(int)Math.Log(s<m-s?s:m-s,10)));return a;}
```
[Try it online!](https://tio.run/##nY0xa8MwEIX3/gphOtxhRdjpVlkOWTK50KHQoXS4OLKrwTLolGYQ@u2uPXXpULIc7z2@j@t517NbTlffN85H2TmOW2hbMZhlMm36piDIeHv7@Ex1Vm/zhgDqFRKshzmABjakOtpmbCaNpI6XC3AJK4MvFL/U63yDupK/QzePwM204wM/r1fWFSLqYOM1eEE6L/rhPbhoO@ctPBYppQFqVMdxDHakaKEQhQSSZzQtledyrZhzLvAvr7pTfNrf/7La/0tdfgA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 142 bytes
```
L-D-M:-append(L,[D],M).
N-L-C-X-R-I:-I=1,C is X*10,N-L-C-C-R-1;D is C+X,(D<N,L-D-M,N-M-D-X-R-I;D>N,N-L-C-(X/10)-R-0;L-D-R).
N-R:-N-[]-0-1-R-1.
```
[Try it online!](https://tio.run/##bY09D4IwFEV3fwVj0Xex1Y36MbQLCXRgakIYTCSGhAABE35@bdFJnd7LuefdN05DNzwwL61zOTSKFLdxbPo7y6nSNRVxsjHIoWBRIkuRnQWpqJ0juxWc3pHykZA6ULWzxPTJ0Frm88LP9VTqi/n4zO4Fjz3kMmjl@qNMYVDV4BChLnHXsNAytc@m61mQPOE/6CgOfzT@Bd0L "Prolog (SWI) – Try It Online")
Explanation coming tomorrow or something
] |
[Question]
[
A [bronze plaque](https://upload.wikimedia.org/wikipedia/commons/3/3a/Emma_Lazarus_plaque.jpg) in the pedestal of the [Statue of Liberty](https://en.wikipedia.org/wiki/Statue_of_Liberty) displays the poem "[The New Colossus](https://en.wikipedia.org/wiki/The_New_Colossus)" by Emma Lazarus, part of which reads:
>
> Give me your tired, your poor,
>
> Your huddled masses yearning to breathe free,
>
> The wretched refuse of your teeming shore.
>
> Send these, the homeless, tempest-tost to me,
>
> I lift my lamp beside the golden door!
>
>
>
To simplify this section of the poem for this challenge, we'll make it all uppercase and replace the newlines with slashes (`/`), keeping commas and other punctuation as is:
```
GIVE ME YOUR TIRED, YOUR POOR,/YOUR HUDDLED MASSES YEARNING TO BREATHE FREE,/THE WRETCHED REFUSE OF YOUR TEEMING SHORE./SEND THESE, THE HOMELESS, TEMPEST-TOST TO ME,/I LIFT MY LAMP BESIDE THE GOLDEN DOOR!
```
We'll call this string S. It has [md5 hash](http://www.miraclesalad.com/webtools/md5.php) `8c66bbb9684f591c34751661ce9b5cea`. You may optionally assume it has a trailing newline, in which case the md5 hash is `0928ff6581bc207d0938b193321f16e6`.
Write a program or function that takes in a single string. When the string is S, output *in order*, one per line, the six phrases that describe the type of people the poem depicts Lady Liberty asking for:
```
TIRED
POOR
HUDDLED MASSES YEARNING TO BREATHE FREE
WRETCHED REFUSE OF YOUR TEEMING SHORE
HOMELESS
TEMPEST-TOST
```
(This precise string, optionally followed by a single trailing newline, must be your output for input S.)
For *at least one* input string that is *not* S, your output should be any string other than the six lines above. This could be as simple as outputting only `TIRED` if the input is only `GIVE ME YOUR TIRED`. This rule is to prevent pure hardcoding. Otherwise, when the input string is not S, your code may do anything.
This is essentially a constant-output challenge where you are given an input that is relatively close to the output. You could of course mostly ignore the input and hardcode the output, but it may be better to, say, strip out the substrings of the input needed for the output.
For reference, here are the zero-based indices and lengths of the six output lines in S:
```
13 5, 25 4, 36 39, 81 37, 136 8, 146 12
```
**The shortest code in bytes wins.**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ẇ“©ØḌKAƑ⁶2ɼU’b8ȷ¤ịY
```
**[Try it online!](https://tio.run/nexus/jelly#LY6xTsNAEER/ZekNlqjSXrix78Sd19o9g9zyJUlDQxq6RKJMkx8ABFRBQvAZ9o@Yc6CaN9LM7E7D2/24ejoePrfD6@bafD2O6@fLn49uXO3uFt8vx/3w/tBP01T7G1AE9dwJJS@wxR@3zFKUJ3SdtQGWolGFUg8jjW9qSkxLgUkOVAlQlDPdCtKVy2lB1SmIq/9tIM4ldSy4KBWNpZxXFLOQ44gA1ewQW2g6T6xpPhHzsKfgq0Sxp2BiS0uotzj1ag4WDdn87dkv "Jelly – TIO Nexus")** or try it with [some other text](https://tio.run/nexus/jelly#AUgAt///4bqG4oCcwqnDmOG4jEtBxpHigbYyybxV4oCZYjjIt8Kk4buLWf///1BST0dSQU1NSU5HIFBVWlpMRVMgJiBDT0RFIEdPTEY).
### How?
Indexes into the list of all non-empty contiguous slices of the input string and joins with line feeds.
```
Ẇ“©ØḌKAƑ⁶2ɼU’b8ȷ¤ịY - Main link: s
¤ - nilad followed by link(s) as a nilad
“©ØḌKAƑ⁶2ɼU’ - base 250 number, 27003436588466956354336
8ȷ - 8 * 1e3 = 8000
b - convert to base, [824,635,7086,6796,1544,2336]
ị - index into
Ẇ - all non-empty contiguous slices of s
Y - join with line feeds
```
---
Previous code, 22 bytes:
```
“ÇŒȷœ%LRw⁹ƊƓɠ‘ṬœṗµḊm2Y
```
Partitions the input string, takes every second element and joins with line feeds. `“ÇŒȷœ%LRw⁹ƊƓɠ‘` is a list of code page indexes, `Ṭ` makes a list of zeros with ones at those indexes, `œṗ` partitions the input at the truthy indexes of that list, `Ḋ` removes the first element, `m2` takes every second element, and `Y` joins with line feeds.
[Answer]
## JavaScript (ES6), ~~128~~ 69 bytes
May output empty lines or some garbage when the input is different from `S`.
```
let f =
s=>[837,1604,2343,5221,8712,9356].map(n=>s.substr(n>>6,n&63)).join`
`
console.log(f(`GIVE ME YOUR TIRED, YOUR POOR,
YOUR HUDDLED MASSES YEARNING TO BREATHE FREE,
THE WRETCHED REFUSE OF YOUR TEEMING SHORE.
SEND THESE, THE HOMELESS, TEMPEST-TOST TO ME,
I LIFT MY LAMP BESIDE THE GOLDEN DOOR!`))
console.log(f(`THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG`))
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~76~~ ~~65~~ 60 bytes
```
echo "TIRED
POOR
${1:36:39}
${1:81:37}
HOMELESS
${1:146:12}"
```
[Try it online!](https://tio.run/nexus/bash#NY7BTsQwDETv/Qqz4lioyqJl6a1Lpk2kpK7sFNTzaiVufADqt5ckwMlja@Z59tv184sO0QlMNTNLdf/ddsdTd3zdijyn7WWrLAd4qJZb@3zq2qftsO/76N5BAbTyIlQo9a/OrLop0i7GeBgKvSqUVvQyuWmkyHQR9NGCBgHqJqsPQXyzyS0YFgXx8McGQg6pZcFjo5gMJb@izoP@@6UNYYbGh8ga84uQwI68GyKFlXwfZrpAnUHJjewNJjKp7d0P "Bash – TIO Nexus")
[Answer]
## *Mathematica*, 71
```
Column@StringTake[#,List@@@{14|18,26|29,37|75,82|118,137|144,147|158}]&
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 72 bytes
```
"$args"-split'[/,.]'-replace'^.*?(YOUR|\bTHE) |^ | TO ME'-match'^[^S G]'
```
[Try it online!](https://tio.run/nexus/powershell#LY7BasMwEETv/YqtKagNsv0JxanGtkCyjFZuMUkMbghtIYWQ5Oh/d@Wkp33LzszOnDyN569Lkl5Ox5@r2OQy24n0fDgdx/1BDNnq9bl3nZ@2n6HGC00DTRQcWYj0d7zuv8WwGZiqnZgf5jmp9DvijRYLBe2h5J1b57zMb1h3ShkosgUzmHoUvtFNtaSuPYr4hkoPyHyhD4/wVke1R9kxyJX/2YBdTFw7jyxnNIqiniGXQbWzMGCOG2wLDmlwHO7FZa7J6DKQ7ckUtqU1WCvcfJUzCg2p2PYx@QM "PowerShell – TIO Nexus")
### Explanation
This is a pretty crappy regex solution.
Splitting the string into an array on `/` or `.` or `,` and then replacing parts of each string that match the first pattern, which gives an array of `-replace`d strings, then use the `-match` operator to return an array of the elements that match the second pattern (which gets rid of the blank lines and 2 lines that didn't get filtered before).
[Answer]
# Mathematica, 86 bytes
```
Riffle[s=#;s~Take~#&/@{{14,18},{26,29},{37,75},{82,118},{137,144},{147,158}},"
"]<>""&
```
Unnamed function taking a list of characters as input and returning a string. Just extracts the relevant substrings of the input and concatenates with newlines.
[Answer]
# TI-Basic, 58 bytes
Very straightforward. `Disp` is like `println`, so there are newlines in between.
```
Disp "TIRED","POOR",sub(Ans,37,39),sub(Ans,82,37),"HOMELESS",sub(Ans,147,12
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 38 32 bytes
It can probably be improved, but this is a job for regexes!
```
!`(?<=R |HE ).*?(?=[,.])|\w+-\w+
```
[Try it online!](https://tio.run/nexus/retina#LY5LbsMwDESvMtklrWJfoIHhVGNLgGQapNzCaAvkFtnk7q6cdkHwEZgPt8Pt2L1dFI9AnJqX7thdvlzzc3p831/PdbZtjB9EJlZZFCUqvfvjWURd@8SweJ/okXszGlb2OsVpRBFclX2p4YOSrt3pU1neQ1Urh8UIGf6zybybLIiyaY2TR9Ub3b4QJDPRrF7MM62ci1jZK3INjkhxKMgrUp9nXGnR8@kbJXlO8PXbwy8 "Retina – TIO Nexus")
] |
[Question]
[
SF(n) is a function which computes the smallest prime factor for a given number n.
We'll call T(N) the sum of every SF(n) with 2 <= n <= N.
T(1) = 0 (the sum is over 0 summands)
T(2) = 2 (2 is the first prime)
T(3) = 5 = 2 + 3
T(4) = 7 = 2 + 3 + 2
T(5) = 12 = 2 + 3 + 2 + 5
...
T(10000) = 5786451
The winner will be the one who manages to compute the largest T(N) in 60 seconds on my own laptop (Toshiba Satellite L845, Intel Core i5, 8GB RAM).
---
```
Current top score: Nicolás Siplis - 3.6e13 points - Nim
```
[Answer]
## Nim, 3.6e13
Simply sieving is not the best answer when trying to calculate the highest N possible since the memory requirements become too high. Here's a different approach (started with Nim a couple days ago and fell in love with the speed and syntax, any suggestions to make it faster or more readable are welcome!).
```
import math
import sequtils
import nimlongint # https://bitbucket.org/behrends/nimlongint/
proc s(n : int) : int128 =
var x = toInt128(n)
(x * x + x) div 2 - 1
proc sum_pfactor(N : int) : int128 =
var
root = int(sqrt(float(N)))
u = newSeqWith(root+1,false)
cntA,cntB,sumA,sumB = newSeq[int128](root+1)
pcnt,psum,ret : int128
interval,finish,d,q,t : int
for i in 0..root:
cntA[i] = i-1
sumA[i] = s(i)
for i in 1..root:
cntB[i] = N div i - 1
sumB[i] = s(N div i)
for p in 2..root:
if cntA[p] == cntA[p-1]:
continue
pcnt = cntA[p - 1]
psum = sumA[p - 1]
q = p * p
ret = ret + p * (cntB[p] - pcnt)
cntB[1] = cntB[1] - cntB[p] + pcnt
sumB[1] = sumB[1] - (sumB[p] - psum) * p
interval = (p and 1) + 1
finish = min(root,N div q)
for i in countup(p+interval,finish,interval):
if u[i]:
continue
d = i * p
if d <= root:
cntB[i] = cntB[i] - cntB[d] + pcnt
sumB[i] = sumB[i] - (sumB[d] - psum) * p
else:
t = N div d
cntB[i] = cntB[i] - cntA[t] + pcnt
sumB[i] = sumB[i] - (sumA[t] - psum) * p
if q <= root:
for i in countup(q,finish-1,p*interval):
u[i] = true
for i in countdown(root,q-1):
t = i div p
cntA[i] = cntA[i] - cntA[t] + pcnt
sumA[i] = sumA[i] - (sumA[t] - psum) * p
sumB[1] + ret
var time = cpuTime()
echo(sum_pfactor(int(3.6e13))," - ",cpuTime() - time)
```
[Answer]
# C, Prime Sieve: 5e9
Results:
```
$ time ./sieve
Finding sum of lowest divisors of n = 2..5000000000
572843021990627911
real 0m57.144s
user 0m56.732s
sys 0m0.456s
```
Program:
While it's a rather staightforward program, it took me a while to figure out how to get the memory management right - I only have enough ram for 1 byte per number in the range, so I had to be careful. It's a standard sieve of Erasthones.
```
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<assert.h>
#define LIMIT ((unsigned long long)5e9 +1)
#define ROOT_LIMIT floor(sqrt(LIMIT))
int main()
{
printf("Finding sum of lowest divisors of n = 2..%llu\n", LIMIT - 1);
char * found_divisor;
found_divisor = malloc(LIMIT * sizeof(char));
if (found_divisor == NULL) {
printf("Error on malloc");
return -1;
}
unsigned long long i;
unsigned long long trial_div;
unsigned long long multiple;
unsigned long long sum = 0;
for (i = 0; i < LIMIT; ++i) {
found_divisor[i] = 0;
}
for (trial_div = 2; trial_div <= ROOT_LIMIT; ++trial_div) {
if (found_divisor[trial_div] == 0) {
for (multiple = trial_div * trial_div; multiple < LIMIT; multiple += trial_div) {
if (found_divisor[multiple] == 0) {
found_divisor[multiple] = 1;
sum += trial_div;
}
}
}
}
for (i = 2; i < LIMIT; ++i) {
if (found_divisor[i] == 0) {
sum += i;
}
}
free(found_divisor);
printf("%lld\n", sum);
return 0;
}
```
[Answer]
# Perl, brute force factoring
```
use ntheory ":all";
sub T {
my $sum=0;
for (1..$_[0]) {
$sum += !($_%2) ? 2 : !($_%3) ? 3 : !($_%5) ? 5 : (factor($_))[0];
}
$sum
}
T(90_000_000);
```
I can get to about 9e7 in 25 seconds on my Linux machine. It could be faster by digging into the C code, as it is saying after a check for 2/3/5, completely factor the number.
There are much more clever ways to do this using sieving. I thought a simple brute force way would be a start. This is basically Project Euler problem 521, by the way.
[Answer]
## Go, 21e9
Does a sieve to find the minimum factor of each number <= N. Spawns goroutines to count sections of the number space.
Run with "go run prime.go -P 4 -N 21000000000".
```
package main
import (
"flag"
"fmt"
"runtime"
)
const S = 1 << 16
func main() {
var N, P int
flag.IntVar(&N, "N", 10000, "N")
flag.IntVar(&P, "P", 4, "number of goroutines to use")
flag.Parse()
fmt.Printf("N = %d\n", N)
fmt.Printf("P = %d\n", P)
runtime.GOMAXPROCS(P)
// Spawn goroutines to check sections of the number range.
c := make(chan uint64, P)
for i := 0; i < P; i++ {
a := 2 + (N-1)*i/P
b := 2 + (N-1)*(i+1)/P
go process(a, b, c)
}
var sum uint64
for i := 0; i < P; i++ {
sum += <-c
}
fmt.Printf("T(%d) = %d\n", N, sum)
}
func process(a, b int, res chan uint64) {
// Find primes up to sqrt(b). Compute starting offsets.
var primes []int
var offsets []int
for p := 2; p*p < b; p++ {
if !prime(p) {
continue
}
primes = append(primes, p)
off := a % p
if off != 0 {
off = p - off
}
offsets = append(offsets, off)
}
// Allocate sieve array.
composite := make([]bool, S)
// Check factors of numbers up to b, a block of S at a time.
var sum uint64
for ; a < b; a += S {
runtime.Gosched()
// Check divisibility of [a,a+S) by our set of primes.
for i, p := range primes {
off := offsets[i]
for ; off < S; off += p {
if composite[off] {
continue // Divisible by a smaller prime.
}
composite[off] = true
if a+off < b {
sum += uint64(p)
}
}
// Remember offset for next block.
offsets[i] = off - S
}
// Any remaining numbers are prime.
for i := 0; i < S; i++ {
if composite[i] {
composite[i] = false // Reset for next block.
continue
}
if a+i < b {
sum += uint64(a + i)
}
}
}
res <- sum
}
func prime(n int) bool {
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
```
Note that the answer for N=21e9 is between 2^63 and 2^64, so I had to use unsigned 64-bit ints to count correctly...
[Answer]
# C++, 1<<34 ~ 1.7e10
```
Intel(R) Core(TM) i5-2410M CPU @ 2.30GHz
$ g++ -O2 test3.cpp
$ time ./a.out
6400765038917999291
real 0m49.640s
user 0m49.610s
sys 0m0.000s
```
```
#include <iostream>
#include <vector>
using namespace std;
const long long root = 1 << 17; // must be a power of two to simplify modulo operation
const long long rootd2 = root >> 1;
const long long rootd2m1 = rootd2 - 1;
const long long mult = root; // must be less than or equal to root
const long long n = root * mult; // unused constant (function argument)
int main() {
vector < int > sieve(rootd2, 0);
vector < int > primes;
vector < long long > nexts;
primes.reserve(root);
nexts.reserve(root);
// initialize sum with result for even numbers
long long sum = n / 2 * 2;
// sieve of Erathosthenes for numbers less than root
// all even numbers are skipped
for(long long i = 1; i < rootd2; ++i){
if(sieve[i]){
sieve[i] = 0;
continue;
}
const long long val = i * 2 + 1;
primes.push_back(val);
sum += val;
long long j;
for(j = (val + 1) * i; j < rootd2; j += val){
sum += val * (1 - sieve[j]); // conditionals replaced by multiplication
sieve[j] = 1;
}
nexts.push_back(j);
}
int k = primes.size();
long long last = rootd2;
// segmented sieve of Erathosthenes
// all even numbers are skipped
for(int segment = 2; segment <= mult; ++segment){
last += rootd2;
for(int i = 0; i < k; ++i){
long long next = nexts[i];
long long prime = primes[i];
if(next < last){
long long ptr = next & rootd2m1; // modulo replaced by bitmasking
while(ptr < rootd2){
sum += prime * (1 - sieve[ptr]); // conditionals replaced by multiplication
sieve[ptr] = 1;
ptr += prime;
}
nexts[i] = (next & ~rootd2m1) + ptr;
}
}
for(int i = 0; i < rootd2; ++i){
sum += ((segment - 1) * root + i * 2 + 1) * (1 - sieve[i]);
sieve[i] = 0;
}
}
cout << sum << endl;
}
```
[Answer]
# Java 8: 1.8e8 2.4e8
This entry does not compare to several of the other ones already up, but I wanted to post my answer since I had fun working on this.
The main optimizations of my approach are as follow:
* Every even number has a smallest factor of 2, so these can be added for free after every odd number is processed. Basically, if you have done the work to calculate `T(N)` when `N % 2 == 1`, you know that `T(N + 1) == T(N) + 2`. This allows me to start my counting at three and to increment by iteration by twos.
* I store my prime numbers in an array as opposed to a `Collection` type. This more than doubled the `N` I can reach.
* I use the prime numbers to factor a number as opposed to performing the Sieve of Eratosthenes. This means that my memory storage is restricted almost completely to my primes array.
* I store the square root of the number for which I am trying to find the smallest factor. I tried @user1354678's approach of squaring a prime factor each time, but this cost me about than 1e7 from my score.
That's about all there is to it. My code iterates from 3 on by twos until it detects that it has hit or exceeded the time limit, at which point it spits out the answer.
```
package sum_of_smallest_factors;
public final class SumOfSmallestFactors {
private static class Result {
private final int number;
int getNumber() {
return number;
}
private final long sum;
long getSum() {
return sum;
}
Result(int number, long sum) {
this.number = number;
this.sum = sum;
}
}
private static final long TIME_LIMIT = 60_000_000_000L; // 60 seconds x 1e9 nanoseconds / second
public static void main(String[] args) {
SumOfSmallestFactors main = new SumOfSmallestFactors();
Result result = main.run();
int number = result.getNumber();
long sum = result.getSum();
System.out.format("T(%,d) = %,d\n", number, sum);
}
private int[] primes = new int[16_777_216];
private int primeCount = 0;
private long startTime;
private SumOfSmallestFactors() {}
private Result run() {
startClock();
int number;
long sumOfSmallestFactors = 2;
for (number = 3; mayContinue(); number += 2) {
int smallestFactor = getSmallestFactor(number);
if (smallestFactor == number) {
addPrime(number);
}
sumOfSmallestFactors += smallestFactor + 2;
}
--number;
Result result = new Result(number, sumOfSmallestFactors);
return result;
}
private void startClock() {
startTime = System.nanoTime();
}
private boolean mayContinue() {
long currentTime = System.nanoTime();
long elapsedTime = currentTime - startTime;
boolean result = (elapsedTime < TIME_LIMIT);
return result;
}
private int getSmallestFactor(int number) {
int smallestFactor = number;
int squareRoot = (int) Math.ceil(Math.sqrt(number));
int index;
int prime = 3;
for (index = 0; index < primeCount; ++index) {
prime = primes[index];
if (prime > squareRoot) {
break;
}
int remainder = number % prime;
if (remainder == 0) {
smallestFactor = prime;
break;
}
}
return smallestFactor;
}
private void addPrime(int prime) {
primes[primeCount] = prime;
++primeCount;
}
}
```
Running on a different system (Windows 8.1, Intel core i7 @ 2.5 GHz, 8 GB RAM) with the latest version of Java 8 has markedly better results with no code changes:
```
T(240,308,208) = 1,537,216,753,010,879
```
[Answer]
# R, 2.5e7
Simple minded sieve of Eratosthenes, vectorised as much as possible. R's not really designed for this sort of problem and I'm pretty sure it can be made faster.
```
MAX <- 2.5e7
Tot <- 0
vec <- 2:MAX
while(TRUE) {
if (vec[1]*vec[1] > vec[length(vec)]) {
Tot <- Tot + sum(as.numeric(vec))
break
}
fact <- which(vec %% vec[1] == 0)
Tot <- Tot + vec[1]*length(vec[fact])
vec <- vec[-fact]
}
Tot
```
[Answer]
## Python, ~7e8
Using an incremental Sieve of Erathostenes. Some care does need to be taken that a marked value is marked with its lowest divisor, but the implementation is otherwise fairly straight forward.
Timing was taken with PyPy 2.6.0, input is accepted as a command line argument.
```
from sys import argv
from math import sqrt
n = int(argv[1])
sieve = {}
imax = int(sqrt(n))
t = n & -2
i = 3
while i <= n:
divs = sieve.pop(i, [])
if divs:
t += divs[-1]
for v in divs:
sieve.setdefault(i+v+v, []).append(v)
else:
t += i
if i <= imax: sieve[i*i] = [i]
i += 2
print t
```
---
**Sample Usage**
```
$ pypy sum-lpf.py 10000
5786451
$ pypy sum-lpf.py 100000000
279218813374515
```
[Answer]
# Julia, 5e7
Surely Julia can do better but this is what I have for now. This does 5e7 in about 60 seconds on JuliaBox but I can't test locally yet. Hopefully by then I'll have thought of a more clever approach.
```
const PRIMES = primes(2^16)
function lpf(n::Int64)
isprime(n) && return n
for p in PRIMES
n % p == 0 && return p
end
end
function T(N::Int64)
local x::Int64
x = @parallel (+) for i = 2:N
lpf(i)
end
x
end
```
Here we're creating a function `lpf` that iterates through sequential primes and checks the input for divisibility by each. The function returns the first divisor encountered, thereby obtaining the least prime factor.
The main function computes `lpf` on the integers from 2 to the input in parallel and reduces the result by summing.
[Answer]
# Common Lisp, 1e7
```
(defvar input 10000000)
(defvar numbers (loop for i from 2 to input collect i))
(defvar counter)
(defvar primes)
(setf primes (loop for i from 2 to (floor (sqrt input))
when (loop for j in primes
do (if (eq (mod i j) 0) (return nil))
finally (return t))
collect i into primes
finally (return primes)))
(format t "~A~%"
(loop for i in primes
do (setf counter 0)
summing (progn (setf numbers (remove-if #'(lambda (x) (if (eq (mod x i) 0) (progn (incf counter) t))) numbers))
(* i counter)) into total
finally (return (+ total (reduce #'+ numbers)))))
```
I've opted to first generate a list of prime numbers from 2 to `(sqrt input)`, then test every value with the primes, whereas previously I would test against every number up to `(sqrt input)`, which would be pointless (e.g., if a number is divisible by 4, it's also divisible by 2, so it's already accounted for.)
Thank God for side-effects while I'm at it. The remove-if both lowers the size of the list and counts how many elements were removed, so I just have to multiply that by whatever value the loop is on and add that into the running total.
(Fun fact: `delete` is the destructive equivalent of `remove`, but for whatever reason, `delete` is all sorts of slower than `remove` in this case.)
[Answer]
**Rust 1.5e9**
A very naive Eratosthene sieve, but I felt Rust did not receive any love here !
```
// Expected (approximate) number of primes
fn hint(n:usize) -> usize {
if n < 2 {
1
} else {
n / ((n as f64).ln() as usize) + 1
}
}
fn main() {
let n:usize = match std::env::args().nth(1) {
Some(s) => s.parse().ok().expect("Please enter a number !"),
None => 10000,
};
let mut primes = Vec::with_capacity(hint(n));
let mut sqrt = 2;
let s = (2..).map(|n:u32| -> u32 {
if (sqrt * sqrt) < n {
sqrt += 1;
}
let (div, unseen) = match primes.iter().take_while(|&p| *p <= sqrt).filter(|&p| n % p == 0).next() {
Some(p) => (*p, false),
None => (n, true),
};
if unseen {
primes.push(div);
}
div
}).take(n-1).fold(0, |acc, p| acc + p);
println!("{}", s);
}
```
[Answer]
## Java 2.14e9
## Pure Sieve of Eratosthenes with advantage of BitSet
I have calculated the Smallest Prime factor sum upto `Integer.MAX_VALUE - 1` just in `33.89 s`. But I can't proceed any larger because any further will lead to Integer Overflow on the Size of Bitset. So I'm working on to create another Bitset for the next set of Ranges. Until then, this is the fastest I'm able to generate.
---
```
T(214,74,83,646) = 109931450137817286 in 33.89 s
aka
T(2,147,483,646) = 109931450137817286 in 33.89 s
```
---
```
import java.util.BitSet;
public class SmallPrimeFactorSum {
static int limit = Integer.MAX_VALUE - 1;
// BitSet is highly efficient against boolean[] when Billion numbers were involved
// BitSet uses only 1 bit for each number
// boolean[] uses 8 bits aka 1 byte for each number which will produce memory issues for large numbers
static BitSet primes = new BitSet(limit + 1);
static int limitSqrt = (int) Math.ceil(Math.sqrt(limit));
static long start = System.nanoTime();
static long sum = 0;
public static void main(String[] args) {
genPrimes();
}
// Generate Primes by Sieve of Eratosthenes
// Sieve of Eratosthenes is much efficient than Sieve of Atkins as
// Sieve of Atkins involes Division, Modulus, Multiplication, Subtraction, Addition but
// Sieve of Eratosthenes involves only addition
static void genPrimes() {
// Inverse the Bit values
primes.flip(0, limit + 1);
// Now all Values in primes will now be true,
// True represents prime number
// False represents not prime number
// Set 0 and 1 as not Prime number
primes.clear(0, 2);
// Set all multiples of each Prime as not Prime;
for ( int prime = 2; prime > 0 && prime <= limit && prime > 0; prime = primes.nextSetBit(prime + 1) ) {
// Add Current Prime as its Prime factor
sum += prime;
// Skip marking if Current Prime > SQRT(limit)
if ( prime > limitSqrt ) {
continue;
}
// Mark Every multiple of current Prime as not Prime
for ( int multiple = prime + prime; multiple <= limit && multiple > 0; multiple += prime ) {
// Mark as not Prime only if it's true already
if ( primes.get(multiple) ) {
// Add Current Prime as multiple's Prime factor
sum += prime;
primes.clear(multiple);
}
}
}
System.out.printf("T(%d) = %d in %.2f s", limit, sum, (System.nanoTime() - start) / 1000000000.0);
//System.out.printf("Total Primes upto %d : %d\n", limit, primes.cardinality());
}
}
```
] |
[Question]
[

In many [image-processing](/questions/tagged/image-processing "show questions tagged 'image-processing'") challenges, the post contains images, which must be saved to a file in order to be able to work on the problem. This is an especially tedious manual task. We programmers should not have to be subjected to such drudgery. Your task is to automatically download all the images contained in a Code Golf.SE question.
## Rules
* Your program may connect to any part of `stackexchange.com`, but may not connect to any other domains, excepting the locations of the images (i.e., don't bother with a URL shortener).
* An integer *N* is given as input, on the command line or stdin.
* The URL `http://codegolf.stackexchange.com/questions/*N*` is guaranteed to be a valid link to a Code Golf question.
* Each image displayed in the body of question *N* must be saved to a file on the local computer. Either of the following locations is acceptable:
+ The current directory
+ A directory input by the user
* Your program must not save files other than the images in the question body (e.g. user avatars, or images contained in answers).
* Images must be saved with the same file extension as the original.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") — write the shortest program you can.
**Validity criterion for answers**
There are various possible edge cases with multiple images of the same name, text with the same name as HTML elements, etc. An answer will be invalidated only if it can be shown to fail on some revision of a question posted before January 10, 2015.
[Answer]
# Mathematica, ~~211~~ 210 bytes
```
i=Import;FileNameTake@#~Export~i@#&/@ImportString["body"/.("items"/.i["http://api.stackexchange.com/2.2/questions/"<>InputString[]<>"?site=codegolf&filter=!*Lgp.gEWHA6BNP.l","JSON"])[[1]],{"HTML","ImageLinks"}]
```
Ungolfed:
```
i = Import;
FileNameTake@#~Export~i@# & /@
ImportString[
"body" /. (
"items" /.
i["http://api.stackexchange.com/2.2/questions/" <>
InputString[] <> "?site=codegolf&filter=!*Lgp.gEWHA6BNP.l",
"JSON"]
)[[1]],
{"HTML", "ImageLinks"}
]
```
It's pretty straightforward. I've set up a [filter](http://api.stackexchange.com/docs/questions-by-ids#order=desc&sort=activity&ids=44481&filter=!*Lgp.gEWHA6BNP.l&site=codegolf&run=true) for the StackExchange API, which returns only the body of a question. The code retrieves the question information with that filter and parses it as JSON. I select the correct element (the body), and use `ImportString` to parse the HTML and filter out all image URLs. `FileNameTake@#~Export~Import@#` then downloads each of the images and stores it in the current working directory with the same file name as that in the URL.
You can find out the current working directory with `Directory[]`.
In principle, there's a much shorter version, because `ImportString` can actually download all the files right away, instead of just giving me the URLs. But then I lose information about the original file type (since they are converted to `Image` objects upon download), so I can only save them all as the same type (PNG, say).
[Answer]
## Javascript - ~~149~~ 161 bytes
```
$.get("http://codegolf.stackexchange.com/q/"+prompt(),function(e){$(".post-text:first img",e).each(function(e,t){$('<a href="'+t.src+'"download>')[0].click()})})
```
with whitespace
```
$.get('http://codegolf.stackexchange.com/q/' + prompt(), function(d) {
$('.post-text:first img',d).each(function(i,e){
$('<a href="' + e.src + '"download>')[0].click();
})
})
```
script has to be run from stackexchange site to work. ~~Will default to the current page if no question number is specified in the prompt~~
[Answer]
## Python 2 - 241 bytes
Pretty straightforward, can probably be golfed further. I search the site for all occurrences of `img src=` between the first occurrence of `post-text` and the `/div` immediately following that. Each image url is then read and saved to the working directory.
```
import string,sys,urllib,re;o=string.find;u=urllib.urlopen
r=u("http://codegolf.stackexchange.com/q/"+sys.argv[1]).read()
i=o(r,"post-text")
for p in re.findall(r'img src="([^"]*)',r[i:o(r,"/div",i)]):f=open(p[-9:],"wb");f.write(u(p).read())
```
[Answer]
# Mathematica, 195
```
x=XMLElement;c=Cases;i=Import;l=Infinity;FileNameTake@#~Export~i@#&/@(((c[#,x["img",{"src"->e_,_},___]:>e,l]&)@*(c[#,x[_,{__,"id"->"question",__},e_]:>e,l]&)@*(i[#,"XMLObject"] &))@InputString[])
```
This exports images in the same way that Martin did in his Mathematica solution, read his answer for more information about that. This approach is very different from his, instead of parsing the result from the API I parse the HTML page directly. Or rather, I parse the symbolic XML that Mathematica can generate from HTML.
[Answer]
# Python 2 - ~~398~~ ~~342~~ 334 bytes
The program download the SE page, extracts the post part (the post-text div element), finds urls that end in an image extension and downloads them. The images are saved as `img<n>.<ext>` in the current directory.
```
import urllib2 as u,re,sys
z=u.urlopen;i=1
p=z('http://codegolf.stackexchange.com/q/'+sys.argv[1]).read()
s=re.search(r'ss="po(.+?)/di',p,16).group(1)
for L in re.findall('"(h.+?://.*?)"',s):
b=L.rsplit('.',1)
if len(b)==2 and b[1].lower() in 'jpg jpeg png gif bmp'.split():
open('img%u.%s'%(i,b[1]),'wb').write(z(L).read());i+=1
```
This program will also download images that are supplied as a link, not only embedded images. By giving each image a unique filename, name clashes are also avoided.
[Answer]
# Bash - 86 bytes
```
wget -r -l1 -np -Ajpg,jpeg,png,bmp,gif http://codegolf.stackexchange.com/questions/$1
```
Nothing wget won't fix.
`-np` prevents wget from entering upper directories(User Imgs)
`-A` only grabs files with the extension matching the list presented. `-r` is a recursive download. `-l` prevents wget from going too deep. `$1` is the question to grab.
[Answer]
# Node.js, ~~251~~ 247 Bytes
```
r=require,g=r('request'),g('http://codegolf.stackexchange.com/q/'+process.argv[2],function(_,_,b){r('cheerio').load(b)('#question .post-text img').each(function(i,a){s=a.attribs.src,g(s).pipe(r('fs').createWriteStream(i+r('path').basename(s)))})})
```
Uses `request` to make HTTP `GET`s and `cheerio` to parse the HTML. Name collisions are resolved by prepending the index of the current image to the basename of the file's URL. Images are saved to same directory as the current file.
[Answer]
# Lua, 200 bytes
```
r=require'socket.http'.request r('http://codegolf.stackexchange.com/questions/'.. ...):gsub('post.text(.-)div',function(p)p:gsub('src="(.-)"',function(i)io.open(i:sub(-9),'wb'):write((r(i)))end)end)
```
Accepts the number as a command-line argument.
Assumes any `src=` attribute will be for an `img` tag since these are the only tags with `src` attributes that stack exchange allows (right?).
Also note the `.. ...`. I'm particularly proud of that one.
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.