text
stringlengths 180
608k
|
---|
[Question]
[
Given a positive integer *n*, compute the value of the [Mertens function](https://en.wikipedia.org/wiki/Mertens_function) \$M(n)\$ where:
$$M(n) = \Sigma\_{k=1}^{n}\mu(k)$$
and \$\mu(k)\$ is the [Möbius function](https://en.wikipedia.org/wiki/M%C3%B6bius_function) where \$μ(k) = 1\$ if \$k\$ has an even number of distinct prime factors, \$-1\$ if \$k\$ has an odd number of distinct prime factors, and \$0\$ if the prime factors are not distinct.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so create the shortest code for a function or program that computes the Mertens function for an input integer *n* > 0.
* This is the OEIS sequence [A002321](https://oeis.org/A002321).
## Test Cases
```
n M(n)
1 1
2 0
3 -1
4 -1
5 -2
6 -1
7 -2
8 -2
9 -2
10 -1
117 -5
5525 5
7044 -25
8888 4
10000 -23
```
[Answer]
# Mathematica, ~~22~~ 20 bytes
Thanks to @miles for saving 2 bytes.
```
Tr@*MoebiusMu@*Range
```
# Explanation
```
Range
```
Generate a list from 1 to input.
```
MoebiusMu
```
Find `MoebiusMu` of each number
```
Tr
```
Sum the result.
[Answer]
# Python 2, ~~45~~ 37 bytes
```
f=lambda n,k=2:n<k or f(n,k+1)-f(n/k)
```
Test it on [Ideone](http://ideone.com/2oF26f).
### Background
This uses the property

from [A002321](https://oeis.org/A002321), which leads to the following recursive formula.

### How it works
We use recursion not only to compute **M** for the quotients, but to compute the sum of those images as well. This saves 8 bytes over the following, straightforward implementation.
```
M=lambda n:1-sum(M(n/k)for k in range(2,n+1))
```
When **f** is called with a single argument **n**, the optional argument **k** defaults to **2**.
If **n = 1**, `n<k` yields *True* and **f** returns this value. This is our base case.
If **n > 1**, `n<k` initially returns *False* and the code following `or` is executed. `f(n/k)` recursively computes one term of the sum, which is subtracted from the return value of `f(n,k+1)`. The latter increments **k** and recursively calls **f**, thus iterating over the possible values of **k**. Once **n < k + 1** or **n = 1**, `f(n,k+1)` will return **1**, ending the recursion.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes
```
LÒvX(ygmyyÙïQ*O
```
**Explanation**
```
L # range [1 .. n]
Ò # list of prime factors for each in list
v # for each prime factor list
X(ygm # (-1)^len(factors)
yyÙïQ* # multiplied by factors == (unique factors)
O # sum
```
[Try it online!](http://05ab1e.tryitonline.net/#code=TMOSdlgoeWdteXnDmcOvUSpP&input=MTE3)
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), ~~22~~ 20 bytes
```
yb:1a+
$p#dl:_1r^|,0
```
[Try it online!](http://brachylog.tryitonline.net/#code=eWI6MWErCiRwI2RsOl8xcl58LDA&input=OQ&args=Wg)
### Explanation
```
yb The list [1, 2, …, Input]
:1a Apply predicate 1 (second line) to each element
+ Sum the resulting list
$p#d All elements of the list of prime factors of the Input are distinct
l:_1r^ Output = (-1)^(<length of the list of prime factors>)
| Or
,0 Output = 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
:Ḋ߀SC
```
[Try it online!](http://jelly.tryitonline.net/#code=OuG4isOf4oKsU0M&input=&args=MTE3) or [verify the smaller test cases](http://jelly.tryitonline.net/#code=OuG4isOf4oKsU0MKMTBSOzExNyw1NTI1wrXFvMOH4oKsRw&input=). (takes a while)
### Background
This uses the property

from [A002321](https://oeis.org/A002321), which leads to the following recursive formula.

### How it works
```
:Ḋ߀SC Main link. Argument: n
Ḋ Dequeue; yield [2, ..., n].
: Perform the integer division of n by each k in [2, ..., n].
߀ Recursively call the main link on each result.
S Sum; add the results from the recursive calls.
C Complement; map the sum r to 1 - r.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
RÆFỊNP€FS
```
[Try it online!](http://jelly.tryitonline.net/#code=UsOGRuG7ik5Q4oKsRlM&input=&args=MTAwMDA) or [verify all test cases](http://jelly.tryitonline.net/#code=UsOGRuG7ik5Q4oKsRlMKMTBSOzExNyw1NTI1LDcwNDQsODg4OCzItzTCtcW8w4figqxH&input=).
### How it works
```
RÆFỊNP€FS Main link. Argument: n
R Range; yield [1, ..., n].
ÆF Factor; decompose each integer in that range into prime-exponent pairs.
Ị Insignificant; yield 1 for argument 1, 0 for all others.
N Negative; map n to -n.
This maps primes to 0, exponent 1 to -1, and all other exponents to 0.
P€ Reduce the columns of the resulting 2D arrays by multiplication.
The product of the prime values will always be 0; the product of the
exponent values is 0 if any exponent is greater than, 1 if there is an
even number of them, -1 is there is an odd number of them.
FS Flatten and sum, computing the sum of µ(k) for k in [1, ..., n].
```
[Answer]
# Haskell, ~~29~~ 27 bytes
```
f n=1-sum(f.div n<$>[2..n])
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ị*%ðþÆḊ
```
Not very efficient; determinants are hard.
[Try it online!](http://jelly.tryitonline.net/#code=4buKKiXDsMO-w4bhuIo&input=&args=OQ) or [verify the smaller test cases](http://jelly.tryitonline.net/#code=4buKKiXDsMO-w4bhuIoKMTBSOzExN8K1xbzDh-KCrEc&input=). (takes a while)
### Background
This uses a formula from [A002321](https://oeis.org/A002321):
**M(n)** is the determinant of the Boolean matrix **An×n**, where **ai,j** is **1** if **j = 1** or **i | j**, and **0** otherwise.
### How it works
```
Ị*%ðþÆḊ Main link. Argument: n
ð Combine the preceding atoms into a chain (unknown arity).
Begin a new, dyadic chain with arguments a and b.
Ị Insignificant; return 1 iff a = 1.
% Compute a % b.
* Compute (a == 1) ** (a % b).
This yields 1 if a = 1, or if a ≠ 1 and a % b = 0; otherwise, it yields 0.
þ Table; construct the matrix A by calling the defined chain for every pair
of integers in [1, ..., n].
ÆḊ Compute the determinant of the resulting matrix.
```
[Answer]
# PHP, 113 bytes
```
for(;$i=$argv[1]--;){for($n=$j=1;$j++<$i;)if(!($i%$j)){$i/=$j;$n++;if(!($i%$j))continue 2;}$a+=$n%2?1:-1;}echo$a;
```
As far as I know php lacks anything like prime number functionality so this is kind of a pain. It's probably possible to do better.
use like:
```
php -r "for(;$i=$argv[1]--;){for($n=$j=1;$j++<$i;)if(!($i%$j)){$i/=$j;$n++;if(!($i%$j))continue 2;}$a+=$n%2?1:-1;}echo$a;" 10000
```
[Answer]
## Racket 103 bytes
```
(λ(N)(for/sum((n(range 1 N)))(define c(length(factorize n)))(cond[(= 0 c)0][(even? c)1][(odd? c)-1])))
```
Ungolfed:
```
(define f
(λ(N)
(for/sum ((n (range 1 N)))
(define c (length (factorize n)))
(cond
[(= 0 c) 0]
[(even? c) 1]
[(odd? c) -1]))))
```
[Answer]
## CJam (20 bytes)
```
qiM{_,:)(@@f/{j-}/}j
```
[Online demo](http://cjam.aditsu.net/#code=qiM%7B_%2C%3A)(%40%40f%2F%7Bj-%7D%2F%7Dj&input=13)
Uses the formula from OEIS
>
> `sum(k = 1..n, a([n/k])) = 1`. - David W. Wilson, Feb 27 2012
>
>
>
and CJam's memoising operator `j`.
### Dissection
```
qi e# Read stdin as an integer
M{ e# Memoise with no base cases
e# Memoised function: stack contains n
_,:)( e# Basic manipulations to give n [2 .. n] 1
@@f/ e# More basic manipulations to give 1 [n/2 ... n/n]
{j-}/ e# For each element of the array, make a memoised recursive call and subtract
}j
```
[Answer]
## JavaScript (ES6), 50 bytes
```
n=>[1,...Array(n-1)].reduce((r,_,i)=>r-f(n/++i|0))
```
Port of @Dennis's Python answer.
[Answer]
# Julia, ~~26~~ 25 bytes
```
!n=1-sum(map(!,n÷(2:n)))
```
[Try it online!](http://julia.tryitonline.net/#code=IW49MS1zdW0obWFwKCEsbsO3KDI6bikpKQoKZm9yIG4gaW4gWzE6MTA7WzExNyw1NTI1LDcwNDQsODg4OCwxMDAwMF1dCiAgICBAcHJpbnRmKCIlNWQgLT4gJTNkXG4iLCBuLCAhbikKZW5k&input=)
### Background
This uses the property

from [A002321](https://oeis.org/A002321), which leads to the following recursive formula.

### How it works
We redefine the unary operator **!** for our purposes.
`n÷(2:n)` computes all required quotients, our redefined **!** is mapped over them, and finally the sum of all recursive calls is subtracted from **1**.
Unfortunately,
```
!n=1-sum(!,n÷(2:n))
```
does not work since dyadic *sum* will choke on an empty collection.
```
!n=n<2||1-sum(!,n÷(2:n))
```
fixes this, but it doesn't save any bytes and returns *True* for input **1**.
[Answer]
# C, ~~51 50~~ 47 bytes
```
f(n,t,u){for(t=u=1;n/++u;t-=f(n/u));return t;}
```
Edit: Thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for -3 bytes!
[Answer]
# PARI/GP, 24 bytes
```
n->sum(x=1,n,moebius(x))
```
[Answer]
# Scala, 53 bytes
```
def?(n:Int,k:Int=2):Int=if(n<k)1 else?(n,k+1)- ?(n/k)
```
A port of Dennis's pythin answer.
I've called the method `?`, which is a token that doesn't stick to letters.
[Answer]
# Pyth, 12 bytes
Defines a function `y` that takes in the `n`.
```
L-1syM/LbtSb
```
[Test suite here.](http://pyth.herokuapp.com/?code=L-1syM%2FLbtSby&input=5&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A117%0A5525%0A7044%0A8888%0A10000&debug=0) (Note that the trailing `y` here is to actually call the declared function.)
[Answer]
# Actually, ~~18~~ ~~17~~ 16 bytes
Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=UmA7eTtsMH7igb8pz4A9KmBNzqM&input=ODg4OA)
```
R`;y;l0~ⁿ)π=*`MΣ
```
**Ungolfing**
```
Implicit input n.
R Push the range [1..n].
`...`M Map the following function over the range. Variable k.
; Duplicate k.
y Push the distinct prime factors of k. Call it dpf.
; Duplicate dpf.
l Push len(dpf).
0~ Push -1.
ⁿ Push (-1)**len(dpf).
) Move (-1)**len(dpf) to BOS. Stack: dpf, k, (-1)**len(dpf)
π Push product(dpf).
= Check if this product is equal to k.
If so, then k is squarefree.
* Multiply (k is squarefree) * (-1)**(length).
If k is NOT squarefree, then 0.
Else if length is odd, then -1.
Else if length is even, then 1.
This function is equivalent to the Möbius function.
Σ Sum the results of the map.
Implicit return.
```
[Answer]
# J, 19 bytes
```
1#.1*/@:-@~:@q:@+i.
```
Computes the Mertens function on `n` using the sum of the Möbius function over the range `[1, n]`.
## Usage
```
f =: 1#.1*/@:-@~:@q:@+i.
(,.f"0) 1 2 3 4 5 6 7 8 9 10 117 5525 7044 8888 10000
1 1
2 0
3 _1
4 _1
5 _2
6 _1
7 _2
8 _2
9 _2
10 _1
117 _5
5525 5
7044 _25
8888 4
10000 _23
```
## Explanation
```
1#.1*/@:-@~:@q:@+i. Input: integer n
i. Range [0, 1, ..., n-1]
1 + Add 1 to each
q:@ Get the prime factors of each
~:@ Sieve mask of each, 1s at the first occurrence
of a value and 0 elsewhere
-@ Negate
*/@: Reduce each using multiplication to get the product
1#. Convert that to decimal from a list of base-1 digits
Equivalent to getting the sum
```
[Answer]
# [Factor](https://factorcode.org) + `math.extras math.unicode`, 27 bytes
```
[ [1,b] [ mobius ] map Σ ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY8xDoIwGIV3TvG7C6EFBPUAxsXFOBGGglUZKFjaRGM8iQuJwUt4B3ev4mRpSfqWfu_15TV9vA6kEDXvvr_ddr1ZLaAi4uTRi-CkNcwJO9KRJSuLek-h4VSIa8NLJqClZ0lZoSpL5-aAEoIJIE1Yka8pUOSaMLQYDYg1zmwa2zSxOLeIfFtGSNcjsxfhYdKY2A_1U9jYREnZcFxQ0peBc--lOLjJO4UUTfMMUqjqvJQtZOrTDXyekJlGP1jPcNeZ8w8)
]
|
[Question]
[
## Background
[**Binomial transform**](https://en.wikipedia.org/wiki/Binomial_transform) is a transform on a finite or infinite integer sequence, which yields another integer sequence. The binomial transform of a sequence \$\{a\_n\}\$ is given by
$$s\_n = \sum\_{k=0}^{n}{(-1)^k \binom{n}{k} a\_k}$$
It has an interesting property that applying the transform twice will yield the original, i.e. the transform is an *involution*.
## Example
Take the sequence `1, 3, 9, 27, 81`. The binomial transform of this sequence is computed as follows:
$$
\begin{align}
s\_0 &= a\_0 = 1\\
s\_1 &= a\_0 - a\_1 = -2\\
s\_2 &= a\_0 - 2a\_1 + a\_2 = 4\\
s\_3 &= a\_0 - 3a\_1 + 3a\_2 - a\_3 = -8\\
s\_4 &= a\_0 - 4a\_1 + 6a\_2 - 4a\_3 + a\_4 = 16
\end{align}
$$
So the binomial transform of `1, 3, 9, 27, 81` is `1, -2, 4, -8, 16`. Verifying that the binomial transform of `1, -2, 4, -8, 16` is indeed `1, 3, 9, 27, 81` is left as an exercise to the reader.
## Task
Compute the binomial transform of a given finite integer sequence.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Note that each test case works in both directions, i.e. if the left side is given as input, then the right side must be output, and vice versa.
```
[0] <-> [0]
[20, 21] <-> [20, -1]
[1, 3, 9, 27, 81] <-> [1, -2, 4, -8, 16]
[20, 21, 6, 15, 8, 48] <-> [20, -1, -16, -40, -80, -183]
[0, 1, 2, 3, 4, 5, 6] <-> [0, -1, 0, 0, 0, 0, 0]
[0, 1, 1, 2, 3, 5, 8, 13, 21]
<-> [0, -1, -1, -2, -3, -5, -8, -13, -21]
[1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0]
<-> [1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
_ƝƬZḢ
```
[Try it online!](https://tio.run/##y0rNyan8/z/@2Nxja6Ie7lj0//9/Qx0FYx0FSx0FI3MdBQtDAA "Jelly – Try It Online")
```
_ƝƬZḢ Main Link
Ƭ While results are unique (until we hit the empty list)
Ɲ To each (overlapping) pair,
_ Subtract
Z Zip; columns to rows
Ḣ The first column
```
On the Wikipedia page, it says that the binomial transform is just the Nth forward differences. So, we just keep getting the difference array until we hit the empty list and stop, and then just grab the left column.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 45 bytes
```
def f(h,*t):print(h);f(*[h-(h:=x)for x in t])
```
[Try it online!](https://tio.run/##TZAxC4MwEIVn/RU3JnKCUWutpWOH7qWLOJQaiSAaQgrx19vTFBGS49737nEkerZqGrNSm2VpZQcdUxhZXmnTj5Ypfu1YVKuYqermeDcZcNCPYBu@rGJYRR1CnTRINU0QUrG1AiFDuJA@I5TiYCMUCOJEFCEvN4M44XSL5AjkFQe@Wz4jsuMSOjQVC3/3wJHRaFOFgTUz1YDeM/AwkO4jtQX2eg9feTdmMgiPsZXu3z9n7TFfQ/43@PID "Python 3.8 (pre-release) – Try It Online")
Takes input splatted like `f(1,2,3)`, outputs by printing entries one per line, terminates with error.
Computes repeated differences, taking advantage of the [Python 3.8 walrus operator](https://codegolf.stackexchange.com/a/180041/20260) `:=` to do so in a list comprehension.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes
```
,/*'(-/'2':)\
```
[Try it online!](https://ngn.bitbucket.io/k#eJw9jEEOgCAQA++8ojfUQKALKvIWzvz/CS5BTDZtOplsry4cdvPBiq17M6Y3FzUkQqhNJDyQG4WL4gJPFOSiJIIQdTJO5R+YaDhM6w0R4TluGv96AXuaGE8=)
* `(...)\` run a converge-scan, repeating until consecutive executions return the same result, or a result matches the initial input
* `-/'2':` take the forward differences
* `,/*'` take the first value of each row, and flatten to remove the trailing empty list, `()`
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
-/@:*!/~@i.@#
```
[Try it online!](https://tio.run/##hVBLDsIgEN17iqcuas20BfoRSUyamLhy5QVYGBt14w28Og5gsboxYQK8eZ@Bu1uU2YCdQQaCgOEqSuxPx4Mrqt6s59Wzv5X90uWzy/n6wGqAyFEYkEiAEgQlA@qPVqaOJNSELbc3BB0pjFlFaHjTBNn92BA6RlumM0dPTH1xyzb@pgOk689Q5I1VyGNr1ndB@5aK6foRJV0MlXV6TcqNI1vu2DbObT3Nqq@nxpxRkcyn2PgD/3gMuBc "J – Try It Online")
For e.g. 1 3 9 27:
`!/~@i.@#` table of bionimal coefficients
```
1 1 1 1
0 1 2 3
0 0 1 3
0 0 0 1
```
`*` times the input
```
1 1 1 1
0 3 6 9
0 0 9 27
0 0 0 27
```
`-/@:` reduce bottom to top with minus
```
1 1 1 1 => + 1 1 1 1
- 0 3 6 9 - 0 3 6 9
- 0 0 9 27 + 0 0 9 27
- 0 0 0 27 - 0 0 0 27
----------
1_2 4 _8
```
[Answer]
# JavaScript (ES6), ~~47~~ 45 bytes
Using forward differences, [as hyper-neutrino first did](https://codegolf.stackexchange.com/a/229775/58563).
Returns a comma-separated string.
```
f=([n,...a])=>a+a?n+[,f(a.map(v=>n-(n=v)))]:n
```
[Try it online!](https://tio.run/##jVJfT8MgEH/vp7hHmh2s0K2ihvrkp2h4IHWdmgnLZvr160FdJXFmEghw/P7cXXh3ozv3p7fjJ/fhZTdNg2GdRyGEs6Vp3co9@VWHA3Piwx3ZaFrPmTdjWZb2wU@PXQHQVRbhP2O9jtjIUBWCkrdpkRGxXCaaRKgR7ol7h6D/5kcaYblC2NCmEWST@SI0FNmSBL3rayo/vnERmm/iTaeQrpMWnelVpZTIheSaqwmlqmepKp@ZyKIz5yTrX93JRPh3ZZxQfDuXxyOFq6VLs9cFvZjkMXvp0i0gBWxhCzGE07PrX5kD00If/DkcduIQ9ow@B32H6Qs "JavaScript (Node.js) – Try It Online")
### How?
At each iteration, we extract the leading term \$n\$ of the array, append it to the final output and do recursive calls with the forward differences until the array is empty.
**Example:**
```
[ **20**, 21, 6, 15, 8, 48 ] < input
[ **-1**, 15, -9, 7, -40 ]
[ **-16**, 24, -16, 47 ]
[ **-40**, 40, -63 ]
[ **-80**, 103 ]
[ **-183** ]
^
output
```
---
# JavaScript (ES6), 74 bytes
A naive implementation that actually computes the binomial coefficients.
```
a=>a.map((_,n)=>a.reduce((t,v,i)=>t+(g=k=>k?g(--k)*(k-n)/~k:i&1?-v:v)(i)))
```
[Try it online!](https://tio.run/##jVLNToNAEL7zFHMyuzoDLLSINdCTT9EQs6GASIWGIkdfHWfBIoltKlnC7rffz8yEd93rU9qWx47qZp8NeTToKNb2hz4K8Yq1NIc223@mmRAd9lgy0j2IIqqiuNoWgqiS96KiWjpf1aa8U1vqN70UpZRyeN5ZADs3QfjP4ziGaxSei@Cp2zKjMFxSo0wh@AhPrH1ECK/rjYy55CGs@BMiqGCRixAwsmYLvg8vufzmmpfZtDKncIRCf/TiPd96Y0mcwnbBxYLGricrd7kWJrPPVJPy/0xnYUI/nRGzaD21R0ZC3jylKevMnkOWWHKe0i0iA4mVWHbetC86fRMaohjSpj41h8w@NIXIhTb/wjc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 48 bytes
```
[ [ dup first . differences vneg ] until-empty ]
```
[Try it online!](https://tio.run/##XY9NbsJADIX3OcW7AFEmQAn0AFU3bFBXiMVocGBEMpmOHVSEcvZ0oiD@LC/8nr9nyaU20oT@Z/O9/lrhRMFRBabflpwhhg8kcvHBOkGt5ZieaeAZthk1ixbLYg0/Uin9SdCMzyS5Joh1RYbuNuUZcnVXClMskS9QqDfiA2qOArPi7meRziM/wzxun93RH3A1fb2u4n6ihs7eVJd0/RZb7FuP0gYWpNjbsqQwfn52dMAOrRNbTaj2csEuBlwVTdPUvmECaXPs/wE "Factor – Try It Online")
Output the first member of the input sequence to stdout followed by a newline, take the differences, and flip the sign of each element until empty.
[Answer]
# [R](https://www.r-project.org/), 45 bytes
```
function(x)for(i in x){show(x[1]);x=-diff(x)}
```
[Try it online!](https://tio.run/##jY/dCgIhEIXvfYq5VHAg3Z@M2CeJrjYkb3ZhKxKiZ7dRW9e7AkU9850zzhLsEOxjGu9unrgXdl64AzeBF6/bdX5yf1JncfQDXpy1BLyD5SNXEhoJBwl6L8EoIVjSUEto6TASVC8Yi6jeEZWJeEUl2P8JW4CEnqSOWAJMFRc3lbCNL5Mk02QnPaisUycKJXOfjF/frl61o5hyO9WUCUrH/FOkCnb5uxgx1Nt4ucOKl@RaW6f@xZEgwgc "R – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
Wθ«I…θ¹≔EΦθλ⁻§θλκθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUGjUFOhmoszoCgzr0TDObEYSFQm56Q6Z@QXaBTqKBhqampac3E6Fhdnpudp@CYWaLhl5pSkFoHkcjR1FHwz80qLNRxLPPNSUitggtmaQKIQqK/2///oaEMdBWMdBUsdBSNzHQULw9jY/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Wθ«
```
Repeat until there are no more terms.
```
I…θ¹
```
Output the next term on its own line.
```
≔EΦθλ⁻§θλκθ
```
Calculate reverse differences.
The binomial transform can be represented as a sort of reverse Pascal's Triangle where each value is the sum of the two below (here using the original `1, 3, 9, 27, 81` example):
```
1
3 -2
9 -6 4
27 -18 12 -8
81 -54 36 -24 16
```
The transform then appears on the rightmost entries on each row. Since addition is commutative, the symmetry demonstrates that transform is thus an involution.
The above code calculates the transform by calculating the bottomleft-topright diagonals in turn from topleft to bottomright. It's also possible to calculate the topleft to bottomright diagonals in turn from bottomleft to topright. The natural code to do this in Charcoal would normally take 17 bytes but unfortunately a combination of factors prevents this from working:
```
F⮌θ≔⁻ιE⊕LυΣ…υλυIυ
```
Don't try it online! Explanation:
```
F⮌θ
```
Loop over the terms in reverse order.
```
≔⁻ιE⊕LυΣ…υλυ
```
Theoretically calculate the next diagonal by vectorised subtraction of sums of prefixes (i.e. cumulative sums but including a leading zero term) from the next term. This doesn't work because a) Charcoal can't calculate `CycleChop([], 0)` at all and b) Charcoal returns `None` for `Sum([])`. The cheapest fix for both of these is to use `And(l, ...)` at a cost of 2 bytes to avoid trying to sum the empty prefix at all, or alternatively each issue can be worked around separately at a cost of 1 byte each.
```
Iυ
```
Output the final diagonal.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~10~~ 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
É¿F▒x"╢
```
[Run and debug it](https://staxlang.xyz/#p=90a846b17822b6&i=%5B0%5D+%0A%5B20,+21%5D+%0A%5B1,+3,+9,+27,+81%5D+%0A%5B20,+21,+6,+15,+8,+48%5D+%0A%5B0,+1,+2,+3,+4,+5,+6%5D+%0A%5B0,+1,+1,+2,+3,+5,+8,+13,+21%5D++++%0A%5B1,+1,+0,+-1,+-1,+0,+1,+1,+0,+-1,+-1,+0%5D++++%0A&m=2)
the lack of a short method to get fixpoint made this a bit more interesting.
## Explanation
```
rwcHP:-c
r reverse
w do-while top of stack is truthy
cHP print last element of the array
:- get deltas (returns [] for 2-element arrays)
c copy
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes
```
⁽¯↔vh
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%81%BD%C2%AF%E2%86%94vh&inputs=%5B1%2C%203%2C%209%2C%2027%2C%2081%5D&header=&footer=)
Me when very many yes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
J’cþ`NÐeZḋ
```
[Try it online!](https://tio.run/##y0rNyan8/9/rUcPM5MP7EvwOT0iNerij@////4Y6xjqWOkbmOhaGAA "Jelly – Try It Online")
## Explanation
```
J | 1..length of sequence
’ | Decrement by 1
cþ` | Outer product using nCr
NÐe | Negate even indices
Z | Transpose
ḋ | Dot product with input
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 27 bytes
```
,\(+/⊣×⊢(!⍨ׯ1*⊢)1⍳⍤+⊢)¨⍳∘≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8f9KhtQvWj3l1ApADBW4EIRNUCibkKAfk5lWmZOTkKaflFQIElXI/6pnr6AzUZ/E8DkjoxGtr6j7oWH57@qGuRhuKj3hWHpx9ab6gF5GkaPurdHKQNYh1aAWQ@6pjxqHPR//9pCgZcaQpGBgpGhkDaUMFYwVLByFzBwhAsqgMU1lEw01EwNNVRsNBRMLEACgNFgYJGOgrGQAEdBaCMGVwULgFRb2isAzUYLAVUA3QOlIBrQBUFAA "APL (Dyalog Unicode) – Try It Online")
I was too lazy to read the article, here's a stupid solution. ~~I don't know why it doesn't work in TIO, but it does work on my computer~~. Requires zero-indexing.
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
f=lambda a:len(a)>1and f([x-y for x,y in zip(a,a[1:])])or a[0]
```
[Try it online!](https://tio.run/##HcrBCoMwEIThV5ljFlIwtooI9UVCDls0NKBrkByML5@aXj5@hok5fXd5luLfK2@fmcHjuohimgzLDK/s@cjw@4FTZwTBFaJizdaMjhzdO9vGlXgESep@A2gbXTVV9FXT/XuovgY4ovID "Python 3 – Try It Online")
Recursive deltas until one element left.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~34~~ 31 bytes
```
(a=Most@a-{##2};#)&@@a&/@(a=#)&
```
[Try it online!](https://tio.run/##PYzNCsIwEITveY1AUZhiNv2xIpW8gCB4FA9LsbSHVtDcQvrqsaEY2MPMNx87sR1eE9ux49C3Ycft9f21hnMnpfZnuc@M4exg1mHN4fYZZ/uQ@aU38pkt947nxQmnPITTCppiIBQ4QR/RUOKoQRUalE1ECgS9WiUq1H@woShRkT4RFHKKtympeeHDDw "Wolfram Language (Mathematica) – Try It Online")
Uses the differences method.
```
(a=#) assign a to input
/@ step through input:
a=Most@a-{##2}; update a to its forward differences
( #)&@@a& while taking its first element (pre-update)
```
[Answer]
# [Red](http://www.red-lang.org), 95 bytes
```
func[v][v: make vector! v until[print v/1 u: copy v
move back tail u u take v: u - v empty? v]]
```
[Try it online!](https://tio.run/##TU/LCoNADLz7FVPvUmPVWintP/S65KDrSsXHiqwL/Xq7VikmgSSTmZBMqlpeqhLs1TmWeh6ksCxsjr5oFaySRk8nWMyDaToxTs1gYM@EOYfU4wfW67VVKAvZwhRNh9m5@WlzVwVOqvrRfJ6wzEutJ1XIN0oID85EyFuOQkS014QLboiuyOg4RQpKkCHOdjQEIXLcGAnSA7ahK5Uux62EEAGtsbH@HXu8fyZ63VXuOv8ePHxGjZKXLw "Red – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 44 bytes
```
f=function(x)if(sum(x|1))c(x[1],f(-diff(x)))
```
[Try it online!](https://tio.run/##jY9NDsIgEIX3nIIlk8wkhf6IC09iXNVM0oU1UZt04d1xAEvZaQIB3nzvDfMIgU@8zONrus9mhYnNc7mZ9W0BRrOe7QXZ0HViliJAYDMai7pFfUTtDqi9gCpp5FB3cnjUdgClIuoaoTIRr2RB/Z@wB6AeROqFFcBXcXFLibr48knybXbKQ8oudZJQMQ/J@PU19aodxZTb2bZMUDrmn5JUqM/fpYiR28fLHTa8JNfaNvUvTgQIHw "R – Try It Online")
Recursive function, taking inspiration from [pajonk's answer](https://codegolf.stackexchange.com/a/229798/95126).
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Nc¡=ä-})y
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=TmOhPeQtfSl5&input=WzEsIDMsIDksIDI3LCA4MV0)
```
Nc¡=ä-})y :Implicit input of array U
N :Array of all inputs
c :Concatenate
¡ : Map U
= : Reassign to U
ä- : Consecutive pairs, reduced by subtraction
} : End map
) :End concat
y :Transpose
:Implicit output of first element
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 69 bytes
```
a->{for(int l=a.length,i=0,j;++i<l;)for(j=l;j-->i;)a[j]=a[j-1]-a[j];}
```
[Try it online!](https://tio.run/##bVFda8IwFH33V1wEoZ1JseqcW2xh7HnswUfpQ1Zbly5NS5IKIv3t3e2HRXCQz3POPTf3JuNnTrPjbyPystAWMrx7lRXSe2KTByytVGxFoVoyltwY@ORCwXUCUFbfUsRgLLe4nQtxhBw5Z2@1UKdDBFyfjNtJAT4KZao80Tuh7CEKIQ0aTsNrWmgHEZAB92SiTvaHiGBBMjafi51kbstngWQZpaFgLj9kUYAL9SPanlndsM6@c8WUNjHWQDAkBbjCAmoyXpYLAkv/HvEJrAi8IvxCYOs/iglsCPjPSBJYb@95pJFddgZrAijZPNKjonfwV/88AAeKqd/PMe4eu0XUfbnYFnDOXHf1vvVVu2PRLaETU0mLnXjXml@MFxfl5St1WiXp9EO7XTYEpR6P46S0Th854vuLsUnuFZX1SvxXmzrTmYEdDWFmZmpKbgls0f97l8J9hAfbwbeetLNu/gA "Java (JDK) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~49 43~~ 42 bytes
```
f=->a{k,*a=a;k ?[k]+f[a.map{|x|k-k=x}]:[]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6xOltHK9E20TpbwT46O1Y7LTpRLzexoLqmoiZbN9u2ojbWKjq29n@BQlp0tJGBjoKRoY6CmY6CoamOgoWOgolFbOx/AA "Ruby – Try It Online")
[Answer]
# MMIX, 52 bytes (13 instrs)
Prototype: `void __mmixware bintran(int64_t *seq, size_t len)`
jxd:
```
00000000: 3b020101 5a010002 f8000000 27020201 ;£¢¢Z¢¡£ẏ¡¡¡'££¢
00000010: 2c030200 8d040308 8dff0300 2604ff04 ,¤£¡⁽¥¤®⁽”¤¡&¥”¥
00000020: ad040308 5b02fffa 27010101 e7000008 Ḍ¥¤®[£”«'¢¢¢ḃ¡¡®
00000030: f0fffff4 ṅ””ṡ
```
Disassembly:
```
bintran SUB $2,$1,1 // i = len - 1
PBNZ $2,0F // if(i) goto loop
POP 0,0 // return
0H SUBU $2,$2,1 // loop: i--
8ADDU $3,$2,$0 // int64_t t = seq + i
LDO $4,$3,8 // a = t[1]
LDO $255,$3,0 // b = t[0]
SUBU $4,$255,$4 // a = b - a
STO $4,$3,8 // t[1] = a
PBNZ $2,0B // if(i) goto loop
SUBU $1,$1,1 // len--
INCL $0,8 // seq++
JMP bintran // bintran(seq, len) (tail recursion eliminated)
```
If you wish to add early exit on zero length, this costs four bytes more.
```
bintran BZ $1,1F
2H PBNZ $2,0F
1H POP 0,0
0H SUBU $2,$2,1
(etc)
JMP 2B
```
The resulting machine code is identical except by prefixing of `42010001` (`B¢¡¢`).
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 35 bytes
```
a->[a*Col((x-1)^n,#a)|n<-[0..#a-1]]
```
[Try it online!](https://tio.run/##TY1BCoNADEWvEnQzUxIxaq2F1k2PMUwhG4sgdpAuWujdp7GCCknIf/@HBJl6eoTYwTUKtU4Ot@dgzJvY3kdMxX7HC7k8y1Ih9j5KCMPHCFALYerHl67JLBLojFiL4FzudRY5QsHzxgglwlnlCaHhzUSoEfioEKFqZq5YafE/qBDUqje8OssFl7sHWhoiXnrN75n3Nv4A "Pari/GP – Try It Online")
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 38 bytes
```
a->Vec(subst(Ser(a),x,-x/t=1-x)/t+y)%y
```
[Try it online!](https://tio.run/##TY3RCoMwDEV/JQiDlqVo1Dn3oD8x2Iv0oRs6BBlFO6hf38UJKiQhOfdeYs3Yq7cNHVTBqPrRvsT0fU5O3NtRGIkelY9dRcrL2J1neZqDsXaYhQFVgx37j@M1Wo4IOk5IhKZJNM80QUhp2QghQ7jxeUUoaRcRCgS6METIy4UzZpr@AzkCS8WON2VNUHZ4wMUmRWtv/iPTWoYf "Pari/GP – Try It Online")
]
|
[Question]
[
A tower is made out of layers, each one being one unit shorter than the one below it. Every layer is completely on top of the previous layer. For example, here is a tower along with it's height map:
```
#
##
###
####
#####
14532
```
Because the lengths of the layers are the integers from 1 to n, and because the layers are completely on top of each other, the height map will always be a permutation of the integers from `1` to `n`. (Can you see why? Comment below)
The converse is not true. Some permutations are not the height map of a tower, meaning they are not *tower permutations*. For example, `[2,1,3,5,4]` is not the height map of any tower, meaning that it's not a tower permutation. However, `[1,4,5,3,2]` is a tower permutation, as you can see from the previous ascii drawing.
Just to be clear, the following is **not** a tower:
```
#
##
###
# ###
#####
21354
```
Because each layer has to be continuous. This is instead a castle :P
Your task is to take a permutation of the integers 1 to n (inclusive) and decide if it's a tower permutation, as per usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") rules. You can assume that `n>0`
# Test cases (all permutations up to n=4)
```
[1] -> True
[1, 2] -> True
[2, 1] -> True
[1, 2, 3] -> True
[1, 3, 2] -> True
[2, 1, 3] -> False
[2, 3, 1] -> True
[3, 1, 2] -> False
[3, 2, 1] -> True
[1, 2, 3, 4] -> True
[1, 2, 4, 3] -> True
[1, 3, 2, 4] -> False
[1, 3, 4, 2] -> True
[1, 4, 2, 3] -> False
[1, 4, 3, 2] -> True
[2, 1, 3, 4] -> False
[2, 1, 4, 3] -> False
[2, 3, 1, 4] -> False
[2, 3, 4, 1] -> True
[2, 4, 1, 3] -> False
[2, 4, 3, 1] -> True
[3, 1, 2, 4] -> False
[3, 1, 4, 2] -> False
[3, 2, 1, 4] -> False
[3, 2, 4, 1] -> False
[3, 4, 1, 2] -> False
[3, 4, 2, 1] -> True
[4, 1, 2, 3] -> False
[4, 1, 3, 2] -> False
[4, 2, 1, 3] -> False
[4, 2, 3, 1] -> False
[4, 3, 1, 2] -> False
[4, 3, 2, 1] -> True
```
[Answer]
# [Python](https://docs.python.org/3.8/), 46 bytes
```
f=lambda l:len(l)<3or min(l[:3])<l[1]*f(l[1:])
```
[Try it online!](https://tio.run/##dZJBboMwEEX3nGJ2wZVTyXgWFQpd9gTdIRZGdRqkCUHGadXTUwdjFYy7m3n@fH/PMPzYy62XL4OZpnNF6tp@KKCSdJ8TO8mbgWvnyrqUDTtRLZqns@tE2bDp@9KRBlFmoHhbdf1wtzl7HgfqbH6A4yscWAZU6S9FuXKlVeZTW6hgJq0jRo@udYauHkzX23wm1SLlQPyh4UvPJnf/w/jd3HVWCw7Fqi04xKcc5JbI/SdB86Zo9EhujeQsKtYiOXsnbuOAO4jJFEG5OHqK23jCkyihp@mXRK6eYvqJe61PILa2mJwR/jemyFWGBKn57bXFKsEfxeQGcLcEDBE2aTGMpohoYvsY1igimvgJMCxyFeEX "Python 3.8 (pre-release) – Try It Online")
Uses the characterization
>
> A tower permutation is one where no element is smaller than both its neighbors.
>
>
>
---
## [Python 2](https://docs.python.org/2/), 36 bytes
```
lambda l:'-1, 1'in`map(cmp,l[1:],l)`
```
[Try it online!](https://tio.run/##dZLBboQgEIbv@xRzExO2CTAnE3vcJ@jNbrrYsl0TtETZbvr0FlFSRXobPn7/@ZnR/NjbV8fHa/k6atnWHxJ0kR0ZBZY13aWVhry3huqKFWeq88v4uDVaASsOIGld9vLx1nTmbkn@NBjdWJLB8Rmy/AC6VN9SE@lKK/tPZaEET2pHejW445VoV5u@6SwQj8pFm0/lSepBUdB0ktPlZqzYeWrx0t/VoXI5@erIXezoloLYErH/JGh8Q4/E1kh4EV@LhPdOdKOAO4jJFEG5OM4Ut/HYTKKEM02/JHKdKaafuNfOCdjWFpMzwv/GFLmKkCA1v72WrxL8UUxuAHdLwBBhkxbDaHhEE9vHsEYW0cRPgGGRqwi/ "Python 2 – Try It Online")
Really crams in the Python 2 nostalgia: `cmp`, backticks, `map` producing a list.
The idea is to use `cmp` to compare consecutive elements to detect an decrease (`-1`) followed by an increase `(+1)`. This is identified by the string representation containing the substring `-1, 1`, so that tower permutations give `False` and others give `True`.
---
## [Python 3](https://docs.python.org/3.8/) error code, 32 bytes
```
def f(a,*l):(a,)>l<l[1:]or f(*l)
```
[Try it online!](https://tio.run/##dZJBbsMgEEX3PsXsgitaCTOLyilZ9gTdWVmQljSWkIMwaZvTu9gY1cZ0hef58/nMYO7ucu34s7HD8KHOcCaSPuiy9kt50C@6YfXxaj32cPi@tFoBqwuQ9CTaztwcKZ96o1tHdvB4gF1ZgBbqS2oi/aeT9lM5EDCR00jsvZ689lb14lXqXhWgft6VcfVI3uzNA2PbzhFfgxCzCQVNwRM61@XQsON45LSjYRSqRVlRSP9S4GvCt1uiJuQaEV8b8UlULUV88s6cRgE3ELMponJ2DBTX8VggScJA8zdJXAPF/BW32pCArW0x2yP8r02JK48Jcv3baqtFgj@K2QngZggYI6zSYmxNldDM9DGOkSU08wgwDnIR4Rc "Python 3.8 (pre-release) – Try It Online")
A nifty short solution by loopy walt. Takes inputs splatted and outputs by erroring or not erroring, with successful termination indicating *not* a tower permutation.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~5~~ 4 bytes
```
>ƝṢƑ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6Fivsjs19uHPRsYlLipOSi9ccm3y4_eHOlkNLDA_thyhYcIuxLdpQR8FIR8FYR8EklgvKMQHy4RwoyxgsbAThmID5RnAZKAtEGcGUGkI4EKWGcBkQC2oWhAM1Cy5jBFcNomBMZBdCFJlAlBvCOVDz4TJGcA6UBfeLCdxjJjADjOGuNYTLGME5CJYxzCgjuG6o_41huo3gnjKEyyBYRvDAMYEFPJADiQ8A)
Explanation:
```
(implicit input) [1, 4, 5, 3, 2]
Ɲ for each neighouring pair: [(1, 4), (4, 5), (5, 3), (3, 2)]
> is left greater than right? [0, 0, 1, 1]
ṠƑ is it the same after sorting?
(implicit output)
```
This tests if the list is increasing and then decreasing again.
[Answer]
# [Julia 1.0](http://julialang.org/), ~~26~~ 23 bytes
```
!v=issorted(diff(v).<0)
```
[Try it online!](https://tio.run/##hVLBbsMgDL3nK@iNSGgq2MflS6JoQguRqCJaAW2n/nyWxoEk3dpewM/v@WEDh3NvtfwZht2lsiEcfTQtb23X8Uv58bkvh2hC/PrWwYSqrmUjaimYGjclWEKCAUWwUJRTU@6ugymnKNrWCoYZ4MYrMzAxigCuj8THU6mGAG66yAy5SQK4bhYf@6UaSG6r/jOjshskN5XBPCkmN8hg7hqTG2QAuWa5NEwXIpumKLQLV@PHB4n@bMR/S6f78Dd8x1O4Xt8rnqhfScYJuqNnPAqmS2Ydu9kTX/6ZmMcri5O3LvaO7yKrqlFbGNcOvw "Julia 1.0 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 33 bytes
Or **[R](https://www.r-project.org/)>=4.1, 26 bytes** by replacing the word `function` with a `\`.
```
function(v)is.unsorted(diff(v)<0)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jTDOzWK80rzi/qCQ1RSMlMy0NKGRjoPk/TSNZw1BTU1lB104hpKg0lQssoKNghC5mpKOAVZ2OgjEWYWMcJiBUuyXmFMPFjbEYbgxWboSh3BhsKS636CiYYJcxwe1QhB6wLf8B "R – Try It Online")
Outputs flipped `TRUE`/`FALSE`.
[Answer]
# [Shue](https://codegolf.stackexchange.com/questions/242897/golf-the-prime-numbers-in-shue), 100 99 bytes
```
=L
=R
,1,R=<,R
1<={
1{={1
,{=<,
L{=L
L1,=L>
>1=}
}1=1}
},=,>
>R=R
LR
,1,1=e
e1=e
1e=e
e,=e
,e=e
LeR
```
[Try it online!](https://tio.run/##lVXBjts2EL3rKwjlEHLNdUtbJyN0UTTepoCxDpRNe/C6BS3TuypkUqCkzS4cf0UPveTr8iObIWXZkiwHGx9kzfDNm@HjDJU@5fdaDZ/jTapNjoykKHvKPCMZ4mD1I71J40Ris/Qxnv/NF59vbzm5IJjXrV984nkruUaFklkkUoljMvIQ/IzMgWjp@86CRbB@du9rbVCEYoXiEml/8dpBhFrBErdxt7f@cXlP2NsvNPx1amcnp2T8DBf/cSp1riz1Mq5WtIgzif4USSEnxmiD1/57YTJpkLTmCN3pHEX3wogoB@c22iGxtm@gAmlyn9OtLITVwJns3MJTLjM8jxYlb7vaF1U6mU1/msyu2jVCgsIo@@eV3ZLayEOrAHYTK5Frk0GlmczxPqxIZNOTxMp54n6WJnGOnezk0FWJ7SqHOda9ce3M@huRR/c4IfWW2/TvjC5SPCQtQWzizxxt8aGtKygjhKIT75DM2WhByO47Ktd2aam7mHd1tWp4WlZUaicfZVTkEkcU1QWsQLDdUt2o3Gqh4gcJNvi3cZlgo1dg3ZhCOvPTPcy5ddZEc4grAZs4@JT89E@N7HgolfqZVb9CNPcOWrtVV@hov8HsR6LhPioUHPjr8DVBY8RGkVZ5rAp5Hjn9HtKmFHRpkzrZmhkrhHbrQt1JnEiFM9Jj5BRZZZ7rke5ZnCALO4yiG9oW03ZDNh/pRW/ZA449w2ixOxvdOsDWMde5vXOja/SdEZtqdpWGrksTEcmNVHmGhJEo1VkWL6EzYAig72CqVmgp78VDrAtD7L3vvUJ//Rpe/3H9O3o7u75BHz9M0NUsRLObd5MQfXj3cYJ@m72deJFeQV3wKfCf@dTjoUcZDfkbGnrsDd96bMu3zKNb8HjTLSCmjPLp2BszvvN2jDN4Uk7BEULs1IUzLj1pH0zaNwoPat@mMnyGPDCNl2zx0vq8w90BX8B@lq9i5U5OACW@2IgUyweR0GR/6fiXYx9uAdf8dtx8v/@vjhWeP174zO/51Ld8j5ZPlJepcWN5GFyQAz62fansGyYOkpoYmtb/@uX/r1/@8@cYQjhINg19wrlcUEFtWpqVf7BKnudsgS7HZRvMGUWDmjmgqL1K0bDpGZ6GVJhy8q1r2CQaOtCgDho67o5sFAUnzqCzigq5Zyy9QbM8VnpaFZbe7p20WEtv0L3FU2xZAWvSBp0aBedkarEOqwq69DvFDmoVHL1B5wkEJ4cQVCU0qg0qaQYtb8fpB9Uxspa3owmC6iCPJXwD "Python 3 – Try It Online")
Takes input as comma-separated list of unary numbers, with a trailing comma.
# Explanation
```
=L - Implicit left edge
=R - Implicit right edge
,1,R=<,R - Spawn a left triangle on the right, if last element is 1. Remove the last element
1<={ - Triangle decrements element, turns into left curly triangle
1{={1 - Curly triangle passes trough ones
,{=<, - Curly triangle turns into a sharp triangle (to decrement next element)
L{=L - After reaching the left edge, curly triangle dissapears
L1,=L> - Same stuff but in the other direction
>1=} - --||--
}1=1} - --||--
},=,> - --||--
>R=R - --||--
LR - If everything has been reduced, output true
,1,1=e - Or if there is a one not located near the edges, create an error
e1=e - Errors propagate
1e=e - --||--
e,=e - --||--
,e=e - --||--
LeR - Final error state
```
[Try it online!](https://tio.run/##lVXBjts2EL3rKwjlEHLNdUtbJyN0UTTepoCxDpRNe/C6BS3TuypkUqCkzS4cf0UPveTr8iObIWXZkiwHGx9kzfDNm@HjDJU@5fdaDZ/jTapNjoykKHvKPCMZ4mD1I71J40Ris/Qxnv/NF59vbzm5IJjXrV984nkruUaFklkkUoljMvIQ/IzMgWjp@86CRbB@du9rbVCEYoXiEml/8dpBhFrBErdxt7f@cXlP2NsvNPx1amcnp2T8DBf/cSp1riz1Mq5WtIgzif4USSEnxmiD1/57YTJpkLTmCN3pHEX3wogoB@c22iGxtm@gAmlyn9OtLITVwJns3MJTLjM8jxYlb7vaF1U6mU1/msyu2jVCgsIo@@eV3ZLayEOrAHYTK5Frk0GlmczxPqxIZNOTxMp54n6WJnGOnezk0FWJ7SqHOda9ce3M@huRR/c4IfWW2/TvjC5SPCQtQWzizxxt8aGtKygjhKIT75DM2WhByO47Ktd2aam7mHd1tWp4WlZUaicfZVTkEkcU1QWsQLDdUt2o3Gqh4gcJNvi3cZlgo1dg3ZhCOvPTPcy5ddZEc4grAZs4@JT89E@N7HgolfqZVb9CNPcOWrtVV@hov8HsR6LhPioUHPjr8DVBY8RGkVZ5rAp5Hjn9HtKmFHRpkzrZmhkrhHbrQt1JnEiFM9Jj5BRZZZ7rke5ZnCALO4yiG9oW03ZDNh/pRW/ZA449w2ixOxvdOsDWMde5vXOja/SdEZtqdpWGrksTEcmNVHmGhJEo1VkWL6EzYAig72CqVmgp78VDrAtD7L3vvUJ//Rpe/3H9O3o7u75BHz9M0NUsRLObd5MQfXj3cYJ@m72deJFeQV3wKfCf@dTjoUcZDfkbGnrsDd96bMu3zKNb8HjTLSCmjPLp2BszvvN2jDN4Uk7BEULsFKIgnnHpSftg0r5ReFD7NpXhMySCcbxki5cW6B0uD/gE9rN8FSt3dAIo8cVGpFg@iIQm@1vHvxz7cA247rfz5vv9f3Ws8Pzxwmd@z6e@5Xu0fKK8TY2by8Pkgh7wte1LZd8wcZDUxNC1/tcv/3/98p8/xxDCQbNp6BPO5YIKatPSrPyDVfI8Zwt0OS77YM4oGtTMAUXtVYqGTc/wNKTClKNvXcMm0dCBBnXQ0HF3ZKMoOHEGnVVUyD1j6Q2a5bHS06qw9HbvpMVaeoPuLZ5iywpYkzbo1Cg4J1OLdVhV0KXfKXZQq@DoDTpPIDg5hKAqoVFtUEkzaHk7Tj@ojpG1vB1NEFQHeSzhGw "Python 3 – Try It Online")
# [Python 3](https://docs.python.org/3/) algorithmic equivalent
```
def f(arr):
if arr==[]:return True
if 1 in arr[1:-1]:return False
if arr[0]==1:return f([e-1 for e in arr[1:]])
if arr[-1]==1:return f([e-1 for e in arr[:-1]])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI7GoSNOKSyEzTQHIsrWNjrUqSi0pLcpTCCkqTQWLGypk5oEkow2tdA3h0m6JOcWpMH3RBrG2toYwqTSN6FRdQ4W0/CKFVITe2FhNuHKgOQTUg6yK1fxfUJSZV6IBVGCkY6hjrGOiYxqrqfkfAA "Python 3 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~8~~ 6 bytes
```
sṪ⌋∈₁Ṫ
```
Outputs false for a tower permutation, true for a non-tower permutation. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/jhzlWPerofdXQ8amoEsv//jzbUMdYx1THRMYoFAA "Brachylog – Try It Online")
### Explanation
Uses the "does it have a local minimum" test from [xnor's answer](https://codegolf.stackexchange.com/a/243180/16766).
```
s For some consecutive sublist of the input
Ṫ which has three elements,
⌋ its minimum
∈₁ occurs at index 1 (i.e. the middle element)
Ṫ in that sublist
```
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), ~~16~~ ~~13~~ 9 bytes
```
mnI<pa lt
```
Returns `True` when it is a tower permutation and `False` when it is not.
The following also works for the same score:
```
mnI<pa cp
```
## Explanation
We want to look for an element which is smaller than both of it's neighbors.
To do this we start with `pa lt`. `pa` takes a function and applies it to all consecutive neighbors, `lt` returns `True` if the first argument is less than the second and `False` otherwise.
```
[1,2,3,5,9,8,7,6,4]
[T,T,T,T,B,B,B,B]
[1,2,9,5,3,8,7,6,4]
[T,T,B,N,T,B,B,B]
```
If we started with a tower permutation this result is some number of `T`s follower by some number of `B`s. If it was not there is a `[B,T]` sub-sequence. This means that we just have to check if the result is monotonically increasing. If it is then it was a tower permutation, if it is not then it wasn't. `mnI` is the function to check if a list is monotonically increasing.
## Reflection
While working on this I found a bug and some documentation errors. None of this actually effects the answer, but I've fixed them.
[Answer]
# [J](http://jsoftware.com/), 19 14 12 bytes
```
-:]/:2>/\0&,
```
[Try it online!](https://tio.run/##dVIxDsIwDNx5hcVAheS2ie0pUlmQmJiYYUJUiIX/T6FqaeQ6yRApuZzts32fuO@aEYYADSA4CNNpOzjfrpfYhkcf6NTf3QHjcfd6vr8wAga/XD0M09MjkH4TQvaPwAbiFOVSlGHRzPKaxZiVY6xVRJAclVTEaSk5l2cuGa4Um5FqPymvRq2Gf6NGA60avOFKcVRSnZbRwKsGMihpDRqVPK8UFyF6FwtXcGsAjdqZCW5toFHO8xbMIJj8EH8 "J – Try It Online")
-5 after realizing from pxeger's answer that I could use sort by instead of group by
another -2 stealing pxeger's idea to use `>` instead of `*@|`
The key insight is that the deltas of successive elements in a tower permutation have at most one "peak":
* `/:` Sort by...
* `2>\0&,` Is left greater than right (pairs of 2
* `-:` Does that equal the original input?
[Answer]
# [Python](https://www.python.org), 49 bytes
```
lambda x:sorted(a:=[*map(int.__gt__,x,x[1:])])==a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZFBasMwFETpNqfQIgupqAF9aVEMPolrjErsxuA4JlUa9wQ9RDaBkN6pPU3t6GvSleZ55g_68ul7-AybXX--NPnL9RCap-cf0_nt69qLMXvf7UO9lj7Li8etH2Tbh1VVvYWq0qMeC5OVqlR57nlwedy0XS2meNsPhyBVNuynEel1I-sP30mvlIrZ8-_DV2G0IC2sFq5cMLiJAazs7TNFcDcmOKzmg1LURIhRA2dW3BWBu-AQ0vOR5P8bxpCLcQPgfjgEYIVdHBZzqcDitgYOAe7KpirCNO9v0zRhKQPnrgiP49LDT7CIP-QP)
Port of my Jelly answer. (Writing this is what inspired the -1 byte golf there)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
V<Ẋ-…
```
[Try it online!](https://tio.run/##TU@xDcMwDHtIGeRo7B1ZjOwBgk5B9zZjD@kR/aZ5RJEZuvYiySRF0ctjW/1@7C@fbr/vezieH3fPWWfJKilqEs4yoo8VxTtQ8FGBB9v0Ypys7RILDnotnaz13tCVydodYmVXMdk/hfU5oIO@ZSKWuAsPssbMQOAHX7DgiNW/4hbZ67/zCQ "Husk – Try It Online")
Outputs zero for towers, non-zero for non-towers.
```
… # Fill gaps with numeric ranges
Ẋ- # Pairwise differences
V # Index of first element that is
< # less than the next one
# (or zero if not found)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
f=->l{l==l.sort||l.pop<l[-1]&&f[l]}
```
[Try it online!](https://tio.run/##Dcu9CoAgFAbQV2lyCLzg0Ja9iDhUKARfKv4MpT27uZ8Ty/H0biXfUCElKPmYWwMFH1YoLjRjVkF/PUxqFkSLpmDiXfKeL@8oGZgz14Zm1Tv6Ce/M0D8 "Ruby – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 76 bytes
```
h->{int d=1,i=1;for(;i<h.length-1;)d&=h[i-1]>h[i]&h[i]<h[++i]?0:1;return d;}
```
[Try it online!](https://tio.run/##VVBNa@MwEL33VzwCKTZNRNW6X3acpZeFPSw9dG/BBzW2Y2Ud20hyIJT8du1oktDtQTN@b968eXir9mq@Lf/6dausxW@lO3xeAcP40eo1rFOO2r7XJXY0i96d0d1mVUCZjY1ZCmzJRIxOt6Ieu7XTfSf@9L869/OMFrpzq2KJGrlv5stPgihzOdO5zOreRJleNKKtuo1r5jKLy@u8Wem5LJbUiutQFs3q5kYXP25TmZnKjaZDmR19xufJAtFemZAJ6bdkwIk36oD8v5yvgbHCOlOpXUQbwg6tdtEEkzgWOzVw/ohetalMmu5VO1ZvdSxcz6tRnJ393w/WVTvRj04M9GtcHU2mNsXUTrvJLGSZoRZqGNrDqw2WnCVGnkOePY5X4R29l17izt@BO@6p3p8wfRMmnh4xxF40SLgnFzVjYkklQ2U@@fKheejJxZFx0EsfXE6Xkq9bNGfV5SpjVnreYj7hPIxon12IZ5bxKTu7Mv8tPx7wiCc84wXyFpLqM@QT5CPkAySZ0RbJ5T8 "Java (JDK) – Try It Online")
Returns `1` if it's a tower, `0` if it's a castle.
[Answer]
# [Quipu](https://github.com/cgccuser/quipu), ~~64~~ ~~58~~ 46 bytes
```
3&2&1&4&\/0&
[][] [] ??
4&3&
[]==
--::
2&
>>
```
Takes input from stdin, one number per line. Outputs by throwing an error for tower permutations and exiting silently for non-tower permutations. [Attempt This Online!](https://ato.pxeger.com/run?1=m720sDSzoHTBgqWlJWm6Fjf1jNWM1AzVTNRi9A3UuKJjo2MVFEDY3p7LRM0YJGJry6Wra2XFZaTGZWcH0QXVvGClIZcRlzGXKZcJRAAA)
### Explanation
Programs in Quipu consist of *threads*, which are two-character-wide columns. This program has six threads, numbered 0 through 5:
```
"0 1 2 3 4 5"
3& 2& 1& 4& \/ 0&
[] [] [] ??
4& 3&
[] ==
-- ::
2&
>>
```
Threads 3 and 4 hold two consecutive numbers in the list. (Initially, they're both 0.) Execution proceeds as follows:
* Thread 0 takes the value of thread 3 minus the value of thread 4 and tests whether the difference is positive, i.e. whether the numbers are in descending order. If they are, jump to thread 2; otherwise, continue to thread 1.
* Thread 1 tests if thread 2 is still 0. If so, it jumps to thread 3; if not, it exits the program.
* Thread 2, if reached, sets its value to 1.
* Thread 3 sets its value equal to the value of thread 4.
* Thread 4 reads and stores a number from stdin.
* Thread 5 jumps back to thread 0.
The end result is that any descending pair sets thread 2's value to 1, and any subsequent ascending pair ends the program. If this descending-ascending pattern never occurs, the program continues until it runs out of input and errors.
[Answer]
# [Behaviour](https://github.com/FabricioLince/BehaviourExolang), 52 bytes
```
t=&(i=1\~([a%i>a%(i+1)a%i>a%(i-1)]i+=1i<#a-1)i>#a-2)
```
I don't exactly know the rules regarding recently self-made esolangs, but here goes nothing.
Ungolfed and commented:
```
t = &(
i=1 // start on the index 1
// repeat the following sequence until failure
\~(
// either the ith member is bigger than the previous or bigger than the next
[
a%i > a%(i+1)
a%i > a%(i-1)
]
// increment index and check if it still is less than n-1
i += 1
i < #a-1
)
// is a tower if the index stopped incrementing on the last possible index (i.e. passed all the checks)
i > #a-2
)
```
Test with:
```
t:{1}
t:{1 2 3}
t:{3 1 2}
```
Bonus (bigger) answer using more obscure features of the language but basicaly the same logic:
```
t=&![#(t=a)<3(#a-2)*&(v=t%(a+1)v>t%a|v<t%(a+2));>&a|b]
```
[Answer]
# Curry, 24 bytes
*Tested to work in both [PAKCS](https://www.informatik.uni-kiel.de/%7Epakcs/) and [KiCS2](https://www-ps.informatik.uni-kiel.de/kics2/)*
```
f(_++a:b:c:_)|b<a&&b<c=1
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI15bO9EqySrZKl6zJskmUU0tySbZ1vB/bmJmnoKVlUJAUWpOaUqqnqe/goYmF1jUVqGgKDOvREFFIU0h2ljHRMdQxyj2PwA "Curry (PAKCS) – Try It Online")
Checks if any value is smaller than both of its neighbors using Curry's powerful pattern matches. Returns a `1` if it isn't a tower permutation and nothing otherwise.
TIO has a limited ability to test things like this. Paste the following to [smap](https://smap.informatik.uni-kiel.de/smap.cgi?new/curry) and run in `PAKCS 2.2.0` for better testing abilities:
```
import Control.SetFunctions
f(_++a:b:c:_)|b<a&&b<c=1
-- Helper to run tests
helper :: [Int] -> Bool
helper a = isEmpty $ set0 $ f a
main =
[ helper [1,2,3]
, helper [3,2,1]
, helper [3,1,2]
, helper [4, 1, 2, 3]
]
```
This test handler will not work in KiCS2 or at least not on the version used by smap. But the function itself does if you want to manually test it.
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 39 bytes
```
[ 3 clump [ dup infimum second= ] ∃ ]
```
[Try it online!](https://tio.run/##fVO7TsQwEOzzFcsHECnxViAoQTQ0QHW6wnJ8h0XsGD8k0OkqGr6THwkhEjlb502qZGZ3PZ6d7LgIgxtfnh4e769g74ZoldkvL7X8CI57eJPOyB68fI/SCOn/cT@48FeveXg9sfNnHY0SQyfBOhnCp3XKBLiuqkMF03OABo5wAZe38OyiXLC2gLZkLSvijJyy1N/x3p8IVjyApXLSBraqCAkGV9Ri6ZhmHtYWmzC9fN6Eq/fHsgNNKu/cHKQoLBrRzjgxD1ftxrLhTerE@S6QohJ9OYX0cpFYL@aRS5swT11OkcHDPHo5RaYPC/k7jpsJFX3UFjbQRQvK7JSOevonxWC6G9jCz/cXbEfNLdTjLw "Factor – Try It Online")
## Explanation
Returns `f` for true and `t` for false.
*"Is there an element that is smaller than both its neighbors?"*
Thanks to @xnor's [answer](https://codegolf.stackexchange.com/a/243180/97916) for the characterization. The shortest I could get the 'sorted signs of differences' method was 44 bytes.
```
! { 2 1 3 5 4 }
3 clump ! { { 2 1 3 } { 1 3 5 } { 3 5 4 } }
[ ... ] ∃ ! (is there any element that...)
! { 2 1 3 }
dup ! { 2 1 3 } { 2 1 3 }
infimum ! { 2 1 3 } 1
second= ! t
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 17 bytes
```
\d+
$*
(1+),\1,\1
```
[Try it online!](https://tio.run/##RY5BDoMwDATvfkeRoPhi8B/6CQ5Uag@9cED8P91MFCElcXa8Wef8Xr/jXYbxtZftM9vjaWPMk2@hVUpY@GKLU33VuTatu7S4toho93hSs7vRonJFPeF556hfa/ZEdPWH1ZQ2Ke9Z6uPqU9E4jVfw5D8ovSdFHIpufycVTtIf "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `0` for a tower permutation, nonzero if not. Explanation: Uses @xnor's observation that each number in a tower permutation is greater than at least one of its neighbours. After unary conversion, the regex simply has to find a run of `1`s where both neighbouring runs of `1`s are at least as long and therefore neither neighbour is lower.
A direct positive test takes a massive 39 bytes:
```
\d+
$*
^(^1+,|1+\1)*((1+),(?!\3))*(1+)$
```
[Try it online!](https://tio.run/##RY6xDsIwDER3/wVSkZzGixvvjPxEVIEEAwsDYuTfw@WiqEPi3PPl7M/z@3rf21mvt1YfWZZVdt09289z9bSqek6ml1MtCQpiac3FbZPNWK3gLkPjDQ2OAwI6PRasMd3UoHB5v8njyEG/15iJ1N3v0lPGpDhmoU/XnEpNp/AXeXAfKvxnCjgp9didqeRM@gM "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Looks for an ascending sequence followed by a descending sequence.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~93~~ \$\cdots\$ ~~59~~ 54 bytes
```
r;f(a,n)int*a;{for(r=0;n-->2;)r|=*a>*++a&*a<a[1];n=r;}
```
[Try it online!](https://tio.run/##dZZdb9owFIbv@ys8JCYCQc05Dl9N015M@xWUiyyEDnVLqwRpaF3/@piJncTnjYYoLn7s18ePEyCfP@f55VIlh0kWlsGxPE2z5P3wWk2qNErK@fyBk6D6k06zh@lsln2eZvfZlnZJmVbJx8UMVz@zYzkJ1PuNMo9rx6moT7TdqVS900fSdbHrChV7vdr2cqj8sXE/NlTaA4sOaJmz7HPkjFUHtFxjbYFuZvhRmw5AVRSJskIV@5B8GMsiiEXdMFP7MJbFUK8iHtighQ/BCEklsObKh1jtWjiDmRsfxtIQRx2MByfB5EM4DWZxHHJN1j4EQxyL84KZCx9itcsOxoOrgFc@hCuBnaG4rVbsc@NDOBUddXB4rWryIRjS3MHhNau1D2217Q05bUbUdkBzhKGt0zbaNrFtFrZZ2mZlm7VtNqG7DVzrcsgFkUsiF0Uui1wYuTRyceTy2OVxW5fLY5fHLo9dHrs8dnns8tjlaZenXZ5uN6p7J01HaZXUx9/F62HSlBTcundT@zZUHmVJWVItqZY0ljSWdCHpQtKlpEtJV5KuJF1LupZ0I@lGUopARwQcdYEvAmEExgiUETgjkEZgjUAbgTcCcQTmCNQRuCOQR2CPQB@BPwZ/DP4Y/DFeb3jBgT8Gfwz@GPwx@GPwx@CPwR@DPwZ/DP4Y/DH4Y/DH4E@DPw3@NPjT4E@DP413LN6yOvA@IYrzW5Gfin33Fes/I@912BO1z2FP9L8et3L@WtYnlX/Pqql5LfKXorIFjJ7OX/npvPli/hajUPnv9cjNNr/b1ORa/LHcF2czLUrcv/ftxttt9VvvehI1mzWjgybM/qLrv0RMnP0iacbsEh@r0tFyQPuaXD2mlrJZKujGXB9vlRl0mIzG9Xhv9nd8vG7ybrQ1zWl73AVyvdqEfTLHGKoSyJshdZpS9Bjd1T2ySgsDu4PFStsKdmr@oMZ7Na6fSrN6HXYnUaRp7Vdye3s8XDfXyE4VBepbVWQvdsDHzcflb374kT3Xl/mvfw "C (gcc) – Try It Online")
*Saved a whopping 24 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire)!!!*
Inputs a pointer to an array of a permutation of the integers from \$1\$ to \$n\$ and \$n\$ (because pointers in C carry no length info).
Returns \$0\$ if it's a tower permutation or \$1\$ otherwise.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 37 bytes
```
a=>!a.some((x,i)=>x<a[i-1]&&x<a[i+1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVS9TsMwEGZgIU9xDNS26kYk8YAaUiYYGAAJthCpVkkgUtpEcStFqngSlg4w8EjwNDhxrebHZPH5u-_On-98-fhc5S_x7nuRr8QaEgi-NutkcvFzxoPZKbdFvowxrmhKgll1ycN04kSjUWONnYgo8u_xkQovIIAteuBCoCmcU0A3PM1q8923FGPBRSwkax46EUxm8FRuYit0KLitrUuh76XgdRFvGKI5NzwTCvK6ibyG5LZJXpPbcBoFNgCZUYVm7jMqlHXlOQrpKVSo-Sa9rApl5isOuUqB003LjDVi_5Wpl9XTCkz1G3LdloIDyowdYIMmMC2ho5bp0rg91NB9ptvo9FDDI2C6kQcJc9-ymrdqiyJL1xg9rxCxl7zAFQQzqDRc8xFpecLbx_s7u-CliHEVnkeEQiXfurQgCAA9oYjYSV5e88UbxiGnUEYUUlKHbq2T_RjJMYQEc4nKmBKuQM0UTPcT5Vsgv5qcZ7Gd5a9YhowByYmTy0B3mEbEt06KsEii8di33kl9u1Y08Tvb5rRpk6uwa7vvr0Vof20TX_0Idju1_gE)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 7 bytes
```
2lvƒ>ÞṠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIybHbGkj7DnuG5oCIsIiIsIls0LDIsMywxXSJd) or [Run all the test cases](https://vyxal.pythonanywhere.com/#WyJQIiwiQGY6MXwiLCIybHbGkj7DnuG5oCIsIjtcbsabQGY7O1rGm2AgPT4gYGo74oGLIiwiW1sxXSxbMSwyXSxbMiwxXSxbMSwyLDNdLFsxLDMsMl0sWzIsMywxXSxbMywyLDFdLFsxLDIsMyw0XSxbMSwyLDQsM10sWzEsMyw0LDJdLFsxLDQsMywyXSxbMiwzLDQsMV0sWzIsNCwzLDFdLFszLDQsMiwxXSxbNCwzLDIsMV0sWzMsMSwyXSxbMSwzLDIsNF0sWzEsNCwyLDNdLFsyLDEsMyw0XSxbMiwxLDQsM10sWzIsMywxLDRdLFsyLDQsMSwzXSxbMywxLDIsNF0sWzMsMSw0LDJdLFszLDIsMSw0XSxbMywyLDQsMV0sWzMsNCwxLDJdLFs0LDEsMiwzXSxbNCwxLDMsMl0sWzQsMiwxLDNdLFs0LDIsMywxXSxbNCwzLDEsMl1dIl0=)
*-2 bytes thanks to Aaroneous Miller*
[Answer]
# Dyalog APL: 10 bytes
Nothing really to say here, regular solution.
```
(⍳∘≢≡⍋)2>/
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
¬№⭆Φθκ›ι§θκ01
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMvv0TDOb8UyAouAQqk@yYWaLhl5pSkFmkU6ihka@oouBelJoK4mToKjiWeeSmpFRAZTaCckoGhEpBh/f9/dLShjoKJjoKpjoKxjoJRbOx/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a tower permutation, nothing if not. Explanation: Port of @xnor's Python 2 answer.
```
θ Input array
Φ Filtered where
κ Current index is not zero
⭆ Map over remaining elements and join
ι Current element
› Is greater than
θ Unfiltered array
§ Indexed by
κ Current index
¬№ Does not contain
01 Literal string `01`
Implicitly print
```
[Answer]
# [Perl 5](https://www.perl.org/), 47 bytes
```
sub{join('',map$_[-2]>pop?I:D,2..@_)=~/^I*D*$/}
```
[Try it online!](https://tio.run/##hVPRasIwFH3vV1zGdW0lKk2zPViqPshABvPFN@fEzbR00zZUCw5xv951zSpuS7JCobknp@fc3BPB881NiVFY7orn42uWpI5tk@1K4HLeoYuByMRw0h8T2u2Olm740XuatMdt7J3KwNq@OzjLC07wbrXZcTd0PFKkax65gRVluWPNAebeAsIB1PsAFkTWCFBFmRLQ7SbgqxFf/6szp3Z3CflqIb8mURXJrz0Y3BFgWpAZ3Z@ZPxUlytTteRLRdChR88loVCXKzEen50rHnlqWGWfC/huLRtVvHJvmpufSS8d/UGZMBNOGgjWWld2yZgRUgxrSy5q4eRrUEGLWBO63ZfdoQfV83eeEYHWRR7gMvksYh9cYOSNMXFkSeZLuo6tW53YHwA@Cv@z5ug8tr1pCnO2bzyQVRbWoiI/pFQEHORyyHDB2YQj2w3QG03sb@mBnbzYB5NUbB9ap/AQ "Perl 5 – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 41 bytes
```
f(a)=#a<3||(a[2]>min(a[1],a[3]))*f(a[^1])
```
[Try it online!](https://tio.run/##DcoxDoMwDIXhq1h0sSszhHQsHIMlCpKFCPIQakUduXvwG359wzNpOp7We0Gh@SXfeN8oacpL1csRMkuKmejth7SFTL38GuocGD4MbjtaRQU2Bmt6/XE9djSCAcbFU9y@/gA "Pari/GP – Try It Online")
A port of [@xnor's Python answer](https://codegolf.stackexchange.com/a/243180/9288).
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 47 bytes
```
a->#a<3||prod(i=2,#a-1,a[i]>min(a[i-1],a[i+1]))
```
[Try it online!](https://tio.run/##FcqxDoMwDATQX7FgcVR7CHQs@YwuVQarJcgDYFkd@ffUveH0TjoTV96sN1i6cBnlMV@X@flBXSYahTPJS2vZ9cAA5/rft1xT6u30eGWCO0HYVt9RgYzAXI8vPtc3WoIBuES1cKT/AA "Pari/GP – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 71, 63 bytes
```
h->{int b=0,s=1;for(int a:h)s=s*b>s*(b=a)?s>0?-1:0:s;return s;}
```
[Try it online!](https://tio.run/##VVDLbtswELznK6YGDFCBTYiJ8qhUOcilQA9FDuktyIF2JEeuLAlcyoAR@NvZ5dpGmgN3NbOzswNt7M7ON29/w6q1RPhtmw4fF8AwLttmBfLWc9v1zRu2PFPP3jXd@uUV1q0pESmwYRM9@qbV9ditfNN3@k//q/M/T@hH0/mX1wVqlOF9vvhgiGWZzqg0Rd07FbHN3xMq6XK5oEu1LG3yQIv0YW7yNKfCVX50Hag4hEIu8hbUzroYA/mXMMCRd3aP8r9oj5EhTd5Vdqt4Q9PQNl5NMEkSvbWDRFb8qnXl8nxn27F6qhPte1lVSXHyf96Tr7a6H70e@G/4Wk2mlGNK024yi1lmqLUdhnb/SNFSsiT4ViI9eRwu4juEYILBVbiCdFxzvT5i/mbMPD9mmD1rkEnPzmrBzLLKxCp89unD89izs6PgqDchuhwvZZ@3eC6q81XBogyyJXwmeQTxvrgwL6zgY3ZxFf5LftzgFne4x3eYFIbrPcwdzC3MDQyb8RbLzT8 "Java (JDK) – Try It Online")
returns 0 if a castle, non zero (1 or -1) if a tower;
## Explanation
Starts with an expected minimum "slope" (s) of 1,
Checks if difference between consecutive values matches the expected "direction" by multiplying them by the slope to normalize direction and ensuring next value is greater. If this check fails while the slope is 1, changes the slope to -1 for the remainder of the comparisons. If this fails while the slope isn't 1, changes to a slope of 0. Otherwise keeps the same slope as last iteration. Slope of 0 means a delta in an unexpected direction and therefore not a tower, also ensures all consecutive direction computations are 0 so computed slope of 0 'sticks'. Returns the slope 's'
[Answer]
# [Desmos](https://www.desmos.com/calculator), ~~41~~ 39 bytes
*-2 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow)*
```
D=sign(l-l[2...])
M(l)=1/max(D-D[2...])
```
The function `M` takes a list and returns `undefined` for tower permutations or `0.5` for non-tower permutations.
[Try it (golfed)](https://www.desmos.com/calculator/fkw3si1wpx)
[Try it (prettified)](https://www.desmos.com/calculator/f2jzik4q0r)
### Explanation
`D` is a helper quantity? macro? that takes the pairwise differences of a list `l` and gets the sign of each. The result will be a list of `1`s and `-1`s. If `l` is a tower permutation, all the `-1`s will come before the `1`s.
`M` then takes the result of `D` and gets *its* pairwise differences. For a tower permutation, this will be a list of `0`s and possibly a `-2`. For a non-tower permutation, there will be a `2` somewhere. Thus, the max of the second-level differences will be `0` for a tower permutation or `2` for a non-tower permutation. But there are also inputs of length 1 or 2 to be considered; they are too short for to have any second-level differences, which means that `max` returns `undefined`. To merge this result with the `0` from longer lists, we invert it, resulting in `undefined` for any tower permutation and `0.5` otherwise.
---
Alternate 39-byte solution that returns `1` instead of `0.5`:
```
D(l)=sign(l-l[2...])
M(l)=1/D(D(l)).max
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ü›D{Q
```
[Try it online](https://tio.run/##yy9OTMpM/f//8J5HDbtcqgP//4821DHRMdUx1jGKBQA) or [verify all test cases](https://tio.run/##RY4hDsMwDEWvUhWbODEv6QWGo4JNKigaqFQpKhnaAXacaWw36UWy@O8rJbHz/P@37@v1tsxly0PfHc9X1w@5fD/H4z3ulyIlJZ0kqYT6BmEvETWSRvD6O@di7KxpDWp10nwGB1TMMKZARaZ0OjFm/G@oCu7yzsjcYcxVMGSAYYY85JMFXoKLMEWFFxlkgXnY3@50x/QD).
**Explanation:**
```
ü # For each overlapping pair of the (implicit) input-list:
› # Check if the first is larger than the second
D # Duplicate this list of checks
{ # Sort the copy
Q # Check if the lists are still the same (thus it was sorted)
# (after which the result is output implicitly)
```
]
|
[Question]
[
You should have heard about the **[Fibonacci Numbers](https://en.wikipedia.org/wiki/Fibonacci_number)**, often called the Fibonacci Sequence. In this sequence the first two terms are 0 and 1, and every number after the first two is the sum of the two preceding ones. In other words, `F(n) = F(n-1) + F(n-2)`.
Here are the first 20 Fibonacci numbers:
```
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
```
---
## Task:
Given an integer `x`, compute the arithmetic mean (the average) of the prime Fibonacci Numbers up to the `x` number of the Fibonacci Sequence.
## Rules:
* the Fibonacci sequence starts with 0 and 1 for this challenge
* `3 < x < 40`, because higher values of `x` might cause some huge execution time or overflows and smaller values have no output
* 1 is ***NOT*** prime, since it only has 1 divisor
* the arithmetic mean should include decimals, if it's the case, or should be displayed as an exact fraction
* you are only allowed to take `x` as input and the code needed to take the input does not count (e.g: if you need something like `x = input()`, you should not take it into consideration when counting the bytes)
---
## Examples:
**Ex. 1:** For `x=10`, the output is `5.75`, because the 10th Fibonacci number is `55` and the prime Fibonacci numbers up to `55` are `2, 3, 5, 13`, their average being `5.75`
Following the explanation from example 1, other examples are:
**Ex. 2:** For `x=15`, the output is `57.5`
**Ex. 3:** For `x=20`, the output is `277.428571428571`, or any other close approximation. In this case `277.4286`, for instance, is an accepted value
**Ex. 4:** For `x=11`, the output is `22.4`
**Ex. 5:** For `x=30`, the output is `60536.4444444444`, or any other close approximation, such as `60536.444`
---
## Leaderboard:
```
var QUESTION_ID=112025,OVERRIDE_USER=59487;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
---
To change the leader, submit a shorter valid solution. Your code should be as short as possible, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Good luck!
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
s=2.;a=b=c=1
exec"p=2**a%a==2;c+=p;s+=a*p;a,b=b,a+b;"*input()
print s/c
```
[Try it online!](https://tio.run/nexus/python2#BcFBCoAgEAXQvacIIahRiqTd8A8zDi7cyJAG3d7emx3pYEGG4nLlK@oNiUhWARJrgHEPEDKWmJGjhMyearN3bLuzp7ax9FPnvH8 "Python 2 – TIO Nexus")
Python doesn't have useful arithmetic built-ins for this, so we do things by hand. The code iterates through Fibonacci numbers via `a,b=b,a+b` starting from `a=b=1`.
The [Fermat primality test](https://en.wikipedia.org/wiki/Fermat_primality_test) with base 2 is used to identify primes as `a` where `2^a == 2 (mod a)`. Though this only checks for probable primes, none of the [false positives](https://oeis.org/A001567) are within the first 40 Fibonacci numbers.
The current sum `s` and count `c` of primes are updated each time a prime is encountered, and their ratio (the mean) is printed at the end. Because the prime check misses `a=2` and it's guaranteed to be in the input range, the sum starts at 2 and the count starts at 1 to compensate.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ÆḞ€ÆPÐfµS÷L
```
[Try it online!](https://tio.run/nexus/jelly#@3@47eGOeY@a1hxuCzg8Ie3Q1uDD233@H24HikT@/29ooKNgaKqjYASiDXUUjA0A "Jelly – TIO Nexus")
### How it works
```
ÆḞ€ÆPÐfµS÷L Main link. Argument: n (integer)
ÆḞ€ Map the Fibonacci atom over [1, ..., n].
ÆPÐf Filter by primality.
µ Begin a new chain. Argument: A (array of Fibonacci primes)
S Yield the sum of A.
L Yield the length of A.
÷ Compute the quotient.
```
[Answer]
# Mathematica, 38 bytes
```
Mean@Select[Fibonacci@Range@#,PrimeQ]&
(* or *)
Mean@Select[Fibonacci~Array~#,PrimeQ]&
```
**Explanation**
```
Mean@Select[Fibonacci@Range@#,PrimeQ]&
& (* For input # *)
Range@# (* List {1, 2, 3, ... #} *)
Fibonacci@ (* Find the corresponding fibonacci numbers *)
Select[ ,PrimeQ] (* Select the prime terms *)
Mean@ (* Take the Mean *)
```
[Answer]
# [Perl 6](https://perl6.org), 51 bytes
```
{sum($/=[grep *.is-prime,(0,1,*+*...*)[0..$_]])/$/}
```
[Try it](https://tio.run/nexus/perl6#NY7LboMwEEX3/opRhBoDZniERyUKn9BVdyGqKuJWliBYNm5TIb6su/4YdR1ld2buGc01msNniX1NjKUXrueajN/w0E9nDs22aDNSL26OH4pLCFDoSCoxckYTlrIgDBAx8I8Jovd6OvmxF6/b@6QIwCAuXFO/s/j7g1oOYqYxPOGXbmEftfsbxnfh2YxciZ5ELVDoxEWamUHHr5L3Mz@DD4v1bLFOcW2GGRr4b0hDZ/q1DW21NynVdIXw5jAI7/cMdoszV2haWG75uiPrliZgXxZYFSQtHFZYkMxts6rCPHssSZq6McOcHFxSJsWhxDzP/wA "Perl 6 – TIO Nexus")
## Expanded:
```
{
sum(
$/ = [ # store as an Array in $/
grep
*.is-prime, # find the primes
(
0, 1, *+* ... * # Fibonacci sequence
)[ 0 .. $_ ] # grab the indicated values in the sequence
]
)
/
$/ # use the Array as a number (elems)
}
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 10 bytes
Code:
```
R♂F;Mr♂P∩æ
```
Explanation:
```
R # On the input, create the range [1 .. input].
♂F # Map the nth Fibonacci command over it.
;M # Duplicate and get the maximum of the list.
r # Create the range [0 .. maximum - 1].
♂P # Map the nth prime operator over each element (zero-indexed).
∩ # Intersection of both.
æ # Get the mean and implicitly display.
```
Uses the **CP-437** encoding. [Try it online!](https://tio.run/nexus/actually#@x/0aGaTm7VvEZAKeNSx8vCy//8NTQE "Actually – TIO Nexus")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
lOi:"yy+]vtZp)Ym
```
[Try it online!](https://tio.run/nexus/matl#@5/jn2mlVFmpHVtWElWgGZn7/7@hAQA "MATL – TIO Nexus")
### Explanation
```
lO % Push 1, then 0. This way the generated numbers with indices 1, 2, 3, ...
% will be 1, 1, 2, ... as required
i % Input n
:" % Do the following n times
yy % Duplicate top two numbers
+ % Add
] % End
v % Concatenate all numbers into a column vector
t % Duplicate
Zp % Vector of logical values: true for prime numbers, false otherwise
) % Apply that vector as an index. This keeps only prime numbers
Ym % Mean. Implicitly display
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~75~~ 71 bytes
```
@(n)mean((t=fix(((1+(s=5^.5)).^(x=1:n)-(1-s).^x)/s./2.^x))(isprime(t)))
```
Anonymous function that uses [Binet's formula](https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression). Input and output are in the form of function arguments.
[Try it online!](https://tio.run/nexus/octave#dY3BDoIwEETvfMVeTHajAsVw0ZD4JSYb2EKTthi2Kn49gvHqXN7MYWaWK0YKwhExNdbNiGj2qE19y2ui/IZzY86RjmiOusaZCs2LajOETu@TC4KJiBYLDXDUC/zXDnr3FEiDgH3ENrkxAkPkIJkdp8AJ/Bj7/@1uPfT8hif7hyi8XBqAvYdOWhfYa2bRlHSAFfUX1S@ZL04lbStJNEHLKrp8AA)
[Answer]
# Maxima, 49 bytes
```
f(n):=mean(sublist(makelist(fib(x),x,n),primep));
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~269~~ ~~264~~ ~~254~~ 218 bytes
* Thanks to *Fatalize* for saving 37 bytes!
* Thanks to *Emigna* for saving 9 bytes!
I'm fairly certain that I could golf some more bytes down.
```
X/X:-X<3.
N/R:-A is N-1,B is N-2,A/C,B/D,R is C+D.
2^0^0.
C^S^E:-G is C-1,G/M,G^Q^R,(p(M)->S=M+Q,E is R+1;S=Q,E is R).
a(X,S):-X^R^Q,S is R/Q.
p(N):-N*(N-1).
p(2).
p(3).
N*2:-N mod 2=\=0.
N*C:-N mod C=\=0,D is C-1,N*D.
```
Run it as **`a(15, R).`** for **x = 15**, **R** is the output variable.
[Try it online!](https://tio.run/nexus/prolog-swi#NY4xC8MgFIR3f4WjJk9NDF3SWkg0ZIqgLg5FCHTpUBro/yfVlCzHu@943O1RxJ7FW8eRFb5nA359sWUtjP9DwiA0jMKAL0DXhiOZmtRwpFNIU8/mg@ePWSwwJ5c8kI0slN2DWmoHU8l93V6DOg3laCURAs3NyScH4cDCcbQRm6mtSN5Ai5WHdlltJXOC358nluqhmkL0SXQhYM4ttjJ831fSXqDU/QA "Prolog (SWI) – TIO Nexus")
---
A more readable version:
```
fibonacci(1, 1) :- !.
fibonacci(2, 2) :- !.
fibonacci(N, R) :-
N0 is N - 1,
N1 is N - 2,
fibonacci(N0, R1),
fibonacci(N1, R2),
R is R1 + R2.
listed(2, 0, 0) :- !.
listed(C, S, Successes) :-
C0 is C - 1,
fibonacci(C0, Result),
listed(C0, S0, S1),
(
is_prime(Result)
->
S = Result + S0, Successes is S1 + 1
; S = S0, Successes is S1
).
f(X, S) :-
listed(X, R, Q),
S is R / Q.
is_prime(Num) :- is_prime(Num, Num - 1).
is_prime(2).
is_prime(3).
is_prime(Num, 2) :- Num mod 2 =\= 0, !.
is_prime(Num, C) :-
Num mod C =\= 0,
C0 is C - 1,
is_prime(Num, C0).
```
[Answer]
# [Röda](http://github.com/fergusq/roda), ~~98~~ ~~94~~ 93 bytes
```
f n{z=0;i=1;j=1;s=0;seq 2,n-1|{|_|c=i+j;i=j;j=c;seq 2,c-1|{z+=1;s+=c}if[c%p>0]()for p}_[s/z]}
```
It's a function that returns the result as a floating point number.
Ungolfed version:
```
function f(n) {
i = 1
j = 1
sum = 0
num = 0
seq(2, n-1) | for _ do
/* calculate next fibonacci number: */
c = i+j
i = j
j = c
/* if it's prime: */
{
num += 1
sum += c
/* primality test: */
} if [c%p > 0]() for p in [seq(2, c-1)]
done
return sum/num
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
!ÅF¹£DpÏDOsg/
```
[Try it online!](https://tio.run/nexus/05ab1e#@694uNXt0M5Di10KDve7@Ben6///b2QAAA)
or as a [Test suite](https://tio.run/nexus/05ab1e#MzRQMDRVMAKShgrGBppllf8VD7e6VR5a7FJwuN/Fvzhd/3@l0uH9VgqH9yvp/AcA)
**Explanation**
```
!ÅF # get a list of fibonacci numbers up to fac(input)
¹£ # take the first input elements of that list
D # duplicate
p # isprime on the copy
Ï # keep the fibonacci numbers which are true in the isprime list
D # duplicate the list of fibonacci primes
O # sum the list
s # swap the other copy to the top of the stack
g # get its length
/ # divide sum by length
```
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 11 bytes
```
S.b#_P)'sl/
```
[Try it online!](https://tio.run/nexus/pyke#@x@sl6QcH6CpXpyj//@/oQEA "Pyke – TIO Nexus")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 129 bytes
```
?sa0sb1sd0ss0sz[[lF1+sF]sqlelG!=q]si[ls+sslz1+sz]sw[lddlb+dsdrsbdsG2se0sF[lGdle%0=ile1+dse<p]dspxlF0=wla1-dsa1<c]dscxEkls1-lz1-/p
```
A Fibonacci number generator and primality checker all in one. Nice.
[Try it online!](https://tio.run/nexus/dc#DcyxDoIwFIXhZ3FwIo33OkOcLA/RdCi9TSSeKHgGSN@bGbv@X/KfDybhpDQhhTUEeO3oI1cUjJdhjZwD2JGoDWrkFmCGqTPaj5NxvLMIfcBoKFcZZhRtWPolGpcdXoYNSZ0xaZ9by/vzDaprQ3dbzlPl@HxdTvlV/g "dc – TIO Nexus")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
Afṗ↑İf
```
[Try it online!](https://tio.run/##yygtzv6fm18enPqoqfG/Y9rDndMftU08siHt////0YYGOoamOkZA0lDH2CAWAA "Husk – Try It Online") Outputs the mean as an exact rational number.
### Explanation
```
Afṗ↑İf (Let X denote the argument.)
A Take the arithmetic mean of
↑ the first X values of
İf the infinite list of Fibonacci numbers,
fṗ filtered for primality.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~14~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ò!gM fj Ë/Fl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=8iFnTSBmaiDLL0Zs&input=MzA)
[Answer]
# perl, 91 bytes
```
$b=1;map{($a,$b)=($b,$a+$b),$p=("x"x$b)!~/^(.|(..+)\2+)$/,$s+=$b*$p,$c+=$p}2..$x;print$s/$c
```
Cuold have been 8 bytes shorter if the modulo pseudoprime test worked as well in perl as in the python answer:
```
$b=1;$s=2;map{($a,$b)=($b,$a+$b),$p=2**$b%$b==2,$s+=$b*$p,$c+=$p}2..$x;print$s/++$c
```
...but this gives wrong answer for input > 16 in perl.
[Answer]
# Axiom, 104 bytes
```
g(n)==(y:=x:=r:=0;repeat(x>n=>break;j:=fibonacci(x);x:=x+1;if prime?(j)then(r:=r+j;y:=y+1));y=0=>-1;r/y)
```
ungolfed, test code and results
```
f(n)==
y:=x:=r:=0
repeat
x>n=>break
j:=fibonacci(x)
x:=x+1
if prime?(j) then(r:=r+j;y:=y+1)
y=0=>-1
r/y
(3) -> [[i,g(i)::Float] for i in [1,2,3,10,15,20,11,30,50]]
Compiling function g with type PositiveInteger -> Fraction Integer
(3)
[[1.0,- 1.0], [2.0,- 1.0], [3.0,2.0], [10.0,5.75], [15.0,57.5],
[20.0,277.4285714285 7142857], [11.0,22.4], [30.0,60536.4444444444 44444],
[50.0,309568576.1818181818 2]]
```
i try to duplicate the matematica, octave etc languages entry, if one not count the mean() function, to implement it would be here **62 bytes** so good too
```
mean(a:List Float):Any==
i:=1; s:=0.0
repeat
if~index?(i,a)then break
s:=s+a.i
i:=i+1
i=1=>[]
s/(i-1)
--62 bytes
f(x:NNI):Any==mean(select(prime?,[fibonacci(i)for i in 1..x]))
```
[Answer]
# JavaScript ES6, ~~137~~ ~~136~~ ~~118~~ 113 bytes
```
m=
n=>(a=[],(f=x=>a[x]=x<2?x:f(--x)+f(--x))(n),eval((a=a.filter(x=>eval("for(y=x;x%--y;);y==1"))).join`+`)/a.length)
console.log(m(10))
console.log(m(15))
console.log(m(20))
console.log(m(11))
console.log(m(30))
```
---
## History
### 118 bytes
```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>eval("for(y=x;x%--y;);y==1"))).join`+`)/a.length)
```
### 136 bytes
```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>x>1&&!Array(x).fill().some((i,j)=>j>1&&!(x%j)))).join`+`)/a.length)
```
### 137 bytes
```
n=>(a=[0,1,1],(f=x=>a[--x]=a[x]||f(x)+f(--x))(n),eval((a=a.filter(x=>{d=x;while(--d>1)if(!(x%d))return 0;return x>1})).join`+`)/a.length)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ÆḞ€ẒƇÆm
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//w4bhuJ7igqzhupLGh8OGbf///zEw "Jelly – Try It Online")
The newest version of Jelly really helps with this. This is essentially identical to [Dennis' answer](https://codegolf.stackexchange.com/a/112026/66833) but uses the newer features, so go upvote his answer.
## How it works
```
ÆḞ€ẒƇÆm - Main link. Takes n on the left
ÆḞ€ - i'th Fibonacci number for each i in [1, 2, .., n]
Ƈ - Comb; Keep those for which the following is true:
Ẓ - Is prime?
Æm - Take the arithmetic mean
```
[Answer]
# [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 71 bytes
```
> Input
> fₙ
>> 2ᶠ1
>> L’
>> Select∧ 4 3
>> mean(5)
>> Output 6
```
Unfortunately, no TIO as this relies on v3 features, and v3 isn't on TIO. However, you can tell it by downloading and running the interpreter in the linked GitHub repo
## How it works
```
> Input
Here, we "define" line 1 to hold our input integer, n
> fₙ
On line 2, we store an infinite list of Fibonacci numbers
>> 2ᶠ1
We then use the ᶠ dyad to take the ᶠirst n elements from the infinite list
>> L’
This line is a "functional operator line". It is passed a value on the Left and returns the ’ (prime) operator result on that value
>> Select∧ 4 3
We now take the list of Fibonacci numbers and Select those which return true when run through line 4
>> mean(5)
>> Output 6
Finally, we take the mean of the resulting list, before outputting it
```
]
|
[Question]
[
# Historic Tetris Achievement
[Blue Scuti](https://en.wikipedia.org/wiki/Willis_Gibson) became the first ever human to beat the classic game of Tetris on NES.
Here's the Tetris [Kill Screen](https://www.youtube.com/watch?v=GuJ5UuknsHU)
[](https://i.stack.imgur.com/vVwak.jpg)
# Challenge
Output the following Tetris `Kill Screen` board (10x20 blocks)
```
EEEEEEEEEE
EEEEEEEEEE
EEEEEEEEEE
EEEEEEEEEE
EEEEEEEEEE
EEEEEEEEEE
EEEEEEEEEE
EEEEEEEEEE
EEEEEEEEEE
EEEEGGEEEE
EEEEBGGEEE
EBEEBBGGEE
EBEGBBBGBE
EEEEEEEEEE
BBGEBBGGBB
BBBEBBEGBB
BBBBBBBGBE
GGEBBBBBBB
GGEGBGGBBB
BBEBBGGGBB
```
| Code | Color |
| --- | --- |
| B | Blue |
| G | Green |
| E | Black |
# Rules
There is no strict requirement to use the characters B, G, and E, or a specific board orientation, as long as the concept of the `Kill Screen` is preserved.
# Examples
```
Original Rotate 180°
██████████ ░░▓▓▓░░█░░
██████████ ░░░▓▓░▓█▓▓
██████████ ░░░░░░░█▓▓
██████████ █░▓░░░░░░░
██████████ ░░▓█░░█░░░
██████████ ░░▓▓░░█▓░░
██████████ ██████████
██████████ █░▓░░░▓█░█
██████████ ██▓▓░░██░█
████▓▓████ ███▓▓░████ Rotate left 90° Rotate right 90°
████░▓▓███ ████▓▓████ ██████████████░░█░░░ ░▓▓░░░██████████████
█░██░░▓▓██ ██████████ ████████████░█░░░░░░ ░▓▓░░░█░░███████████
█░█▓░░░▓░█ ██████████ ███████████▓▓█▓▓▓░░▓ ███░░▓██████████████
██████████ ██████████ ██████████▓▓░█▓█░░▓▓ ░▓░░███▓████████████
░░▓█░░▓▓░░ ██████████ █████████▓▓░░█░░░░▓▓ ░░░░░░█░░░▓█████████
░░░█░░█▓░░ ██████████ █████████▓░░░█░░░░░░ ▓▓░░░░█░░▓▓█████████
░░░░░░░▓░█ ██████████ ████████████▓███░░▓░ ▓▓░░█▓█░▓▓██████████
▓▓█░░░░░░░ ██████████ ██████████████▓░░███ ▓░░▓▓▓█▓▓███████████
▓▓█▓░▓▓░░░ ██████████ ███████████░░█░░░▓▓░ ░░░░░░█░████████████
░░█░░▓▓▓░░ ██████████ ██████████████░░░▓▓░ ░░░█░░██████████████
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 0 0 0 0 0 0 1111111111 ..........
0 0 0 0 1 1 0 0 0 0 1111221111 ....##.... ""
0 0 0 0 2 1 1 0 0 0 1111022111 ....O##... 00000000000000220222 !""
0 2 0 0 2 2 1 1 0 0 1011002211 .O..OO##.. 00000000000020222222 ! !!""
0 2 0 1 2 2 2 1 2 0 1012000201 .O.#OOO#O. 00000000000110111221 ! "!!!"!
0 0 0 0 0 0 0 0 0 0 1111111111 .......... 00000000001120102211
2 2 1 0 2 2 1 1 2 2 0021002200 OO#.OO##OO 00000000011220222211 !!" !!""!!
2 2 2 0 2 2 0 1 2 2 0001001200 OOO.OO.#OO 00000000012220222222 !!! !! "!!
2 2 2 2 2 2 2 1 2 0 0000000201 OOOOOOO#O. 00000000000010002212 !!!!!!!"!
1 1 0 2 2 2 2 2 2 2 2210000000 ##.OOOOOOO 00000000000000122000 "" !!!!!!!
1 1 0 1 2 1 1 2 2 2 2212022000 ##.#O##OOO 00000000000220222112 "" "!""!!!
2 2 0 2 2 1 1 1 2 2 0010022200 OO.OO###OO 00000000000000222112 !! !!"""!!
```
[Answer]
# C (gcc), ~~476~~ ~~395~~ ~~308~~ ~~283~~ ~~153~~ 151 bytes
*-130 bytes thanks to @Command Master
-2 bytes thanks to @ceilingcat*
Applying [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) to the ascii-art.
```
*a=L"sssssssss7%77%-#'%#1s''%'1''Y%Y%%1''/'";b;main(c){for(;c=*a++;(b+=c/5-3)%20||puts(""))printf("[4%dm %*s",c%5,c/5,"[0m");}
```
[Try it online](https://godbolt.org/z/o8dr1YKbh)
**Output**
[](https://i.stack.imgur.com/ALSgm.png)
[Linux Terminal](https://godbolt.org/z/sz3E1xn87)
[](https://i.stack.imgur.com/EBcYT.png)
[Answer]
# [Zsh](https://www.zsh.org/), 98 bytes
```
repeat 9 <<<1111111111
for w (MJ4 M3D KS7 QY7 MS4 150Z 15LQ QZZ 19JR 1809 14OH)rev<<<$[[##3]36#$w]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3k4pSC1ITSxQsFWxsbAzhgCstv0ihXEHD18tEwdfYRcE72FwhMNJcwTfYRMHQ1CAKSPgEKgRGARmWXkEKhhYGlgqGJv4emkWpZUCDVKKjlZWNY43NlFXKYyE2QS2EWQwA)
Converts each line from base 36 to base 3. Each line is reversed, because no line ends with a `G` (`0`), so we can avoid needing to pad with zeroes.
[Generator](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3DdLyixSKFTQSilLLakqKFNxdnRQMDI0SNLlSkzPyFXTzFFSio5WVjc1ijZVVimNjFCD6oNoX3KxwBQJ3dxDJBSKcwGwuVycgE8wGMd2dgGwniAII4AIKgBU4OQGZTkCmK5TpBFXrDpIHAxDTHawUpACsC8iGOAAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes
```
“ṚƝ*ẊḢ-PṇḃeḶ:@İñṇY¤kṂė’b3Ż94¡s⁵Y
```
[Try it online!](https://tio.run/##AUYAuf9qZWxsef//4oCc4bmaxp0q4bqK4biiLVDhuYfhuINl4bi2OkDEsMOx4bmHWcKka@G5gsSX4oCZYjPFuzk0wqFz4oG1Wf// "Jelly – Try It Online")
A niladic link that outputs the kill screen with 0 for E, 1 for G and 2 for B. A base-250 encoded integer that is converted to base 3, prepended with 94 zeros, split into pieces length 10 and then joined with new lines.
[Answer]
# [Python](https://www.python.org), ~~114~~ 112 bytes
```
x=int("cmlzatvntfmkheiwxpk0p5iob21d1xxc29",36)
c='0'*90
while x:c+=str(x%3);x//=3
while c:print(c[:10]);c=c[10:]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3CypsM_NKNJSSc3OqEkvK8krScrMzUjPLKwqyDQpMM_OTjAxTDCsqko0slXSMzTS5km3VDdS1LA24yjMyc1IVKqyStW2LS4o0KlSNNa0r9PVtjaEyyVYFRSCTk6OtDA1iNa2TbZOjDQ2sYiH2Qq2HOQMA)
This isn't winning any code golf, but it's an interesting concept I wanted to try out before. Basically it is the last 11 rows concatenated, interpreted as a base-3 number, then reversed. Of course, storing the data in the source code as a ~~hex~~ base-36 number wastes a lot of bits, and the printing and decoding can be optimized much further.
# [Python](https://www.python.org), 106 bytes
```
lambda i=200,x=int("2mwpsm5yo9be8gwx4tjcljqj9lx0jxigz",36):f(i-1,x//3)+str(x%3)+'\n'[i%10<1]if i else''
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3s3ISc5NSEhUybY0MDHQqbDPzSjSUjHLLC4pzTSvzLZNSLdLLK0xKspJzsgqzLHMqDLIqMtOrlHSMzTSt0jQydQ11KvT1jTW1i0uKNCpUgQz1Rw3dMXnq0ZmqhgY2hrGZaQqZCqk5xanq6hAbVxUUgexI09DUhAgsWAChAQ)
This is the program rewritten as a function returning the result, based on l4m2's answer. Before the `\n` there's a ZWSP that is counted in the byte-count but technically means the string has a bunch of extra non-printing spaces.
Very rough constant generation code:
```
b="""EEEEGGEEEE
EEEEBGGEEE
EBEEBBGGEE
EBEGBBBGBE
EEEEEEEEEE
BBGEBBGGBB
BBBEBBEGBB
BBBBBBBGBE
GGEBBBBBBB
GGEGBGGBBB
BBEBBGGGBB"""
b = b.replace('E','0').replace('G','1').replace('B','2')
b = b.replace('\n','')[::-1]
x = int(b,3)
print(hex(x))
```
[Answer]
# [Funge-98](https://esolangs.org/wiki/Funge-98), 165 bytes
```
9\wv>58k:9k.a,1+:
v3> ^j3:k35,a<
2p>53k:3k.7:..'^e
v>k.2277722523k:772757725k:57752725k:227522523k:7722572258k:527222752555772255255557725k.a,
<,a.k9p10-1_@#:g10
```
[Try it online!](https://tio.run/##RY7BCsIwDEDP9isKHjy4lTUldA2j@CEyqVAHBkYvTvz6mtWDhySPvITknh@vdcl9GPvyaVirDtf3FnFkCmxSZ8@kDpuLen46YoddmpTWUCI6JsfGkzGnOastsgHw3gMgiBLwKAmZpCA0kgH8e8A95NBum0LE1m/025YX1NQlw6HYobe3y5EWO9T6BQ)
Instead of `B`, `G`, and `E`, this program outputs `2`, `7`, and `5`.
Contains a tab, which does not seem to work in code blocks, so here is a hex dump:
```
00000000: 2039 5c77 763e 3538 6b3a 396b 2e61 2c31 9\wv>58k:9k.a,1
00000010: 2b3a 0a09 7633 3e20 5e6a 333a 6b33 352c +:..v3> ^j3:k35,
00000020: 613c 0a20 2032 703e 3533 6b3a 336b 2e37 a<. 2p>53k:3k.7
00000030: 3a2e 2e27 5e65 0a76 3e6b 2e32 3237 3737 :..'^e.v>k.22777
00000040: 3232 3532 336b 3a37 3732 3735 3737 3235 22523k:772757725
00000050: 6b3a 3537 3735 3237 3235 6b3a 3232 3735 k:57752725k:2275
00000060: 3232 3532 336b 3a37 3732 3235 3732 3235 22523k:772257225
00000070: 386b 3a35 3237 3232 3237 3532 3535 3537 8k:5272227525557
00000080: 3732 3235 3532 3535 3535 3737 3235 6b2e 72255255557725k.
00000090: 612c 0a3c 2c61 2e6b 3970 3130 2d31 5f40 a,.<,a.k9p10-1_@
000000a0: 233a 6731 30 #:g10
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~37~~ 35 bytes
```
GTχE⪪”{“⌈K→◧ψM^≡Nq§d5G↑℅a⁰≔)⦃L+y≡”χ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9PwypER8HQQEdB3VVd05oroCgzr0QjuCAns0RDyRUI3N1docAJwnQCIgjTydXdCch0ckUAIBcs6wQCQJYrhOUEUecOkoRw3IEyCGXuIKYSyB2amtb////XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The `GTχE` draws a `10×10` square of `E`s, leaving the cursor at the bottom left, so that the `10`th line will be overwritten as the bottom `11` lines are then drawn by splitting a compressed string into rows of `10` characters.
[Answer]
# [Perl 5](https://www.perl.org/), 108 bytes
```
say for('}'x13 .']W}MJWeJURW]JMOZOJ}eROMRWjMRMOzROJMWMzWMOJWjMR_R')=~s,.,($&&G)x((63&ord$&)/8),gre=~/.{10}/g
```
[Try it online!](https://tio.run/##FcjdCoIwGADQV/FC9gO2OcToxuvgg4/BIAaBRNASI5psEWbMR2/RuTyTC/c253h@F1cfGE10Vk0haG8TgnVwMLYH1EcNyRmNxt7QoF6MBrS4WNTwn5OhvFtjJSpWErLnM2PbhvhwKQmXO14NwXWrFB9VJznk/PXTc/SPmDf4aoWqfw "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~84~~ ~~83~~ 78 bytes
```
puts (?0*94+0x7241ea9db46487237308d479dcb396cc036e301ec3.to_s(3)).scan /.{10}/
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN_0KSkuKFTTsDbQsTbQNKsyNTAxTEy1TkkzMTCzMjYzNjQ0sUkzMLVOSk4wtzZKTDYzNUo0NDFOTjfVK8uOLNYw1NfWKkxPzFPT1qg0NavUhpkINh1kCAA)
Ports Jelly, which to my surprise is extremely short in Ruby.
Previous solutions:
# [Ruby](https://www.ruby-lang.org/), 86 bytes
```
puts [674,5102,9124,30937,96952,116639,2264,459,18212,716].map{_1.to_s(3).rjust 20,?0}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN8MKSkuKFaLNzE10TA0NjHQsDY1MdIwNLI3NdSzNLE2NdAwNzcyMLXWMjMxMdExMLXUMLYwMjXTMDc1i9XITC6rjDfVK8uOLNYw19YqySotLFIwMdOwNaiGmQy2BWQYA)
Outputs the board rotated 90 degrees, rough port of my Japt solution.
## [Ruby](https://www.ruby-lang.org/), ~~119~~ 114 bytes
```
puts [716,18212,459,2264,116639,96952,30937,9124,5102,674].map{_1.to_s(3).rjust(20,?0).chars}.transpose.map{_1*''}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc5BCsIwEEDRq7hrK2PITJJJs_IgIqWKIoI2ZJJFkZ7ETRd6KG_jwrr_8N_zlcphnOd3yedN-0mxZFntPDJgS0hgXQAitoDIbAIEDo7A6GA8BCQLDjUBe7tXtz4-OlR56KQ2jUrXIrkmDVvdqOOlTzKpnPq7xEFOS7yuqul3XgB_yBc)
Un-rotated version of above solution.
[Answer]
# Python 3.10.10, 164 bytes(UTF-8)
---
###### Definitely not the shortest, but oh well.
```
a="\n#.~"
for i in"ªªªZV¨ªªfU¡ªª¾ªª~n=ªª~Yõ¨ªzeU¡ªªºZªªª^*ªªjY}¨ªªjõ":w=ord(i)*4;print("".join(a[(w:=w//4)&3]for i in a),end="")
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9FWKSZPWa9OiSstv0ghUyEzT@nQKhCMCju0AkSnhR5aCBbZV3@oF8Soy7MFU5GHt4JUVKXCFOyKOtQO0RunBSKzImshRmQd3sqoZFVum1@UopGpqWViXVCUmVeioaSkl5WfmaeRGK1RbmVbrq9voqlmHAtzhkKipk5qXoqtkpLm//8A "Python 3.8 (pre-release) – Try It Online")
Outputs a 90deg rotated board, with some extra newlines.
## How
I packed 4 characters into a byte, using 2 bits for each character(`#`,`.`,`~`, or `\n`).
Then, I just use `ord` to convert the ASCII junk back into integers, then unpack it.
#### Clever things:
* Since `for i in range(4)` is obviously way too long, I used `for i in a`, as `a` (coincidentally) has a `len` of 4, and I don't need the value of `i`(the second i) anyway.
* `*4` when assigning `w`, then `(w:=w//4)` in the loop, making use of the [walrus operator](https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions). I originally had `a[w&3+0*(w:=w//4)]`, but then I realized I can just multiply the initial value of `w` by 4.
###### Misc note: I checked, `print(*(genexpr),sep="",end="")` is longer than `print("".join(genexpr),end="")`(by exactly 1 character)
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~695~~ 682 bytes
```
[S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S S T T N
_Push_3_"][S N
S _Duplicate_3_"][S N
S _Duplicate_3_"][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S S T N
_Push_1_<space>][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S T T S T S T N
_Push_-21_\n][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S S S T T N
_Push_3_"][S N
S _Duplicate_3_"][S S S T S N
_Push_2_!][S S S T T N
_Push_3_"][S S S T N
_Push_1_<space>][S S S T T N
_Push_3_"][S N
S _Duplicate_3_"][S S T T S T S T N
_Push_-21_\n][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S S S T N
_Push_1_<space>][S S S T T N
_Push_3_"][S N
S _Duplicate_3_"][S S T T S T S T N
_Push_-21_\n][S S S T N
_Push_1_<space>][S S S T S N
_Push_2_!][S S S T T N
_Push_3_"][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S S T T S T S T N
_Push_-21_\n][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S S T T N
_Push_3_"][S S S T N
_Push_1_<space>][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S S T N
_Push_1_<space>][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S S T T S T S T N
_Push_-21_\n][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S S T T N
_Push_3_"][S N
S _Duplicate_3_"][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S S T N
_Push_1_<space>][S S S T T N
_Push_3_"][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S T T S T S T N
_Push_-21_\n][S S S T N
_Push_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S S T T S T S T N
_Push_-21_\n][S S S T N
_Push_1_<space>][S S S T S N
_Push_2_!][S S S T T N
_Push_3_"][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S N
S _Duplicate_2_!][S S S T T N
_Push_3_"][S S S T N
_Push_1_<space>][S S S T S N
_Push_2_!][S S S T N
_Push_1_<space>][S S T T S T S T N
_Push_-21_\n][S S S T N
_Push_1_<space>][S N
S _Duplicate_1_<space>][S S S T T N
_Push_3_"][S N
S _Duplicate_3_"][S S S T S N
_Push_2_!][S N
S _Duplicate_2_!][S S S T N
_Push_1_<space>][S N
S _Duplicate_1_<space>][S S S T S N
_Push_2_!][S S S T N
_Push_1_<space>][S S T T S T S T N
_Push_-21_\n][S S S T N
_Push_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S S S T T N
_Push_3_"][S N
S _Duplicate_3_"][S S S T S N
_Push_2_!][S S S T N
_Push_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S S T T S T S T N
_Push_-21_\n][S S S T N
_Push_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S S S T T N
_Push_3_"][S N
S _Duplicate_3_"][S S S T N
_Push_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S S S N
_Push_0][S S S T S S T N
_Push_9][T T S _Store][N
S S S N
_Create_Label_LOOP1][S S T T S T S T N
_Push_-21_\n][S S S T N
_Push_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S N
S _Duplicate_1_<space>][S S S N
_Push_0][T T T _Retrieve][S S S T N
_Push_1][T S S T _Subtract][S N
S _Duplicate][S S S N
_Push_0][S N
T _Swap_top_two][T T S _Store][N
T S N
_If_0_Jump_to_Label_LOOP2][N
S N
S N
_Jump_to_Label_LOOP1][N
S S N
_Create_Label_LOOP2][S S S T T T T T N
_Push_31][T S S S _Add_top_two][T N
S S _Output_as_character][N
S N
N
_Jump_to_Label_LOOP2]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[**Try it online**](https://tio.run/##lZHBCoQwDETPM1@RX5NFWG/CLuzndxNjJdpE0HqYDp3mJf29l@/8WafX3JqIQKjLBDbh@jAZdoDK6MScm77tOdS5@NfHeb02zw8FzhhZMzexbALVHDKclKvuZGB1eS1SsMXJM0UbX4gVYnwRnGp02xnVhN/FB9MQDWE7ho5ijZipDi3Mg0o/Ym/K/Nb@) (with raw spaces, tabs and new-lines only).
Outputs with `! "` instead of `BEG` to save 13 bytes.
(Here the TIO for the old/longer program: [Try it online with `BEG` as output](https://tio.run/##lVFbCoAwDPtuTtGriQj6Jyh4/LlsUzu7CfqANmuadD3mZZ@2dRinEFRFFPFVRimAViBMJvFRJjdkiRnMaSaakwbRft36x0Bp3GvgJayT9kBfPH8Ntf7Lo3fUsvY1jbN7hS@Zjj27ALTd@U2h69JuRiqVC06FBEsz/LkSBUsTWwuDsxCMCEgGbg3@kDIZT0I4AQ).)
**Explanation in pseudo-code:**
```
Push the codepoint-integers minus 31 of string '!!"""!! !!\n
!!!""!" ""\n
!!!!!!! ""\n
!"!!!!!!!\n
!!" !! !!!\n
!!""!! "!!\n
\n
!"!!!" ! \n
""!! ! \n
""! \n
"" '
a=9
Start LOOP1:
Push the codepoint-integers minus 31 of string '\n
'
a = a-1
If a==0:
Jump to LOOP2
Go to next iteration of LOOP1
LOOP2:
Add 31 to the top integer
Print it as character with this codepoint to STDOUT
Go to next iteration of LOOP2
```
The constant `31` is generated by [this Java program](https://tio.run/##fVLva9swEP2ev@J8n2Scmgy2D7UjSgsdGJYO6nQblDJkV03UObIny4Ew8renJ/9InG3UH6TH3Xvvzqd7FVtx8fr863DIC1HXsBBK/5kAVE1WqBxqKyxd21I9w4ZSLLVG6dXjEwjf0QC6ABhZN4UFDuJx9hS3GaUt1BtRFLJ2iURbuZImXFz/@Pnt@svD7RQSfhmPTQb2/WCG2OW/Pixv76OX0jBnqngSq/mHT7NYBUHfxqkRjji104oPWgCny3ZWQhZ1bYYraW8oUDP/KKd@X4BlnCsf8lJbpRvZ1Y2PDMup/LL8vlakrUQub5QWZtdVZtmF8uORG7Oh/N2IombVuAxQiyY0sirI4LMytWXVtAowvUtxpN@DLGoJ5zobmBHjiCpuh/AQpPImLKRe2TXzYX4c7aiRf6Y98h6928nmlE4ors5Ldme6q63chGVjw4qGYgvNsJNzDAbTAGN6QwySACECDN4bauL3Zf92Zuftt6z9hI5@Zft1eM/b7ZLuB7IVhp4X0xQDpjmfXSFGek7XEiM8PsywgXk0bLMtzyxd1l8Iuw5FVjPt@/9bNRvwfP7x8op8I/KPR/Mz0jZGEwPvsPuj/eFwcBlEd7Ykr8UT8Ai22EH0CHswWpcJBVqC5xH0CEIPvZ6LLt9@DmJLdYRWRfgN), based on [this Whitespace tip of mine](https://codegolf.stackexchange.com/a/158232/52210).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 92 bytes
```
f=(x=200,n=0xe482b7c850b79b07c4080ea138643fd606dacb4523n)=>x?f(x-1,n/3n)+n%3n+[`
`[x%10]]:''
```
[Try it online!](https://tio.run/##DcfdCsIgGADQ@95jTNlWnz9TC6wHGYOp0yjGZ7QI3946d@fpvm4P78frM2BeYw0Z97zF45bvhNRkSbEcoEcLJUrDvQ5mBK/PHnSQYCA6JoySIq0K1OqClyMXSO213BIpA@vx9G@HjcBuWg7LVBoG83xp20oJpfUH "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 146 bytes
```
x=>(x=`EEEEEEEEEE
`).repeat(9)+`EEEEGGEEEE
EEEEBGGEEE
EBEEBBGGEE
EBEGBBBGBE
${x}BBGEBBGGBB
BBBEBBEGBB
BBBBBBBGBE
GGEBBBBBBB
GGEGBGGBBB
BBEBBGGGBB`
```
[Try it online!](https://tio.run/##PcvBCoMwDAbge5/DQ4LofQc9BEpeo8UV2RArKqMw9uxdEsQcwkf@P@/4ice0v7azW/Mz1SmvR15Sv@QZoJZhhDIEf48L2O9pS/GEB7YWMFugi8zOk9CsZBKTd823/ESWEDm5Cv1FukqsuY2SraoF@xKHioBY/w "JavaScript (Node.js) – Try It Online")
* +
[Answer]
# [Uiua](https://www.uiua.org), 104 bytes
```
≡(&p⊏:".O#"⇌)⬚0≡(≡/(+×2)↯⊟:2⌈÷2⧻.)⋯⊂⊚9+.640_1184_66856_68940_0_337197_345357_349516_169301_167093_332973
```
[Pad](https://uiua.org/pad?src=0_8_0__4omhKCZw4oqPOiIuTyMi4oeMKeKsmjDiiaEo4omhLygrw5cyKeKGr-KKnzoy4oyIw7cy4qe7Linii6_iioLiipo5Ky42NDBfMTE4NF82Njg1Nl82ODk0MF8wXzMzNzE5N18zNDUzNTdfMzQ5NTE2XzE2OTMwMV8xNjcwOTNfMzMyOTczCg==)
Outputs the following:
```
..........
..........
..........
..........
..........
..........
..........
..........
..........
....##....
....O##...
.O..OO##..
.O.#OOO#O.
..........
OO#.OO##OO
OOO.OO.#OO
OOOOOOO#O.
##.OOOOOOO
##.#O##OOO
OO.OO###OO
```
[Answer]
# APL+WIN, 112 bytes, 109 bytes or 68 bytes
Prompts for characters to display. 3 bytes can be saved if a matrix of the integers 1 2 3 is allowed. Simply delete the first 2 characters and the last.
```
⎕[⍉(2×b⊤n,48 24 12 68 0 140 4 4 768 856 28)+((b←10⍴2)⊤(n←9⍴0),0 32 304 314 0 819 947 1018 127 39 867)+z←10 20⍴1]
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##HY5NCsIwEIX3OcXsTGgLmSQ2yVYQERQPIC7aSkUoVehKD@AfVNyIF/AI3sCb5CJ1KrN5j8f3Mdm@StaHrNptkqLKmmZbdOH@nM/C6aEZpemCErJwOZf9sAztlavvKw@3dx0bB8oAKkgdSEAjwdBZam6YgnIi4jzveRnajxLE8JqqpyZFLEEr0NKARkO4Qw/eWECJjpwWtAeXWhEd/wZQvQRXHb3CupINxpPRgMEP "APL (Dyalog Classic) – Try It Online")
Alternatively using the base 3 approach with the integers 0 1 2 representing E G B
```
(9 10⍴0)⍪(11⍴3)⊤376 9124 594 4417 146893 166580 55205 18212 2551 337
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##Dcw7CgIxEADQPqeYcrdYyGRm8jmCoHiGsLIiBBS28gKuCCs23sDK2hPNRWK6V718KcPhmsv5OIwlz/NprPp877Z6e5Fp2uyb0Oh9mWqXAK2uP9vr@u0QG6nXx4eCh4SOQRIDMwZA9jERoPcSLYg4K4DRoQMngkAUahtNnYyBPw "APL (Dyalog Classic) – Try It Online")
[Answer]
# Python (3), ~~229~~ ~~142~~ ~~132~~ 125 bytes
```
x=0
while x<400:print(''.join("█░▓"[int('bie58lyn9recsv5ux1hcplbz7kxon7tmdbe9cplju',36)>>i&3]for i in range(x,x+20,2)));x+=20
```
[Try it online](https://tio.run/##HchBDoIwEADAu69oOAgNxFQQERU@YjwIVruIW1JBF1/g1ZjwQD5SjXOcpm@VxshaysTkoaCWjLYLIdaNAWw9151VGtBzxuE1Du9x@Di7/xcg41XdY2pkebvHHc1V2dTFM7mQxqS9HguZ/qLq3CBa8jyHabQ/acOAATJzwLP0KCA/FEHIOd@Qn4XC2i8)
**Output (Rotated 180°)**
```
▓▓░░░▓▓█▓▓
▓▓▓░░▓░█░░
▓▓▓▓▓▓▓█░░
█▓░▓▓▓▓▓▓▓
▓▓░█▓▓█▓▓▓
▓▓░░▓▓█░▓▓
██████████
█▓░▓▓▓░█▓█
██░░▓▓██▓█
███░░▓████
████░░████
██████████
██████████
██████████
██████████
██████████
██████████
██████████
██████████
██████████
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~50~~ 49 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
`mcnhp4 bn26 3hsvn2Ô©u6pn8t4n4v l2`qÍ®nH3ÃùT20 Õ·
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YG1jbmhwNJpibjI2jTNoc3ZuMtSpdTZwbjh0NG40doFsMmBxza5uSDPD%2bVQyMCDVtw)
My idea was to compress the 10 columns as base-3, left-pad each with zeroes to length 20, and transpose. I think this is more optimal than compressing the 11 rows as base-3 and prepending 9 rows of zeroes, which seems to be the strategy most submissions are using right now.
The idea used by Nick Kennedy's clever Jelly solution doesn't translate to Japt because it doesn't have support for bigints without hooking into JS, and when you leave Japt-land you don't get compression, so the program ends up quite a bit longer.
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 47 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
`l2n4v8t4nu6pn2Ô©3hsvn26ebnhp4nmc`qÍ®nH3ÃùT20
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=YGwybjR2gTh0NG51NnBuMtSpM2hzdm4yNo1lYm5ocDRubWNgcc2ubkgzw/lUMjA)
Output rotated 90 degrees.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~159~~ ~~156~~ 153 bytes
```
console.log('94E2G8EB2G4EB2E2B2G3EBEG3BGB11E2BGE2B2G5BE2BEG9BGBE2GE7B2GEGB2G5BE2B3G2B'.replace(/(\d+)(.)/g,(_,t,c)=>c.repeat(t)).replace(/.{10}/g,`$&
`))
```
[Try it online!](https://tio.run/##RYpBCsIwEEX3nkNsBmNq04p2oYvAMJcQbEhDqZSmtMGNePY4CuJm/vz3390@7OLmfoq7MbQ@JRfGJQxeDaETWV2hphMaTRUf1PyUaJBKQ6YouNOXHQwHUs2UfTwyQvrxkrTJ1OynwTovcnFttyAU5J0UNxmlg/PFfWZvo4gAf1M9i/2LtWa9WTUAKb0B "JavaScript (Node.js) – Try It Online")
[Answer]
# Assembly (nasm, x64, linux) 322 bytes
```
b dq 0,0,0,0,01ADB000000000h,0BEF21AC00033838h,0BFE67E8h,8455DEDA83BD4C42h,41B2938E84746B28h,8343133241A32656h
global _start
_start:mov r8,b
mov bl,20
l:mov eax,[r8]
mov rsi,rsp
mov rcx,10
mov[rsi],cl
r:mov dl,0
mov r9,10
div r9
add dl,48
dec si
mov[rsi],dl
loop r
mov al,1
mov dx,11
mov di,1
syscall
add r8,4
dec bl
jnz l
```
[Try it online!](https://tio.run/##RY5dbsMgEITfOQUH2Er82SF9M7FziSiqwFi1o3WcQlQlvbwLOFXhgW9nZ0bYGIfZ4fPtauO8ro76L8rgdXnTGvZ3RmCmOwreHNIgpZY6K8eu3nWJtKqqtmsbLU2rDkqMoLgRe6k7rXaqNiJ7pJJcSqF4I0Vd1SP5xMVZpB/xbsOdbM/7vHzToMGRDA5BMIJFHOwDTkGfyyLECUK8bdw/gLOMpySfoUcSSsIjsM2xzwY/ZSLW@7xRmvihp3H6D3okuCw3GkrIIvACPtW/aEpSfMbeIpae9FFVahySy/WH4rr@Ag)
[Answer]
# [YASEPL](https://github.com/madeforlosers/yasepl-esolang), ~~131~~ 130 bytes
```
=m)"1"=a;m,10<<<<<<<<<;m,4~#44<~>944111#19>11994411>1914999491;m,10<=g;"9",2~#41~#44<~#91~#14<~~~>9491#441~~~>9#44149449<~#m~#444~
```
really annoying code but here's the output:
```
1111111111
1111111111
1111111111
1111111111
1111111111
1111111111
1111111111
1111111111
1111111111
1111441111
1111944111
1911994411
1914999491
1111111111
9941994499
9991991499
9999999491
4419999999
4414944999
9919944499
```
uses 1, 4, and 9
edit : fixed an inconsistency
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 100 bytes
```
E93G1E7BG1E3BE1B1G1E2BEGB2GBE10B1GEB1G1B4EB1EGB8GBEG1EB6G1EGBG1B4EB1G2B1
\d+
$*
+`(.)1
$1$1
!`.{10}
```
[Try it online!](https://tio.run/##K0otycxL/P@fy9XS2N3Q1dwJSBg7uRo6GQIZRk6u7k5G7kCuAZDvChJzMgFSQFELoChQhZOZO4gHFXc3cjLkiknR5lLR4tJO0NDTNORSMVQx5FJM0Ks2NKj9//@/blkOAA "Retina 0.8.2 – Try It Online") Explanation: Inspired by @mekb's JavaScript answer.
```
E93G1E7BG1E3BE1B1G1E2BEGB2GBE10B1GEB1G1B4EB1EGB8GBEG1EB6G1EGBG1B4EB1G2B1
```
Insert the RLE compressed string.
```
\d+
$*
```
Convert to unary.
```
+`(.)1
$1$1
```
Perform RLE decoding.
```
!`.{10}
```
Split into rows of `10` characters.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `j`, 77 bytes
```
90'e×"∧.€¯uэuꜝ!¹»ġ«ᶳ⊻)pṚnṘᵞΘṆuĿġɾ⌐5Ṙ}Ч∥•Ɠ₌ᶳ¿⌈X¥¿₀Ḥ₉ỌŀoṆ~2JᶪNgWyZ∨ᵏᵘ#Ṡ=<W„J₀Ẇ
```
[Try it Online!](https://vyxal.github.io/latest.html#WyJqIiwiIiwiOTAnZcOXXCLiiKcu4oKswq910Y116pydIcK5wrvEocKr4baz4oq7KXDhuZpu4bmY4bWezpjhuYZ1xL/Eocm+4oyQNeG5mH3Qp+KIpeKAosaT4oKM4bazwr/ijIhYwqXCv+KCgOG4pOKCieG7jMWAb+G5hn4ySuG2qk5nV3la4oio4bWP4bWYI+G5oD08V+KAnkrigoDhuoZcbiIsIiIsIlxuIiwiMy40LjEiXQ==)
90 'e's then the rest of the board as a string, split into chunks of 10
will try to do an algorithmic approach later
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-l`, 46 bytes
```
0X94.(A*"!`V(;O0
1U _3^R@=Mc,c"FDh)TB3<>t
```
The code contains unprintable characters which do not display correctly on StackExchange. Here's a hexdump:
```
00000000: 3058 3934 2e28 412a 2203 2160 5628 3b4f 0X94.(A*".!`V(;O
00000010: 300c 3155 095f 330e 5e52 4016 3d4d 632c 0.1U._3.^R@.=Mc,
00000020: 1a08 6322 4644 6829 5442 333c 3e74 ..c"FDh)TB3<>t
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSbo5S7IKlpSVpuhY39QwiLE30NBy1lJgVE8I0rP0NeAxDOeON-eKCHMRsfZN1pDiSldxcMjRDnIxt7EoguqCaF0BpAA)
### Explanation
Basically the same idea as [Nick Kennedy's Jelly answer](https://codegolf.stackexchange.com/a/269414/16766), though Pip doesn't have the same base decompression builtin:
```
0X94.(A*"..."FDh)TB3<>t
t is 10; h is 100 (implicit)
"..." String of characters
A* Get ASCII code of each
FDh Treat those as base-100 digits and convert to base 10
( )TB3 Convert to base 3
0X94. Prepend string of 94 zeros
<>t Group into chunks of length 10
Print each on a separate line (-l flag)
```
I experimented with several bases and found 100 to give the best results. It's not the most efficient compression, but saving two bytes by writing `h` instead of `100` makes up for that.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 32 bytes
```
"ṁṘkƓ₳İᵛᵂƛ»Ω7∥I»;ᶤḌᶠĖꜝ“3y₅dÞ0₀Ẇ'
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJcIuG5geG5mGvGk+KCs8Sw4bWb4bWCxpvCu86pN+KIpUnCuzvhtqThuIzhtqDEluqcneKAnDN54oKFZMOeMOKCgOG6hiciLCIiLCIiLCIzLjQuMSJd)
This is roughly a port of Nick Kennedy's Jelly answer.
[Answer]
# Pascal (FPC), 232 bytes
On 6 June 1984, the first Tetris version was written in [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)) for the Electronica 60.
```
var i:Byte;begin for i:=1 to 9 do WriteLn('EEEEEEEEEE');WriteLn('EEEEGGEEEE'#10'EEEEBGGEEE'#10'EBEEBBGGEE'#10'EBEGBBBGBE'#10'EEEEEEEEEE'#10'BBGEBBGGBB'#10'BBBEBBEGBB'#10'BBBBBBBGBE'#10'GGEBBBBBBB'#10'GGEGBGGBBB'#10'BBEBBGGGBB');end.
```
[Try it online!](https://tio.run/##VcwxC8IwEAXgv3LgUDsodtTg8qDc4u4c21QCkpQ2CP76mJyN1tu@d@9u1HOnH7th7GJ86onsCa9g1M3craPB5@DcUPB0pN7TdbLBXNy2ar9T1eovZZZ00xyEEH@IRHEhIxm/8vIxMy2kDCxEYrsiVrecuzKFLKelLJ/yba2M6/cxvgE)
**Challenge**
Can the code be modified to < 200 bytes?
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•{Žúƶ
Í‹¼šÎëPšpUθrćQ´β•3B¾94×ìTô»
```
~~Outputs `012` for `BEG`/blue-black-green respectively.~~
-1 byte thanks to *@noodleMan* by using `012` for `EGB`/black-green-blue instead.
[Try it online.](https://tio.run/##AUMAvP9vc2FiaWX//@KAonvFvcO6xrYKw43igLnCvMWhw47Dq1DFoXBVzrhyxIdRwrTOsuKAojNCwr45NMOXw6xUw7TCu///)
**Explanation:**
```
•{Žúƶ
Í‹¼šÎëPšpUθrćQ´β•
# Push compressed integer 166987503168216280220890692936947577852890694295235
3B # Convert it to base-3: 1100000000211000020022110002012221200000000000221022112222202201222222222120110222222211012112222202211122
¾94× # Push a string of 94 "0"s
ì # Prepend it
Tô # Split it into parts of size 10
» # Join this list by newlines
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210), to understand why `•{Žúƶ\nÍ‹¼šÎëPšpUθrćQ´β•` is `166987503168216280220890692936947577852890694295235`.
[Answer]
# [Javascript (V8)](https://v8.dev), 134 bytes
```
for(x of"@@@@@@@@@Ԁी𠩐𡪘@")print("0".repeat(10-(m=((v=x.codePointAt(0))<65?0:v).toString(4)).length)+m)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SKNCIT9NyQEGrjQ8WNrwYcHKCR8Wrprh8GnJylmfVqyY9WnVqhkfJ61a9XHi0lWfFi2dpaRZUJSZV6KhZKCkV5RakJpYomFooKuRa6uhUWZboZecn5IakA9U4FiiYaCpaWNmam9gVaapV5IfXALUl65hoqmpl5Oal16Soamdq/n/PwA "JavaScript (V8) – Try It Online")
My first post! :3 Might as well start here because I'm a tetris fanatic
]
|
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
The Elves like playing number games. One day, Bin (a friend of Fen) suggests a new game: given a positive integer `n`, each Elf says a number which has exactly `n` runs of ones in binary. The first Elf must say the smallest number, and the next ones must say the smallest number greater than the last one.
## Task
Given `n`, output the sequence.
You can use any of [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O methods:
* Given `n`, output the corresponding sequence infinitely
* Given `n` and the index `k` (may be 1- or 0-indexed), output the `k`th number in the sequence for `n`
* Given `n` and `k`, output the first `k` numbers of the sequence for `n`
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
n = 1
1, 2, 3, 4, 6, 7, 8, 12, 14, 15, 16, 24, 28, 30, 31, 32, 48, 56, 60, 62, 63,
64, 96, 112, 120, 124, 126, 127, ...
n = 2
5, 9, 10, 11, 13, 17, 18, 19, 20, 22, 23, 25, 26, 27, 29, 33, 34, 35, 36, 38,
39, 40, 44, 46, 47, 49, 50, 51, 52, 54, 55, 57, 58, 59, 61, 65, 66, 67, 68, ...
n = 3
21, 37, 41, 42, 43, 45, 53, 69, 73, 74, 75, 77, 81, 82, 83, 84, 86, 87, 89,
90, 91, 93, 101, 105, 106, 107, 109, 117, ...
n = 4
85, 149, 165, 169, 170, 171, 173, 181, 213, 277, 293, 297, 298, 299, 301, 309,
325, 329, 330, 331, 333, 337, 338, 339, 340, 342, 343, 345, ...
n = 5
341, 597, 661, 677, 681, 682, 683, 685, 693, 725, 853, 1109, 1173, 1189, 1193,
1194, 1195, 1197, 1205, 1237, 1301, 1317, 1321, 1322, 1323, 1325, ...
n = 6
1365, 2389, 2645, 2709, 2725, 2729, 2730, 2731, 2733, 2741, 2773, 2901, 3413,
4437, 4693, 4757, 4773, 4777, 4778, 4779, 4781, 4789, 4821, 4949, 5205, ...
```
The corresponding OEIS sequences are [A023758](http://oeis.org/A023758) (without leading 0), [A043682](http://oeis.org/A043682), [A043683](http://oeis.org/A043683), [A043684](http://oeis.org/A043684), [A043685](http://oeis.org/A043685), and [A043686](http://oeis.org/A043686).
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 55 bytes
```
n->for(i=1,oo,sumdigits(bitxor(i,2*i),2)-2*n||print(i))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN83zdO3S8os0Mm0NdfLzdYpLc1My0zNLijWSMksqQOI6RlqZmjpGmrpGWnk1NQVFmXklGpmamhDtS9I0zKDMBQsgNAA)
Outputs the sequence infinitely.
For each positive integer \$i\$, print it if the sum of binary digits of \$\operatorname{bitxor}(i,2i)\$ is \$2n\$.
[Answer]
# [Python 3](https://docs.python.org/3/), 61 bytes
```
def f(n,i=1):
while[n-1!=bin(i).count('01')or print(i)]:i+=1
```
A function that, given the number of runs, \$n\$, will print indefinitely.
**[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI08n09ZQ04pLoTwjMyc1Ok/XUNE2KTNPI1NTLzm/NK9EQ93AUF0zv0ihoCgTyMvUjLXK1LY1/J@mYab5HwA "Python 3 – Try It Online")**
### How?
The number of runs of `1`s is the number of occurrences of `01` plus one (a binary number always starts with a one).
The clause of the `while` loop will always be truthy as it is either `[True]` (when `i` has not got the right number of runs of ones) or `[None]` (when it does and `print(i)` executes and returns `None`).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ 12 bytes
```
`@BY'wsG=?@D
```
Outputs the sequence indefinitely.
[**Try it online!**](https://tio.run/##y00syfn/P8HBKVK9vNjd1t7B5f9/IwA) (you can stop it to see the output).
### Explanation
```
` % Do...while
@ % Push iteration index, starting at 1
B % Convert to binary. Gives, for example, [1 1 0 0 0] at iteration 24
Y' % Run-length encoding. Gives two outputs: [1 0], [2 3] in the example.
% (The first output is the one really needed; the second will be
% repurposed as loop condition to create an infinite loop)
w % Swap. Moves [1 0] to the top of the stack
s % Sum. This gives the number of runs of ones
G= % Does it equal the input?
? % If so
@D % Push iteration index and display immediately
% End (implicit)
% End (implicit). The loop condition, [2 3] in the example, is always
% a vector of non-zero numbers, which is truthy, thereby producing an
% infinite loop
```
[Answer]
# [Rust](https://www.rust-lang.org), 52 bytes
```
|j|(1u32..).filter(move|i|(i^i*2).count_ones()==j*2)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LcwxDoIwGAXgnVNUpr9GG0VNDFA8g4ujxJA2-bG0prQulJO4MOjudbyNGHzLS17yvsfT-tYNb6lJc0ENtFPCEclf3snl_rMNdYC13ySMUSZROWGhMXcRMACecZ5QVhmvXWm0aIFyXo_T_3vMImksQYKaTATfkS4iY24WtVN6BnGXHvp4IQEpc5ergGT1E5USlUvT_CSqvCwKoDSL-qif4GGY-gs)
Uses the xor trick. Could save 1 byte by using u8 and abusing the "ignore number limits" rule.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 56 bytes
*-2 thanks to [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)*
Prints the sequence infinitely. And so do the other versions.
Using [alephalpha's method](https://codegolf.stackexchange.com/a/255350/58563) is more straightforward and shorter. Instead of incrementing each run one by one, \$k \operatorname{XOR} 2\times k\$ isolates all of them at once.
```
n=>{for(k=0;g=k=>k&&.5+g(k&k-1);)g(++k^2*k)-n||print(k)}
```
[Try it online!](https://tio.run/##BcFRCoAgDADQ28iWGCUEgcyjBBIoNjAx8Sc7u713ueaes8RcVduHp5HIvv4uwLSYQEyWhZg3GYAFqxUNBpCSDz0xqtR7LjFVYPyGB43jBw "JavaScript (V8) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), 61 bytes
```
n=>{for(k=0;g=k=>k&&k%2+g(++k/(k&-k)>>1);)g(++k)-n||print(k)}
```
[Try it online!](https://tio.run/##HchBCoAgEADA1yS7iFSeAln/EoFiCyYmXrK3b9Ac59z7fh81lWb6JoEkk3/CVYFpcZGYPCvFk9URtOYZWBlG71d0@A@aPEapKTdgfCWARfkA "JavaScript (V8) – Try It Online")
### Recursion logic
Below is an example of the recursion that happens in \$g\$ for \$k=441=110111001\_2\$, which has three runs of 1's:
```
0110111001 | odd -> we have a first run of 1's
0110111010 | increment
011011101 | divide by (k & -k) --> remove the trailing zeros
01101110 | right-shift by 1
------------+--------------------------------------------------
01101110 | even -> this is not a run of 1's
01101111 | increment
01101111 | divide by (k & -k) --> no change here
0110111 | right-shift by 1
------------+--------------------------------------------------
0110111 | odd -> we have a 2nd run of 1's
0111000 | increment
0111 | divide by (k & -k) --> remove the trailing zeros
011 | right-shift by 1
------------+--------------------------------------------------
011 | odd -> we have a 3rd run of 1's
100 | increment
1 | divide by (k & -k) --> remove the trailing zeros
0 | right-shift by 1
------------+--------------------------------------------------
0 | stop
```
---
# [JavaScript (V8)](https://v8.dev/), 63 bytes
A longer, slower, less fun solution using a regular expression.
```
n=>{for(k=1;;k++)k.toString(2).split(/1+/).length+~n||print(k)}
```
[Try it online!](https://tio.run/##DcpBCoAgEADA7yiSYqdA7BO9QCLLFBVdvGR9ffM8c5tm6l5chqktaDVGvT42FeK1VMozRj2HtEFx8SQz5TUHB0RIJigPRzzhYl/sPQ8H4umLdiz8AQ "JavaScript (V8) – Try It Online")
[Answer]
# Excel (ms365), ~~86~~, 80 bytes
-8 Bytes thanks to [jdt](https://codegolf.stackexchange.com/users/41374/jdt)
[](https://i.stack.imgur.com/YQNgd.png)
[](https://i.stack.imgur.com/NX90l.png)
[](https://i.stack.imgur.com/PL5lL.png)
Formula in `A1`:
```
=LET(x,ROW(A:A),FILTER(x,MAP(BASE(x,2),LAMBDA(a,COUNTA(TEXTSPLIT(a,0,,1))))=B1))
```
`ROW(1:1048576)` is used since that is the upper limit for Excel's rowcount in ms365.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 36 bytes
```
{grep *.base(2).comb(/1+/)==$_,1..*}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@786vSi1QEFLLymxOFXDSFMvOT83SUPfUFtf09ZWJV7HUE9Pq/Z/cWKlQpqGoWZ0nLFBrDUXhGuEyjWGcv8DAA "Perl 6 – Try It Online")
Anonymous function that takes \$n\$ and returns an infinite sequence.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
BŒgSḢ=ð#`
```
[Try it online!](https://tio.run/##y0rNyan8/9/p6KT04Ic7Ftke3qCc8P//f7P/RgYA "Jelly – Try It Online")
Full program taking `n` and `k` as successive command line arguments, outputting the first `k` elements of the sequence for `n`. A fun 11-byte alternative is `BIAS:2‘ð#``.
```
ð#` Count up the first k integers from n, which satisfy, given n:
Œg Group runs in the
B binary representation of the candidate.
S Sum the runs column-wise.
Ḣ= Is the first sum equal to n?
```
[Answer]
# [Python 3](https://docs.python.org/3/), 100 bytes
```
from itertools import*
def f(n):
k=1
while 1:
if 0<len([*groupby(bin(k))])-2*n<3:print(k)
k+=1
```
[Try it online!](https://tio.run/##DcpBCsMgEEDRvaeYpVoKsaGbkJykdBPqNINmRsyUktMbl//xy6mb8NgaVtmBNFYVyQfQXqSqN5@IgJbdZCAtwcB/oxwh9ARCGOYc2b78t8qvrKddiW1y7u3uD8/zOJVKrF36nW5LaGifrl0 "Python 3 – Try It Online")
`itertools.groupby` can be used to find consecutive groups of equal values, and we can check the total number of groups to verify if its valid.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 55 bytes
Takes \$ n \$ as input, and outputs the corresponding sequence infinitely.
Based on the recurrence `f(i) = f(i/2) + (i%4==1)`, which records the number of runs of ones in binary. The funny-looking expression, `i%4%3%2`, is used to save a byte over `(i%4==1)`.
```
n=>{for(i=0;;)(os[++i]=i%4%3%2+~~os[i>>1])-n||print(i)}
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9auOi2/SCPT1sDaWlMjvzhaWzsz1jZT1UTVWNVIu64OKJJpZ2cYq6mbV1NTUJSZV6KRqVn7P03DSPM/AA "JavaScript (V8) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒbγĀOQ
```
Outputs the infinite sequence.
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8U5OSzm0@0uAf@P@/CQA) or [verify the first 100 items up to \$n\$=6](https://tio.run/##AS8A0P9vc2FiaWX/NkVOwqk/IiDihpIgIj//4oieypJizrPEgE/CrlH/fdGCwqMswrY//w).
`γĀO` could alternatively be `Ô1ö`:
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8U5OSDk8xPLwt8P9/EwA) or [verify the first 100 items up to \$n\$=6](https://tio.run/##AS8A0P9vc2FiaWX/NkVOwqk/IiDihpIgIj//4oieypJiw5Qxw7bCrlH/fdGCwqMswrY//w).
**Explanation:**
```
∞ # Push the infinite list of positive integers: [1,2,3,...]
ʒ # Filter it by:
b # Convert the current integer to a binary-string
γ # Split it into groups of equal adjacent items
Ā # Python-style truthify each group: 1 for runs of 1s: "1"/"11"/"111"/etc.;
# 0 for runs of 0s: "0"/"00"/"000"/etc.
O # Sum it together to get the amount of groups of 1s
Q # Check if its equal to the (implicit) input-integer
# (after which the filtered infinite list is output implicitly as result)
Ô # Connected-uniquify each group of equal adjacent items
1ö # Convert it from base-1 to base-10, basically summing the digits
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~23~~ 21 bytes
```
W++iI$+TBiBXi*2=a*2Pi
```
[Try It Online!](https://tio.run/##K8gs@P8/XFs701NFO8Qp0ykiU8vINlHLKCDz////xgA)
Port of [@alephalpha's answer](https://codegolf.stackexchange.com/a/255350/110555). ALternatively, [a ~~27~~ 23 byte version](https://dso.surge.sh/#@WyJwaXAiLCIiLCJMYntUJCtUQjIqVWlCWGk9YSoyeFBpfSIsIiIsIjMgMTAiLCIiXQ==) taking `n` and `k` and returning the first `k` items
-2 bytes (and -4 from the `n+k` version) thanks to @DLosc
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 71 bytes
```
i1:0$:2%?\2 ,40.
>:?v~{:}= ?^1+10.
01.\:2%?v\$1+$1-2,
1.11,2-1/ /:naob
```
[Try](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTE6MCQ6MiU/XFwyICw0MC5cbj46P3Z+ezp9PSA/XjErMTAuXG4wMS5cXDoyJT92XFwkMSskMS0yLFxuMS4xMSwyLTEvICAvOm5hb2IiLCJpbnB1dCI6Ilx1MDAwMiIsInN0YWNrIjoiIiwibW9kZSI6Im51bWJlcnMifQ==)
## Explanation
[](https://i.stack.imgur.com/OuiuZ.png)
><> lacks any kind of bitwise operators. So the only way to do this is with modulo. Basically, There I built a state machine that keeps track of the last bit. If `num%2 == 1` and this wasn't true in the last state we add one to the streak.
Top edge, red corner: Setup: Read the input, and start counting from 1.
Top edge: Left dark blue half. Start a loop. Set current streak to 0. Then we reach the state if the last bit was a 0. We mod 1 and if it is 1 we go down to add 1 to the streak. Otherwise we divide the number by 2 and return to the `:2` part.
Second row, left part and third row left half: This is the state where the last bit was a 1. If it is a 1 again we sub 1 div 2 then jump back. If it is a 0 we can go back to the last state 0 state. If the entire number is 0 we jump to middle row right half.
Middle row, right half: Compare the streak to the input. If they are equal print it (bottom right corner red) In either case add 1 to the counter and jump back to the start.
Third row right half: This is the case if the last digit was a 0 but this is a 1. Add one to the streak.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
bĠ∩Ṡ⁰c)ȯ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJixKDiiKnhuaDigbBjKcivIiwiIiwiMTBcbjIiXQ==)
Takes `k` and `n` and returns the first `k` items.
Port of Jelly.
## Explained (old)
```
b0€ꜝL⁰=)ȯ
-------)ȯ # first k integers where:
b0€ # the binary representation of the number
ꜝ # with empty lists removed
L⁰= # is of length n
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 129 bytes
```
L$`\d+$
*
"$+"{`_(1*)$
_0$1
T`d`10`01*$
/^(_)+(?<-1>1+(0+|$))+(?(1)^)$/^{`_(1*)$
_0$1
))T`d`10`01*$
+`(\d*)\D+(\d)
$.($1*2*_$2*)¶
```
[Try it online!](https://tio.run/##VcstDgIxEIZhP8fYfGJ@AttZFAkBg0Qim3ZIisAgyDo4FwfgYgUcqDeveG7n@XI9ee8HRG4GUhpgwz0quwqoJjgdo4WnSK6gsXAV491m4Vs3TvaAfJ9dimAs/1Lk11pwbip5b58KYclwnbRiUnk9e1/T6g0 "Retina – Try It Online") No test suite because of the way the program uses history. Takes `k` and `n` as input and outputs the `k`th number in the sequence for `n`. Explanation:
```
L$`\d+$
*
```
Drop `k` and convert `n` to unary.
```
"$+"{`
)`
```
Repeat `k` times.
```
_(1*)$
_0$1
T`d`10`01*$
```
Increment the binary number after `n`.
```
/^(_)+(?<-1>1+(0+|$))+(?(1)^)$/^{`
)`
```
Repeat while the binary number does not have exactly `n` runs of `1` bits...
```
_(1*)$
_0$1
T`d`10`01*$
```
... increment the binary number after `n`.
```
+`(\d*)\D+(\d)
$.($1*2*_$2*)¶
```
Convert the binary number to decimal.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 28 bytes
```
NθNη≔⁰ζW‹ⅉη«≦⊕ζ¿⁼θ⊕№⍘ζ²01⟦Iζ
```
[Try it online!](https://tio.run/##TYy7CsIwFIbn9ikOnU4gQtVJnLQ4FFQEJxGHWNMmkKZtLgoVnz0GdOi/ff@tEsxUHVMhlLr37ujbOzc4kHU6ZRF5Y61sNOYUxkgvIRUH3HNr8YKEgiAE3mlyYP2/WOrK8JZrxx@/SSJrwN3gmbI4UJjkWHReO9wyy8/OSN3gSGERT7N8npEoOEXX4bVg1uFIbvHtE8ISVmH2VF8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `k` elements. Explanation:
```
NθNη
```
Input `n` and `k`.
```
≔⁰ζ
```
Start at zero.
```
W‹ⅉη«
```
Repeat until `k` numbers have been output.
```
≦⊕ζ
```
Try the next number.
```
¿⁼θ⊕№⍘ζ²01
```
If this number has `n-1` copies of `01`, then...
```
⟦Iζ
```
... output this number on its own line.
Edit: Saved 1 byte by using @JonathanAllen's run counting technique.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
ℕ≜ḃḅzh+
```
A [generator](https://codegolf.meta.stackexchange.com/a/10753/16766) predicate that takes \$n\$ through its output parameter and produces the numbers from the corresponding sequence through its input parameter. [Try it online!](https://tio.run/##ASsA1P9icmFjaHlsb2cy/37ihrDigoHhuoniiqX/4oSV4omc4biD4biFemgr//82 "Brachylog – Try It Online")
### Explanation
```
ℕ≜ḃḅzh+
ℕ The input parameter is a nonnegative integer
≜ Try each possibility in ascending order
ḃ Convert to binary digits
ḅ Group into blocks (runs of identical items)
z Zip the list of blocks
h Take the first sublist (which contains the first element of each block)
+ Sum
The predicate succeeds if that sum is equal to the output parameter
(i.e. n); otherwise, it fails, backtracks, and tries the next number
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_¤qT èÊ¥U}jV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X6RxVCDoyqVVfWpW&input=NiA1)
Inputs as `n k`. Outputs the first `k` elements. Can be changed to output the `k`-th element (0-indexed) by swapping `j` to `i`. Can reverse the inputs by swapping `U` and `V`.
```
_¤qT èÊ¥U}jV
_ }jV # Get the first k non-negative integers where this is true:
¤ # Convert to binary string
qT # Split using "0" as a delimiter
èÊ # Count the non-empty items
¥U # Return true if it equals n
```
There could easily be a 4-byte alternative to `qT èÊ`, but I haven't been able to find one yet.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 16 bytes
```
W++iI+X1NTBi=aPi
```
Outputs the sequence forever. [Try it online!](https://tio.run/##K8gs@P8/XFs701M7wtAvxCnTNjEg8////8YA "Pip – Try It Online")
(Works in both Pip Classic and modern Pip.)
### Explanation
Implements the spec directly.
```
W++iI+X1NTBi=aPi
a is first command-line argument; i is 0 (implicit)
W Loop while
++i increment i
is truthy (i.e. forever):
I If...
X1 Convert 1 to a regex
+ Apply the + quantifier to it (one or more 1's)
N Count the number of matches in
TBi i, converted to binary
=a ... equals the program argument:
Pi Print that value of i
```
[Answer]
# [Python](https://www.python.org), 83 bytes
```
f=lambda n,k,b=1,s=.5:n and((k<b)*(4**(s+n-1)-f(n-.5,b-k-1))or f(n,k,b+b*n/s,s+.5))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5BDoIwEEXXeoouZ8q0QmKNIfYUnqANVgEdCMWFZ3HDRu_kbSxRlv_9vJ__fPeP8dLxNL3uY1D7zzHYq7v5ygmmlrwtKFptShaOK4D24FHCVkqIGasCVQBW2pBXbUrYDSKB2cu85E2kmGmD-J_ehdQ3omYxOD6foMhzLNerfqh5hIYCGGqQfM0wg1_ExV4OfgE)
Given n and k this directly computes the k-th term of the n-th series.
Not competitive with the count-up-and-filter methods but I thought it may be interesting.
[Answer]
# x86 32-bit machine code, 22 bytes
```
53 31 C0 40 6B D8 FE 4B 21 C3 F3 0F B8 DB 39 D3 75 F1 E2 EF 5B C3
```
[Try it online!](https://tio.run/##jVLdToMwFL5un@I4s6QVMHOaGIfzDbzxysSZpStlnAmF8KMsulcXT9mcUxNjL3o4/c73A1QHS627TlUZCLgbCB5PWNFUCZhFy1mbl2BU67uNlxOGVvePDLMmdSP@Fg7GnEVGb0nKRnuIsyIvtK13Bw7WWbHrIupW1kDJWZrnhas03U@ZCStNzeVAhnw@V3Vd4qKpzXwuRKyqWqs0lRKQhGPh9ie/b6wM4TlH8hcy7I4pbtpEBq6rOsL8NLnhbihTaIXkr@RWUh@LAbw5HxbT2/ZqK5jCWUjlaApXVD1PcjhYe97wAgc@rBz582xmAy/45/ruiltXdK6XVJ0ro5QH0kN8Iz90tL/Tsi/WLmQsVj5Kx9wchp3ZW6UTpL@g88hM@kROtCXRkQ9raqMcXr/ERuN7UltPhWhshUtrItCJKk9kLB/aRxlu4CXB1MBvHDxoPc@l/AmZww8IYoiwWNemkjNLVq0D6TI0pYVRyDfdu45Ttay6IDsf00ZXd0pMk34A "C (gcc) – Try It Online")
Following the `fastcall` calling convention, this takes a 1-indexed `k` in ECX and `n` in EDX, and returns a number in EAX.
In assembly:
```
f: push ebx # Save the value of EBX onto the stack.
xor eax, eax # Set EAX to 0.
r: inc eax # Add 1 to EAX. EAX will hold the number, x, being tested.
imul ebx, eax, -2 # Set EBX to EAX times -2.
dec ebx # Reduce EBX by 1, making -2x-1, which is the ones' complement of 2x.
and ebx, eax # Set EBX to its bitwise AND with EAX.
# Before this, EBX has a 1 bit to the left of each 0 bit in x and at the end.
# The result of this AND has a 1 bit at the end of each run of 1 bits in x.
popcnt ebx, ebx # Set EBX to the number of 1 bits in EBX.
cmp ebx, edx # Compare that with n (in EDX).
jne r # Jump back, to repeat, if they are not equal.
loop r # Reduce ECX by 1 and jump back if it's nonzero, counting down from k.
pop ebx # Restore the value of EBX from the stack.
ret # Return.
```
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
[{[:I.]=1#.2</\"1[:#:@i.4^+
```
[Try it online!](https://tio.run/##y/r/P03B1kohujraylMv1tZQWc/IRj9GyTDaStnKIVPPJE77f2pyRr6ChqGCtkKmnqmmgkZanYKSgoGCgaa@ggZI5D8A "J – Try It Online")
Takes *k*, 0-indexed, as left argument and *n* as right argument.
* `4` `^` `+`: Raise 4 [to the power (`^`)](https://www.jsoftware.com/help/dictionary/d200.htm) of [the sum (`+`)](https://www.jsoftware.com/help/dictionary/d100.htm) of *k* and *n*. This is an upper bound for the result, as can be proven by considering numbers of the form `(10)*10*` in binary.
* `[:` `#:` `@` `i.`: [Make a list of the integers from 0 (inclusive) to 4*k*+*n* (exclusive) using `i.`](https://www.jsoftware.com/help/dictionary/didot.htm), and then [by composition (`@`)](https://www.jsoftware.com/help/dictionary/d620.htm), [convert those numbers into their binary representations (`#:`)](https://www.jsoftware.com/help/dictionary/d402.htm), using [a 'cap' (`[:`)](https://www.jsoftware.com/help/dictionary/d502.htm) to do so monadically.
The result is a table like this, where each row is a binary representation:
```
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
```
* `2` `<` `/` `\` `"` `1`:
+ [For each infix (`\`)](https://www.jsoftware.com/help/dictionary/d430.htm) of length 2 (each pair of consecutive bits), apply ['less than' (`<`)](https://www.jsoftware.com/help/dictionary/d010.htm) [between the bits (`/`)](https://www.jsoftware.com/help/dictionary/d420.htm), producing 1 for each 0–1 pair (which appears at the start of each run of ones) and 0 otherwise.
Note that this will miss the first run when the very first bit is 1, in the second half of the numbers, but there is enough excess in the upper bound of 4*k*+*n* to let us ignore the second half.
+ On its own, that construction would incorrectly take pairs of *rows*. To fix that, [set its rank (`"`)](https://www.jsoftware.com/help/dictionary/d600v.htm) to 1, so that it applies separately to each row, and then it takes pairs of bits within the rows.
* `1` `#.`: [Convert from base 1](https://www.jsoftware.com/help/dictionary/d401.htm), obtaining the number of runs of ones in each number. Conveniently, this naturally has rank 1, so it doesn't need rank adjustment.
* `]` `=`: [Check for equality (`=`)](https://www.jsoftware.com/help/dictionary/d000.htm) with [the right argument *n* (`]`)](https://www.jsoftware.com/help/dictionary/d500.htm).
* `[:` `I.`: On a list of 0s and 1s, as here, [`I.` gives a list of the indices of the 1s](https://www.jsoftware.com/help/dictionary/dicapdot.htm). Again, use [a 'cap' (`[:`)](https://www.jsoftware.com/help/dictionary/d502.htm) to do this monadically.
* `[` `{`: Use [the left argument *k* (`[`)](https://www.jsoftware.com/help/dictionary/d500.htm) [as an index (`{`) into the list](https://www.jsoftware.com/help/dictionary/d520.htm).
---
Some earlier versions:
```
[i.~[:+/\]=1#.2</\"1[:#:@i.4^+
[i.~[:+/\]=[:+/2</\0|:[:#:@i.4^+
[i.~[:+/\]=0+/@(}:<}.)@|:[:#:@i.4^+
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 79 bytes
```
i;j;m;t;f(n,k){for(i=0;k;k-=!m)for(m=n,j=i++,t=0;j;j/=2)t^j&1?t=!t,m-=t:0;--i;}
```
[Try it online!](https://tio.run/##fVXtbtpAEPyfp7gipcLBKL4P39l13f6o@hQJlSJiUkxwInBV1IhXL51Z85HEqJFY1rNze7NzhzMdP0ynu928qItl0RazYRMvopfZ02o4L5NiUSzG5YdlxOdl2cR1OR@N4haVuqivSxO1P@qP@mtbfmjj5bhsPyXFeDwvtrt506rl3bwZRurlQuGPQLV5rqZtda9vJqpULzpWJlY2Vi5WPlYhVlmsNCANQKf4ADXIDXCb4IMVFnWH5xQ1D8zj2aOHBy8HpqWBSRjYxhAzYVv0VJhOBfbJQeECtNdopaFEUwpwNjLoaIAbUNnOoG5Qs8As9rDALXBLmcAd1jjgDpgD1wFLgaXon6JXilqKNSlqKUdB3aPmgXmOBdxnZxTbTrGhDeyLb0c7aCH70Qb0CvgO2CMAC3QVvAy8DHgGPMMeGXFwc@jKUc85d0IDEhqf0LWEPiQ0R5/zz3VqMvI5ovZyZMwC3QzsRi2aAgydNUGsY5ZLljHQSm5tuZely7azl0cuZy5Oc2QrHtNkS5ctx7dOziE9IzHtJFo6lXJHLz4HMZgZbfH0xXMMT2WBAjJ6qQ/DS55JLj7p3ElMJQa5b8wNJWqZRVu5RdZIzhuEaCWeE@r3vwhLD43lXsbzTE2gBiOiECWnL4haorjqJA/iqzjp6LZzcktkKhd425xwELs8k8gbG@gGIvOMml0utxZznVHbdGrX8z/V02x4/FVH13vk6gTF6h3L9Fmmz7J9lu2zXJ/l@qy0z0r7LN9n@eg0@9Vx@G7244Tx6X1ySu0pdaf0YOX0qVm3avrzbnWFWE0X1aprOrjdfDe3m/wbPukgVq@f7WC/Gq9iNeRpzJv7aoNlSbFPP7@fKVLX6v1QUaFGI@Ef3sxvmtavutaHtoFr6t6iw7VoQO@oI6WLXnmBcv2f@hr17t9Ov1ahdjReekxuul6Tt@TnFeiz4aApL@9jtUBU4y8K8XJ928DKBiDOPD74jU3RefJqy@3FKa6q9teqgQcX293f6ezx7mG9G//ejR@X/wA "C (gcc) – Try It Online")
Inputs \$n\$ and \$k\$.
Returns the \$k^\text{th}\$ number which has exactly \$n\$ runs of ones in binary.
[Answer]
# [Perl 5](https://www.perl.org/), 60 + 2 (`-na` options) = 62 bytes
Given `n` and `k` and outputs the first `k` numbers of the sequence for `n`.
```
{$F+=say if$F[0]==split/0+/,sprintf'%b',++$_;$F[1]>$F&&redo}
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP2/WsVN27Y4sVIhM03FLdog1ta2uCAns0TfQFtfp7igKDOvJE1dNUldR1tbJd4aqMIw1k7FTU2tKDUlv/b/f2MFQ4N/@QUlmfl5xf918xIB "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Returns the `k`th term, 0-indexed
```
@¶X¤ò< Ê}iV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLZYpPI8IMp9aVY&input=NQo4)
```
@¶X¤ò< Ê}iV :Implicit input of integers U=n & V=k
@ :Function taking an integer X as argument
¶ : Test if U is equal to
X¤ : X converted to a binary string
ò< : Partitioned between characters that are less than each other
Ê : Length
} :End function
iV :Get the Vth integer that returns true
```
[Answer]
# [Julia](https://julialang.org), 52 bytes
```
>(x,i=0)=count("01",bitstring(i))==x&&@show(i)~x>i+1
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjdN7DQqdDJtDTRtk_NL80o0lAwMlXSSMkuKS4oy89I1MjU1bW0r1NQcijPyy4G8ugq7TG1DiN4ldhpmmhAmzDgA)
infinite recursive function, needs Julia 1.3 or later
]
|
[Question]
[
# Intro
[](https://i.stack.imgur.com/MaKOj.png)
Given a whole number \$< 100,\$ extend/shorten the english representation of the number to have as many characters as it's value.
[Sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/19297#19297)
# Rules
Take the number \$n\$, and get it in words from [this dictionary.](https://github.com/razetime/code-golf/raw/master/R-code/numbers) You may take this dictionary in any way you prefer. (a list, read from link, command line arg, STDIN, variable, so on.)
[Here's the file as a JSON Array.](https://gist.github.com/Lyxal/117cbe9be10abd5cb454344071bbceaa) (Courtesy of Lyxal)
Then, do the following with the string:
* If the string's length is lower than the number, repeat some of its characters in place until the length matches the number.
* The first and last characters should not be repeated, and the numbers of repetitions of the other characters should differ by at most one (so you can repeat some of them 5 times and others 6 times, for example; it doesn't matter which ones exactly).
* If the string's length is greater than the number, remove any of its characters except the first and last to make the length match the number.
**1 and 0 are exceptions, since they are too small.**
* The order of the letters in the string must be maintained.
* Example:
```
50 → f[ift]y → 3 letters must be duplicated 16 times
61 → s[ixtyon]e → 5 letters must be duplicated 10 times, 1 character must be duplicated 9 times
```
## Step by step run-through
Taking 11 as an example,
(formatted as `word → length`)
```
eleven → 6
^
elleven → 7
^
elleeven → 8
^
elleevven → 9
^
elleevveen → 10
^
ellleevveen → 11 (end)
```
## Examples
```
2 → to
3 → the or tre or tee
4 → four
5 → fiive or fivve
7 → seevven or sevveen or seeveen
10 → teeeeeeeen
Special cases:
0 → (Any null value/no output)
1 → o
```
## Winning Criteria
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in each language wins.
## ~~LoTM Bounty~~ [Claimed by Dominic Van Essen!](https://codegolf.stackexchange.com/a/212055/80214)
The first Husk answer to this question will get a +50 rep bounty from me on top of Zgarb's bounty, if it satisfies the criteria put up [here in the **Additional Efforts** part.](https://codegolf.meta.stackexchange.com/questions/19386/language-of-the-month-for-october-2020-husk)
[Answer]
# [R](https://www.r-project.org/), ~~(110 105 96)~~ ~~96~~ 95 bytes
*Hopefully answering the correct question now...*
```
function(n,a)cat(substring(b<-a[n+1],r<-sort(c(1,l<-nchar(b),rep(3:l-1,n))[1:n]*!!n),r),sep='')
```
[Try it online!](https://tio.run/##VZTdbsIgGIaP7VU4T4StJjM7mtErcWbRhk4SB4ZSXV127a58f@BR3weV9/kUCffO3sxnf97c29410XqnXL3XzT6qrj90MVj3pQ7rxX7rXpa7OqwXnQ9RNWpZn9YL1xz3QR10HcxZva1Oi2XttN4uV273/PTkxnVdd@a8mc/13fXfBxO6TaNmNxP8rJ7OvDPpEa9A8RgMcOv7AE97Ae7sDzzMxbgUjP06xhScpQ1o/cTviFdzws/Gow3R4GraV7JtOY7bS0wbMEAN5dTEedzcxSEnmSIBz4LAEyHyXEQ0HRLNSFDMMaLMiyhTp9GGnHy5LN8pgHgAigeSLb4p8UAQD8DsAcgerScNCL5YJAnM@dctFBDIAIAEMHM/kNQDSfv4Qw4SfLHI7ZClPVE@YG3RnoDbIUt7otyeiNvT2Rkk@GKR2jFzOxC3I@QzLu2YuR1I2oGkHY7rUET/8AI7EIkFsngQsgli@acrbZCzDzIbwfqQky@XSYeAbRBZhohckEiF4OEWyCKI7AH/1yEnXy6TBwF7ILIHEXkgkQcBeyA@3EnkoatqPKrKTq2bvq7e3/VvNaHrVtma7kNdTdJlO/9wc1393f8B "R – Try It Online")
Doh! Read the question, stupid!
Ok, first (several) attempts were not answering the correct question, because I didn't read the challenge properly and didn't notice that the first+last characters shouldn't be repeated. Coincidentally, though, the near-complete-rewrite came out at the same number of bytes!
**How?**
Ungolfed code:
```
size_up=
function(n,a){ # n is number, a is array of text strings
b=a[n+1] # get the text string for this number
l=nchar(b) # get the number of characters
r=sort( # r = sort the indices of characters to output:
c(1,l, # we need index 1 and the last index (l)...
rep(2:(l-1),n)) # then plenty of repeats of 2..(l-1) ...
[1:n]) # and, from this, we'll use the first n.
if(n) # only output anything if n>0 ...
cat(substring(b,r,r),sep='')
# ...in which case concatenate the indexed
} # characters of the text string b.
```
[Answer]
# [Haskell](https://www.haskell.org/), 59 bytes
```
d!n|h:t<-d!!n=take n$h:[t!!div(i*length t-i)(n-1)|i<-[1..]]
```
[Try it online!](https://tio.run/##RZMxb4MwEIV3/wojdUgqETVrlXbp2k4dow6RMMEqtSO4pqXKf0997x1k4b4z8L4DTHcYP0PfX69NlS7do@zqpqrSkxw@g0933eNeqqqJ51W870M6SueljutVqrfrS9zV@@1m8/Fx/TrE5J98k533jd/Vvo8pjH539@yPQV5ykpBkLCe/Dqc3f/qWdxlek9@vinTtLz7pPfuHzWa7LWl/Ycgup@DkJzvphhBcm78H18ZzcGP8dWM4h@RCPHbiUtQLte2xKj@hL5dJFwcJpdc7CbFFLQGsejkIQQqaBSghSSYrnEQJ85AwFRmzGeqERJ3TaJ6rMGcmc3Kdc7KSlwU@OYgmME3EOD8kTSSawGYCw9RmFeGY51Y1BHvLs4SkDpAqCDAAKQAyv7zficc8t8gHMF/RPmU75yshH8B8RctXRL5@t4nHPLeaT0A@EPkk2y/MJyAfyHwg87Efprnm2xIshvSwockYLvKyRRcfGzOygRMrk5W8LKjQCD4ydIZqI6rM6PZXmIoME7b2ZCUvC2oygokMk6GaiGoygol8@wtp@gc "Haskell – Try It Online")
Usage: `["zero","one",...]!n`.
For example, for input `11`, it will output an `'e'` followed by `"leven"` indexed at:
$$
\left\lfloor\frac{4}{10}\right\rfloor,
\left\lfloor\frac{8}{10}\right\rfloor,
\dots,
\left\lfloor\frac{40}{10}\right\rfloor
$$
which is `"lleevvveen"`. (Intuitively, the formula stretches the indices [0..4] of `"leven"` to [0..10].)
`take n$` is used to support the 0 case (otherwise the output is `"z"`), but it also lets us write `[1..]` instead of `[1..n-1]`, so the net cost is only 4 bytes rather than 7.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~28~~ ~~27~~ ~~25~~ ~~22~~ 21 bytes
*Edit: -2 bytes thanks to Zgarb, -3 more bytes thanks to Jo King, and then -1 more byte thanks again to Zgarb (those last 4 bytes took a while to work-through and understand; I've added an explanation but it isn't easy for [Husk](https://github.com/barbuz/Husk) newbies like me...)*
```
SṀ!(O↑¹:1S:ȯ*¹…2←L)!→
```
[Try it online!](https://tio.run/##yygtzv7/P/jhzgZFDf9HbRMP7bQyDLY6sV7r0M5HDcuMHrVN8NFUfNQ26f///0YG/6OVqlKL8pV0lPLzUoFkSTmIXZJRlAripeWXFoGozDIQrzizAkSmlqXmAenUzPSMEiCdlwnRCBHMgcqWlKfmgDWVZGQWlaSCxUCmwZiZaVAW0FAYC6QVygYbDmGCzIcygYbmlVQqxQIA "Husk – Try It Online")
My first [Husk](https://github.com/barbuz/Husk) answer, inspired by the 'language of the month'.
Port of the approach in [my R answer](https://codegolf.stackexchange.com/a/211979/95126).
I'm pretty happy just to figure-out how to write a working program (hooray!), so it's almost-certainly not as golfy as it could be...
**How?** (commented after Zgarb & Jo King's golfs: it's quite complicated now...):
First of all, we'll put-in all the implicit arguments (as superscripts `⁰` and `²`):
```
SṀ!(O↑²:1S:ȯ*²…2←L)!→²⁰
```
Now the commented code:
```
S # S is a 'hook' combinator to recycle argument x: Sfgx == fx(gx)
Ṁ! # f is M! = map the list-index function across a list of indexes, with the list to index given by argument x
(O↑²:1S:ȯ*²…2←L) # g is (O↑²:1S:ȯ*²…2←L) = function to generate the list of indexes from argument x (see below)
!→²⁰ # x is !→²⁰ = the text name of the number (for instance, "twenty"; see below)
# Explanation of g:
S # S 'hook' combinator again, so Sfgy here == fy(gy)
: # f is : = prefix with y
ȯ # g is given by ȯ*²…2←
# ȯ is 3-function combinator: ȯfgh == single function fgh
← # subtract 1
…2 # and construct a series from 2..this value,
*² # and repeat this series n times, with n given by argument 2 (first given program argument);
# so ȯ*²…2← is the function that repeats 2..x, n times, for argument y
L # y is the length of the argument x
# So: up to here, we have :Lx *²…2←Lx
:1 # Now prefix with 1...
↑² # then select the first n elements, with n given by argument 2 (first given program argument)...
O # and sort the result. This is the list of indexes from x.
# Explanation of x:
! ⁰ # element of argument 1 (second given), indexed by...
→² # argument 2 (first given) +1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ị©L⁸,_2œs/Ẉ⁸>Ø.¤j®x"
```
A dyadic Link accepting the number on the left and the list of number-names on the right (in Jelly index order), which yields a list of characters.
**[Try it online!](https://tio.run/##TZQxTgMxEEXvsnUECgfgBNwAISovcbRaS5slienokChpOAANDTWCbhEHCRcxnvl/bDfr/yay33jXztYNQ0zp9P28vF/9PX6ubi9@X3bnp6@nDJc/r2fL23b5OHYppfU6XXdhdN2qmw9BnpvJCfXhfpLB74V2/ihPt3djHp2/28x5HD0mojjw1/ngBp00b/w0O63JahZ9z5QXtSRTmXVxRFmfMS86zrEE61gy@0Zm9yDugYCdALAf5tp3JtsbyHYoO4klhKZob02z2ZXMDvD1lZgd2exKxa5Eex8g1zHUEtSI5atVMTK8mqFFpFXBpArmzF8p2hhqiU6N5hQox6WvTsl0ajSnQHEK0CnnIdoYaglORDoV6EQu59SciHQqmFPBnHryYk2hLdNMMDfQ7CT6Qc11aXoAli6A7EOrsYTQFNEEM3sAsQUCOgCgAeb21hY9iHa9aLGE0BRhZ6YdRDsBdgDszLSD2n@OYn9wU@hu/gE "Jelly – Try It Online")** Or see [all 100](https://tio.run/##TZRNTsMwEIXvkhVIFX8H4ARcACGEWDhtqiiW0tDW7GCFxJINB0BCSIg1gl0rDtJeJHjmvbG9id83lf2NE7tz17ZhHHe/z5uPi/3D9@Tm7O9lcbz7eYpwvn092rzNN1/raty@7x8/L8exv@2m7uD05ORwvKp856pJNay8PGe9E6r9XS9DsxRaNGt5uqXr4uia6WyIY9dgIootfx1WrtVJw6zpB6c1Wc1iUzPFRS3JVGZdHFHWZ4yLdkNIwTqWzL6R2T2IeyBgJwDshzn3Hcn2BrIdyk5CCr4o2lvTbHYlswOa/ErMjmx2pWRXor32kOvocwlqxPTVshgZXs3QItKqYFIFc8avFGz0uUSnRnMKpONSZ6dkOjWaUyA5BeiU8xBs9LkEJyKdCnQip3NqTkQ6FcypYE49eSEnX5ZpJpgbaHYS/aDiuhQ9AFMXQPah1ZCCL4pogpk9gNgCAR0A0ABzeWuTHkS7XrSQgi@KsDPTDqKdADsAdmbaQeU/R7Lfu95X1/8 "Jelly – Try It Online").
### How?
```
ị©L⁸,_2œs/Ẉ⁸>Ø.¤j®x" - Link: N, Words
ị - (N) index into (Words) -> the word
© - copy for later
L - length
⁸ - chain's left argument -> N
, - pair -> [N, length(Word)]
_2 - subtract two -> [N-2, length(Word)-2]
/ - reduce using:
œs - split (implicit range [1..N-2]) into (length(Word)-2)
approximately equal parts
Ẉ - length of each -> sizes (call this [s1, s2, ...])
¤ - nilad followed by link(s) as a nilad:
⁸ - chain's left argument -> N
Ø. - bits -> [0,1]
> - greater than? -> [N>0, N>1]
j - join -> [N>0, s1, s2, ..., N>1]
® - recall from earlier -> the word
" - zip with:
x - repeat
```
[Answer]
# [J](http://jsoftware.com/), 40 39 bytes
```
[{.[(]#~1:0 _1}2+/@}.($[:}:@}.@=#\))>@{
```
[Try it online!](https://tio.run/##VZRNT8JAFEX38ysmYoJErYDfVQyJiStXbpGwwKnUECaBClaCfx3n3fumZBZ0zp2Ue15Ly9f@o5xWg8w@PmSTvh3brs275tctvfELZ6qNN9Vs6Zwp/PfSFOXamVX5Y1Zu7RbGlZ@zyixKOVHiHLvVxs3DadWsXFYuZPkmoSywhgKucjoIRQLSBQgli6rWhZMIYR4SpiJjNkWZkChzKsW5AnNmMieXOWtdfLPBKwfRBKaJWMaLpIlEE1hNYJgKLyIcfYyiIehdjhKSOECiIMAApADI/nB/ax59jOgHsF9Qf8oi9guhH8B@Qe0XRL/8bjWPPkbpJ6AfiH6SPi/sJ6AfyH4g@/E81HH1hy1YFOlhoEkZLnLziDY@BjUywImdWhffbIhQCT4ydIpiI4pM6fBWqIoMEx7tWhffbIhJCSYyTIpiIopJCSby4S1UU8eYo6xd2EFu2/ZM3ujwOc/s89vry360zUYn49ZfL@/aSW/XP70Y7rKT41G@ywMMB633TudpuN2HEjededuzhZW/CKZ@ki6TdJWk6yTdJOk2SXdJuk9Sr5vGOM3@Hw "J – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 98 bytes
```
def f(n,a):x,*s,y=a[n];l=len(s);d=n-2;a[0]=(x+"".join(s[i]*(d//l+(i<d%l))for i in range(l))+y)[:n]
```
[Try it online!](https://tio.run/##NY/LDsIgEEX3fgUhMQGL752VLyEsajrYMTgYitr687XFurr33Hlk5tGnJtBxGGpwzAlSlTx1atWqXleGbOm1BxKtLGtN60NZmZ3Vois439wCjgWDdiXq7dYXAs/10kvpQmTIkFis6ApiTIpemhPZgZ73C8SWaWb4B2LgivFAMEl6Z0pNhMwuPGNWfGVuscsCL6DJAF6bNBnCecGc@39HeoP/zaYGY4IxtQsn9nvF5jvk4hGRkphx/EwOXw "Python 3 – Try It Online")
-8 bytes thanks to ovs
-2 bytes thanks to pxeger
(-9 bytes between the two because one of the saved bytes overlaps between the two optimizations)
-9 more bytes thanks to ovs
[Answer]
# JavaScript (ES6), ~~78~~ 73 bytes
Expects `(n)(dictionary)`. Returns an empty string for zero.
```
n=>d=>(s=d[n--],g=k=>k<n?s[~k?k/~-n*(s.length-2)+1|0||2:0]+g(k+1):'')(-1)
```
[Try it online!](https://tio.run/##VZTNUsIwFEb3PEWGja2lCi7B4oMwLBxIS2wncdqIVtFXx@b@Jaz6nQD5zm1D317Pr8OhN@@@tO6or3V1tdX2WG2zoTrubFnuF03VVtv22b4Mu7/2pX38K@19Njx02jb@VD7lxeqyvFye1st90WRtscrXd3d5Vq7y69EcVKV282/du/lCzZ3V4eI/gfyp18C1@@jhas7Ag/mCiz5rG4I2zcmHYA1tQOsdf8N/6g5/60@m9xpXw76STc1x2l5i2IABaiiHJs7T5taPMckUAXgWBJ4IkecioumQaEaCZI4JZV5EmTqMNsbk0mW5pwDiASgeSCa5U@KBIB6A0QOQPWpHGhBcskgSmOPTTRQQyACABDBzP5DUA0n79CBHCS5Z5HbI0h4oHrA6aQ/A7ZClPVBsD8Tt4eyMElyySO2YuR2I2xHiGZd2zNwOJO1A0g7HdUyiu/mAHYjEAlk8CNkEMf3TpTbI0QeZjWB9jMmly6RDwDaILENELkikQnDzFogiiOwB/9cxJpcukwcBeyCyBxF5IJEHAXsg3ryTyGO/mc2ms5rZ6aW33CirntVqGUJR5OpnptTB2cF1@qFzTWYXqs5snk3vyDzfzH6v/w "JavaScript (Node.js) – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~50~~ ~~46~~ 40 bytes
-4 bytes thanks to ovs
-6 bytes thanks to coltim
```
{x#,/(1,(+/'(-2+#y@x;0N)#2_x#1),1)#'y@x}
```
[Try it online!](https://tio.run/##VZRBbsIwEEX3PUVLFiQiCMISNj1BL1BV3eAUCxRLwYW4iLOn8cyfsbPKfwP4v4GQ89qdx7HdP4ai3pRNXa42y3K9WxXhfThsP6pi9z0UTVU3VbGcRs/xuC8Xf6Z3i8PrwnUmXvydyJ96Q9y6356u9kZ8tQNdzM10MRj7c/IxdBYHYH6Rd/i7ufBn/cn23vA0nqvZthKn4zXGAwSoBjk2SZ4O73xISbeIILswyEaMshcI2zFhR0C2x4S6L6NuHVcLKbl8rN8pgXoQqgeTzb4p9WBQD8LkQSgerYMGBZcNIcE5/bqZAgMMCCDAWfqJtJ5I26cfMmhw2VDaKWt7pHSDtVl7BGmnrO2RUnskaY/3TtDgsiHaOUs7kbQzpHtc2zlLO5G2E2k73a4hi272gjiA1IJZPYBiwpj/6XIb5uTDLEY0Dym5fAwdgNgwigwILkxQAcyeAkmEUTzo/xpScvkYHgDxYBQPEDyY4AEQD8bZMwke1cuj/RwOx6/n8q3Zbsd/ "K (oK) – Try It Online")
[Answer]
# Rust, 203 bytes
```
|i,a|if i<2{a[i].truncate(i)}else
if let[f,m@..,l]=&*a[i].clone(){let mut v:Vec<_>=(0..m.len()).cycle().take(i-2).collect();v.sort();a[i]=v.iter().map(|&j|m[j]).collect();a[i].insert(0,*f);a[i].push(*l)}
```
[Try it online](https://play.rust-lang.org/?version=stable&mode=release&edition=2018&code=fn%20main()%20%7B%0A%0A%20%20%20%20let%20a%3A%26%5B%26str%5D%3D%26%5B%22zero%22%2C%20%22one%22%2C%20%22two%22%2C%20%22three%22%2C%20%22four%22%2C%20%22five%22%2C%20%22six%22%2C%20%22seven%22%2C%20%22eight%22%2C%20%22nine%22%2C%20%22ten%22%2C%20%22eleven%22%2C%20%22twelve%22%2C%20%22thirteen%22%2C%20%22fourteen%22%2C%20%22fifteen%22%2C%20%22sixteen%22%2C%20%22seventeen%22%2C%20%22eighteen%22%2C%20%22nineteen%22%2C%20%22twenty%22%2C%20%22twentyone%22%2C%20%22twentytwo%22%2C%20%22twentythree%22%2C%20%22twentyfour%22%2C%20%22twentyfive%22%2C%20%22twentysix%22%2C%20%22twentyseven%22%2C%20%22twentyeight%22%2C%20%22twentynine%22%2C%20%22thirty%22%2C%20%22thirtyone%22%2C%20%22thirtytwo%22%2C%20%22thirtythree%22%2C%20%22thirtyfour%22%2C%20%22thirtyfive%22%2C%20%22thirtysix%22%2C%20%22thirtyseven%22%2C%20%22thirtyeight%22%2C%20%22thirtynine%22%2C%20%22forty%22%2C%20%22fortyone%22%2C%20%22fortytwo%22%2C%20%22fortythree%22%2C%20%22fortyfour%22%2C%20%22fortyfive%22%2C%20%22fortysix%22%2C%20%22fortyseven%22%2C%20%22fortyeight%22%2C%20%22fortynine%22%2C%20%22fifty%22%2C%20%22fiftyone%22%2C%20%22fiftytwo%22%2C%20%22fiftythree%22%2C%20%22fiftyfour%22%2C%20%22fiftyfive%22%2C%20%22fiftysix%22%2C%20%22fiftyseven%22%2C%20%22fiftyeight%22%2C%20%22fiftynine%22%2C%20%22sixty%22%2C%20%22sixtyone%22%2C%20%22sixtytwo%22%2C%20%22sixtythree%22%2C%20%22sixtyfour%22%2C%20%22sixtyfive%22%2C%20%22sixtysix%22%2C%20%22sixtyseven%22%2C%20%22sixtyeight%22%2C%20%22sixtynine%22%2C%20%22seventy%22%2C%20%22seventyone%22%2C%20%22seventytwo%22%2C%20%22seventythree%22%2C%20%22seventyfour%22%2C%20%22seventyfive%22%2C%20%22seventysix%22%2C%20%22seventyseven%22%2C%20%22seventyeight%22%2C%20%22seventynine%22%2C%20%22eighty%22%2C%20%22eightyone%22%2C%20%22eightytwo%22%2C%20%22eightythree%22%2C%20%22eightyfour%22%2C%20%22eightyfive%22%2C%20%22eightysix%22%2C%20%22eightyseven%22%2C%20%22eightyeight%22%2C%20%22eightynine%22%2C%20%22ninety%22%2C%20%22ninetyone%22%2C%20%22ninetytwo%22%2C%20%22ninetythree%22%2C%20%22ninetyfour%22%2C%20%22ninetyfive%22%2C%20%22ninetysix%22%2C%20%22ninetyseven%22%2C%20%22ninetyeight%22%2C%20%22ninetynine%22%5D%3B%0A%20%20%20%20let%20a%3A%26mut%20%5BVec%3Cchar%3E%5D%3D%26mut%20a.into_iter().map(%7Cs%7Cs.chars().collect()).collect%3A%3A%3CVec%3C_%3E%3E()%3B%0A%20%20%20%20%0A%0A%20%20%20%20let%20f%3Afn(usize%2C%26mut%20%5BVec%3Cchar%3E%5D)%3D%0A%7Ci%2Ca%7Cif%20i%3C2%7Ba%5Bi%5D.truncate(i)%7Delse%20if%20let%5Bf%2Cm%40..%2Cl%5D%3D%26*a%5Bi%5D.clone()%7Blet%20mut%20v%3AVec%3C_%3E%3D(0..m.len()).cycle().take(i-2).collect()%3Bv.sort()%3Ba%5Bi%5D%3Dv.iter().map(%7C%26j%7Cm%5Bj%5D).collect()%3Ba%5Bi%5D.insert(0%2C*f)%3Ba%5Bi%5D.push(*l)%7D%0A%20%20%20%20%3B%0A%20%20%20%20%0A%20%20%20%20f(0%2Ca)%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20a%5B0%5D)%3B%0A%20%20%20%20f(2%2Ca)%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20a%5B2%5D)%3B%0A%20%20%20%20f(7%2Ca)%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20a%5B7%5D)%3B%0A%20%20%20%20f(12%2Ca)%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20a%5B12%5D)%3B%0A%20%20%20%20f(16%2Ca)%3B%0A%20%20%20%20println!(%22%7B%3A%3F%7D%22%2C%20a%5B16%5D)%3B%0A%7D)
A closure of type `fn(usize,&mut [Vec<char>])`. The result is written in `a[i]`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~39~~ ~~37~~ 36 [bytes](https://github.com/abrudz/SBCS)
-2 bytes thanks to [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)!
-1 byte thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)!
Assumes `⎕IO←0`.
```
⊃∘⌷{⍵↑⍺/⍨1,⍨1,(⍵-2)(⌊÷+|⍨>∘⍳⊢)≢2↓⍺}⊣
```
[Try it online!](https://tio.run/##ZZA9CsJAEIV7T7FdFBX/eisbK88gujELIStxTfythKDBiCKCtTb2IoKtN5mLxJlNYqHNzDdv5z12tzu0y/1p15aDGHandgeCfTU2sUK4gvUZts85RA8IDhC9KhDdaiVd8iiW64U8bMP3s7hArUnb0R3CSwE2lzoER3QsIbzGLdFTDBOZMeOuNJghHY5V@cTKcjlNphy71IRH00hMqHKPO9i5GFgKuyMSYyLa6anyua1NyhKu4lqjtAyFmRKGZkTWlHV4gpSfIoY6avoFfeMcfpB@R5WZjB71FWq/QuNvI1uJPw "APL (Dyalog Unicode) – Try It Online")
**Explanation**
This function takes the dictionary as the right argument and the integer as the left argument.
`⊃∘⌷` is a function that gets the word at the left index in the right dictionary.
`⊣` is the left identity function.
The inner function `{ ... }` is then called with the word as a left argument `⍺` and the integer as a right argument `⍵`.
`≢2↓⍺` is the length of the word without the first two characters (`a`).
`⍵-2` is just the integer input minus `2` (`b`).
With these two arguments the function `⌊÷+|⍨>∘⍳⊢` is called:
`⍳⊢` creates an index vector `0 1 ... a-1`.
`|⍨` calculates `b mod a`.
`>` compares this to the index vector, which results in a boolean vector with `b mod a` `1`'s and `a - b mod a` `0`'s.
`⌊÷` is the floor of `b÷a`.
`+` adds this to the boolean vector.
`1,` prepends a `1`, `1,⍨` appends a `1`.
`⍺/v` selects as many items from the word x, as indicated in `v`. Example: `1 3 2 2 2 1/'eleven'≡'ellleevveen'`. This is commuted (`⍨`) here to avoid brackets.
`⍵↑` then takes the required number of characters. This is required for `0` and `1`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
NθF⊕θSηFθ§η∧ι⊖÷×⊕⁻ιθ⁻²Lη∨⁻²θ¹
```
[Try it online!](https://tio.run/##VZPLbsIwEEX3/oosg0QXbZeskNgg9SW1P0BhIJbALsY80p9PPfeOg8oiPjM490xe626V1nG1H4Zl@Dnnt/PhW1J7nMzcNqamXYZ1koOELJvSnDTY9JmTD7u2q5uOk@ajdHI7z8uwkVvbTZt52LR@2izkfv4y5IW/@I20X/4gp3/Zrz6cT3pCkUwbVk/T5kXCLnfFpN331I5/HEv9OMFvNgyPz@5XUnQxiMvX6HKXRMps5@S2/iLu5G/uJBcJTvyuyy543ajlHt18lX3ZljufspRazyT4LdYSwFW3gxCkoFmAEhJybwsnUcI8JExFxmyGOiFR5zSqcxXmzGROrnP2tsSxwSsH0QSmiejrRdJEoglsJjBM5fEWEY6xlqoh2F2uEpI6QKogwACkAMj8cn97HmMtkQ9gvqI9ym3NV0I@gPmKlq@IfH1uPY@xlppPQD4Q@SR7X5hPQD6Q@UDm433o6xrvLVgM6WFBkzFc5PEVHX0szMgCTnR6W@LYUKERfGToDNVGVJnR/aswFRkmvNq9LXFsqMkIJjJMhmoiqskIJvL9K6RpeLjs/wA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as the number and then the dictionary. Removing the `F⊕θSη` results in a program that resizes the second line to the length given on the first line. Annoyingly, `2` was the hardest number to process, since both the first and last character are edge cases. Explanation:
```
Nθ
```
Input `n`.
```
F⊕θSη
```
Read in the dictionary up until and including the entry for `n`.
```
Fθ
```
Loop over `n` characters. (`⭆θ` also works.)
```
§η
```
Output the character of the dictionary word given by the computed index.
```
∧ι
```
For the first character of the output the computed index is always `0`.
```
⊖÷×⊕⁻ιθ⁻²Lη∨⁻²θ¹
```
Otherwise scale the distance to the end of the string from `0..n-2` to `0..l-2` (where `l` is the length of the dictionary word), rounded up. Note that this results in `0/0` for `n=2`, so the denominator is coerced to `1` in this case. Example for `n=5, five`:
```
i=0 o=0
i=1 o=3-ceil((4-1)*(4-2)/(5-2))=3-ceil(3*2/3)=3-2=1
i=2 o=3-ceil((4-2)*(4-2)/(5-2))=3-ceil(2*2/3)=3-2=1
i=3 o=3-ceil((4-3)*(4-2)/(5-2))=3-ceil(1*2/3)=3-1=2
i=4 o=3-ceil((4-4)*(4-2)/(5-2))=3-ceil(0*2/3)=3-0=3
```
Therefore the output indices are `0, 1, 1, 2, 3` resulting in `fiive`. (In actual fact the calculations are done using negative indices, so the actual indices are `0, -3, -3, -2, -1`, which means that they are actually rounded down, rather then up.)
[Answer]
# [Perl 5](https://www.perl.org/), 77 bytes
```
sub{@w=@{$d[$n=pop]};$h=$n<4?2:(@w-2)/($n-2);join'',@w[map.99+$h*$_,0..$n-1]}
```
[Try it online!](https://tio.run/##ZZXRctowEEXf/RU71BPshpiEJtMB6oYf6FvfMkyGFhm7dSxiK1CXIb9Od/fKiYfyYB1ppXt3LVlsTV3enV4aQ99N42azb7Y286B5@UFZedjabfrajKMkTi75MQ5vwsm4PtKHrKgbR6tqTeWK4We@qoOnlhbr9Gm1fWi2ZeHG4@XoeR8Ff01tyVaG3N6Sy2tjKLMvNWXFzlBT/KHG7ExFptjkjqpCJkq3lNHA7U3J01xe1M7wsKwEFJm2LIBWpiupkIBoCYhI5VpCg0yENB@QZgXW3DxKhkC28TLIFoycwchc8mx9Y98G2CnwBCdlOAGLrkhx6ghOyurkNdQps2KkT9t1pSCAf8udCYg9AiWxAKiDIkpRhD6/3xZP23WlDAD0Bf1WZr4GJdVXgL4gClBUfdm3Fk/bdSV/gOorqj5I8lfSQ6Og@orIXxH6eh7arrXvQ1JFh/BBB06e9WyC346o9@sWe0d01FNHWt/YtwEpy5P4BWC18yhuQDHz9P5VeCuwOAV6tFuccHUCiZMnrQysTh7FCSgn2pM6gd@/QjjF80C@6zBLT3wlHBb7dHEI1w9hlfLVsDzOwzwNqy@395NZtNhfTeJxFFbczH/ZohoOR4v9A98HyXR6GeYfw8fRdZJw/GZ5PM3lKJJIF9WWIg5Mp/EhIP7J4Ma69CLMIolyDjJsf0faki5J0@v7SKaReabhMEZohtBNL2TPYpNezJ0HP/WDtTmL3vai8lLPwnf9cLHbnS//3IvzO9/x1XSed78mvrrw@29WvzxTlka1etOIIswsTbVxuU6O6eKCb3TPvJK52yTdUV6wPMbxaOD4b6CoNtiYq6uvuhkUDZK@WjKIB@rGm3MM1nwEH/26@ekf "Perl 5 – Try It Online")
[Answer]
# Scala, 93 bytes
```
i=>a=>{val f+:m:+l=a(i);(f+:Seq.fill(i)(m.indices).flatten.take(i-2).sorted.map(m):+l)take i}
```
[Try it online!](https://tio.run/##ZZRPb9MwGIfv/RRRT7YGEewAUlEqTZw4c0QTMq2zGly7JKZbmPbZi/3@s8sOU37P28y/x23ieWe8ucQfP@0udXedfUo27Ofu7nR6Xp2N78zw1f5W6792ius33ToGWy7pESgdJgs8xj8TXN0ZeHZPcLFnG0qw7uGQSgiOFqC55zvSo/X4v@ngpmRxWtaV7EaOeXmJZQEGqKFcmjjnxUNaapJdFOC9IPCOEHlfRLQ7JNojQbOPjLJfRNl12dpSU2zH8p0CiAegeCC55psSDwTxAKwegOwxRtKAEJshSWCuv26jgEAGACSAmfuBpB5I2vMPuUiIzZDbIUt7ofqAjU17AW6HLO2Fanshbi/PziIhNkNqx8ztQNyOUJ9xacfM7UDSDiTt8LguTYxXH7ADkVggiwchmyC2L11rg1x9kNkI5ktNsR2TDgHbILIMEbkgkQrB1SlQRRDZA97XpabYjsmDgD0Q2YOIPJDIg4A9EK/OJPLQ/dGc1Pc@xXzq6dUKjsBx8yWkYZsn38rf54OZ7u@RIQ8XN2zNsH2Gm282x82NH4xy@pPKlG/rR@d9ZnXsXdi7nZ11P3qT8iHYJ/PLKvf2VvdzfkfsHgSOOi@hy0ede7mcJheSD2pU77QyWq/q4P3/g4@v7rh9NfmAk5fLPw "Scala – Try It Online")
Defines a function of type `Int=>Seq[Seq[Char]]=>Seq[Char]`.
## Explanation:
```
i => a => { // define a curried lambda function with two arguments
val f+:m:+l = a(i) // destructure the string to extract the first and last letter
( // return...
f +: // the first letter prepended to
Seq.fill(i)(m.indices) // the numbers from 0 to i-2, all repeated i times
// for "seven", this is 7 instances of [0,1,2]
.flatten // flatten this list
.take(i-2) // take the first i-2 numbers from the list
.sorted // sort them
.map(m) // and use them as indices for the middle part of the string
:+l // append l
)
take i // to handle 0 and 1, take i letters from the result
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
è⍍₂и¾šηε{®ª}0šδè¹ù
```
Takes the list of words as additional second input.
Outputs as a list of characters.
[Try it online](https://tio.run/##TZQxTgMxEEV7jpGaAhougyhA8hJL0VramASDKOAmdCsKKhCkodhAG3EGLrJ45v@x3az/m8h@4107YX155d0878fvx2mcxr@np9/P6evn@fBxeL@fXqeXh5MMb/tx2u1383x2enS@uHNDWBwvQu/yM24lx@XghLpwM8jgN0JrfytPt3F9Hp2/XsY89h4TUVzx17h1K50Ul36ITmuymkXfMeVFLclUZl0cUdZnzIv2MZVgHUtm38jsHsQ9ELATAPbDXPvOZHsD2Q5lJ6mE0BTtrWk2u5LZAb6@ErMjm12p2JVo7wLkOoZaghqxfLUqRoZXM7SItCqYVMGc@SslG0Mt0anRnALluHTVKZlOjeYUKE4BOuU8JBtDLcGJSKcCncjlnJoTkU4FcyqYU09eqim0ZZoJ5gaanUQ/qLkuTQ/A0gWQfWg1lRCaIppgZg8gtkBABwA0wNze2qIH0a4XLZUQmiLszLSDaCfADoCdmXZQ@89B@8U/) or [verify all \$[0,99]\$ test cases](https://tio.run/##TZQxTsMwFIavUmXuwA26MTD0AogBJIdYqmIpDS0BMdCBAzCzsEUMTCBgYUhhQqrgCr1IsN//P9tL/H@vsr/nxK5bnp5ZM/5tDuezYrK/u58Us/m47b9uh37o95vN7/vw@f24e9u9Xg/Pw9PNgYeXbT/ffow/D0fT8bi4Mo0rpoWrjX@265DbqjGBSnfRhMGuAi3tZXialan9aOx51fqxtpiI4oK/tmuzkEltZZvWSC2sptGWTH5RTWEqsyyOGNZn9IvWbReDdhwy@0Zm9yDugYCdALAf5tS3J90bSHcYdtLF4LKivjXJahdSO8CmV6J2ZLULRbsQ7aWDXEaXSlAjxq@WxMjwSoYWkVYBlQqo03@lTkeXSnRKVGeAeFzK5AyZTonqDBCdAegM56HT0aUSnIh0CtCJHM@pOhHpFFCngDrl5HUpubxMM0HdQLWT6Adl1yXrARi7ALIPqXYxuKyIJpjZA4gtENABAA0w57c26kG0y0XrYnBZEXZm2kG0E2AHwM5MOyj/56D95B8).
**Explanation:**
```
è # Index the (implicit) input-integer into the (implicit) string-list
ā # Push a list in the range [1,string-length] (without popping)
¨¨ # Remove the last two values to make the range [1,length-2]
₂и # Repeat this list 26 times: [1,2,3] → [1,2,3,1,2,3,1,2,3,...]
¾š # Prepend a 0 to this list
η # Take all prefixes
ε # Map each prefix-list to:
{ # Sort the list
®ª # And append a -1
}0š # After the map: prepend a 0 to the list of lists
δ # Map over each list:
è # Index it in the string that's still on the stack
# (modulair 0-based, so the -1 indexes into the last character)
¹ù # Keep the list of characters of a length equal to the first input
# (after which the result is output implicitly as result)
```
If outputting a lazy infinite result is allowed, the `₂и` could be `Þ` instead for -1 byte: [try it online](https://tio.run/##TZSxTsMwFEV3PqMzAyz8DGIAyaGWqlhKTYtBDPwIUreIgQmEujAksPaXgt@799le4nteZZ/nxG7Y3t55tyzz@Ps6jdM4v00/f4fT9@nrefqY3l8uMnzO43Scj8tydXl2vXpyQ1idr0Lv8jPuJcf14IS68DDI4HdCW/8oT7dzfR6dv1/HPPYeE1Hc8Ne4dxudFNd@iE5rsppF3zHlRS3JVGZdHFHWZ8yL9jGVYB1LZt/I7B7EPRCwEwD2w1z7zmR7A9kOZSephNAU7a1pNruS2QG@vhKzI5tdqdiVaO8C5DqGWoIasXy1KkaGVzO0iLQqmFTBnPkrJRtDLdGp0ZwC5bh01SmZTo3mFChOATrlPCQbQy3BiUinAp3I5ZyaE5FOBXMqmFNPXqoptGWaCeYGmp1EP6i5Lk0PwNIFkH1oNZUQmiKaYGYPILZAQAcANMDc3tqiB9GuFy2VEJoi7My0g2gnwA6AnZl2UPvPQfvNPw).
[Answer]
# [Factor](https://factorcode.org/), 201 bytes
```
: s ( n d -- s ) dupd 2dup nth length 2 - pick 1 - 1 max dup [ / ] dip swap
<repetition> dup first [ + ] accumulate [ 1 + >integer ] map nip [ nth ] dip
dupd swap nths [ 1 head ] dip append swap head ;
```
[Try it online!](https://tio.run/##TZQ9b9swEIZ3/YqDpxat0jpbnCJDlyJAmw5GhyLIQEsnmYhMqRQVRyn6293jfchexOelJD5HiWTjqtTH06/t/cO3DTxjDNhB11euG@Hg0p4vV32sMQpGF1ocIbgDjoOrCEf8M2HINERMaR6iDwlui/uHDWz9G5bTULoyTIcdxqLY/v7x9ef3DdS@SsVfWL1h7Few6gPSNR0zp33EnJp@irnxLzmN/jVf8QUDtejbfaI2eHmROgvq7fR2OmLHb6W9jwm5Lw9n6BslGtUov6rMowtmAWPBo4Y0rwys5sxaubDWL0lnoUHmIkFmpHwunJLNThLPsdC5kN5I/cz25ZjNz8n8Evz5q5hf2PycFj8n8zc966UVOaO4BZdfdzYLi5hZvIKq5WBWDouUftWsv8ykGVXKaNIclkXTnKWZVcpo0hwWaQ4mzati1tWhUkaRCqqUg0qFl@VqUkGVcjAph0XKC3BelqKJJahag8klml6TFiDpYttcFCFxKUOiFcLds20DLUNYqlDWIiRpDRqkBAlSgfLl9l38kkzPO262rad6YdErq16S6jWIXoLolVUv6fIMUT38K/LBRGdaKtuu37nutIER3kGAGsqS8D3U01DDNV0h0PnYYWipuYYSBl89w5pgTUfla34OHuETPNFZN8B4dEPxJeKAySffhzu@3/g4JnrqAz3lqmo6TJ1LSB1r6rqjcxRbOnifaDyy@TxedvKIBdeRh819I7@zR1erzw0DBr3P3benmxt4/Pxx90SP8iTbZZI0L3FcFaf/ "Factor – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
gV
_uUÊ-2 Ä}hV[0UÊÉ] Í®gU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z1YKX3VVyi0yIMR9aFZbMFXKyV0gza5nVQ&input=LVAKWyJ6ZXJvIiwgIm9uZSIsICJ0d28iLCAidGhyZWUiLCAiZm91ciIsICJmaXZlIiwgInNpeCIsICJzZXZlbiIsICJlaWdodCIsICJuaW5lIiwgInRlbiIsICJlbGV2ZW4iLCAidHdlbHZlIiwgInRoaXJ0ZWVuIiwgImZvdXJ0ZWVuIiwgImZpZnRlZW4iLCAic2l4dGVlbiIsICJzZXZlbnRlZW4iLCAiZWlnaHRlZW4iLCAibmluZXRlZW4iLCAidHdlbnR5IiwgInR3ZW50eW9uZSIsICJ0d2VudHl0d28iLCAidHdlbnR5dGhyZWUiLCAidHdlbnR5Zm91ciIsICJ0d2VudHlmaXZlIiwgInR3ZW50eXNpeCIsICJ0d2VudHlzZXZlbiIsICJ0d2VudHllaWdodCIsICJ0d2VudHluaW5lIiwgInRoaXJ0eSIsICJ0aGlydHlvbmUiLCAidGhpcnR5dHdvIiwgInRoaXJ0eXRocmVlIiwgInRoaXJ0eWZvdXIiLCAidGhpcnR5Zml2ZSIsICJ0aGlydHlzaXgiLCAidGhpcnR5c2V2ZW4iLCAidGhpcnR5ZWlnaHQiLCAidGhpcnR5bmluZSIsICJmb3J0eSIsICJmb3J0eW9uZSIsICJmb3J0eXR3byIsICJmb3J0eXRocmVlIiwgImZvcnR5Zm91ciIsICJmb3J0eWZpdmUiLCAiZm9ydHlzaXgiLCAiZm9ydHlzZXZlbiIsICJmb3J0eWVpZ2h0IiwgImZvcnR5bmluZSIsICJmaWZ0eSIsICJmaWZ0eW9uZSIsICJmaWZ0eXR3byIsICJmaWZ0eXRocmVlIiwgImZpZnR5Zm91ciIsICJmaWZ0eWZpdmUiLCAiZmlmdHlzaXgiLCAiZmlmdHlzZXZlbiIsICJmaWZ0eWVpZ2h0IiwgImZpZnR5bmluZSIsICJzaXh0eSIsICJzaXh0eW9uZSIsICJzaXh0eXR3byIsICJzaXh0eXRocmVlIiwgInNpeHR5Zm91ciIsICJzaXh0eWZpdmUiLCAic2l4dHlzaXgiLCAic2l4dHlzZXZlbiIsICJzaXh0eWVpZ2h0IiwgInNpeHR5bmluZSIsICJzZXZlbnR5IiwgInNldmVudHlvbmUiLCAic2V2ZW50eXR3byIsICJzZXZlbnR5dGhyZWUiLCAic2V2ZW50eWZvdXIiLCAic2V2ZW50eWZpdmUiLCAic2V2ZW50eXNpeCIsICJzZXZlbnR5c2V2ZW4iLCAic2V2ZW50eWVpZ2h0IiwgInNldmVudHluaW5lIiwgImVpZ2h0eSIsICJlaWdodHlvbmUiLCAiZWlnaHR5dHdvIiwgImVpZ2h0eXRocmVlIiwgImVpZ2h0eWZvdXIiLCAiZWlnaHR5Zml2ZSIsICJlaWdodHlzaXgiLCAiZWlnaHR5c2V2ZW4iLCAiZWlnaHR5ZWlnaHQiLCAiZWlnaHR5bmluZSIsICJuaW5ldHkiLCAibmluZXR5b25lIiwgIm5pbmV0eXR3byIsICJuaW5ldHl0aHJlZSIsICJuaW5ldHlmb3VyIiwgIm5pbmV0eWZpdmUiLCAibmluZXR5c2l4IiwgIm5pbmV0eXNldmVuIiwgIm5pbmV0eWVpZ2h0IiwgIm5pbmV0eW5pbmUiXQoxMQ)
```
Input :
U = dictionary
V = number
gV - get element from dictionary
hV[0UÊÉ] - build a list of V indexes,
starting with [0 , last idx]
and calling the following function on last element to generate next items.
_uUÊ-2 Ä} - returns number modulo( literal length -2) + 1
Example : 11 - eleven
[0,5] -> 5%4+1
[0,5,2] -> 2%4+1
[0,5,2,3]
[0,5,2,3,4,1,..]
ͮgU - sort and maps to literal
-P flag to join result
```
]
|
[Question]
[
Here's a reasonably trivial sequence which is not in the [Online Encyclopedia of Integer Sequences](https://oeis.org/).
Start with an empty sequence then define each term as the number of characters required to write out, in English, all of the digits of the sequence so far without spaces.\*
For reference the number of characters of all of the (base ten) digits in English are:
```
zero one two three four five six seven eight nine
4 3 3 5 4 4 3 5 5 4
```
(Which is the start of both [A52360](https://oeis.org/A052360) and [A5589](https://oeis.org/A005589).)
This makes the first entry \$a(0) = 0\$ since there are zero digits present in the empty sequence.
This makes the second entry \$a(1) = 4\$ as it takes four characters to write "zero", the only digit present so far.
This makes the third entry \$a(2) = 8\$ as it takes four more characters to write the "four" for a total of eight to write "zerofour".
This makes the fourth entry \$a(3) = 13\$ as it takes five more characters to write "eight" for a total of thirteen to write "zerofoureight".
This makes the fifth entry \$a(4) = 21\$ as it takes eight more characters to write "onethree" for a total of twenty-one to write "zerofoureightonethree".
...and so on. Here are the first 100 entries:
```
0, 4, 8, 13, 21, 27, 35, 44, 52, 59, 67, 75, 84, 93, 102, 112, 121, 130, 142, 152, 162, 171, 182, 193, 205, 216, 225, 235, 247, 259, 270, 282, 293, 305, 318, 331, 344, 357, 371, 384, 398, 412, 422, 432, 444, 456, 467, 479, 492, 503, 516, 526, 536, 548, 561, 571, 583, 597, 610, 620, 630, 642, 652, 662, 671, 682, 693, 705, 718, 731, 744, 757, 771, 784, 798, 812, 823, 836, 849, 862, 873, 888, 903, 916, 926, 936, 948, 961, 971, 983, 997, 1010, 1024, 1038, 1055, 1070, 1086, 1101, 1114, 1127
```
\* We could define it for other languages and/or other bases or with spaces of course
### The challenge
Given \$n\$ output, in as few bytes of code as possible, any of:
* The first \$n\$ terms of the sequence (should work for non-negative integers)
* The value of \$a(n)\$ (should work for non-negative integers)
* The \$n\$th term of the sequence (should work for positive integers - i.e. value of \$a(n-1)\$)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins for each language, and the shortest answer in bytes wins. Don't let golfing languages stop you from entering in your favourite language be it a practical one or an esoteric one!
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes
```
{({[+] @_.join.uninames>>.comb X-6}...*)[$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WqM6WjtWwSFeLys/M0@vNC8zLzE3tdjOTi85PzdJIULXrFZPT09LM1olPrb2f3FipUKahqGBpjUXhBkHYv8HAA "Perl 6 – Try It Online")
No need for fancy moduloing when you can get the name of the digit directly! Anonymous code block that returns the nth value of the sequence, or you can pass in a range to get a list of values
### Explanation:
```
{( )[$_]} # Index input into:
{ }...* # An infinite sequence
# Where each element is
[+] # The sum of
@_.join # All previous elements joined together
.uninames # The unicode names for each character
# These are names in the form "DIGIT ONE"
>>.comb # Split each to lists of characters
X-6 # Subtract 6 from each
```
[Answer]
# JavaScript (ES6), ~~69~~ ~~68~~ ~~61~~ 58 bytes
Returns \$a(n)\$.
```
f=(n,s=0)=>n?f(n-1,[...s+''].map(d=>s+=(d+10)%23%3+3)|s):s
```
[Try it online!](https://tio.run/##FcxBDoIwEEDRq3QBYSaFppWdOngQY0JDqdHglDDGDXL2iru/ePlP//EyLI/53XAKY86RgGshi9TxJQI3rr4aY0RX1c28/AyBOtEEQTuL5aEtW93iV/AoOaYFWJGyJ8XqrJz9h9aohsSSptFM6Q69h2LlDXdXrPsftx7zDw "JavaScript (Node.js) – Try It Online")
### How?
A digit \$d\$ is converted to a number \$n\$ of letters with:
$$n=(((d \times 100 + 10) \bmod 23) \bmod 3)+3$$
```
d | *100 | +10 | MOD 23 | MOD 3 | +3 | word
---+------+-----+--------+-------+----+-------
0 | 0 | 10 | 10 | 1 | 4 | zero
1 | 100 | 110 | 18 | 0 | 3 | one
2 | 200 | 210 | 3 | 0 | 3 | two
3 | 300 | 310 | 11 | 2 | 5 | three
4 | 400 | 410 | 19 | 1 | 4 | four
5 | 500 | 510 | 4 | 1 | 4 | five
6 | 600 | 610 | 12 | 0 | 3 | six
7 | 700 | 710 | 20 | 2 | 5 | seven
8 | 800 | 810 | 5 | 2 | 5 | eight
9 | 900 | 910 | 13 | 1 | 4 | nine
```
Because the number is split into digit characters, we can process \$d\times 100+10\$ by just adding \$10\$ (as a string concatenation).
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
┴♥7[╘⌂←─üTJ‼√
```
[Run and debug it](https://staxlang.xyz/#p=c103375bd47f1bc481544a13fb&i=0%0A1%0A2%0A100&a=1&m=2)
The key insight here is that digit `d` requires `((4 - 2 * d) // 3) % 3 + 3` letters to spell. (That's python integer division, and python-style non-negative modulus)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 21 bytes
```
Lai+:$+4335443554@^Pi
```
Takes input \$n\$ as a command-line argument and outputs the first \$n\$ terms. [Try it online!](https://tio.run/##K8gs@P/fJzFT20pF28TY2NTExNjU1MQhLiDz////JgA "Pip – Try It Online")
### Explanation
```
Lai+:$+4335443554@^Pi
a is 1st cmdline arg; i is 0 (implicit)
La Loop (a) times:
Pi Print i
^ Split it into a list of characters (i.e. digits)
4335443554@ Use each digit to index into this number, giving the length of the
name of the digit (0 -> 4, 1 -> 3, etc.)
$+ Sum the results
i+: Increment i by that amount
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes
```
Nest[#+Tr@StringLength@IntegerName@IntegerDigits@#&,0,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8vtbgkWlk7pMghuAQoku6TmpdekuHgmVeSmp5a5JeYmwpju2SmZ5YUOyir6RjoKMeq/dd3UAhKzEtPjTbQMTSIjf0PAA "Wolfram Language (Mathematica) – Try It Online")
`Tr@StringLength@IntegerName@IntegerDigits@#&` lists the digits of `#`, converts each of them to an English name, counts the length, and sums the results. Lots of things thread over lists, it's very exciting. Then we just iteratively apply the definition.
TIO complains that it doesn't have an Internet connection, but I'm not sure why, because it figures out the right answer anyway. Maybe it's checking for updates to the names of integers?
Outputs the value of \$a(n)\$, but we could change it to give the entire list \$a(0), a(1), \dots, a(n)\$ by changing `Nest` to `NestList`.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 82 bytes
```
import StdEnv,Text
$a=iter a(\n=n+sum[3+indexOf{c}" 9810324765"rem 3\\c<-:""<+n])0
```
[Try it online!](https://tio.run/##JcxNC4IwGADge79iDA@FKZZ9GXqrQxAU1E09vMwZg72vMmcY0V9vCR2fyyO0BHLYVL2WDEGRU9g2xrKbrY70nN/lYCceZMpKw2BaUEZ@12Me@4oqOVzqt/hwluwWUbxcbTdrbiSyuChEGuw5T30qZ5G7WRjHbPxb5rE8CsMkKd1X1BoenQtOZ3d4EaASf1w12Lox@AM "Clean – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~29~~ 28 bytes
```
{{⍵++/3+3|⌊3÷⍨4-2×⍎¨⍕⍵}⍣⍵⊢0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6urH/Vu1dbWN9Y2rnnU02V8ePuj3hUmukaHpz/q7Tu04lHvVKB87aPexUDqUdcig9r/aUB9QDmIEV3Nh9YbP2qbCOQFBzkDyRAPz@D/aSCNmw0NDAA "APL (Dyalog Unicode) – Try It Online")
Dfn. Prints \$f(input)\$
Thanks to the guys @The APL Orchard for helping with this one:
@ngn for 2 bytes; @H.PWiz for ~~3~~ 4 bytes.
Now using @recursive's formula.
### How:
```
{{⍵++/3+3|⌊3÷⍨4-2×⍎¨⍕⍵}⍣⍵⊢0} ⍝ Main fn
{ }⍣⍵⊢0 ⍝ Starting with 0, repeat (⍣) the inner fn input times
3+3|⌊3÷⍨4-2×⍎¨⍕⍵ ⍝ @recursive's formula
⍵++/ ⍝ Sum with the input.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes
```
ÎFD•Qb₁ñ•sSèOO
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cJ@by6OGRYFJj5oaD28EsoqDD6/w9///3wQA "05AB1E – Try It Online")
**Explanation**
```
Î # initialize stack with 0 and input
F # input times do:
D # duplicate the current number
sSè # and use one copy to index into
•Qb₁ñ• # 433544355
OO # sum digits and sum the stack
```
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
```
n=0
exec"for c in`n`:n+=(4-2*int(c))/3%3+3\n"*input()
print n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WgCu1IjVZKS2/SCFZITMvIS/BKk/bVsNE10grM69EI1lTU99Y1VjbOCZPCShQUFqioclVUASUUsj7/9/SEgA "Python 2 – Try It Online")
Uses [recursive's digit count mapping](https://codegolf.stackexchange.com/a/174531/20260).
---
**[Python 2](https://docs.python.org/2/), 63 bytes**
```
f=lambda n:n and f(n-1)+sum((4-2*int(c))/3%3+3for c in`f(n-1)`)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qTyExL0UhTSNP11BTu7g0V0PDRNdIKzOvRCNZU1PfWNVY2zgtv0ghWSEzLwGiKkHzf0ERSEGahqmm5n8A "Python 2 – Try It Online")
A recursive function version. It takes exponential time to run because it has two recursive calls to `f(n-1)`.
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
f=lambda n,k=0:n and f(n-1,k+sum(632179420>>3*int(d)&7for d in`k`))or k
```
[Try it online!](https://tio.run/##FclLCoAgEADQq8wqnD5gGoWBnkVDJLGm6LPo9Fa7B29/rnkjkXPQi1sn74DqpPlI4MhDYNS0darOe2W9FO2gOsGNkWWki3kshrAd4CGSTRbxc8r78V9gSiHmFw "Python 2 – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 17 bytes
```
0\{_▒♀*♂+L%3%3+Σ+
```
[Try it online!](https://tio.run/##y00syUjPz0n7/98gpjr@0bRJj2Y2aD2a2aTto2qsaqx9brE2UIbLkMuIy5jLhMuUy4zLnMuCyxIA "MathGolf – Try It Online")
This uses [Arnauld's method](https://codegolf.stackexchange.com/a/174530/76162). Outputs the nth element of the sequence.. If the empty string is okay for `a(0)`, then we could remove the `0\` at the beginning.
### Explanation:
```
0\ Setup 0 as the counter
{ Loop input times
_▒ Duplicate counter and split to list of digits
♀* Multiply each element by 100
♂+ Add 10
L% Modulo by 23
3% Modulo by 3
3+ Add 3
Σ Sum list
+ And add to counter
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
u+Gs@L+L3jC\3jGTQ0
```
Try it online [here](https://pyth.herokuapp.com/?code=u%2BGs%40L%2BL3jC%5C%E1%AF%BB3jGTQ0&input=6&debug=0).
```
u+Gs@L+L3jC\3jGTQ0 Implicit: Q=eval(input()), T=10
u Q0 Starting at 0, repeat the following Q times, with current value as G:
C\ Get character code 7163
j 3 Convert the above to base 3, yields [1, 0, 0, 2, 1, 1, 0, 2, 2]
+L3 Add 3 to each to generate digit length dictionary
jGT Get digits of G (convert to base 10)
@L Lookup each value in the above in the dictionary, modular indexing
s Take the sum
+G Add G to the above
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 54 bytes
```
->n{s=0;n.times{s+=s.digits.sum{|d|4+392[d]-70[d]}};s}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vutjWwDpPryQzN7W4uljbtlgvJTM9s6RYr7g0t7ompcZE29jSKDolVtfcAEjW1loX1/4vUNAw0NMzNNDUy00s0FBL0@QqUEiLtrSM/Q8A "Ruby – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 95 bytes
```
n->{int l=0;while(n-->0)l+=(""+l).chars().map(x->"4335443554".charAt(x-48)-48).sum();return l;}
```
[Try it online!](https://tio.run/##NU7BaoUwELz7FYunpGKwqFBIFUpPPfTUY@khzdP31sZEks1r4eG322jpYZjdndmdndRVldPpa8N5cZ5gSr2IhEaM0WpCZ8WdzLRRIcCrQgu3DGCJnwY1BFKU6OrwBHPS2Bt5tOf3D1D@HPhhBXix9OxsiPPgYYQONlv2N7QEpqvk9wXNwGxZ9hU3RcfyvDBc6IvygXExq4X9lH3e1HXbNHXbNvmhPVEaNw98h0iXGZd@oOgtGLlu8ogdnWd7CqbISiZ6hPtqL4ri/7NkEkrrYSGG/G9rzXas2y8 "Java (JDK) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 13 bytes
```
0?(»Þ([ǒ»Ȯİ∑Ṡ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=0%3F%28%C2%BB%C3%9E%28%5B%C7%92%C2%BB%C8%AE%C4%B0%E2%88%91%E1%B9%A0&inputs=3&header=&footer=)
A port of the 05AB1E answer
## Explained
```
0?(»Þ([ǒ»Ȯİ∑Ṡ
0? # Push 0 followed by the input number
( # Input number of times:
»Þ([ǒ» # Push the number 433544355
Ȯİ # And get the indexes corresponding to the numbers in the second last item on the stack
∑Ṡ # Sum that list and then the stack
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 82 bytes
```
f=(a,b=1,s=4)=>a?b<a?f(a,++b,s+=[...s+''].reduce((q,w)=>+'4335443554'[w]+q,0)):s:0
```
[Try it online!](https://tio.run/##ZcpBDsIgEADAux8Bskha2V4asQ9pegAKRtMU21X7fORquE7mab@W/P54vc9rmkPO0XArnWklGRTmZgd3tUMsBuAkgRmVUgSMTWoP88cHzjd5lAgMte4QddchG48JNtkI0VPfZJ9WSktQS7rzyIue/qWt5FKJrgSFyD8)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ṃ“vẋç’ḃ5¤S+Ɗ¡
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//4bmD4oCcduG6i8On4oCZ4biDNcKkUyvGisKh//85OQ "Jelly – Try It Online")
0-indexed.
Full program; takes input from STDIN.
[Answer]
# [Red](http://www.red-lang.org), 99 95 bytes
```
func[n][d:"4335443554"s: 0 repeat i n[print s foreach c form s[s: s - 48 + do d/(-47 + do c)]]]
```
[Try it online!](https://tio.run/##JcqxCsIwEAbg3af46aRIMZILSh7D9bih5C7YwbQk7fNHpds3fNW0v0xZTjn2vJfERVjjQN4HIh8CDS3Codpq04YZhdc6lw0Neak2pTfSXx80/sWGEfTEFbpAb@eRHofTRUR6xt25/gU "Red – Try It Online")
Just a straightforward solution.
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
(+1#.|(3+3|23|10+100*]),.&.":)@]^:[&0
```
[Try it online!](https://tio.run/##NYyxCoAgGAZ3n@KjQDPr5zc3oeg9opZIqqXB1Z7dgohbjhvuzCH2BIYH58rYklLljEudS5aNZa5n3ZCkwutxXvwkOWtREFToSaHB7RGiENu6Xwiw/Jlq8aL@LAcc9L5EfgA "J – Try It Online")
Uses Arnauld's method
## Explanation:
The argument is `n`
```
^: - apply the verb on the left hand site
[ - n times
&0 - to a starting value 0
( )@] - calculate for the current value of the argument
,.&.": - convert to string and then each char to digit
(3+3|23|10+100*]) - map each digit to its word length
| - a filler for the fork
1#. - sum the lengths
+ - add them to the current value
```
[Answer]
**Edited after 1st comment.**
Prints all terms
# Scala, 76 bytes
```
def^(n:Int)=(1 to n).scanLeft(0)((y,_)=>y+(y+"").map(x=>(x*9+1)%13%3+3).sum)
```
[Try it online!](https://tio.run/##DctBCsIwEADAu69YCoVdI6UhJ4UUPAq@oRLTFJR2G8wKCeLbo3Of5N3i6nZ/Bi/gIWQJPCU4xwifOoV5RD5dWMiiBtmAqUve8TXMgj0hlsON7FAUFtU01K0uYrYD5v1RaWq1aY0y//JeqcbXg2VhHFH3RLtvrT8 "Scala – Try It Online")
Prints nth term
# Scala, 72 bytes
```
def^(n:Int)=Stream.iterate(0)(x=>x+(x+"").map(x=>(x*9+1)%13%3+3).sum)(n)
```
# Scala, 69 bytes
```
def^(n:Int)=(0/:(1 to n))((y,_)=>y+(y+"").map(x=>(x*9+1)%13%3+3).sum)
```
# Scala, 67 bytes
```
def s(b:Int):Stream[Int]=b#::s(b+(b+"").map(x=>(x*9+1)%13%3+3).sum)
```
# Scala, 67 bytes
```
val s:Stream[Int]=0#::s.map(x=>x+(x+"").map(x=>(x*9+1)%13%3+3).sum)
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcopCvkFpRkpqXUqzgWFCgUP2/LDFHodgquKQoNTE32jOvJNbWQNnKqlgvN7FAo8LWrkJbo0JbSUkTxteo0LLUNtRUNTRWNdY21tQrLs3V/F9QlJlXkpOnUaxhaKCpyVX7/z8A "Scala – Try It Online")
]
|
[Question]
[
## Introduction:
I think everyone knows what a Lava Lamp is, but in case they do not:
[](https://i.stack.imgur.com/dILgU.gif)
[(Image source)](http://api.ning.com/files/qrbliHRnvdw1Rjlr3hjMBmZV8cArQzQHkjqIHMFYV8KWdSCn2lBsAOS6i8s6TltTPjR1JKi9OOFVeYuHqDer7HzWmrvpdteJ/1614584823.gif?xgip=108%3A0%3A324%3A324%3B%3B&width=48&height=48&crop=1%3A1)
They're basically glass tubes that contain wax in a translucent liquid. The bottom part is heated when the lamp is turned on, causing a change in density and thus the wax floats to the top. When it cools down, it falls down again, causing the effect we see above.
It usually takes about 45-60 minutes for the base of the lamp to rise in temperature high enough to change the solid wax to liquid wax (if the lamp is located in an area at room temperature).
[More information on Wikipedia, which is also used as source for some of the text above.](https://en.wikipedia.org/wiki/Lava_lamp)
## Challenge:
Given a positive integer `n` indicating the amount of minutes that have passed since we've turned the Lava Lamp on, output a random state of the Lava Lamp based on integers on five levels.
For this challenge we'll say the Lava Lamp contains 1000 units of wax in total, and we have five levels where the wax can be at.
1) If `n` is below 45, the Lava Lamp is still heating up, so the output will be four empty lines with `1000` at the bottom:
```
1000
```
2) If `n` is in the range `[45, 60)` the Lava Lamp has increased in temperature enough for wax to move around, but no very high yet. The wax can reach up to and including the third level.
3) If `n` is `60` or higher, the wax can be at any of the five levels.
So given the positive integer `n` as input, we'll output a [random](https://codegolf.meta.stackexchange.com/a/1325/52210) state with the three rules above in mind.
**Here are some example outputs:**
Possible outputs for any `n` that is `>= 45`:
```
523
106
371
```
```
913
87
```
Possible outputs for any `n` that is `>= 60`:
```
73
113
312
5
497
```
```
284
55
637
24
```
Constant output for `n` that is `<= 44` (and possible output for any `n`):
```
1000
```
## Challenge rules:
* There can be empty lines, even though the level above it is not empty.
* Just `0` isn't allowed on any line. Should be empty instead.
* Output is somewhat flexible. You are allowed to output a list/array of strings/objects instead of a new-line delimited result as above. The reason I say strings/objects is due to the rule above. An empty line should be `""`, `null`, `[]`, etc., but cannot be `0` or a negative integer (nor can it be `false`) (I.e. `["", "", 913, "", 87]` for `n >= 45`). You are also allowed to reverse the output (I.e. `1000\n\n\n\n` instead of `\n\n\n\n1000` or `[87, null, 913, null, null]` instead of `[null, null, 913, null, 87]`).
* The numbers should all be integers. The can be decimals with `0` as decimal value, but none of the numbers should have any decimal digits, and the integers should always sum to exactly `1000`.
* All possible [random](https://codegolf.meta.stackexchange.com/a/1325/52210) outputs based on `n` should have a non-zero chance of occurring.
* A trailing new-line (so there are six lines of output) is allowed.
## 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, adding an explanation for your answer is highly recommended.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~117~~ ~~113~~ ~~108~~ ~~107~~ ~~106~~ 105 bytes
```
from random import*
def f(n):a=['']*5;exec"i=randint(0,(n>44)+(n>59)<<1);a[i]=(a[i]or 0)+1;"*1000;print a
```
[Try it online!](https://tio.run/##RYyxDoMgFEV3v4K4yNMOiEq1aH/EOJAqkUEwhKH9evpkcTn35eS@e/7C7iyPUXt3EK/simGO0/lQZuumiaYWXmqai2IpO7l9t09upqtnbKDsQe27baHC6AYYxxqkms0y0YvOEwZVLfOyZozJ0@MLUVFTBpmmDTIpvHHiYpfY3x43kSL1Bb@94LwZ@vYJ8Q8 "Python 2 – Try It Online")
Returns a reversed list (bottom first)
---
Version inspired by the stackoverflow [answer](https://stackoverflow.com/a/8064754/1682559) in the comments (edgecases are more likely):
# [Python 2](https://docs.python.org/2/), 129 bytes
```
from random import*
def f(n):a=sorted([1000]*5+sample(range(1001)*5,(n>44)+(n>59)<<1));print[y-x or''for x,y in zip([0]+a,a)[:5]]
```
[Try it online!](https://tio.run/##RYxBDoIwEEX3nKI7ZwCTUigCohchLJpAtYm0TWEBXh5HNmzen7zM/35b3s6KfdfBTSwoO1CYybuwxNEwaqbBYqMeM4lxgC7jnPexTGY1@c8IVHiNQDLDWKZgn0WBCYWssW0zxLsPxi7ddl2ZC5eLdoGt6caMZV/joeN9olKFXSP7ftfAMdKQE48W3bT2pzxYnZ7mieXxX4rTl0LkdVXccP8B "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 78 bytes
Returns a reversed array where empty levels are filled with a space.
```
t=>(a=[...' '],g=k=>k?g(k-1,a[Math.random()*(t>59?5:t<45||3)|0]++):a)(1e3)
```
[Try it online!](https://tio.run/##ZcxNDoIwEEDhvadwx4xAA6E1Qmw5gScgLCb8KtgaaFz17lWXpm/5Ld6D3rR32/1lU236wY/SW6mAZMMYi46/ojaZ5CLVUk@wpHlCzY3szDbSvXkCnsAqUdaislcunCvQZW0cY0UI@VCg74zezTqw1UwwQoZ4@BfOQxIBiTKgc/i6fMl/AA "JavaScript (Node.js) – Try It Online")
### Commented
```
t => ( // t = input
a = [...' '], // a[] = output array, initially filled with 5 spaces
g = k => // g = recursive function taking an iteration counter k
k ? // if k is not equal to zero:
g( // do a recursive call:
k - 1, // decrement k
a[ // update a[]:
Math.random() * ( // pick a random slot:
t > 59 ? 5 : // among all 5 slots if t > 59
t < 45 // force the 1st slot if t < 45
|| 3 // among the 3 first slots otherwise
) | 0 // round the above result to an integer
]++ // increment the wax amount on this slot
) // end of recursive call
: // else:
a // stop recursion and return a[]
)(1e3) // initial call to g() with k = 1000
```
[Answer]
# [R](https://www.r-project.org/), ~~85~~ 84 bytes
```
function(n)write(ifelse(t<-table(cut(runif(1e3,2*(n<60)+3*(n<45),5),0:5)),t,""),1,1)
```
-1 byte thanks to @Giuseppe
[Try it online!](https://tio.run/##JYpBCsMwDATvfUZOUquA3TQ5FH8mCRIIglpcmT7ftRtYhh12c5U0Vim2u74MDL9ZnUGFjw@Dp9HX7WDYi0MupgKRJ7pfwdIS8Db18piRWsJzRiSnYUCKFLG@s5pDwIt0nNa@TTtPX/5zY/0B "R – Try It Online")
Explanation (ungolfed):
```
function(n){
# Generate 1000 random uniform numbers in [5,5] (if n<45),
# in [2,5] (if 45<=n<60) and in [0,5] (if n>=60).
x = runif(1e3,2*(n<60)+3*(n<45),5)
# Code each by the number of the interval it falls in (0,1],(1,2]...(4,5]
cx = cut(x,0:5)
# Tabulate the intervals. Because cut() returns a factor,
# zero counts are included
t = table(cx)
# Vector-wise replace zero elements with "" and cat out, 1 per line.
t1 = ifelse(t,t,"")
write(t1,1,1)
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~131~~, ~~116~~, ~~90~~, ~~89~~, 87 bytes
```
L(l,a,v,A){for(A=5,v=1e3;A--;v-=a)printf("%d\n"+!a*2,a=l>59|A<3&l>44?rand()%-~v:!A*v);}
```
[Try it online!](https://tio.run/##VY7NUoMwFIX3PMVtHZwEEodacGxDcNi3T6AuYvhpahocoHFR8dGN0OqiuzPfPd@dI2ktpbtRRupjUULa9YVq7naZd4W0ertmvTqUI3EbpIkgluT4VDUtynlCLF@US5ZTyizlAn@0yvQVmvvFi5mHMxHcE8F1lqy@8nR5q7M4fmqFKRD26bddz/LAYja40YGDUAZNQbS1JHInWgiCMVsMJw@gO2tSN/IdYcxGMi2Y@opHDMJQpZPILm2A6bLnom8Ump48q9ezBPC/cKvMsS/BL9bjUgL7v/MGXdLgDc4tEhfHLk5csnIPkXuMfmSlRd05@vkL "C (gcc) – Try It Online")
**Update**: Fixed a bug in the original. Fused in the helper function, reducing an additional 15 bytes.
**Update 2**: -25 bytes thanks to ErikF.
**Update 3**: -1 byte thanks to ceilingcat.
## Degolf
```
L(l,a,v,A){
for(A=5,v=1e3;A--;v-=a)
printf("%d\n"+!a*2, // No clue how this works anymore, but it'll advance the pointer
// to the string constant when a number shouldn't be printed.
a=l>59|A<3&l>44?rand()%-~v // Random integer to print in [0, v]
:!A*v); // If bottom layer, return remaining volume
}
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~21~~ 20 bytes
```
5º*♪{k[K∞╟(]m<Σ∞wΦ}σ
```
[Try it online!](https://tio.run/##y00syUjPz0n7/9/00C6tRzNXVWdHez/qmPdo6nyN2Fybc4uB7PJzy2rPN///b8BlYsJlYsplasllZsBlaGAAAA "MathGolf – Try It Online")
This is my first answer in my new language. I based my solution on Emigna's 05AB1E solution, but used some neat features of MathGolf to make it a tiny bit shorter.
## Explanation
```
5º* push 5, [0], multiply (yielding [0,0,0,0,0]
♪ push 1000
{ start block
k push input as integer
K∞ push 22 and double it, yielding 44
╟( push 60 and decrease, yielding 59
α wrap last two elements in array, yielding [44,59]
m< map is less than, giving [0,0], [1,0] or [1,1]
Σ sum array, giving 0, 1 or 2
∞ double, giving 0, 2 or 4
w push random integer in range
Φ increase array element
} execute for loop (loops 1000 times)
σ convert to string and remove leading zeroes (implicit map)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ ~~26~~ 25 bytes
Saved a byte thanks to *Adnan*.
Saved another byte thanks to *Kevin Cruijssen*.
```
5Å0₄FD„,;ÇI‹O·ÝΩ©è>®ǝ]ε0Û
```
[Try it online!](https://tio.run/##ATYAyf9vc2FiaWX//zXDhTDigoRGROKAniw7w4dJ4oC5T8K3w53OqcKpw6g@wq7HnV3OtTDDm///NTk "05AB1E – Try It Online")
**Explanation**
```
5Å0 # initialize with a list of 5 zeroes
₄F # 1000 times do:
D # duplicate the list
„,;ÇI‹ # check if the input is larger than 44 and/or 59
O· # sum and double, yielding (0,2 or 4)
ÝΩ # pick a random number between and 0 and the number above
©è # get the count in that level
> # increment it
®ǝ # insert it at the same position
] # end loop
ε0Û # remove leading zeroes on each level
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~87~~ 86 bytes
```
f=(n,w=1e3,s=5,r=n<45|n<60&s<4|s<2?w:Math.random()*w|0)=>s?`${r||""}
`+f(n,w-r,s-1):""
```
[Try it online!](https://tio.run/##hc7fCsIgHIbh812GRGjp2EoHLW1X0D1Mttkfloa/kQfZtRsdFsFOPx4@3qt@aOj85T4x6/ohJaOwpUGVw5aCEtQrK7mIVlbFEiSPIDdNqI96Oude297dMFmFWBB1gKZdPH2MCL2ydm0@L8xTYCWpEUr7rHMW3DjkozthgwtCvifyKzifJ2KWiN0sqf60pDc "JavaScript (Node.js) – Try It Online")
The 83-byte solution (`(n/15-2|0)*s<4`) is reserved first because I need to check for larger `n`.
UPDATE: Yeah, `(n/15-2|0)*s<4` didn't work because for larger `n` because `n` large enough makes the sum fail to reach 1000.
[Answer]
# PHP, 92 bytes
```
$i=5;for($n=1e3;$i--;$n-=$x)echo($x=rand($i?0:$n,$i<($argn<60?$argn<45?:3:5)?$n:0))?:"","
";
```
Run as pipe with `-R` or [try it online](http://sandbox.onlinephpfunctions.com/code/218896eb2ea7e4780ca690544349f6ead123293c).
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 215 bytes
```
import StdEnv,Math.Random,Text
? ::!Int->Int
?_=code{ccall time "I:I"
}
$n#l=take(max(2*min(n/15-2)2)0+1)(genRandReal(?0))
#l=map toInt[1E3*e/sum l\\e<-l]
|sum l==1000=map(\v|v>0=v<+"\n"="\n")(l++repeat 0)%(0,4)= $n
```
[Try it online!](https://tio.run/##JY/BS8MwGMXv@StinZCsrUurXsqyXtyhoCCbNyvykWazmHwpXVYmzn/d2Orl8X7w3oOnjAYM1jVHo6mFFkNrO9d7uvXNGofkEfz79QawcTZ51idPSloUFxX6dDUKKd@kco3@UgqMob61mkZVUUXkm8zw0kgPH5pZOLF8bltkuMju0pznXMQZZ3uN0/JGg2Gl4JyMBQsd9W6cfsnWN3O9OBwtNXWtl6l5Jec/kjITQkxJVg/nYSXksIyjGiM5CWcmjnvdafBU8Csmklsu6QzD1sN4a7R0qocftTOwP4S0egj3nwi2Vf/wZMDvXG9/AQ "Clean – Try It Online")
So I've finally found a shorter way to get a random seed than importing `System._Unsafe`, `System.Time` and using `toInt(accUnsafe time)`...
And boy is it truly in the spirit of codegolf - embedding a call to C, ignoring the world state type normally used to ensure the evaluation order of such things.
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), ~~121~~ ~~117~~ ~~113~~ 111 bytes
```
m->{for(int w=1000,j,i=5;i-->0;w-=j=i>0?j*=Math.random():w,System.out.println(j<1?"":j))j=m>59|m>44&i<3?w+1:0;}
```
[Try it online!](https://tio.run/##bVA9T8MwEN3zK04ZUEIbyxWtBE2cDIiBgalsiMGkSXsmtiP70oBKf3twq4qJJ52edF/v3Sl5kJnafk51J72H18YTHKMIoB8@OqzBk6RAB4tb0BJNsiGHZvf2DtLtfAq0d3b08PRVNz2hNWEYAlRYywbCjrWDqc8F9miNH3TjimdDza5xJbQgYNJZeWytS9AQjGLBOZ@rOYpVjllW8nzMhBJY8krdihdJe@ak2VqdpOtxvvn21GhmB2J9MEWdSVSxqOJ4rdJUCV2uHn50uVzeYHFXjbPFmuenKY8uBoMkXDQxmOB5oALuLzwTsEqvZwD8oxFaIIbsD3GaX5tbJuvzHxK8pk7ROU7TLw "Java (JDK 10) – Try It Online")
It's biased towards putting more wax near the top, but it's theoretically possible for any legal arrangement of wax to appear.
edit: 4 bytes were saved by [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
# In Human-readable Java:
```
(int minutes /* golfed variable m */) -> {
int waxRemaining = 1000; // golfed variable w
// golfed version goes from index 4 to 0 in a bit of a roundabout way
// starting at 5 but decrementing right away
for (int level = 4 /* golfed variable i */; level <= 0; level--) {
// golfed variable j
// the golfed version initializes this to (waxRemaining + 1)
// in order to juice out some extra bytes during the Math.random() call
int waxAtLevel = 0;
// the golfed version does all of these ifs as ternary operations
// and avoids using 2-character operators wherever possible
// so e.g. "a == 0" becomes "a<1" and "a && b" becomes "a&b"
// since here we are certain things can't be negative,
// and took a good look at the Java operator precedence cheat-sheet
// to make sure "&" and "|" would work properly to give a truthy value
if (level == 0) {
// if we are at the bottom level, just put the rest of the wax there
waxAtLevel = waxRemaining;
} else if (minutes >= 60 || (minutes >= 45 && level < 3)) {
// otherwise if we are at a legal level put a random portion of the remaining wax there
// note: the random portion can be between 0 and waxRemaining inclusive
waxAtLevel = (int) (Math.random() * (waxRemaining + 1));
}
if (waxAtLevel > 0) {
// only print the amount of way at this level if its greater than 0
System.out.print(waxAtLevel);
}
System.out.println();
waxRemaining -= waxAtLevel;
}
}
```
[Answer]
# [Powershell](https://docs.microsoft.com/en-us/powershell/), 188 162 bytes
```
param($m);$t=0;$a=,0*5;$s=if($m-lt45){4}elseif($m-lt60){2}else{0};$s..4|%{$t+=$a[$_]=if($_-eq4){1e3-$t}elseif($t-ne1e3){Random(1000-$t)}}$a|%{if($_){$_}else{''}}
```
[Try it online!](https://tio.run/##PYzLCsIwEEX3fsdIO2rKVNO6KPkJtyIl4IhC@rANuBjz7TFUdHvuPWccXjzNd3YuxtFOtsuhwwa8oQas2dGmamA2j1vCynldoejAbuYfqQllvxChkK5Fod9rAb81YM/QXha1VfzUKCUfFPi/7lXPCaGcbH8durwkorRjCCuwKbKYKNB@81kWQoyxPn4A)
-2 bytes by @Kevin Cruijssen
-4 bytes by removing optional Get- verb
-20 bytes by shortning loop and removing spaces
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~192~~ 190 bytes
```
var n,a:word;z:array[0..4]of word;begin read(n);if n>44then a:=a+3;if n>59then a:=a+2;Randomize;for n:=0to 999do inc(z[random(a)]);for n:=0to 4do if z[n]>0then writeln(z[n])else writeln end.
```
[Try it online!](https://tio.run/##TcxBDoIwEEDRq8yyjUqIlkXbwCHcEhYjbbUJTkkhEnv5Khij25efP@LU43BwY5/zAyPQHtUSotFJYYz4bMuiEF1wsOHFXj1BtGgYce0dUCPEfLMEqGrcnT5UyR8d9RnJhLtPVrvw/qu6nANIKU0ATz1LbdwChrzj/4lYAweppa4pt@ES/WwHYitxO0z2K2DJFDmLqnoB "Pascal (FPC) – Try It Online")
Using [packing into bins method by TFeld](https://codegolf.stackexchange.com/a/171985/60517). Prints bottom row first with a trailing newline.
It seems that FPC doesn't have problems with `random(0)`, so I have some unusual adding there.
---
My original submission, golfed down to 209 bytes:
```
var n,i,a,r:int32;begin read(n);if n>44then a:=a-2;if n>59then a:=a-2;r:=1000;Randomize;for i:=-3to-0do begin if i>a then begin n:=random(r+1);if n>0then write(n);r:=r-n;end;writeln;end;if r>0then write(r)end.
```
[Try it online!](https://tio.run/##VY5LDsIwDAWvkmURDUp/CxKlh@AGpknBUnEqE4HE5UtIWMDOGr959gr3CRY5r9O2PYAF1VhDzRopdq05@wuSYA@uop3BWdDY9/HqSYC2INuChuMvYm0bpZQ5Ablww5c3c2CB2souBqlcEKU1qTiCyGohpC1nqeJ98z2n8v7JGP3nhVTOkownZzJbypyi/BflXcKHbeuH4Q0 "Pascal (FPC) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
>“,;‘SḤ‘µȷŻṗS⁼¥ƇȷX;0ẋ5¤ḣ5Yḟ0
```
A full program printing the result (upside down, as has been allowed).
**[Try it online!](https://tio.run/##AUEAvv9qZWxsef//PuKAnCw74oCYU@G4pOKAmMK1N8W74bmXU@KBvMKlxoc3WDsw4bqLNcKk4bij4bmaWeG4nzD///81OQ "Jelly – Try It Online")** - this is altered to use `7` rather than `ȷ` (1000) because the implementation is golf-tastically slow! (...for \$n>59\$ a list of \$10^{15}\$ 5-tuples is built and then filtered, from which to choose)
### How?
```
>“,;‘SḤ‘µȷŻṗS⁼¥ƇȷX;0ẋ5¤ḣ5Yḟ0 - Main Link: integer, n
“,;‘ - list of code-page indices = [44,59]
> - greater than? (vectorises)
S - sum (i.e. 0, 1 or 2)
Ḥ - double (i.e 0, 2 or 4)
‘ - increment (i.e. 1, 3 or 5)
µ - start a new monadic link, call that x (i.e. f(x))
ȷ - literal 1000
Ż - zero-range = [0,1,2,...,1000]
ṗ - Cartesian power (all tuples of length x using those numbers)
Ƈ - filter keep if:
¥ - last two links as a dyad:
S - sum
⁼ ȷ - equals 1000? (i.e. only valid tuples)
X - random choice (get one of these tuples)
¤ - nilad followed by link(s) as a nilad:
0 - zero
ẋ5 - repeat five times = [0,0,0,0,0]
; - concatenate (e.g. [354,388,258,0,0,0,0,0])
ḣ5 - head to index 5 (e.g. [354,388,258,0,0])
Y - join with newlines
ḟ0 - filter out zeros
- implicit print
```
[Answer]
# [Twig](https://twig.symfony.com/), 126 bytes
This was an actually fun challenge!
This code creates a macro that has to be imported.
```
{%macro a(s,z=1000)%}{%for _ in 4..1%}{%set t=s>59or(s>44and _<3)?random(z):''%}{%set z=z-t%}{{t}}
{%endfor%}{{z}}{%endmacro%}
```
To import it, just do this:
```
{%- import 'macro.twig' as a -%}
{{- a.a(50) -}}
```
This should do the trick.
You can try it on <https://twigfiddle.com/t4dfgy>
**Notice**: Due to the page removing whitespaces, I was forced to add an `-` at the end of the line, to prove that it is outputting the correct number of lines.
On a regular installation, you would just see the newlines without issues.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 62 bytes
```
{($!=1e3)||@,|((+$!-($!-=$!.rand+|0)||@)xx($_/15+|0)*2-4)[^4]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pDRdHWMNVYs6bGQadGQ0NbRVEXKKRrq6KoV5SYl6JdYwCS0qyo0FCJ1zc0BfG1jHRNNKPjTGJr/6flFykY6Bga6JgAkamOqYGOmYGOuYFCNZeCQnFipYJKvIKtnYIe0C6uWq7/AA "Perl 6 – Try It Online")
An anonymous code block that takes a string and returns a list of integers, with `Nil` or an empty list (`[]`) in place of `0`s.
### Explanation:
```
{($!=1e3)||@,|((+$!-($!-=$!.rand+|0)||@)xx($_/15+|0)*2-4)[^4]}
{ } # Anonymous code block
($!=1e3) # Initialise $! to 1000
+$!-($!-=$!.rand+|0) # Pick a random value from 0 to $!
||@ # Or an empty array if it is zero
, ( )xx # Repeat this
($_/15+|0)*2-4 # The given value mapped to 0,2,4
|( )[^4] # Get the first four values
($! )||@ # Where the first value is the leftover number in $! or an empty array
```
[Answer]
# [PHP](https://php.net/), ~~113~~ ~~108~~ ~~99~~ ~~97~~ 93 bytes
```
<?php $i=$argv[1];while($a++<1e3){${r.rand(1,$i<60?$i<45?:3:5)}++;}echo"$r5
$r4
$r3
$r2
$r1";
```
[Try it online!](https://tio.run/##K8go@P/fxr4go0BBJdNWJbEovSzaMNa6PCMzJ1VDJVFb28Yw1VizWqW6SK8oMS9Fw1BHJdPGzMAeSJqY2lsZW5lq1mprW9emJmfkK6kUmXKpFJkAsTEQGwGxoZL1////TQ0MAA)
-11 bytes thanks to @titus
-9 bytes because everything is a string
[Answer]
# [J](http://jsoftware.com/), ~~56~~ ~~55~~ ~~54~~ ~~48~~ ~~43~~ 40 bytes
```
5{.1e3(2<@-/\[,0,~[:\:~?@$~)2*1#.>&44 59
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Tav1DFONNYxsHHT1Y6J1DHTqoq1irOrsHVTqNI20DJX17NRMTBRMLf9rcnEVpRaWZhalKqjnleamFmUmq3MVJeal5OdmVqWqq3NxpSZn5CukKRjAGCYmcJYpjGUGlzU0MOD6DwA "J – Try It Online")
*-3 bytes thanks to FrownyFrog*
---
Another conceptually nice method that's a bit longer but guarantees perfectly uniform distribution over all possibilities, per [the method here](https://math.stackexchange.com/a/1276225/20688):
### [J](http://jsoftware.com/), 53 bytes
```
5$!.a:[:<@(+/);._1 0:,(1e3#1)({~#?#)@,0$~2*1#.>&44 59
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/TVUU9RKtoq1sHDS09TWt9eINFQysdDQMU42VDTU1quuU7ZU1HXQMVOqMtAyV9ezUTEwUTC3/a3JxFaUWlmYWpSqo55XmphZlJqtzFSXmpeTnZlalqqtzcaUmZ@QrpCkYwBgmppgsM7ispSXXfwA "J – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~115~~ ~~105~~ 98 bytes
-17 bytes thanks to mazzy
```
$a=,0*5
45,60-ge"$args"|%{$i+=2}
$i..4|%{$t+=$a[$_]=random(1001-$t)}
$a[4]+=1e3-$t
$a|%{"$_"*!!$_}
```
[Try it online!](https://tio.run/##Lcq7CoMwGEDhPU@h4W9tvRHbqCBk6tK5SwcRDRgvELVEoYP12dP0Mp6P85ieQs2dkFJDw1YNnPnEjRGN/YQErcDAVTvj126F3mOnDUEfhvSTi8eA51AWTPGxnoZDREgUwHI0D89p4bFInE2bMjuGEru2DeWmN@Rcul7KzEF7aCxKEcLVeOdqyPBPkq/cRG1dp@WPaarf "PowerShell – Try It Online")
A golf of [Edwin's lovely answer](https://codegolf.stackexchange.com/a/172142/78849). If you like this, upvote him.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~37~~ 36 bytes
```
F²F²⊞υ∧‹³⁺ι÷Iθ¹⁵‽⊕⁻φ↨υ¹⊞υ⁻φΣυEυ⎇ιIιω
```
[Try it online!](https://tio.run/##TY3LCsIwEEX3fsUsJxCh9bEQVz42BQtF/YHQjDTQTjWPil8fm0rB2dzFnHtP3Shb96qN8dFbwJWAOavgGgwSDqzxQs7hWkLVBodGQsH@bAajCU/KeXwJCflWiDGuinXfYcG1pY7Yk8bS8NjKsyyTcFSO0mguptsvZss/dAsdht/XGvZYqmdC7mRZ2U/yT1Yz6t4Ji3Gzi8uh/QI "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte by converting the empty list from base 1 instead of trying to sum it. Explanation:
```
F²F²
```
Loop twice, twice. Alternatively I could have integer divided the loop index by 2 for the same byte count.
```
‹³⁺ι÷Iθ¹⁵
```
If the outer index plus a fifteenth of the temperature is greater than three...
```
⊞υ∧...‽⊕⁻φΣ∨υω
```
... then push a random integer up to and including 1000 - the sum so far. Unfortunately Charcoal can't calculate the sum of an empty list so I have to convert from base 1 instead.
```
⊞υ⁻φΣυ
```
Push the leftover amount to the list. (The sum is safe here because the list is no longer empty.)
```
Eυ⎇ιIιω
```
Convert the list to string, but use the empty string instead of zero.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~62~~ 55 bytes
```
->n{w=1000;[4,4,3,3].map{|r|r*15>n||w-=q=rand(w);q}<<w}
```
[Try it online!](https://tio.run/##Nco7CoAgAADQvVM0VmgofkBKLyIORrglJYREdnYjtOktL5zLlZ3MUPk7SowQmjQFFBBAzLjZ/U4hhQEz5VOKUB4yWL92sZ@OZ57jk/fWaWSaD1KltMqK7FcUeX0cF4Uw@QU "Ruby – Try It Online")
Tests are limited to 0-99 degrees, because lava lamps could be [dangerous](https://www.youtube.com/watch?v=_rjkvQo_FDQ) at higher temperatures:
]
|
[Question]
[
**Challenge**
Given a sequence of numbers, create a function which returns the sequence steps.
* Assume a sequence will be `N >= 3`
* Sequence will repeat it steps at least once
* Sequence will only contain natural numbers
* Your function or program should return the shortest possible sequence of steps
**Example:**
Input: `[1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17]`
Output: `[1, 1, 2]`
**Explanation:** The initial sequence goes from `1 => 2 (1 step), 2 => 3 (1 step), 3 => 5 (2 steps)`. Then it repeats. The output then is `[1 step, 1 step, 2 steps] => [1, 1, 2]`
**Another example:**
Input: `[2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20]`
Output: `[3, 1, 1, 1]`
```
[2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20]
\ /\ /\ /\ /
3 1 1 1 Then it repeats...
```
**Test Cases**
`Input: [1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28] => Output: [3,4,1,1]`
`Input: [6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41] => Output: [5,2]`
`Input: [2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47] => Output: [4,4,3,4]`
`Input: [5, 6, 7] => Output: [1]`
---
**Clarifications**
* The input length - 1 is divisible by the output length
* Assume sequence will always going to be increasing
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes
```
IsJEƇḢḢ
```
[Try it online!](https://tio.run/##XY@xDcIwEEV7prgBrsidHccMgBCsYLmkQemoaGmyBzUD0COxR1jEfDuOZJB8zf/vf9@dT@N4TelwOe7e0/y846XX9Lk99imFIEzKZJh6Jsc0MG2ZpMPAEehiMTBliLyhoA3pK6UNCVmyjhbtSgKELexabP4wxBWFCk19ibjme5@LMP1CmLwt@gySVtaV3G@1Sg34GoBv4Vv4drmjHhHjFw "Jelly – Try It Online")
### How it works
```
IsJEƇḢḢ Main link. Argument: A (array)
I Increment; compute D, the array of A's forward differences.
J Indices; yield [1, ..., len(A)].
s Split D into chunks of length k, for each k in [1, ..., len(A)].
EƇ Comb equal; keep only partitions of identical chunks.
Ḣ Head; extract the first matching parititon.
Ḣ Head; extract the first chunk.
```
[Answer]
# JavaScript (ES6), 58 bytes
Outputs a comma-separated string (with a leading comma).
```
a=>(a.map(p=x=>-(p-(p=x)))+'').match(/N((,\d+)*?)\1*$/)[1]
```
[Try it online!](https://tio.run/##ZZBNDoIwFIT3nqILE/r0Ib62IC7QG3gBZNHgf1SIGuPtcVQ0UReTNDPTr5Pu/NWfy9O2voTHarFsVlnjs4n2g4OvdZ3dskmo6/BxIqJ@EBCCS7nR0Uxrni/61JvSXHrdiHIpmrI6nqv9crCv1nqlc2HlWKWsxqxkCFloBMESeMZACQTPpAWRiiKVW3YsLEXnh4aiSAsBwABo4tdlC5DFUxZQJ29QzOYPgmLyPcZIy0lbDnKH3CF3ozfLYRSG/fHiJ@9Twx/cAQ "JavaScript (Node.js) – Try It Online")
Or **[56 bytes](https://tio.run/##ZZBNDoIwFIT3nqILE1p9iK8tiAv0Bl4AWTSAf1Fp1Bhvj6OiibqYNJmZfp10567uXJ62/hIem6puV1nrspl0o4Pz0me3bObDx6nUMAgU3Eu5kdFCSgqX1VAN5mrJg36kci7asjmem3092jdruZI5k7AkUhJTEjyGDDSBYDE8raEEgqfTQikRRSI3ZImJi94PDUXmDgKABlDHr8sGIIOnDKCW36CY9B8ExeR7jOaOk3Yc5Ba5RW4nb5bFKAz748VP3qeGP7gD)** if we use `,-` as the separator and we assume that the sequence is always *strictly* increasing.
### How?
We first convert the input array **a[ ]** to a list of consecutive differences with:
```
a.map(p = x => -(p - (p = x)))
```
Because **p** is initially set to a non-numeric value (the callback function of *map()*), the first iteration yields *NaN*.
Example:
```
[6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41]
[ NaN, 5, 2, 5, 2, 5, 2, 5, 2, 5, 2 ]
```
We then coerce the result to a string:
```
"NaN,5,2,5,2,5,2,5,2,5,2"
```
Finally, we look for the shortest1 pattern of comma-separated integers (`,\d+`) starting right after "NaN" and repeating till the end of the string:
```
match(/N((,\d+)*?)\1*$/)
```
*1: using the non-greedy `*?`*
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
s₂ᶠ-ᵐṅᵐ~j₍t
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRU9PDbQt0H26d8HBnK5Csy3rU1Fvy/3@0oY6CkY6CsY6CqY6CmY6CuY6CpY6CoQEQA2UMgeKGJkAMlDQ0j/0fBQA "Brachylog – Try It Online")
Would be 5 bytes if there was a built-in for consecutive differences.
### Explanation
```
Example input: [6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41]
s₂ᶠ Find all substrings of length 2: [[6,11],[11,13],…,[34,39],[39,41]]
-ᵐ Map subtraction: [-5,-2,-5,-2,-5,-2,-5,-2,-5,-2]
ṅᵐ Map negate: [5,2,5,2,5,2,5,2,5,2]
~j₍ Anti-juxtapose the list of differences; the shortest repeated list is found
first, with the biggest number of repetitions: [5,[5,2]]
t Tail: [5,2]
```
[Answer]
# Pyth, 11 bytes
```
<J.+Qf.<IJT
```
[Try it here](http://pyth.herokuapp.com/?code=%3CJ.%2BQf.%3CIJT&input=%5B1%2C+4%2C+8%2C+9%2C+10%2C+13%2C+17%2C+18%2C+19%2C+22%2C+26%2C+27%2C+28%5D&debug=0)
### Explanation
```
<J.+Qf.<IJT
J.+Q Call the sequence of differences in the input J.
f Find the first positive integer T...
.<IJT ... where rotating J by T doesn't change it.
<J Take that many elements of J.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14~~ 12 bytes
```
äa
¯@eUéX}aÄ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=5GEKr0BlVelYfWHE&input=WzUsNiw3XQ==)
---
## Explanation
```
:Implicit input of array U
äa :Consecutive absolute differences
\n :Reassign to U
@ }aÄ :Return the first positive integer X that returns true
UéX : Rotate U right X times
e : Check equality with U
¯ :Slice U to that element
```
---
## Original
```
äa
@eUîX}a@¯XÄ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=5GEKQGVV7lh9YUCvWMQ=&input=WzUsNiw3XQ==)
[Answer]
# [R](https://www.r-project.org/), ~~49~~ 46 bytes
Full program:
```
d=diff(scan());while(any((s=d[1:T])-d))T=T+1;s
```
[Try it online!](https://tio.run/##BcExCoAwDAXQq/wxQQQTRavSW3QTBzEWC@JgB/H09b2nFPOWYqS8bzcxz@@ZroO2@yPK3haZwsq1MQcfKplzEXRwGCENpIUMEAcZoQrtoQPUlR8 "R – Try It Online")
### [R](https://www.r-project.org/), ~~72~~ ~~58~~ 54 bytes
Original function submission with all test cases in one place:
```
function(a,d=diff(a)){while(any((s=d[1:T])-d))T=T+1;s}
```
[Try it online!](https://tio.run/##XY/BCsIwEETvfkWOWVyhm6Y1Kv2L3sRDaQ0WpIJVRMRvrxNNsXqYy8ybYfc8@GLw166@tKdOV9wUTeu9roget0N73Ouqu2vdF81W1uWOFg1RWZRz2fTPwetaCyvDKmWVscpZLVmtWEkCIRH4YiGEsiSahYaZsC5yZsLCluBjxySxA8a@6XE8/QMxYDBp4BkXS/nkCBfGoOzDpOFmLKboWvkelv/OG4kVFyvILXKL3I7/xGeIhhc "R – Try It Online")
Thanks to JayCe for suggesting the full program route and -4 bytes on the function, and to Giuseppe for further -3.
[Answer]
# [J](http://jsoftware.com/), 22 19 bytes
3 bytes saved thanks to FrownyFrog!
```
0{"1[:~./:|."{}.-}:
```
[Try it online!](https://tio.run/##Rc7BDoIwEIThO0/xhwsx0drdlhaa8CQejcR48cAR8dUrNEGuO19m9pXHaTBYEjbbuZZb@ppr@ph6XsxlSflU1YZmHEzDmSUxTlX1uD/fjCgtgUiHCKKIQzwSkfXSo3aHgl9Rj9hi/kDRgEa022UoVW4DatF2S53iPK7Hy7EcjjKVArsCA97iHT7utvyYfw "J – Try It Online")
[Try it online!][TIO-ji2uiwla]
## How?
```
- find the successive differences by subtracting
}: the list with last element dropped
}. from the list with the first element dropped
|."{ rotate the list of differences
/: 0..length-1 times (the input graded up)
[:~. remove duplicating rows
0{"1 take the first element of each row
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Saved 3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
```
¥.œʒË}нн
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0FK9o5NPTTrcXXth74W9//9HG@komOkoGBoAsTEQm@soGBkCsSkQW@goGAOljYHyJkB5E6C8iXksAA "05AB1E – Try It Online")
---
### [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
āεI¥ô}ʒË}нн
```
[Try it online!](https://tio.run/##MzBNTDJM/f//SOO5rZ6Hlh7eUntq0uHu2gt7L@z9/z/aSEfBTEfB0ACIjYHYXEfByBCITYHYQkfBGChtDJQ3AcqbAOVNzGMB "05AB1E – Try It Online")
```
āεI¥ô}ʒË}нн Full program.
ā Length range. Push [1 ... len(inp)].
ε } For each...
I¥ô ... Chop the deltas into pieces of the corresponding size
ʒË} Keep only those that have all their elements equal.
нн And first retrieve the first element of the first one.
```
---
### 13 bytes
A cute alternative, IMO:
```
¥©ηʒDg®ôÙ˜Q}н
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0NJDK89tPzXJJf3QusNbDs88PSew9sLe//@jjXQUzHQUDA2A2BiIzXUUjAyB2BSILXQUjIHSxkB5E6C8CVDexDwWAA "05AB1E – Try It Online")
```
¥©ηʒDg®ôÙ˜Q}н Full program.
¥ Push the deltas.
© Copy them to the register.
ηʒ } And filter the prefixes by...
D Q ... Is the prefix itself equal to...
g®ô ... The deltas, split into chunks of its length...
Ù˜ ... Deduplicated and flattened?
н Head.
```
[Answer]
# Javascript, 49 ~~56~~ bytes
*Edit* 7 bytes saved thanks (guess who?) Arnauld
Same regex idea as Arnauld, but curiously so different in implementation ...
Returning a string with steps comma separated (and a leading comma)
```
p=>/N(.+?)\1+$/.exec(p.map(p=v=>[v-p,p=v][0]))[1]
```
**Test**
```
var F=
p=>/N(.+?)\1+$/.exec(p.map(p=v=>[v-p,p=v][0]))[1]
;[[1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17]
,[1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28]
,[6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41]
,[2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47]
,[5, 6, 7]]
.forEach(x=>console.log(x + ' -> ' + F(x)))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ ~~13~~ 12 bytes
```
dt5YLFTF#Xu)
```
[Try it online!](https://tio.run/##XY6xDsIwDET3foUlJiQPteOkYUedGDuAokggMcJWvj9caJACg5e752c/b@ujXMt99ZfTvMy782tfjktJwqRMjskzBaaJ6cAkIwaNIBfDoJQpD0k7LjZGOw6x1BwOHcGjtw/5lbo/CMsKnSLTmGlIobscqwXjN8DVR6FzWDTZvgm/XpWGx4ajN/SG3qbqb@/nNw "MATL – Try It Online")
Just discovered that MATL does have a circulant function!
### Explanation
`d` - Get the differences between successive terms, as an array
`t5YL` - duplicate that, then call the `YL` ('gallery') function with `5` ('circulant') option. Creates a matrix with the given vector as first row, then successive rows are the same vector shifted circularly, until it wraps around.
`FTF#Xu` - Check for unique rows and get their row numbers (not sure if there's a shorter way of doing this). When sequence steps repeat, the circularly shifted row will be the same as the first row, and the subsequent rows will be repeats. So this gets the indices of the first run of sequence steps before they start repeating.
`)` - index using that into the original differences array, to get the answer.
---
Older:
```
d`tt@YS-a}@:)
```
[Try it online!](https://tio.run/##XY4xDsIwDEX3nsIrkpFqJ00CUwduAAuKIrUSI2xZOXv6Q4MUGLz8//zs15qfZSmPJef5fj2u7/l8KJdbicKkTIZpYnJMnunEJCMGjSAXi0EpPg1ROy40RjsOsdQcDh3Bo7cf8is1fxCWFTpFpiHREF13OVQLZtoBUx@FzmDRyv6N@/WqNDw0HL1Fb9FbX/3t/bQB "MATL – Try It Online")
*(-1 byte thanks to Giuseppe)*
### Explanation:
```
d % Get the differences between successive terms, as an array
` % Start do-while loop
tt % duplicate the difference array twice
@ % push the current loop index value
YS % circularly shift the difference array by that amount
- % subtract the shifted diffs from the original diffs
a % see if the subtraction resulted in any non-zeros
% if it did, shifted differences were not equal to original differences, so continue loop
}@ % if it didn't, then get loop index
:) % get the differences upto the loop index, before they started repeating
% implicit loop end
```
[Answer]
# [Python 2](https://docs.python.org/2/), 101 bytes
```
def f(l):d=[y-x for x,y in zip(l,l[1:])];g=len(l);print[d[:k]for k in range(1,g+1)if g/k*d[:k]==d][0]
```
[Try it online!](https://tio.run/##HcrLDoIwEEDRX5llq2OkD8VA@iVNFyZ92NAUQliAP18HF3d17nJsn7nK1nyIEFnhgzf2uO0Q5xV2PCBX@OaFFSxWDI67MZkSKo3jsua6WW@HyZ3zdK7ru6bABKar4DlCuk@X/2CMd7ZzLTIrEZ4IoqMU1SNIQT2oF4IiVuSaXJPr3vH2Aw "Python 2 – Try It Online")
First generates the deltas **d**, then finds the first prefix **p** of **d** that when repeated **⌊len(L) / len(p)⌋** times yields **L**, where **L** is the input list.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 62 bytes
Relies on Regex logic adapted from [Arnauld's answer](https://codegolf.stackexchange.com/a/166184/78274).
```
->a{i=-2;a.map{|x|(i+=1)>=0?x-a[i]:0}*?,=~/((,\d+)*?)\1*$/;$1}
```
[Try it online!](https://tio.run/##XY/JDoJAEETvfsUcOLA0SjcDombkQ3AOGEPCwYS4JBqXX8dCMRk99KWqXnX34by99o3p43V9a00sq3q6r7vb/XL328hwsDZJeYnrqrXL5BGWZJ4z36fNLgrCMthw6M1WHj/67nw6qqaqmJSQSkllpHJSc1ILUpxg4DB01hiYPLd28qXEyRdjVpw8ZB50dEnicMjpN/Fdkv6FUSKoFWhSOGDuHFQMpZjsk0uH@9Gagtf8e2T@u0Z4xIoRg6/ha/ja/W98ztr@BQ "Ruby – Try It Online")
Alternative determination of step differences, also 62 bytes:
```
->a{[0,*a.each_cons(2).map{|x,y|y-x}]*?,=~/((,\d+)*?)\1*$/;$1}
```
[Try it online!](https://tio.run/##XY/NDoJADITvPsUePABWoGUFjFEfBDcG/@JFJaKJBPXVcVBMVg@9zMw3bc/XVdXsps1wltdZSF7ub/P1frk@HUtHXP@QF/X9RtW9Gt4expvT9Bk4Di02A9ebuwv2@sGkz4@muF5KtcsyJiWkIlIjUjGphNSYFIcYOAydNQYmJ8b0vpRY@bTLipWHzK2OLgktDjn9Jr5Lor8wSgS1Ak1SC4ytg9K2FDP65KL2frRG4DX/Hhn/rhHusLTD4Gv4Gr62/@ueM6Z5AQ "Ruby – Try It Online")
[Answer]
# Java 10, ~~104~~ 100 bytes
```
a->{var t="";for(int i=a.length;i-->1;t+=a[i]-a[i-1]+" ");return t.replaceAll("( ?.+?)\\1*$","$1");}
```
Regex `( ?.+?)\1*$` for shortest repeating substring from [*@Neil*'s comment on *@Arnauld*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/questions/166177/get-the-sequence-steps/166184#comment402027_166184).
[Try it online.](https://tio.run/##lZBBbsIwEEX3nGJksUiKE2EnQKoooB6gbLoEFm4w1NQY5BiqCuXs6SS4Eu0KpEwkz7ff/zM7cRbRbv3ZlFpUFbwKZS49AGWctBtRSpi3R4A3Z5XZQhmgsliBCHNs11j4VU44VcIcDBTQiGh6OQsLriAk3xxs@wJUIWItzdZ95CqKpix3g0Is1CrCX8RWAwIkzK10J2vAxVYeNXq/aB2QAGbxYBYul@ypTyjpM7xYN/nV@Xh61@jsA5wPag17nCC4pu1y@vjflZP7@HBy8RElp01g4jIw8gu6gS6MAqeQUBhRGFOYUHimwIZYqDDssxQLRTapw274O6D8Bpd5FL/BYZu1fbTiw/uxiEk74G/E5B8LPTi6cuzx7H7u@GbarI2ENbpiknY5aJogPmUPbWD8NyRnnpp5Kuop6inq6QO79Yv1D@pe3fwA)
**Explanation:**
```
a->{ // Method with integer-array parameter and String return-type
var t=""; // Temp-String, starting empty
for(int i=a.length;i-->1; // Loop backward over the input-array, skipping the first item
t+=a[i]-a[i-1] // Calculate the difference between two adjacent items
+" "); // And append this with a space to the temp-String
return t.replaceAll("( ?.+?)\\1*$",
// Find the shortest repeating substring
"$1");}// And only keep one such substring
```
[Answer]
# APL+WIN, 39 bytes
Prompt for input.
```
(↑((⍴v)=+/¨(⊂v)=(⍳⍴v)⌽¨⊂v)/⍳⍴v)↑v←-2-/⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5rPGqbqKHxqHdLmaattv6hFRqPupqATKDIZrDgo569h1aAxfThQm0Ty4AG6Brp6gMN@w805n8al6GCkYKxgqmCmYK5gqWCoYGCoaGCobGCoYmCoamCoTlXGpcRVNYCLGUEkzVXMASKWCoYGQAA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
v←-2-/⎕ Prompt for input and take successive differences
(⍳⍴v)⌽¨⊂v create a nested vector ans sequentially rotate by one to length of v
+/¨(⊂v)= compare to original v and sum positions where there is match
(⍴v)= identify where all elements match
(↑(....) identify number of rotations giving a first complete match
(↑(...)↑v take first number of elements from above from v as repeated sequence
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~86~~ 85 bytes
```
def f(a,n=1):d=[y-x for x,y in zip(a,a[1:])];return d[:-n]==d[n:]and d[:n]or f(a,n+1)
```
[Try it online!](https://tio.run/##XZDBasMwEETP6VfsLTXZQFZWHEdF/RGhg0Ax9UUxxoE4P@@OXBXcHvYy82a0q2Gevu5JLUu8ddS9B05WKhOtm49P6u4jPXmmPtGrH2AGJ8ZX/mO8TY8xUXTmmLy10SXjQ4pZSB6htegg1ZIbQs47J0yKqWY6MzVMF6Yrk5wwcAS6aAxMuXgmpzZgWyC1ASFL1lGiTjkAQK/ob239j0JaoU9BU21ONJu321yDOf8AdV4VdTWCWso@zd9iJYVvCw9fw9fw9XpDOcB787Ybxj5NFHhvP/eM/6mWbw "Python 2 – Try It Online")
Construct the differences as `d`; if `d` repeats with unit size `n` then `d[n:]==d[:-n]`; else recurse.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 42 bytes
```
\d+
$*
(?<=(1+),)\1
1+(.+?)\1*$
$1
1+
$.&
```
[Try it online!](https://tio.run/##PU45DsIwEOz3HQY58SjKrDe2I4FS8okUIEFBQ4H4vzER0M2ted5e98el7vzpXNdrENeLXw5Hz9ChWynC4IewNNg7cWxU3LCvlVBETEjImMERJBhBAycwC2EoX6fJGSzgDFVogmZokfTrFOgInT5ybKuGOMMo2sb/deWWKFsiwUZYhGXZHrwB "Retina 0.8.2 – Try It Online") Link includes test cases. Output includes leading comma. Explanation:
```
\d+
$*
```
Convert to unary.
```
(?<=(1+),)\1
```
Compute forward differences, except for the first number, which gets left behind.
```
1+(.+?)\1*$
$1
```
Match repeating differences.
```
1+
$.&
```
Convert to decimal.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¥DηvÐNƒÁ}QD—#
```
[Try it online](https://tio.run/##AUQAu/8wNWFiMWX//8KlRM63dsOQTsaSw4F9UUTigJQj//9bMiw2LDEwLDEzLDE3LDIxLDI1LDI4LDMyLDM2LDQwLDQzLDQ3XQ) or [verify all test cases](https://tio.run/##TY49CsJAFISvIthOsfP27U/61IL1kkLBK9gJegMRr@ARxN6AZQ7hRdbNxqDt@76ZN8Ztttzl4Z6ft3Z47Pvz6nXpT4d1@z5elzmnRAgsHDwCGtCABC2ooANDh0WSL46VyYwDWC4NxIwSoUWYGuwfFIiHBEgcLT/XxxKDuJHYMkBhGyinb/5XIqxSrJKHGqiF1lV1U9d9AA).
I know there are already [two shorter 05AB1E answers posted by *@Mr.Xcoder*](https://codegolf.stackexchange.com/a/166188/52210), but I wanted to try this alternative approach using rotation and equality check.
Might be able to golf it down a few bytes without dropping `Á`.
-1 byte after a tip of *@Emigna* to remove the global\_variable registers (`©` and 2x `®`) and use a Duplicate (`D`) and a Triplicate (`Ð`) instead.
**Explanation:**
```
¥ # Calculate the deltas of the input-array
# i.e. [1,2,3,5,6,7,9] → [1,1,2,1,1,2]
D # Duplicate it
η # Push all its prefixes
# [1,1,2,1,1,2] → [[1],[1,1],[1,1,2],[1,1,2,1],[1,1,2,1,1],[1,1,2,1,1,2]]
v # For-each over these prefixes
Ð # Triplicate the (duplicated) deltas-list
NƒÁ} # Rotate the deltas-list N+1 amount of times,
# where N is the prefix index (== prefix_length-1)
# i.e. [1,1,2] and [1,1,2,1,1,2] (rotate 3 times) → [1,1,2,1,1,2]
Q # If the rotated deltas and initial deltas are equal
# [1,1,2,1,1,2] and [1,1,2,1,1,2] → 1
D—# # Print the current prefix-list, and stop the for-each loop
```
[Answer]
Haskell, 107 bytes
```
let i=map(uncurry(-))$zip(tail x)(init x)in head$filter(\s->take(length i)(concat$repeat s)==i)(tail$inits i)
```
x is the input array.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~8~~ 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
░»F\☺»
```
[Run and debug it](https://staxlang.xyz/#p=b0af465c01af&i=[2,+5,+6,+7,+8,+11,+12,+13,+14,+17,+18,+19,+20]%0A[1,+4,+8,+9,+10,+13,+17,+18,+19,+22,+26,+27,+28]%0A[2,+6,+10,+13,+17,+21,+25,+28,+32,+36,+40,+43,+47]%0A[5+6+7]&a=1&m=2)
Here's an unpacked annotated version to show how it works.
```
:- pairwise differences
:( all leftward rotations of array
u keep only unique rotations
mh output the first element from each unique rotation
```
[Run this one](https://staxlang.xyz/#c=%3A-%09pairwise+differences%0A%3A%28%09all+leftward+rotations+of+array%0Au%09keep+only+unique+rotations%0Amh%09output+the+first+element+from+each+unique+rotation&i=[2,+5,+6,+7,+8,+11,+12,+13,+14,+17,+18,+19,+20]%0A[1,+4,+8,+9,+10,+13,+17,+18,+19,+22,+26,+27,+28]%0A[2,+6,+10,+13,+17,+21,+25,+28,+32,+36,+40,+43,+47]%0A[5+6+7]&a=1&m=2)
[Answer]
# [Perl 6](https://perl6.org), 57 bytes
```
{~(.rotor(2=>-1).map:{.[1]-.[0]})~~/^(.+?){}" $0"+$/;~$0}
```
[Test it](https://tio.run/##fZBdbsIwDMffcwpr6gZdQ2nSUti6dj3AHvdWwoQgk5D4qGiZNqH2MNvjzsDLLsQRmBPSifGAFMeR7d/fsXO5noeHTSHhLXQnESGLD7iZrKYS4sO2brvrVblat3mcdJjtLsb5/dbNmOi4mScqu667o7brPNrb6gos78qxulFtedUBRdJSFiXEMJ8tZaFJ2BKALhrASN/D4lb7/e4z2@@@oFYvoV5Z@jBb5psyQYFsOHWEcOAashZtISMaGFpx0rqsIt9zOSnl9LKQ9pb6XYSX8/PdtHefZkVJj5E/KRO0XkhFiNrcM04akXw@XoKjx47I62ptNtBJoJ1qNZo2EghPZTGx9UZmBah9myKbwnlZRKpDxihwCj6FHoWQQp/CHQXmoWGGYZwFaJhkfQFxAgpQjCAZP4EGBuAnEIaZiqMg946wr2F1kEcXaLLp6J9BKMZRnmOMDxqBgDKq6PDkiwPVAa13LPbVRCjto0jAjmCPmi@H/5txZriB4TAfYD7AfGBGDrApNkbezGs2IX4B "Perl 6 – Try It Online")
Output is space separated (`"1 1 2"`)
## Expanded:
```
{ # bare block lambda with implicit parameter $_
~( # stringify (space separated)
.rotor( 2 => -1 ) # from the input take 2 backup 1, repeat
.map: { .[1] - .[0] } # subtract each pair to find the differences
)
~~ # smartmatch
/ # regex
^ # beginning of string
( .+? ) # match at least one character, but as few as possible
{} # make sure $0 is set (probably a compiler bug)
" $0"+ # match $0 one or more times (with a leading space)
$ # end of string
/;
~$0 # return the stringified $0
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
¥©η.ΔÞ®Å?
```
Explanation:
```
# take input implicitly
¥ # deltas, eg [4, 5, 7, 8, 10] -> [1, 2, 1, 2]
© # save this to the global register
η # prefixes, eg [1, 2, 1, 2] -> [[1], [1, 2], ...]
.Δ # find the first one such that
Þ # cycled infinitely, eg [1, 2] -> [1, 2, 1, 2, ...]
Å? # starts with
® # the global register
# and implicitly print the found element
```
Alternative 9-byte:
```
¥η.ΔÞ.¥-Ë
```
Same algo, but instead of comparing to the list of deltas (which needs to be saved/restored), this uses `.¥` (undelta) then compares to the (implicit) input.
[Try it online!](https://tio.run/##yy9OTMpM/f//0NJDK89t1zs35fC8Q@sOt9r//x9tqKNgpKNgrKNgqqNgpqNgrqNgqaNgaADEQBlDoLihCRADJQ3NYwE "05AB1E – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 55 bytes
```
s/\d+ (?=(\d+))/($1-$&).$"/ge;s/\d+$//;s/^(.+?)\1*$/$1/
```
[Try it online!](https://tio.run/##HclBCoNAEETRqxTSyIyibakTEREvIllFghDiEHN@W3H1H/y4/D7BbNf5lcNNo7vqvTphIakvJdH3MtxXVC88XZlPfmYmKlQzokaDgAc69GAFEmzAFgxgd2zxv27f3Yp4Ag "Perl 5 – Try It Online")
Numbers are input as a space separated list. Output is the same format.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
←ḟΛ=Um`CẊ≠⁰N
```
[Try it online!](https://tio.run/##AUEAvv9odXNr///ihpDhuJ/Omz1VbWBD4bqK4omg4oGwTv///1s2LDExLDEzLDE4LDIwLDI1LDI3LDMyLDM0LDM5LDQxXQ "Husk – Try It Online") or [Verify all test cases](https://tio.run/##RcwhDgIxFADRC43o/@22XYHC41BNEyQJWUU4wCJIQOERcAQk4RDcYXuRstSg52W2h/2uDuU41nK6Tq/757ZYD5vl9L6U86OMz1WtNSXBEekRg1gkIBHpUUU9GtCYSR6RliNq0O4XrGIdtsfJLBT/X6g0E5vxOIOzuDCzbmYh5y8 "Husk – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~26~~ 23 bytes
```
FindRepeat@*Differences
```
[Try it online!](https://tio.run/##TY47DsIwEER7n8I1Wons2vlQIKVA1IgbWMEWLohQSBfl7GacuEgxzds3o/24@e0/bo6DS@Ga7nF8Pf3Xu7k/3WIIfvLj4H/pMcURKJx7tahFSNekG9It6Y40MwLGBrEIMGd@IS3VSmqBYDcVhKtiHi20BXsCJl1uNGXW7JKgJPUuGMgGcwZFy1mW7ZnjsHDxu@LjbnG3uNs2d2pqqF3Vmv4 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [K4](http://kx.com/download), 30 bytes
**Solution:**
```
(*&d~/:c#'(!c:#d)#\:d)#d:1_-':
```
**Examples:**
```
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20
3 1 1 1
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17
1 1 2
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':1, 4, 8, 9, 10, 13, 17, 18, 19, 22, 26, 27, 28
3 4 1 1
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':6, 11, 13, 18, 20, 25, 27, 32, 34, 39, 41
5 2
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':2, 6, 10, 13, 17, 21, 25, 28, 32, 36, 40, 43, 47
4 4 3 4
q)k)(*&d~/:c#'(!c:#d)#\:d)#d:1_-':5 6 7
,1
```
**Explanation:**
Seems hefty for what we're trying to solve. Get the deltas of the input and then build sequences and determine the shortest one that matches it.
```
(*&d~/:c#'(!c:#d)#\:d)#d:1_-': / the solution
-': / deltas
1_ / drop first
d: / save as d
# / take (#) from
( ) / do this together
#\:d / take (#) each-left (\:) from d
( ) / do this together
#d / count length of d
c: / save as c
! / range 0..c-1
c#' / take c copies of each
d~/: / d equal (~) to each right (/:)
& / where true
* / first one
```
]
|
[Question]
[
*~~Inspired by~~ Taken from [a question at Stack Overflow](https://stackoverflow.com/q/47693536/2586922)*.
# The challenge
Given an integer `n>1`, output all arrays that can be obtained by swapping exactly two entries in the array `[1, 2, ..., n]`.
The arrays can be produced in any order.
You can consistently use `[0, 1, ..., n-1]` (0-based) instead of `[1, 2, ..., n]` (1-based).
# Additional rules
* Input and output are [flexible as usual](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* [Programs or functions](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Shortest code in bytes wins.
# Test cases
Input `2` gives output (assumed 1-based)
```
2 1
```
Input `3` gives output (note that the three arrays could be in any order)
```
1 3 2
2 1 3
3 2 1
```
Input `4` gives output
```
1 2 4 3
1 3 2 4
1 4 3 2
2 1 3 4
3 2 1 4
4 2 3 1
```
Input `7` gives output
```
1 2 3 4 5 7 6
1 2 3 4 6 5 7
1 2 3 4 7 6 5
1 2 3 5 4 6 7
1 2 3 6 5 4 7
1 2 3 7 5 6 4
1 2 4 3 5 6 7
1 2 5 4 3 6 7
1 2 6 4 5 3 7
1 2 7 4 5 6 3
1 3 2 4 5 6 7
1 4 3 2 5 6 7
1 5 3 4 2 6 7
1 6 3 4 5 2 7
1 7 3 4 5 6 2
2 1 3 4 5 6 7
3 2 1 4 5 6 7
4 2 3 1 5 6 7
5 2 3 4 1 6 7
6 2 3 4 5 1 7
7 2 3 4 5 6 1
```
[Answer]
# [R](https://www.r-project.org/), 54 bytes
```
function(n)combn(n,2,function(x){z=1:n
z[x]=rev(x)
z})
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPMzk/NwlI6xjpwAUrNKurbA2t8riqoitibYtSy4AiXFW1mv/TNEw0/wMA "R – Try It Online")
Returns a matrix where each column is a permutation.
[`combn(n,k)`](https://stat.ethz.ch/R-manual/R-devel/library/utils/html/combn.html) generates all combinations of size `k` from the list `n`, or from `1:n` if `n` is a single integer. It also optionally takes a function `FUN` to be applied to the resultant combinations. So we write a function that performs the swap and returns the swapped list. The results are then all accumulated into an `array`, which is in this case 2-dimensional and hence a matrix.
[Answer]
# [Python 2](https://docs.python.org/2/), 71 bytes
```
r=range(input())
print[map({i:j,j:i}.get,r,r)for i in r for j in r[:i]]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPVUjM6@gtERDU5OroCgzryQ6N7FAozrTKksnyyqzVi89tUSnSKdIMy2/SCFTITNPoUgBxMwCM6OtMmNj//83AQA "Python 2 – Try It Online")
Uses [this tip](https://codegolf.stackexchange.com/a/51621/20260).
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
f n=[[1..x-1]++y:[x+1..y-1]++x:[y+1..n]|x<-[1..n],y<-[x+1..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY62lBPr0LXMFZbu9IqukIbyKsE8yqsoitBvLzYmgob3WgwS6cSyKqAiMb@z03MzFOwVchNLPCNV9AoKC0JLinyyVPQUyjNK88vSikGsoByCsUZ@eWaCioKaQrm/wE "Haskell – Try It Online")
I just generate the permutation, given the `x` and `y` to swap, for each `x,y`
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
r=range(input())
for j in r:
for i in r[:j]:t=r*1;t[i]=j;t[j]=i;print t
```
[Try it online!](https://tio.run/##HccrDoAwDABQzykqNxwEtaUnWSYQfFrRLU0RnL581Mvrt51NZndFXeXYAkm/LMQ47E2BgQQ0DfCF/pTENRnqOGUrVJFfuCLlriQG5r48 "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes
```
r/.{#->#2,#2->#}&@@@Subsets[r=Range@#,{2}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v0hfr1pZ107ZSEfZCEjVqjk4OASXJhWnlhRHF9kGJealpzoo61Qb1caq/Q8oyswriU5zMI/9DwA "Wolfram Language (Mathematica) – Try It Online")
Explanation: `Subsets[Range@#,{2}]` generates all subsets of `{1,2,...,n}` of size 2, then for each subset, `/.` swaps those two things in the list `{1,2,...,n}`.
That approach is disappointingly similar to many of the other submissions, but here's one that's more unique to Mathematica, for 3 extra bytes:
```
r~Permute~Cycles@{#}&/@Subsets[r=Range@#,{2}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v6guILUot7Qktc65MjkntdihWrlWTd8huDSpOLWkOLrINigxLz3VQVmn2qg2Vu1/QFFmXkl0moN57H8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## Haskell, 62 bytes
```
g n|b<-[1..n]=[[last$k:[j|k==i]++[i|k==j]|k<-b]|i<-b,j<-b,j<i]
```
[Try it online!](https://tio.run/##JcYxCoAwDADAr2RwUNSAgovYJ/iCEKQFqWlrEXXs36victymL7@GkLOFmMzUUocYWREFfd2FH8klr5RwXZN8c5z81BpO8tq4H@G8a4mgYNfHvEB5nBJvtBVQjzhwfgA "Haskell – Try It Online")
```
i<-b -- loop 'i' through [1..n]
j<-b -- loop 'j' through [1..n]
j<i -- consider only cases where j<i
[ k<-b] -- make a list by looping 'k' through [1..n]
last -- pick
[i|k==j] -- 'i' if k==j
[j|k==i] -- 'j' if k==i
k -- 'k' else
```
[Answer]
# [Haskell](https://www.haskell.org/), 71 bytes
```
f 0=[]
f x=map(++[x])(f$x-1)++[[1..y-1]++x:[y+1..x-1]++[y]|y<-[1..x-1]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwDY6litNocI2N7FAQ1s7uiJWUyNNpULXUBPIiTbU06vUNYzV1q6wiq7UBvIqwLzoytiaShvdaKhA7P/cxMw824KizLwSlTQFk/8A "Haskell – Try It Online")
---
This adds the current number to the end of all the permutations of last and then computes all the swaps that include the new number.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
:2XN!"G:@tP(
```
[Try it online!](https://tio.run/##y00syfn/38oowk9Ryd3KoSRA4/9/cwA "MATL – Try It Online")
```
%implicit input, say, 4
: %range, stack is {[1,2,3,4]}
2 %push 2
XN %nchoosek, compute all combinations of [1,2,3,4] taken 2 at a time
%this results in a matrix where each row is a combination, i.e.,
%[1, 2;
1, 3;
1, 4;
2, 3;
2, 4;
3, 4]
! %transpose, because "for" iterates over columns
" %begin for loop
G: %push input and range, stack is now [1,2,3,4]
@t %push "for" index (the column), say, [1;2], twice
P %flip array, so stack is now: {[1,2,3,4],[1;2],[2;1]}
( %assignment index, sets [1,2,3,4]([1;2])=[2;1],
%resulting in [2,1,3,4]
%implicit end of loop, implicit end of program, print the stack implicitly.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 8 bytes
```
ŒcżU$y€R
```
[Try it online!](https://tio.run/##y0rNyan8///opOSje0JVKh81rQn6b6RjrGOiY364HchzB@KsRw1zDm07tO0/AA "Jelly – Try It Online")
### How it works
```
ŒcżU$y€R Main link. Argument: n
Œc Take all 2-combinations of [1, ..., n].
żU$ Zip the result with the reversed pairs.
R Range; yield [1, ..., n].
y€ For each [[i, j], [j, i]] in the result to the left, yield the result to
the right, with i replaced by j and vice versa.
```
[Answer]
# C, 93 bytes
```
i,j,k;f(n){for(i=0;i++<n;)for(j=i;j++<n;puts(""))for(k=0;k++<n;)printf("%d ",k-i?k-j?k:i:j);}
```
[Try it online!](https://tio.run/##ZYzBCsIwEETv/YoQEHZpAqKC0LX0WyQS2V2Mpa2n0m@PsYqXzmnmzTDB30PImZ04pQgJ5/gcgNs9cV1fEuEnSsska@xf0wjW4oq1rPS76gdOUwS7uxnr1HOnXjptuBGkJZfOPK6cAKu5MkURDvj/oh86btFpi87FLfkN)
[Answer]
# Octave, 38 bytes
```
@(n)(p=perms(k=1:n))(sum(p~=k,2)==2,:)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPU6PAtiC1KLdYI9vW0CpPU1OjuDRXo6DONlvHSNPW1kjHSvN/Yl6xhonmfwA "Octave – Try It Online")
Generates all permutations of 1:n and select from them those that have two elements different from 1:n.
[Answer]
# JavaScript (ES6), 81 bytes
Prints 0-indexed arrays.
```
n=>(a=[...Array(n).keys()]).map(i=>a.map(j=>i>j&&alert(a.map(k=>k-i?k-j?k:i:j))))
```
### Demo
`alert()` is replaced with `console.log()` in this snippet for user-friendliness.
```
let f =
n=>(a=[...Array(n).keys()]).map(i=>a.map(j=>i>j&&alert(a.map(k=>k-i?k-j?k:i:j))))
alert = s => console.log(JSON.stringify(s));
f(4)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
```
lambda n:[r(i)+[j]+r(i+1,j)+[i]+r(j+1,n)for j in r(n)for i in r(j)]
r=range
```
[Try it online!](https://tio.run/##JccxDoAgDADA3Vd0hOCii4kJL0EGjKJttJDGxdcjhu0uv8@ZeCzRLuUK97oF4NmJQm0ceVNhhp5q8A/VsI5JgAAZRLVgC2nfiZXAx16yID8Q1aTLBw "Python 2 – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~90~~ 82 bytes
```
import StdEnv
$n#n=[1..n]
=tl(removeDup[[if(c<>b)if(c<>a)c b a\\c<-n]\\b<-n,a<-n])
```
It can be done in 80 bytes, but it turns into a direct translation of the Haskell answers.
[Try it online!](https://tio.run/##JcyxCoMwEIDh3acI1MFAFTp1MZ3sUOjmmDhczlgCyUU0Cn35Xi2dvn/6MTggjmncghMRPLGPc1qy6PN4p70o6URKX5qGhkLlUC0upt1126y1nypsb1b@BYnCCjAG25oGY@zBGX4tuc9wHJUor/zBKcBr5frx5O5NED2uXw "Clean – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 9 bytes
```
LœʒD{αĀO<
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f5@jkU5Ncqs9tPNLgb/P/vykA "05AB1E – Try It Online")
**Explanation**
```
L # push range [1 ... input]
œ # get all permutations
ʒ # filter, keep only elements that are true when
α # absolute value is taken with
D{ # a sorted copy
Ā # each non-zero value in the resulting array is converted to 1
O # the array is summed
< # and the sum is decremented
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
!2§kδ#≠Pḣ
```
[Try it online!](https://tio.run/##yygtzv7/X9Ho0PLsc1uUH3UuCHi4Y/H////NAA "Husk – Try It Online")
## Explanation
```
!2§kδ#≠Pḣ Input is an integer n.
ḣ Range: r=[1,2,..,n]
P Permutations of r.
k Classify by
# number of elements
≠ that are different from
§ δ the corresponding element of r.
!2 Take the second class.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~55~~ 53 bytes
```
->n{n.times{|x|x.times{|y|(w=*0...n)[w[x]=y]=x;p w}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vJDM3tbi6pqKmAsasrNEot9Uy0NPTy9OMLo@uiLWtjLWtsC5QKK@trf2fFm0Uy5UWbQIizGP/AwA "Ruby – Try It Online")
0-based solution
The trick here is that the inner loop always "skips" an iteration: the first time it's not executed at all, then only once on the second pass, and so on.
I was happy with 55 bytes until I saw that **R** could be golfed down to 54, so I had to get it to 53.
[Answer]
# [Python 2](https://docs.python.org/2/), 90 bytes
```
f=lambda n,r=range:n*[n]and[a+[n]for a in f(n-1)]+[r(1,i)+[n]+r(i+1,n)+[i]for i in r(1,n)]
```
[Try it online!](https://tio.run/##PYpBCsIwEADvfcUeE7MeUgWh0JeEHFZqdMFswpKLr4@NFG8zzNRPexWZe0/rm/J9IxDUVUmej0VOQSLJFsjtkIoCAQskI2dvowtqPLIdzalh51F24d/IYxxdbOxJS4ZalaUB51q0HTb91xnhgnBFuC0THNUkw9b2Lw "Python 2 – Try It Online")
[Answer]
# Pyth, 9 bytes
```
t{.rLQ*=U
```
[Demonstration](https://pyth.herokuapp.com/?code=t%7B.rLQ%2a%3DU&input=4&debug=0)
The easiest way to swap two values is to use `.r`, which is Pyth's rotary translation function. `.r<list>[A, B]` will swap all occurrences of `A` and `B` in `list`.
Therefore, by applying the translation function to `UQ`, the list from `0` to `n-1` with each two element list of different numbers in the list, we will generate the desired output. `Q` is the input, `n`, and `U` is the range function.
The easy way to do this would be:
```
.rLUQ.cUQ2
```
`.cUQ2` generates all 2 element combinations of distinct elements in the range, and `.rLUQ` maps the `.r` function over them and the list `UQ`.
However, that would be 10 bytes.
Instead of making `.cUQ2`, the distinct ordered pairs, we can make all pairs with `*=U`. This is implicitly equivalent to `*=UQQ`. It starts by overwriting `Q` with `UQ`, then taking the Cartesian product of `UQ` and `UQ`. This gives all pairs of numbers in the range, not necessarily ordered or distinct.
`.rLQ` swaps using each list. Recall that `Q` is now equal to the list from `0` to `n-1`, not `n`.
Because the pairs were not ordered, there are duplicates. `{` removes duplicates. Because the pairs were not distinct, the unchanged list is present. This list will always be first after deduplication, because `{` preserves the order of the first appearance and the unchanged list is produced by rotating by `[0,0]`. `t` removes the first element, giving the desired list of swaps.
[Answer]
# Pyth, 11 bytes
```
fq2snVTUQ.p
```
[Try it online](http://pyth.herokuapp.com/?code=fq2snVTUQ.p&input=7&debug=0)
Not as short as isaacg's approach, but different enough to post.
### Explanation
```
fq2snVTUQ.p
.pQ Take the permutations of the (implicit) range [0,...,input].
f T Filter to get the permutations...
snV UQ ... where the number of differences with [0,...,input]...
q2 ... is 2.
```
[Answer]
# Java 8, ~~109~~ 105 bytes
```
n->{String r="";for(int i=0,j,k;i++<n;)for(j=i;j++<n;r+="\n")for(k=0;k++<n;)r+=k!=i?k!=j?k:i:j;return r;}
```
I'm rusty.. Haven't code-golfed in months.. Ended up porting [@Steadybox' C answer](https://codegolf.stackexchange.com/a/152285/52210).. Can probably be golfed some more.
[Try it here.](https://tio.run/##hZDBasMwDIbvewotp5i0oayDQTWvT7Bedlx78Fx3yE6V4DiFUfLsqZrkOgqWQf8nIf3y5mKWdePYH8NgK9O28GmIr08AxMnFk7EOdvcU4CtF4l@wuRBghSL2EvLaZBJZ2AGDhoGXH9e5Nuosw1MdxxbSq4VfBKSieGdUd9lrQj@msdDZnrNRDXqFYSoSOTxr2srnt2FDG4/RpS4yROwHnMY33U8l4@ctLjUd4Swm8mmJ74NRs4G/NrlzWXepbISkinMubf6iRi//8vUD/vqAv6n5Vv1wAw)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 66 bytes
```
->n{a=*1..n
a.permutation.select{|b|b.zip(a).count{|c,d|c!=d}==2}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtFWy1BPL48rUa8gtSi3tCSxJDM/T684NSc1uaS6JqkmSa8qs0AjUVMvOb80DyiSrJNSk6xom1Jra2tUW/tfw0hPz1xTLzUxOaO6pqKmQCEtuiK29j8A "Ruby – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 80 bytes
*-12 bytes thanks to Unihedron.*
```
->n{(r=1..n).map{|x|r.map{|y|r.map{|i|i==x ?y:i==y ?x:i}}}.flatten(1).uniq[1,n]}
```
[Try it online!](https://tio.run/##NcZBCoAgEADAr3hUqAWhk2A9RDwUJCzUYmKgqG@3IDrNhHvL3ek@zlR40BKABJyrLzXV8CX/wYpaJ7Zk9ZrZkhS21sAda4w7cSngJryMHMi27gNSZM5Mtj8 "Ruby – Try It Online")
I had an approach in mind that best translated to Ruby for some reason so... I don't even really know Ruby...
]
|
[Question]
[
## Premise:
Your reputation is in Stack-Exchange Form if it can be represented by decomposing your medal counts (gold, silver, and bronze counted separately) into their base-10 digits and joining them in any given order, with a few caveats.
While decomposing, each
* Gold medal digit is worth three digits.
* Silver is worth two digits.
* Bronze is one digit.
* Additionally, since SE does not display a medal type if you do not have any, a count of 0 medals for a type will **not** yield a `[0]`.
**Example:**
* `[1 Gold, 2 Silvers, 3 Bronzes]` will decompose into `[1,1,1,2,2,3]`. 321112 and 213121 are two examples of an SE-form number for these medals.
* `[20 Golds, 0 Silvers, 20 Bronzes]` will decompose into `[2,2,2,0,0,0,2,0]`. 20002022 is an SE-form number.
* `[11 Golds, 0 Silvers, 0 Bronzes]` will decompose into `[1,1,1,1,1,1]`. 111111 is the only SE-form number for this.
There will be no leading 0's when considering a SE number. E.g., in the 2nd example above, `00002222 -> 2222` would not be considered a SE-form number for `[20,0,20]`.
## Input/Output:
Input is a list/tuple/array/whatever of `[reputation, gold_medals, silver_medals, bronze_medals]` which are all non-negative integers. This is the assumed order but can be changed. Just make a note in your answer if you do.
Output is any two consistent values for true and false.
## Rules:
* Input will always be valid
* You will always have at least 1 Rep
* You can have no medals at all, which should always return false then.
* The medal counts have no bearing on reality. Having several hundred golds and no bronzes is fine.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins.
## Test Cases:
```
#[Rep, Gold, Silver, Bronze] -> Output
[4, 0, 0, 4] -> True
[1447, 0, 4, 17] -> True
[74414, 4, 0, 17] -> True
[4444, 4, 0, 4] -> True
[4455, 0, 54, 0] -> True
[5355, 5, 0, 3] -> True
[53535, 5, 3, 0] -> True
[4444, 0, 0, 4444] -> True
[444, 4, 0, 0] -> True
[1234, 0, 0, 1234] -> True
[1234, 0, 0, 4321] -> True
[4444, 1, 0, 1] -> False
[5555, 5, 0, 55] -> False
[1234, 1, 23, 4] -> False
[1, 0, 0, 0] -> False
[1001001, 0, 10, 10] -> False
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~14~~ ~~13~~ ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞×0KJ‚€{íË
```
Takes the medals input in the order `[bronze, silver, gold]` as first input, and `reputation` as second input.
-1 byte thanks to *@Grimy*.
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8w9MNvL0eNcx61LSm@vDaw93//0cbGugAkUEsl6GBAQgBAA) or [verify all test cases](https://tio.run/##RY0xCsJQDIavIp0z5DV5dOzipEcoHSo6uOhQEMRFHFRwcxEc3AW9hPUk7yLP5KVqCOH/yJ8/y7aZzGdxtX4fXvdhmQ2axXSQla3KsD@LjOF46y44HoXtNewem@7ZnSLEqmJgQMAaKsdcgCuUhfiLCKwolZwG3ov05vQkRMoGpDtKZFc67EWvUojLiSGN/r1Kptz9vbIXcBorBfb0Z4Wc0i4dWASiNjjUxrr@AA).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
× # Repeat the values in the (implicit) input-list that many times as string
# (since the input-list contains just 3 values, the rest of the infinite
# list is ignored)
0K # Remove all 0s (so all "0", "00" and "000")
J # Join the strings in the list together
‚ # Pair this string with the (implicit) second input
€{í # Sort the digits in both strings in descending order
Ë # And check if both are now equal
# (after which the result is output implicitly as result)
```
[Answer]
# JavaScript (ES6), ~~92~~ 74 bytes
Takes input as `(['gold','silver','bronze'])('rep')`. Returns a Boolean value.
```
b=>r=>[...b.map((n,i)=>n.repeat(+n&&3-i)).join``].sort()+''==[...r].sort()
```
[Try it online!](https://tio.run/##hZHBjsIgGITv@xR7EoiVlALxRI8@gTfXRHSr1lRoaN1kn75LoZU1abEhfwj5OjMMN/kjm5Mp63al9HfRnUV3FLkR@Q5jfMR3WUOokhKJXGFT1IVs4VItFnRVIoRvulSHwx432rQQLQEQov/NjCfdSatGVwWu9AWCrXm011@APv6fnuEOpCD59IOBPYJ2ohmI9YOsHUUYW0@B7Kk2gOw9Ofjab9aaD7QHOZ8C@VOQOo7TCEeDnuUon3X2CftssZDhMmNGFlckGfWKbhM3pxl5QV9Y8KU2smqmXpYEt2j4UJwtzDXCp5tzghkNb/Y@vK@DzEJknA5L035ZuPsD "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 74 bytes
Takes input as `(gold, silver, bronze, 'rep')`. Returns a Boolean value.
```
(g,s,b,r)=>(F=s=>[...s].sort()+0)(r)==F([g,g,g,s,s,b].filter(x=>x).join``)
```
[Try it online!](https://tio.run/##fZFNbsMgEIX3PUV2gEqRMYyywkufoLs0UtzUdhxZpgK3Sk/vDqaLVIbwIyTeNzOP4dp8N/7shs/5ZbIf7dKZhfbc83fumKlobbypDkIIfxTeupmy54JRlExNDz0P0wf6KLphnFtHb6a6MXG1w3Q6seVsJ2/HVoy2p@TVfc2XH8Ke7m87WvAdLs13RBOWEFGRe1Sl1vstoNfoFdCPiDU/jmQJiAwCAFsAVlGhDiqjqxiPuoJkheAAR9ZENBA96FwGWaqQIRzZIqqUd8g/hrxNdTP67Q/ImD1rLjYAILwQUh3A0FLFHj8yF54nk6L820QWRVgILb8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~28 bytes~~ ~~20 bytes~~ ~~16 bytes~~ 13 bytes
Returns 0 for false and 1 for true. This can definitely be golfed down.
```
[1,3,2,1]Y"t2:7)XzVXzY@Ums0>
```
Down to 16 bytes if the reputation score can be taken in separately, and the order is [bronze, silver, gold], reputation
Down to 13 bytes thanks to Luis Mendo
```
3:Y"XzVXzY@Um
```
[Try it online!](https://tio.run/##y00syfmf8N/YKlIpoiosoirSITT3v0vI/2hDcx0THYNYLkMTE3OuaEMdAx3DWC4TIAAA "MATL – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~38~~ ~~34~~ ~~31~~ 20 bytes
```
-:&(\:~&.":)]#~#\.**
```
[Try it online!](https://tio.run/##ZZHBqgIxDEX3fsVFQd@IDs00YaDgSnDlyrVv9VDEjX/gr49JJx2rL3QgnHu5TTP3Yd6urtglrLBBQNJv22J/Oh6GbVr@nNNz2c5T87t4Ls7tej00s8vf7QEiEbLCVXsIaOSxU9YZRIfo3qDl1qD5FErGO0D5bKSswFyMsdzL3GeBQf1Ee2YyP1tqXyhrOeR3ArNIThATCpWYqSiKqGkccay8npuHs3aiflmo5@1i8eb2H2XdFPzJAbsSbpug@uGmiUxDavOpeaSuO/rKKs3vCgC@M/Wn2MkOymd4AQ "J – Try It Online")
*-11 bytes thanks to FrownyFrog!*
[Answer]
# [Ruby](https://www.ruby-lang.org/), 69 bytes
```
->r,g,s,b{([g,g,g,s,s,b]-[0]).flat_map(&:digits).sort==r.digits.sort}
```
[Try it online!](https://tio.run/##XY/daoQwEIXvfYpcSNGSTRMzQSjYFwlB3K5mXdxdSbItpfTZbX7UQocJzPk4c4aYx/FrGZrl8GawxhYfvwupsY6zV@ogqSrJMHWuvXZz8fR6GvXobEns3bimMSTpKH@Wz/M49Uj3zmZoNuPNobwl7@f7dSbT5WFdUbESo0E@9x/dVORtqTDKX7L@dlokYERjg8okA6iTwIjVHtQADKKkKwFfG4CohYhCBOaB4AEkxpPmCfBkSAnrUV8JbZnBwSq@O8L8DwGv2J7DkiscEn@Hhdh3vKHi6/e2hHiE0tBpPT71Cw "Ruby – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes
```
,0
,
,(\d*),(\d*),
¶$1$1$1$2$2
%O`.
^(.+)¶\1$
```
[Try it online!](https://tio.run/##RY5BDsJACEX3nGOatEqaYYD0CC69QGNqogs3Loxn6wF6sSkwNQKZvA8fMp/n9/W@166/LBUzIGA/P07D8cK2JoosqUB3XUa49eN52NaZUq2C2VKARCYHpAkkhE9cWASLoaqBmgJlY1fsyM5s7XDHRQv4rWagwq3v8FfChdoO@QxUj6uqzURY2H8XbjuTs5d7vXY "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation:
```
,0
,
```
Delete zero scores.
```
,(\d*),(\d*),
¶$1$1$1$2$2
```
Expand the gold and silver scores, and convert the separator to a newline.
```
%O`.
```
Sort the reputation and the expanded scores separately.
```
^(.+)¶\1$
```
Compare the sorted digits.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~14~~ ~~13~~ 12 bytes
```
íp fn ¬á øUg
```
Takes input as `[rep, bronze, silver, gold]`
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7XAgZm4grOEg%2bFVn&input=WyI0IiwiNCIsIjAiLCIwIl0) or [Verify all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=VD1VzlXF1HVUIO1wIGZuIKzhIPhVZw&input=WwpbIjQiLCAiMCIsICIwIiwgIjQiXSwKWyIxNDQ3IiwgIjAiLCAiNCIsICIxNyJdLApbIjQxNDQ3IiwgIjQiLCAiMCIsICIxNyJdLApbIjQ0NDQiLCAiNCIsICIwIiwgIjQiXSwKWyI0NDU1IiwgIjAiLCAiNTQiLCAiMCJdLApbIjUzNTUiLCAiNSIsICIwIiwgIjMiXSwKWyI1MzUzNSIsICI1IiwgIjMiLCAiMCJdLApbIjQ0NDQiLCAiMCIsICIwIiwgIjQ0NDQiXSwKWyI0NDQiLCAiNCIsICIwIiwgIjAiXSwKWyIxMjM0IiwgIjAiLCAiMCIsICIxMjM0Il0sClsiMTIzNCIsICIwIiwgIjAiLCAiNDMyMSJdLAoKWyI0NDQ0IiwgIjEiLCAiMCIsICIxIl0sClsiNTU1NSIsICI1IiwgIjAiLCAiNTUiXSwKWyIxMjM0IiwgIjEiLCAiMjMiLCAiNCJdLApbIjEiLCAiMCIsICIwIiwgIjAiXSwKWyIxMDAxMDAxIiwgIjAiLCAiMTAiLCAiMTAiXQpd)
```
Sample input: U = [1447, 17, 4, 0]
íp Repeats each value of U by it's index amount e.g. ["","17","44","000"]
fn Remove all falsy values when converted to a number e.g. ["17","44"]
¬ Concatenate e.g. "1744"
á All permutations e.g. ["1744","1744","1474","1447","1474","1447","7144","7144","7414","7441","7414","7441","4174","4147","4714","4741","4417","4471","4174","4147","4714","4741","4417","4471"]
øUg Does it contain the first item of the input?
```
[Answer]
## Racket, ~~149~~ ~~107~~ 98 bytes
```
(λ(r b s g[h(λ x(sort(string->list(apply ~a(remq*'(0)x)))char<?))])(equal?(h r)(h b s s g g g)))
```
[Try it online!](https://tio.run/##dZFLTsQwDIb3PYUlFthISEnjqBvEHASxCENfopROGqRhw8W4A1cqSZOOoC1JZCv67N92Ys3xpXTTVWf6Gux8yfC5rNq@hGrC7y@08AQj1A@Nv8AZxzfrcHS27evb@64dHZph6D7g06AtX0831yjoTETHxti7A9EjYXl6N90BG7DkTVDzemH7sImyDAev5roesAKGuGYv/CH6wyVzEZAsYtCaF8ySF@7zecXZr9/6W651QgCaN/paRa5SkN5ypZd8teWX@sHvzJdwzN/pT@ZqDpj93vskziqXC99tQKYCcj2AjgNqvT/gpUAwudrky/SB4r8PFCIc70MTIvDpBw)
First time golfing in Racket, so still looking for improvements...
Explanation (of the original longer version, but same idea):
```
(λ(r b ; take rep and badges as arguments
[g(λ(x) ; helper function g which takes a string
(sort ; and returns the sorted
(string->list x) ; list of characters
char<?))]) ; (sort by ascii code)
(equal? ; compare...
(g(~a r)) ; g called on the rep converted to string
(g ; and g called on...
(string-join ; the concatenation of
(map ~a ; the stringified elements of
(append* ; the flattened list given by
(filter ; the elements of the following list where
(λ(x)(>(car x)0)) ; the badge count is nonzero:
(map make-list ; repeat the badge counts
'(1 2 3)b)))) ; 1, 2, and 3 times respectively
""))))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
xJ$¹ƇV,Ṣ€E
```
[Try it online!](https://tio.run/##y0rNyan8/7/CS@XQzmPtYToPdy561LTG9f///9GGBjoKIGwQ@9/QwACEAA "Jelly – Try It Online")
Argument 1: `[Bronze, Silver, Gold]`
Argument 2: `Rep`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
1F⁴F↨NχFι⊞υκFχ¿⁻№υι№θIι⎚
```
[Try it online!](https://tio.run/##NYy7DoMwDEX3fsUVkyNRCUSZ2MrUoYhfSFEQUdOkTWJ@P7X6sAdf6@jcZdNxCdqVMkfrM1VtpYbDGiLopPC5Z50MXfyT88SPm4mkarSN@lGrMHPaiGvc/6ZQ2BV0tZ4TjYGlWLgV8fu8JOiURZbB6IyW1qGUvpNFgw59Oe7uDQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order rep, bronze, silver, gold and outputs `1` if the rep is valid. Explanation:
```
1
```
Assume the rep is valid.
```
F⁴F↨NχFι⊞υκ
```
Loop over the four input values. Push each digit of each value `i` times where `i` is the 0-indexed index of the value. Numeric base conversion is used here as that converts `0` to an empty array.
```
Fχ¿⁻№υι№θIι⎚
```
Check the count of each digit in the array matches that in the first input. If any differ, clear the canvas.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
DẋṠƊ€ẋ"3RU¤FṢ⁼⁴DṢ¤
```
[Try it online!](https://tio.run/##y0rNyan8/9/l4a7uhzsXHOt61LQGyFQyDgo9tMTt4c5Fjxr3PGrc4gJkHVry//9/Ax0FEx0FQ/P/hiYm5gA "Jelly – Try It Online")
this is a *bit* bad
[Answer]
# [Python 2](https://docs.python.org/2/), ~~80~~ ~~79~~ ~~77~~ 68 bytes
```
lambda r,g,s,b:S((g>0)*3*`g`+(s>0)*2*`s`+(b>0)*`b`)==S(`r`)
S=sorted
```
[Try it online!](https://tio.run/##RYsxDsMgEAR7v4ISyBXHoTSRyCdoU5yRYxIpsS2g8esJuHC0u9JIo9328loXqrN71M/4DdMoEkTIEG5eynhHpa3myBeZO5Pm3Dh05sDKOS85sRq8y2sqz6lu6b0UMUtjyCAiWRAGgcCq4VSIvSDwcG1/d7UtIFrbEVX9AQ "Python 2 – Try It Online")
Takes input as `rep, gold, silver, bronze`.
[Answer]
# [Perl 5](https://www.perl.org/) `-lF`, 62 bytes
```
map{@r=sort/./g,@r if($_=<>x$_)>0}1..3;@F=sort@F;say"@r"eq"@F"
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saDaoci2OL@oRF9PP13HoUghM01DJd7Wxq5CJV7TzqDWUE/P2NrBDazEwc26OLFSyaFIKbVQycFN6f9/cxMTQxMuQ3MuAy6Tf/kFJZn5ecX/dX1N9QwMDf7r5rgBAA "Perl 5 – Try It Online")
Takes input on separate lines as
```
reputation
bronze
silver
gold
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
€mdPfIṁdṘN
```
[Try it online!](https://tio.run/##yygtzv7//1HTmtyUgDTPhzsbUx7unOH3////aENzHRMdg9j/hiYm5gA "Husk – Try It Online")
Similar to the Japt answer.
Takes `[bronze,silver,gold]` as first argument, `rep` as second argument.
## Explanation
```
€mdPfIṁdṘN
N natural numbers
Ṙ repeat medals that many times
ṁd get all their digits as a single array
fI filter out zeroes
P permutations
md mapped to their base-10 numbers
€ is rep in the list?
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 66 ~~69~~ bytes
-3 bytes thanks to mazzy
```
''+($args|%{"$_"*$i++*!!$_}|% t*y|sort)-eq(''+$args[0]|% t*y|sort)
```
[Try it online!](https://tio.run/##ZZLBasMwDIbP81OombvaSQp2bBMYdMc9wW6jlB7SbZDRLekYo8mzZ7YcN04rHBB8/y9Zkb@Ov1XTvld1PdDD5jysVhmj@@at7ZbnhO6SlH5kWbpY0F3fLeGU/nXtsTnxdfXNrBSVr2Ibo6EnhH7CBhhhOgeBR/McfNyvn@Cl@akIk1qXHuYgSxRMsNRaakQi0AlqG4GNlWNoDBLjBFdljXLQc3XttFB5qm6dvuc4jQ2LZzDcR4yTRnMW6uJ0@cwZQ60KGcPQVHpr@IWOP@/r1t3YTOMYE3Ueua9u/YWadhDz0Fpc9jPnQrjj@@PHecTtnu0zIXcJZXRnnwEHTFRIipDILX@EBDJgD/QAqAUUAqrAS0g//AM "PowerShell – Try It Online")
Takes input at (Rep, Bronze, Silver, Gold)
Figure I'll take a crack at my own question. Converts the numbers `toCharArray`s and sorts them. Appends an empty string so the sorted arrays are converted back to space-separated strings which can then be compared.
We handle 0 medal counts with `!!$_` which doubly negates the number, making it go `non-zero number-> 0 -> 1` or `0 -> 1 -> 0` which is used to blank the repeat counter.
[Answer]
# Wolfram Language (Mathematica), ~~69~~ 68 bytes
```
i=IntegerDigits
Sort@i@#==Sort[Join@@i/@Select[{##2,##3,#4},#!=0&]]&
```
Defines an anonymous function; takes inputs to function as [reputation, bronze, silver, gold].
I think this method for repeating silver and gold is interesting (and unique among these answers): in an anonymous function, `#n` represents argument n and `##n` represents a sequence of arguments from argument n to the end, so if one were to expand `{##2,##3,#4}`, it would become `{#2,#3,#4,#3,#4,#4}`, which repeats each the necessary number of times while being 7 bytes less than the expanded form.
]
|
[Question]
[
*inspired by [Count down from infinity](https://codegolf.stackexchange.com/q/98274/45941)*
Given a non-negative integer `N`, output the number of repetitions of the following steps it takes to reach 0:
1. Convert `N` to binary (`4812390 -> 10010010110111001100110`)
2. Flip each bit (`10010010110111001100110 -> 01101101001000110011001`)
3. Trim leading zeroes (`01101101001000110011001 -> 1101101001000110011001`)
4. Convert back to decimal (`1101101001000110011001 -> 3576217`)
## Rules
* Input and output may be in any unambiguous, consistent format
* The input will be within the native representable integer range for your language (if your language supports arbitrarily-large integers, there is no bound)
## Test Cases
```
0 -> 0
1 -> 1
42 -> 6
97 -> 3
170 -> 8
255 -> 1
682 -> 10
8675309 -> 11
4812390 -> 14
178956970 -> 28
2863311530 -> 32
```
---
This sequence is [A005811](http://oeis.org/A005811) in the OEIS.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
^HBS
```
[Try it online!](http://jelly.tryitonline.net/#code=XkhCUw&input=&args=Mjg2MzMxMTUzMA) or [verify all test cases](http://jelly.tryitonline.net/#code=XkhCUwrFvMOH4oKsRw&input=&args=MCwgMSwgNDIsIDk3LCAxNzAsIDI1NSwgNjgyLCA4Njc1MzA5LCA0ODEyMzkwLCAxNzg5NTY5NzAsIDI4NjMzMTE1MzA).
### Background
Let **n** be a non-negative integer.
Steps 2 and 3 of the process described in the spec can alternatively be stated as removing all leading **1**'s and toggling the remaining bits.
This means that we'll remove exactly one group of adjacent and equal binary digits in each iteration, so the Binary Countdown Length of **n** is just the number of these groups in the binary representation of **n**. For the purposes of this challenge, think of **0** as having no digits.
For **n = 8675309**, the process looks as follows in binary.
```
100001000101111111101101
11110111010000000010010
1000101111111101101
111010000000010010
101111111101101
10000000010010
1111111101101
10010
1101
10
1
0
```
Instead of counting these groups (which would fail for edge case **0**), we do the following.
**n** and **n:2** have the following binary representations.
```
n = 8675309 = 100001000101111111101101_2
n:2 = 4337654 = 10000100010111111110110_2
```
Note that **n:2**'s binary representation is simply **n**'s, shifted one bit to the left.
If we XOR **n** and **n:2**, we'll obtain a **1** (MSB), and an additional **1** for each pair of different adjacent digits. The number of groups is thus equal to the number of set bits in **n ⊻ n:2**.
### How it works
```
^HBS Main link. Argument: n
H Halve; yield n:2.
^ XOR n with n:2.
B Convert the result to binary.
S Compute the sum of the resulting binary digits.
```
[Answer]
# Python 2, 30 bytes
```
lambda n:bin(n^n/2).count('1')
```
Test it on [Ideone](http://ideone.com/Mj7cu7).
### Background
Let **n** be a non-negative integer.
Steps 2 and 3 of the process described in the spec can alternatively be stated as removing all leading **1**'s and toggling the remaining bits.
This means that we'll remove exactly one group of adjacent and equal binary digits in each iteration, so the Binary Countdown Length of **n** is just the number of these groups in the binary representation of **n**. For the purposes of this challenge, think of **0** as having no digits.
For **n = 8675309**, the process looks as follows in binary.
```
100001000101111111101101
11110111010000000010010
1000101111111101101
111010000000010010
101111111101101
10000000010010
1111111101101
10010
1101
10
1
0
```
Instead of counting these groups (which would fail for edge case **0**), we do the following.
**n** and **n:2** have the following binary representations.
```
n = 8675309 = 100001000101111111101101_2
n:2 = 4337654 = 10000100010111111110110_2
```
Note that **n:2**'s binary representation is simply **n**'s, shifted one bit to the left.
If we XOR **n** and **n:2**, we'll obtain a **1** (MSB), and an additional **1** for each pair of different adjacent digits. The number of groups is thus equal to the number of set bits in **n ⊻ n:2**.
[Answer]
## Python 2, 29 bytes
```
f=lambda n:n and-n%4/2+f(n/2)
```
Counts the number of alternations between 0 and 1 in the binary expansion, counting the leading 1 as an alternation. Does so by checking whether the last two binary digits are different, then recursing onto the number with the last digit removed. The last two digits are different exactly if `n%4` is 1 or 2, which can be checked as `-n%4/2`.
[Answer]
# Haskell, 34 bytes
```
b 0=0
b n|x<-b$div n 2=x+mod(x+n)2
```
[Answer]
## JavaScript (ES6), 26 bytes
```
f=n=>n&&(n^(n>>=1))%2+f(n)
```
Works by counting the transitions between 0 and 1. Only works up to 31 bits. 29 bytes to support 53 bits:
```
f=n=>1<=n&&(n%2^n/2%2)+f(n/2)
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~7~~ 5 bytes
Saved 2 bytes thanks to *Dennis*.
```
b0ÛÔg
```
Without the edge case of *0* this could be 3 bytes `bÔg`.
[Try it online!](http://05ab1e.tryitonline.net/#code=YjDDm8OUZw&input=Mjg2MzMxMTUzMA) or as a [Test suite](http://05ab1e.tryitonline.net/#code=fHZ5YjDDm8OUZyw&input=MAoxCjQyCjk3CjE3MAoyNTUKNjgyCjg2NzUzMDkKNDgxMjM5MAoxNzg5NTY5NzAKMjg2MzMxMTUzMA)
**Explanation**
```
b # convert to binary
0Û # trim off leading zeroes
Ô # remove adjacent duplicates
g # length
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 14 bytes
```
ri0{2b:!2bj)}j
```
[Try it online!](http://cjam.tryitonline.net/#code=cmkwezJiOiEyYmopfWo&input=Mjg2MzMxMTUzMA)
```
ri e# read integer
0 e# value for terminal case
{ e# recursive function
2b e# create binary representation with no leading zeros
:! e# flip bits
2b e# convert binary back to integer
j e# recursive call
) e# increment from 0 on the way up
}j e# end
```
Basically a knock off of [my answer](https://codegolf.stackexchange.com/a/98324/46756) to the other question.
[Answer]
# Java 7,~~112 108 100 90~~ 73 bytes
```
int c(int i){int l=1,j=i;for(;(j=j/2)>0;l*=2);return i<1?0:1+c(2*l-1-i);}
```
###
Basic idea
```
Lets take an no 10110(21)
then you do set all bits in no 21 and you will get 11111
and after that you would subtract the original number from 11111.
You will get 01001 and loop it until you will get 0
```
[Answer]
# J, 14 bytes
```
**1+/@,2~:/\#:
```
Counts the number of runs in the binary digits of *n* with the special case returning 0 for *n* = 0.
## Usage
```
f =: **1+/@,2~:/\#:
(,.f"0) 0 1 42 97 170 255 682 8675309 4812390 178956970 2863311530
0 0
1 1
42 6
97 3
170 8
255 1
682 10
8675309 11
4812390 14
178956970 28
2863311530 32
```
## Explanation
```
**1+/@,2~:/\#: Input: integer n
#: Get the binary digits of n
2 \ For each overlapping sublist of size 2
~:/ Reduce by not-equals
1 , Prepend a 1
+/@ Reduce by addition
* Sign(n), returns 0 for n = 0 else 1
* Multiply with the previous sum and return
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), ~~11~~ 10 bytes
*Thanks to @Dennis for saving one byte!*
```
ri_2be`,e&
```
[Try it online!](http://cjam.tryitonline.net/#code=cmlfMmJlYCxlJg&input=Mjg2MzMxMTUzMA)
### Explanation
```
ri #e Read as integer
#e STACK: 97
_ #e Duplicate
#e STACK: 97, 97
2b #e Convert to binary
#e STACK: 97, [1 1 0 0 0 0 1]
e` #e Run-length encoding
#e STACK: 97, [[2 1] [4 0] [1 1]]
, #e Length
#e STACK: 97, 3
e& #e Return first value if 0, or else the second value
#e STACK: 3
```
[Answer]
## Racket 349 bytes
```
(define(h s)(apply string(map(λ(x)(if(eq? x #\0)#\1 #\0))(string->list s))))(define(g s)(let*
((l(string-length s))(k(for/list((i s)(n l)#:final(not(equal? i #\0)))n)))(substring s(last k))))
(define(f n)(if(= 0 n)0(begin(let loop((n n)(c 1))(define m(string->number(string-append "#b"
(g(h(number->string n 2))))))(if(> m 0)(loop m(add1 c))c))))
```
Ungolfed:
```
(define (invertBinary s)
(apply string
(map
(λ(x)(if(eq? x #\0)#\1 #\0))
(string->list s))))
(define (trimLeading0s s)
(let* ((l (string-length s))
(k (for/list ((i s)
(n l)
#:final (not(equal? i #\0)))
n)))
(substring s (last k))))
(define (f n)
(if (= 0 n) 0
(begin
(let loop ((n n)
(c 1))
(define m
(string->number
(string-append
"#b"
(trimLeading0s
(invertBinary
(number->string n 2))))))
(if (> m 0)
(loop m (add1 c))
c)))))
```
Testing:
```
(f 0)
(f 1)
(f 42)
(f 97)
(f 170)
(f 255)
(f 682)
(f 8675309)
(f 4812390)
(f 178956970)
(f 2863311530)
```
Output:
```
0
1
6
3
8
1
10
11
14
28
32
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 7 bytes
```
BY'nwa*
```
[Try it online!](http://matl.tryitonline.net/#code=QlknbndhKg&input=Mjg2MzMxMTUzMA)
### Explanation
```
% Implicit input, for example 97
% STACK: 97
B % Convert to binary
% STACK: [1 1 0 0 0 0 1]
Y' % Run-length encoding
% STACK: [1 0 1], [2 4 1]
n % Number of elements
% STACK: [1 0 1], 3
w % Swap
% STACK: 3, [1 0 1]
a % Any: gives 1 if any element is nonzero
% STACK: 3, 1
* % Multiply
% STACK: 3
% Implicit display
```
[Answer]
# Vim, ~~62~~ 59 bytes
-3 bytes thanks to DJMcMayhem
```
C0
<C-r>=pri<Tab>'%b',<C-r>")
<Esc>0qqC<C-r>=tr(@",'01','10')
<Esc>:s/^0\+
k<C-a>j@qq@q
```
Here is the xxd output with the unprintable characters intact:
```
0000000: 4330 0d12 3d70 7269 0927 2562 272c 1222 C0..=pri.'%b',."
0000010: 290d 1b30 7171 4312 3d74 7228 4022 2c27 )..0qqC.=tr(@",'
0000020: 3031 272c 2731 3027 290d 1b3a 732f 5e30 01','10')..:s/^0
0000030: 5c2b 0d6b 016a 4071 7140 71 \+.k.j@qq@q
```
[Try it online!](http://v.tryitonline.net/#code=QzAKEj1wcmkJJyViJywSIikKGzBxcUMSPXRyKEAiLCcwMScsJzEwJykKGzpzL14wXCsKawFqQHFxQHE&input=Mjg2MzMxMTUzMA)
## Explanation
```
C " Delete the number (it goes in @")
0<CR> " Print 0 (our counter) and a carriage return
<C-r>=pri<Tab>'%b',<C-r>")<CR><Esc> " Use `printf()` to insert the number as base 2
0qq " Return to column 0, start recording a macro
C<C-r>=tr(@",'01','10')<CR><Esc> " Replace 0s with 1s and vice versa
:s/^0\+<CR> " Delete leading 0s
k<C-a> " Increment the number on the line above
j " Return to the previous line
@q " Invoke macro recursively
q@q " Stop recording and invoke macro
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 8 bytes
```
rib2gnL[
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KDPJKD3PJ/r/fwszc1NjA0sA "Burlesque – Try It Online")
```
ri # Read as integer
b2 # Convert to binary
gn # Collapse like bits
L[ # Find length
```
# 29 bytes
```
ri0j{j+.j2dg)n!2ug}{^^nz}w!vv
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KNMgqzpLWy8ryagoMyJCM0/RqDS9tjouLq@qtlyxrOz/fwszc1NjA0sA "Burlesque – Try It Online")
Actually doing the calculation
```
ri #Read val as int
0j #Push a 0 (counter) to the bottom of the stack
{
j+.j # Increment counter and put back
2dg # Get the digits of binary val
)n! # Not each digit
2ug # Convert back to decimal
}
{^^nz}w! # While not zero
vv # Drop final zero leaving counter
```
[Answer]
# Ruby, 26 bytes
```
f=->n{n<1?0:-n%4/2+f[n/2]}
```
Inspired by xnor's Python answer.
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `s`, 3 bytes
```
½⊻b
```
[Try it Online!](https://vyxal.github.io/latest.html#WyJzIiwiIiwiwr3iirtiIiwiIiwiMjg2MzMxMTUzMCIsIjMuNC4xIl0=)
port of the jelly answer
[Answer]
# [Go](https://go.dev), 172 bytes
```
import(."fmt";."strings")
func f(n uint)(i int){for;n>0;i++{Sscanf(Map(func(r rune)rune{if r<'1'{return'1'}else{return'0'}},TrimLeft(Sprintf("%b",n),"0")),"%b",&n)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVHBatwwEKVXfcVUkKxEpotlZ712Nw4U0lsTQta3thTXkRaTrNbIcmkQ_pJelkJu-aHkayKtGuhlnmZ4j3nz9OfvZrd_6pv2rtlI2Dadfhyt-lA8P3Xbfmcsm1O1tXQ1p4M1nd4MlBM16hYU0zB22nLWQQCndmalz5NVd3Li1kPbaMUum54FMjNgRi15KK5TYM5mYuaMtKPR_jXJ-0G-tclsmrA23faLVJate7_UKkaPflLUHGlCua-hO9Z8IlE0Rc8v767sQy-hBu91bK2LDlcgf_fB40TIr8aAlYMdoIKv32tHXILJhMQJFAFOU8wDlkvMDuNlgkV4pItFZORFiuIgKfLlIktKFFFZiDQrExSnUVeUi7z06jTKizzLhPB8zFI_8FYOKYbAGQdHrsOd95rRqqrW9aeb2mOIemfgB1r4WIFptP-haN6Rpj0MFbNzzYnPNAzeV2Dn4VgH12-53UJ1Dr6yo1v-TVP0DI2BjZHLYfJu_l__-eoiLv8X634f8RU)
Implements the algorithm more or less verbatim from the OP.
[Answer]
# PHP, 64 bytes
based on [my countdown solution](http:///codegolf.stackexchange.com/a/98279#98279)
```
for($n=$argv[1];$n;print 1)$n=bindec(strtr(decbin($n),"01",10));
```
prints `1` character `k` times, where `k` is the number of iterations.
---
+4 bytes for integer output: (empty output for `0`)
```
for($n=$argv[1];$n;$i++)$n=bindec(strtr(decbin($n),"01",10));echo$i;
```
[Answer]
# JavaScript (ES6), 44
Recursive function
Limited to javascript positive integer, 31 bits:
```
f=(a,s=0)=>a?f((-1>>>Math.clz32(a))-a,s+1):s
```
Managing double precision number up to 53 significant bits - **59** bytes:
```
F=(a,s=0)=>a?F('0b'+a.toString(2).replace(/./g,1)-a,s+1):s
```
In another way: using the amazing algorithm by @Dennis, non recursive function managing up 53 bits, **43** bytes:
```
a=>a&&a.toString(2).match(/(.)\1*/g).length
```
[Answer]
# PHP, 51 bytes
```
<?=preg_match_all('/(1+|0+)/',decbin($argv[1])?:o);
```
Uses a regex to count the number of runs of 1 or 0. Unfortunately this needs a special case for input of `0` that requires 3 additional bytes (and gives a notice).
[Answer]
# Java 7, 71 bytes
`int b(Long a){return a==0?0:1+b(~a&-1L>>>64-a.toString(a,2).length());}`
I know this is beaten by [Geobits' `split` solution](http://chat.stackexchange.com/transcript/240?m=33270508#33270508) (which will eventually be posted) but this was still fun to write
[Answer]
# Octave, 47 bytes
```
@(x)(sum(dec2bin(bitxor(x,idivide(x,2)))=='1'))
```
According to the OEIS entry, the value we are looking for as the solution to this challenge is *also* equal to the number of `1`s in the Gray code for the given integer.
Wikipedia tells me the Gray code can be calculated as x ^ (x >> 1), so in the above function I calculate the Gray code as such, convert it to a binary string, and count how many digits of that string are `1`.
[Answer]
## Java 7, 64 bytes
```
long g(Long n){return n.toString(n,2).split("0+").length*2-n%2;}
```
I know this could be beaten by a port of one of the better answers, but I came up with it in chat, and I can't *not* post it after [Poke said something about it](https://codegolf.stackexchange.com/a/98444/14215) :)
[Answer]
# Bash, 57 bytes
Packages: Core Utililities, grep, sed, vim (for `xxd`)
Assume the number is given in binary format. Any length is acceptable :)
```
xxd -b -c1|cut -d" " -f2|sed s/^0*//|grep -o .|uniq|wc -l
```
[Answer]
# [Perl 5](https://www.perl.org/), 31 + 1 (`p`) = 32 bytes
```
$_=(sprintf'%b',$_^$_/2)=~y/1//
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lajuKAoM68kTV01SV1HJT5OJV7fSNO2rlLfUF///39L83/5BSWZ@XnF/3V9TfUMDA3@6xYAAA "Perl 5 – Try It Online")
Using @Dennis's method.
[Answer]
# [Tcl](http://tcl.tk/), 119 bytes
```
proc D n i\ 0 {
while \$n {set n [regsub ^0+(?=.) [string map {0 1 1 0} [format %b $n]] ""]
incr i
scan $n %b n}
set i}
```
[Try it online!](https://tio.run/##FY3dCoIwHMXv/09xCIMiiE1zbhfRTW9hBiZmA52yLbqQPbttnLvzOx@@G7dtsXOHOwz0Awwr/T567PHIDFbX@@jXth/c94UnOx1u1/MRtfNWmwFTu2Bl4FEsoH7Pdmo99i9kpmmw2zWkTWehyXWtiWZCJlBa1WEbUz2eEANx0CUnVRGvGOVlSULmJEVVFkxFJHleqBSrpCqFShkpioLzyCnEieXrHep7Oqaw/QE "Tcl – Try It Online")
**Still very ungolfed for my taste**
[Answer]
# [PHP](https://php.net/), ~~55~~ 52 bytes
```
for($i=$argn;$i;$c++,$i^=(1<<log($i,2)+1)-1);echo$c;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFQybVUSi9LzrFUyrVWStbV1VDLjbDUMbWxy8tOBkjpGmtqGmrqGmtapyRn5KsnW//@bWBgaGVsa/MsvKMnMzyv@r@sGAA "PHP – Try It Online")
All done arithmetically/bitwise (no strings). Am stuck getting it smaller than the [51 byte answer](https://codegolf.stackexchange.com/a/98420/84624) though...
[Answer]
# APL, 13 characters/bytes
```
+/2≠/0,2⊥⍣¯1⊢
```
base 10 to base 2 conversion with all necessary digits
```
2⊥⍣¯1⊢
2⊥⍣¯1⊢4812390
---> 1 0 0 1 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 1 1 0
```
add a leading 0
```
0,
0,1 0 0 1 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 1 1 0
---> 0 1 0 0 1 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 1 1 0
```
pair-wise reduction that gives 1 if consecutive elements are not equal
```
2≠/
2≠/0 1 0 0 1 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 1 1 0
---> 1 1 0 1 1 0 1 1 1 0 1 1 0 0 1 0 1 0 1 0 1 0 1
```
sum
```
+/
+/1 1 0 1 1 0 1 1 1 0 1 1 0 0 1 0 1 0 1 0 1 0 1
---> 14
```
[Answer]
# [PHP](https://php.net/), 50 bytes
```
<?=array_sum(str_split(decbin($argn&-2^$argn*2)));
```
[Try it online!](https://tio.run/##K8go@P/fxt42sagosTK@uDRXo7ikKL64ICezRCMlNTkpM09DJbEoPU9N1ygOzNAy0tTUtP7/38jCzNjY0NDU2OBffkFJZn5e8X9dNwA "PHP – Try It Online")
Unfortunately, really don't think I can get it any more golfed than this!
The idea is to count transitions 1->0 or 0->1.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 76 Bytes, 72 Bytes (thanks to celingcat)
```
unsigned n,m,i;f(x){for(i=0;n=x;x^=m-1,i++)for(m=2;n/=2;m+=m);return i;}
```
[Try it online!](https://tio.run/##bcxBCoMwEEDRfU8hQiFDItVQkTLkJqVQopFZzLSkCgHx7GldN5u/eIvvm9n7nFf50CzTWIlhQxhUgi28oiLXoriE6eG46QxpDQezsyiXX1g7BozTskapCPfMTxIF2@kdSZag6vN4l9oE1QLgH3YlvNqS3obiYCh@bd8fvOcv "C (gcc) – Try It Online")
]
|
[Question]
[
Inspired by one of many bugs I ran into while implementing selection sort in trilangle.
Given a non-empty list of non-negative integers, "sort" the list using the following procedure:
1. Find and output the smallest value in the list.
2. If the list only has one element, stop.
3. Recurse on a sublist:
* If the last element in the list is the smallest, recurse on everything but the last value.
* Otherwise, recurse on everything but the first value.
Your code doesn't have to follow this procedure exactly, as long as the result is the same.
Sample implementation in JS:
```
function* sort(arr) {
if (arr.length === 1) {
return yield arr[0];
}
const min = Math.min(...arr);
yield min;
if (min === arr.at(-1)) {
arr.pop();
yield* sort(arr);
} else {
const [, ...rest] = arr;
yield* sort(rest);
}
}
```
Some notes on the algorithm:
* The output will always contain the same number of elements as the input.
* The input *may* contain duplicates.
* Every element in the output is an element of the input, but they don't necessarily appear the same number of times.
* The elements of the output will be in nondecreasing order.
## I/O
[I/O defaults](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply. Since I don't see this mentioned there, I will explicitly add the following rule:
You are allowed to implement this destructively. If taking the input by reference, the input does not have to have the same value once the procedure is completed. Note that I use this in the sample implementation above: I call `.pop()` without copying the array first.
## Examples
```
[4, 3, 1, 2] => [1, 1, 1, 2]
[1, 2, 3, 4] => [1, 2, 3, 4]
[3, 2, 1, 0] => [0, 1, 2, 3]
[1, 2, 3, 1] => [1, 1, 2, 3]
[101, 103, 101, 105] => [101, 101, 101, 105]
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program (per language) wins.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~15~~ ~~13~~ ~~10~~ 9 bytes
```
(:g…Ȯt=ǔḢ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIoOmfigKbIrnQ9x5ThuKIiLCIiLCJbNCwgMywgMSwgMl0iXQ==)
~~It's not every day I get to use recursion in a lambda~~ Nevermind, I don't anymore.
*-3 thanks to AndrovT*
*-1 by outputting items on newlines*
## Explained
```
(:g…Ȯt=ǔḢ
( # input length times:
:g… # get the minimum of the top of the stack without popping and print that without popping
Ȯt # push the tail of the item over the top of the stack
= # does that equal the min?
ǔ # rotate the list right that many times (once if tail is min [placing tail at front] or no times at all).
Ḣ # Remove the head of the list
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ṖḊṂṄ=Ṫʋ`?ƒ
```
[Try it online!](https://tio.run/##y0rNyan8///hzmkPd3Q93Nn0cGeL7cOdq051J9gfm/T/cDuQr/n/f7SJjoKxjoKhjoJRrI5CNIgGC5iAeMZgHlDMAEXOEMwzAPINDUBcCMs0FgA "Jelly – Try It Online")
Full program, printing each element on its own line with a trailing newline.
I tried a couple printing-based solutions earlier (including some with `Ṫ` that also attempted to leverage it for `Ṗ`), but they all tied the pure solution. However, Jonathan Allan's golf to that gave me room to fit a print in with the extra space so long as it was also with dyadic chaining, which then required some creative wrestling with the loop quick of choice (at one point the program ended in `µµ¿`!) until it eventually inspired me to abuse `ƒ`.
```
ƒ Reduce over the list, starting with the list, by:
Ignoring the right argument,
? if
Ṫʋ the last element (popped) from
= ` the list of for each element in the list if it equals
Ṃ the minimum
Ṅ which is printed on its own line,
Ṗ then remove the last element,
Ḋ else remove the first element.
ƒ The end result is an empty list with no effect on the output.
```
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
ṖḊ=ṂṪƊ?ƬṂ€Ṗ
```
[Try it online!](https://tio.run/##y0rNyan8///hzmkPd3TZPtzZ9HDnqmNd9sfWAJmPmoDktP@H249Oerhzhmbk///RJjoKxjoKhjoKRrE6CtEgGixgAuIZg3lAMQMUOUMwzwDINzQAcSEs01gA "Jelly – Try It Online")
*-1 thanks to Jonathan Allan*
Feels kinda clumsy, but may as well post it ~~while it's the shortest~~ :P
```
Ƭ Repeat while unique, collecting all results:
? If
Ṫ the last element (popped) from
= Ɗ the list of, for each element of the input, if it's equal to
Ṃ the minimum,
Ṗ then remove the last element,
Ḋ else remove the first element.
Ṃ€ Take the minimum of each result
Ṗ and remove the last.
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 10 bytes
```
ᶦ{:Ɔ≥$tI}ṁ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FhsfbltWbXWs7VHnUpUSz9qHOxuXFCclF0NlF9y0jDbRMdYx1DGK5YoGkkC2CZBlDGQZ6hjAxQxBLANDHUMDIBtMm8ZCTAAA)
```
ᶦ{:Ɔ≥$tI}ṁ
ᶦ{ } Iterate the block until it fails
I Choose the first non-failed result between the following two:
:Ɔ≥$ If the last item is the smallest, remove it from the list; otherwise fail
t Remove the first item of the list
ṁ Take the minimum of each step of the iteration
```
---
## [Nekomata v0.1.0.0](https://github.com/AlephAlpha/Nekomata/tree/v0.1.0.0), 13 bytes
```
ⁱ{:↔C≥↔$t?∃}⊥
```
```
ⁱ{:↔C≥↔$t?∃}⊥
ⁱ{ } Iterate the block until it fails
?∃ Choose the first non-failed result between the following two:
:↔C≥↔$ If the last item is the smallest, remove it from the list; otherwise fail
t Remove the first item of the list
⊥ Take the minimum of each step of the iteration
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
vDW=Qθ._¦
```
-1 byte being inspired by the rotate used in [*@lyxal*'s Vyxal answer](https://codegolf.stackexchange.com/a/258952/52210).
[Try it online](https://tio.run/##yy9OTMpM/f@/zCXcNvDcDr34Q8v@/4820VEw1lEw1FEwigUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLkFQO5OpUu/8tcwm0Dz@3Qiz@07H/toW32/6OjTXSMdQx1jGJ1FKKBFJBjAmIaA5mGOgYIUUMw08BQx9AAyAHTprGxAA).
**Original 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
vDW=Êθ·<.$
```
Outputs the result on separated newlines.
[Try it online](https://tio.run/##yy9OTMpM/f@/zCXc9nDXuR2Httvoqfz/H22io2Cso2Coo2AUCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLkFQO5OpUu/8tcwm0Pd53bcWi7jZ7K/9pD2@z/R0eb6BjrGOoYxeooRAMpIMcExDQGMg11DBCihmCmgaGOoQGQA6ZNY2MB).
**Explanation:**
```
v # Loop over the (implicit) input-list, without using its values:
D # Duplicate the current list
# (which will be the implicit input-list in the first iteration)
W # Push its minimum (without popping the list)
= # Output it with trailing newline (without popping)
Q # Check for each value in the list whether it's equal to this minimum
θ # Pop and push the last item
._ # Rotate the list that many times towards the left
¦ # Remove the first item
vDW= # Same as above
Ê # Check for each value in the list whether it's NOT equal to this minimum
θ # Pop and push the last item
· # Double it
< # Decrease it by 1
.$ # Remove that many leading items from the list
# (1 will remove the first item; -1 will remove the last item)
```
[Answer]
# JavaScript (ES6), 65 bytes
```
f=a=>a+a?[m=Math.min(...b=[...a]),...f(b.pop()^m?a.slice(1):b)]:a
```
[Try it online!](https://tio.run/##dY5NDoIwEEb3nqLLNtahFdyQVE7gCZqaDAiKAUqEeP1aiiSG4Cz6M29evnniG4fiVffjobO30rlKoTrjHjPdqguOD2jrjgJArrQ/0TDur4rm0NuesmubIQxNXZRUsjRnJkVX2G6wTQmNvdOK6oSTmBPJydGQbzFGoohoGdqB7FbS1AxesiEtZC3FAfkBsZbEHOO9/0lye71tSUxQTNb8OplFmv/yh7gP "JavaScript (Node.js) – Try It Online")
### Commented
```
f = a => // recursive function taking the input array a[]
a + a ? // if a[] is not empty:
[ // append ...
m = Math.min( // ... m, which is the minimum value in a[]
...b = [...a] // define b[] as a copy of a[]
), //
...f( // append the result of a recursive call:
b.pop() // remove the last element from b[]
^ m ? // if it's not equal to the minimum:
a.slice(1) // pass a[] without the first element
: // else:
b // pass b[] (i.e. a[] without the last element)
) // end of recursive call
] //
: // else:
a // stop
```
---
# JavaScript (ES13), 64 bytes
Suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh).
```
f=a=>a+a?[m=Math.min(...a),...f(a,a.splice((a.at(-1)>m)-1,1))]:a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWNx3SbBNt7RK1E-2jc219E0sy9HIz8zT09PQSNXWAZJpGok6iXnFBTmZyqoZGol5iiYauoaZdrqauoY6hpmasVSLEnFuMAsn5ecX5Oal6OfnpGmka0SY6CsY6CoY6CkaxClCgqamgr68QbQgWBstwoWkCCYL1mWDRBJNB12QMlgIqMEDXZACxBqgPt02G2J2HXZMBSNIApAvCMo2FaYLwDZFkIAEDC2gA)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 57 bytes
```
f(a)=if(#a,concat(m=vecmin(a),f(a[^if(m-a[#a],1,#a)])),a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9BCsIwEEWvMrSbBKaQ2Aq6qBcJUYZgJGBqKFXwLG66Ec_kbZzEunA1_82DP8zjlWgMh1Oa5-d18s3mvfWCZB-8qAndZXA0idjfji6GgQWyNXu2sSFTk0WNNUkrJZJcChKldL4LgmYHaQzDxLHKUEGulgjGdAgtgkZYWcY8y6LL1BbinfpzupBi1irjN62tXe7-HvgA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
Wθ«⟦I⌊θ⟧≔⎇⁼↨θ⁰⌊θ…θ⊖LθΦθλθ
```
[Try it online!](https://tio.run/##TY0/C8IwFMTn9lNkfIEILeLkpFUnBQe30iHERxN4Tc2fKkX87LFxcjnuuN9xSkuvRkkpvbQhZOA4e5fF1RsboW1kiHAx1gzTsDS849uy2IVgegs39Fb6GY5ukhRgLwOCE6zigv0tBGtmRdjo8ZHbAyqPA9qIdzij7aPO0EKdDEX0GaEc3XL0Salt66oWrK7WWX5u03Vp9aQv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Wθ«
```
Repeat until the list is empty.
```
⟦I⌊θ⟧
```
Output its minimum.
```
≔⎇⁼↨θ⁰⌊θ…θ⊖LθΦθλθ
```
Remove the last or first element as appropriate.
[Answer]
# Excel (ms365), 153 bytes
[](https://i.stack.imgur.com/BPrAO.png) - [](https://i.stack.imgur.com/alT49.png) - [](https://i.stack.imgur.com/8ou64.png) - [](https://i.stack.imgur.com/Q2jFP.png) - [](https://i.stack.imgur.com/jldqf.png)
With data in `A1:A4`, formula in `B1`:
```
=TOCOL(BYCOL(REDUCE(A1:A4,A1:A3,LAMBDA(x,y,LET(z,TOCOL(TAKE(x,,-1),2),HSTACK(x,IF(TAKE(z,-1)=MIN(z),DROP(z,-1),DROP(z,1)))))),LAMBDA(a,MIN(TOCOL(a,2)))))
```
[Answer]
# [R](https://www.r-project.org/), ~~68~~ ~~63~~ 57 bytes
```
f=function(l)if(L<-sum(l|1))c(m<-min(l),f(l[-L^!l[L]>m]))
```
[Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jRzMzTcPHRre4NFcjp8ZQUzNZI9dGNzcTJKOTppETresTp5gT7RNrlxurqfk/TSNZw0THWMdQx0hTkwvEA7KAfBMozxjIM9QxQJEzhPEMDHUMDYB8MG0KNA0A "R – Try It Online")
-5 bytes thanks to pajonk. 50 bytes if using newer versions of R.
[Answer]
# [Python](https://www.python.org), 53 bytes
```
f=lambda l:l and[m:=min(l)]+f(l[l[-1]>m:][:len(l)-1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3TdNscxJzk1ISFXKschQS81Kic61sczPzNHI0Y7XTNHKic6J1DWPtcq1io61yUkHCQK4mVHNiWn6RQo5CZp5CdLSJjoKxjoKhjoJRrE40iALzTYAcYzAHKGSALGMI4hgAuYYGIB6EZRoba8XFWVCUmVeiAbRcE2oRzLUA)
Find the minimum. Remove the first element, or not, as appropriate; then take the first n−1 elements where n is the original number of elements, which removes the last element if the first wasn't removed. Call recursively.
[Answer]
# Swift 5.6, 96 bytes
```
func f(x:[Int])->[Int]{x.min().map{[$0]+f(x:$0==x.last ?x.dropLast():[_](x.dropFirst()))} ?? []}
```
[Try it on SwiftFiddle](https://swiftfiddle.com/bpzbefpbtjcodkgz5fjccssoyq)
It's not often you see [`Optional.map(_:)`](https://developer.apple.com/documentation/swift/optional/map(_:)-7txtz) used in real-world code, since it's easily confused with other operations of the same name (i.e. `Array.map(_:)`).
Ungolfed:
```
func f(_ arr: [Int]) -> [Int] {
return arr.min()
.map { min in
[min] + f(
arr.last == min
? arr.dropLast()
: Array(arr.dropFirst()) // dropFirst is lazy by default
)
} ?? []
}
```
Or, written without `.map`:
```
func f(_ arr: [Int]) -> [Int] {
if let min = arr.min() {
return [min] + f(
arr.last == min
? arr.dropLast()
: Array(arr.dropFirst())
)
} else {
return []
}
}
```
[Answer]
# [Arturo](https://arturo-lang.io), 63 bytes
```
f:$[a][([]=a)?->a[m:min a@[m]++f(m=last a)?->chop a->drop a 1]]
```
[Try it](http://arturo-lang.io/playground?OrfXNA)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 19 bytes
```
WgIg@v=PMNgDQgELPOg
```
Takes input as multiple command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhabw9M90x3KbAN8_dJdAtNdfQL80yEyUAVrok10FIx1FAx1FIxioWIA)
### Explanation
I was expecting to use recursion for this, but a plain old while loop ended up shorter.
```
WgIg@v=PMNgDQgELPOg
; g is list of command-line args; v is -1 (implicit)
Wg ; Loop while g is not empty:
I ; If
MNg ; Minimum of g
P ; (Print that value)
= ; Is equal to
g@v ; Last element of g
; Then
DQg ; Remove last element of g
EL ; Else
POg ; Remove first element of g
```
[Answer]
# Haskell + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 25 bytes
```
uue$mn-<(nt?.tl~<gj*=*mn)
```
## Explanation
This answer is based around the `uue` builtin, which has the type:
```
uue :: (List a -> (b, List a)) -> List a -> List b
```
This is a bit complex but it basically describes the recursion scheme we want, it accepts a function which removes a value from a list, and repeatedly applies the function until the list is empty collecting the results in a list.
With this all we have to do is build a function which takes a list and "removes" the proper value. Getting the value itself is really easy, it's the minimum, so we can just use `mn`. We just have to build the list itself. `nt` removes the last element from a list and `tl` removes the first. We combine them with the ternary `(?.)` to make `nt?.tl` which accepts a boolean and a list and removes the last if true and the first otherwise. Then we make `gj*=*mn` which takes a list and compares if the minimum `mn` and the last `gj` are equal. We combine these with `(~<)` to thread their arguments together, to build
```
nt?.tl~<gj*=*mn
```
Which removes an element based on the logic described in the question.
To finish this off we use the fanout `(-<)` to combine the parts int a single function emitting a tuple, and feed that to `uue`.
## Reflection
This is pretty good, the logic in the question itself is pretty messy, and it feels like this captures it pretty efficiently. But I'm seeing a few things that could be improved.
* I could pre-compose `uue` and variants with a fanout. This can't be done with every unfolding function, but it would save a bunch of bytes here, and has reusability.
```
uef mn$nt?.tl~<gj*=*mn
```
* `ixu` could do with a version pre-composed with `ø`. i.e. an "interate until empty" function. This would save 1 byte:
```
mn<<ixe(nt?.tl~<gj*=*mn)
```
While I'm at that I might as well add other variants, like `ixz` for "iterate until zero".
[Answer]
# [Go](https://go.dev), ~~166~~ 160 bytes
```
func f(I[]int)[]int{m,L,k:=I[0],len(I),I
if L<2{return I}
for _,e:=range I{if e<m{m=e}}
if m==I[L-1]{k=f(I[:L-1])}else{k=f(I[1:])}
return append([]int{m},k...)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBBasMwELzrFSInCzbGTlIoJnqAwIfcgykmlYKxJRtZPgm9pBdTKPQLfUp_U62tSy-andFqZ1Yfn89x_ZnaR98-JdVtZ0inp9G6_KC0O3wtTh1ff1e1mAdVmbg3nXFsO72GGvqKi3vRwCBNJhgI0ilaX0_eSrdYQ0UgarT0DWTFbWuig_CxQ16111yGgO2axxH1sWx8z9GhwpoFOcwyKWUVOUkj22mS5j1LEQL0eZ6zkHJ-bzlxi4xRT4ZudjOtOL03ez_xF6BnoCXQUwDiETfhguy8sagV_-7KjRWRlwXSvXqJaiBpPTRCn33H3daTm42eg8mQQ_w9RMbwVcq7rjv-AQ)
A quick-and-dirty port of the sample implementation.
Changelog:
* `L==1 -> L<2`, `return I[0:1] -> return I`: -5 bytes
[Answer]
# [Julia 1.0](http://julialang.org/), 41 bytes
```
!l=!l[(2:end).-(l[end]==@show min(l...))]
```
[Try it online!](https://tio.run/##TY5BbsMgEEX3PsV3ViBRZJx004qqF@gJkBcThypElFiYtunpXQxN5ZFG@m/eDOLy6R2p27K0XrfesP7JhhOXD8ybHAatX@fz9RsfLjAvpeR8WN6vEQ4uIFo6eRfszHiDXCSO0LBf5NmbTSQnirNljlc7RReSD4wEdrC3yY5pxk7gWHWKPyhhu9saeh6qHymN55Lyv5rcizkI7AWUQD9Av8CoAoWbFfriD//yzo3ZF8ijrsqunmW/vVTbZ@@yW7FbbU2Pf0uV1Gb@Cw "Julia 1.0 – Try It Online")
I interpreted *"1. Find and output the smallest value in the list."* as *"print the value with garbage around it"*, hopefully that's acceptable. Also ends with an error. Otherwise, cleaner version below
## [Julia 1.0](http://julialang.org/), 55 bytes
```
!l=l>[] ? [(m=min(l...););!l[(2:end).-(l[end]==m)]] : l
```
[Try it online!](https://tio.run/##TY1NbsIwEEb3OcWXnS2lVhxgA3LoBTiB5cUgjORq4iInRb19cOJSZVbzvjc/Xz8cSP/Oc82Ge@twhhWDGUIUrJSSJ3mq2Yru6ONNqg/BNjfOmEE6hyN4vn8nBISI5OnGIfpRyAq5qLnCwD@JxcVPpB6URi@CLPaRQpw4CjJ9TSX6pHH0aUJNMAbXKj@a7b7BroFu0DmYHlavsHK1QLf6/b98c2V3K@SoLbIta9lvN/X27Fu2C7aLLd3hb6iQ3uQv "Julia 1.0 – Try It Online")
Clean version (returns the "sorted" list)
[Answer]
# Excel, 136 bytes
Define `g` in *Name Manager* as:
```
=LAMBDA(a,
LET(
b,TAKE(a,-1),
c,MIN(a),
d,DROP(a,-1^(c=b)),
e,MIN(d),
IF(COUNT(d),VSTACK(e,g(d)))
)
)
```
Then, within the worksheet:
```
=LET(f,A1:A4,VSTACK(MIN(f),DROP(g(f),-1)))
```
Assumes data in `A1:A4`.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
#=?qeQ
hSQPQt
```
[Try it online!](https://tio.run/##K6gsyfj/X9nWvjA1kCsjODAgsOT//2gTHQVjHQVDHQWjWAA "Pyth – Try It Online")
### Explanation
```
#=?qeQhSQPQtQ # implicitly add Q
# implicitly assign Q = eval(input())
# # repeat until error
= # assign to Q
?qeQhSQ # if the last element of Q equals the minimum element of Q (min element is printed here by newline)
PQ # all but the last element of Q
tQ # else all but the first element of Q
```
[Answer]
as long as the numbers are within a small range, like `[0, 10^8)`, one could do ::::
```
echo '1,1,3,101,2,2,2,101,103,4,3,3,4,105,1,3,0,2,1,1' |
```
>
>
> ```
> mawk '
> function ______(__,___,_,____) {
> for(_ in __) break
> if (length(__) <= (_+=_^=NF=FS=OFS="")) {
> if (+__[___=_--]<+__[_]) {
> __[_]=__[___] substr("",
> __[___]=__[_])
> } return } _=+(____=" ")
> for(___ in __) { !+(_=__[___]) ? ($!_=(_)____$!_) : $_=$_(____)_ }
> return split($(_<_),__,NF=FS=OFS=____)
> } BEGIN { CONVFMT = "%.250g"
> ORS = "," } { printf("\n [ %s%.0s ]\n\n [ ",
> $_, split($_,__,",")______(__))
> for(___ = length(__); ++_<___;) print __[_]
> printf("%s ]\n\n", __[___]) }'
>
> ```
>
>
```
[ 1,1,3,101,2,2,2,101,103,4,3,3,4,105,1,3,0,2,1,1 ]
[ 0,1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,101,101,103,105 ]
```
instead of doing any sort of comparisons, it's what I would call `"NF-sort"` - it's essentially like a hybrid between counting sort and pigeonhole (aka bucket) sort,
e.g. right before the last step in the function,
>
> `$101 == "101 101"` - 2 copies of the string `"101"`
>
>
>
although the code isn't short at all, it's a purely linear algorithm (aka `O(n)`) since no comparisons, nested loops, or recursions are needed other than for the special case of `"0"`, which are prepended at `$1` instead.
]
|
[Question]
[
Your task is to write a non-empty program / function of byte count **L**, which, when repeated **M** times, checks whether a given positive integer **N** is equal to **L × M**.
You should, in theory, support an arbitrary number of repetitions (an arbitrary positive integer value of **M**), but it's fine if, due to language limitations, it cannot work over a certain threshold. Reading the source code of your program or accessing information about it is **strictly forbidden**.
For providing output, you should choose a consistent value for one of the states (either truthy or falsy) and use any other (not necessarily consistent) possible output for the other state ([Discussion](https://codegolf.meta.stackexchange.com/a/12308/59487)).
Your answers will be scored by your initial program's length **L** (in bytes), with less bytes being better.
## Example
Let's say your (initial) program is `ABCDE`. Then:
* `ABCDE` (1 repetition) should check if the input equals **5**.
* `ABCDEABCDE` (2 repetitions) should check if the input equals **10**.
* `ABCDEABCDEABCDE` (3 repetitions) should check if the input equals **15**. Etc...
The score of this sample code would be **5**, as the initial source is 5 bytes long.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
’
```
Output is **0** for a match, non-zero for a non-match.
[Try it online!](https://tio.run/##y0rNyan8//9Rw8wBRP///zcxAgA "Jelly – Try It Online")
### How it works
This makes advantage of the overly liberal output format. Repeating `’` **M** times simply decrements the input **M** times, so the result will be zero if and only if the input is **LM**, where **L = 1**.
[Answer]
## Haskell, 8 bytes
```
(-8+).id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WQ9dCW1MvM4UrHc6EC2VgCMHo/7mJmXkKtgop@VwKCgVFmXklCioKuYkFCmkK0RY6hmY6RiaxaDLpOGUyEDL/AQ "Haskell – Try It Online")
Like many other answers it returns 0 for truthy and non-0 for falsy by repeatedly subtracting the length of the code from the input number.
[Answer]
## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~21~~ 20 bytes
```
\d+
*
^$
_
^_{20}
_
```
[Try it online!](https://tio.run/##Dcg7CoAwEEDB/p1DQbTJbj4kJ/ASkihoYWMhduLZY8qZ@3jOa5PaD/Nal31iJHcUcnnVfFBqFRSLRCShBm1uEbEJZ3CCU3zEJ4IhCEF/ "Retina – Try It Online") Just repeat the part in the *Code* window to see how it handles the multiples.
Gives `0` for the correct multiple and positive integers for everything else.
### Explanation
Let's look at the single program first:
```
\d+
*
```
This converts a decimal number to unary (using `_` as the unary digit).
```
^$
_
```
If the string is empty (which can't happen at this point, because the input is guaranteed to be positive), we replace it with a single `_`.
```
^_{20}
```
Now we get rid of the first 20 underscores. Iff the input was `20`, this results in an empty string.
```
_
```
And finally we count the number of underscores in the result, which is zero iff the input was `20`.
---
Now what happens when we repeat the source code. Since we don't insert a linefeed when joining the programs, the first line will go right at the end of the last line, we get this when the double the program:
```
\d+
*
^$
_
^_{20}
_\d+
*
^$
_
^_{20}
_
```
Now instead of counting the underscores, we end up with the following stage:
```
_\d+
*
```
This stage does nothing, because there are no more digits in the working string at this point, so the regex can't match.
```
^$
_
```
Now this stage becomes relevant. If the input was a smaller multiple of 20, the string has been emptied by the previous copy of the source code. In that case, we turn it into a single underscore, which we know can never be turned into an empty string again by our program. This way we ensure that *only* the **M**th multiple is accepted (and not all multiples up to the **M**th).
```
^_{20}
```
We remove the first 20 underscores once more. So **M** repetitions of the source code will remove **20M** underscores from the string, if possible.
```
_
```
And when we get to the end of the program, we still count underscores so that valid inputs give zero.
[Answer]
# x86 32-bit machine code fragment, 1 byte
```
48 dec eax
```
Input in EAX, output in EAX: 0 for true, non-zero for false. (Also leaves the ZF flag set for true, unset for false, so you could `je was_equal`). As a "bonus", you don't have to worry about wrapping; 32-bit x86 can only address 4GiB of memory, so you can't make M large enough to wrap all the way around and find `1 == 2**32 + 1` or something.
To make a callable function, append a `0xC3` `ret` instruction after repeating `0x48` M times. (Not counted in the total count, because many languages need to repeat just the function body, or an expression, to be able to compete).
Calleable from GNU C with the prototype `__attribute__((regparm(1))) int checkeqM(int eax);` [GNU C's `regparm` x86 function attribute](https://gcc.gnu.org/onlinedocs/gcc/x86-Function-Attributes.html#index-regparm-function-attribute_002c-x86), like `-mregparm`, uses EAX to pass the first integer arg.
For example, this complete program takes 2 args, and JITs M copies of the instruction + a `ret` into a buffer, and then calls it as a function. (Requires executable heap; compile with [`gcc -O3 -m32 -z execstack`](https://stackoverflow.com/questions/23276488/why-is-execstack-required-to-execute-code-on-the-heap))
```
/******* Test harness: JIT into a buffer and call it ******/
// compile with gcc -O3 -no-pie -fno-pie -m32 -z execstack
// or use mprotect or VirtualProtect instead of -z execstack
// or mmap(PROT_EXEC|PROT_READ|PROT_WRITE) instead of malloc
// declare a function pointer to a regparm=1 function
// The special calling convention applies to this function-pointer only
// So main() can still get its args properly, and call libc functions.
// unlike if you compile with -mregparm=1
typedef int __attribute__((regparm(1))) (*eax_arg_funcptr_t)(unsigned arg);
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc<3) return -1;
unsigned N=strtoul(argv[1], NULL, 0), M = strtoul(argv[2], NULL, 0);
char *execbuf = malloc(M+1); // no error checking
memset(execbuf, 0x48, M); // times M dec eax
execbuf[M] = 0xC3; // ret
// Tell GCC we're about to run this data as code. x86 has coherent I-cache,
// but this also stops optimization from removing these as dead stores.
__builtin___clear_cache (execbuf, execbuf+M+1);
// asm("" ::: "memory"); // compiler memory barrier works too.
eax_arg_funcptr_t execfunc = (eax_arg_funcptr_t) execbuf;
int res = execfunc(N);
printf("%u == %u => %d\n", N,M, res );
return !!res; // exit status only takes the low 8 bits of return value
}
```
[non-PIE executables](https://stackoverflow.com/questions/43367427/32-bit-absolute-addresses-no-longer-allowed-in-x86-64-linux) are loaded lower in virtual memory; can do a bigger contiguous malloc.
```
$ gcc -g -O3 -m32 -no-pie -fno-pie -fno-plt -z execstack coderepeat-i386.c
$ time ./a.out 2747483748 2747483748 # 2^31 + 600000100 is close to as big as we can allocate successfully
2747483748 == 2747483748 => 0
real 0m1.590s # on a 3.9GHz Skylake with DDR4-2666
user 0m0.831s
sys 0m0.755s
$ echo $?
0
# perf stat output:
670,816 page-faults # 0.418 M/sec
6,235,285,157 cycles # 3.885 GHz
5,370,142,756 instructions # 0.86 insn per cycle
```
Note that [GNU C doesn't support](https://stackoverflow.com/questions/9386979/what-is-the-maximum-size-of-an-array-in-c#comment85866179_9387041) object sizes larger than `ptrdiff_t` (signed 32-bit), but `malloc` and `memset` do still work, so this program succeeds.
# ARM Thumb machine code fragment, 2 bytes
```
3802 subs r0, #2
```
First arg in `r0` and return value in `r0` is the standard ARM calling convention. This also sets flags (the `s` suffix). Fun fact; the *non*-flag-setting version of `sub` is a 32-bit wide instruction.
The return instruction you need to append is `bx lr`.
# AArch64 machine code fragment, 4 bytes
```
d1001000 sub x0, x0, #0x4
```
Works for 64-bit integers. Input / output in `x0`, as per the standard calling convention. `int64_t foo(uint64_t);`
AArch64 doesn't have a Thumb mode (yet), so 1 instruction is the best we can do.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 16 (or 1) bytes
Boring answer:
```
<C-x>
```
one byte.
Less boring answer:
```
uÓ^$/0
16Ø^a$
```
[Try it online!](https://tio.run/##K/v/v/Tw5DgVfQMuQzPGwzPihBJVuP7//29oBgA "V – Try It Online")
Hexdump:
```
00000000: 75d3 5e24 2f30 0a31 3601 d85e 1261 240a u.^$/0.16..^.a$.
```
I actually wrote this about 5 minutes after the challenge came out. It took me 30 minutes to patch this horrible pile of spaghetti code that I call a *language*.
[Answer]
# [Python 3](https://docs.python.org/3/), 27 bytes
```
int=lambda x,i=int:i(x)-27;
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzOvxDYnMTcpJVGhQifTFsi1ytSo0NQ1Mrf@n5ZfpJCnkJmnEG2oo2BkBsTmQGyho2BqDMQmQGyqo2BmEGvFpQAEBUVAzRp5OgpgSlPzPwA "Python 3 – Try It Online")
Code repeated twice:
```
int=lambda x,i=int:i(x)-27;int=lambda x,i=int:i(x)-27;
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzOvxDYnMTcpJVGhQifTFsi1ytSo0NQ1MrfGI/U/Lb9IIU8hM08h2lBHwcgMiM2B2EJHwdQYiE2A2FRHwcwg1opLAQgKioCaNfJ0FMCUpuZ/AA "Python 3 – Try It Online")
[Answer]
# TI-Basic (83 series), 4 bytes
```
:Ans-4
```
Takes input in `Ans`: for example, you might type `17:prgmCODEGOLF` to run this with an input of `17`. Prints (and returns in `Ans`) the value `0` if the input is equal to **L × M**, and a nonzero value otherwise.
Note that the `:` is part of the code, so if you are entering this into the program editor, you should see
```
PROGRAM:CODEGOLF
::Ans-4
```
if you enter it once and
```
PROGRAM:CODEGOLF
::Ans-4:Ans-4:An
s-4
```
if you enter it three times.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 6 bytes
```
$_-=6;
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXtfWzPr/f7N/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
uses `0` for equal
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
-₂
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X/dRU9P//0b/owA "Brachylog – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 24 bytes
```
({}[(((()()()){}){}){}])
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O6NloDCDRBULO6FoJiNf//NzIBAA "Brain-Flak – Try It Online")
Returns `0` for equal and something else for not equal.
## How it works:
```
({} #pop the top of the stack
[(((()()()){}){}){}] #subtract 24
) #push the result.
```
This code run `n` times will subtract `n * 24` from the input, giving 0 only when the input = `n*24`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 1 byte
```
v
```
[Try it online!](https://tio.run/##Ky5JrPj/v@z/f0MA "Stax – Try it online!")
[Answer]
# [Haskell](https://www.haskell.org/), 12 bytes
```
(-)$0
+12--
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0NXU8WAS0Hb0EhX939uYmaegq1CQVFmXomCikKagqHR/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
Outputs `0` for truthy and some non-zero integer for falsy.
## Alternate solution, 12 bytes
```
id
.(-)12--
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzOFS0FPQ1fT0EhX939uYmaegq1CQVFmXomCikKagqHR/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
[Answer]
# [Befunge-98](https://github.com/catseye/FBBI), 15 bytes
```
]#<@.-&+
>fv
v+
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/P1bZxkFPV02byy6tjKtM@/9/E2MA "Befunge-98 (FBBI) – Try It Online")
[Try it doubled!](https://tio.run/##S0pNK81LT9W1tPj/P1bZxkFPV02byy6tjKtMG437/7@xAQA "Befunge-98 (FBBI) – Try It Online")
Uses 0 for equal and anything else for unequal.
# Explanation:
This code repeated many times will look something like this:
```
]#<@.-&+
>fv
v+]#<@.-&+
>fv
v+]#<@.-&+
>fv
.
.
.
v+]#<@.-&+
>fv
v+
```
1. `]` right turn. Sends the IP down.
2. `>` move east. Sends the IP right.
3. `f` push a 16.
4. `v` move south. Sends the IP down. If this is the last time, Goto step 8.
5. `]` right turn. Sends the IP left.
6. `+` add. Adds the 16 to the top of the stack.
7. `v` move south. Sends the IP down. Goto step 2.
8. `<` move west. Send the IP left.
9. `#` skip. jump over the `]` and wrap around to the end.
10. `+` add. Adds the 16 to the top of the stack.
11. `&` input. Push a number from the user.
12. `-` subtract. get the difference of sum we were working on and the input.
13. `.` print. Print the result.
14. `@` end.
[Answer]
# [Pure Bash](https://www.gnu.org/software/bash/), 15
Input given as a command-line parameter. Output as a shell exit code - `1` for TRUE and `0` for FALSE.
```
(((a+=15)-$1))
```
* [Try it online x1](https://tio.run/##FctBCoAgEEbh/ZziX7hQQmhqDCKis1gZtlFI72/11t/bfYntyg9qKBV3AgvYgScMM8YeI0ME4iDTgjOTJnyVUGEt1D81rbXvVnbGKjaG2g/CETPURobOnEJ7AQ "Bash – Try It Online")
* [Try it online x2](https://tio.run/##XYtNCoAgFAb37xTfwoUSQi@fQUR0ln4M2ySk97faNruBmXXJsR7pRgm54LzAAvbgHt0A18IxRCAe0o/YE2nCSw4F1kJ9U9VaL83E3ljFxtBP69eHLSaomQzt6Qr1AQ)
* [Try it online x3](https://tio.run/##fctLCoAgFEbh@V3FP3CghNDNaxARraWHYZOEdP9WG@jMzuBblxzrkW6UkAvOCyxgD@7RDXAtHEME4iH9iD2RJrzlUGAt1Ieq1nppJvbGKjaG/rd@PGwxQc1kaE9XqA8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
PI⁼Iθ×¹³L⊞Oυω
```
[Try it online!](https://tio.run/##AS8A0P9jaGFyY29hbP//77yw77yp4oG877ypzrjDl8K5wrPvvKziip7vvK/Phc@J//8xMw "Charcoal – Try It Online") Based on my answer to [I double the source, you double the output!](https://codegolf.stackexchange.com/questions/132558) Explanation:
```
⊞Oυω Push empty string to predefined empty list
L Take the length
×¹³ Multiply by 13
⁼Iθ Compare to the input
I Cast to string
P Print without moving the cursor
```
Manages to output `1` for truthy and `0` for falsy. Subsequent repetitions compare the input against `13`, `26`, `39`, `52` etc. but each time the answer is overprinted so only the final answer is seen.
[Answer]
# JavaScript ES6, 32 Bytes
```
((f=k=>n=>n>0?n==k:f(k+32))(32))
```
if true be 0 and false as others, 31 bytes
```
(f=k=>n=>n>0?n-k:_=>f(k+_))(31)
```
```
console.log([
((f=k=>n=>n>0?n==k:f(k+32))(32)) (31),
((f=k=>n=>n>0?n==k:f(k+32))(32)) (32),
((f=k=>n=>n>0?n==k:f(k+32))(32)) (33),
((f=k=>n=>n>0?n==k:f(k+32))(32)) (64),
((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (32),
((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (63),
((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (64),
((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (96)
]);
```
[Answer]
# MIPS, 4 bytes
Uses `$a0` as argument and return value.
```
0x2084fffc addi $a0, $a0, -4
```
# MIPS, 8 bytes (using MIPS calling convention)
```
0x2084fff8 addi $a0, $a0, -8
0x00041021 move $v0, $a0
```
# x86, 5 bytes
This is my first x86 answer so feedback welcome. Uses \_fastcall convention with ecx as first argument.
```
83 e9 05 sub $0x5,%ecx
89 c8 mov %ecx,%eax
```
[Peter Cordes](https://codegolf.stackexchange.com/users/30206/peter-cordes) has a 1 byte solution in the comments.
---
**Brainfuck commentary**: The hard part is getting brainfuck to return a single value. Otherwise something like this would be easy.
```
- >,[-<->] < .
```
[Answer]
# Octave: 23 bytes
```
+23;[ans,i]((N==ans)+1)
```
If N = L\*M, the expression returns `0+i` (i.e. a purely imaginary number), otherwise the expression results in a complex number with a real component.
For a slightly nicer result at the cost of an extra byte:
```
+24;[ans,-1]((N==ans)+1)
```
If N = L\*M the expression returns `-1`, otherwise a positive number.
Demo:
```
N=48;
+24;[ans,-1]((N==ans)+1) #>> 24
+24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1) #>> -1
+24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1) #>> 23
```
---
PS, you can get the same result with `+24;if N==ans;-1;end;ans` but the bytecount is the same
[Answer]
# Lua, ~~56~~ 46 bytes
```
a=(a or io.read())-46io.write(a<=0 and a or"")
```
Outputs a 0 (without a trailing newline) if equal and either nothing or a series of negative numbers (with preceding zero in some cases) if not equal.
Alone: [Try it online!](https://tio.run/##yylN/P8/0VYjUSG/SCEzX68oNTFFQ1NT18QMyCkvyixJ1Ui0sTVQSMxLUQCpUVLS/P/fFAA "Lua – Try It Online")
Repeated a bunch of times: [Try it online!](https://tio.run/##yylN/P8/0VYjUSG/SCEzX68oNTFFQ1NT18QMyCkvyixJ1Ui0sTVQSMxLUQCpUVLSHKqq//83MjYAAA "Lua – Try It Online")
## Explanation
```
a=(a or io.read())-46
```
On the first iteration (when `a` hasn't been defined yet and is therefore `nil`), sets `a` to a number taken from input, otherwise to itself. In both cases, 46 is then subtracted from `a`.
```
io.write(a<=0 and a or"")
```
This just prints `a` if it is less than (to take care of cases where the input was larger than the total length) or equal to zero, and the empty string otherwise.
*-10 bytes* for remembering that Lua does conversions between numbers and strings automatically. Whoops.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte
```
‹
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%80%B9&inputs=1&header=&footer=)
Outputs 0 for truthy and something else for falsy.
Port of the other answers, decrements.
[Answer]
# JavaScript (ES6), 47 bytes
This is using the same technique as [Benoit Esnard](https://codegolf.stackexchange.com/users/38454/benoit-esnard) in [this answer](https://codegolf.stackexchange.com/a/132680/58563) (from *I double the source, you double the output!*).
Prints **0** if **n = 47 \* M**, or a non-zero value otherwise.
```
n=prompt(setTimeout`alert(n)`)-47/*
n-=47//*///
```
### Demo for M = 1
```
n=prompt(setTimeout`alert(n)`)-47/*
n-=47//*///
```
### Demo for M = 2
```
n=prompt(setTimeout`alert(n)`)-47/*
n-=47//*///n=prompt(setTimeout`alert(n)`)-47/*
n-=47//*///
```
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 24 bytes
```
({}[(((()()()){}){}){}])
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v9fo7o2WgMINEFQs7oWgmI1////b2QCAA "Brain-Flak (BrainHack) – Try It Online")
Just subtracts 24 from the input. Outputs `0` for true and anything else for false.
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 68 bytes
```
{<>}<>(({}[((((()()()()){}){}()){}){}])<>{})((){[()](<{}<>>)}{}<>{})
```
[Try it online!](https://tio.run/##SypKzMzLSEzO/v@/2sau1sZOQ6O6NloDBDQhULO6FohgdKymjR2QAZStjtbQjNWwqQbqsdOsBVFA8f///wMA "Brain-Flak (BrainHack) – Try It Online")
This one is more sophisticated it outputs `1` for true and `0` for false.
]
|
[Question]
[
[Triangularity](https://github.com/Mr-Xcoder/Triangularity) is a new esolang developed by [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) where code structure has to follow a very specific pattern:
* For the `n`th line of code, there must be exactly `2n-1` characters of the program on it. This causes a triangular/pyramid shape, with the first line having only one character and the rest increasing by increments of 2.
* Each line must be padded with `.`s on the left and right, such that the characters are centered on their lines and all lines are padded to the same length. If `l` is defined as the number of lines in the program, each line in the program must have a length of `2 * l - 1`
For example, the program on the left is valid, but the program on the right isn't:
```
Valid | Invalid
|
...A... | ABCDE
..BCD.. | FGH
.EFGHI. | IJKLMN
JKLMNOP | OPQRS
```
When laid out in the valid structure, the name becomes obvious.
## Task
Your task is to take a single line string as input, representing Triangularity code, and output it converted into valid code as described above.
Specifications for I/O:
* The input will only contain characters in the range `0x20 - 0x7e`
* The length of the input always will be a square number and thus paddable nicely.
* You must use dots for the output padding, not something else.
You may input and output through any [acceptable](https://codegolf.meta.stackexchange.com/q/2447/66833) method. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in *bytes* wins!
## Test cases
```
input
----
output
g
----
g
PcSa
----
.P.
cSa
DfJ0vCq7G
----
..D..
.fJ0.
vCq7G
7xsB8a1Oqw5fhHX0
----
...7...
..xsB..
.8a1Oq.
w5fhHX0
QNYATbkX2sKZ6IuOmofwhgaef
----
....Q....
...NYA...
..TbkX2..
.sKZ6IuO.
mofwhgaef
ABCDEF"$%& G8"F@
----
...A...
..BCD..
.EF"$%.
& G8"F@
ab.c
----
.a.
b.c
```
For those who know Triangularity, you'll notice from the last test case that strings don't have to be handled
[Answer]
# [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 127 bytes
```
.......).......
......2)1......
...../)IL^.....
....f)rMD@_....
...)2)1/)IL^...
..f+`"'.'*"+E..
.DWReD)2s^)Its.
D+@sh+s+})10cJ.
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8CNKE0F4Qy0jRE5utrevrEIfhpmkW@Lg7xML4mUDVMBZCfpp2gpK6nrqWk7Qriu4QHpbpoGhXHaXqWFOtxuWg7FGdoF2vXahoaJHvp/f8f6BfpGJKUHWFU7B1l5lnqn5ufVp6RnpiaBgA "Triangularity – Try It Online")
## Explanation
Removing the characters that make up for the padding, we get the following program:
```
)2)1/)IL^f)rMD@_)2)1/)IL^f+`"'.'*"+EDWReD)2s^)ItsD+@sh+s+})10cJ
```
... Which is quite length-ish, right? Let's break it down into pieces.
**Generating the integers [0 … √len(input))**
```
)2)1/)IL^f)r – Subprogram #1.
) – Creates a new stack entry, equal to 0. This must precede any integer
literal, because each character in '0123456789' isn't parsed on its
own as a literal, but rather they are commands which multiply the ToS
by 10 and add the value of their digit equivalent.
2 – ToS * 10 + 2 = 2. || STACK: [2]
)1 – The literal 1. || STACK: [2, 1]
/ – Division. || STACK: [1 / 2] = [0.5]
)I – Get the input at index 0. || STACK: [0.5, input]
L – Length. || STACK: [0.5, len(input)]
^ – Exponentiation. || STACK: [len(input) ** 0.5]
f – Trim decimals. || STACK: [int(len(input) ** 0.5)]
)r – Create the list [0 .. ToS). || STACK: [[0 ... int(len(input) ** 0.5))]
```
**Generating the dots**
```
MD@_)2)1/)IL^f+`"'.'*"+E – Subprogram #2.
MD – For each integer in the range, run some code on a separate
stack, preinitialised to two copies of the argument.
@_ – Increment and negate the ToS.
)2)1/)IL^f – The square root of the length of the input, again.
+ – Add the two.
` – And cast the integer given to a string.
"'.'*"+ – Prepends the literal "'.'*" to the string representation.
E – Evaluate as a Python expression (basically string repetition).
```
**Trimming the characters at the front**
```
DWReD)2s^)It – Subprogram #3.
D – Duplicate the result of the expression above.
W – Wrap the whole intermediate stack to an array.
Re – Reverse the stack and dump the contents separately onto the stack.
D – Duplicate the result.
)2 – Push the literal 2.
s^ – Swap and perform exponentiation.
)It – Push the input and trim the characters before that index.
```
**Trimming the characters at the end**
```
sD+@sh+s+ – Subprogram #4.
s – Swap the top two elements on the stack.
D+ – Double. Push twice and add.
@ – Increment.
sh – Swap the top two elements and trim the characters after that index.
+ – Append the first set of dots.
s+ – And prepend the second set of dots.
```
**Ending the loop and pretty-printing**
```
})10cJ – Subprogram #5.
} – End the loop.
)10 – Push the literal 10.
c – Convert from code-point to character (yields '\n').
J – And join the result by newlines.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~15~~ ~~14~~ 10 bytes
Outputs an array of lines.
```
ò@°T¬v1Ãû.
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8kCwVKx2McP7Lg==&input=IlFOWUFUYmtYMnNLWjZJdU9tb2Z3aGdhZWYiCi1S) | [Check all test cases](https://ethproductions.github.io/japt/?v=1.4.5&code=o1Q9MCxYIPJAsFSsdjHD+y4gtytS&input=WyJnIiwiUGNTYSIsIkRmSjB2Q3E3RyIsIjd4c0I4YTFPcXc1ZmhIWDAiLCJRTllBVGJrWDJzS1o2SXVPbW9md2hnYWVmIiwnQUJDREVGIiQlJiBHOCJGQCcsImFiLmMiXQotUg==)
---
## Explantion
```
ò@ Ã :Partition at characters where the following function returns true
°T : Increment T (initially 0)
¬ : Square root
v1 : Divisible by 1?
:(Or, in other words, split after every character with a 1-based index that's a perfect square)
û. :Centre pad each element with .s to the length of the longest element
```
---
## Original Solution
```
ʬÆsTT±X+°XÃû.
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=yqzGc1RUsVgrsFjD+y4=&input=IlFOWUFUYmtYMnNLWjZJdU9tb2Z3aGdhZWYiCi1S)
```
Ê :Length of input
¬ :Square root
Æ Ã :Range [0,ʬ) and pass each X through a function
s : Slice input
T : from index T, initially 0
T±X+°X : to index T incremented by X plus X incremented
û. :Centre pad each element with .s to the length of the longest element
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
Ṡzö`JR2tR'.ṡCİ1
```
[Try it online!](https://tio.run/##yygtzv7//@HOBVWHtyV4BRmVBKnrPdy50PnIBsP///8rZaRXVOXnZOfnlGSAoRIA "Husk – Try It Online")
## Explanation
```
Ṡzö`JR2tR'.ṡCİ1 Implicit input, say s = "DfJ0vCq7G".
İ1 List of odd positive integers: [1,3,5,7,..
C Cut s to those lengths: x = ["D","fJ0","vCq7G"]
ṡ Reversed indices of x: y = [3,2,1]
Ṡz Zip x and y using this function:
Arguments are a string and a number, e.g. r = "fJ0" and n = 2.
R'. n copies of '.': ".."
t Drop first element: "."
R2 Two copies of this: [".","."]
ö`J Join by r: ".fJ0."
Result is ["..D..",".fJ0.","vCq7G"]; implicitly print on separate lines.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ ~~19~~ 18 bytes
Saved a byte thanks to *Magic Octopus Urn*
```
ā·<£õKRvy'.N×.ø}r»
```
[Try it online!](https://tio.run/##ATMAzP8wNWFiMWX//8SBwrc8wqPDtUtSdnknLk7Dly7DuH1ywrv//0FCQ0RFRiIkJSYgRzgiRkA "05AB1E – Try It Online")
**Explanation**
```
ā # push the list [1 ... len(input)]
·< # multiply each by 2 and decrement each, making a list of odd numbers
£ # split the input into chunks of these sizes
õK # remove empty strings
R # reverse list
vy } # for each y in the list
.ø # surround it with
'.N× # "." (dot) repeated N times, where N is the current iteration index
r # reverse the stack
» # join stack by newlines
```
[Answer]
# [Python 2](https://docs.python.org/2/), 83 bytes
```
i=input();u=int(len(i)**.5)
for t in range(u):g="."*(u+~t);print g+i[t*t:][:t-~t]+g
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERD07oUyCrRyEnN08jU1NLSM9XkSssvUihRyMxTKErMS0/VKNW0SrdV0lPS0ijVrivRtC4oAmpQSNfOjC7RKrGKjbYq0a0ridVO//9fKdAv0jEkKTvCqNg7ysyz1D83P608Iz0xNU0JAA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
J²‘Ṭœṗ⁸Ṛz”.Zµṙ"JC$Ṛ
```
A monadic link returning a list of lists of characters (the lines)
**[Try it online!](https://tio.run/##AT4Awf9qZWxsef//SsKy4oCY4bmsxZPhuZfigbjhuZp64oCdLlrCteG5mSJKQyThuZr/w4dZ//8iRGZKMHZDcTdHIg "Jelly – Try It Online")**
### How?
```
J²‘Ṭœṗ⁸Ṛz”.Zµṙ"JC$Ṛ - Link: list of characters e.g. "DfJ0vCq7G"
J - range of length [1,2,3,4,5,6,7,8,9]
² - square (vectorises) [1,4,9,16,25,36,49,64,81]
‘ - increment [2,5,10,17,26,37,50,65,82]
Ṭ - untruth (1s at those indices) [0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,...]
⁸ - chain's left argument "DfJ0vCq7G"
œṗ - partition at indexes ["D","fJ0","vCq7G"]
Ṛ - reverse ["vCq7G","fJ0","D"]
”. - literal '.' '.'
z - transpose with filler ["vfD","CJ.","q0.","7..","G.."]
Z - transpose ["vCq7G","fJ0..","D...."]
µ - start a new monadic chain
$ - last two links as a monad:
J - range of length [1,2,3]
C - complement (vectorises) [0,-1,-2]
" - zip with:
ṙ - rotate left by ["vCq7G",".fJ0.","..D.."]
Ṛ - reverse ["..D..",".fJ0.","vCq7G"]
```
[Answer]
# JavaScript (ES7), ~~82~~ 78 bytes
```
f=(s,k=1-s.length**.5*2,p='')=>s&&f(s.slice(0,k),k+2,p+'.')+`
`+p+s.slice(k)+p
```
### Test cases
```
f=(s,k=1-s.length**.5*2,p='')=>s&&f(s.slice(0,k),k+2,p+'.')+`
`+p+s.slice(k)+p
console.log(f('g'))
console.log(f('PcSa'))
console.log(f('DfJ0vCq7G'))
console.log(f('7xsB8a1Oqw5fhHX0'))
console.log(f('QNYATbkX2sKZ6IuOmofwhgaef'))
console.log(f('ABCDEF"$%& G8"F@'))
```
### Commented
```
f = ( // f = recursive function taking:
s, // s = input string
k = 1 - s.length**.5 * 2, // k = additive inverse of the length of the base
p = '' // p = padding string
) => //
s && // if s is not empty:
f( // do a recursive call with:
s.slice(0, k), // s without the last -k characters
k + 2, // the updated base length (2 less characters)
p + '.' // the updated padding string
) + // end of recursive call()
`\n` + // append a line feed
p + // append the left padding string
s.slice(k) + // append the last -k characters of s
p // append the right padding string
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
```
gÅÉ£õKð'ø‡.c¶¡ζøð'.‡'øð‡»
```
[Try it online!](https://tio.run/##MzBNTDJM/f8//XDr4c5Diw9v9T68Qf3wjkcNC/WSD207tPDctsM7gCJ6QAF1EAtIH9r9/7@jk7OLq5uSiqqagruFkpsDAA "05AB1E – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 21 bytes
```
tnX^eRP&1ZvGyg(46y~(!
```
[Try it online!](https://tio.run/##y00syfn/vyQvIi41KEDNMKrMvTJdw8Sssk5D8f9/dUcnZxdXNyUVVTUFdwslNwd1AA "MATL – Try It Online")
### Explanation
Consider input `'DfJ0vCq7G'` as an example. The stack contents are shown separated by commas, with the top element last. Rows in a 2D array use semicolon as separator.
```
t % Implicit input: string. Duplicate
% STACK: 'DfJ0vCq7G',
'DfJ0vCq7G'
nX^ % Number of elements. Square root
% STACK: 'DfJ0vCq7G',
3
e % Reshape with that many rows (in column major order)
% STACK: ['D0q';
'fv7';
'JCG']
R % Upper triangular part: set elements below diagonal to char(0)
% (displayed as space)
% STACK: ['D0q';
' v7';
' G']
P % Flip vertically
% STACK: [' G';
' v7';
'D0q']
&1Zv % Reflect vertically
% STACK: [' G';
' v7';
'D0q';
' v7';
' G']
G % Push input again
% STACK: [' G';
' v7';
'D0q';
' v7';
' G'],
'DfJ0vCq7G'
yg % Duplicate from below and convert to logical. This gives true for
% for nonzero chars (the entries where input chars will be written)
% STACK: [' G';
' v7';
'D0q';
' v7';
' G'],
'DfJ0vCq7G',
[0 0 1;
0 1 1;
1 1 1;
0 1 1;
0 0 1]
( % Assignment indexing: write values at those positions
% STACK: [' v';
' fC';
'DJq';
' 07';
' G']
46 % Push 46, which is ASCII for '.'
% STACK: [' v';
' fC';
'DJq';
' 07';
' G'],
46
y~ % Duplicate from below and apply logical negate. This gives true
% for char(0) (the entries where '.' will be written)
% STACK: [' G';
' v7';
'D0q';
' v7';
' G'],
46
[1 1 0;
1 0 0;
0 0 0;
1 0 0;
1 1 0]
( % Assignment indexing: write value at those positions
% STACK: ['..G';
'.v7';
'D0q';
'.v7';
'..G'],
! % Transpose. Implicit display
% STACK: ['..D..';
'.fJ0.';
'vCq7G']
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~107~~ ~~94~~ ~~89~~ 88 bytes
```
import StdEnv
@s _[]=s
@s n r= @([['.':l]++['.']\\l<-s]++[take n r])(n+2)(drop n r)
```
```
@[]1
```
[Try it online!](https://tio.run/##HYxPC8IgHEDvfYofo9IxFtQpokF/tkXQbUcnQ6bGSN1QC/ryWXZ7Dx6vV4KZoEf@VAI0G0wY9DRaD43nlXnNJDjoCC3cnwzYQmJC0ArtFM2yCLRt1T530Tx7iNjQFJtsk2Juxyl6GhrPfs8CJKFrIOh4OpdVncwXS7hsk/qAaPj0UrG7C/n1Fsq3YXro3Rc "Clean – Try It Online") Example usage: `@[]1 ['ABCDEF"$%& G8"F@']`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~84~~ 68 bytes
```
[]%1
(s%n)[]=s
(s%n)r=(['.':l++"."|l<-s]++[take n r])%(n+2)$drop n r
```
[Try it online!](https://tio.run/##JcldT8IwGIbhc3/Fm4bJlsoCJAoxLpEPAUVFgwdo14OXuW5kXSnrBh742602nt3P9eRoilRKm0WxZdzrnfnGUwHjkfmvKvJZO2xfS0pJSL7lTcdwSlmNRQoKKh54vqL9oPVZ7bUDW@JOQQQl6ifwdVOv6@pRQQiNkjuVmr/KAmDkJVkjuQAyFQ/d4@QwmLsx@DLjIfZWh9OlyBebrrPX5/fR27bY9M3y4@q@WZV7ccozTIU7R@PJ9G4Wk5Z3DvNhTGa3TnEbJoTbn0RIzIztJFr/Ag "Haskell – Try It Online")
Example usage: `[]%1 $ "abcd"` yields the list of lines `[".a.","bcd"]`.
[Answer]
# Perl, ~~56~~ 52 bytes
Includes `+3` for `-p`
```
#!/usr/bin/perl -p
$_=("."x y///c**.5)=~s%.%$'@{[$&x/$`$`./g]}$'
%rg
```
Give input on STDIN (in principle without final newline, but that only matters for the empty input)
[Answer]
# [Red](http://www.red-lang.org), 227 203 bytes
```
f: func[s][l: to-integer(length? s)** 0.5
n: 0 foreach m parse s[collect[(r: []repeat i l[append r reduce['keep i * 2 - 1
charset[not{Я}]]])r]][v: copy""insert/dup v"."l - n: n + 1 print rejoin[v m v]]]
```
[Try it online!](https://tio.run/##FY6xTsMwGAb3PMUnL22DWtpKMGRBjAgJBGIALA@p/TtJ69rWbycIIZ6JV@GNgplPdzomMz@TgVSzbWBHr2VS0jXIYT34TB3x0pHvcn@DtKprbDdXlW@whQ1Mre5xRmw5EZLUwTnSWS65KT2mSG3GACfbGMkbMJjMqEkuTkSxkBp7rLGrdP9fyNKH/PX7862UWrFScmqgQ/wUYvCJOF@aMWISG@GKVBY8LrBD5LJZwscweDmVm6nos4V4eni7fTmcXvfp/v36bnw8B/vRdy1ZUc1/ "Red – Try It Online")
Ungolfed:
```
f: func[s][
l: to-integer (length? s) ** 0.5
n: 0
foreach m parse s [
collect [
(r: []
repeat i l [ append r reduce [
'keep i * 2 - 1 charset [ not{Я} ]]])
r ]]
[v: copy ""
insert/dup v "." l - n: n + 1
print rejoin [v m v]]
]
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~88~~ ~~72~~ 71 bytes
```
S1`
+m`^(.)+¶(?>(?<-1>.)+)..(?!¶)
$&¶
P^'.m`^.(?=(..)*)(?<-1>.)*
P'.`.+
```
[Try it online!](https://tio.run/##K0otycxLNPz/P9gwgUs7NyFOQ09T@9A2DXs7DXsbXUM7IE9TT0/DXvHQNk0uFbVD27gC4tT1gOqAYrYaenqaWpowhVpcAep6CXra//8H@kU6hiRlRxgVe0eZeZb65@anlWekJ6amAQA "Retina – Try It Online") Edit: Saved ~~12~~ 13 bytes thanks to @MartinEnder. Explanation:
```
S1`
```
Split first character into its own line to get the ball rolling.
```
+m`^(.)+¶(?>(?<-1>.)+)..(?!¶)
$&¶
```
Chop each line two characters longer than the previous one.
```
P^'.m`^.(?=(..)*)(?<-1>.)*
```
Left-pad the first half of each line, effectively centring them.
```
P'.`.+
```
Right-pad all of the lines.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~21~~ 19 bytes
```
UB.F₂Lθ«P✂θXι²X⊕ι²↙
```
[Try it online!](https://tio.run/##NYw9D4IwFABn@BWE6TVBBwYHnTQuRPALB3Wr5QENpU9qgcH42ysOjneXnKi5EcSVcznaDRdNZajXBYTzkK38kkwAeddzg2ciCynqytbQMcaCt@9lvbLyaaS2kCspELooONKIBmQUxOwPiRYGW9QWC5DsV9j09jIaEJZbGnWKpZ3Mx7nT/ra@PJpr/NrdF0l/aKkc64pj6WaD@gI "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes by discovering `SquareRoot`. Explanation:
```
UB. Set the background fill to `.`
θ (First) input
L Length
₂ Square root
F « Loop over implicit range
ι ι Current value
⊕ Incremented
² ² Literal 2
X X Power
✂θ Slice the (first) input string
P Print without moving the cursor
↙ Move down left
```
[Answer]
# [Python 2](https://docs.python.org/2/), 84 bytes
```
s=input()
l=int(len(s)**.5)
for i in range(l):print s[i*i:][:i-~i].center(l*2-1,'.')
```
[Try it online!](https://tio.run/##JcqxDoMgEADQ3a9g445UorS2lcQvUQfTYHsJOQnQwaW/Tk3c3vDCnj8bm7IOU0kDcfhmwMofyuAdQ0KldIfVukVBgljEhd8OPNoQjyPSSIrsPFqqfzTrl@PsInhl6vYitcRSZGuut@7@ePbNKfkH "Python 2 – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), 123 bytes
```
import StdEnv
?n l#(a,b)=splitAt n l
|b>[]=[a: ?(n+2)b]=[a]
$s#s= ?1s
=[c++l++c\\l<-s&i<-[1..],c<-[repeatn(length s-i)'.']]
```
[Try it online!](https://tio.run/##FY1PC4IwHEDvfoofaqlMhTpFuOyvEXTruHaYc9lgLnErCPrsLbu99y6PK8G06x7NUwnomNROdv1jsHCxzUG/vFKDCmKW1gk2vZJ2Y2Es3qdeEYoJW0IZazRP6r9QLzSBwVDOjIcJR0ghxK9XVWRmKouMzPKcpnyEQfSCWR0roVt7B5PJJMojSt3FsnGNISTRZrvbHyo/nEzhuPCrdUTdl98Ua43LTme3f2vWSW5@ "Clean – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~73~~ 66 bytes
```
->s{(1..z=s.size**0.5).map{|q|s[q*q-2*q+1...q*q].center 2*z-1,?.}}
```
[Try it online!](https://tio.run/##RY5NT8JAGITv@yvebNToSjdtE4RLVT4ElEQ0ekBLY7bLLiWGwvK2IqX89lqpxNPMMzOHWafhttBeYV3j7tzhPPOQ4zxTjNm8fsEXYrXLTY6@YcZymbksJ7z0AZcqTtQaXJZZTu2G7/dFojD5kAIVggc@AaAzWvuVJ/kiKtfVD/ZXxzT6FTa@sd0Uzshs6joajO0qfX58a72Gn2MXh@9X9@losdSbaCaUrupWu9O9603oyekZ9JsT2rutchFySUlAyP8ProSMYLqEfB6v0iQvZ6UgHOgI1KLAwLGPrP1DHfwxUfG0@AE "Ruby – Try It Online")
-5 bytes: Return an array of strings instead of printing them
-2 bytes: Declare `z` in place instead of ahead of time
Ungolfed:
```
->s{
(1..z=s.size**0.5).map{|q| # Map the range [1,sqrt(s.size)]
s[q*q-2*q+1...q*q] # To the relevant portion of s,
.center 2*z-1, ?. # padded left and right with . characters
}
}
```
Declaring a variable `r=q-1` so that I can take `s[r*r...q*q]` saves exactly zero bytes.
Using `.center` instead of padding manually also saves zero bytes, but I like it better.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╚└÷2╬#►o┴X≡¥ΩåV∙¬?♥
```
[Run and debug it](https://staxlang.xyz/#p=c8c0f632ce23106fc158f09dea8656f9aa3f03&i=DfJ0vCq7G%0AABCDEF%22%24%25%26+G8%22F%40&m=2)
ASCII equivalent:
```
z;%|q{Hv,:/~]+F|Cm0]'.R
```
]
|
[Question]
[
Write a program that prompts the user for an even integer greater than 2.
Given Goldbach’s conjecture that every even integer greater than 2 can
be expressed as the sum of two primes, print out two prime numbers which, when
added together, provide the requested even number.
Edit: the program only has to print A PAIR of primes, not all.
For example:
4 : 2 + 2
6: 3 + 3
8: 3 + 5
10: 5 + 5 or 3 + 7
[Answer]
# APL, 34 or 44 bytes
The first version is **34** symbol long and is restricted to characters from the original single-byte APL charsets, such as the one still supported in Dyalog APL:
```
↑c/⍨n=+/¨c←,∘.,⍨v/⍨~v∊v∘.×v←1↓⍳n←⎕
```
Explanation:
```
n←⎕ ⍝ ask for a number, store as n
v←1↓⍳n ⍝ generate all integers from 2 to n
v∘.×v ⍝ compute the product table of any two such integers
v/⍨~v∊ ⍝ select those that don't appear in the product table
c←,∘.,⍨ ⍝ generate all possible pairs of these primes
n=+/¨c ⍝ check which pairs have a sum equal to n
↑c/⍨ ⍝ take the first that does
```
---
The second version is only **22** symbol long, because it exploits the `π` function to check for prime numbers, but that's only available in [NARS2000](http://www.nars2000.org/) which uses Unicode, so the byte count is **44** in UCS-2:
```
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
```
Explanation:
```
⎕ ⍝ ask for a number N
⍳ -1 ⍝ generate all naturals from 1 to N-1
(⍪,⌽) ⍝ arrange it into a table of all pairs of naturals with sum N
{∧/0π⍵} ⍝ check which pairs are made of all primes
2⍴(⌿⍨ ) ⍝ return the first pair that does
```
**Examples**
(⎕: is the prompt asking for a number)
```
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
4
2 2
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
6
3 3
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
8
3 5
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
124
11 113
```
[Answer]
# Python 2, ~~75~~ 71 bytes
```
n=input();k=m=1;p={0}
while{n-k,k}-p:m*=k*k;k+=1;p|={m%k*k}
print n-k,k
```
Test it on [Ideone](http://ideone.com/r6QiFE).
### How it works
We use a corollary of [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem):

At all times, the variable **m** is equal to the square of the factorial of **k - 1**; **k** starts at value **1** and **m** at value **0!² = 1**. The set **p** will consist of **0** and all prime numbers up to the current value of **k**.
In each iteration, we first check if both **n - k** and **k** belong to **p**, which is true if and only if the set difference of **{n-k, k}** and **p** is empty. If it is, the condition is falsy and the loop continues.
Note that **k > 0**, and **{n - k, k}** will satisfy the condition for some positive value of **n - k** (assuming that Goldbach's conjecture is true), so the **0** in **p** won't lead to false positives.
In the loop, we update **k** and **m**. The new value of **m** is **m × k² = (k - 1)!² × k² = k!²**, and the new value of **k** is **k + 1**, so **m = (k - 1)!²** still holds before and after the update.
Then, we perform set union to add the value of **m % k × k** to **p**. By the corollary of Wilson's theorem, this will add **1 × k = k** if **k** is prime and **0 × k = 0** if not.
When the loop ends, we print the last values of **n - k** and **k**, which will be primes with sum **n**.
[Answer]
# Ruby 2.0 (65)
```
require'prime'
n=gets.to_i
Prime.find{|i|p [i,n-i]if(n-i).prime?}
```
[Answer]
## PHP - 73 bytes
```
<?for(;@($n%--$$n?:$o=&$argv[1]>$$n=++$n)||${++$b}^${--$o};);echo"$b+$o";
```
Input is taken as a command line argument.
Sample usage:
```
$ php goldbach.php 7098
19+7079
```
[Answer]
## GolfScript ~~41~~ ~~33~~ 32
```
~(,2>.-1%]zip{{.,2>\{\%!}+,},!}?
```
Accepts command line argument e.g.
```
echo "14" | ruby golfscript.rb goldbach.gs
-> [2 12]
```
Finds all relevant partitions of the input number with:
```
(,2>.-1%]zip #If only zip were a one-character command! It is so often useful.
```
and then finds the first partition where no numbers are NOT prime with:
```
{np,!}? #For each partition, filter down to elements that are not prime, and only accept if there are no such results (since [] is falsey).
```
where the composite-checking block `np` is:
```
{.,2>\{\%!}+,}
```
this block filters down to all numbers that evenly divide a given number. If there are no such numbers (so the number is prime), the result is `[]`, which is falsey in GolfScript.
[Answer]
## perl 6: 69
```
$/=get;for grep &is-prime,^$/ {exit say $_,$_-$/ if ($/-$_).is-prime}
```
[Answer]
### R, ~~170~~ ~~112~~ 83 characters
```
a=scan();b=2:a;p=b[rowSums(!outer(b,b,`%%`))<2];q=p[(a-p)%in%p][1];cat(a,":",q,a-q)
```
Indented:
```
a=scan() #Take user input as a numeric
b=2:a
p=b[rowSums(!outer(b,b,`%%`))<2] #Find all primes from 2 to user input
q=p[(a-p)%in%p][1] #Check which a-p also belong to p and takes the first one
cat(a,":",q,a-q)
```
Usage:
```
> a=scan();b=2:a;p=b[rowSums(!outer(b,b,`%%`))<2];q=p[(a-p)%in%p][1];cat(a,":",q,a-q)
1: 72
2:
Read 1 item
72 : 5 67
```
**Old solution at 112 characters, for posterity**
```
a=scan();b=2:a;p=b[rowSums(!outer(b,b,`%%`))<2];w=which(outer(p,p,`+`)==a,T);cat(a,":",p[w[1,1]],p[w[1,2]])
```
Indented:
```
a=scan()
b=2:a
p=b[rowSums(!outer(b,b,`%%`))<2]
w=which(outer(p,p,`+`)==a,T) #Find the index of valid combinations
cat(a,":",p[w[1,1]],p[w[1,2]]) #Prints the first valid combination
```
[Answer]
# Python - 107
Basically an improvement on the second part of nutria's answer
(I ran this on 2.7 but I think it should also work for 3.x)
```
p=lambda x:all(x%i!=0 for i in range(2,x))
n=input()
for i in range(2,n-1):
if p(i)&p(n-i): print i,n-i
```
[Answer]
## JavaScript (ES6) (Regex), 105
```
a=/^(xx+?)(?!(xx+)\2+$)x*(?=\1$)(?!(xx+)\3+$)/.exec("x".repeat(prompt()));alert(a[1].length+"+"+a[0].length)
```
Now you have a regex that tests the Goldbach conjecture, which has low requirement on special features (basic back-reference support, positive and negative look-ahead).
This uses [`String.prototype.repeat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat), which is part of EcmaScript 6th edition proposal. Currently, this code only works on Firefox.
I really need a better language that has terse command when working with regex...
[Answer]
## Scala, ~~286~~ ~~192~~ ~~172~~ 148 chars
Not the fastest but it works. Call g(10) to obtain the list of goldbach pairs for 10.
```
def g(n:Int)={def p(n:Int,f:Int=2):Boolean=f>n/2||n%f!=0&&p(n,f+1)
s"$n : "+(for(i<-2 to n/2;j=n-i if p(i)&&p(j))yield s"$i + $j").mkString(" or ")}
```
Conversion to C++ is straightforward.
[Answer]
# C - 139 129 characters
```
a,b;i(x,y){return x>y?x%y?i(x,y+1):0:x>1;}main(){scanf("%i",&a);for(b=a/2;b-->1;)i(b,2)&&i(a-
b,2)&&printf("%i:%i+%i\n",a,b,a-b);}
```
[Answer]
### newLISP - 169 148 chars
```
(define(p n)(=(length(factor n))1))
(define(g n)(when(even? n)(for(i 3 n 2)
(and(p i)(p(- n i))(println n {: } i { }(- n i))))))
(g(int(read-line)))
```
includes the code to run it. The results are over-generous...
```
72: 5 67
72: 11 61
72: 13 59
72: 19 53
72: 29 43
72: 31 41
72: 41 31
72: 43 29
72: 53 19
72: 59 13
72: 61 11
72: 67 5
```
[Answer]
## Sage, 60
Similar in score and feel to [r.e.s.'s solution](https://codegolf.stackexchange.com/a/19512/2180), but I think it's different enough to post.
```
i=n=input()
while not{i,n-i}<set(primes(n)):i-=1
print i,n-i
```
[Answer]
## [Sage](http://www.sagemath.org/), ~~65~~ 62
```
n=input()
i=0
p=is_prime
while p(i)*p(n-i)==0:i+=1
print i,n-i
```
With the above in file `goldbach.sage`, execute it with Sage running in a terminal:
```
sage: %runfile goldbach.sage
```
Thanks to @boothby for the `p=is_prime` idea.
[Answer]
Haskell, 97C
```
g n=head[(a,b)|let q=p n,a<-q,b<-q,a+b==n]
p n=filter c[2..n]
c p=null[x|x<-[2..p-1],p`mod`x==0]
```
Explanation:
* `g` is the "goldbach" function. Calling `g n` gives you the pair of primes that add up to `n`.
* `p` is a function that generates a list of primes less than `n`.
* `c` is the prime checker function used to define `p`.
Example runs:
```
*Main> g 4
(2,2)
*Main> g 6
(3,3)
*Main> g 8
(3,5)
*Main> g 10
(3,7)
*Main> g 12
(5,7)
*Main> map g [4,6..100]
[(2,2),(3,3),(3,5),(3,7),(5,7),(3,11),(3,13),(5,13),(3,17),(3,19),(5,19),(3,23),(5,23),(7,23),(3,29),(3,31),(5,31),(7,31),(3,37),(5,37),(3,41),(3,43),(5,43),(3,47),(5,47),(7,47),(3,53),(5,53),(7,53),(3,59),(3,61),(5,61),(7,61),(3,67),(5,67),(3,71),(3,73),(5,73),(7,73),(3,79),(5,79),(3,83),(5,83),(7,83),(3,89),(5,89),(7,89),(19,79),(3,97)]
```
[Answer]
# Mathematica 56
This returns all of the solutions for the input integer.
```
Select[Tuples[Prime@Range@PrimePi[n = Input[]], 2], Tr@# == n &]
```
For example, when 1298 is input…
>
> {{7, 1291}, {19, 1279}, {61, 1237}, {67, 1231}, {97, 1201}, {127,
> 1171}, {181, 1117}, {211, 1087}, {229, 1069}, {277, 1021}, {307,
> 991}, {331, 967}, {379, 919}, {421, 877}, {439, 859}, {487,
> 811}, {541, 757}, {547, 751}, {571, 727}, {607, 691}, {691,
> 607}, {727, 571}, {751, 547}, {757, 541}, {811, 487}, {859,
> 439}, {877, 421}, {919, 379}, {967, 331}, {991, 307}, {1021,
> 277}, {1069, 229}, {1087, 211}, {1117, 181}, {1171, 127}, {1201,
> 97}, {1231, 67}, {1237, 61}, {1279, 19}, {1291, 7}}
>
>
>
As written, it returns each solution twice.
```
Union[Sort/@ %]
```
>
> {{7, 1291}, {19, 1279}, {61, 1237}, {67, 1231}, {97, 1201}, {127,
> 1171}, {181, 1117}, {211, 1087}, {229, 1069}, {277, 1021}, {307,
> 991}, {331, 967}, {379, 919}, {421, 877}, {439, 859}, {487,
> 811}, {541, 757}, {547, 751}, {571, 727}, {607, 691}}
>
>
>
[Answer]
# Julia, ~~50~~ 49 bytes
```
~=primes;n=ARGS[]|>int
(n-~n)∩~n|>extrema|>show
```
[Try it online!](http://julia.tryitonline.net/#code=fj1wcmltZXM7bj1BUkdTW118PmludAoobi1-biniiKl-bnw-ZXh0cmVtYXw-c2hvdw&input=&args=NTAw)
If a function were acceptable, the code could be shortened to **32 bytes**:
```
~=primes
!n=(n-~n)∩~n|>extrema
```
### How it works
`~=primes` creates an alias for the built-in **primes** function which returns a list of all prime numbers up to its argument. `n=ARGS[]|>int` parses the first command-line argument as saves it in **n**.
To find a suitable pair of primes, we first compute the aforementioned prime range with `~n`. Then, `n-~n` yields all differences of these primes and **n**.
By intersecting (`∩`) the result with the prime range itself, we make sure that the remaining primes **p** are such that **n - p** is also a prime.
Finally, `extrema` takes the lowest and highest prime in the intersection, so their sum must be **n**.
[Answer]
# Julia, 62 Chars (85 with prompt)
```
julia> g(n)=collect(filter((x)->sum(x)==n,combinations(primes(n),2)))
g (generic function with 1 method)
julia> g(88)
4-element Array{Array{Int64,1},1}:
[5,83]
[17,71]
[29,59]
[41,47]
```
[Answer]
## [GTB](http://timtechsoftware.com/gtb "GTB"), 31
*For your TI-84 Calculator*
```
`A:.5A→B@%;A,4)4$~B+1,B-1#~B,B&
```
No prime built-ins.
**Example runs**
```
?4
2
2
?6
3
3
?8
3
5
?10
5
5
```
[Answer]
# JavaScript, ~~139~~ ~~137~~ 136
```
a=prompt();function b(n){for(i=2;i<n;i++)if(n%i<1)return;return 1}for(c=2,r=1;c<a&&r;c++)if(b(c)&&b(a-c))alert(a+": "+c+" + "+(a-c)),r=0
```
[Answer]
## Python 3 - ~~150~~ 143 characters
Old version (150 characters):
```
p=lambda n:0 in[n % i for i in range(2,n)]
n=int(input())
[print('%d+%d'%(a, b))for b in range(2,n)for a in range(2,n)if not(a+b!=n or p(a) or p(b))]
```
New version (thanks to ProgramFOX):
```
p=lambda n:0 in[n%i for i in range(2,n)]
n=int(input())
[print('%d+%d'%(a,b))for b in range(2,n)for a in range(2,n)if not((a+b!=n)|p(a)|p(b))]
```
It prints every combination, for example:
4
2+2
10 7+3 5+5 3+7
[Answer]
# q [116 chars]
```
y where all each{{2=count where 0=(x mod)each til x+1}each x}each y:{a where x=sum each a:a cross a:til x}"I"$read0 0
```
No inbuilt function to find prime number.
Input
```
72
```
Output
```
5 67
11 61
13 59
19 53
29 43
31 41
41 31
43 29
53 19
59 13
61 11
67 5
```
[Answer]
## Python - 206
A little late to the party but I am practicing my golfing skills.
I actually coded this before I found this question! So mine doesn't include the beautiful lambda that the other Python solutions use.
```
import math
def p(n):
if n%2==0&n>2:return False
for i in range(3,n):
if n%i==0:return False
return True
X=int(input())
for i in range(2,X):
if p(i)&p(X-i):print i,X-i;break
```
[Answer]
# J - ~~35~~ 32 char
"Prompt the user" is the bane of every J golfer. There go all my hard-earned characters!
```
p:(n,n)#:i.&n,+/~p:i.n=:".1!:1]1
```
Explained:
* `".1!:1]1` - Read in a string (`1!:1`) from input (file handle `1`) and convert it to a number (`".`).
* `p:i.n=:` - Assign this number to the variable `n`, and then take the first `n` primes.
* `+/~` - Make an addition table, `n` wide and `n` high.
* `i.&n,` - Turn the table into a single list, and then find the index of the first occurrence of `n`, which exists if Goldbach's conjecture is true.
* `p:(n,n)#:` - Retrieve the row and column from the index, and take the corresponding primes.
Usage:
```
p:(n,n)#:i.&n,+/~p:i.n=:".1!:1]1
666
5 661
p:(n,n)#:i.&n,+/~p:i.n=:".1!:1]1
1024
3 1021
```
Had the prompt not been a requirement, here's a 25 character verb:
```
(,~p:@#:]i.~&,+/~@:p:@i.)
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (non-competing)
```
_ÆRfÆR.ị
```
[Try it online!](http://jelly.tryitonline.net/#code=X8OGUmbDhlIu4buL&input=&args=NTAw) or [verify all test cases](http://jelly.tryitonline.net/#code=X8OGUmbDhlIu4buLCsOH4oKsRw&input=&args=NCwgNiwgOCwgMTA).
### How it works
```
_ÆRfÆR.ị Main link. Argument: n (integer)
ÆR Prime range; yield all primes in [1, ..., n].
_ Subtract all primes from n.
fÆR Filter; intersect the list of differences with the prime range.
.ị At-index 0.5; yield the last and first element.
```
[Answer]
Python3 version of [this one](https://codegolf.stackexchange.com/a/19881/110481) -110 bytes
```
p=lambda x:all(x%i!=0 for i in range(2,x))
n=int(input())
for i in range(2,n-1):
if p(i)&p(n-i): print(i,n-i)
```
and a super golfed version:
```
exec(bytes('㵰慬扭慤砠愺汬砨椥㴡‰潦湩爠湡敧㈨砬⤩渊椽瑮椨灮瑵⤨潦湩爠湡敧㈨測ㄭ㨩 晩瀠椨☩⡰⥩›牰湩⡴Ⱪ⥩','u16')[2:])
```
[Answer]
# SQL, ~~295~~ 284
In postgresql:
```
create function c(c int) returns table (n int, m int) as $$
with recursive i(n) as
(select 2 union all select n+1 from i where n<c),
p as (select * from i a where not exists
(select * from i b where a.n!=b.n and mod(a.n,b.n)=0))
select * from p a, p b where a.n+b.n=c
$$ language sql;
```
Should be able to do it in half the space though, if it weren't for things like "no left outer join in recursion", "no subquery in recursion"...
Here's the output:
```
postgres=# select c(10);
c
-------
(3,7)
(5,5)
(7,3)
(3 rows)
postgres=# select c(88);
c
---------
(5,83)
(17,71)
(29,59)
(41,47)
(47,41)
(59,29)
(71,17)
(83,5)
(8 rows)
```
[Answer]
## Batch - 266
```
@echo off&setLocal enableDelayedExpansion&for /L %%a in (2,1,%1)do (set/aa=%%a-1&set c=&for /L %%b in (2,1,!a!)do set/ab=%%a%%%%b&if !b!==0 set c=1
if !c! NEQ 1 set l=!l!%%a,)&for %%c in (!l!)do for %%d in (!l!)do set/ad=%%c+%%d&if !d!==%1 set o=%%c + %%d
echo !o!
```
Set out neatly -
```
@echo off
setLocal enableDelayedExpansion
for /L %%a in (2,1,%1) do (
set /a a=%%a-1
set c=
for /L %%b in (2,1,!a!) do (
set /a b=%%a%%%%b
if !b!==0 set c=1
)
if !c! NEQ 1 set l=!l!%%a,
)
for %%c in (!l!) do for %%d in (!l!) do (
set /a d=%%c+%%d
if !d!==%1 set o=%%c + %%d
)
echo !o!
```
[Answer]
## Perl 5, 58 bytes
57, plus 1 for `-nE`
```
/^(11+?)(?!(11+)\2+$)1*(?=\1$)(?!(11+)\3+$)/;say for$1,$&
```
Input and output are in unary. Example:
```
$ perl -nE'/^(11+?)(?!(11+)\2+$)1*(?=\1$)(?!(11+)\3+$)/;say for$1,$&'
1111111111
111
1111111
```
[Hat-tip.](/a/19528)
[Answer]
# Oracle SQL 11.2, 202 bytes
```
WITH v(x,y,s)AS(SELECT LEVEL,LEVEL,0 FROM DUAL CONNECT BY LEVEL<=:1 UNION ALL SELECT x,y-1,s+SIGN(MOD(x,y))FROM v WHERE y>1),p AS(SELECT x FROM v WHERE x-s=2)SELECT a.x,b.x FROM p a,p b WHERE:1=a.x+b.x;
```
Un-golfed
```
WITH v(x,y,s) AS
(
SELECT LEVEL,LEVEL,0 FROM DUAL CONNECT BY LEVEL<=:1
UNION ALL
SELECT x,y-1,s+SIGN(MOD(x,y))FROM v WHERE y>1
)
,p AS (SELECT x FROM v WHERE x-s=2)
SELECT a.x,b.x
FROM p a,p b
WHERE :1=a.x+b.x;
```
]
|
[Question]
[
Given an undirected graph, find out if it is a tree.
A tree is an undirected graph in which there is exactly one path between any two vertices. In other word, the graph is both acyclic and connected.
## Input
You can take input in any reasonable format. Here are some example formats:
* an adjacency matrix, e.g., `[[0,1,1,0],[1,0,1,1],[1,1,0,0],[0,1,0,0]]`;
* an adjacency list, e.g., `{1:[2,3],2:[1,3,4],3:[1,2],4:[2]}`;
* an edge list, e.g., `[(1,2),(1,3),(2,3),(2,4)]`;
* a built-in graph object, e.g., `Graph[{1,2,3,4},{1<->2,1<->3,2<->3,2<->4}]` in Mathematica.
All the above examples represent the following graph, which is [not a tree](https://codegolf.stackexchange.com/users/66104/not-a-tree):
```
1---2---4
\ /
3
```
Here I use numbers `1,2,3,4` to represent the vertices. You may also use, for example, `0,1,2,3`.
You may assume that:
* The graph is non-empty.
* The graph has no loop (an edge connecting a vertex with itself) or multi-edge (two or more edges that connect the same two vertices).
* Each vertex is connected to at least one other vertex.
## Output
A value representing whether the graph is a tree. 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 take inputs as edge lists.
### Truthy
```
[(1, 2)]
[(1, 2), (2, 3), (2, 4)]
[(1, 2), (2, 3), (3, 4), (4, 5)]
[(1, 2), (1, 3), (2, 4), (2, 5)]
[(1, 3), (1, 6), (1, 7), (2, 3), (2, 5), (4, 7)]
```
### Falsy
```
[(1, 2), (3, 4)]
[(1, 2), (1, 3), (2, 3), (2, 4)]
[(1, 2), (1, 3), (2, 3), (4, 5)]
[(1, 3), (1, 5), (2, 3), (3, 4), (4, 5)]
[(1, 2), (3, 4), (3, 5), (4, 5), (4, 7), (6, 7)]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ ~~6~~ ~~5~~ 4 bytes (thanks @Jonathan Allan!)
```
ṖÆḊ’
```
[Try it online!](https://tio.run/##y0rNyan8///hzmmH2x7u6HrUMPP////R0YY6BkBoGKsTrWuoA@YAmQY6YI6uIZgN5hnExgIA "Jelly – Try It Online")
```
Ṗ Delete the last row of the input matrix
ÆḊ Compute sqrt(det(A A^T)), where A is the result of the previous step
’ Decrement
```
Accepts the [oriented incidence matrix](https://en.wikipedia.org/wiki/Incidence_matrix) of the graph. Based on [Kirchhoff's Theorem](https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem), the fact that a graph has exactly one [spanning tree](https://en.wikipedia.org/wiki/Spanning_tree) if and only if it's a tree graph, and the fact that the [Laplacian matrix](https://en.wikipedia.org/wiki/Laplacian_matrix) of a graph can be easily computed from its oriented incidence matrix as follows: $$L=BB^T$$ where *L* is the Laplacian matrix and *B* is the oriented incidence matrix. Outputs a truthy value if the graph is ***not*** a tree, and a falsy value if it is.
After deleting the last row from the incidence matrix (`Ṗ`) and multiplying by its transpose, the result will be equal to the Laplacian matrix with the last row and last column deleted: exactly what we need. `ÆḊ` transposes, multiplies, *and* computes the determinant for us: perfect! It also takes the square root of the result, but for reasons I'll explain later, this isn't a problem.
The determinant of the matrix product mentioned previously, the square of the result of all but the last step, is the number of spanning trees of the graph. This is 0 for a non-fully-connected graph, 1 for a tree, and 2 or more for a fully-connected non-tree graph. Now, I mentioned that `ÆḊ` takes the square root of the determinant. Is this a problem? It isn't, since the square root of 0 is 0, the square root of 1 is 1, and the square root of a number greater than 1 will also be a number greater than 1. Therefore, after decrementing (`’`), the result will be falsy (0) if and only if the determinant is 1: that is, if and only if the graph is a tree graph.
If the number of nodes happens to be one greater than the number of edges, deleting the last row will result in a square matrix. In this case, `ÆḊ` will simply compute the determinant, so won't this lead to incorrect outputs? It won't, since for a square matrix *A*: $$\sqrt{\det(A A^T)} = \sqrt{\det(A) \det(A^T)} = \sqrt{\det(A) \det(A)} = |\det(A)|$$
Therefore, the result will still be exactly what we need (since the determinant of the matrix in question is guaranteed to be non-negative).
[Answer]
# [Python](https://www.python.org) NumPy, 49 bytes
```
lambda M:M.sum()<2*len(M)*(M**0-M/M.size).I.all()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVA9T8MwEBVrfsWNtuWEJmlaVNGBkcEbW-lglEREsh0rH4j2r7BUQjDyf-DXcE1cmkYZmN7dved37_z2aXfNc2kO7_n68aNtcv_mO1RSP6USxEoEdasJvY2YygwRlBHB2MwX10gU-4wG94FUilD38KvQtqwaMK22O5A1GOvlZQUKCgOlRYsZXXkAOFhD9iIVUfTYCmyNDfZZVdYkYhustXxFcssL03QSHMk0DWRDBCcMu6aSprZlnaHMDznl4dBKo7B3KTReILgIHmgnsBVakhyPcakPP1d3GxJyiOjWcwUHEnGIHc4nifhIIM45JBeCcPiyxz9B7AQLh8vRqsQ5Li8c43GGwYrpkGPBfCJD8q9rTkR8DncOibjowvZf-Qs)
Takes adjacency matrix as input.
### How
We check two things:
1. number of edges is number of vertices - 1
2. graph is connected
To check 2 we use
1. powers M^n of the adjacency matrix describe paths of length n
2. the graph will be connected iff the sum I + M + M^2 + M^3 + ... has no zero elements. (We can always scale M so that this sum converges.)
3. the sum in 2 is a geometric series and can be written as (I-M)^-1
# [Python](https://www.python.org) NumPy, 43 bytes (@Command Master)
```
lambda M:M.sum()<3*len(M)*(M**len(M)).all()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVBLTsMwFBTbnOIt7dSNml-LKorEAbxjV7owSiIi2Y6VDyJchU0lBPfgGHAaXhKXplEWrOZ9ZuaN_fZp2vqp0Mf3bPfw0dTZ8vp7IYV6TATwLfeqRhF6E7oy1YRTl3DXltQTUhJqJV-5MkVZg26UaUFUoI2TFSVIyDUUBhUrunUAcLCD9FlIImnXcmy18V7TsqhI4O6xVuIFlweW67qn4EgkiSdqwhlxsatLoStTVCnSlj6jzB9bKSQOLrnC7Jxx754uulHaomLIfruivcaUeIVk3Wh4yPHn6m5PfAYBPTi2YEACBqHFaHYRdgvEiEF8QfDHygH_CKElrC1uJqdi67i5cAynGUYn5kNOCdFMhvhfrzktwnO4c0jEdR92-Mpf)
This requires the main diagonal to be set in the input.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 10 bytes
```
TreeGraphQ
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6QoNdW9KLEgI/B/QFFmXolDmgOYG11taKNrZ1Qby4VNWMcISBqDSRP8SoxBSnRMgKQpLoWGCLPAJA6FxmCFZmDSHMkBpmDTzYGasBtvjM@RCLsJ@AZZoQkhR5oS73mIEmO4P6C@0TGD@uk/AA "Wolfram Language (Mathematica) – Try It Online")
So I find a builtin in Mathematica... (my first Mathematica answer btw :D)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
```
ZLœεIk€à{āQ}à
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yufo5HNbPbMfNa05vKD6SGNg7eEF//9HRxvqKBjH6iiAaDMobQ6ijaDiQNoURJuAxGMB "05AB1E – Try It Online")
-1 thanks to @Kevin Cruijssen
Takes input as an edge list, with vertices indexed 1,2,3,...,n.
## Explanation
Uses the fact that a graph is a tree iff there's a way to order its vertices such that all but one appear exactly once as the maximum value in some edge.
Proof:
* The minimum value in each connected component won't appear, so if there's only one value missing there must be a single connected component.
* If there's a cycle there must be more then \$n-1\$ edges, so the list of the maximum value in each won't be of length \$ n-1 \$.
* If the graph is a tree, its preorder scan would satisfy the condition.
```
Z push the maximum value in the edge list, the size of the graph
L push the list [1, 2, ..., n]
œ push all permutations of it
ε map each permutations to:
I push the input
k find the index of each vertex in each edge in the given permutation, 0-based
ۈ find the maximum value in each pair
{ sort that list
ā push the list [1, 2, ..., len(arr)]
Q and compare it to the sorted list of indices
}
à take the maximum value - return 1 if any of the values are 1, else 0
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 26 bytes
```
{&//{|/'x*\:x}/x&~2-/3-/x}
```
[Try it online!](https://ngn.codeberg.page/k#eJx9jtFOgzAUhu95inNhJtXVUgpb0hN9ESRZs1FFUQw08RBgz26HXrCN2OS/6Zf//J/V/UqIfhC3dPesaRS0OsZcKC5oDAKn+5usOzbaAuGufsdwZ01ZIWGHDcvHwOiehnvS4eMg1oLYQ4aoUeaCuBxBVGXroLZQHF6KFvgTmMOb2Ref+w4+jGtKgvC7dK/QFpXlVV1/tSxwmQnXEmIG1y+XE/YUY1A+CfsHK0gwgZQtYPnb9lnAyuONz/ZvJPVXtmzWVhe7Uzu6OH6ut4DP1KLZdnplP2ufvtWkNGnh5qQW/QCH/mlV)
The input is an adjacency matrix with 1s along the diagonal and symmetric with respect to transposition.
The condition tested is: the total number of 1s in the adjacency matrix is \$3n-2\$ and its transitive closure consists only of 1s.
`{` `}` function with implicit argument `x`
`3-/` subtract all rows of the matrix from the constant 3. The 3 will be broadcast to match the length of a row, so it's effectively \$3n\$. The result is a vector.
`2-/` subtract the items of the vector from the constant 2. The result is a scalar: \$(\sum\_i\sum\_j A\_{ij})-3n+2\$.
`~` "not", i.e. "is equal to 0?"
`x&` "and" with the original matrix, i.e. zero it if the first condition is not true
`{|/'x*\:x}/` transitive closure
* `{` `}/` repeat until convergence
* `x*\:x` a 3d array of the matrix's row-by-column products
* `|/'` boolean or-sum of each
`&//` boolean and over the entire matrix
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
ZyGRzQ=GYeh
```
This uses the same approach as [loopy walt's Python/Numpy answer](https://codegolf.stackexchange.com/a/251195/36398).
Input is a square logical matrix, where entries `T` and `F` denote `true` and `false` respectively. This represents the adjacency matrix of the graph.
Output is a truthy/falsy value, specifically a non-empty array of zeros and ones, which is truthy [if and only if](https://codegolf.stackexchange.com/a/95057/36398) if it does not contain any zero.
[Try it online!](https://tio.run/##y00syfn/P6rSPagq0NY9MjXj//9oNwU3hRAFCBlirQDjgoWsQWJgITcI1w0JghWjyIYgy1vDTQVzYwE) Or [verify all test cases](https://tio.run/##dVG9CsIwEN77FLdldQ/iItdZucVKwQ5Ch7poBSv47GlM0t5djJTAd7nc93O9dePgLq6Z6uP7sK1P197tDN2fYz@Z6mOwGx4etPvmRe6MQBYIsK2@EBAwlP74@/UmAX7Ez0SfIkxFhCjIBX0SSFz@s7Bh5lUkDKKcQNaKXEyBluFiQHVJ9tkH6mhW@kBOonJY4gjFHdHPjijnLexIrU7N5bulzNP/mIsCcan@HJac5e6CEsw) (footer includes truthiness/falsihood test)
### How it works
```
Zy % Implicit input: square matrix. Size: gives a two-element row vector
GR % Push input again. Take the upper triangular part
zQ % Number of nonzeros. Add 1
= % Are they equal? Element-wise
G % Push input again
Ye % Logical version of matrix exponential. This computes A*e^A, where A
% is the adjacency matrix, replacing non-zero entries by 1 (and
% avoiding numerical precision issues). The result indicates for each
% node which nodes it is connected to
h % Concatenate horizontally. This reshapes into a row vector (the two
% concatenated arrays are a row vector and a square matrix). Implicit
% display
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
->l{*r=1;l.all?{|a,b|(a==l||r!=r-=[l=a])&&r!=r|=[b]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nWqvI1tA6Ry8xJ8e@uiZRJ6lGI9HWNqempkjRtkjXNjrHNjFWU00NxKuxjU6Kra39X6CQFh0dbahjFKsTbaRjDCSNdUxiY2O5kCWwCEHUGiLp@A8A "Ruby – Try It Online")
Assume the list is sorted.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
WΦ⁻θυ∨¬υ⁼¹ΣEκ⊙υ№ξμ⊞υ⊟ι¬⁻θυ
```
[Try it online!](https://tio.run/##TY07C8MwDIT3/gqNMqhD30OnUtotbaBjyGBCIKaOnThWH7/etSBDtXzi7rhrOh0ar21K787YFvBqbGwDFsbxhCMBK4J7wJuPKO9lZG0nXBE8uMdCD/gkOLkvMsHZs4v4IejVfFDy1IlV@gGNUsdFGUzOSNvfQjZSqipp3eQN4X7mQbie9cydcCt6Xafly/4A "Charcoal – Try It Online") Link is to verbose version of code. Takes an edge list as input and outputs a Charcoal boolean, i.e. `-` for a tree, nothing if not. Identifies non-trees with multi-edges and non-trees with loops if they are not the last edge on the list. Explanation:
```
WΦ⁻θυ∨¬υ⁼¹ΣEκ⊙υ№ξμ
```
Except on the first iteration, only consider those edges where exactly one vertex has been previously visited. While at least one such edge exists...
```
⊞υ⊟ι
```
... mark one of those edges has having been visited.
```
¬⁻θυ
```
Check that there are no unvisited edges left. An edge may remain unvisited if it is part of a cycle (in which case both of its vertices will have become visited) or if it is disconnected (in which case neither of its vertices were visited). If neither holds then the original graph was a tree.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
LÞefA?LT*?f∑>
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiTMOeZWZBP0xUKj9m4oiRPiIsIiIsIltbMSwgMV0sIFsxLCAxXV1cbltbMSwgMSwgMCwgMF0sIFsxLCAxLCAxLCAxXSwgWzAsIDEsIDEsIDBdLCBbMCwgMSwgMCwgMV1dXG5bWzEsIDEsIDAsIDAsIDBdLCBbMSwgMSwgMSwgMCwgMF0sIFswLCAxLCAxLCAxLCAwXSwgWzAsIDAsIDEsIDEsIDFdLCBbMCwgMCwgMCwgMSwgMV1dXG5bWzEsIDEsIDEsIDAsIDBdLCBbMSwgMSwgMCwgMSwgMV0sIFsxLCAwLCAxLCAwLCAwXSwgWzAsIDEsIDAsIDEsIDBdLCBbMCwgMSwgMCwgMCwgMV1dXG5bWzEsIDAsIDEsIDAsIDAsIDEsIDFdLCBbMCwgMSwgMSwgMCwgMSwgMCwgMF0sIFsxLCAxLCAxLCAwLCAwLCAwLCAwXSwgWzAsIDAsIDAsIDEsIDAsIDAsIDFdLCBbMCwgMSwgMCwgMCwgMSwgMCwgMF0sIFsxLCAwLCAwLCAwLCAwLCAxLCAwXSwgWzEsIDAsIDAsIDEsIDAsIDAsIDFdXVxuW1sxLCAxLCAwLCAwXSwgWzEsIDEsIDAsIDBdLCBbMCwgMCwgMSwgMV0sIFswLCAwLCAxLCAxXV1cbltbMSwgMSwgMSwgMF0sIFsxLCAxLCAxLCAxXSwgWzEsIDEsIDEsIDBdLCBbMCwgMSwgMCwgMV1dXG5bWzEsIDEsIDEsIDAsIDBdLCBbMSwgMSwgMSwgMCwgMF0sIFsxLCAxLCAxLCAwLCAwXSwgWzAsIDAsIDAsIDEsIDFdLCBbMCwgMCwgMCwgMSwgMV1dXG5bWzEsIDAsIDEsIDAsIDFdLCBbMCwgMSwgMSwgMCwgMF0sIFsxLCAxLCAxLCAxLCAwXSwgWzAsIDAsIDEsIDEsIDFdLCBbMSwgMCwgMCwgMSwgMV1dXG5bWzEsIDEsIDAsIDAsIDAsIDAsIDBdLCBbMSwgMSwgMCwgMCwgMCwgMCwgMF0sIFswLCAwLCAxLCAxLCAxLCAwLCAwXSwgWzAsIDAsIDEsIDEsIDEsIDAsIDFdLCBbMCwgMCwgMSwgMSwgMSwgMCwgMF0sIFswLCAwLCAwLCAwLCAwLCAxLCAxXSwgWzAsIDAsIDAsIDEsIDAsIDEsIDFdXSJd)
Takes input as an adjacency matrix with 1s on the main diagonal. Port of @loopy walt's second answer from @Command Master, upvote that!
```
LÞefA?LT*?f∑>
L # Get the length of the input
Þe # Matrix exponentiate it to that
f # Flatten
A # Are all non-zero? Call this X
?L # Get the length of the input again
T # Triple it (multiply by 3)
* # Multiply this by X. Call this Y
?f∑ # Get the flattened sum of the input
> # Is Y greater than this?
```
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
```
æ*LȦ×L×3>ẎS$
```
[Try it online!](https://tio.run/##y0rNyan8///wMi2fE8sOT/c5PN3Y7uGuvmCV/0f3OBxuf9S05uikhztnAGkgygJRDXMUbGwVHjXMjfz/Pzo62lBHwTBWRwFCgxhglo6CARDBxCEIxDOA8QwQPAMsOtE1G6DoQDXCAN0GhBiysRhuMkBogvMMMFyGLoDiWhRRDC9iDwcDFB8iOxdmOrp1KIYYICFDdGEsTsTmbbSQQ@OhhRlmJBoSEYmGeCIRW6xicw26g5BsQgtnNEfiShuGuNKGAXq04BBGMRGfsCFB1Xj9DHdiLAA "Jelly – Try It Online")
-1 byte thanks to Jonathan Allan.
Same.
```
æ*LȦ×L×3>ẎS$
æ* - Matrix exponentiate the input to...
L - Its length.
Ȧ - After flattening, are they all non-zero?
×L - Multiply this by the length of the input.
×3 - Multiply by 3.
> - Is this greater than...
ẎS$ - The flattened sum of the input?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/code-page)
```
ŒPḊFQLƊ_LƊ€ȧ/’
```
A monadic Link that accepts an edge list and yields a zero (falsey) if a tree or a non-zero integer (truthy) if not a tree.
**[Try it online!](https://tio.run/##y0rNyan8///opICHO7rcAn2OdcUD8aOmNSeW6z9qmPn////oaEMdo1idaCMdYyBprGMCJA2BZCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opICHO7rcAn2OdcUD8aOmNSeW6z9qmPn/UcOcvPwShUSFkqLU1EcNc4F8KOtwuz1QWeT//9HRGoY6CkaasVw6UJaOgoaRjoIxlDbBLmMMkgHSJjoKpqgqDJH1QmiECmOoCjMobY5mmynUTHNUM40x3IFkCw6XoqswweYOU@L8BJMxRrgQ4VIgbQZxcSwA "Jelly – Try It Online").
### How?
We know that (a) the number of edges must be exactly one less than the number of vertices and (b) there must be no sub-graph (including the whole graph, but excluding the empty graph) which has the same number of vertices and edges. So this finds the difference between vertex count and edge count for every non-empty set of edges, checks that all are non-zero and that the result for the full set of edges is \$1\$.
```
ŒPḊFQLƊ_LƊ€ȧ/’ - Link: list of edges
ŒP - get the powerset of the edges (N.B. full-set is rightmost)
Ḋ - dequeue (removes the empty set)
€ - for each:
Ɗ - last three links as a monad:
Ɗ - last three links as a monad:
F - flatten the current set of edges
Q - deduplicate -> distinct vertices used by this set of edges
L - length -> vertex count
L - length of this set of edges -> edge count
_ - subtract -> vertex count - edge count
/ - reduce by:
ȧ - logical AND -> 1 if a tree, 0,2,3,... otherwise
’ - decrement -> zero (falsey) if a tree non-zero (truthy) otherwise
```
---
If one takes an adjacency matrix with all vertices also identified as self-connected \$12\$ bytes is possible - see [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)'s [answer](https://codegolf.stackexchange.com/a/251220/53748).
---
If one takes the Laplacian matrix then \$6\$ bytes is possible - see [Alex](https://codegolf.stackexchange.com/users/21775/alex)'s [answer](https://codegolf.stackexchange.com/a/251223/53748).
[Answer]
# [Python](https://www.python.org), ~~108~~ ~~102~~ 95 bytes
```
f=lambda g,s=0,v={0}:(v.add(s),[f(g,c)for c in g[s]-v],len(v)==len(g)==sum(map(len,g))//2+1)[2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lVJNToQwFI5bTvESF9PGDsLgTMwknMIlIaZCW0mgQ9pCMpnMSdzMRm_jAfQ0tlBGHN3YBa_0-3nfa_ry1u7N806eTq-d4cv7j0ee1rR5KikIotOI9OkhOm5RH9KyRBqTjCNBCsx3CgqoJIhM58s-JzWTqMdp6qqwVXcNamiL7D8RGN_erm5inK1y3-a9atqdMqD3mlgb3bLCBM60riRzvhYItSkruQ3ArlZV0iCOWE9r5DgY42BArkExzQyUjNOuNkCVGM69aagrIanpFEMchy1VtGGGKZ0t-kUeelFY1IwqhP8vdLcS4XGo0-fVQ3aIjwTsleXBtCWwIpC4bTx-fkDDkcct787VZKR41LISD0QXLlawJrCZay17IGzO1GgymTUeuzjZZasp6-QT_yLM0VncKcAZvxjqrwSTxNbvMZJzfIuvj_7FfAE)
Program to convert edge list to adjacency list can be found [here](https://ato.pxeger.com/run?1=jVBBboMwEFSufkMPK_ViSxCVAElVqYf-oPcoqizsUFfBINug8JZeuLSPymtqgxsC4hAka1Y7s7PDfv9WrfksZdf91OYYPl9WD4_wrspc0QJMCVkpG64MZxCFQjJ-thVnOYeT0MYJnq5tyr5oxmXW9hxCoqhKZUC3GqFjqWxXchDSNdbaMCFfENjPuWl4Bd7QE3Yagvq-tbPdveYGE3DzH25YUZlzXNCzfZXDYDAghBz6MaesA2icuGeGLd5xX0MI0WFNGcONK8mEbUa2HtierpSQBlsBGY7kb9VdVm97HAWwsbt9EQDeBBB7TBaJ2BEWkwDSiSC6nRzwKoi9YOtxN1uVesfdxDGeZ7hZsRxyLkgWMqR3_c0_EY_hxpAWt33Y4ZR_)
[Answer]
# JavaScript (ES6), 69 bytes
Expects a 0-indexed adjacency list. Returns *false* for a tree, or *true* otherwise.
```
a=>a.some(g=(b,i,m,k=i/i)=>b.map(j=>k-=m^(q=m|1<<i)&&!g(a[j],j,q))|k)
```
[Try it online!](https://tio.run/##jY/BjoIwEIbvPMXsxbRJYaOIHrDc9imabtIqaKFQFd3L4rOzFeqKRBMP7Uz6f//M31z8iHp9VPuTX5lN2ma0FTQRQW3KFG0pkkSRkhRUfSpMExmUYo9ymhQ@Lb/RgZbNdLVSeDL52CLBck5ycsC4KXAbMw@AsSmBGefk3hNgMwKhq/NXWnjVbJ0TiMbMdOjv65AJHbNwdTnaGbm5y95TnbV@nB8@yTXY@TL7mJk/zxW9@8@bFt4z37Pbuuj@4HEvyMzxS6x3SANN4NcOURnSuOsAdHoCscmBAuNx//JvQEwQkBx3PhC@H4O8XsgamODW45qmsW4c7M/1DknsAHkD5CMgLHDB/a61qWqj00CbLcquLtwJF3tSXacu45By@gW3fw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = adjacency list
a.some( // for each entry in a[]:
g = ( // invoke the recursive function g taking:
b, // b[] = adjacent vertices at the current position
i, // i = current position
m, // m = bitmask of visited vertices
k = i / i // k = counter initialized to 1 if i > 0,
) => // or to NaN if i = 0
b.map(j => // for each vertex j in b[]:
k -= // decrement k if:
m ^ ( // i was not already visited, i.e. m is not equal
q = // to the new bitmask q where
m | 1 << i // i is marked as visited
) && // and
!g( // the result of this recursive call is 0:
a[j], // list of adjacent vertices at the new position
j, // new position
q // updated bitmask of visited vertices
) // end of recursive call
) | k // end of map(); return k, which is 0 if one and only
// one path to the root was found, or still NaN if the
// root was already reached, or non-zero'ish otherwise
) // end of some()
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 59 bytes
```
c=>c[(g=(i,p)=>c[i].every(j=>j==p||c[t++]&&g(j,i)))(t=1)*t]
```
[Try it online!](https://tio.run/##nVFNb4JAEL3zK@aEs3XdFBFNbNbevDU99LjZNBRXAlEgLrES8bfT5aPVWLWmJOQtM@/NvnnE/tbXwSbK8kGSLlQ151XAZ4HAkGNEM1KfI8nUVm0KjPks5jwry0Dk/b607RBjGhFCMOcOechltQQOahEqDXwGc3z9iFWQM1/rKExwf6BgATDGhHkT9QlvKseGzpYrP0eHEMnWfob4TmFHoXakST0K90YIIHZy2lYbwUtHLRpOO0ina4Wq@RaPEjjnrcBIwbZN0TktFhLK8pxZXGLuJIFnqHtTEJIYOwdCLEKeLCtIE52uFFulIS5RCIfCUMq6dbFDQQwpuB2O7mO6NdPgiIJ3W@Gczm7xusLtFOMOJ2fuvO7Oye8JvYF5euSqD/fP3U6c3pnGuWJ0z27e/3L8ZrrHFI5pGBz/pHLr5zUSrwv4GEn1BQ "JavaScript (Node.js) – Try It Online")
Input as 0-indexed adjacency list. Output falsy for a tree, truthy otherwise.
```
c=> // input 0-indexed adjacency list
c[
(g= // function `g` returns `false` if any
// circular paths are found
// And after function `g`, the global
// variable `t` is set to the number
// of node we visited, or in the other
// word, the number of nodes in the tree
(i, // Starting from node `i`
p)=> // Do not go back to previous node `p`
// or the "parent" node `p` if we consider
// it as a tree
// `p` is initialed to `undefined`, as root
// node do not have a parent
c[i].every( // `c[i]` is all nodes connected to `i`
j=> // For all nodes `j` that connected to `i`
j==p|| // if the node is not the parent node
c[t++]&& // we visit the node `j`
// increase the counter of node visited `t`
// for a graph contains `n` nodes, if this is
// the `n+1`th node we visit, we know there
// a circular in the graph. We use `c[t]` to
// detect it and report falsy
g(j,i) // we visit the following node `j`
))(
t=1 // Mark node `1` as visited, so initial `t` to 1
) // Visit the graph starting from node `1`
// As graph in this question would at least
// contains 2 nodes, we can safely use node
// `1` as the initial node
*t] // If there is a loop, `false*t` is `0`
// And `c[0]` is always truthy
// If there is not a loop, `true*t` is `t`
// If all nodes are connected, the number of
// nodes we visited is the number of nodes
// in the graph. As nodes are 0-indexed,
// `c[t]` is `undefined`, which is falsy
// If some nodes are not connected to node `1`,
// the number of nodes we visited is less
// than the number of nodes in the graph.
// And `c[t]` would be truthy.
```
---
# [JavaScript (Node.js)](https://nodejs.org), 66 bytes
```
m=>(g=(i,p,j=-1)=>m.map(r=>r[++j!=p&&i]&&m[t++]&&g(j,i))|t-j)(t=0)
```
[Try it online!](https://tio.run/##nVHLboMwELznK7YXxxYGhQDJoVqO@YEeLVShxCAQL4HVgsS/U14tadqkqL6Md2dnvTuO/Te/OpdRofQsv8juhF2KLg2RRrzgMeomQzc1Ur@gJbql0LT4CQtCIo@QVChN6zGkMY8Ya5UeM6pwx7oAEOQllBWgCycqDMPI5Du8SEXHtBEkvqImY97YmdYcXjkMA1RskIy3kWqGUJtEVZ5KKoeEFDsPEBFqIKSPzClqoG0XrvnG1aw/z5vNOc@qPJFGkoc0oEKYHPaeN1C/MhzEnoM1o72u0hoqe7Q5OI8V5nXvCe8rrFlxmPF4M50zv3n82WGr92fL7s5h/bnb1aQr3bhV2Gt2c/7n42eltbiwuNHj4cuVR583SpzZ4MWS7gM "JavaScript (Node.js) – Try It Online")
Input a 0/1 matrix. Output falsy for a tree, truthy otherwise.
```
m=>(
g=( // search the matrix
i, // start from node `i`
p, // with previous node is `p`
j=-1 // index of inner loop, initial to -1
)=>m.map(r=>( // for each nodes that
r[++j!=p&& // not the one where we come from
i]&& // and is connected to `i`
m[t++]&& // increase counter for visited nodes `t`
// if we had visited `length+1` nodes, there is a loop
// and we should stop here
g(j,i) // visit the next node `j`
))|t-j // return 0 if we visited every nodes once
)(
t=0 // initial count of node visited to `0`
// as node `0` is not counted into `t`
// the final `t` is "how many nodes we visited" - 1
)
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 177 bytes
```
r,q,*o,*z;c(v,p,i){for(q|=1<<v;i--;)z[v]&1<<i?q&1<<i?r|=i^p:c(i,v,9):0;}f(*s){z=calloc(9,4);q=r=0;for(o=s;*o;o+=2)z[*o]|=1<<o[1],z[o[1]]|=1<<*o;for(c(*s,0,9);*++s;)r|=~q&1<<*s;}
```
[Try it online!](https://tio.run/##jVFdS8MwFH1ufkUsKEmbQrt2G1sWfPMX@FYrlGhnoPZ7FdvVn25NmrE5dWDgcrj3nnvODZc7PI2z7ThWpCRWTqyOctSSggjcJ3mFyj3zNpuWCsehuAvb6Eam4rbUUO2ZeCzWHAnSkhVeu3RIkFXjvmM8TtOcoxUJMC1ZxVyq5HJWUyunuc1mUs3Ko0k@D72IdKECXZAUxeZSi7hSmFq2XVMs7T4mZ6umw/gaiwxh0ANDZA1snusm9NxIhhtBBgxZN3qPwBmB7kBOiQpfQyDhz56vezLmvyje2fjsJ8XXlIWG5ZnffJpZ6oW@Sfp/rXLyubjtOSW4sMr8f/869HzdC46gvrA4bm0MFAB4eMWuqZF5X@2al3cTU2DIo0GkriEggy6VsIGeQtvG@iIJmg4lIkU3ikqSE2RePz1kJoFX1VQViRSBjMFADknS5HIXp7U2GcAAxk@epPG2Hp23Lw "C (clang) – Try It Online")
-7 bytes thanks to ceilingcat.
Function `c` recursively checks for cyclicity in the graph and then we simply see if all the vertices were visited.
**Caveat:**
Only works for vertices numbered 1 to 8
]
|
[Question]
[
Given an positive even integer \$ n \$, output the set of "ways to pair up" the set \$ [1, n] \$. For example, with \$ n = 4 \$, we can pair up the set \$ \{1, 2, 3, 4\} \$ in these ways:
* \$ \{\{1, 2\}, \{3, 4\}\} \$
* \$ \{\{1, 3\}, \{2, 4\}\} \$
* \$ \{\{1, 4\}, \{2, 3\}\} \$
This can more formally be described as the set of sets of pairs of integers such that those pairs exactly cover the set \$ [1, n] \$.
Note that because we're dealing with sets here, the order of the pairs is irrelevant. For example, \$ \{\{1, 2\}, \{3, 4\}\} \$ is considered the same as \$ \{\{3, 4\},\{2, 1\}\} \$.
For the same reason, the order of your output does not matter. However, your output may not contain duplicates.
* If you want, you can choose to operate on the set \$ [0, n) \$ instead of \$ [1, n] \$
* If you want, you can choose to take the integer \$ \frac n 2 \$ as input, instead of \$ n \$
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
2 -> {{{1, 2}}}
4 -> {{{1, 2}, {3, 4}}, {{1, 3}, {2, 4}}, {{1, 4}, {2, 3}}}
6 -> {{{1, 2}, {3, 4}, {5, 6}}, {{1, 2}, {3, 5}, {4, 6}}, {{1, 2}, {3, 6}, {4, 5}}, {{1, 3}, {2, 4}, {5, 6}}, {{1, 3}, {2, 5}, {4, 6}}, {{1, 3}, {2, 6}, {4, 5}}, {{1, 4}, {2, 3}, {5, 6}}, {{1, 4}, {2, 5}, {3, 6}}, {{1, 4}, {2, 6}, {3, 5}}, {{1, 5}, {2, 3}, {4, 6}}, {{1, 5}, {2, 4}, {3, 6}}, {{1, 5}, {2, 6}, {3, 4}}, {{1, 6}, {2, 3}, {4, 5}}, {{1, 6}, {2, 4}, {3, 5}}, {{1, 6}, {2, 5}, {3, 4}}}
8 -> {{{1, 2}, {3, 4}, {5, 6}, {7, 8}}, {{1, 2}, {3, 4}, {5, 7}, {6, 8}}, {{1, 2}, {3, 4}, {5, 8}, {6, 7}}, {{1, 2}, {3, 5}, {4, 6}, {7, 8}}, {{1, 2}, {3, 5}, {4, 7}, {6, 8}}, {{1, 2}, {3, 5}, {4, 8}, {6, 7}}, {{1, 2}, {3, 6}, {4, 5}, {7, 8}}, {{1, 2}, {3, 6}, {4, 7}, {5, 8}}, {{1, 2}, {3, 6}, {4, 8}, {5, 7}}, {{1, 2}, {3, 7}, {4, 5}, {6, 8}}, {{1, 2}, {3, 7}, {4, 6}, {5, 8}}, {{1, 2}, {3, 7}, {4, 8}, {5, 6}}, {{1, 2}, {3, 8}, {4, 5}, {6, 7}}, {{1, 2}, {3, 8}, {4, 6}, {5, 7}}, {{1, 2}, {3, 8}, {4, 7}, {5, 6}}, {{1, 3}, {2, 4}, {5, 6}, {7, 8}}, {{1, 3}, {2, 4}, {5, 7}, {6, 8}}, {{1, 3}, {2, 4}, {5, 8}, {6, 7}}, {{1, 3}, {2, 5}, {4, 6}, {7, 8}}, {{1, 3}, {2, 5}, {4, 7}, {6, 8}}, {{1, 3}, {2, 5}, {4, 8}, {6, 7}}, {{1, 3}, {2, 6}, {4, 5}, {7, 8}}, {{1, 3}, {2, 6}, {4, 7}, {5, 8}}, {{1, 3}, {2, 6}, {4, 8}, {5, 7}}, {{1, 3}, {2, 7}, {4, 5}, {6, 8}}, {{1, 3}, {2, 7}, {4, 6}, {5, 8}}, {{1, 3}, {2, 7}, {4, 8}, {5, 6}}, {{1, 3}, {2, 8}, {4, 5}, {6, 7}}, {{1, 3}, {2, 8}, {4, 6}, {5, 7}}, {{1, 3}, {2, 8}, {4, 7}, {5, 6}}, {{1, 4}, {2, 3}, {5, 6}, {7, 8}}, {{1, 4}, {2, 3}, {5, 7}, {6, 8}}, {{1, 4}, {2, 3}, {5, 8}, {6, 7}}, {{1, 4}, {2, 5}, {3, 6}, {7, 8}}, {{1, 4}, {2, 5}, {3, 7}, {6, 8}}, {{1, 4}, {2, 5}, {3, 8}, {6, 7}}, {{1, 4}, {2, 6}, {3, 5}, {7, 8}}, {{1, 4}, {2, 6}, {3, 7}, {5, 8}}, {{1, 4}, {2, 6}, {3, 8}, {5, 7}}, {{1, 4}, {2, 7}, {3, 5}, {6, 8}}, {{1, 4}, {2, 7}, {3, 6}, {5, 8}}, {{1, 4}, {2, 7}, {3, 8}, {5, 6}}, {{1, 4}, {2, 8}, {3, 5}, {6, 7}}, {{1, 4}, {2, 8}, {3, 6}, {5, 7}}, {{1, 4}, {2, 8}, {3, 7}, {5, 6}}, {{1, 5}, {2, 3}, {4, 6}, {7, 8}}, {{1, 5}, {2, 3}, {4, 7}, {6, 8}}, {{1, 5}, {2, 3}, {4, 8}, {6, 7}}, {{1, 5}, {2, 4}, {3, 6}, {7, 8}}, {{1, 5}, {2, 4}, {3, 7}, {6, 8}}, {{1, 5}, {2, 4}, {3, 8}, {6, 7}}, {{1, 5}, {2, 6}, {3, 4}, {7, 8}}, {{1, 5}, {2, 6}, {3, 7}, {4, 8}}, {{1, 5}, {2, 6}, {3, 8}, {4, 7}}, {{1, 5}, {2, 7}, {3, 4}, {6, 8}}, {{1, 5}, {2, 7}, {3, 6}, {4, 8}}, {{1, 5}, {2, 7}, {3, 8}, {4, 6}}, {{1, 5}, {2, 8}, {3, 4}, {6, 7}}, {{1, 5}, {2, 8}, {3, 6}, {4, 7}}, {{1, 5}, {2, 8}, {3, 7}, {4, 6}}, {{1, 6}, {2, 3}, {4, 5}, {7, 8}}, {{1, 6}, {2, 3}, {4, 7}, {5, 8}}, {{1, 6}, {2, 3}, {4, 8}, {5, 7}}, {{1, 6}, {2, 4}, {3, 5}, {7, 8}}, {{1, 6}, {2, 4}, {3, 7}, {5, 8}}, {{1, 6}, {2, 4}, {3, 8}, {5, 7}}, {{1, 6}, {2, 5}, {3, 4}, {7, 8}}, {{1, 6}, {2, 5}, {3, 7}, {4, 8}}, {{1, 6}, {2, 5}, {3, 8}, {4, 7}}, {{1, 6}, {2, 7}, {3, 4}, {5, 8}}, {{1, 6}, {2, 7}, {3, 5}, {4, 8}}, {{1, 6}, {2, 7}, {3, 8}, {4, 5}}, {{1, 6}, {2, 8}, {3, 4}, {5, 7}}, {{1, 6}, {2, 8}, {3, 5}, {4, 7}}, {{1, 6}, {2, 8}, {3, 7}, {4, 5}}, {{1, 7}, {2, 3}, {4, 5}, {6, 8}}, {{1, 7}, {2, 3}, {4, 6}, {5, 8}}, {{1, 7}, {2, 3}, {4, 8}, {5, 6}}, {{1, 7}, {2, 4}, {3, 5}, {6, 8}}, {{1, 7}, {2, 4}, {3, 6}, {5, 8}}, {{1, 7}, {2, 4}, {3, 8}, {5, 6}}, {{1, 7}, {2, 5}, {3, 4}, {6, 8}}, {{1, 7}, {2, 5}, {3, 6}, {4, 8}}, {{1, 7}, {2, 5}, {3, 8}, {4, 6}}, {{1, 7}, {2, 6}, {3, 4}, {5, 8}}, {{1, 7}, {2, 6}, {3, 5}, {4, 8}}, {{1, 7}, {2, 6}, {3, 8}, {4, 5}}, {{1, 7}, {2, 8}, {3, 4}, {5, 6}}, {{1, 7}, {2, 8}, {3, 5}, {4, 6}}, {{1, 7}, {2, 8}, {3, 6}, {4, 5}}, {{1, 8}, {2, 3}, {4, 5}, {6, 7}}, {{1, 8}, {2, 3}, {4, 6}, {5, 7}}, {{1, 8}, {2, 3}, {4, 7}, {5, 6}}, {{1, 8}, {2, 4}, {3, 5}, {6, 7}}, {{1, 8}, {2, 4}, {3, 6}, {5, 7}}, {{1, 8}, {2, 4}, {3, 7}, {5, 6}}, {{1, 8}, {2, 5}, {3, 4}, {6, 7}}, {{1, 8}, {2, 5}, {3, 6}, {4, 7}}, {{1, 8}, {2, 5}, {3, 7}, {4, 6}}, {{1, 8}, {2, 6}, {3, 4}, {5, 7}}, {{1, 8}, {2, 6}, {3, 5}, {4, 7}}, {{1, 8}, {2, 6}, {3, 7}, {4, 5}}, {{1, 8}, {2, 7}, {3, 4}, {5, 6}}, {{1, 8}, {2, 7}, {3, 5}, {4, 6}}, {{1, 8}, {2, 7}, {3, 6}, {4, 5}}}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Œ!HĊĠ€Ṣ€Q
```
[Try it online!](https://tio.run/##fZc9ThxBEIVzn2IskVgaCbHT9XMEp4RotaETiws4IIAEiZATICdOfAEkMuAg@CLjWZjeberV6w12Z7u@6VfTb6u69@ePy8tf8/x6//X7y93Lw7@bv2@Pv5f38/n59uNq/379dLg@ufry/Of028U8bzfjsN1uz8Zhs1tey5dyHFiupnEo78P7kWl/sWlHyjoyrTcr3rx8yjjo4ZYakVUMI7pGJBGOs9UIzlYjONsx6ThbaWebsogesq8RaWf7lIG0WU9ZRGGJNcwmECmQgYasy2qGczOWTxsHh6WvhK1mcsJXwjrGMpVKcJVKcJWjrUxFWxXpEX546khYq5Jmau3TSo9wWgoeVIwSSjP18LTaKZ64YpFAXyKBvmAhMhXufiS4Cnc/Euh@JND9SnD3I6FUhbtfCe5@JJRmyt3HZhdXLBLoSyTQF2ycTEXaqtAewVW07RKpirYq0iPQ/dI6N2XuR0KpigUV9MWDilFCaaYenlY7m1NcsUigL5FAX3CjYyqFuh8JrqLtTpSqKHReRhzrJhLWqqSZGuwijHB6NPCgYpRQmqnDTsQPE3HFNHNfegTWCx5MmEqhVamZ@6mKUPc16zClR6D7mrmfZmpwUmGE06Ocw6mLEUIzdTipVMIy9z/9ki3rDtIjsI9Z5n6qUmi3NOI@qgitSst2oNIjsCot6zBppkrdN9Jh0Benf5GMuM8J/JPjxH2jBO4vTrqDAlHoLubEfU5wFaHd0on7nMBu6cR9o4RQFaVV6aTDKCWEZmro/m73Hw "Jelly – Try It Online")
```
Œ! All permutations of [1 .. n].
H Halve each number in each permutation
Ċ rounding up,
Ġ€ group indices of equal values in each,
Ṣ€ sort each index-grouping,
Q and uniquify.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `R`, 9 bytes
```
Ṗƛ2ẇvss;U
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJSUCIsIiIsIuG5lsabMuG6h3ZzcztVIiwiIiwiNCJd)
Takes \$n\$ as input.
```
Ṗƛ2ẇvss;U
·πñ # Permutations of [1, n]
∆õ # For each:
2ẇ # Split into chunks of length 2
vs # Sort each
s # Sort
; # Close map
U # Uniquify
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
dɾ2ḋḋ'fÞu
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiZMm+MuG4i+G4iydmw551IiwiIiwiMiJd)
Port of caird's Jelly answer, takes \$\frac{n}{2}\$ as input.
```
dɾ2ḋḋ'fÞu
d # Double, n √ó 2
…æ # Range [1, that]
2ḋ # Combinations without replacement of length 2
ḋ # Combinations without replacement of length {input}
' # Filter for:
f√ûu # Is it unique after flattening?
```
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 44 bytes
```
f n=g[1..n]
g[]=[]
g(a:b++c:d)=(a,c):g(b++d)
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NIc82PdpQTy8vlis9OtY2GkhpJFolaWsnW6Vo2mok6iRrWqVrAPkpmv9zEzPzFGwV0hTM/gMA "Curry (PAKCS) – Try It Online")
This is a non-deterministic function whose return values are the all the ouputs.
[Answer]
# [Python](https://www.python.org), 84 bytes
```
def f(n,o={}):(n>sum(1>o[K]!=f(n-1,o|{K:n})for K in o)==f(n-1,o|{n:0}))==n==print(o)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3Q1JS0xTSNPJ08m2razWtNPLsiktzNQzt8qO9YxVtgRK6hjr5NdXeVnm1mmn5RQreCpl5CvmatgipPCuDWk2gQJ6tbUFRZl6JRr4mxOx1aRpGmlxpGiYgwgwqCLMYAA)
Using dictionaries instead of sets.
### Previous [Python](https://www.python.org), 91 bytes
```
def f(n,*o):[f(n-1,*{*o}^{(K,n),K})for K in o if-1*K][n-1:]or f(n-1,*o,n)if n else print(o)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3o1NS0xTSNPJ0tPI1raKBDF1DHa1qrfzauGoNb508TR3vWs20_CIFb4XMPIV8hcw0XUMt79hooDKrWKAwVEM-UGVmmkKeQmpOcapCQVFmXolGvibEinVpGkaaXGkaJiDCDCoIsx8A)
Takes `n` and prints all unique pairings.
How?
Counting down `n` either add the current value to an existing unfinished pair or start a new pair. One can check that this visits each pairing exactly once.
[Answer]
# [Python](https://www.python.org), ~~101~~ ~~98~~ 94 bytes
```
def f(r,*x):
if r:a,*r=r;[f({*r}-{b},*x,(a,b))for b in r]
else:print(x)
def g(n):f(range(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY341JS0xTSNIp0tCo0rbgUMtMUiqwSdbSKbIuso9M0qrWKanWrk2qBsjoaiTpJmppp-UUKSQqZeQpFsVwKqTnFqVYFRZl5JRoVmlwgk9I18jStgMYl5qWnApmaEFuWpGuYQZkwiwE)
Takes \$n\$ as input, operates on the set \$[0,n)\$, prints tuples of tuples.
---
-3 bytes from @Unrelated String by using splatting instead of passing in an array
-4 bytes from @pxeger by using list comprehension
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
Map[Union,{#~Partition~2&/@Permutations@Range@#},3]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zexIDo0LzM/T6dauS4gsagkswTIqTNS03cISC3KLS1JBPGLHYIS89JTHZRrdYxj1f4HFGXmlUQr69qlOSjHqtUFJyfm1VVzGelwmehwmelwWXDV/gcA "Wolfram Language (Mathematica) – Try It Online")
Input \$n\$. Returns a list of pair-lists, wrapped in a list.
```
Map[Union,{#~Partition~2&/@Permutations@Range@#},3]&
Permutations@Range@# permutations
#~Partition~2&/@ pair
{ } increase depth by 1
Map[Union, ,3] unique all
```
Since `Map` does not apply at level `0` by default, wrapping the output with `{ }` saves 2 bytes over including that level explicitly, e.g. with `Map[Union,...,{0,2}]` or `u@Map[u=Union,...,2]`.
[-1](https://tio.run/##y00syUjNTSzJTE78n2b73zexIDo0LzM/T0e5LiCxqCSzBMiuM1LTdwhILcotLUkE8YsdghLz0lMdlNV1jGPV/gcUZeaVRCvr2qU5KMeq1QUnJ@bVVXMZ6XCZ6HCZ6XBZcNX@BwA) if output wrapped in a `Derivative[1]` rather than a `List` is acceptable.
[Answer]
# [Haskell](https://www.haskell.org), 60 bytes
```
f n=g[1..n]
g[]=[[]]
g(h:t)=[(h,e):x|e<-t,x<-g$filter(e/=)t]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN23SFPJs06MN9fTyYrnSo2Nto6NjgQyNDKsSTdtojQydVE2rippUG90SnQob3XSVtMycktQijVR9W82SWKgZxrmJmXkKtgop-VwKCgVFmXklCioKaQpGKDwTFJ4ZRCvMGQA)
Not sure if it can be improved.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Lœε2ô€{{}ê
```
[Try it online](https://tio.run/##yy9OTMpM/f/f5@jkc1uNDm951LSmurr28Kr//00A) or [verify all test cases](https://tio.run/##AS4A0f9vc2FiaWX/OMOFw4jCpnZ5PyIg4oaSICI/ef9MxZPOtTLDtOKCrHt7fcOq/yz/).
Alternative with the same byte-count (thanks to *@CommandMaster*):
```
L¬©.√Ü√¶ íÀú{¬ÆQ
```
[Try it online](https://tio.run/##ARsA5P9vc2FiaWX//0zCqS7DhsOmypLLnHvCrlH//zQ) or [verify all test cases](https://tio.run/##AS8A0P9vc2FiaWX/OMOFw4jCpnZ5PyIg4oaSICI/ef9Mwqkuw4bDpsqSy5x7wq5R/30s/w).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
œ # Get all permutations of this list
ε # Map over each permutation:
2ô # Split it into parts of size 2
€{ # Sort each inner pair
{ # Then sort all pairs
}ê # After the map: sort and uniquify the list of lists of pairs
# (which in this case is faster than just an uniquify)
# (after which the result is output implicitly)
L # Push a list in the range [1, (implicit) input]
© # Store this list in variable `®` (without popping)
.Æ # Create all sorted unique pairs of this list
√¶ # Get the powerset of this list of pairs
í # Filter each inner list of pairs by:
Àú # Flatten it to a single list
{ # Sort it
®Q # Check if it's equal to list [1,input] from variable `®`
# (after which the filtered list is output implicitly)
```
[Answer]
# [R](https://www.r-project.org), ~~95~~ 92 bytes
```
f=\(n,v=1:n,a={},`+`=list)`if`(n,sapply(seq(v)[-1],\(i,b=c(1,i))f(n-2,v[-b],c(+v[b],a))),+a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Tc1BCgIhFIDh67yHz4UtIgJPokM6Q4YgYmrCEJ2kjS1atusy3aaBadHqX3yL__7I_WVDOCTrs4-nIp-X6vjuo53UEKlJsY9k5fVGhhkZfKlovDMLFZtSmKEcz9BQcTGQBk-jnECQR3QQ-Yaa4uNAE7CmllpEJGZxfbxLzfD_hi3-qPe1Xw)
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 75 bytes
```
[ iota [ natural-sort ] dup '[ 2 group _ map @ ] map-permutations members ]
```
[Try it online!](https://tio.run/##HY2xDsIwDET3fsVtTHRACCFY2BALC2KqEEqD20a0SXCcoUJ8e3E7WTq/u9cYK4Gn@@1yPR8wGOlKNr6lhBRYnG/xJvbUo@ERLYcc5yzRJ5O3Si0NG4baeaNDzmqRJCEyiYyRnRe4gGNRfLHBFjvs8ZsqzcSggpYym349y/DAK0esKgUXE546H3HSh951JB6yGHHBq5eGmjjhMc1IhbIs4Xslydhu@gM "Factor – Try It Online")
Uses \$[0..n)\$ instead of \$[1..n]\$ to save a byte.
This would be more clearly written as
```
[ iota [ 2 group [ natural-sort ] map natural-sort ] map-permutations members ]
```
However, `natural-sort` is so long it's shorter to stick in a quotation, dup it, and fry them into the `map-permutations` quotation appropriately. I'll explain the second version since the first version constructs it.
* `iota` Get an integer range from 0 inclusive to the input exclusive.
* `[ ... ] map-permutations` Apply `[ ... ]` to each permutation of the above range and collect the results in a new sequence.
* `2 group` Group a sequence into pairs. e.g. `{ 1 2 3 4 }` -> `{ { 1 2 } { 3 4 } }`.
* `[ natural-sort ] map` Sort each pair.
* `natural-sort` Sort the sequence of pairs.
* `members` Take the unique elements of a sequence.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ŒcœcHFQƑ$Ƈ
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//xZJjxZNjSEZRxpEkxof/LMOHxZLhuZgkSylq4oG@wrbCtv//MiwgNCwgNiwgOA "Jelly – Try It Online")
## How it works
```
ŒcœcHFQƑ$Ƈ - Main link. Takes n on the left
Œc - Unordered pairs
H - Halve
œc - Combinations without replacement of length n/2
$Ƈ - Keep those for which the following is true:
F - When flattened,
Ƒ - the list is unchanged after
Q - deduplication
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
umȯOmOC2Pḣ
```
[Try it online!](https://tio.run/##yygtzv7/vzT3xHr/XH9no4CHOxb////fBAA "Husk – Try It Online")
Range (`ḣ`) => permutations (`P`) => map (`m`) 3 functions (`ȯ`) over each: cut into sublists of 2 (`C2`), sort each sublist (`mO`), and sort each (`O`) => finally keep only unique elements (`u`).
[Answer]
# [Python](https://www.python.org), 124 bytes
*Thanks to user `Steffan` for -4 bytes.*
Takes the integer \$ \frac n 2 \$ as input and operates on the set \$ [0, n) \$. Outputs a set of tuples of tuples.
```
lambda n:{t for t in c(sorted(c(range(2*n),2)),n)if len(sum(t,()))==len({*sum(t,())})}
from itertools import*;c=combinations
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PY5LDoJAEET3nKJ3dBMISlwYDJ7EDb_RSZgeMjQLg5zEDYnRO3kbIRBXlaqk6tXz097lZnl6qezy7kVFx--jyU1R5cDpIKCsAwHNUGJnndQVluhyvtaYBExhQhQyaQVNzdj1BiVEIsqyxQ_BPxlp9JSzBrTUTqxtOtCmnQeDU5mV1hSac9GWu-3DYeHywt1g4X43w1IPoHWaBZU_8AjRGQaFHMcJjT6t3Wla9Qc)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 68 bytes
```
->n{[*1..n].permutation.map{|c|c.each_slice(2).map(&:sort).sort}|[]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOlrLUE8vL1avILUot7QksSQzP08vN7Gguia5JlkvNTE5I744JzM5VcNIEySsoWZVnF9UoqkHImtromNr/xcopEWbxHKBKLPY/wA "Ruby – Try It Online")
[Answer]
# [SageMath](https://www.sagemath.org/), 35 bytes
```
lambda n:PerfectMatchings(n).list()
```
[Try it on SageMathCell!](https://sagecell.sagemath.org/?z=eJxLU7BVyEnMTUpJVMizCkgtSktNLvFNLEnOyMxLL9bI09TLySwu0dDk5VIgAHi50vKLFDIVMvMUNAz19Ew0rSB6Cooy80o00tSrjRS0FDJrFXTtFKrTNMAczVp1TQBQKx70&lang=sage&interacts=eJyLjgUAARUAuQ==)
[Answer]
# Rust, 225 bytes
My other attempts where even longer. So much `collect().collect()..`
```
fn f(e:u8)->Vec<Vec<(u8,u8)>>{let g=|t,e|if t+1<e{t+1}else{t+2};if e==0{vec![vec![]]}else{(1..e).flat_map(|q|f(e-2).iter().map(|o|o.iter().map(|m|(g(m.0,q),g(m.1,q))).chain([(0,q)]).collect()).collect::<Vec<_>>()).collect()}}
```
[Answer]
# [Rust](https://www.rust-lang.org), ~~191~~ 186 bytes
```
fn f(e:u8)->Vec<Vec<[u8;2]>>{if e>0{(1..e).flat_map(|q|{let mut k=f(e-2);for r in&mut k{for m in r.iter_mut(){for n in m{*n+=(*n>=q)as u8}}r.push([q,e])}k}).collect()}else{vec![vec![]]}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=1ZTBToNAEIYvnvoUKwczU4G2xJimCJ49efNCSEPqUons0tLFC-yTeOlB38H4JvokHt3dGm1Nq0ZtogeWfz6S3fmGwPVNWc3EXWQ5Dj3PRFbwwOt6PcsmlnNqxY87TyknLMk4IKlbnY6qUqCDqo9OeEZHR_qCqm8rEIZ1TgUZB42waZOlROz3jmitVknzmQ6e9BWmQdCtr-hoNzJLHC8eQ891KbppnoghSybQTBt1kuOhmwlaAroGFk2xUrMGxsDcrj1FW4eeCoju6EK3HIHmsSqLPKcjAfgaBwPT-jAMlyCglJ86_rbBHjCbY_M6u0bNyQE9uykmM1L1fW2o7Tii_I9qwLQRezOyuQb8DWz_jYXddQ5m6KwS5DJY6PhpUZKSZHzP0FqVxiHjpKzbbD9QfbeXTPw2X7AlGSnfbVK6k2p2AUYN5aVc7t5Md2Xem3widZoX_1iHMGJkdOQ6snqtwwaJSEnEf1VCKYTBpwZTm37F4LYSqdN_uN--hvlmhooCfmz0PYOTSZlxkfNdsOrBsVS_9hQ8RL-1hh9s4Ieav2w4ny_uzw)
A golfed version of [mousetail's solution](https://codegolf.stackexchange.com/a/249914/78410).
-5 bytes thanks to alephalpha. Didn't realize that `r.iter_mut()` can save a separate `for r in &mut k`.
List of changes:
* I decided to remove `.collect::<Vec<_>>()` right inside `flat_map` in favor of taking an owned Vec (that is returned from `f(e-2)`) and modifying it.
* Then, since both fields of `(u8,u8)` are being modified using the same formula, I decided to change its type to `[u8;2]` and iterate over it instead.
* Finally, switching to 1-based solution saved a few bytes related to arithmetic.
[Answer]
# [lin](https://github.com/molarmanful/lin), 52 bytes
```
.\n $`.n `t2`comb.n2/ `comb \; `#
`flat dup `uniq `=
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Returns an iterator with 0-indexed results.
For testing purposes (use `-i` flag if running locally):
```
6 ; `_ wrap_
.\n $`.n `t2`comb.n2/ `comb \; `#
`flat dup `uniq `=
```
## Explanation
Assuming even integer input *n* (`.\n`).
* ``$ `.n `t` push range `[0..n)`
* `2`comb` length-2 combinations
* `.n2/ `comb` length-(*n*/2) combinations
* `\; `#` filter...
+ ``flat dup `uniq `=` check if element flattened is unique
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 20 bytes
```
UQ(SNSN*_CHa/2MPM,a)
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJVUShTTlNOKl9DSGEvMk1QTSxhKSIsIiIsIiIsIi1wIDQiXQ==)
Operating on the range \$[0,n)\$ instead of \$[1,n]\$.
I'm just porting some of the other answers here like the Jelly and Vyxal one, so hopefully it is right.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 112 bytes
Prints space-separated lists of comma-separated 0-indexed values.
```
f=(n,i=0,m,o,g=j=>++j<n?g(j,m&(q=1<<i|1<<j)||f(n,i,m|q,[o]+[i,j]+' ')):f(n,i+1,m,o))=>2**n+~m?i<n&&g(i):print(o)
```
[Try it online!](https://tio.run/##JY3NDoMgEITvfYo9CSu0qZ6Mgj6I8WBMNRAB/@Kltq9uwV5mdrJfZnS7t2u3qGm779l59pJaruSTG@74ILUsGdPCVgPV3ER0lokQ6vCi8Tj6wHJzzLx2DasV1w0jQBDz68OS0IIoyzSOLfuaSgkbRQNVmE@Lsht1ePZuoRYkpAVYEBKy4MxnhPcNoHN2dePrMbqBkjqABFgggDQEC0/4qcv/jf78nD8 "JavaScript (V8) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~12~~ 11 bytes
```
{mSSMcd2.PS
```
[Try it online!](https://tio.run/##K6gsyfj/vzo3ONg3OcVILyD4/38TAA "Pyth – Try It Online")
```
{mSSMcd2.PS
S Range from 1 to the input
.P Permutations
m For each permutation:
cd2 - Chop into chunks of size 2
SM - Sort each chunk
S - Sort the list of chunks
{ Deduplicate
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 10 bytes
```
Œ!s2Ṣ€ṢƊ€Q
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FluOTlIsNnq4c9GjpjVA8lgXkA5cUpyUXLz6cPvRSQ93zgAKRELULo42i4VqAwA)
Now that it's been beaten, I'll post my own answer (also [previously shared in chat](https://chat.stackexchange.com/transcript/240?m=61551172#61551172)).
Explanation:
```
Œ! permutations of (implicit range from 1 to) n
Ɗ€ for each permutation:
s2 split into chunks of 2
Ṣ€ sort each pair
·π¢ sort the list of pairs
Q remove duplicates
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 59 bytes
```
Nθ⊞υ⟦⟧F⊗θ«≔⟦⟧ηFυ«F⌕AEκLλ¹⊞ηEκ⎇⁻λνμ⁺μ⟦ι⟧¿‹Lκθ⊞η⊞Oκ⟦ι⟧»≔ηυ»Iη
```
[Try it online!](https://tio.run/##TY49C8IwEIbn9lfceIE4iKOTKIJgtYNb6RBtNME0rfkQRPzt8axFvOU@3ufeu5MS7tQJk9LG9jHsYnuUDm9snpfRK4wcqpqac@cAV108GtmQyuCZZwvv9cViVXNQhGQDEwfpW6@1bRbGYCF6vHLYSnsJCg1jHKZkMRxQHEb5IJ0V7oGFttGj4WCJazmUhlrKla4ZBR3K9BlwK73H0fJK5O3P8ZP3vXQidO5jPazS4uv3NEGRJq@8dNoGXAofUBGT0ixN7uYN "Charcoal – Try It Online") Link is to verbose version of code. Takes `ⁿ⁄2` as input. Explanation:
```
Nθ
```
Input `‚Åø‚ÅÑ2`.
```
⊞υ⟦⟧
```
Start with a pairing of no numbers.
```
F⊗θ«
```
Loop from `0` to `n`.
```
≔⟦⟧η
```
Start collecting pairings
```
Fυ«
```
Loop over the existing pairings.
```
F⌕AEκLλ¹
```
Loop over the unpaired numbers in this pairing.
```
⊞ηEκ⎇⁻λνμ⁺μ⟦ι⟧
```
Pair the current number with that unpaired number.
```
¿‹Lκθ⊞η⊞Oκ⟦ι⟧
```
If there is room then also add the number as an unpaired number.
```
»≔ηυ
```
Save the resulting pairings.
```
»Iη
```
Output the final pairings.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 114 bytes
```
f=(n,[i,...a]=[...Array(n)].map((_,i)=>i+1))=>i?a.flatMap(j=>f(n,a.filter(k=>k-i&&k-j)).map(r=>[[i,j],...r])):[[]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZjPctowEMbvHPsEOnTAnhiTgG15kjGZHnpoZ_pnJkfiKR5iiBNiGON02iF-kl5yaB-qfZpKgLC0q8UXW9Jv91v0Icnw63e5ustfX_881_N-_LeaJ07pTQrP9_0sTSbi9q6qsp9O6ab-U7Z2nG9e4Sbj4uzClbfrzJ8vs_qTGHlIxnMRKzqKZZ1XzmMyfuwX3e5j_8F1d7FVMp6I1A-pzF6lrns5maTpXvnfm_Kq05l2zll_zLbbpukM90_bC48NG9EO9LbHtiOPBY18kD0j-TDUe4JDz0jGRrZYcQ89Fh0j1Ego74FtJDqMhBZdmE2N4GxqBGdra4bZAj3byDYSHatXI6Gezagg1Kse2UZUtnY-I5AtRCMBqiACVQfSi_iUF-LOPRajmVcEl_foFBEfCH7CV0pFEbSKImiV1lVKJdJVwlNEfPzUkOC6irVSrn9aqwoHKvj7HgMVXEcMVGiCIxW8duCMQQL7AgnsC16HlArtPiRoFdp9SGD3IYHdVwTtPiSw-5DA7iuCdh8S2H1IYPfxXgdnDBLYF0hgX_C-SakoglZRBK3S7sGUSqSrhKcI7L4iuK5irZTrn9aqwoEK9iUGKriOGKjQBHYfn01wxiCBfYEE9gWfc5RKoFdqVVEErdKemZSK4X5wimjXDSS4rmKt1HDfqsKBCvYlBiq4jhio0ARHKvhdAs4YJPB6gQReL_i9hFIx3LeqGO5bVdp3HEolBPNBE9h9RRjuWys1dgerCnQfv6_FQAXXEQMVmuBIhdvcN77JkMD7GCTwPqYIw32rirE7WFWg-1jFcN-qYpxAwSkCr0pFGDuMtVLjBLKqwB0G-wLdx3VA92kC_8aJCfc5SeDzBRL4fFEEdB_ngO7TBK0C3cc5oPs0gXdLRUD3cQ7oPk3gVakIuMPgOuAOQxOa-01n6tdV8eS4_ma9LGqnd1v2XH--qt5ns3unzjc1S8Tvwg5js1UpGhOPFeX6ufZY_mOdz-qbukpZwiToP2W1iBk4_pkrf0zK-8C9OobuAwT88ebLZ3-dVZvcOSbxq3y9zGa5M7jdDhYe601EGce-ZteV9lwtXZVvnpcy3dzZ5fpQ1s6uNB1aZ5uNQPYy_jIvF_U9S5LkEK16ul0RIa8DmH_Pq58ibVEV5UJOwAGfF-XdblK-HocOgfI68LqMxiItPaQVlGp6lCFp6slLjeiiQ1NDXs707VZmb6Y7QrRUoOh5eWHk8OQibTyteZ42U1dL7qpGO-urZe4vVwtnN_fXrHf7POTnYY9d7h-DWe_4Her1x6Kxn1wR37hX-7-d1B9f_wE)
]
|
[Question]
[
Build an interpreter for a fake, stack-based language that gets an input, interprets it, and outputs the result as an array of numbers. It should iterate through each byte and perform a different function based on this table:
0000 (0):
Concatenate (Combine top two numbers in a stack as if they were a string. ex: 12,5 -> 125)
0001 (1):
Increment (Add 1 to the number on the top of the stack)
0010 (2):
Decrement (Subtract one from the number at the top of the stack)
0011 (3):
Multiply (Multiply the top two numbers in the stack)
0100 (4):
Divide (Divide the 2nd-to-top number by the top number on the stack)
0101 (5):
Add (Add the top two numbers on the stack)
0110 (6):
Subtract (Subtract the top number on the stack from the one below it)
0111 (7):
Exponent (Calculate the second-to-top number to the power of the top number)
1000 (8):
Modulus: (Find the second-to-top number modulo the top one)
1001 (9):
Rotate Right (Shift the stack down one. The number on the bottom is now on the top)
1010 (A):
Rotate Left (Shift the stack up one. The number on the top is now on the bottom)
1011 (B):
Duplicate (Copy the top number so that it appears twice. ex: 4,1 becomes 4,1,1)
1100 (C):
Double Duplicate (Copy the top two numbers on the stack. ex: 4,1,2 becomes 4,1,2,1,2)
1101 (D):
Swap (Swap the top two numbers on the stack. ex: 4,1,2 becomes 4,2,1)
1110 (E):
Double Swap (Swap the top two numbers with two below them.ex: 1,2,3,4,5 becomes 1,4,5,2,3)
1111 (F):
Delete/Pop (Remove the number at the top of the stack)
For example, a file containing
```
1 1 B C 5 C 5 B 9 5 - Input (hex)
| | | | | | | | | |
1 2 2 2 4 4 6 6 2 8 - Stack
2 2 2 2 4 6 6 6
2 2 4 2 4 6 4
2 2 2 2 4 2
2 2 2
```
would output [8,6,4,2]
## Rules:
* Unicode/symbols are okay, but ASCII is best.
* Be creative! Shortness counts, but creativity is great!
* If bytes are too hard, use `"$iv*/+-^%><dtsz."` or `"0123456789ABCDEF"` instead of actual bytes.
* SPEED! The faster, the better.
* The score is based on reputation, but size is a huge factor.
## Bonus:
Try to complete [this](https://codegolf.stackexchange.com/questions/17005/produce-the-number-2014-without-any-numbers-in-your-source-code) challenge using your newly made interpreter in as short of a string as possible.
## Note:
The thing that makes this challenging as opposed to other code-golfing challenges is that there is no code to go by with this. If, lets say, you had to write a brainf\*ck interpreter, you could look at other people's implementations. With this, you can't do that.
---
I forgot to put and ending date on this. I guess I'll make it one month from when I created this. Person with the highest votes at Feb. 22 wins!
[Answer]
# Ruby, 67 lines of regex substitutions
I decided to write the interpreter in regex, while sticking to efficient algorithms.
I could have gone for plain bytes, but using symbols makes the code more readable in my opinion. Of course, if we could pack two instructions in one byte...
Concatenation of negative values results in ten's complement behavior, reflecting the internal representation.
Division is integer division and the remainder is never negative.
```
subs = [
# stack expansion
[/^ ?([$iv*\/+\-^%dtsz.])/, ' 0 \1' ],
[/^ (\d+ [$*\/+\-^%tsz])/, ' 0 \1' ],
[/^ ((\d+ ){2,3}z)/, ' 0 \1' ],
[/ (0|9)\1+/, ' \1' ],
# concatenation
[/ (\d+) (?:0+|9+)(\d+) \$/, ' \1\2 ' ],
[/ (\d+) (0|9) \$/, ' \1\2 ' ],
# swaps
[/ ((?:\d+ )*)(\d+) </, ' \2 \1' ],
[/ (\d+)((?: \d+)*) >/, '\2 \1 ' ],
[/ (\d+) (\d+) s/, ' \2 \1 '],
[/ (\d+ \d+) (\d+ \d+) z/, ' \2 \1 '],
# dups
[/ (\d+) d/, ' \1 \1 '],
[/ (\d+ \d+) t/, ' \1 \1 '],
# pop
[/ (\d+) \./, ' ' ],
# increment / decrement
[/ (\d+) i/, ' \1I '], [/ (\d+) v/, ' \1V '],
*(%w[0I 1I 2I 3I 4I 5I 6I 7I 8I 9I].zip [*?1..?9, 'I0']),
*(%w[0V 1V 2V 3V 4V 5V 6V 7V 8V 9V].zip ['V9', *?0..?8]),
[' 1', ' 01'], [' 8', ' 98'], [' I', ' '], [' V', ' '],
# addition, subtraction
[/ (\d+) (\d+) \+/, ' \1P \2P ' ], #init addition
[/ (\d+) (\d+) \-/, ' \1S \2S ' ], #init subtraction
[/ ([PS](\d)\w*) (\d+[PS]\w*) /, ' \2\1 \3 ' ], #sign extend left
[/ (\d+[PS]\w*) ([PS](\d)\w*) /, ' \1 \3\2 ' ], #sign extend right
[/ (\d*)(\d)P(\S*) (\d*)0P(0*) /, ' \1P\2\3 \4P0\5 '], #advance addition
[/ (\d*)(\d)S(\S*) (\d*)0S(0*) /, ' \1S\2\3 \4S0\5 '], #advance subtraction
[/ (\d+)P(\S*) (\d*[1-5])P(0*) /, ' \1IP\2 \3VP\4 ' ], #transfer left
[/ (\d+)P(\S*) (\d*[6-9])P(0*) /, ' \1VP\2 \3IP\4 ' ], #transfer right
[/ (\d+)S(\S*) (\d*[1-5])S(0*) /, ' \1VS\2 \3VS\4 ' ], #decrement both
[/ (\d+)S(\S*) (\d*[6-9])S(0*) /, ' \1IS\2 \3IS\4 ' ], #increment both
[/ [PS](\S+) [PS]0+ /, ' \1 ' ], #finish
# digitwise negation
*(%w[9N 8N 7N 6N 5N 4N 3N 2N 1N 0N].zip [*'N0'..'N9']),
#multiplication and division by 2
*([*'H0'..'H9'].zip %w[0H 0F 1H 1F 2H 2F 3H 3F 4H 4F]),
*([*'F0'..'F9'].zip %w[5H 5F 6H 6F 7H 7F 8H 8F 9H 9F]),
*(%w[0T 1T 2T 3T 4T 5T 6T 7T 8T 9T].zip %w[T0 T2 T4 T6 T8 TI0 TI2 TI4 TI6 TI8]),
['H ', ' '], [' T', ' '],
# sign correction for */%
[/ (\d+) (9\d*) ([*\/%])/, ' \1NI \2NI \3'], [' N', ' '],
# multiplication
[/ (0+ \d+|\d+ 0+) \*/, ' 0 ' ], #multiplication by zero
[/ (\d+) (0\d*[02468]) \*/, ' \1T H\2 *' ], #multiplication by an even number
[/ (\d+) (0\d*[13579]) \*/, ' \1 \1 \2V *+'], #multiplication by an odd number
# division / modulo
[?/, 'r.'], [?%, 'rs.'],
[/ (0|9)(\d*) (0\d+) r/, ' \3 0 \1D\2 ' ], #init division
[/ (\d+) (\d+) (0\d*)D(\d*) /, ' \1 \2I \3SD\4 \1S ' ], #subtract divisor
[/ (\d+) (\d+) (9\d*)D(\d)(\d*) /, ' \1 \2V0 \3P\4D\5 \1P '], #add divisor and advance
[/ (\d+) (\d+) (9\d*)D /, ' \2V \3P \1P ' ], #add divisor and finish
#exponentiation
[/ \d+ 0+ \^/, ' 01 ' ], # case: zeroth power
[/ 9\d+ 9+ \^/, ' 9 ' ], # case: reciprocal of negative
[/ \d+ 9\d+ \^/, ' 0 ' ], # case: high negative power
[/ 0\d+ 9\d+ \^/, ' 0 ' ], # case: reciprocal of positive
[/ (\d+) 0+1 \^/, ' \1 ' ], # case: power of one
[/ (\d+) (\d*[02468]) \^/, ' \1 \1 *H\2 ^' ], # case: even exponent
[/ (\d+) (\d*[13579]) \^/, ' \1 \2V ^\1 *' ], # case: odd exponent
]
x = gets.tr '^$iv*/+\-^%><dtsz.', ''
until x =~ /^ (\d+ )*$/
subs.each do |sub|
x.sub!(*sub) # && (puts x; sleep 0.1)
end
end
```
As for the bonus round, the shortest solution I've come up with (**13 characters**) is a clean solution:
```
iistisii$<$<$
```
[Answer]
## x86 assembly (on Win32)
“SPEED!” seems to be hugely important here, and we all know nothing beats assembly language in that regard. So, let’s do that in assembly!
This is an implementation of the language in x86 assembly language (in NASM syntax), with the numbers stored and interpreted as unsigned 32-bit integers, using the native x86 stack directly. Stack underflow, and overflow during any arithmetic operation (or division by zero) is a runtime error, terminating the program with an error message.
```
global _start
extern _GetCommandLineA@0
extern _GetStdHandle@4
extern _CreateFileA@28
extern _GetFileSize@8
extern _LocalAlloc@8
extern _ReadFile@20
extern _CloseHandle@4
extern _WriteFile@20
section .text
; ---------------------------------------------------------------------------------------
; Initialization
; ---------------------------------------------------------------------------------------
_start:
; Retrieve command line
CALL _GetCommandLineA@0
; Skip argv[0]
MOV ESI, EAX
XOR EAX, EAX
skipuntilspace:
MOV AL, [ESI]
INC ESI
TEST EAX, EAX
JE missingparam
CMP EAX, ' '
JNE skipuntilspace
INC ESI
; Open the file
PUSH 0
PUSH 80h
PUSH 3
PUSH 0
PUSH 1
PUSH 80000000h
PUSH ESI
CALL _CreateFileA@28
CMP EAX, -1
JE cannotopenfile
; Get its size
PUSH EAX
PUSH 0
PUSH EAX
CALL _GetFileSize@8
PUSH EAX
; Allocate memory buffer
PUSH EAX
PUSH 0
CALL _LocalAlloc@8
TEST EAX, EAX
MOV ESI, EAX
JZ outofmemory
POP ECX
POP EAX
PUSH EAX
; Store end-of-program pointer
MOV [programend], ESI
ADD [programend], ECX
; Read the file contents
PUSH 0
PUSH buff
PUSH ECX
PUSH ESI
PUSH EAX
CALL _ReadFile@20
TEST EAX, EAX
JZ cannotopenfile
; Close the file
CALL _CloseHandle@4
; ---------------------------------------------------------------------------------------
; Main loop of the interpreter
; ---------------------------------------------------------------------------------------
; Store the end of stack into EBP
MOV EBP, ESP
; Push an initial 0 onto the stack
XOR EAX, EAX
PUSH EAX
mainloop:
; Load the next opcode, if not end of program
XOR EAX, EAX
CMP ESI, [programend]
MOV AL, [ESI]
JAE endloop
LEA ESI, [ESI+1]
; Check if the opcode is valid
CMP EAX, (maxop - opcodetable) / 8
JA fault_invalidopcode
; Check for required stack space
MOV ECX, [opcodetable + 8 * EAX + 4]
LEA EDI, [ESP + ECX]
CMP EDI, EBP
JA fault_stackunderflow
; Jump to the respective opcode handler
MOV EAX, [opcodetable + 8 * EAX]
JMP EAX
; ---------------------------------------------------------------------------------------
; Implementation of the specific operations
; ---------------------------------------------------------------------------------------
; ************** CAT 0000 (0): Concatenate (Combine top two numbers in a stack as if they were a string. ex: 12,5 -> 125)
op_concatenate:
POP EBX
POP EAX
MOV ECX, EAX
MOV EDI, 10
concat_loop:
XOR EDX, EDX
SHL EBX, 1
DIV EDI
LEA EBX, [4 * EBX + EBX]
TEST EAX, EAX
JNZ concat_loop
ADD EBX, ECX
PUSH EBX
JMP mainloop
; ************** INC 0001 (1): Increment (Add 1 to the number on the top of the stack)
op_increment:
POP EAX
ADD EAX, 1
PUSH EAX
JNC mainloop
JMP fault_intoverflow
; ************** DEC 0010 (2): Decrement (Subtract one from the number at the top of the stack)
op_decrement:
POP EAX
SUB EAX, 1
PUSH EAX
JNC mainloop
JMP fault_intoverflow
; ************** MUL 0011 (3): Multiply (Multiply the top two numbers in the stack)
op_multiply:
POP EAX
POP EDX
MUL EDX
TEST EDX, EDX
PUSH EAX
JZ mainloop
JMP fault_intoverflow
; ************** DIV 0100 (4): Divide (Divide the 2nd-to-top number by the top number on the stack)
op_divide:
POP ECX
TEST ECX, ECX
POP EAX
JZ fault_dividebyzero
XOR EDX, EDX
DIV ECX
PUSH EAX
JMP mainloop
; ************** MOD 0101 (5): Add (Add the top two numbers on the stack)
op_add:
POP EAX
ADD [ESP], EAX
JNC mainloop
JMP fault_intoverflow
; ************** SUB 0110 (6): Subtract (Subtract the top number on the stack from the one below it)
op_subtract:
POP EAX
SUB [ESP], EAX
JNC mainloop
JMP fault_intoverflow
; ************** EXP 0111 (7): Exponent (Calculate the second-to-top number to the power of the top number)
op_exponent:
POP ECX
POP EBX
MOV EAX, 1
exploop:
TEST ECX, 1
JZ expnomult
MUL EBX
TEST EDX, EDX
JNZ fault_intoverflow
expnomult:
SHR ECX, 1
JZ expdone
XCHG EAX, EBX
MUL EAX
TEST EDX, EDX
XCHG EAX, EBX
JZ exploop
JMP fault_intoverflow
expdone:
PUSH EAX
JMP mainloop
; ************** MOD 1000 (8): Modulus: (Find the second-to-top number modulo the top one)
op_modulus:
POP ECX
TEST ECX, ECX
POP EAX
JZ fault_dividebyzero
XOR EDX, EDX
IDIV ECX
PUSH EDX
JMP mainloop
; ************** ROR 1001 (9): Rotate Right (Shift the stack down one. The number on the bottom is now on the top)
op_rotright:
MOV EAX, [EBP - 4]
LEA ECX, [EBP - 4]
SUB ECX, ESP
MOV EDX, ESI
SHR ECX, 2
LEA EDI, [EBP - 4]
LEA ESI, [EBP - 8]
STD
REP MOVSD
MOV [ESP], EAX
CLD
MOV ESI, EDX
JMP mainloop
; ************** ROL 1010 (A): Rotate Left (Shift the stack up one. The number on the top is now on the bottom)
op_rotleft:
MOV EAX, [ESP]
LEA ECX, [EBP - 4]
SUB ECX, ESP
MOV EDX, ESI
SHR ECX, 2
LEA ESI, [ESP + 4]
MOV EDI, ESP
REP MOVSD
MOV [EBP - 4], EAX
MOV ESI, EDX
JMP mainloop
; ************** DUP 1011 (B): Duplicate (Copy the top number so that it appears twice. ex: 4,1 becomes 4,1,1)
op_duplicate:
PUSH DWORD [ESP]
JMP mainloop
; ************** DU2 1100 (C): Double Duplicate (Copy the top two numbers on the stack. ex: 4,1,2 becomes 4,1,2,1,2)
op_dblduplicate:
PUSH DWORD [ESP+4]
PUSH DWORD [ESP+4]
JMP mainloop
; ************** SWP 1101 (D): Swap (Swap the top two numbers on the stack. ex: 4,1,2 becomes 4,2,1)
op_swap:
POP EAX
POP EDX
PUSH EAX
PUSH EDX
JMP mainloop
; ************** SW2 1110 (E): Double Swap (Swap the top two numbers with two below them.ex: 1,2,3,4,5 becomes 1,4,5,2,3)
op_dblswap:
POP EAX
POP EBX
POP ECX
POP EDX
PUSH EBX
PUSH EAX
PUSH EDX
PUSH ECX
JMP mainloop
; ************** POP 1111 (F): Delete/Pop (Remove the number at the top of the stack)
op_pop:
POP EAX
JMP mainloop
; ---------------------------------------------------------------------------------------
; End of the program: print out the resulting stack and exit
; ---------------------------------------------------------------------------------------
endloop:
MOV ESI, ESP
printloop:
CMP ESI, EBP
JNB exit
MOV EAX, [ESI]
MOV EBX, ESI
PUSH EBX
CALL printnum
POP EBX
LEA ESI, [EBX + 4]
JMP printloop
exit:
MOV ESP, EBP
;POP EAX
XOR EAX, EAX
RET
; ---------------------------------------------------------------------------------------
; Faults
; ---------------------------------------------------------------------------------------
fault_invalidopcode:
MOV EAX, err_invalidopcode
JMP fault
fault_stackunderflow:
MOV EAX, err_stackunderflow
JMP fault
fault_dividebyzero:
MOV EAX, err_dividebyzero
JMP fault
fault_intoverflow:
MOV EAX, err_intoverflow
JMP fault
fault:
CALL print
MOV EAX, crlf
CALL print
MOV ESP, EBP
MOV EAX, 1
RET
missingparam:
MOV EAX, err_missingparameter
JMP fault
cannotopenfile:
MOV EAX, err_cannotopenfile
JMP fault
outofmemory:
MOV EAX, err_outofmemory
JMP fault
; ---------------------------------------------------------------------------------------
; Helper functions
; ---------------------------------------------------------------------------------------
printnum:
MOV EBX, 10
CALL printnumrec
MOV EAX, crlf
JMP print
printnumrec:
PUSH EAX
PUSH EDX
XOR EDX, EDX
DIV EBX
TEST EAX, EAX
JZ printnumend
CALL printnumrec
printnumend:
MOV EAX, EDX
CALL printdigit
POP EDX
POP EAX
RET
printdigit:
ADD EAX, '0'
MOV [printbuff], EAX
MOV EAX, printbuff
JMP print
print:
MOV ESI, EAX
PUSH 0
PUSH buff
CALL strlen
PUSH EAX
PUSH ESI
PUSH -11
CALL _GetStdHandle@4
PUSH EAX
CALL _WriteFile@20
RET
strlen:
XOR ECX, ECX
strlen_loop:
CMP BYTE [ESI+ECX], 0
JE strlen_end
LEA ECX, [ECX+1]
JMP strlen_loop
strlen_end:
MOV EAX, ECX
RET
; ---------------------------------------------------------------------------------------
; Data
; ---------------------------------------------------------------------------------------
section .data
; Table of opcode handlers and required stack space (in bytes, i.e. 4*operands)
opcodetable:
DD op_concatenate, 8
DD op_increment, 4
DD op_decrement, 4
DD op_multiply, 8
DD op_divide, 8
DD op_add, 8
DD op_subtract, 8
DD op_exponent, 8
DD op_modulus, 8
DD op_rotright, 0
DD op_rotleft, 0
DD op_duplicate, 4
DD op_dblduplicate, 8
DD op_swap, 8
DD op_dblswap, 16
DD op_pop, 4
maxop:
crlf DB 13, 10, 0
err_invalidopcode DB "Invalid opcode", 0
err_stackunderflow DB "Stack underflow", 0
err_dividebyzero DB "Division by zero", 0
err_intoverflow DB "Integer overflow", 0
err_missingparameter: DB "Missing parameter: Use nexlang file.bin", 0
err_cannotopenfile: DB "Unable to open input file", 0
err_outofmemory: DB "Not enough memory", 0
section .bss
programend RESD 1
printbuff RESD 1
buff RESD 1
```
To compile this, use something like
```
nasm.exe -fwin32 nexlang.asm
ld -o nexlang.exe -e _start nexlang.obj -s -lkernel32
```
The program receives the name of the binary file containing the program on the command line (e.g. `nexlang.exe testprg.bin`). When finished, it prints the final contents of the stack to standard output in a human-readable format.
To help with testing, save the following into `nex.def`:
```
%define CAT DB 00h
%define INC DB 01h
%define DEC DB 02h
%define MUL DB 03h
%define DIV DB 04h
%define ADD DB 05h
%define SUB DB 06h
%define EXP DB 07h
%define MOD DB 08h
%define ROR DB 09h
%define ROL DB 0Ah
%define DUP DB 0Bh
%define DU2 DB 0Ch
%define SWP DB 0Dh
%define SW2 DB 0Eh
%define POP DB 0Fh
```
And then write your NEX (“non-existing”, as named in the question title) programs using the above-defined mnemonics, and compile with something like
```
nasm.exe -p nex.def -o prg.bin prg.nex
```
E.g. for the original test case, use the following `prg.nex`:
```
INC ; 1
INC ; 2
INC ; 3
INC ; 4
DUP ; 4 4
DU2 ; 4 4 4 4
ADD ; 8 4 4
DU2 ; 8 4 8 4 4
ADD ; 12 8 4 4
DUP ; 12 12 8 4 4
ROR ; 4 12 12 8 4
ADD ; 16 12 8 4
```
And finally, for the “2014” challenge, use the following 14-byte NEX program:
```
DUP ; 0 0
DUP ; 0 0 0
INC ; 1 0 0
INC ; 2 0 0
SWP ; 0 2 0
CAT ; 20 0
SWP ; 0 20
INC ; 1 20
DUP ; 1 1 20
INC ; 2 1 20
INC ; 3 1 20
INC ; 4 1 20
CAT ; 14 20
CAT ; 2014
```
[Answer]
# GolfScript, 64 chars
OK, so I decided to try and golf this. And what better language for golfing than GolfScript?
Conveniently, GolfScript itself is already a stack-based language with single-byte commands, and, as it happens, 11 out of your 16 commands map directly to built-in GolfScript commands. So all I really need to do to interpret your language is to implement the remaining five commands in GolfScript and build a translation table:
```
0\{'`+~
)
(
*
/
+
-
?
%
](+~
])\~
.
1$1$
\
[@]\+~\
;'n%=~}/]-1%`
```
The code looks kind of spread out, because I'm using newlines as delimiters for the translation table. The initial `0\` pushes a zero onto the stack and moves it below the input program. The `{ }/` loop, comprising most of the code, takes the input program off the stack and iterates the loop body over each of its characters, and the final `]-1%`` collects the stack into an array, reverses it (because your sample output starts from the top of the stack) and stringifies it.
The loop body starts with a 16-line single-quoted string. `n%` splits this string at line breaks, `=` looks up the substring corresponding to the input character, and `~` evaluates the substring as GolfScript code.
Finally, here are the GolfScript implementations of the 16 commands:
* 0 = ``+~`: concatenate two numbers as strings
* 1 = `)`: increment
* 2 = `(`: decrement
* 3 = `*`: multiply
* 4 = `/`: divide
* 5 = `+`: add
* 6 = `-`: subtract
* 7 = `?`: raise to power
* 8 = `%`: modulus
* 9 = `](+~`: rotate stack right
* A = `])\~`: rotate stack left
* B = `.`: duplicate
* C = `1$1$`: double duplicate
* D = `\`: swap
* E = `[@]\+~\`: double swap
* F = `;`: pop
I'm kind of unhappy with the double swap — it's ugly and much longer than any of the other commands. It feels like there ought to be a better way, but if so, I haven't found it yet. Still, at least it works.
For example, running the program above on the input (given as a GolfScript / Ruby / Perl / Python / etc. double-quoted string):
```
"\x01\x01\x0B\x0C\x05\x0C\x05\x0B\x09\x05"
```
yields the output:
```
[8 6 4 2]
```
---
**Edit:** I managed to save two more chars, for a total of **62 chars**, using a more compact encoding of the translation table. However, it kind of sacrifices readability:
```
0\{(')(*/+-?%'1/'](+~
])\~
.
1$1$
\
[@]\+~\
;
`+~'n/+=~}/]-1%`
```
Notable features of this version include the `(` at the beginning of the loop, which shifts the command indices from 0..15 to -1..14 so that I can put the long sequence of single-character commands from 1 to 8 at the beginning of the table. This allows me to store them in a separate string and eliminate the eight newlines delimiting them; alas, the extra complexity costs me six characters elsewhere.
[Answer]
# Haskell
Just for fun, I made a solution that uses [no variables](https://en.wikipedia.org/wiki/Point-free_style) whatsoever, only combines functions together.
```
import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Function
type SM = State [Int]
pop :: SM Int
pop = state ((,) <$> head <*> tail)
push :: Int -> SM ()
push = modify . (:)
popN :: Int -> SM [Int]
popN = sequence . flip replicate pop
pushN :: [Int] -> SM ()
pushN = mapM_ push
rotL, rotR :: Int -> [a] -> [a]
rotL = (uncurry (flip (++)) .) . splitAt
rotR = (reverse .) . flip (flip rotL . reverse)
step :: Int -> SM ()
step 0x00 = push =<< ((read .) . on (++) show) <$> pop <*> pop
step 0x01 = push . (+ 1) =<< pop
step 0x02 = push . subtract 1 =<< pop
step 0x03 = push =<< (*) <$> pop <*> pop
step 0x04 = push =<< flip div <$> pop <*> pop
step 0x05 = push =<< (+) <$> pop <*> pop
step 0x06 = push =<< flip (-) <$> pop <*> pop
step 0x07 = push =<< flip (^) <$> pop <*> pop
step 0x08 = push =<< flip mod <$> pop <*> pop
step 0x09 = modify $ (:) <$> last <*> init
step 0x0A = modify $ rotL 1
step 0x0B = pop >>= pushN . replicate 2
step 0x0C = popN 2 >>= pushN . concat . replicate 2
step 0x0D = popN 2 >>= pushN . rotL 1
step 0x0E = popN 4 >>= pushN . rotL 2
step 0x0F = void pop
run :: [Int] -> [Int]
run = flip execState [0] . mapM_ step
```
[Answer]
# Ruby, ~~330~~ 316 characters
I decided to golf it. (Because that's always fun.)
```
s=[0]
o=->c{t=s.pop;s.push s.pop.send(c,t)}
gets.chop.each_char{|c|eval %w[t=s.pop;s.push"#{s.pop}#{t}".to_i s[-1]+=1 s[-1]-=1 o[:*] o[:/] o[:+] o[:-] o[:**] o[:%] s.rotate! s.rotate!(-1) s.push(s[-1]) s.concat(s[-2..-1]) s[-1],s[-2]=s[-2],s[-1] s[-1],s[-2],s[-3],s[-4]=s[-4],s[-3],s[-1],s[-2] s.pop][c.to_i 16]}
p s
```
The main part is this:
```
gets.chop.each_char{|c|eval [(huge array of strings)][c.to_i 16]}
```
It translates each hex digit into a base-10 integer, and then uses the `[(huge array of strings)]` to find the right string that represents that command. Then it `eval`s that string.
Note that `%w[x y z]` is equivalent to `['x','y','z']`.
I also like how you can find smiley faces in that line! Some of them are
* `:*`
* `:/`
* `:-]`
* `:%`
Sample run:
```
c:\a\ruby>random_cg_lang
11BC5C5B95
[2, 4, 6, 8]
```
[Answer]
# C - 642 634 characters
For the `$iv*/+-^%><dtsz.` dialect only (adds `q` as an ending character, along with `0`):
```
#define P s=*t;a=realloc(a,--w<<2);t=a+w-1;
#define H(n)a=realloc(a,(w+=n)<<2);
#define B(n)break;case n:
*a,*t,s,w=1,i;main(){t=a=calloc(4,1);while((i=getchar())&&i^'q')switch(i){B(36)P*t*=pow(10,((
int)log10(s))+1);*t+=s;B(105)++*t;B(118)--*t;B(42)P*t*=s;B(47)P*t/=s;B(43)P*t+=s;B(45)P*t-=s;
B(94)P*t=pow(*t,s);B(37)P*t%=s;B(62)s=*a;memcpy(a,a+1,(w-1)<<2);*t=s;B(60)s=*t;memcpy(a+1,a,(
w-1)<<2);*a=s;B(100)H(1)t=a+w-2;s=*t;t++;*t=s;B(116)H(2)t=a+w-1;t[-1]=t[-3];*t=t[-2];B(115)s=
*t;*t=t[-1];t[-1]=s;B(122)s=*t;*t=t[-2];t[-2]=s;s=t[-1];t[-1]=t[-3];t[-3]=s;B(46)P}putchar('[
');putchar(32);while(w)printf("%i ",a[--w]);putchar(']');}
```
Solution for the 2014 challenge: `dididiizs>`.
[Answer]
# k, 228
```
(,0){({(-7h$,/$2#x),2_x};@[;0;+;1];@[;0;-;1];{.[*;|2#x],2_x};{.[%;|2#x],2_x};
{.[+;|2#x],2_x};{.[-;|2#x],2_x};{.[xexp;|2#x],2_x};{.[mod;|2#x],2_x};{(*|x),-1_x};
{(1_x),*x};{(*x),x};{(2#x),x};{(|2#x),2_x};{,/(|2 2#x),4_x};1_)[y]x}/
0x01010b0c050c050b0905
8 4 6 2
```
There's a fair amount of repetition in the implementation of similar instructions, which can be probably be engineered away to some extent.
[Answer]
# C ~~924~~ ~~882~~ ~~622~~ ~~603~~ ~~587~~ ~~569~~ 562 chars
With obvious newlines removed (retained for readability).
```
#define A sbrk(8);signal(11,S);
#define W(x)write(1,x,1);
#define P (t>s?*--t:0)
#define U *t++
#define B(x,y)else if(b==(w=w+1 x)){w=P;y;U=w;}
*t,*s,w,a,d;char b;S(x){A}
p(x){if(x<0){W("-")x=-x;}if(x>9)p(x/10);b=48+x%10;W(&b)}
main(c){t=s=A U=0;
while(read(0,&b,1))if(!(w=47));
B(,w+=P*pow(10,w?ceil(log10(w)):1))
B(,++w)
B(,--w)
B(,w*=P)
B(,w=P/w)
B(,w+=P)
B(,w=P-w)
B(,w=pow(P,w))
B(,w=P%w)
B(,w=*s;memmove(s,s+1,t-s<<2))
B(+7,memmove(s+1,s,t++-s<<2);*s=w;w=P)
B(,U=w)
B(,a=P;U=a;U=w;U=a)
B(,a=P;U=w;w=a)
B(,a=P;c=P;d=P;U=a;U=w;U=c;w=d)
B(,w=P)
for(W("[")t>s;)p(P),W(" ")
W("]")}
```
This implements the "underflow pushes zero" interpretation from Jan Dvorak's comment.
The golfed version actually changed substantially compared to the ungolfed version here, under the (welcome) pressure of [Oberon's fine answer](https://codegolf.stackexchange.com/a/19319/2381).
I found that replacing the `switch` statement in favor of an `if`...`else` chain enabled me to factor-out all of the digits from my *cases*. Instead it initializes the `w` variable to 47 so one increment raises it to 48 (== ascii `'0'`) then each case increments `w` until we need to skip to `'A'` at which point we make use of the mostly empty first macro argument which adds an extra 7 to get up to 'A'. The ungolfed version *does* show my favorite `sbrk`/`SIGSEGV` trick to get "free" memory with no further allocations.
```
#include<math.h>
#include<signal.h>
void S(int x){signal(SIGSEGV,S);sbrk(8*8*8);}
int*s,*t,*i,w,a,c,d; //stack top index working accumulator count data
u(x){*t++=x;} //push()
o(){return t>s?*--t:0;} //pop()
#define W(x)write(1,&x,1); //output a byte
p(x){ //print()
if(x<0){ //negative?
W(*"-") //output '-'
x=-x; //negate
}
if(x>9) //more than one digit?
p(x/10); //recurse after integer-divide
b=48+x%10; //isolate and convert single digit to ascii
W(b) //output ascii digit
}
main(){
char b[1];
signal(SIGSEGV,S); //auto-allocate memory for stack
t=s=sbrk(8*8*8); //get start of memory and allocate
while(read(0,b,1)){
write(1,b,1); //for debugging: echo the command being executed
switch(*b){
case '0': w=o(); a=o(); for(c=ceil(log10(w));c>0;c--) a*=10; u(a+w); break;
case '1': u(o()+1); break;
case '2': u(o()-1); break;
case '3': w=o(); u(o()*w); break;
case '4': w=o(); u(o()/w); break;
case '5': u(o()+o()); break;
case '6': w=o(); u(o()-w); break;
case '7': c=o();a=1; for(w=o();c>0;c--) a*=w; u(a); break;
case '8': w=o(); u(o()%w); break;
case '9': w=*s; memmove(s,s+1,4*(t-s-1)); t[-1]=w; break;
case 'A': w=t[-1]; memmove(s+1,s,4*(t-s-1)); *s=w; break;
case 'B': w=o(); u(w); u(w); break;
case 'C': w=o(); a=o(); u(a); u(w); u(a); u(w); break;
case 'D': w=o(); a=o(); u(w); u(a); break;
case 'E': w=o(); a=o(); c=o(); d=o(); u(a); u(w); u(d); u(c); break;
case 'F': o(); break;
}
}
write(1,"\n[",2); //dump the stack
i=t;
do {
p(*--i);
} while(i>s && write(1,",",1));
write(1,"]\n",2);
}
```
[Answer]
### R, 428 characters
```
f=function(I){s=0;for(i in strsplit(I,"")[[1]]){r=s[-(1:2)];s=switch(i,'0'=c(as.integer(paste0(s[2],s[1])),r),'1'=c(s[1]+1,s[-1]),'2'=c(s[1]-1,s[-1]),'3'=c(s[1]*s[2],r),'4'=c(s[2]%/%s[1],r),'5'=c(s[1]+s[2],r),'6'=c(s[1]-s[2],r),'7'=c(s[2]^s[1],r),'8'=c(s[2]%%s[1],r),'9'=c(s[length(s)],s[-length(s)]),'A'=c(s[-1],s[1]),'B'=c(rep(s[1],2),s[-1]),'C'=c(rep(s[1:2],2),r),'D'=c(s[2:1],r),'E'=c(s[3:4],s[1:2],s[-(1:4)]),'F'=s[-1])};s}
```
With indentations:
```
f=function(I){
s=0
for(i in strsplit(I,"")[[1]]){
r=s[-(1:2)]
s=switch(i,
'0'=c(as.integer(paste0(s[2],s[1])),r),
'1'=c(s[1]+1,s[-1]),
'2'=c(s[1]-1,s[-1]),
'3'=c(s[1]*s[2],r),
'4'=c(s[2]%/%s[1],r),
'5'=c(s[1]+s[2],r),
'6'=c(s[1]-s[2],r),
'7'=c(s[2]^s[1],r),
'8'=c(s[2]%%s[1],r),
'9'=c(s[length(s)],s[-length(s)]),
'A'=c(s[-1],s[1]),
'B'=c(rep(s[1],2),s[-1]),
'C'=c(rep(s[1:2],2),r),
'D'=c(s[2:1],r),
'E'=c(s[3:4],s[1:2],s[-(1:4)]),
'F'=s[-1])
}
s
}
```
In action:
```
> f('11BC5C5B95')
[1] 8 6 4 2
```
[Answer]
## JavaScript, 685
Non-golfed version ([gist](https://gist.github.com/ooflorent/8609899)):
```
var Token = {
Concatenate: '0',
Increment: '1',
Decrement: '2',
Multiply: '3',
Divide: '4',
Add: '5',
Subtract: '6',
Exponent: '7',
Modulus: '8',
RotateRight: '9',
RotateLeft: 'A',
Duplicate: 'B',
DoubleDuplicate: 'C',
Swap: 'D',
DoubleSwap: 'E',
Delete: 'F'
};
function parse(input, mem) {
var a, b, c, d;
var stack = mem ? mem.slice() : [0];
for (var i = 0, n = input.length; i < n; i++) {
switch (input[i]) {
case Token.Concatenate:
a = stack.pop();
b = stack.pop();
stack.push(parseInt([b] + a));
break;
case Token.Increment:
a = stack.pop();
stack.push(a + 1);
break;
case Token.Decrement:
a = stack.pop();
stack.push(a - 1);
break;
case Token.Multiply:
a = stack.pop();
b = stack.pop();
stack.push(b * a);
break;
case Token.Divide:
a = stack.pop();
b = stack.pop();
stack.push(b / a | 0);
break;
case Token.Add:
a = stack.pop();
b = stack.pop();
stack.push(b + a);
break;
case Token.Subtract:
a = stack.pop();
b = stack.pop();
stack.push(b - a);
break;
case Token.Exponent:
a = stack.pop();
b = stack.pop();
stack.push(Math.pow(b, a));
break;
case Token.Modulus:
a = stack.pop();
b = stack.pop();
stack.push(b % a);
break;
case Token.RotateRight:
a = stack.shift();
stack.push(a);
break;
case Token.RotateLeft:
a = stack.pop();
stack.unshift(a);
break;
case Token.Duplicate:
a = stack[stack.length - 1];
stack.push(a);
break;
case Token.DoubleDuplicate:
a = stack[stack.length - 1];
b = stack[stack.length - 2];
stack.push(b, a);
break;
case Token.Swap:
a = stack.pop();
b = stack.pop();
stack.push(a, b);
break;
case Token.DoubleSwap:
a = stack.pop();
b = stack.pop();
c = stack.pop();
d = stack.pop();
stack.push(b, a, d, c);
break;
case Token.Delete:
stack.pop();
break;
default:
throw new SynxtaxError('Invalid token "' + input[i] + '"');
}
}
return stack.reverse();
}
exports.Token = Token;
exports.parse = parse;
```
Golfed version:
```
function f(c){var b,d,e,f,a=[i=0],g=c.length;a.a=a.pop;for(a.b=a.push;i<g;i++)switch(c[i])
{case"0":b=a.a();a.b(parseInt([a.a()]+b));break;case"1":a[a.length-1]++;break;case"2":
a[a.length-1]--;break;case"3":a.b(a.a()*a.a());break;case"4":b=a.a();a.b(a.a()/b|0);break;
case"5":a.b(a.a()+a.a());break;case"6":b=a.a();a.b(a.a()-b);break;case"7":b=a.a();
a.b(Math.pow(a.a(),b));break;case"8":b=a.a();a.b(a.a()%b);break;case"9":a.b(a.shift());break;
case"A":a.a();a.unshift(a.a());break;case"B":a.b(a[a.length-1]);break;case"C":
a.b(a[a.length-2],a[a.length-1]);break;case"D":b=a.a();a.b(b,a.a());break;case"E":b=a.a();
d=a.a();e=a.a();f=a.a();a.b(d,b,f,e);break;case"F":a.a()}return a.reverse()}
```
Example:
```
> f('11BC5C5B95')
[ 8, 6, 4, 2]
```
[Answer]
# Haskell
```
import Data.List (elemIndex)
type Stack = [Integer]
u :: (Integer -> Integer) -> Stack -> Stack
u p (x:t) = p x : t -- unary operation
b :: (Integer -> Integer -> Integer) -> Stack -> Stack
b p (x:y:t) = p x y : t -- binary operation
encoding :: String
encoding = "$iv*/+-^%><dtsz."
-- encoding = "0123456789ABCDEF"
-- list of operations
ops :: [Stack -> Stack]
ops = [
b (\x y -> read (show x ++ show y)),-- concatenation
u (+1), -- increment
u (subtract 1), -- decrement
b (*), -- multiplication
b div, -- division
b (+), -- addition
b (-), -- subtraction
b (^), -- exponent
b mod, -- modulus
(\s -> last s : init s), -- rotate right
(\(x:t) -> t ++ [x]), -- rotate left
(\(x:t) -> x:x:t), -- duplicate
(\(x:y:t) -> x:y:x:y:t), -- double duplicate
(\(x:y:t) -> y:x:t), -- swap
(\(x:y:x':y':t) -> x':y':x:y:t), -- double swap
tail] -- pop
run :: String -> Maybe Stack
run code = run' code [0] where
run' [] stack = Just stack
run' (x:t) stack = elemIndex x encoding >>= run' t . ($stack) . (ops!!)
```
Running
```
λ: run "diidt^svz"
Just [2,0,1,4]
```
[Answer]
# Common Lisp - 589
Accepts hex input without spaces.
```
(setf w'(0))(defmacro u(&rest b)`(let((a(pop w))(b(pop w))),@b))(defmacro v(s)`(u(push(funcall ,s b a)w)))(setf i(list'(u(push(parse-integer(append(write-to-string b)(write-to-string a)))w))'(incf(car w))'(decf(car w))'(v #'*)'(v #'/)'(v #'+)'(v #'-)'(v #'expt)'(v #'%)'(let((a (car(last w))))(nbutlast w)(push a w))'(let((a(pop w)))(nconc w(list a)))'(push(car w)w)'(progn(push(cadr w)w)(push(cadr w)w))'(u(push a w)(push b w))'(u(push a(cdr(nthcdr 2 w)))(push b(cdr(nthcdr 2 w))))'(pop w)))(mapcar(coerce(read-line)'list)(lambda(a)(eval(nth(parse-integer(string a):radix 16)i)))(print w)
```
Ungolfed:
```
(defparameter *stack* '(0))
(defmacro topvalues (&rest body)
`(let ((top1 (pop *stack*))
(top2 (pop *stack*))) ,@body))
(defmacro simple-op (opsym &rest body)
`(topvalues
(push (funcall ,opsym top2 top1) *stack* )))
(defparameter *ops*
(list
;concatenate
'(topvalues
(push
(parse-integer (append (write-to-string b) (write-to-string a)))
*stack*))
;increment
'(incf (first *stack*))
;decrement
'(decf (first *stack*))
;multiply
'(simple-op #'*)
;divide
'(simple-op #'/)
;add
'(simple-op #'+)
;subtract
'(simple-op #'-)
;exponent
'(simple-op #'expt)
;modulus
'(simple-op #'%)
;rotate right
'(let ((a (car (last *stack*))))
(nbutlast *stack*)
(push a *stack*))
;rotate left
'(let ((a (pop *stack*)))
(nconc *stack* (list a)))
;duplicate
'(push (first *stack*) *stack*)
;double duplicate
'(progn
(push (second *stack*) *stack*)
(push (second *stack*) *stack*))
;swap
'(topvalues
(push top1 *stack*)
(push top2 *stack*))
;double swap
'(topvalues
(push top1 (cdr (nthcdr 2 *stack*)))
(push top2 (cdr (nthcdr 2 *stack*))))
;delete/pop
'(pop *stack*)))
(mapcar
(lambda (a)
(eval (nth (parse-integer (string a) :radix 16) *ops*)))
(coerce (read-line) 'list))
```
[Answer]
## PHP
it's not the prettiest one, but it works.
runs from shell, expects a filename as first argument. it accepts any of the 3 dialects (even mixed)
behaviour not defined for negatives or missing index
```
<?php
$f[0] = $f[48] = $f[36] = function(&$s){$v=array_shift($s);$s[0] .= $v;};
$f[1] = $f[49] = $f[105] = function(&$s){$s[0]++;};
$f[2] = $f[50] = $f[118] = function(&$s){$s[0]--;};
$f[3] = $f[51] = $f[42] = function(&$s){$v = array_shift($s); $s[0] *= $v;};
$f[4] = $f[52] = $f[47] = function(&$s){$v = array_shift($s); $s[0] = intval(floor($s[0] / $v));};
$f[5] = $f[53] = $f[43] = function(&$s){$v = array_shift($s); $s[0] += $v;};
$f[6] = $f[54] = $f[45] = function(&$s){$v = array_shift($s); $s[0] -= $v;};
$f[7] = $f[55] = $f[94] = function(&$s){$v = array_shift($s); $s[0] = pow($s[0], $v);};
$f[8] = $f[56] = $f[37] = function(&$s){$v = array_shift($s); $s[0] %= $v;};
$f[9] = $f[57] = $f[62] = function(&$s){$v = array_pop($s); array_unshift($s, $v);};
$f[10] = $f[65] = $f[60] = function(&$s){$v = array_shift($s); array_push($s, $v);};
$f[11] = $f[66] = $f[100] = function(&$s){array_unshift($s, $s[0]);};
$f[12] = $f[67] = $f[116] = function(&$s){$v = [$s[0], $s[1]]; array_unshift($s, $v[0], $v[1]);};
$f[13] = $f[68] = $f[115] = function(&$s){$v = $s[0]; $s[0] = $s[1]; $s[1] = $v;};
$f[14] = $f[69] = $f[122] = function(&$s){$v = $s[0]; $s[0] = $s[2]; $s[2] = $v; $v = $s[1]; $s[1] = $s[3]; $s[3] = $v;};
$f[15] = $f[70] = $f[46] = function(&$s){array_unshift($s);};
$stack = [0];
$file = fopen($argv[1], 'rb');
$size = filesize($argv[1]);
while($size--){
$f[ord(fread($file, 1))]($stack);
}
fclose($file);
echo '['.implode(',',$stack)."]\n";
```
[Answer]
# PureBasic - 2821 891 chars
This is an interactive interpreter - no file, you just enter the codes given 0-9, A-F, and it will execute that command, and display as the example post displays it.
Use "X" or "Q" to quit.
This was really fun to do :)
```
Global NewList ProgramStack.q()
Global Num1.q, Num2.q
Macro Push(Value)
LastElement(ProgramStack())
AddElement(ProgramStack())
ProgramStack() = Value
EndMacro
Macro Pop(Variable)
LastElement(ProgramStack())
Variable = ProgramStack()
DeleteElement(ProgramStack())
EndMacro
Macro Peek(Variable)
LastElement(ProgramStack())
Variable = ProgramStack()
EndMacro
Push(0)
Procedure Concatenate()
Pop(Num1)
Pop(Num2)
Push(Val( Str(Num2) + Str(Num1) ))
EndProcedure
Procedure Increment()
LastElement(ProgramStack())
ProgramStack() + 1
EndProcedure
Procedure Decrement()
LastElement(ProgramStack())
ProgramStack() - 1
EndProcedure
Procedure Multiply()
Pop(Num1)
Pop(Num2)
Push( Num2 * Num1 )
EndProcedure
Procedure Divide()
Pop(Num1)
Pop(Num2)
Push( Num2 / Num1 )
EndProcedure
Procedure Add()
Pop(Num1)
Pop(Num2)
Push( Num2 + Num1 )
EndProcedure
Procedure Subtract()
Pop(Num1)
Pop(Num2)
Push( Num2 - Num1 )
EndProcedure
Procedure Exponent()
Pop(Num1)
Pop(Num2)
Push( Pow(Num2, Num1) )
EndProcedure
Procedure Modulus()
Pop(Num1)
Pop(Num2)
Push( Mod(Num2, Num1) )
EndProcedure
Procedure RotateRight()
FirstElement(ProgramStack())
Num1 = ProgramStack()
DeleteElement(ProgramStack(),1)
Push(Num1)
EndProcedure
Procedure RotateLeft()
Pop(Num1)
FirstElement(ProgramStack())
InsertElement(ProgramStack())
ProgramStack() = Num1
EndProcedure
Procedure Duplicate()
Peek(Num1)
Push(Num1)
EndProcedure
Procedure DoubleDuplicate()
Pop(Num1)
Pop(Num2)
Push(Num2)
Push(Num1)
Push(Num2)
Push(Num1)
EndProcedure
Procedure SingleSwap()
Pop(Num1)
Pop(Num2)
Push(Num1)
Push(Num2)
EndProcedure
Procedure DoubleSwap()
Protected Num3.q, Num4.q
Pop(Num1)
Pop(Num2)
Pop(Num3)
Pop(Num4)
Push(Num2)
Push(Num1)
Push(Num4)
Push(Num3)
EndProcedure
Procedure Delete()
Pop(Num1)
EndProcedure
OpenConsole()
EnableGraphicalConsole(1)
Position = 0
Repeat
ConsoleLocate(Position, 0)
e.s = UCase( Inkey() )
Select e
Case "0"
Concatenate()
Case "1"
Increment()
Case "2"
Decrement()
Case "3"
Multiply()
Case "4"
Divide()
Case "5"
Add()
Case "6"
Subtract()
Case "7"
Exponent()
Case "8"
Modulus()
Case "9"
RotateRight()
Case "A"
RotateLeft()
Case "B"
Duplicate()
Case "C"
DoubleDuplicate()
Case "D"
SingleSwap()
Case "E"
DoubleSwap()
Case "F"
Delete()
EndSelect
If e <> ""
Print(e)
ConsoleLocate(Position, 1)
Print("|")
yLoc.i = ListSize(ProgramStack()) + 1
ForEach ProgramStack()
ConsoleLocate(Position, yLoc)
Print(Str(ProgramStack()))
yLoc - 1
Next
Position + 2
EndIf
Until e = "X" Or e = "Q"
```
edit: After sleeping, I figured I'd golf it - I've left the readable version though for referencce.
Everything works the same except I've taken out the Q or X to quit, just close the window to quit:
```
NewList S()
Macro P
Print
EndMacro
Macro G
ConsoleLocate
EndMacro
Macro LE
LastElement(S())
EndMacro
Macro U(V)
LE
AddElement(S())
S()=V
EndMacro
Macro O(V)
LE
V=S()
DeleteElement(S())
EndMacro
U(0)
OpenConsole()
EnableGraphicalConsole(1)
X=0
Repeat
G(X,0)
e.s=UCase(Inkey())
Select e
Case"0"
O(H)
O(J)
U(Val(Str(J)+Str(H)))
Case"1"
LE
S()+1
Case"2"
LE
S()-1
Case"3"
O(H)
O(J)
U(J*H)
Case"4"
O(H)
O(J)
U(J/H)
Case"5"
O(H)
O(J)
U(J+H)
Case"6"
O(H)
O(J)
U(J-H)
Case"7"
O(H)
O(J)
U(Pow(J,H))
Case"8"
O(H)
O(J)
U(Mod(J,H))
Case"9"
FirstElement(S())
H=S()
DeleteElement(S(),1)
U(H)
Case"A"
O(H)
FirstElement(S())
InsertElement(S())
S()=H
Case"B"
O(H)
U(H)
U(H)
Case"C"
O(H)
O(J)
U(J)
U(H)
U(J)
U(H)
Case"D"
O(H)
O(J)
U(H)
U(J)
Case"E"
O(H)
O(J)
O(K)
O(L)
U(J)
U(H)
U(L)
U(K)
Case"F"
O(H)
EndSelect
If e<>""
P(e)
G(X,1)
Y=ListSize(S())+1
ForEach S()
G(X,Y)
P(Str(S()))
Y-1
Next
X+2
EndIf
ForEver
```
[Answer]
# Common Lisp - 586
```
(defmacro n(s)(with-gensyms($)(labels((?()`(pop,$))(!(x)`(push,x,$))(@(~)(!(list ~(?)(?))))(r@(~)(@`(lambda(x y)(,~ y x)))))`(let((,$`(,0))),@(loop for p below(length s)collect(case(parse-integer s :start p :end(1+ p):radix 16)(0(@'(lambda(a b)(+(* a(expt 10(if(> b 0)(ceiling(log b 10))1)))b))))(1`(incf(car,$)))(2`(decf(car,$)))(3(@'*))(4(@'/)) (5(@'+))(6(@'-))(7(r@'expt))(8(r@'mod))(9`(setf,$(#1=rotate,$)))(10`(setf,$(#1#,$ -1)))(11`(push(car,$),$))(12`(setf,$(nconc(#2=subseq,$ 0 2),$)))(13`(reversef(#2#,$ 0 2)))(14`(setf,$(append(#1#(#2#,$ 0 4)2)(#2#,$ 4))))(15`(pop,$)))),$))))
```
# Ungolfed
Lexically binds a fresh stack in the macroexpanded code: no reference to a global variable. Also, it is compiled down to machine code.
```
(ql:quickload :alexandria)
(mapc #'use-package '(cl alexandria))
(defmacro n(s)
(with-gensyms($)
(labels ((?()`(pop,$))
(!(x)`(push,x,$))
(bop(op)(!(list op(?)(?))))
(rbop(op)(bop`(lambda(x y)(,op y x)))))
`(let((,$`(,0)))
,@(loop for p below(length s)
collect(case(parse-integer s :start p :end(1+ p):radix 16)
(#x0(bop'(lambda(a b)(+(* a(expt 10(if(> b 0)(ceiling(log b 10))1)))b))))
(#x1`(incf(car,$)))
(#x2`(decf(car,$)))
(#x3(bop'*))
(#x4(bop'/))
(#x5(bop'+))
(#x6(bop'-))
(#x7(rbop'expt))
(#x8(rbop'mod))
(#x9`(setf,$(rotate,$)))
(#xA`(setf,$(rotate,$ -1)))
(#xB`(push(car,$),$))
(#xC`(setf,$(nconc(subseq,$ 0 2),$)))
(#xD`(reversef(subseq ,$ 0 2)))
(#xE`(setf,$(append(rotate(subseq,$ 0 4)2)(subseq,$ 4))))
(#xF`(pop,$))))
,$))))
```
# Example
```
(n "11bc5c5b95")
=> macroexpands into (8 6 4 2)
```
[Answer]
# Python 2, 508 bytes
```
s,d=[0],lambda:s.pop(1)
for C in raw_input():
D=int(C,16)
if D<1:s[0]=int(`s[0]`+`d()`)
if D==1:s[0]+=1
if D==2:s[0]-=1
if D==3:s[0]*=d()
if D==4:s[0]=d()/s[0]
if D==5:s[0]+=d()
if D==6:s[0]-=d()
if D==7:s[0]=d()**s[0]
if D==8:s[0]=d()%s[0]
if D==9:s=s[-1:]+s[:-1]
if D==10:s=s[1:]+s[:1]
if D==11:s=s[:1]+s
if D==12:s=s[0:2]+s
if D==13:s=s[1:2]+s[:1]+s[2:]
if D==14:s=s[2:4]+s[0:2]+s[4:]
if D>14:s=s[1:]
print s
```
Uses "0123456789ABCDEF" encoding. I'm really proud in how this one turned out. It doesn't read file, it gets input from STDIN, but if that's a problem it could easily be changed.
2 solutions for the 2014 problem:
`B11CB3A1AED0A00` (~~16~~ 15 bytes) - Generic Concatenator.
`BB102CD11B513B3622E` (~~20~~ 19 bytes) - Much cooler - Evaluates to (5\*(10-1))^2-11
[Answer]
# Python 2, 955 bytes
```
import sys
global s
s=[0]
c=lambda x: x.append(str(x.pop())+str(x.pop()))
i=lambda x: x.append(x.pop()+1)
v=lambda x: x.append(x.pop()-1)
x=lambda x: x.append(x.pop()*x.pop())
q=lambda x: x.append(x.pop(-2)/x.pop())
a=lambda x: x.append(x.pop()+x.pop())
w=lambda x: x.append(x.pop(-2)-x.pop())
e=lambda x: x.append(x.pop(-2)**x.pop())
m=lambda x: x.append(x.pop(-2)%x.pop())
r=lambda x: x.append(x.pop(0))
l=lambda x: x.insert(0,x.pop())
d=lambda x: x.append(x[-1])
t=lambda x: x.extend(x[-2:])
s=lambda x: x.insert(-2,x.pop())
def z(x):
for y in [0,1]:
s.insert(-3,s.pop())
k={'$':c,'i':i,'v':v,'*':x,'/':q,'+':a,'-':w,'^':e,'%':m,'>':r,'<':l,'d':d,
't':t,'s':s,'z':z,'.':lambda x: x.pop()}
if __name__=='__main__':
with open(sys.argv[1],'r') as f:
while 1:
b=f.read(1)
if not b or b not in k.keys():
break
else:
n=k[b](s)
for x in s: print s,
```
# What each function does
* **c:** concatenate ($)
* **i:** increment (i)
* **v:** decrement (v)
* **x:** multiply (\*)
* **q:** divide (/)
* **a:** add (+)
* **w:** subtract (-)
* **e:** exponent (^)
* **m:** modulo (%)
* **r:** right shift (>)
* **l:** left shift (<)
* **d:** duplicate (d)
* **t:** duplicate twice (t)
* **s:** swap top 2 values (s)
* **z:** double swap (z)
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/16702/edit)
There are a range of questions revolving around this concept, but these all seem to just involve causing a crash, resulting in many answers which are very obviously designed to cause a crash. So the challenge I set you is to write some plausible code (although what the codes supposed "intention" is I leave up to you), that crashes either the entire target OS, or just itself, in a way which is not immediately obvious. (I realize that what counts as "immediately obvious" is subjective, but hopefully the challenge is still reasonably clear).
The winner is the answer with the most votes after 5 days.
[Answer]
# C, linux. Crashes system if run as root
```
/* Fork child process, wait 5 seconds and kill it */
pid_t pid = fork();
if(pid =! 0) {
/* Parent */
sleep(5);
kill(pid, 11);
}
else {
/* Child process. Would contain some code */
}
```
By changing `!=` to `=!`, an innocent comparison is turned into an assignment. And given that pid 1 is `init`, and killing `init` causes a kernel panic, this is not code you would want to run as root :)
[Answer]
## C#
Let's just initialize a list of bytes with every byte value from 0 to 255.
```
List<byte> bytes = new List<byte>();
for (byte i = 0; i <= 255; i++)
{
bytes.Add(i);
}
```
Out of memory? I distinctly recall having more than 256 bytes installed...
**Spoiler:**
>
> A byte will *always* be less than or equal to 255. Addition wraps around from 255 to 0.
>
>
>
[Answer]
# **C**
```
#include <stdio.h>
int main(void) {
fputs(stdout, "Hello, world!\n");
return 0;
}
```
(Compiler warnings will give it away.)
[Answer]
# JavaScript
```
var arr = [3,6,1,54,2,-4,8,10,3,7]
function qs(a) {
if (a.length < 2) return a
var part = a.shift()
var higher = [], lower = []
for (var i = 0; i < a.length; i ++) {
var x = a[i] // *** THIS LINE ***
(x < part ? lower : higher).push(x)
}
return qs(lower).concat([part]).concat(qs(higher))
}
alert(qs(arr))
```
Working quicksort, except for the fact that lack of semicolon on the line I marked with a comment causes it to parse wrong and crash.
Adding a semicolon at the end of that line fixes it.
[Answer]
# C++
Inputs names and store them in a vector. Prints names upon entry of flag value. Asks if user thought of more names; if so, inputs names.
```
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void print(const vector<string>& v) {
for (int i = 0; i <= names.size(); i++)
cout << v[i] << endl;
}
void input(vector<string>& v) {
string tmp;
cout << "Enter a list of names seperated by returns: ";
do {
getline(cin, tmp);
if (tmp != "-1")
v.push_back(tmp);
} while (tmp != "-1");
print(v);
}
int main() {
vector<string> names;
string tmp;
do {
input(names);
cout << "Do you have any more names to input (y or n)? ";
cin >> tmp;
} while (tmp == "y");
return 0;
}
```
For non-C++, Java, C users, the error is in `print()`s `for` statement. It should be `for (int i = 0; i < names.size(); i++)`. This is an easy error to make and overlook (until you get the compiler message) because it is only 1 character and because the >= operator is sometimes required in `for` loops.
[Answer]
## [GTB](http://timtechsoftware.com/gtb "GTB")
```
:""→_[_+"+"→_]
```
Crashes the calculator because `[_+` should be `["_"+`, but since it isn't, the calculator runs out of memory, potentially clearing the RAM in the wrong way.
]
|
[Question]
[
Assign the numbers 0 through 7 to the 8 vertices of a cube in any way you want. Exactly one number must be assigned to each vertex.
For example, your vertices might be assigned like this:
```
3-----1
/| /|
4-----2 |
| | | |
| 5---|-0
|/ |/
6-----7
```
Write a program that takes in an integer from 0 to 5. Each of these 6 numbers is associated with exactly one face of your cube in any way you like. When one of these numbers is input, the 4 vertex numbers of the associated face must be printed to stdout in a 2×2 square of digits. The face is to be viewed straight on from outside the cube. All 4 face rotations are valid.
For example, if 0 is associated with the front face of the example cube above, then this would be a valid output for input `0`:
```
42
67
```
The face may be viewed at any 90° rotation, so these are also valid:
```
27
46
```
```
76
24
```
```
64
72
```
This output (and its rotations) are **not valid**, as they are viewed from the wrong side of the face:
```
24
76
```
The same idea applies to all other faces. e.g. if 1 is associated with the back face, then input `1` might produce output `13[newline]05` (and `31[newline]50` would be invalid).
So the real challenge is choosing your vertex numbers and rotations such that translating the input into its 4 vertex numbers is easy and short.
**The shortest code in bytes wins. Tiebreaker is earlier post.** ([Handy byte counter.](https://mothereff.in/byte-counter))
### Notes
* You may write a function instead of a program. It should take an integer from 0 to 5 and print or return the 2×2 digit grid string.
* Take input from stdin, command line, or function arg. You may assume input is valid.
* The output may optionally have a trailing newline.
* Be sure to tell us the vertex and face numbers you chose.
[Answer]
# CJam, ~~23~~ 16 bytes
There's probably an elegant mathematical solution to this problem. ~~But I have no clue how to find one, so super compressed hard coding it is!~~
I found one! Well, it's not a classically elegant mathematical solution as it uses bitwise operations, but it is entirely formulaic.
```
li_o1^_p_6|o3+6%
```
[Try it online.](http://cjam.aditsu.net/#code=li_o1%5E_p_6%7Co3%2B6%25&input=0)
### Cube layout
```
4-----7 4-----7 3-----2
/| /| / 0 /| / 3 /|
1-----0 | 1-----0 | 6-----5 |
| | | | | |2| | |4|
| 5---|-2 | 1 | 2 | 5 | 7
|/ |/ | |/ | |/
6-----3 6-----3 1-----4
```
### Explanation
My old answer already laid out the cube such that each face can be described with its first (top-left) vertex number equal to the face number. But I wanted to be able to calculate more vertex numbers using the face number. At some point, I came up with the idea that got my foot in the door, to calculate the second (top-left) vertex number as the face number XOR 1. And after a while of trial and error, I managed to come up with the layout shown above and the formulas below that allow me to to calculate *every* vertex number for a face `n` quite succinctly:
* Top-left: `n`
* Top-right: `n^1`
* Bottom-left: `(n^1)|6`
* Bottom-right: `((n^1)+3)%6`
For reference, I'll reproduce the output for each face in the desired layout here:
```
Face: 0 1 2 3 4 5
Vertices: 01 10 23 32 45 54
74 63 70 65 72 61
```
So the whole program just comes down to reading the input face number and producing these values in order, albeit with slightly different printing logic for different vertices. Note that, because every vertex after the first starts with a base of `n^1`, I only need to calculate that once, which compacts the logic even further.
---
*For posterity's sake, and because I think it was still a pretty good approach, here's my old answer.*
# CJam, 23 bytes
There's probably an elegant mathematical solution to this problem. But I have no clue how to find one, so super compressed hard coding it is!
```
"pÜ×ñè¨"487b8b3/ri_o=~p
```
[Try it online.](http://cjam.aditsu.net/#code=%22p%C3%9C%C3%97%C3%B1%C3%A8%C2%A8%22487b8b3%2Fri_o%3D~p&input=0)
### Cube layout
```
0-----7 0-----7 3-----6
/| /| / 0 /| / 3 /|
1-----2 | 1-----2 | 4-----5 |
| | | | | |2| | |5|
| 5---|-6 | 1 | 6 | 4 | 7
|/ |/ | |/ | |/
4-----3 4-----3 1-----0
```
### Explanation
The basic approach employed is to hard code the vertices for each face in as little space as possible. Similarly to Optimizer's base conversion solution, this treats the vertex list as an octal number packed as ASCII character data. But that's about where the similarities end to make way for further optimizations!
Here are the three key optimizations I made to the "naive" solution:
* Lay out the cube such that each face can be described with its face number as the first vertex number. Looking at my cube layout as presented above, one can see that the top-left vertex number of each face is equal to the face number. This allows me to encode six fewer vertices at the cost of having to print the input back, which turns out to save a byte.
* Pack the vertex data into a string for which each "character" has a maximum larger than 256. As this maximum increases past 256, the length of the string slowly decreases, but it becomes increasingly likely that any one "character" exceeds 256 and is thus no longer part of the 1-byte ASCII character set. So I wrote a program that tries encoding the vertex data in every base from 256 to 1000, with which I found about 10 bases that save one byte of character data compared to base 256. I chose 487, as that also has the nice property that the resulting string consists entirely of printable ASCII.
* Mixed with the first optimization, produce the output asymetrically. The usual approach in CJam would be to format the vertex data as a 2-element list of 2-element lists, insert a newline in the middle, and let the output be implicitly printed. But I instead print the first vertex (equal to the input face number) with an operator that doesn't add a newline, retrieve the 3-element list of the other vertices, grab the next vertex and print it with an operator that does add a newline, and let the other two vertices be implicitly printed. This saves a byte.
[Answer]
# C,69
```
f(c){int d=c++%2*2-1;printf("%d%d\n%d%d",(c-d)%6,c%6,c%2+6,(c+d)%6);}
```
**Ungolfed in test program**
```
f(c){
int d=c++%2*2-1;
printf("%d%d\n%d%d",(c-d)%6,c%6,c%2+6,(c+d)%6);
}
int n;
main(){
scanf("%d",&n);
f(n);
}
```
**Explanation**
My cube numbering, when unfolded, looks like this:
```
0---7
| |
| 0 |
| |
1---2---7
| | |
| 1 | 2 |
| | |
6---3---4---7
| | |
| 3 | 4 |
| | |
6---5---0
| |
| 5 |
| |
6---1
```
The top left corner has the same number as the face.
The bottom right corner has number `(n+2)%6`
For odd `n` the top right corner is `(n+1)%6` and the bottom left is `6`
For even `n` the top right corner is `7` and the bottom left is `(n+1)%6`
The program displays the odd numbers as shown and the even numbers rotated 180 degrees. This means that the top right corner is always `(n+1)%6` and the bottom left is always `(n+1)%2+6`. Inverting `n` and `n+2` is easier (it is done by setting `c=n+1` and using `d` to add or subtract `1` or `-1` as necessary.)
**Output**
```
$ ./a
0
21
70
$ ./a
1
12
63
$ ./a
2
43
72
$ ./a
3
34
65
$ ./a
4
05
74
$ ./a
5
50
61
```
[Answer]
# Element, 18
```
_4:2%6+``2+6%`-5+`
```
Unlike many more advanced golfing languages, Element does not have a compression operator, so the brevity of the solution is tied rather closely to the exact numbering scheme used. After some experimentation, I have created a new numbering scheme which allows the vertices to be computed using only simple arithmetic operations.
```
1-----0 1-----0 2-----5
/| /| / 4 /| / 3 /|
4-----6 | 4-----6 | 3-----7 |
| | | | | |0| | |5|
| 7---|-5 | 2 | 5 | 1 | 0
|/ |/ | |/ | |/
3-----2 3-----2 4-----1
```
The top-left corner is 6 if even and 7 if odd. The top-right corner is the face number itself. The bottom-left is the face number, plus 2, mod 6. The bottom-right is 5 minus the face number.
Here is an explanation of the code.
```
_4:2%6+``2+6%`-5+`
_4: take input and make several copies of it
2%6+` take face #, mod 2, add 6, and output
` output input, which already has the newline attached
2+6%` take face #, add 2, mod 6, and output
-5+` negate face #, add 5, and output
```
Here are the outputs for each of the faces:
```
0
60
25
1
71
34
2
62
43
3
73
52
4
64
01
5
75
10
```
[Answer]
# Octave, ~~108~~ ~~100~~ ~~68~~ 50 bytes
Of course ther is a way of doing it way more elegant than my previous approaches, plain hardcoding. I am amazed how Octave is way more suitable for codegolf than Matlab=)
```
f=@(n)['040201375767';'261345154623'](:,2*n+(1:2))
```
## Layout:
(Sorry, I forgot to add this.)
### Cube layout
```
1-----5 1-----5 6-----7
/| /| / 2 /| / 5 /|
0-----4 | 0-----4 | 2-----3 |
| | | | | |4| | |3|
| 3---|-7 | 0 | 7 | 1 | 5
|/ |/ | |/ | |/
2-----6 2-----6 0-----1
```
## Old Versions:
```
f=@(n)[0 4 0 2 0 1 3 7 5 7 6 7;2 6 1 3 4 5 1 5 4 6 2 3](:,2*n+(1:2))
```
Even older Versions:
This is really gonna make a 2x2x2 array and then choosing a 'slice'. We do a 3d matrix permutation and each time choose the top or bottom slice. (This one does not work in matlab because of the indexing of an expression rather than a matrix)
I am sure there would be more direct ways of doing it that would be shorter.
```
f=@(n)squeeze(permute(reshape(0:7,2,2,2),circshift((1:3)',n))(n=fix(n/3)+1,circshift((1:2)',n-1),:))
f=@(n)squeeze(permute(reshape(0:7,2,2,2),circshift((1:3)',n))(floor(n/3)+1,circshift((1:2)',floor(n/3)),:))
```
[Answer]
# CJam, ~~31~~ 28 (or 26) bytes
```
8,2/W%_1m<]z[D75K46]2/+ri=N*
```
which can also be compressed using base conversion into a [26 bytes version](http://cjam.aditsu.net/#code=%22%C3%A5k_%C2%A4%C3%9EV%C2%96%C2%B6%C2%89%22255b8b2%2F2%2Fri%3DN*&input=3).
Assumes the cube to be like:
```
7-----1
/| /|
5-----3 |
| | | |
| 6---|-0
|/ |/
4-----2
```
with faces like
```
7-----1 .-----. .-----. .-----.
/ 4 /| / 4 /| / 4 /| / 0 /|
5-----3 | .-----. | .-----. | .-----. |
| |2| | |1| | |0| | |5|
| 1 | 0 | 0 | . | 3 | . | 3 | .
| |/ | |/ | |/ | |/
4-----2 .-----. .-----. .-----.
```
[Try it online here](http://cjam.aditsu.net/#code=8%2C2%2FW%25_1m%3C%5Dz%5BD75K46%5D2%2F%2Bri%3DN*&input=3)
[Answer]
## CJam (25 bytes)
```
"ñRXµ roM~"(ib65b2/q~=N*
```
This contains a non-printable character and a tab (which will be mangled by the StackExchange software), so in xxd format:
```
0000000: 22f1 5258 1fb5 0972 6f4d 7e22 2869 6236 ".RX...roM~"(ib6
0000010: 3562 322f 717e 3d4e 2a 5b2/q~=N*
```
[Online demo](http://cjam.aditsu.net/#code=%22%C3%B1RX%1F%C2%B5%09roM~%22%28ib65b2%2Fq~%3DN%2a&input=0)
Cube:
```
1-----0 Faces:
/| /| 10 46
4-----6 | 14 37
| | | | 20 31
| 3---|-2 23 57
|/ |/ 56 20
7-----5 57 64
```
This is pure hard-coding, with the cube vertices selected to maximise base compressibility. I decode to 2-digit numbers, so none of them can begin with 0. I don't want any to begin with 7 either, since that pushes the second base too high. Therefore 0 and 7 must be on a long diagonal. I want a 10 edge to go first to reduce the value I'm encoding. Other than that, there's a fair amount of flexibility without changing the byte count.
I'm slightly disappointed that having popped the first character from the magic string, it's necessary to cast it to an int before using it as a base for base conversion. Hopefully future versions of CJam will save that byte, although it will be too late to exploit that here.
[Answer]
# JavaScript (ES6), 53 ~~62~~
**Edit** Save 8 bytes using template strings, thx @NinjaBearMonkey. Beware, the newlines inside quotes are significant and cannot be collapsed.
Can't be clever in Javascript, it's too verbose.
```
f=n=>`01
23
45
67
01
31
5702
64`.substr(n-4?n*3:20,5)
```
*Output* `for(i=0;i<6;i++)console.log(f(i),i)`
>
> 01
>
> 23
>
> 0
>
>
> 23
>
> 45
>
> 1
>
>
> 45
>
> 67
>
> 2
>
>
> 67
>
> 01
>
> 3
>
>
> 02
>
> 64
>
> 4
>
>
> 31
>
> 57
>
> 5
>
>
>
See the snippet to veify the number associations (*that* was fun)
```
function P3D(x,y,z) {
this.x = x;this.y = y;this.z = z;
this.rotateX = angle => {
var rad = angle * Math.PI / 180,
cosa = Math.cos(rad),sina = Math.sin(rad),
y = this.y * cosa - this.z * sina,
z = this.y * sina + this.z * cosa
return new P3D(this.x, y, z)
}
this.rotateY = angle => {
var rad = angle * Math.PI / 180,
cosa = Math.cos(rad), sina = Math.sin(rad),
z = this.z * cosa - this.x * sina,
x = this.z * sina + this.x * cosa
return new P3D(x,this.y, z)
}
this.rotateZ = angle => {
var rad = angle * Math.PI / 180,
cosa = Math.cos(rad), sina = Math.sin(rad),
x = this.x * cosa - this.y * sina,
y = this.x * sina + this.y * cosa
return new P3D(x, y, this.z)
}
this.project = (viewWidth, viewHeight, fov, viewDistance) => {
var factor = fov / (viewDistance + this.z),
x = this.x * factor + viewWidth / 2,
y = this.y * factor + viewHeight / 2
return new P3D(x, y, this.z)
}
}
var vx = [
new P3D(-1,1,-1),
new P3D(1,1,-1),
new P3D(-1,-1,-1),
new P3D(1,-1,-1),
new P3D(-1,-1,1),
new P3D(1,-1,1),
new P3D(-1,1,1),
new P3D(1,1,1),
];
// Define the vx that compose each of the 6 faces. These numbers are
// indices to the vertex list defined above.
var faces = [[0,1,3,2],[2,3,5,4],[4,5,7,6],[6,7,1,0],[0,2,4,6],[1,3,5,7]]
faces.map((f,i)=>{
var mx=vx[f[0]].x+vx[f[1]].x+vx[f[2]].x+vx[f[3]].x,
my=vx[f[0]].y+vx[f[1]].y+vx[f[2]].y+vx[f[3]].y,
mz=vx[f[0]].z+vx[f[1]].z+vx[f[2]].z+vx[f[3]].z
vx[i+10]=new P3D(mx/4, my/4, mz/4)
f[4]=i
f[5]=i+10
})
var angle = 0;
var ctx = CV.getContext("2d");
setInterval(loop,33)
function loop() {
ctx.fillStyle = "#fff"
ctx.fillRect(0,0,400,200);
ctx.font = "20px Arial"
angle += 2
var t = vx.map(v=>
v
.rotateX(angle).rotateY(-angle).rotateZ(-angle)
.project(400,200,128,3)
)
ctx.strokeStyle = "#f00"
t.forEach((v,i)=>i<8?ctx.strokeText(i,v.x,v.y):0)
ctx.strokeStyle = "#428"
ctx.beginPath()
faces.forEach(f=>(
ctx.moveTo(t[f[0]].x,t[f[0]].y),
ctx.lineTo(t[f[1]].x,t[f[1]].y),
ctx.lineTo(t[f[2]].x,t[f[2]].y),
ctx.lineTo(t[f[3]].x,t[f[3]].y),
ctx.lineTo(t[f[0]].x,t[f[0]].y),
ctx.strokeText(f[4],t[f[5]].x,t[f[5]].y)
))
ctx.closePath(),
ctx.stroke()
}
```
```
<canvas id=CV width=400 height=200></canvas>
```
[Answer]
# Ruby Rev 1, ~~40~~ 36
`->(c){print(c^1,c,"\n",6|c,(c+3)%6)}`
Thanks to @rcrmn for suggesting using a lambda to save 4 bytes. I wasn't sure about leaving it anonymous but it seems to have been discussed on meta [here](http://meta.codegolf.stackexchange.com/a/1503/15599) and decided this was OK.
Here it is as a 40-byte function, for comparison with my Rev 0 Ruby answer, also below (Original C answer is in a separate post.)
```
def f(c)print(c^1,c,"\n",6|c,(c+3)%6)end
```
Further inspiration from Runer112: This relies on a modification of the numbering scheme used in his latest (16 byte!) answer. A direct port of PhiNotPi's scheme would give the same score.
By shifting the numbering from Rev 0 round one step, and taking everything XOR 1, we get the following cube:
```
4---7
| |
| 1 |
| |
1---0---7
| | |
| 0 | 3 |
| | |
6---3---2---7
| | |
| 2 | 5 |
| | |
6---5---4
| |
| 4 |
| |
6---1
```
Output
```
0
10
63
1
01
74
2
32
65
3
23
70
4
54
61
5
45
72
```
# Ruby Rev 0, ~~56 52~~ 50
Saved 4 bytes by removing unnecesary `()%6`from `c-d` and another 2 (inspired by runer112) by `6+c%2 --> 6|c` .
Score is for the function, which is just the first line. I'm new to Ruby and I'm surprised I can't find a shorter way than 12 characters (11 plus newline) to get a user input number into n. As a result, doing a function instead of a program saves 1 byte.
```
def f(c)d=c%2*2-1;print((c+d)%6,c,"\n",c|6,c-d)end
n=gets.to_i
f(n)
```
This is a port of my C answer. In C, the `%` operator returns a negative value with a negative number. In Ruby it always returns a positive value, so there is no need to add 1 to `c`. As a result, it is advantageous to shift the numbering of the faces by 1 as below:
```
0---7
| |
| 1 |
| |
1---2---7
| | |
| 2 | 3 |
| | |
6---3---4---7
| | |
| 4 | 5 |
| | |
6---5---0
| |
| 0 |
| |
6---1
```
With the new face numbering, the program prints the evens as shown above and the odds rotated through 180 degrees:
```
1
21
70
2
12
63
3
43
72
4
34
65
5
05
74
0
50
61
```
[Answer]
# Pyth, 30
Thanks @Jakube for 2 bytes.
```
Jc2jkfx>Q2!.&T^2%Q3U8jb?_J%Q2J
```
[Try it here.](https://pyth.herokuapp.com/?code=Jc2jkfx%3EQ2!.%26T%5E2%25Q3U8jb%3F_J%25Q2J&input=0&debug=0)
Golfing advice from pyth experts will be graciously accepted. In particular I think the output section might have some improvements.
Port of the following python:...
# Python, 109
```
Q=input()
s=''.join(map(str,filter(lambda v:(Q<3)^(v&(1<<Q%3)>0),range(8))))
print s[1-Q%2::2],'\n',s[Q%2::2]
```
...which is a port of
# Pure Bash, 130
For the purposes of explanation:
```
for v in {0..7};{
if(($1/3));then((v&(1<<$1%3)))&&a+=$v
else((v&(1<<$1%3)))||a+=$v
fi
}
i=$[$1%2*2]
echo "${a:i:2+i}
${a:2-i:4-i}"
```
The cube vertices are numbered thus:
```
4-----5
/| /|
0-----1 |
| | | |
| 6---|-7
|/ |/
2-----3
```
And the faces are numbered thus:
```
Face Vertices Swap
0 0,2,4,6
1 0,1,4,5 x
2 0,1,2,3
3 1,3,5,7 x
4 2,3,6,7
5 4,5,6,7 x
```
The `Swap` column indicates the order of the vertices should be switched in the output.
The algorithm starts out with all vertices {0..7}. Vertices are eliminated according to bits set in the vertex numbers:
* For faces 0,1 and 2, vertices with bits 1,2 or 3 cleared respectively are kept
* For faces 3,4 and 5, vertices with bits 1,2 or 3 set respectively are kept
The "kept" vertices are appended to a string. The string is output chars 0,1 then 2,3 or vice versa, depending on whether the swap flag (face number mod 2) is set.
[Answer]
# J - 26 bytes
Function taking face number as argument and returning the grid of digits.
```
0{.@":"0@{0&(|:|.)&(i.3#2)
```
We are using the following cube:
```
4-----5 Face numbers:
/| /| 0 - front
0-----1 | 1 - top
| | | | 2 - left
| 6---|-7 3 - back
|/ |/ 4 - bottom
2-----3 5 - right
```
Example (try it yourself at [tryj.tk](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=0%7B.%40%22%3A%220%40%7B0%26%28%7C%3A%7C.%29%26%28i.3%232%29%203)):
```
0{.@":"0@{0&(|:|.)&(i.3#2) 3 NB. inline
76
54
f =: 0{.@":"0@{0&(|:|.)&(i.3#2) NB. named
f each 0 1 2 3 4 5 NB. all results
+--+--+--+--+--+--+
|01|40|64|76|37|13|
|23|51|20|54|26|57|
+--+--+--+--+--+--+
```
The bread and butter is `0&(|:|.)`. This is a verb that reverses and rotates the cube in such as way as to visit every face when iteratively applied, which is what we do using the input argument. The vertices of the cube are generated by `i.3#2`, so we use that as the starting point, and take the front face `0...{` when we're done.
Printing the digits as a string costs 8 chars: `{.@":"0@` If we were allowed to simply return an array, that's a saving of 8 whole characters. *[commences fist-shaking and indiscernible griping]*
[Answer]
# [><> (Fish)](http://esolangs.org/wiki/Fish), 38 bytes
```
'/ =/2= 28"H5'a@i-!
noan~\;
~>:?!^1-@~
```
Every output is stored as two 2-digit rows. The rows are stored as charcodes in the string `'/ =/2= 28"H'` (except the row `10` which is appended after the string as `a`). The first character (`/ = 47`) is used to redirect the program flow on the second interaction.
The top `2*(53-n)` elements are discarded (where n is the charcode of the input number) and the next two codes are printed with a newline between.
Layout:
```
3-----2
/| /|
4-----7 |
| | | |
| 5---|-0
|/ |/
6-----1 0 1 2 3 4 5 sides are top front bottom back left right respectively.
```
]
|
[Question]
[
Given an integer `n` (where `n < 10001`) as input, write a program that will output the first `n` [Ulam numbers](http://oeis.org/A002858). An Ulam number is defined as follows:
1. U1 = `1`, U2 = `2`.
2. For `n > 2`, Un is the smallest integer which is greater than Un-1 that is the sum of two **distinct** earlier terms in exactly one way.
For example, U3 is `3` (2+1), U4 is `4` (3+1) (note that (2+2) does not count as the terms are not distinct), and U5 is `6`, (U5 is not 5 because 5 can be represented as either 2+3 or 4+1). Here are the first few Ulam numbers:
>
> `1, 2, 3, 4, 6, 8, 11, 13, 16, 18, 26, 28, 36, 38, 47, 48, 53, 57, 62, 69, 72, 77, 82, 87, 97, 99`
>
>
>
This is code golf, so the shortest entry wins.
[Answer]
# CJam, ~~47~~ ~~41~~ 37 bytes
```
li4,1${__m*{_~<\:+*}%$2/z:^$2=+}*1><`
```
[Try it online.](http://cjam.aditsu.net/)
### Example run
```
$ cjam <(echo 'li4,1${__m*{_~<\:+*}%$2/z:^$2=+}*1><`') <<< 26
[1 2 3 4 6 8 11 13 16 18 26 28 36 38 47 48 53 57 62 69 72 77 82 87 97 99]
```
### How it works
This basic idea is the following:
1. Start with the array `A := [ 0 U₁ U₂ ... Uₖ ]`.
2. Compute `S`, the array of all sums `x + y` such that `x,y ∊ A` and `x < y`.
3. Discard all non-unique sums from `S`. Since every Ulam number greater than 2 is both the sum of two smaller ones and the sum of zero and itself, this discards the Ulam numbers `U₃, U₄, ... Uₖ`.
4. The remaining array is `[ U₁ U₂ Uₖ₊₁ ... ]`, so the next Ulam number is the third smallest element. Append it to `A` and go back to step 1.
```
li " Read one integer (I) from STDIN. ";
4, " Push the array A = [ 0 1 2 3 ]. ";
1${ }* " Do the following I times: ";
__m* " Push the Cartesian product A × A. ";
{ }% " For each pair (x,y) in A × A: ";
_~<\:+* " Compute (x + y) * (x < y). ";
$2 " Sort the resulting array. ";
/ " Split it into chunks of length 2. ";
z " Transpose the resulting two-dimensional array. ";
:^ " Compute the symmetric difference of its rows. ";
$ " Sort the resulting array. ";
2= " Extract its third element. ";
+ " Push it on the array A. ";
1> " Discard the first element of A (0). ";
< " Discard all but the first I elements of A. ";
` " Push a string representation of A. ";
```
[Answer]
# J - 46 char
Function taking `n` as argument.
```
_2}.(,]<./@-.~</~({.+_*1<#)/.~@#&,+/~)@[&0&1 2
```
Explained by explosion:
```
( ) NB. procedure for a list:
+/~ NB. take an addition table
</~ #&, NB. select the top right half (no diag)
( )/.~@ NB. for each unique value:
1<# NB. if more than one present
{.+_* NB. add infinity to it
] -.~ NB. remove existing Ulam numbers
<./@ NB. take the smallest
, NB. append to Ulam numbers
@[&0 NB. repeat this procedure:
&1 2 NB. n times starting with [1, 2]
_2}. NB. drop the last two numbers
```
[Answer]
## T-SQL, ~~301~~ ~~300~~ ~~288~~ 287
I've committed a little light SQL abuse.
```
DECLARE @N INT=100,@T INT=1DECLARE @ TABLE(I INT,U INT)INSERT @ VALUES(1,1),(2,2)#:IF @T>2INSERT @ SELECT TOP 1@T,A.U+B.U FROM @ A,@ B WHERE A.U>B.U GROUP BY A.U+B.U HAVING COUNT(*)=1AND A.U+B.U>ALL(SELECT U FROM @)ORDER BY 2SET @T+=1IF @T<=@N GOTO # SELECT U FROM @ WHERE I<=@N ORDER BY I
```
Try it in SQL Server 2008 [here](http://sqlfiddle.com/#!3/d41d8/39009).
@N holds the input integer. Change the example "100" to what n should be. "10000" will probably finish eventually, but I haven't let that run to completion. This entry's char count is for a one-digit input. Output is in query result form.
[Answer]
# Haskell, ~~70~~ 67 characters
```
u n=take n$1:2:[x|x<-[1..],[_]<-[[y|y<-u$n-1,z<-u$n-1,y<z,y+z==x]]]
```
usage:
```
>u 6
[1,2,3,4,6,8]
```
[Answer]
## GolfScript (41 37 bytes)
```
~.14*,3,\{1$.{2$1$-.@<*}%&,2=*|}/0-<`
```
[Online demo](http://golfscript.apphb.com/?c=Oyc2JwoKfi4xNCosMyxcezEkLnsyJDEkLS5APCp9JSYsMj0qfH0vMC08YA%3D%3D)
Cartesian products in GolfScript are quite long, so this takes a different approach. The long-term growth of the Ulam numbers is that the `n`th Ulam number is about `13.5n`, but in the first 10000 terms the greatest ratio between the `n`th Ulam number and `n` is just under `13.3`. So given `n` we can filter the first `14n` numbers to find those which belong in the sequence.
With thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for 41->37.
[Answer]
## JavaScript ES6, ~~100 ... 93~~ 90 characters
Run this in Web Console or Scratchpad of latest Firefox (Nightly or release).
**EDIT 8** Golfed a lot!!! and made it down to ~~94 characters~~ ~~93~~ 90 characters (thanks to @openorclose). (My first sub 100)
Here is my version which is much faster ~~but is 3 characters longer (107 characters)~~ ~~and is exactly the same amount of characters as above~~ and is much smaller than the brute force method below!, (thanks to edc65 ) :
```
u=n=>(s=>{for(r=[i=l=1];c=l<n;i+=c&&i-2?1:s[r[l++]=i]=1)r.map(j=>c-=j<i/2&s[i-j])})([])||r
```
I will keep trying to golf it further. But we are squeezing it out of the scope of JS :P
Here are some numbers when I run this inside a script tag in a webpage:
```
n time (s)
10 0.001
100 0.005
1000 2.021
10000 236.983
100000 ~~pending~~ tldr; Too long didn't run :P
```
---
This is my first submission which is heavily inspired by @rink.attendant.6's answer in JavaScript.
```
u=n=>{for(l=[1,g=2],i=3;g<n;++i){z=1;for(j of l)for(k of l)z-=j<k&j+k==i;!z?l[g++]=i:0}return n>1?l:[1]}
```
I know this can be golfed even further. I will post a non-bruteforced solution too, which might be even shorter.
**EDIT 1**: Golfed a bit more and fixed for n = 1
I must say that I do envy Haskell and J for such super handy shortcuts for every kind of requirement -\_-
[Answer]
## Perl - 71 bytes
```
#!perl -p
@a=$b[2]=1;1while$b[++$a]^1||$_>map(++$b[$_+$a],@a)&&push@a,$a;$_="@a"
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAv@OyTaqiRFG8XaGloblmdk5qQCedraKomxcYY1NSrxdrmJBRpAflK0SjxIVMchUVNNraC0OMMhUUcl0Vol3lbJIVHp/39DAwMDAA "Perl 5 – Try It Online")
Counting the shebang as one.
Using a second array to store the sums seems to be significantly faster than a hash. Memory usage is also less, which I wouldn't have expected.
Sample usage:
```
$ echo 30 | perl ulam.pl
```
Sample output:
```
1 2 3 4 6 8 11 13 16 18 26 28 36 38 47 48 53 57 62 69 72 77 82 87 97 99 102 106 114 126
```
Approximate runtimes:
```
n = 100 0.015s
n = 1000 0.062s
n = 10000 4.828s
```
[Answer]
## Java, 259
```
import java.util.*;class C{public static void main(String[]a){List<Integer>l=new ArrayList<>();l.add(1);l.add(2);for(int i=3,z=0;l.size()<new Long(a[0]);i++,z=0){for(int j:l){for(int k:l){if(j<k&j+k==i)z++;}}if(z==1)l.add(i);}l.forEach(System.out::println);}}
```
Brute force works well for this.
```
import java.util.*;
class C {
public static void main(String[] a) {
List<Integer>l = new ArrayList<>();
l.add(1);
l.add(2);
for (int i = 3, z = 0; l.size() < new Long(a[0]); i++, z = 0) {
for (int j : l) {
for (int k : l) {
if (j < k & j + k == i)
z++;
}
}
if (z == 1)
l.add(i);
}
l.forEach(System.out::println);
}
}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~36~~ 35 bytes
*-1 byte by Adám*
```
{⍵↑{⍵,⊃∧(∊⊢⊆⍨⍧⍨∊2 3⍨)⍵~⍨,+⍀⍨⍵}⍣⍵⍳2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR79ZHbRNBlM6jruZHHcs1HnV0Pepa9Kir7VHvike9y0FkR5eRgjGQoQlUVgekdbQf9TaApbfWPupdDDKjd7NR7f@0R20THvX2Peqb6ukPNO3QemOg2UBecJAzkAzx8Az@n6ZgyJWmYATEhgZcj3o69BXSFEwNAA "APL (Dyalog Extended) – Try It Online")
```
{⍵↑{⍵,⊃∧(∊⊢⊆⍨⍧⍨∊2 3⍨)⍵~⍨,+⍀⍨⍵}⍣⍵⍳2} Monadic function taking an argument n:
{⍵,⊃∧(∊⊢⊆⍨⍧⍨∊2 3⍨)⍵~⍨,+⍀⍨⍵} Helper function to compute the next Ulam number
given ⍵ (the first few Ulam numbers)
+⍀⍨⍵ Make an addition table from ⍵.
, Flatten into a list.
⍵~⍨ Remove all entries already in ⍵.
(∊⊢⊆⍨2 3∊⍨⍧⍨) Helper function taking an argument x:
⍧⍨ The count of elts of x in itself
2 3∊⍨ 1s where those counts are in (2 3), else 0s.*
⊢⊆⍨ Partition x, removing values corresponding to 0s.
∊ Join the partitions into a single list.
(∊⊢⊆⍨⍧⍨∊2 3⍨) Keep all elements that occur exactly 2 or 3 times.
(i.e. that occur once as a
sum of distinct elements of ⍵).
∧ Sort ascending.
⊃ Take the first value (the next Ulam #).
⍵, Append that value to ⍵.
{⍵↑{...}⍣⍵⍳2}
{ {...}⍣⍵ } Call the helper function n times
⍳2 starting with (1 2). First n+2 Ulam numbers.
⍵↑ Keep the first n elements.
```
When we make the addition table, diagonal elements are twice the entries in ⍵. Non-diagonal elements are sums of distinct elements, with each \$x\$ occurring twice for each way \$x\$ can be written as a sum of distinct elements. Therefore, each number \$x\$ occurs \$2a+b\$ times, where \$a\$ is the number of ways \$x\$ can be written as a sum of distinct elements from ⍵, and \$b\$ is 1 iff \$x\$ is twice some entry in ⍵. We want \$a=1\$, so it is sufficient to check \$2a+b \in \{ 2, 3\}\$.
\* (In ngn/APL, a constant can end a train without using `⍨`. But ngn/APL doesn't have count-in, so we need ⍨ somewhere.)
[Answer]
# PHP 5.4+, 164
Same approach as my answers:
```
<?function u($n){for($l=[1,2],$i=3;count($l)<$n;++$i){$z=0;foreach($l as $j){foreach($l as $k){$z+=$j<$k&$j+$k==$i;}}if($z==1)$l[]=$i;}return array_slice($l,0,$n);}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
Œc§ḟµḟœ-Q$Ṃɓ;
2RÇ⁸¡ḣ
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//xZJjwqfhuJ/CteG4n8WTLVEk4bmCyZM7CjJSw4figbjCoeG4o////zEw "Jelly – Try It Online")
```
Œc§ḟµḟœ-Q$Ṃɓ; Helper link that appends the next number to x, a list of Ulam numbers:
Œc All unordered pairs of x
§ Sum each pair
ḟ Filter out the numbers already present in x.
µ Let this list be y. Then apply the following chain:
œ-Q$Ṃ Find the minimum of all unique elements.
ḟ Take y and filter out the elements in
œ-Q$ the multiset difference between y and its unique elements.
Ṃ Then find the Ṃinimum of the result.
ɓ; Append (ɓ reverses argument order) the result to
2RÇ⁸¡ḣ Main link:
2R Start with [1,2].
Ç⁸¡ Apply the helper link (Ç) n (⁸) times to generate n+2 Ulam #s.
ḣ Keep the first n values.
```
[Answer]
## CoffeeScript, ~~119~~ 114
Lately I've been practising CoffeeScript to improve at golfing JavaScript, so here's my JavaScript answer compiled into CoffeeScript:
```
u=(n)->l=[1,2];i=3;z=0;(for j in l
for k in l
z+=j<k&j+k==i
l.push(i) if z==1;++i;z=0)while l.length<n;l[..n-1]
```
I don't understand [loops and comprehensions in CoffeeScript](http://coffeescript.org/#loops) very well so perhaps this can be golfed further but it's what I have for now. Newlines are counted as one character (Unix style).
[Answer]
## JavaScript, ~~147~~ ~~154~~ 150 (136)
Heavily inspired by @Ypnypn's brute-force Java solution posted earlier:
```
function u(n){for(l=[1,2],i=3;l.length<n;++i){z=0;l.forEach(function(j){l.forEach(function(k){z+=j<k&j+k==i})});if(z==1)l.push(i)}return l.slice(0,n)}
```
Thanks for @Dennis for shaving 4 to 18 bytes off my original version
### Dangerous version (using [`for..in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops)
I would not recommend running this because looping through an object that is an [`instanceof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) using a `for..in` loop could cause your machine to burst into flames and/or transform into an angry killing machine, but here it is:
```
function u(n){for(l=[1,2],i=3;l.length<n;++i){z=0;for(j in l)for(k in l)z+=l[j]<l[k]&l[j]+l[k]==i;if(z==1)l.push(i)}return l.slice(0,n)}
```
### Ungolfed
```
function u(n) {
var l = [1, 2],
i = 3,
j, k, z;
for (; l.length < n; ++i) {
z = 0;
l.forEach(function (j) {
l.forEach(function (k) {
if (j < k & j + k === i) {
z++;
}
});
});
if (z === 1) {
l.push(i);
}
}
return l.slice(0, n);
}
```
[Answer]
# Mathematica, ~~107~~ 91 bytes
```
Nest[#~Append~Min@Cases[Tally[Tr/@#~Subsets~2],{n_,1}:>n]&,{1,2},i=Input[]]~Drop~{3}~Take~i
```
It's a very direct implementation of the spec.
* Find all pairs.
* Delete all duplicates.
* Delete all numbers less than the last Ulam number.
* Append the minimum to the list.
I'm also applying Dennis's trick of including sums with `0`, but the catch is that this makes the third element of the list `0` before resuming as one would expect, so I need to remove that element from the list.
It handles an input of `1000` in a few seconds, but I doubt that you'll get a result for 10k in a reasonable amount of time. But I don't think any of the others performs well on that either.
[Answer]
# OCaml - 254 Characters
The code use an hash table to store the sum of the current elements of the list and update it each time a new element is computed.
```
open Hashtbl let h=create 7 let()=add h 3 1 let rec r n i l=if n=0then List.rev l else if mem h i&&find h i=1then(List.iter(fun x->if mem h(x+i)then replace h(x+i)2else add h(x+i)1)l;r(n-1)(i+1)(i::l))else r n(i+1)l let u n=if n=1then[1]else r(n-2)3[2;1]
```
## Usage:
Within OCaml interpreter:
```
# u 26;;
- : int list =
[1; 2; 3; 4; 6; 8; 11; 13; 16; 18; 26; 28; 36; 38; 47; 48; 53; 57; 62; 69;
72; 77; 82; 87; 97; 99]
```
## Ungolfed
```
open Hashtbl
let h = create 7
let() = add h 3 1
let rec r n i l =
if n=0 then List.rev l
else if mem h i && find h i=1 then
begin
List.iter
(fun x-> if mem h(x+i) then replace h (x+i) 2 else add h (x+i) 1)
l;
r (n-1) (i+1) (i::l)
end
else r n (i+1) l
let u n = if n=1 then [1] else r (n-2) 3 [2;1]
```
[Answer]
# Python, ~~137~~ ~~128~~ 126 characters.
```
U,i=[1,2],2
for _ in [[0]]*(input()-2):
t=_*3*i
for a in U:
for b in U:t[a+b]+=a!=b
i=t[i+1:].index(2)+i+1;U+=[i]
print U
```
This is my first golf, and I've brought it down from ~250 characters, I'm pretty happy but would love suggestions on how to improve!
[Answer]
# C#, 257
Brute force approach, using LINQ:
```
using System.Linq;class U{void F(int n){var u=n<2?new int[]{1}:new int[]{1,2};for(int i=3;u.Length<n;++i)if(u.SelectMany(x=>u,(a,b)=>new{A=a,B=b}).Count(x=>x.A>x.B&&x.A==i-x.B)==1)u=u.Union(new int[]{i}).ToArray();System.Console.Write(string.Join("",u));}}
```
## Ungolfed, With Test Harness
```
using System.Linq;
class Ulam
{
void F(int n)
{
//handle special case where n = 1 (ugh)
var u = n < 2 ? new int[] { 1 } : new int[] { 1, 2 };
for (int i=3; u.Length<n; ++i)
if (u.SelectMany(x => u, (a, b) => new { A = a, B = b })
.Count(x => x.A > x.B && x.A == i - x.B) == 1)
u = u.Union(new int[] { i }).ToArray();
System.Console.Write(string.Join(" ",u));
}
public static void Main(string[] args)
{
new Ulam().F(1);
System.Console.WriteLine();
new Ulam().F(2);
System.Console.WriteLine();
new Ulam().F(3);
System.Console.WriteLine();
new Ulam().F(26);
System.Console.WriteLine();
}
}
```
[Answer]
# Pyth, ~~27~~ 25 bytes
```
<uaGh-sfq1lT.gksM.cG2GQS2
```
Try it online [here](https://pyth.herokuapp.com/?code=%3CuaGh-sfq1lT.gksM.cG2GQS2&input=10&debug=0).
```
<uaGh-sfq1lT.gksM.cG2GQS2Q Implicit: Q=eval(input())
Trailing Q inferred
u Q Perform the following Q times...
S2 ... with G initialised to [1,2]:
.cG2 Get all 2-element combinations of G
sM Sum each pair
.gk Group them by value
The groups are sorted by the result of the sum
f Filter the groups, as T, keeping those where:
lT Length of T
q1 Equal to 1
s Flatten list
- G Remove elements of the above which are already in G
h Take the first of the remaining elements
This is the smallest, as the grouping also sorted them
aG Append this to G
< Q Take the first Q elements, implicit print
```
*Edit: golfed 2 bytes by performing summation before grouping. Previous version: `<uaGh-mssdfq1lT.gsk.cG2GQS2`*
[Answer]
# C, 478 bytes
```
#define R return
bs(x,v,l,h,r)unsigned x,*v,l,h,*r;{unsigned m;for(;l<=h;){m=(l+h)/2;if(x<v[m])h=m-1;else if(x>v[m])l=m+1;else{*r=m;R 1;}}*r=m;R 0;}
#include<stdlib.h>
unsigned*f(unsigned w){unsigned*u=0,i,k,m,y,z;if(w>1E6||w==0)R u;u=malloc(w*sizeof*u);if(!u)R u;k=0;u[k++]=1;if(w==1)R u;m=u[k++]=2;if(w==2)R u;l:for(i=0,y=0,z=k-1,++m;i<k;y+=bs(m-u[i],u,i+1,z,&z),++i)if(y>1||u[i]+(i+1!=k?u[i+1]:0)>m)break;if(m==0){free(u);u=0;R u;}if(y!=1)goto l;u[k++]=m;if(k< w)goto l;R u;}
```
In Tio now in 9 seconds it would find 10000 values (and in there print the first 100 values). The trick is using not linear search in the inner loop but binary search...
These below are functions well indented and full readable (at last for me):
```
bsCopy(x,v,l,h,r)unsigned x,*v,l,h,*r;
{unsigned m;
for(;l<=h;){m=(l+h)/2;if(x<v[m])h=m-1;else if(x>v[m])l=m+1;else{*r=m;R 1;}}
*r=m;R 0;// in *r if return 0 the min index that fail else the index of find x
}
unsigned*fCopy(unsigned w)
{unsigned*u=0,i,k,m,y,z;
if(w>1E6||w==0)R u;
u=malloc(w*sizeof*u);
if(!u)R u;
k=0;u[k++]=1;if(w==1)R u;
m=u[k++]=2;if(w==2)R u;//below I suppose m-u[i] is in the range (if exist in u) (i+1)..z
l: for(i=0,y=0,z=k-1,++m;i<k;y+=bsCopy(m-u[i],u,i+1,z,&z),++i)
if(y>1||u[i]+(i+1!=k?u[i+1]:0)>m)break;
if(m==0){free(u);u=0;R u;}
if(y!=1)goto l;
u[k++]=m;if(k< w)goto l;
R u;
}
```
[Answer]
# APL(NARS), 278 char, 556 bytes
```
∇u←p w;m;y;i;k;z;r;bs
bs←{(x l h)←⍵⋄l>h:0,h⋄x<⍺[t←⌊2÷⍨l+h]:⍺∇x,l,t-1⋄x>⍺[t]:⍺∇x,(t+1),h⋄1,t}
u←⍬ ⋄→0×⍳(w>1E6)∨w≤0
u←u,1⋄→0×⍳w=1
u←u,2⋄→0×⍳w=2⋄k←m←2
i←1⋄y←0⋄m+←1⋄z←k
→7×⍳(y>1)∨i>k⋄→7×⍳m<u[i]+{i=k:0⋄u[i+1]}⋄r←u bs(m-u[i]),(i+1),z⋄y+←↑r⋄z←2⊃r⋄i+←1⋄→6
→5×⍳y≠1⋄u←u,m⋄k+←1⋄→5×⍳k<w
∇
```
it would be the translation in APL of C one I sent.
It seems i not understand when to use ∇∇ in place of ∇... possible ∇∇ is used when there is one
argument is one function (and not one other type).
"u bs x, a,b" should be the bin search in "u" array for the value "x" in the range a..b; it would return 1, indexWhereFind
or 0, indexWhereEndOfsearch. With argument 200 p function take +- a minute here...
```
p 100
1 2 3 4 6 8 11 13 16 18 26 28 36 38 47 48 53 57 62 69 72 77 82 87 97 99 102 106 114 126
131 138 145 148 155 175 177 180 182 189 197 206 209 219 221 236 238 241 243 253
258 260 273 282 309 316 319 324 339 341 356 358 363 370 382 390 400 402 409 412
414 429 431 434 441 451 456 483 485 497 502 522 524 544 546 566 568 585 602 605
607 612 624 627 646 668 673 685 688 690
p¨1 2 3 4
1 1 2 1 2 3 1 2 3 4
```
]
|
[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/11020/edit).
Closed 2 years ago.
[Improve this question](/posts/11020/edit)
Given three sides of a triangle, print area of this triangle.
Test cases:
**In:** `2,3,4`
**Out:** `2.90473750965556`
**In:** `3,4,5`
**Out:** `6`
Given the sides \$a\$, \$b\$, and \$c\$, you can assume that \$a>0\$, \$b>0\$, \$c>0\$, \$a+b>c\$, \$b+c>a\$, and \$c+a>b\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer per language in bytes wins.
[Answer]
## J, ~~23~~ 19 chars
```
(4%~2%:[:*/+/-0,+:)
(4%~2%:[:*/+/-0,+:) 2 3 4
2.90474
(4%~2%:[:*/+/-0,+:) 3,4,5
6
```
17-char version if input is in `i`: `4%~%:*/(+/,+/-+:)i`
original 23-char version: `(%:@(+/**/@(+/-+:))%4:)`
[Answer]
## APL ~~21~~ 20
Takes screen input via ←⎕
```
(×/(+/t÷2)-0,t←⎕)*.5
```
[Answer]
**Mathematica 23**
```
√Times@@(+##/2-{0,##})&
```
[Answer]
# Python 2, 53
```
t=input()
s=a=sum(t)/2.
for x in t:a*=s-x
print a**.5
```
Input: `2,3,4`
Output: `2.90473750966`
[Answer]
## Python 57 bytes
```
a,b,c=input()
s=(a+b+c)*.5
print(s*(s-a)*(s-b)*(s-c))**.5
```
Using [Heron's Formula](http://mathworld.wolfram.com/HeronsFormula.html).
Sample usage:
```
$ echo 2,3,4 | python triangle-area.py
2.90473750966
$ echo 3,4,5 | python triangle-area.py
6.0
```
---
**A 58 byte variant:**
```
a,b,c=input()
print((a+b+c)*(b+c-a)*(a+c-b)*(a+b-c))**.5/4
```
[Answer]
### GolfScript, 38 characters
```
~].~++:d\{2*d\-*}/'"#{'\+'**0.5/4}"'+~
```
Since the question didn't specify otherwise I chose to work only on integer lengths. Sides must be given on STDIN separated by spaces.
Example:
```
> 2 3 4
2.9047375096555625
```
[Answer]
## R : ~~48~~ 43 characters
```
f=function(...)prod(sum(...)/2-c(0,...))^.5
```
Using Heron's formula as well but taking advantage of R's vectorization.
Thanks to @flodel for the idea of the ellipsis.
Usage:
```
f(2,3,4)
[1] 2.904738
f(3,4,5)
[1] 6
```
[Answer]
# Mathematica ~~20~~ 16 or ~~22~~ 18 bytes
With 4 bytes saved by @swish.
This returns an exact answer:
```
Area@SSSTriangle@
```
**Example**
```
Area@SSSTriangle[2,3,4]
```
[](https://i.stack.imgur.com/Gn8F1.png)
---
To return the answer in decimal form, two additional bytes are required.
```
N@Area@SSSTriangle[2,3,4]
```
2.90474
[Answer]
# K, 23
```
{sqrt s**/(s:.5*+/x)-x}
```
Example
```
k){sqrt s**/(s:.5*+/x)-x} 2 3 4
2.904738
```
[Answer]
### APL, 23 20 characters
```
{(×/(+/⍵÷2)-0,⍵)*÷2} 2 3 4
```
Example:
```
> {(×/(+/⍵÷2)-0,⍵)*÷2} 2 3 4
2.90474
```
[Answer]
## Javascript, ~~88~~ 85
```
v=prompt().split(/,/g);s=v[0]/2+v[1]/2+v[2]/2;Math.sqrt(s*(s-v[0])*(s-v[1])*(s-v[2]))
```
Not good but fun :) Also Heron...
Demonstrates the ungolfability of simple problems in JS lol
**Note**: run from console to see result.
88->85: Removed `a`, `b` and `c`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 55 bytes
```
#define f(a,b,c)sqrt((a+b+c)*(a+b-c)*(a-b+c)*(b+c-a))/4
```
[Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU0jUSdJJ1mzuLCoREMjUTtJO1lTC0TrgmldCB9I6iZqauqb/M9NzMzT0KzmUigoyswrSdNQUk2LyVPSSdMw0jHWMdHUtMaUAYrrmIJkav//S07LSUwv/q@bkwsA "C (gcc) – Try It Online")
Yet another implementation of Hero's formula.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
SH;_P½ʋ
```
[Try it online!](https://tio.run/##y0rNyan8/z/Ywzo@4NDeU93/D7c/alrz/390tJGOsY5JrE40kNQxjY0FAA "Jelly – Try It Online")
[Answer]
# Haskell: 51 (27) characters
```
readLn>>=(\l->print$sqrt$product$map(sum l/2-)$0:l)
```
A very straight-forward implementation of Heron's formula. Example run:
```
Prelude> readLn>>=(\l->print$sqrt$product$map(sum l/2-)$0:l)
[2,3,4]
2.9047375096555625
Prelude>
```
Note that it accepts any numeric input, not only integers. And if the input already is in l the solution only needs to be 36 characters long, and if we are not interested in printing the answer the solution only needs to be 30 characters long. What more is that if we can allow ourself to change the input format we can remove 3 more characters. So if our input looks like [2,3,4,0.0] and is already in l we can get our answer with only:
```
sqrt$product$map(sum l/2-)l
```
Example run:
```
Prelude> let l = [2,3,4,0.0]
Prelude> sqrt$product$map(sum l/2-)l
2.9047375096555625
Prelude>
```
[Answer]
# PHP, ~~78~~ 77
```
<?=sqrt(($s=array_sum($c=fgetcsv(STDIN))/2)*($s-$c[0])*($s-$c[1])*$s-=$c[2]);
```
Useage:
```
php triangle.php
2,3,4
```
Output: `2.9047375096556`
I don't think I can make it shorter? I'm still new to golfing. Anyone let me know if I overlooked something.
Thanks Primo for saving me 1 byte, lol.
[Answer]
## JavaScript (84 86)
```
s=(eval('abc '.split('').join('=prompt()|0;'))+a+b)/2;Math.sqrt(s*(s-a)*(s-b)*(s-c))
```
Another JavaScript solution based on Heron's formula, but trying a different approach for loading variables. Needs to be run from the console. Each side is entered in a separate prompt.
**EDIT**: Make use of return value of `eval` to save 2 characters. Beats @tomsmeding, wahoo! :)
[Answer]
# Excel, 42 bytes
Based on Heron's formula, high school algebra to golf.
```
=SQRT(((A1+B1)^2-C1^2)*(C1^2-(A1-B1)^2))/4
```
Ungolfed / Unalgebra'ed
```
=SQRT((A1+B1+C1)/2*(((A1+B1+C1)/2)-A1)*(((A1+B1+C1)/2)-B1)*(((A1+B1+C1)/2)-C1))
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~17~~ ~~16~~ 15 bytes
```
½*Nx
NmnU ×*U q
```
[Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=vSpOeApObW5VINcqVSBx&input=MiwzLDQ=)
Saved 2 bytes thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions) pointing out a redundant newline and some alternative ways to reduce the array.
[Answer]
# Tcl, 74 chars.
```
proc R {a b c} {set s ($a+$b+$c)/2.
expr sqrt($s*($s-$a)*($s-$b)*($s-$c))}
```
Pass the sides as argument.
For the input `2 3 4` the value of `s` is `(2+3+4)/2.` as string. Double evaluation FTW.
[Answer]
## Julia 0.6.0, 48 bytes
Basically heron's formula:
```
f(a,b,c)=(p=(a+b+c)/2;sqrt(p*(p-a)*(p-b)*(p-c)))
```
[Answer]
# TI-BASIC, ~~14~~ 12 bytes
```
4⁻¹√(sum(Ansprod(sum(Ans)-2Ans
```
Starting from a Heron's Formula routine [written by Kenneth Hammond (Weregoose)](http://adriweb.free.fr/upload/ti/weregoose.html), I golfed off two bytes. Note that TI-BASIC is tokenized, and each token, like `Ans` and `prod(`, is one or two bytes in the calculator's memory.
Input through `Ans` i.e. in the form `{a,b,c}:[program name]`.
Explained:
```
sum(Ans)-2*Ans (a+b+c)-2{a,b,c}={b+c-a,c+a-b,a+b-c}
Ans*prod( {a,b,c}*(b+c-a)(c+a-b)(a+b-c)
sum( (a+b+c)(b+c-a)(c+a-b)(a+b-c)
4⁻¹*√( √((a+b+c)(b+c-a)(c+a-b)(a+b-c)/16)
=√(s(s-a)(s-b)(s-c))
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 34 bytes
```
9ksssddlsld++2/d3R-rdls-rdld-***vp
```
[Try it online!](https://tio.run/##S0n@b6RgrGCi8N8yu7i4OCUlpzgnRVvbSD/FOEi3CMgDESm6WlpaZQX//wMA "dc – Try It Online")
[Answer]
# [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 36 bytes
```
sqrt(a*(a-b)*(a-c)*(a-d))((b+c+d)/2)
```
Heron's formula.
[Try it online!](https://tio.run/##SyxKykn9/7@4sKhEI1FLI1E3SRNEJoPJFE1NDY0k7WTtFE19I83///8bmfw3NvhvaAEA "ARBLE – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum -ap`, 40 bytes
```
$r=$t=.5*sum@F;map$r*=$t-$_,@F;$_=sqrt$r
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lyFalxFbPVKu4NNfBzTo3sUClSAsopKsSrwPkq8TbFhcWlagU/f9vrGCiYPovv6AkMz@v@L@ur6megaEBkPbJLC6xsgotycyxBZrxXzexAAA "Perl 5 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╝0∞♀»♦▓y╩╪
```
[Run and debug it](https://staxlang.xyz/#p=bc30ec0caf04b279cad8&i=[2.0,+3.0,+4.0]%0A[3.0,+4.0,+5.0]&a=1&m=2)
Operates triples of floating point numbers. Uses [Heron's Formula](https://en.wikipedia.org/wiki/Heron%27s_formula)
[Answer]
# APL(NARS), 16 chars, 32 bytes
```
{√×/(+/⍵÷2)-0,⍵}
```
One has to cenvert the Erone formula if a, b, c are sides of triangle
```
p =(a+b+c)/2
Area=√p*(p-a)(p-b)(p-c)
```
to APL language... test
```
f←{√×/(+/⍵÷2)-0,⍵}
f 2 3 4
2.90473751
f 3 4 5
6
```
]
|
[Question]
[
### Challenge
Given some input string, return a truthy value if it represents a correct roman numeral between 1 (=`I`) and 3999 (=`MMMCMXCIX`), and a falsey value otherwise.
### Details
* The input is a non-empty string that only comprises the characters `IVXLCDM`.
* The roman numerals (that we use here in this challenge) are defined as follows:
We use only following symbols:
```
Symbol I V X L C D M
Value 1 5 10 50 100 500 1000
```
To define which strings are actually valid roman numerals, it is probably easiest to provide the rule of conversation: To write a decimal number `a3 a2 a1 a0` (where each `ai` represents one digit. So for example to represent `792` we have `a3=0, a2=7, a1=9, a0=2`.) as a roman numeral, we decompose it into the power of tens. The different powers of ten can be written as follows:
```
1-9: I, II, III, IV, V, VI, VII, VIII, IX
10-90: X, XX, XXX, XL, L, LX, LXX, LXXX, XC
100-900: C, CC, CCC, CD, D, DC, DCC, DCCC, CM
1000-3000: M, MM, MMM
```
Beginning at the left side with the most significant digit of the, we can convert the number that each digit represents separately and concatenate them. So for the example from above this would look like so:
```
Digit a3 a2 a1 a0
Decimal 0 7 9 2
Roman DCC XC II
```
Therefore the roman numeral for `792` is `DCCXCII`. Here is a full list of all roman numerals that are relevant for this challenge: [OEIS a006968.txt](https://oeis.org/A006968/a006968.txt)
### Examples
**Truthy**
```
MCCXXXIV (1234)
CMLXXXVIII (988)
DXIV (514)
CI (101)
```
**Falsey**
```
MMIXVIII
IVX
IXV
MMMM
XXXVX
IVI
VIV
```
[Answer]
# [Verbose](https://esolangs.org/wiki/Verbose), 1362 bytes
```
GET A ROMAN NUMERAL TYPED IN BY THE CURRENT PERSON USING THIS PROGRAM AND PUT IT ONTO THE TOP OF THE PROGRAM STACK
PUT THE NUMBER MMMM ONTO THE TOP OF THE PROGRAM STACK
MOVE THE FIRST ELEMENT OF THE PROGRAM STACK TO THE SECOND ELEMENT'S PLACE AND THE SECOND ELEMENT OF THE STACK TO THE FIRST ELEMENT'S PLACE
DIVIDE THE FIRST ELEMENT OF THE PROGRAM STACK BY THE SECOND ELEMENT OF THE PROGRAM STACK AND PUT THE RESULT ONTO THE TOP OF THE PROGRAM STACK
PUT THE NUMBER V ONTO THE TOP OF THE PROGRAM STACK
GET THE FIRST ELEMENT OF THE PROGRAM STACK AND THE SECOND ELEMENT OF THE PROGRAM STACK AND IF THE SECOND ELEMENT OF THE PROGRAM STACK IS NOT ZERO JUMP TO THE INSTRUCTION THAT IS THE CURRENT INSTRUCTION NUMBER AND THE FIRST ELEMENT ADDED TOGETHER'S RESULT
PUT THE NUMBER I ONTO THE TOP OF THE PROGRAM STACK
GET THE TOP ELEMENT OF THE STACK AND OUTPUT IT FOR THE CURRENT PERSON USING THIS PROGRAM TO SEE
PUT THE NUMBER III ONTO THE TOP OF THE PROGRAM STACK
GET THE FIRST ELEMENT OF THE PROGRAM STACK AND THE SECOND ELEMENT OF THE PROGRAM STACK AND IF THE SECOND ELEMENT OF THE PROGRAM STACK IS NOT ZERO JUMP TO THE INSTRUCTION THAT IS THE CURRENT INSTRUCTION NUMBER AND THE FIRST ELEMENT ADDED TOGETHER'S RESULT
PUT THE NUMBER NULLA ONTO THE TOP OF THE PROGRAM STACK
GET THE TOP ELEMENT OF THE STACK AND OUTPUT IT FOR THE CURRENT PERSON USING THIS PROGRAM TO SEE
```
Outputs `I` for valid roman numerals in the range `I-MMMCMXCIX` and `NULLA` (0) or informs user input is not a valid roman numeral otherwise.
[Answer]
## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~79~~ 109 bytes
This seems like a Regex challenge, I'm sure a shorter solution can be found...
```
s=>System.Text.RegularExpressions.Regex.IsMatch(s,"^M{0,3}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$")
```
[Try it online!](https://tio.run/##dY5NC4JAEIbv/YqQDiuYBB378LAWDDiXim1BDEo2WzANZwMj@@32eYm24/O8M@9MSv2UdDs/F@mYTKWLzNuVZT7t7ruTlibT5YWMOvorVRt/obJzvq1m9alSRLos6KlU7QPh1qQHRp6zwevAG94YjzFMmjDgL3SZjHmUNFEgPwyxFEkjAnhzz3HbdaWNinSh2J45yLmUEoTjuqPOV8IxeiQCAH6z0L5hmUSEPx0gpEVKYetA/LXP52wN4nWrvQM)
[Answer]
# Java 8, 70 bytes
```
s->s.matches("M{0,3}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})")
```
Port of [*@Innat3*'s C# answer](https://codegolf.stackexchange.com/a/183016/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##jZBBa4MwHMXvfoo/nhRWO9htZfMQGQRMLx0hIB7SNFvtNBYTC6X62V20jp1KzCHwyOO938uJX/jqdPgZRMm1BsILdfMACmVk88WFhO0oAfZ1XUquQAQ70xTqG3S4sQ@9Zy9tuCkEbEHBGwx69a6jihtxlDrwye356aUPUEaSvEtiNMkwYBlK8y6N2axxxmje0RjftR8OmzH53O5LmzwXXOriAJUlnBmyHHh4x1uv4bNpzfH6OsndVRtZRXVrorN1mlIFKhKWBiHGGKZ@ONE/NiKSWiPFGDutizOTRcX/hXbTBy@1fLzJRUbwsgmYMreHueGJPU7T@K8L6ugfdu/1wy8)
**Explanation:**
```
s-> // Method with String parameter and boolean return-type
s.matches("...") // Check if the string matches the regex fully
// (which implicitly adds a leading "^" and trailing "$")
M{0,3} // No, 1, 2, or 3 adjacent "M"
( | ) // Followed by either:
C[MD] // A "C" with an "M" or "D" after it
| // or:
D? // An optional "D"
C{0,3} // Followed by no, 1, 2, or 3 adjacent "C"
( | ) // Followed by either:
X[CL] // An "X" with a "C" or "L" after it
| // or:
L? // An optional "L"
X{0,3} // Followed by no, 1, 2, or 3 adjacent "X"
( | ) // Followed by either:
I[XV] // An "I" with an "X" or "V" after it
| // or:
V? // An optional "V"
I{0,3} // Followed by no, 1, 2, or 3 adjacent "I"
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
Check[FromRomanNumeral@#<3999,1<0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zkjNTk72q0oPzcoPzcxz680N7UoMcdB2cbY0tJSx9DGIFbtf0BRZl6Jgr5DYGlmakl0ur6DQrWSr7NzRESEZ5iSjpKzrw@QGebp6QnkuEDFQGxfX0@YsGdYBIiMCAML@/oCKZAesGCYp1Jt7P//AA "Wolfram Language (Mathematica) – Try It Online")
*5 bytes saved, thanks to @attinat*
the limitation `[1,3999]` unfortunateley costs 7 bytes...
here is the code for any roman number
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
Check[FromRomanNumeral@#,F]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zkjNTk72q0oPzcoPzcxz680N7UoMcdBWcctVu1/QFFmXomCvkNgaWZqSXS6voNCtZKvs3NERIRnmJKOkrOvD5AZ5unpCeS4QMVAbF9fT5iwZ1gEiIwIAwv7@gIpkB6wYJinUm3s//8A "Wolfram Language (Mathematica) – Try It Online")
the above code works for any number, not just [1,3999]
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) assembly ([Intellivision](https://en.wikipedia.org/wiki/Intellivision)), ~~52 ... 48~~ 47 DECLEs1 = 59 bytes
Let's try this on a system that predates Perl by a good 7 years. :-)
Takes a pointer to a null-terminated string in **R4**. Sets the **Zero** flag if the input is a valid Roman numeral, or clears it otherwise.
```
ROMW 10 ; use 10-bit ROM width
ORG $4800 ; map this program at $4800
;; ------------------------------------------------------------- ;;
;; test code ;;
;; ------------------------------------------------------------- ;;
4800 EIS ; enable interrupts
4801 SDBD ; R5 = pointer into test case index
4802 MVII #ndx, R5
4805 MVII #$214, R3 ; R3 = backtab pointer
4807 MVII #11, R0 ; R0 = number of test cases
4809 loop SDBD ; R4 = pointer to next test case
480A MVI@ R5, R4
480B PSHR R0 ; save R0, R3, R5 onto the stack
480C PSHR R3
480D PSHR R5
480E CALL isRoman ; invoke our routine
4811 PULR R5 ; restore R5 and R3
4812 PULR R3
4813 MVII #$1A7, R0 ; use a white 'T' by default
4815 BEQ disp
4817 MVII #$137, R0 ; or a white 'F' is the Z flag was cleared
4819 disp MVO@ R0, R3 ; draw it
481A INCR R3 ; increment the backtab pointer
481B PULR R0 ; restore R0
481C DECR R0 ; and advance to the next test case, if any
481D BNEQ loop
481F DECR R7 ; loop forever
;; ------------------------------------------------------------- ;;
;; test cases ;;
;; ------------------------------------------------------------- ;;
4820 ndx BIDECLE test0, test1, test2, test3
4828 BIDECLE test4, test5, test6, test7, test8, test9, test10
; truthy
4836 test0 STRING "MCCXXXIV", 0
483F test1 STRING "CMLXXXVIII", 0
484A test2 STRING "DXIV", 0
484F test3 STRING "CI", 0
; falsy
4852 test4 STRING "MMIXVIII", 0
485B test5 STRING "IVX", 0
485F test6 STRING "IXV", 0
4863 test7 STRING "MMMM", 0
4868 test8 STRING "XXXVX", 0
486E test9 STRING "IVI", 0
4872 test10 STRING "VIV", 0
;; ------------------------------------------------------------- ;;
;; routine ;;
;; ------------------------------------------------------------- ;;
isRoman PROC
4876 PSHR R5 ; push the return address
4877 MOVR R7, R2 ; R2 = dummy 1st suffix
4878 MOVR R2, R5 ; R5 = pointer into table
4879 ADDI #@tbl-$+1,R5
487B @loop MVI@ R5, R1 ; R1 = main digit (M, C, X, I)
487C MVI@ R5, R3 ; R3 = prefix or 2nd suffix (-, D, L, V)
487D MVI@ R4, R0 ; R0 = next digit
487E CMPR R0, R3 ; if this is the prefix ...
487F BNEQ @main
4881 COMR R2 ; ... disable the suffixes
4882 COMR R3 ; by setting them to invalid values
4883 MVI@ R4, R0 ; and read R0 again
4884 @main CMPR R0, R1 ; if R0 is not equal to the main digit,
4885 BNEQ @back ; assume that this part is over
4887 MVI@ R4, R0 ; R0 = next digit
4888 CMPR R0, R1 ; if this is a 2nd occurrence
4889 BNEQ @suffix ; of the main digit ...
488B CMP@ R4, R1 ; ... it may be followed by a 3rd occurrence
488C BNEQ @back
488E MOVR R2, R0 ; if so, force the test below to succeed
488F @suffix CMPR R0, R2 ; otherwise, it may be either the 1st suffix
4890 BEQ @next
4892 CMPR R0, R3 ; or the 2nd suffix (these tests always fail
4893 BEQ @next ; if the suffixes were disabled above)
4895 @back DECR R4 ; the last digit either belongs to the next
; iteration or is invalid
4896 @next MOVR R1, R2 ; use the current main digit
; as the next 1st suffix
4897 SUBI #'I', R1 ; was it the last iteration? ...
4899 BNEQ @loop
489B CMP@ R4, R1 ; ... yes: make sure that we've also reached
; the end of the input
489C PULR R7 ; return
489D @tbl DECLE 'M', '-' ; table format: main digit, 2nd suffix
489F DECLE 'C', 'D'
48A1 DECLE 'X', 'L'
48A3 DECLE 'I', 'V'
ENDP
```
### How?
The regular expression can be rewritten as 4 groups with the same structure, provided that `#` is any invalid character that is guaranteed not be present in the input string.
```
+-------+---> main digit
| |
(M[##]|#?M{0,3})(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})
|| |
|+--+-----> prefix or second suffix
|
+---------> first suffix
```
The *first suffix* of the group \$N\$ is the *main digit* of the group \$N-1\$. Therefore, we can store the patterns with the pair \$(\text{main\_digit}, \text{second\_suffix})\$ alone.
Our routine attempts to parse the input string character by character according to these patterns and eventually checks whether the end of the string is reached.
### Output
[](https://i.stack.imgur.com/j8byw.gif)
*screenshot of [jzIntv](http://spatula-city.org/~im14u2c/intv/)*
---
*1. A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This routine is 47 DECLEs long, starting at $4876 and ending at $48A4 (included).*
[Answer]
# [R](https://www.r-project.org/), ~~74~~ ~~71~~ 56 bytes
Thanks to @RobinRyder, @Giuseppe, & @MickyT for their suggestions how to use grep effectively with R's built in `as.roman`.
```
sub("^M(.+)","\\1",scan(,""))%in%paste(as.roman(1:2999))
```
[Try it online!](https://tio.run/##JYoxCwIxDEb3/IzAQYPl4NzqGpeAWUuGQ6ji4OAp1/P31/Tc3nvft7ZWv7eAVw3jgTDiPE8Y670sISISDc9l@JS6PUKp4/p@eZ9Ox5QSUVNmM5MMrBeHLCJw3l1AVf5BsoGjB1XoL9fcd2U1FgN17ro/2g8 "R – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
```
RomanNumeral@Range@3999~Count~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pyg/NzHPrzQ3tSgxxyEoMS891cHY0tKyzjm/NK@kTlntf0BRZl6Jgr5DYGlmakl0ur6DQrWSr7NzRESEZ5iSjpKzrw@QGebp6QnkuEDFQGxfX0@YsGdYBIiMCAML@/oCKZAesGCYp1Jt7P//AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~48 47 46~~ 44 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Nick Kennedy
```
5Żo7;“ÆæC‘ð“IVXLCDM”ṃ@3Ƥm2”MẋⱮ3¤ṭŻ€ṚŒpF€ḟ€0ċ
```
A monadic Link accepting a non-empty list of characters consisting only of `IVXLCDM` which yields either `1` (when it's a valid Roman numeral between \$1\$ and \$3999\$) or `0` (if not).
**[Try it online!](https://tio.run/##y0rNyan8/9/06O58c@tHDXMOtx1e5vyoYUaS8eENQK5nWISPs4vvo4a5D3d3OxgfW5JrBGT7PtzV/WjjOuNDSx7uXHt096OmNQ93zjo6qcANxNoxH0gaHOn@//@/s69PREREmKenJwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/06O58c@tHDXMOtx1e5vyoYUaS8eENQK5nWISPs4vvo4a5D3d3OxgfW5JrBGT7PtzV/WjjOuNDSx7uXHt096OmNQ93zjo6qcANxNoxH0gaHOn@f7gdyPj/P1rd19k5IiLCM0xdh0tB3dnXB8gJ8/T0BHNd4OIQvq@vJ0ISaDuEjgiDSvr6ghkgE6BSYSClsQA "Jelly – Try It Online").
### How?
```
5Żo7;“ÆæC‘ð“IVXLCDM”ṃ@3Ƥm2”MẋⱮ3¤ṭŻ€ṚŒpF€ḟ€0ċ - Main Link: list of characters S
5Żo7;“ÆæC‘ - chain 1: f(S) -> X
5Ż - zero range of five = [0,1,2,3,4,5]
o7 - OR seven [7,1,2,3,4,5]
“ÆæC‘ - list of code-page indices [13,22,67]
; - concatenate [7,1,2,3,4,5,13,22,67]
ð - start a new dyadic chain...
“IVXLCDM”ṃ@3Ƥm2”MẋⱮ3¤ṭŻ€ṚŒpF€ḟ€0ċ - chain 2: f(X,S) -> isValid
“IVXLCDM” - list of characters, IVXLCDM
3Ƥ - for infixes of length three:
- (i.e. IVX VXL XLC LCD CDM)
ṃ@ - base decompression with swapped arguments
- (i.e. use characters as base-3 digits of X's values)
- (e.g. IVX -> VI I V IX II IV III VII VIII)
m2 - modulo two slice (results for IVX XLC and CDM only)
¤ - nilad followed by link(s) as a nilad:
”M - character 'M'
Ɱ3 - map across [1,2,3] with:
ẋ - repeat -> M MM MMM
ṭ - tack
Ż€ - prepend a zero to each
Ṛ - reverse
- -- now we have the table:
- 0 M MM MMM
- 0 DC C D CM CC CD CCC DCC DCCC
- 0 LX X L XC XX XL XXX LXX LXXX
- 0 VI I V IX II IV III VII VIII
Œp - Cartesian product [[0,0,0,0],...,["M","CM",0,"IV"],...]
F€ - flatten €ach [[0,0,0,0],...,['M','C','M',0,'I','V'],...]
ḟ€0 - filter out the zeros from €ach ["",...,"MCMIV",...]
ċ - count occurrences of S
```
[Answer]
# Perl 5 (`-p`), 57 bytes
```
$_=/^M*(C[MD]|D?C*)(X[CL]|L?X*)(I[XV]|V?I*)$/&!/(.)\1{3}/
```
[TIO](https://tio.run/##HYu9CsIwFEb3PEWFIknAXmMtVEQ6pMuF3jVcqKmTg1BssW7WVzem3c75fsb7qy/CBEmmAc4hvV2gIy1tS7Wf68pqJbm1jZ@biiNjy87PrkKtUthuQGbqaj75F0Iga5kZXSLNIT8qYamJ7hAxkaeyVKJey8IsXczM3ihBhOtEoGMRMQZEYvlFdfgbxvdjeE5h149/)
* uses almost the same regular expression except `{0,3}` quantifier was changed by `*`
* `&!/(.)\1{3}/` to ensure the same character can't occur 4 times in a row.
* can't be golfed with `-/(.)\1{3}/` because would give`-1` for `IIIIVI` for example
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
import re
re.compile('M{,3}(D?C{,3}|C[DM])(L?X{,3}|X[LC])(V?I{,3}|I[VX])$').match
```
[Try it online!](https://tio.run/##JczBCoMwDAbge5/Cw8AWhrDtNhge6iVgriUgMpwoFqwtpUPGtmfvqssl//cT4l5hsss5Rm2c9SHzAxtvfih6a5yeB57j@3j58qqU2/7IpsJW8LqkndTUMlGVsBMaRa045KIwXeinuE7pRXa6Oq@XwB/WznzkvlvvenHPwEWaiFISESgmsU5BAQCrdgNDhH8BiliKqUBk21WigvgD "Python 2 – Try It Online")
Let's look at the last part of the regex, which matching the Roman numerals up to 9 (including the empty string)
```
V?I{,3}|I[VX]
```
This has two alternatives separated by `|`:
* `V?I{,3}`: An optional `V` followed by up to 3 `I`'s. This matches the empty string `I`,`II`,`III`, `V`, `VI`,`VII`,`VIII`.
* `I[VX]`: An `I` followed by a `V` or `X`. This matches `IV` and `IX`.
The same things with `X,L,C` matching the tens, with `C,D,M` matches the hundreds, and finally `^M{,3}` allows up to 3 `M`'s (thousands) at the start.
I tried generating the template for each trio of characters rather than writing it 3 times, but this was a lot longer.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~56~~ 51 bytes
```
(.)\1{3}
0
^M*(C[MD]|D?C*)(X[CL]|L?X*)(I[XV]|V?I*)$
```
Port of [*@NahuelFouilleul*'s Perl 5 answer](https://codegolf.stackexchange.com/a/183023/52210), so make sure to upvote him!
[Try it online](https://tio.run/##K0otycxLNPz/X0NPM8aw2riWy4ArzldLwzna1yW2xsXeWUtTIyLa2Se2xsc@Asj2jI4Ii60Js/fU0lT5/9/X19fZN8LZMwIA) or [verify all test cases](https://tio.run/##JYqxCgIxEAX7/Q6FJIV4@AEpNiAP8tpl4YxoYWFjIXbefXuM2s0M87y97o/r1LfheOlhF0/T@7DKXs5MQWeWtpSsKQaftbalZh@M2a0tlpHipneSSle4UNXdYaKsAwyAlJ9DSPwDzGXgCKR8r6EGMdgH).
**Explanation:**
```
(.)\1{3} # If four adjacent characters can be found which are the same
0 # Replace it with a 0
^...$ # Then check if the string matches the following fully:
M* # No or any amount of adjacent "M"
( | ) # Followed by either:
C[MD] # A "C" with an "M" or "D" after it
| # or:
D? # An optional "D"
C* # Followed by no or any amount of adjacent "C"
( | ) # Followed by either:
X[CL] # An "X" with a "C" or "L" after it
| # or:
L? # An optional "L"
X* # Followed by no or any amount of adjacent "X"
( | ) # Followed by either:
I[XV] # An "I" with an "X" or "V" after it
| # or:
V? # An optional "V"
I* # Followed by no or any amount of adjacent "I"
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~61~~ ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŽF¯L.XIå
```
Whopping \$\color{green}{\textrm{-52 bytes}}\$ thanks to *@Adnan*, because apparently 05AB1E's Roman Number builtin wasn't documented, haha.. xD
[Try it online](https://tio.run/##yy9OTMpM/f//6F63Q@t99CI8Dy/9/9/X19fZN8LZMwIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f@je90OrffRi6g8vPS/zv9oJV9fX2ffCGfPCCUdJV9n54iICM8wINPZ1wfIDPP09ARyXKBiQLYCUIMnTNwzDKQLyAXpBQIgBdIEFgzzVIoFAA).
**Explanation:**
```
ŽF¯ # Push comressed integer 3999
L # Create a list in the range [1,3999]
.X # Convert each integer in this list to a roman number string
Iå # Check if the input is in this list
# (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽF¯` is `3999`.
---
**Original 61 bytes answer:**
```
•1∞Γ'иÛnuÞ\₂…•Ž8вв€SÐ)v.•6#&‘нδ•u3ôNèyè}'M3L×)Rεõš}`3Fâ}€˜JIå
```
[Try it online](https://tio.run/##AXgAh/9vc2FiaWX//@KAojHiiJ7OkyfQuMObbnXDnlzigoLigKbigKLFvTjQstCy4oKsU8OQKXYu4oCiNiMm4oCY0L3OtOKAonUzw7ROw6h5w6h9J00zTMOXKVLOtcO1xaF9YDNGw6J94oKsy5xKScOl//9NTU1DTVhDSVg) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f9HDYsMH3XMOzdZ/cKOw7PzSg/Pi3nU1PSoYRlQ4uheiwubLmx61LQm@PAEzTI9oJCZstqjhhkX9p7bAuSUGh/e4nd4ReXhFbXqvsY@h6drBp3benjr0YW1CcZuhxfVAjWenuNVeXjpf53/0Uq@vr7OvhHOnhFKOkq@zs4RERGeYUCms68PkBnm6ekJ5LhAxYBsBaAGT5i4ZxhIF5AL0gsEQAqkCSwY5qkUCwA).
**Explanation:**
```
•1∞Γ'иÛnuÞ\₂…• '# Push compressed integer 397940501547566186191992778
Ž8в # Push compressed integer 2112
в # Convert the integer to Base-2112 as list:
# [1,11,111,12,2,21,211,2111,10]
€S # Convert each number to a list of digits
Ð # Triplicate this list
) # And wrap it into a list of lists (of lists)
v # Loop `y` over each these three lists:
.•6#&‘нδ• # Push compressed string "xivcxlmcd"
u # Uppercased
3ô # And split into parts of size 3: ["XIV","CXL","MCD"]
Nè # Use the loop index to get the current part
yè # And index the list of lists of digits into this string
}'M '# After the loop: push "M"
3L # Push list [1,2,3]
× # Repeat the "M" that many times: ["M","MM","MMM"]
) # Wrap all lists on the stack into a list:
# [[["I"],["I","I"],["I","I","I"],["I","V"],["V"],["V","I"],["V","I","I"],["V","I","I","I"],["I","X"]],[["X"],["X","X"],["X","X","X"],["X","L"],["L"],["L","X"],["L","X","X"],["L","X","X","X"],["X","C"]],[["C"],["C","C"],["C","C","C"],["C","D"],["D"],["D","C"],["D","C","C"],["D","C","C","C"],["C","M"]],["M","MM","MMM"]]
R # Reverse this list
εõš} # Prepend an empty string "" before each inner list
` # Push the four lists onto the stack
3F # Loop 3 times:
â # Take the cartesian product of the two top lists
}€˜ # After the loop: flatten each inner list
J # Join each inner list together to a single string
Iå # And check if the input is in this list
# (after which the result is output implicitly)
```
[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:
* `•1∞Γ'иÛnuÞ\₂…•` is `397940501547566186191992778`
* `Ž8в` is `2112`
* `•1∞Γ'иÛnuÞ\₂…•Ž8вв` is `[1,11,111,12,2,21,211,2111,10]`
* `.•6#&‘нδ•` is `"xivcxlmcd"`
[Answer]
# perl -MRegexp::Common -pe, 34 bytes
```
$_=/^$RE{num}{roman}$/&!/(.)\1{3}/
```
The `&!/(.)\1{3}/` part is necessary, because `Regexp::Common` allows four (but not five) of the same characters in a row. That way, it matches roman numbers used on clock faces, where `IIII` is often used for 4.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~116~~ ~~113~~ ~~109~~ ~~107~~ ~~105~~ 106 bytes
```
import re
lambda n:re.match(r'(M{,3}(C(M|CC?|D)?|DC{,3}))(X(C|XX?|L)?|(LX{,3}))?(I(X|II?|V)?|VI{,3})?$',n)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fbvs/M7cgv6hEoSiVKycxNyklUSHPqihVLzexJDlDo0hdw7dax7hWw1nDt8bZ2b7GRROInUFCmpoaERrONRER9jU@QEENnwiIqL2Gp0ZEjaenfU0YUDjMEyxqr6Kuk6f5//9/AA "Python 3 – Try It Online")
*-1 byte thanks to ShadowRanger*
[Answer]
# [Ruby](https://www.ruby-lang.org/), (`-n`) 56 bytes
```
p~/^M{,3}(D?C{,3}|CM|CD)(L?X{,3}|XC|XL)(V?I{,3}|IV|IX)$/
```
[Try it online!](https://tio.run/##JYq7CgIxEEX7@Q6LBJQt7Gy2mDQXdtphKkELUZDdZR/FYvTTjUms7jmHO63XLaXx05zltT@@XWi5bGSJHLzrWqtqHK3zTltUhUaY3zUpLdO63LcTCbOZQYmly6AAKFQH3S7PuVwE/w41ypiDCJVzVgUp9DuMy2Po53Tofw "Ruby – Try It Online")
Outputs 0 (truthy) or nil (falsy).
]
|
[Question]
[
This is a bit similar to this [dust covered entry](https://stackoverflow.com/questions/2985540/code-golf-banner-generation) but I'm hoping my spin on it makes it unique enough. Not been able to find anything dissuading me from posting this but there is quite the sea out there.
Anyway! The challenge:
Your code receives a string of characters; It converts this into an ASCII-art style version of the same string, but with a catch.
# Input transformation
* The only characters to be supported are A-Z and 0-9
* Lower case letters are transformed into uppercase
* Anything else is silently removed
# Character drawing
* Each "pixel" of the enlarged font is drawn from the input string
* The n'th pixel is equal to the n'th character in the input string. If n is greater than the length of the input string, wrap around back to the beginning
* Individual letters are drawn left-to-right, top-to-bottom
* Subsequent letters pick up their "pixel character" index from where the last letter left off (e.g. with an input length of 10, if the first letter had 9 pixels, the second letter's first pixel will be drawn with the 10th input character, the second pixel will be drawn with the 1st input character)
* Each letter is drawn in a 5x5 grid, fully padded with spaces. You can find the font you are to use pre-rendered for you in [this pastebin](https://pastebin.com/e504bUBB) or a bit further down in this post
* Every letter is drawn on the same line, so the total number of line breaks in your output will be 4
* Every letter is seperated by 2 columns of spaces
# The font
```
000
0 00
0 0 0
00 0
000
111
1
1
1
11111
2222
2
222
2
22222
3333
3
333
3
3333
44
4 4
44444
4
4
55555
5
5555
5
5555
6666
6
6666
6 6
666
77777
7
7
7
7
888
8 8
888
8 8
888
999
9 9
9999
9
9999
AAA
A A
AAAAA
A A
A A
BBBB
B B
BBBB
B B
BBBB
CCCC
C
C
C
CCCC
DDDD
D D
D D
D D
DDDD
EEEEE
E
EEE
E
EEEEE
FFFFF
F
FFF
F
F
GGGG
G
G GG
G G
GGGG
H H
H H
HHHHH
H H
H H
IIIII
I
I
I
IIIII
JJJJJ
J
J
J
JJ
K K
K K
KKK
K K
K K
L
L
L
L
LLLLL
M M
MM MM
M M M
M M
M M
N N
NN N
N N N
N NN
N N
OOO
O O
O O
O O
OOO
PPPP
P P
PPPP
P
P
QQ
Q Q
Q QQ
Q Q
QQ Q
RRRR
R R
RRRR
R R
R R
SSSS
S
SSS
S
SSSS
TTTTT
T
T
T
T
U U
U U
U U
U U
UUU
V V
V V
V V
V V
V
W W
W W
W W W
WW WW
W W
X X
X X
X
X X
X X
Y Y
Y Y
Y
Y
Y
ZZZZZ
Z
Z
Z
ZZZZZ
```
Yes I know the 4 and Q are ugly
# An example
Input
```
0123456789
```
Output
```
012 567 6789 0123 34 45678 9012 34567 234 567
3 45 8 0 4 5 6 9 3 8 5 6 8 9
6 7 8 9 123 567 78901 0123 4567 9 789 0123
90 1 0 4 8 2 4 8 9 0 0 1 4
234 12345 56789 9012 3 5678 012 1 234 5678
```
# Another example
Input
```
a3 B'2
```
Output
```
A3B B2A3 2A3B 2A3B
2 A B 2 A 2
3B2A3 2A3 3B2A A3B
B 2 B 3 B 2
A 3 2A3B 2A3B A3B2A
```
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. Code golf so no green tick will be given.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~413~~ ~~411~~ ~~373~~ ~~364~~ ~~352~~ 345 bytes
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
-9 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king).
-1 byte thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn).
Data string contains unprintables, escaped version below.
```
k=list(filter(str.isalnum,input()))
q=range(5);o=['']*5;r=k*25;d=0
for c in'uM<LxSe#ye>El4NpD@$ gh>
I,m]aB>e,
]?kFL
yglxV!
%w832wGj%uT{Hr*K,*[P\n6.&ED#T
}^
DLI&p7f\d`*lG!FacG\rz?!A':d*=126;d+=ord(c)-1
for c in k:
for i in q:
for y in q+[999]*2:o[i]+=d>>int(c,36)*25+i*5+y&1and r.pop(0)or' '
print'\n'.join(o).upper()
```
[Try it online!](https://tio.run/##PZH7b9JQFMezTBNXCCPGucVHcukcty8bKCsbYDuHFMbGHjo2H4Cxthe4a3dvd2kD1fi3Y4uJP518Tr4553y/J4jDKSXa0qEuAgZgPM8vPcPHs1AYYz9ETJiFTMUz2yfRvYJJEIWCKIrcg8FsMkGCLjaoMYBwJOkNZniSpjdco8SNKQMOwARG54/e9fKLZ9doN0abpuXvXwSt9282JlPzdX6rq@TuR3ZuvWmiLSU7Wj/y2r21TDzxF7eFnefZTD6zNz@saPPO3V7U/33CpDNFGlwNSVUtWq3dfvbP91ebre1etxgcbI@H7g9pzX/ZeVpo287jJ7nOkP06Krw4hnVXMspateHKBmWu4Ihvy/8PBF6dAyngFB7q3EYK8QrkQa1WG0lanQ7wSDZc08QkFBylUhUTnzKWdDkulm3iAqYGNBBKImUQQC5giQ4OCVTvKCYCFdUoCJIkxWWSLjefYh@BPotQshmELE4LAGiBHJB@YUWrEVzadVAQAuuybTFG2T/pT4ZsbwlLZa2yr1cPDmuQg8fNDy2r3Tnpnp71zi8urz5@uu7f3H7@8vUb5Hi7AppQ4/8C "Python 2 – Try It Online")
As each character has 25 pixels it can be easily encoded in 25 bits. The base 126 number `'uM\x04<L\x10x\x14Se#ye\x0f>El4NpD@$\tgh>\x1d\x10\x15I,\x0em]a\x0e\x03B>e\x15,\x0c]\x03?kFL\x01\x0byglxV!\x18\x16\x0c\x0b\x10\x0b%w832wGj%uT{Hr*K,*[P\n6.&ED#T\x0c}^\x1c\x0fD\x17LI&p7\x17f\\d`*\x01l\x1bG\x12!Fac\x05\x08\x0eG\rz?!\x1aA'` encodes all chars, the `0` is encoded by the least significant 25 bits, the `1` by the next 25 bits and the `Z` is encoded by the 25 most significant bits. A single character is encoded in the following order:
```
00 01 02 03 04
05 06 07 08 09
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
```
(`00` is the least significant bit, `25` the most significant one)
Spaces are encoded by a zero, non-spaces by a one. *Example*:
```
77777 11111
7 00001
7 => 00010 => (0001000100010001000011111)
7 00100
7 01000
```
---
## Ungolfed
```
k = list(filter(str.isalnum,input())) # keep only alphanumeric characters of the input
o = ['']*5 # this list contains the output, initially 5 empty lines
r = k * 25 # make a copy of the input 25-times the length, these chars will be used for the pixels
data = 0
# data encoded in base 126
b92d = 'uM<LxSe#ye>El4NpD@$ gh>
I,m]aB>e,
]?kFL
yglxV!
%w832wGj%uT{Hr*K,*[P\n6.&ED#T
}^
DLI&p7f\d`*lG!FacG\rz?!A'
for c in b92d: # convert base 92 to base 10
d*=126;d+=ord(c)-1
for c in k: # iterate over the filtered input
a_index = int(c, 36) # the index of the current char in '0..9A..Z' / '0..9a..z'
for i in range(5): # for each row of the output
for y in range(5)+[999]*2: # for each pixel in the row, th two 999's are used for spaces
is_set = data >> (a_index*25 + i*5 + y) & 1 # We shift the to the right to have ...
# the current pixels value at the LSB:
# 25 bits for each char that came before
# 5 bits for each previous row and 1 bit
# for every pixel in the same row
o[i] += is_set and r.pop(0) or ' ' # If the current pixel is set, append ...
# ... a character from the input to the current row
print '\n'.join(o).upper() # print the output
```
[Try it online!](https://tio.run/##nZT9T9tGGMdVdZU2gyia1nXai/SQrNgJqRtCoQ0b6WAEypq@bNB2LWTdxX4SX@P4rLsziTvtb2fPncMI60/DkaKz73k@z8v3uUtzHYmkcRaIEGELZKlUOhvSIuZKe30ea5Se0tLnisVJNqrxJM20V6lUAMowRExBJHEOLE4jRvsoeQBBxCQLyFOB6IOOEKyXI4h77Lrd6joYbx1xZeNAIBLNeKKsrcg0GdfIh2vOYoKvA45SnZNtgsqRRBlCFRoFZcSGCIwQaX4pGu3f1XyEBTTGZKCjmlkrtAkqGPM4hh5CpjCEvpDWMOUTjJUTMs0oTt0pA9g1JqZDIbGhxwix2thwes1GSEZu9vSTHzuLky8OsZzjzVY7vv8s3f3p@88GUeu7xVsHtYVRly1c32nhrdp89/qj4V7n2lw@iCevlr76cn5uce7O@OFaY7z//k529NdjWX1Sqx6/OEk2/OX2bvlo/u8/vr25e7tzsJw@uN0/Cf@sXou/2f98aY8FNz5d2D@RHx4tfb3tOqaAwKZHWW3Cv0/ZdPcUpS7ybjZAi2kJdYeKq25RKT@EK1tChl5QubvqXKCGMxyL4iQq06QRAW27igmxfTEKA7B3PAlxQm3hifaCGqxtVAqxjS5mZypSkEmJibZamFhu3feb277/1oV7xQvz/Q8uIU063JhIlgzQW69sFsmY78iCCKQYn1OL4XGMgdnOZ91WjpvNZrfa2LzkbAU3ZsadSGZGQI8FkLGrgMmZAVEpC2gCi25w9U6hpkLtfLRa4E1rr9JkrgCvmv@8AsuwagK@RlAR72sbhySw4fgg0uYlYqcIvu878P@f8qV2FvMLpyzO6FgU0TqHO5tXI1MlPa7VRbesWjoicMBGSKeHdvBq7P@iU4mnXGTKysmSkNpGBldjWyjNaH5ZXmVyJvwUKo55F1a2zpU0MaWfitSrV4AALv1moQf9jztNvkC@NWBpiuR/ZQ3J0dxi5zcn9KUYzVxm04E5j21qSCWdMHBPEtd/L3jiiYqfURLSs@et2L04Emd0sTvjiMcIRzJDMw9a5sVY4ATp0qbrzb5ZT8d8DTDV0H6@15ZSyMK0J5ENz9z6amPt/vrGg4dN13G3d37ebe/tPz745Unn6bPnL3797fDo5avXv7956zoltgY7bqP0Dw "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~228~~ ~~225~~ ~~224~~ 214 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")
Full program. Prompts stdin for string. Prints to stdout. About half of the code is just decoding the encoded alphabet.
```
⍉↓(⍴t)⍴r\i⍴⍨+/r←,t←(⊂a⍳i←(1(819⌶)⍞)∩a←⎕D,⎕A)⌷0(220⌶)¯1(219⌶)¯125+⎕AV⍳_________________________________________________________________________________________________________________________________________________
```
`_`…`_` represents the following 143-byte LZ4-encoded string in quotes: `"⊥\u0004pæ€}€\\⊃⌿Æ€â<Å€∧€ÀÆ€Ð┬:Ëcü\u0000≥ðè⊤õ⍨¢∧·èý\u0005þÐÕ\u001EÐ :\u001Eè⌊×ßi[B⊂ɫoãà oéìÐ⍙⊃Ý∣à)≥èB⊃\u001B\u001F⊥ä{⌿⍨ G⍺\u001B⌿Æ\u001F∇x└îR`:└è→⊂\u0000ê∧⍒\u0003ɫqè$$ÛD⊥â∊\u001B\u001Eéu|\u001B@4A|⍪┌nàkááЀ€€€€€€"`
[Try it online!](https://tio.run/##zVPLTlRBEN3PV9Ru7gQMXdXvJQ/FF6Ii@AgJuYmJISFhQti4dYFoGGNi2LqWFQuN7v2U/pHhVPdVFySuubm3prqqus6p0z399ODW67f9weGb@d5Ne8rJ5/LpfHt1i1IKmRwxC4k1lGzAQnxzsiBvPWUjljinFhUJFAzWsa1TdHbYiA3/ykyi7DmQT/At5UzihYCRjCdxBoDaPyDtFEMbBDSQ2FpysrVEvCVs8K2lsCUQVRc5vGhvh145wmHUKl2AZKYQdARHgTOGZNDzQEFjUTRTY2IVKDTGxuU2tAiDh8211PFAGzCtJfxIlpuAIgm8bROqToK6yHCTaN1fAXVDVBpiKLusokMuoVxlGiKYxGfXeOtkg8SghoGHSZo0IK28EYGKA5OgCK6yM3U05gi8GgExHEHwdQ2eAZBJT980QUzEr2@fGc7xv2ZUTt/TdF5mH8rJl67MfhxPYI5292HL7NvC0hGu2uIxTFc@vuvL7Pu@@twlzuXsJ4q/TsrpRd8u5NoizPKknP0ynYjRgt@X3EmrhSt@QSt20OfG/afmkGJO9ZmODG6D8yGmPGqh8Xj0J9dbWhnL9fjyyura7Tvrd@/df/Bw43r60ebjJ0@3nm3vPH/x8tUV "APL (Dyalog Unicode) – Try It Online")
`_`…`_` 143-byte LZ4-encoded string in quotes
`⎕AV⍳` **ɩ**ndices of that in the **A**tomic **V**ector (the character set)
`¯125+` add -125 to that (to get signed 8-bit integers)
`¯1(219⌶)` LZ4 decompress
`0(220⌶)` deserialise to a 36 layer, 5 row, 5 column Boolean array
`(`…`)⌷` index into that using the following indices:
`⎕A` uppercase **A**lphabet
`⎕D,` prepend the **D**igits
`a←` store in `a` (for **a**lphabet)
`(`…`)∩` intersection of the following and that (removes invalid input):
`⍞` prompt for text input from stdin (console)
`1(819⌶)` fold to uppercase (`819` looks like `Big`, 1 is for yes big as opposed to small)
`i←` store in `i` (for **i**nput)
`a⍳` **ɩ**ndices of that in `a`
`⊂` enclose (to index with each one representing the leading coordinate)
`t←` store in `t` (for **t**ext)
`,` ravel (flatten)
`r←` store in `r` (for **r**avelled)
`+/` sum that (i.e. number of characters needed to paint the artwork)
`i⍴⍨` cyclically **r**eshape the input to that length
`r\` expand that; insert a spaces at 0s, consume letters at 1s
`(`…)⍴` reshape to the following shape:
`⍴t` the shape of the text
`↓` split the N-by-5-by5 array into an N-by-5 matrix of art lines
`⍉` transpose into a 5-by-N matrix of art lines (this aligns corresponding lines of the characters)
By default, APL separates simple elements of a nested array with 2 spaces.
[Answer]
# [Python 2](https://docs.python.org/2/), 428 bytes
```
s=filter(str.isalnum,input().upper());x=s
R=['']*5
for c in s:
i=0;exec"n=int('RAAAOQQ2RBAQBQRRBDRRDCDDAQ8QBRDDDDDRXDDF0XX6CCDDCDCCCD00ECNLDDEDC0DDD66YYABH0A3RQQRQCDOOFR00OCHHDQIQA0D6H0000DXL0CXYXDDDCDCCDD00ECDFDCEEX0D6N6044AQARRQYQADQBQRCBDRKDRDDAC9DQ0A0DD0R'[i*36+ord(c)%55%45],36);R[i]+=bin(n+36*(n<30)<<2)[3:].replace(*'0 ').replace(*'1.');i+=1;"*5
while'.'in`R`:R=eval(`R`.replace('.',x[0],1));x=x[1:]+s
print'\n'.join(R)
```
[Try it online!](https://tio.run/##TVBdb5tAEHz3r6CWouOMhRZjrokxD8etLVeNYt0@YVGkOJQoV9EzApy6/fPuxQ9V92U/ZnY0mu73@Hayi@t1yF5NOza9P4x9aIZja88/58Z259Hn4bnrHMJ5esmGCWUlY9Usmbyeeq/2jPWG1cQzGaTNpamnNjN29BlJKfdaLyiXOtdEORKhQpT6XueEH0UF4haKQih3V6hcA9iop0fEDSpwDCEOB5nvQMakNWmF@/2WAPZqt0P9RUtAsQNXWDyCKg5O76aDNx3cotpsCsd5ErBcSi2J9EFL/PCjnJ@v6HxI9YAanBICsdLMYhGc@u9@ze@S5G6ZVPNY8JRKUwXZi7G@DWIx8@06Br5eL3gZr6qwb7r2WDf@jIHH@H9rFDKemiCL0qmLy/v1ZtqGhczYZ3peUda8H1vfjf8@HDa/lFDNo1vUlzJaVcEw6XqXKPtmWfjj5CwQv14ZRIt4mYjP9w/T40vtffrD/gI "Python 2 – Try It Online")
---
The letters are encoded as follows:
Each unique part (there are 23) is converted to binary, and a 1 is added in front. Then it is converted to base 36.
```
part bin 1+bin int base36
' ...' -> 00111 -> 100111 -> 39 -> 13
```
The resulting base-36 numbers are:
```
[10,12,13,14,16,18,19,1A,1B,1C,1D,1E,1F,1H,1I,1K,1L,1N,1O,1Q,1R,X,Y]
```
The initial `1` is removed, so we have a single character:
```
[0,2,3,4,6,8,9,A,B,C,D,E,F,H,I,K,L,N,O,Q,R,X,Y]
```
Each letter (`A-Z0-9`) is then encoded to five of these new chars.
```
0 = ' ... ','. ..','. . .','.. .',' ... ' -> A,F,H,L,A
1 = '... ',' . ',' . ',' . ','.....' -> O,0,0,0,R
etc.
```
Into five lists:
```
'AOQQ2RBRAAAQBQRRBDRRDCDDAQ8QBRDDDDDR'
'F0XX6CCXDDDDCDCCCD00ECNLDDEDC0DDD66Y'
'H0A3RQQYABRQCDOOFR00OCHHDQIQA0D6H000'
'L0CXYXD0DXDDCDCCDD00ECDFDCEEX0D6N604'
'ARRQYQA4AQDQBQRCBDRKDRDDAC9DQ0A0DD0R'
```
To map the input to an index in these lists, the ordinal is modded:
```
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ord(c) = [48-57, 65-90]
ord(c)%55%45 = [3-9, 0-2, 10-35]
```
Because the ordinals are not 0-35, but slightly mixed, the 5 lists are rearranged, and concatenated:
```
'RAAAOQQ2RBAQBQRRBDRRDCDDAQ8QBRDDDDDR'
'XDDF0XX6CCDDCDCCCD00ECNLDDEDC0DDD66Y'
'YABH0A3RQQRQCDOOFR00OCHHDQIQA0D6H000'
'0DXL0CXYXDDDCDCCDD00ECDFDCEEX0D6N604'
'4AQARRQYQADQBQRCBDRKDRDDAC9DQ0A0DD0R'
->
'RAAAOQQ2RBAQBQRRBDRRDCDDAQ8QBRDDDDDRXDDF0XX6CCDDCDCCCD00ECNLDDEDC0DDD66YYABH0A3RQQRQCDOOFR00OCHHDQIQA0D6H0000DXL0CXYXDDDCDCCDD00ECDFDCEEX0D6N6044AQARRQYQADQBQRCBDRKDRDDAC9DQ0A0DD0R'
```
---
For each char in the input, it's 5 letters are found, and converted to a ints(base36):
```
n=int('RAAA...D0R'[i*36+ord(c)%55%45],36)
i*36 #get row i
ord(c)%55%45 #n -> 0..35
int( ,36) #convert to int
```
If the number is below `30`, `36`is added (the missing `1`we removed earlier)
```
n+36*(n<30)
```
Then the number is converted back to binary, and `0`s and `1`s are converted to and `.`. Two spaces are added at the end during the conversion.
```
bin(n+36*(n<30)<<2)[3:].replace(*'0 ').replace(*'1.')
n+36*(n<30) #add leading base36 '1'
<<2 #add 2 0's to end
bin( ) #convert to binary string
[3:] #remove '0b1' from front
.replace(*'0 ').replace(*'1.') #replace 0 and 1
```
Eg.
```
C base36 int <<2 bin-str str
3 -> 13 -> 39 -> 156 -> 0b10011100 -> ' ... '
```
For each `.` in the result, it is replaced by the next character from the input (iterated by `x`)
```
while'.'in`R`:R=eval(`R`.replace('.',x[0],1));x=x[1:]+s
```
[Answer]
# Java 8, ~~917~~ 907 bytes
```
int i,l;String[]S;s->{String q=" ",t="",r[]={t,t,t,t,t};S=s.toUpperCase().replaceAll("[^A-Z0-9]",t).split(t);i=-1;l=S.length;for(String c:S){r[0]+=s("12357BDEFHIJKLMNPRTUVWXYZ",c)+s("012356789ABCDEFGIJOPQRSTZ",c)+s("0123456789ABCDEFGIJOPQRSTZ",c)+s("023456789ABCDEFGIJOPRSTZ",c)+s("567CEFGHIJKMNSTUVWXYZ",c)+q;r[1]+=s("05689ABCDEFGHKLMNOPQRSUVW",c)+s("4MNXY",c)+s("1IJT",c)+s("04KMQXYZ",c)+s("023789ABDHMNOPRUVW",c)+q;r[2]+=s("0456ABCDEFGHKLMNOPQRUW",c)+s("245689ABEFHKPRSV",c)+s("012345689ABEFHIJKMNPQRSTWXYZ",c)+s("23456789ABGHPQRSV",c)+s("0349ADGHMNOUW",c)+q;r[3]+=s("0268ABCDEFGHKLMNOPQRUW",c)+s("0VWXZ",c)+s("17IJTY",c)+s("4KNQRVWX",c)+s("035689ABDGHMNOSUW",c)+q;r[4]+=s("12359ABDEFHIJKLMNPRSWXZ",c)+s("012356789BCDEGIJLOQSUZ",c)+s("01235689BCDEGILOQSTUVYZ",c)+s("012345689BCDEGILOSUZ",c)+s("12ACEGHIKLMNQRWXZ",c)+q;}return"".join("\n",r);}String s(String...s){return s[0].contains(s[1])?S[++i%l]:" ";}
```
Will golf it down from here to at least halve the current byte-count hopefully..
[Try it online.](https://tio.run/##fVRrc5pAFP2eX7FlplMYhSgSH2FoazT1FYmKplFqZwjBiCGA7JpMxuG327u8pPYxfIDdc@49Zy/37sZ4NfjN4/PBdAyM0dCw3f0ZQrZLrGBlmBZS6RIhjQS2@4RMNvnAnAz74VnMRXbRkWNEX2oyDTg/RyMjIMhbIbK20MM7sXjT27kEIlTkIgUdMP95n6TbKgxiikRhmGKgL5U9KSZPKGsKFog3830raBnYYjkhsHwHrDUdh2X0n01@UeIbS4jmBOw7NmEJJ9sKX5YdRRMcy30ia3nlBalz81Lj9oFeWhYUzDJlsXJRu2pff@v2@oOboTqaTGd33@/nC6ZocgUglCijWqs3mlctoHV6/dvReKJNfyNI/2f8hZDHAWvBNnUwVLW8/lYO9HJstHRRzRJ0qdNIBLhpFmmo3s/TRbnXn2by0mA4zp9IrERe2l2aZJKmoFpiogV2T6VmmZAoxVagZgM4x91JIRIoOkxUh3w1j5XodCl4DK5IjWa7Qy3Njn4qiR@xWv@3nxLUKxMo1@DkWRmkgTqeAHxUif3FQlpOSTq2A8Vz/aDlsmfNQM3Af7y5HWuzEzQFKQb/cr74oz4pngsti83WNXQAlRxPUsWtHAYW2QUuwwgbz3ZZ5ocLA8LJoZyOYdLVgiBg6OqIjDA0t2B6LoFhxiyGDuK@aHqhYH90lpcwZ3J4gCH0dw@ObSJMDAKvV89@RC8QwKZjjAwuGf13TKwXwdsRwQeIsK71Fl0UMIquYLKMUUFXn8RtXayttx/eGl8ZLrkcwsMv)
**Explanation:**
```
int i, // Index-integer on class-level
l; // Length-integer on class-level
String[]S; // String-array of characters on class-level
s->{ // Method with String as both parameter and return-type
String q=" ", // Temp String containing two spaces to reduce bytes
t="", // Temp Empty String to reduce bytes
r[]={t,t,t,t,t}; // Start with five empty rows
S=s.toUpperCase() // Transform the input-String to uppercase
.replaceAll("[^A-Z0-9]",t)// Remove all non alphanumeric characters
.split(t); // And transform it into a String-array of characters
i=-1; // Set the index-integer on -1 to start with
l=S.length; // Set the length of the modified input
for(String c:S){ // Loop over the characters of the modified input:
r[0]+= // Append to the first row:
s("12357BDEFHIJKLMNPRTUVWXYZ",c) // The first pixel
+s("012356789ABCDEFGIJOPQRSTZ",c) // The second pixel
+s("0123456789ABCDEFGIJOPQRSTZ",c) // The third pixel
+s("023456789ABCDEFGIJOPRSTZ",c) // The fourth pixel
+s("567CEFGHIJKMNSTUVWXYZ",c) // The fifth pixel
+q; // Two trailing spaces
r[1]+= // Append to the second row:
s("05689ABCDEFGHKLMNOPQRSUVW",c) // The first pixel
+s("4MNXY",c) // The second pixel
+s("1IJT",c) // The third pixel
+s("04KMQXYZ",c) // The fourth pixel
+s("023789ABDHMNOPRUVW",c) // The fifth pixel
+q; // Two trailing spaces
r[2]+= // Append to the third row:
s("0456ABCDEFGHKLMNOPQRUW",c) // The first pixel
+s("245689ABEFHKPRSV",c) // The second pixel
+s("012345689ABEFHIJKMNPQRSTWXYZ",c) // The third pixel
+s("23456789ABGHPQRSV",c) // The fourth pixel
+s("0349ADGHMNOUW",c) // The fifth pixel
+q; // Two trailing spaces
r[3]+= // Append to the fourth row:
s("0268ABCDEFGHKLMNOPQRUW",c) // The first pixel
+s("0VWXZ",c) // The second pixel
+s("17IJTY",c) // The third pixel
+s("4KNQRVWX",c) // The fourth pixel
+s("035689ABDGHMNOSUW",c) // The fifth pixel
+q; // Two trailing spaces
r[4]+= // Append to the fifth row:
s("12359ABDEFHIJKLMNPRSWXZ",c) // The first pixel
+s("012356789BCDEGIJLOQSUZ",c) // The second pixel
+s("01235689BCDEGILOQSTUVYZ",c) // The third pixel
+s("012345689BCDEGILOSUZ",c) // The fourth pixel
+s("12ACEGHIKLMNQRWXZ",c) // The fifth pixel
+q;} // Two trailing spaces
return"".join("\n",r);} // Return the rows joined with new-lines
// Separated method with String-varargs parameter and String return-type
String s(String...s){
return s[0].contains(s[1])? // If the String contains the character-String:
// Increase `i` by 1 first with `++i`
S[++i%l] // Then return the i'th character of the modified input
// with wraparound by using modulo-`l`
: // Else:
" ";} // Return a space
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~213~~ ~~211~~ ~~210~~ ~~209~~ ~~206~~ ~~193~~ ~~191~~ ~~190~~ ~~188~~ 187 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
u f\w Ën36 g`...`ò4)nLõd)¤®Í?FgT°:SÃò5n)ù6ÃÕm¸
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVI&code=dSBmXHcgy24zNiBnYBAhMkseMjc4IDMyHCAySU8HQgovIgcKGxEdKwchNwkJEBoVDxAaGisQG18aIQU5HxEbYyghBBgTIgZePCIGXi0RHB4sEyo0NiFBDFQhQQxNEy0xUhIgVSATShpeE0NIFhAaM1chBThVDhQ7NiEFOTIRG0obIUEMORMpCQ8TKCMKEyk1IhMQUAYTEE4BITo6TGDyNCluTPVkKaSuzT9GZ1SwOlPD8jVuKfk2w9VtuA&input=IjE4IGF6Ig) or [test all characters](https://tio.run/##y0osKPn/v1QhTUm1XEnhcHeesZlCeoKAopG3nJG5hYKxkYyCkac/uxOXvhI7l7SgrDa7ojknp4CUKL@AlJS2gHS8lCKrpbygdLKGIouEsBJbnA0Q6wrKyOkIa5mYKTryhACxr7CuYZCQQqiCsJdUnLCzh5iAlHG4IqtFKJ@ItRlQv5GgtJc0UJ2lsCYnv7CGMpewpqmSsEAAm7CAH6OilZVPwuFNJpp5Poe3pmgeWnJo3eFee7f0kEMbrIIPNx/eZJqneXinGZA1NffQjv8htgZBmUHaoYVB/6O5lAwMjYxNTM3MLSwVHbSUuJQSk5JTUtPSMzKzsnNygfy8/ILCouKS0rLyisoqJa5YLt3cIAA) (the extra bytes are due to TIO not supporting Japt v2)
---
## Explanation
### Lookup Table
Every group of 4 characters in the backtick enclosed string (represented by `...` above to save space and because it contains a bunch of unprintables) is the binary representation of each character (`0` for spaces, `1` for characters) with the newlines removed and converted to base-100.
**Example**
```
ZZZZZ -> 11111
Z -> 00010
Z -> 00100 -> 1111100010001000100011111 -> 32575775 -> !::L
Z -> 01000
ZZZZZ -> 11111
```
### The Code
```
u f\w Ën36 g`...`ò4)nLõd)¤®Í?FgT°:SÃò5n)ù6ÃÕm¸ :Implicit input of string U
u :Uppercase
f :Match
\w : RegEx /[a-z0-9]/gi
Ë :Map each D in array F
n36 : Convert D from base-36 to decimal
g : Index into
`...` : The string described above
ò4 : Partitions of length 4
) : End Indexing
n : Convert from base
Lõ : Range [1,100]
d : Get characters at those codepoints
) : End base conversion
¤ : Convert to binary
® : Map
Í : Convert from binary to decimal
? : If truthy (i.e, 1)
Fg : Get the element in F at index
T° : T (initially 0) postfix incremented
: : Else
S : Space
à : End map
ò : Partitions of length
5n : -5 (i.e., weighted towards the end)
) : End partition
ù6 : Left pad each with spaces to length 6
à :End map
Õ :Transpose
m :Map
¸ : Join with spaces
:Implicit output joined with newlines
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 366 bytes
```
->s{s.tr!('^0-9A-Za-z','');b=([s]*s.size).map(&:chars);%w(esuu6vfveeeufuvvfhvvhghheucufvhhhhhv j411agg1hhhhghgggh44igrphhihg4hhhaa2 l4e7vuu2efvughssjv44sgllhumue4hal444 p4g121h4h1hhghgghh44ighjhgii14hara48 evvu2ue8euhufuvgfhvohvhhegdhu4e4hh4v).map{|x|w=t='';s.chars{|c|c=~/\w/&&w+="%5b "%x[c.to_i 36].to_i(36)};w.size.times{|i|t+=w[i]>?0?b[i/7].rotate![-1]:' '};t}}
```
[Try it online!](https://tio.run/##JZDxboIwEMZfpZooMAda7NRJ0Li9xCZjS2GlV6PR0F5xCnt1h@z@uvty9@X3XYnZz62Ib/5KX3Vgyp7rfE78542/5f7FeXQcL8piN9Hpgw60uggvOPCTO1zmwEvtRYPKFRpxZgsrhMACrS3AWpAAAnMsLNzLkh2jlEtJ75MEKSUwpmR5AlAgWStyHpI9E3OLGIrCogStd5YxLfd7wAMKBnzPGCMnJmlIgQH9d4LOCXYglaLtUsnZgghrMUSxEAh3JtkyHaFlEfIbkLVewGyX5Fqf6yo2seNEOugyXeu8zuPf8Uc1Hg6rUdwfPGWE9AfnJA/M8UuR6SztGnc685qo6r4SGHUQ7amqzSiuEpWu1pN1lqjxPA3Ko@FG9BKfpkuHOE1kmuZ2QqNJkfQnNNy8vL69b/vp7Q8 "Ruby – Try It Online")
This can be golfed a lot, but now I've run out of time and ideas. It was harder than I first thought just to get it working.
### How it works:
It's not so hard to understand, I'll just explain how the alphabet is coded with an example. Every line of every character is converted to binary and then to base-36.
```
AAA -> 01110 -> E
A A -> 10001 -> H
AAAAA -> 11111 -> V
A A -> 10001 -> H
A A -> 10001 -> H
```
The first step is stripping all non-alphanumeric characters from the input string.
Then I generate a lookup table for the final rendering, because I want to print line for line.
After that, iterating on the alphabet line, I create the binary pattern of the letters.
Finally I replace 0 with spaces and 1 with characters from the lookup table.
Feel free to golf further, I know this could be 20-30 bytes shorter (using gsub instead of tr, and so on), but I'm not interested now, unless I can make the alphabet table drastically smaller.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~172~~ 164 bytes
```
≔⁺⭆χιαα≔Φ↥S№αιθFθ«E⁵⭆§⪪”)∧%"<⁰ETV´el⟧2[◧À&η²p.±‹§K×GR←∨�X¶⌈hF)ξυ9DUuqε↘Z)s⎚H⊙←<¿.&]~b≧✂⪪XïJ61%ZWm/ειK⮌λ﹪▷(σΠNc←º✳Fb⌕⊘¹ÞEpM&➙δl◨α↑j≕ςL¡ρG⁰/y”⁵⁺κ×⁵⌕αι⎇Iμ§θ⊖L⊞Oυω M⁷±⁵
```
[Try it online!](https://tio.run/##dVTdTsIwFL5mT9HsxkNSk1ZDvOAKMSQkoiTgAzSjjsXRja5DjfHZ58pK13a4ZN05PX9fv9OzZM9kUrC8aWZVlaUC1nldwUbJTKQrVgIlGGVjjNj5nUbGa5Hlikt4K0suE1ZxWIqyVl0YjFvfeVELBUwHt9qxjXwvJILjGP1Eo3XrpkCnn2DU15qppdjxL9iUeaYgJpRSQon56NV8zqJWnIVeHtJtmNihwUabPZO2122840icCN9AiYOqx@W@JPCzkq9Sv0ZnoC5MY70m@dWJA7j3C7K45yABVwODS4DDIiVDfKH6X6OGhgtntCeo640xknDpq1F7S8KjnqXO4GAOKbEdDNi1J7dYzJ3s0g4j3IZa1hz2rp3c5CYD9AFS4lXwItzBcJ2JJ4cGvynh1dVPjNGknd/zT@EDo2124JUe2kUmdma69XxvuRRMfsOcVQoO7cZllI8YPfFE8gMXiu/gmYtU7WFdV/vX9s/BVCGhxuizyxKjWAvTaLQqThweMHrhKVMcJnrzt2nYPXq8uYua21P@Bw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁺⭆χιαα
```
Prefix the digits to the predefined uppercase alphabet.
```
≔Φ↥S№αιθ
```
Uppercase the input and filter out all the unsupported characters.
```
Fθ«
```
Loop over the remaining characters.
```
E⁵
```
Loop over each row, implicitly printing each result on its own line.
```
⭆§⪪”...”⁵⁺κ×⁵⌕αι
```
The compressed string is @ovs's large integer constant, converted to binary and reversed. It is then sliced into 180 substrings of 5 characters, and the relevant substring for the current character and row is then looped over.
```
⎇Iμ§θ⊖L⊞Oυω
```
If the bit was set then cyclically print the next character of the filtered input otherwise print a space.
```
M⁷±⁵
```
Position the cursor ready to print the next character.
[Answer]
## [Perl 5](https://www.perl.org/) with `-nlaF/[^A-Za-z0-9]+|/`, 247 bytes
```
@l{0..9,A..Z}=unpack("b*",q&....!.?.......G...../.......\....c|...C......'..N.>..c.1~B......I1..~.5.8k....^|!...}.......BH.1..."1..."*FE.....&)=~/.{25}/g;eval'$;[$j%5].=($l{+uc}=~/.{5}/g)[$j++%5]=~s/./$&?uc$F[$i++%@F]:$"/ger.$"x2;'x5for@F;say for@
```
[Try it online!](https://tio.run/##LU/tUsIwEHwV7FQKlKZJP6S1gwKOVX/oA0BgpqQtg3T4FCcK7aNb7wg/NnPZ29u73Wb7wq/rQXGihITdISHjsn9cbxOxamnzjtbd7ZqEy7THZRZySbMbKLxHeAIuhcNlL@cypFC7AFCl3otqBvChgBAENLe5nCdYcMkYgigClJzL3AOAyRxW5IE4wwsi4UO/9wRTYJdnimBQpxdLA0gBRP6Bige8C/0E0qwagRzHQBp46kRcnLpvTDGMVvBFS3EXrIDLCJZoMTtDyhAX4aRTqnMS/xrMVcgwizt6hZ9gKg0eF/oa7gEjlsKQq3Xi52sESBcECjRvtvuVTU6OX9qLKPtOCkOPJvrnrT8l/ZZenMyjKC8KFLShY5rQ61cHm9h68/Eo9HiiL4EcxNN7XbMX2Z7omnQiQ/r5Zj@Io0Py08CqrhO3MTKcv832a7lZH2prXSSxPZkNrXFi/VIrnJpnu7befUIZ/Qc "Perl 5 – Try It Online")
---
## Explanation
First a lookup table is created in `%l` using the `pack`ed data. This data is a 900-bit binary string of each char packed as a 25-bit binary string (stored as 113 bytes - only 1 more byte than charcoal!), similar to some other answers, so `A` is:
```
AAA
A A
AAAAA
A A
A A
```
which, using `0` for space and `1` for `A` is:
```
01110
10001
11111
10001
10001
```
and without the line breaks is:
```
0111010001111111000110001
```
Once the lookup is initialised, we iterate over each valid char in `@F` (which is populated using Perl's `-a`utosplit option) appending to each of the 5 elements of the list `@;` for each row in the array from the lookup, replacing all `1`s with `uc$F[$i++%@F]` which is the `$i`th character (modulo `@F` which is the length of `@F`) converted to `u`pper`c`ase, and all `0`s with `$"` which defaults to space. Once each index in `@;` is populated for each character in `@F`, `say` prints each line with a trailing newline.
**Note**: the string after `unpack` contains unprintables which are escaped using `\xXX` notation. [Verification for score of 247](https://tio.run/##dZPbUtxGEIbveYofeQ2YtUZzPnhZe21XNslF8gAmUCXNwSbeAsIhIebw6qRnVzZJKpkL1Wik/vrvv3uG/vLT4@PNTUJ7AXZyen59xa5OzvAaLJ6lXPfsfDXb@iOijf86y/HT2Wwr9lf/eb55nueLFdrTVb9susPjt@2Hvv3C23A0vesatD8ZxgX/RzgODg7Q8PlcdJ3c31dtq6dTs71tFwv37Jnf2wvHx83s8ZGP6xU0txFuUBwyywwVZIQWtJPZ9HBJJThjM7BY3XLGwsu3jH24n1@fbm0IghiOWwGr7ADppYSVsoeUBHJCWgIlhxw4Mc77@HmvGfabl7/tMFojQxJDiqyhSvaI0hUEHhWiSxra0Zl33CEUXoBt9oZt1vfsbwxVGWXowYsQELWCoadIE4tG4UNA8VbBxSKAbiT8Uh/x7itDEyOa7KAV9yg5GgifCiGlQ4miQGf6oDJJBWPvN5Bdxn5mr78yDDFyzVSiEnBZS0RfCrwOnGQlBR3og9fUOWodEw/vNpgfxbdabPU0pwhlooXyZKyvzYm2FpRdJLeCR9JBAg/MMP@5Eo7vtp/8cJWRqNjeVP@UV8hFUHap6bVqG3rhEQw1DPejH@9@YKSCNSPDE0OJZCFSr2pHe2irDbgvAZ5WdYYaHGhIsA7cX363Bu28mI@MsK5FFhoDN0BJZUgWvVqnBljjLKygCZROkqcPHbuV5r77OMu/96vdycjoq47B0HhpS5NliGFSHdYkfT2rAyyHOqcKmB1Ofn1ujth8b7K6nV7HkTGs/ajT/CTGuEQzYx1V8A1eQbifVyVVyAuiTacjI9YZ22RfgxyZUupVKSReWlU2EqTWFiAN84fLjnWTnTfXcbIcGYkYZqD/baBMlM7QFaT/CUnZNXVjrYicob4cTk6m0@eL5dGrSdN9zBcjI1cdueaUzldPCeTqzliys1DkGqkGEgg2aW7kbPfGlLOLxXJ2OTIKMaxwAZI/BeF/Vv8navRf).
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~165~~ ~~164~~ 163 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
⁰CīøDs8↓3‛⁸⁷ω8<t↑\≈⅓dPb¦l═│ƹč<⁷i3ζ°@Ο≠ΖηKπ⁴Φd←⅔Ωī$∞ΧΗf▼xƧqWƨ∑ģpc!ƨ@┐Γ<§5ΛMn«Ιq;⁾№╔1xdψBN≤⁴ζ8□\b╗³╤>↔²Μ±}H}≤╬bφIæ7“2─{rƧ- W}⁰∑M¼nEU{SUZ+;W:?ew;cF+C}X}⁰┌cŗā;{√┼@L*┼
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMDcwQyV1MDEyQiVGOERzOCV1MjE5MzMldTIwMUIldTIwNzgldTIwNzcldTAzQzk4JTNDdCV1MjE5MSU1QyV1MjI0OCV1MjE1M2RQYiVBNmwldTI1NTAldTI1MDIlQzYlQjkldTAxMEQlM0MldTIwNzdpMyV1MDNCNiVCMEAldTAzOUYldTIyNjAldTAzOTYldTAzQjdLJXUwM0MwJXUyMDc0JXUwM0E2ZCV1MjE5MCV1MjE1NCV1MDNBOSV1MDEyQiUyNCV1MjIxRSV1MDNBNyV1MDM5N2YldTI1QkN4JXUwMUE3cVcldTAxQTgldTIyMTEldTAxMjNwYyUyMSV1MDFBOEAldTI1MTAldTAzOTMlM0MlQTc1JXUwMzlCTW4lQUIldTAzOTlxJTNCJXUyMDdFJXUyMTE2JXUyNTU0MXhkJXUwM0M4Qk4ldTIyNjQldTIwNzQldTAzQjY4JXUyNUExJTVDYiV1MjU1NyVCMyV1MjU2NCUzRSV1MjE5NCVCMiV1MDM5QyVCMSU3REglN0QldTIyNjQldTI1NkNiJXUwM0M2SSVFNjcldTIwMUMyJXUyNTAwJTdCciV1MDFBNy0lMjBXJTdEJXUyMDcwJXUyMjExTSVCQ25FVSU3QlNVWislM0JXJTNBJTNGZXclM0JjRitDJTdEWCU3RCV1MjA3MCV1MjUwQ2MldTAxNTcldTAxMDElM0IlN0IldTIyMUEldTI1M0NATColdTI1M0M_,inputs=YSUyQ2IlMjBjJTIxZCUyMyUyNXh5ejEyJTIxJTIx,v=0.12)
Explanation:
```
...“ big long number of the character data
2─ convert to a base 2 string
{r } for each number in it
Ƨ- W get it's index in "- ": space for 0, dash for 1
⁰∑ join up the results
M¼n split into groups of 25 - the letters
E save that in variable E
U{ }⁰ map over the input uppercased
SUZ+ push 1234567890 + the alphabet
;W get the current characters index in that string
:? } duplicate, if not 0 (aka if found)
e push the variable E
w get in it the duplicated number'th item
this leavesleaving the array below the item
; get the array ontop
cF+C append the character to the array C
X and remove the top item - either the duplicate or the array
┌ push "-"
c load the variable C
ŗ cycically replace "-" in maps result with the characters of C
ā push an empty array - the output
;{ for each item in the result of the replacement
√ squareify it
┼ and append that to the output array
@L*┼ top-to-bottom, left-to-right add 10 spaces to the array
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~365~~ 347 bytes
*Saved 1 byte thanks to @Scoots*
Returns an array of 5 strings. Includes a leading space on each row.
~~37~~ 36 bytes are lost in converting everything to uppercase and matching `[A-Z0-9]` :-/
```
a=>(a=a.toUpperCase(s=[...' ']).match(/[A-Z\d]/g)).map(x=c=>(g=n=>n<35&&g(n+1,s[n<25?n/5|0:n%5]+=Buffer("mJ*Z?<^#?.&+o@V+`L7ho=Jkm?`:Tm)Km?ZZo@p*#MmjoCZ[=('ZoC#;?-g[RZW[>.cJ#Mmm?<^;Vp5[#p*]?,iM#KAm$$:Mm?0*R[#;-46B#qC;o==*X$(km?0-XDc=$.Mm#%]=X$*-?1M[".slice(parseInt(c,36)*(i=v=4))).map(c=>v+=c%80*80**--i)|v>>n&n<25?a[++x]||a[x=0]:' '))(0))&&s
```
[Try it online!](https://tio.run/##jY9bc9owEEbf@ysYbGxJxsJcTFJAVsDpJRD3QhNCrbgTjWIcUyS5mDI88N@pk@lL@5SdnX3YPfvNnDXf81Js82LnKv2YnlbkxEkAOOF4p2@LIt2GvExBSRjG2K49l51ALPlOPIEWG7vx/WPSyuDzqgAHIqrnjCgSqFHXt6wMKKfdLJkadXyqWv7RG6iGnzhk8nu1SregLqcopqMfBsWWoy8WzsP12ZMm05@SPgxuJJxJGsf6okBGJNc6jBkBdqxDY0jdjM3jOxZgMa1ussoYLgqfGQVKaDOPjNlYmuYgktRDc2YM3V5/YvwKh5oQtDRBle@5y0tBTBxJo5GQpYlc2o5YHZebXKSg4NsyvVI7IJrdPkQgJ3vSg381K8m9Q0Tj3ENVI9fN4XEfBMp60eTMcQ7J8cjZgXjJwK7ZEAIPQssqT0KrUm9SvNEZWIG61@50e37/7PxtHeK1zhWw75UNnZf55j@Yd2sTu/MKcDwJL9@9//Dxajq7jl7Bf/r85ev8283t4m75Pf6Hh6c/ "JavaScript (Node.js) – Try It Online")
### Character encoding
Characters are encoded upside-down and converted to a custom base-80 with an offset of **4**, using the ASCII range **[35..114]**.
Values **35** to **79** are directly mapped to the corresponding ASCII character, while values **0** to **34** are mapped to
characters **80** to **114**. This allows to decode by just taking the ASCII code **modulo 80**.
For instance, **'F'** is encoded as `"RZW["`:
```
....# 00001
....# 00001
..### --> 00111 --> 0000100001001110000111111 --[decimal]--> 1088575 --[-4]--> 1088571
....# 00001
##### 11111
floor(1088571 / 80**3) = 2 --> (( 2 + 45) mod 80) + 35 = 82 --> 'R'
floor(1088571 / 80**2) mod 80 = 10 --> ((10 + 45) mod 80) + 35 = 90 --> 'Z'
floor(1088571 / 80) mod 80 = 7 --> (( 7 + 45) mod 80) + 35 = 87 --> 'W'
1088571 mod 80 = 11 --> ((11 + 45) mod 80) + 35 = 91 --> '['
```
Starting with **i = v = 4**, it is decoded back to a 25-bit integer by doing:
```
Buffer("RZW[").map(c => v += c % 80 * 80 ** --i)
```
In the full code, we actually process an unbounded **slice()** of the encoded stream, which means that we are likely to iterate significantly more than **4** times. This is not a problem because all iterations with **i < 0** will only affect the decimal part of the result, which is ignored anyway by the bitwise operations that immediately follow.
[Try it online!](https://tio.run/##HYxBCsIwFET3PcVHkPxUm5SiIEhdeAS7ENRNSNOYUpOQxl4/pg7MzGIeM4pFzDIYHyvrepWSgRaW7MO5ELmu32FQATe3x/25oewjPEpoLxnZtSBhC6cayn@UUFWGFoV0dnaTYpPTuLDouhiM1dhQ5kXfRREiNsc9kJqsd1G@kbNVXFM2OmORvGyegvKTkAp5zXWmGaE0pR8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 792 690 bytes
```
#define S strlen
#define V v[1][i]
#define A putchar(32);
#define F(x)(((G(x,0)*92+G(x,1))*92+G(x,2))*92+G(x,3))*92+G(x,4))
#define G(x,y)(f[(x-(x<58?48:55))*5+y]-35)
i,j,l;main(c,v)char**v;{l=S(v[c=1]);char*x[l],t[l+1],*p=t,*f="$dKqK&>%Q3&R`ms&RYXg#gAB/&b_R/$n>Pw&]?vO$cbu+$ccG#$csC+&X7sS$n0w[&X+={&b^%s&b^$W$n3qS%(4\\_&^Bjg&^Bj/%(Pec$xx%S%+L`/%*jjw$cel7&X7oS$NWLO&X7u3$n.U+&^BhG%(')k%'|*/%(+:'%%UO;%%U=K&]`{+";*x=t;for(;i<l;i++){V>96?V-=32:V;(V>47)&(V<58)|(V>64)&(V<91)?*(p++)=V:V;}*p=0;for(;c<S(t);)x[c++]=((__builtin_popcount(F(t[c-1])+x[c-1]-t)%S(t))+t;for(c=6;--c;){for(i=0;i<S(t);i++){for(j=5,l=1<<c*5+3;j--;)if((l>>=1)&F(t[i]){putchar(*x[i]++);!*x[i]?x[i]=t:x;}else A A A}puts(p);}}
```
[Try it online!](https://tio.run/##RVLvb6JAEP3ev8JTwFkWThHw17qaekn9YHP2JKVeKNW6VbseRSqoNNa/3Vs0tdlk9s3LvLeTmWX6grHjsfAym/NwlnNycbIOZuHVF@Hmtp7he9y/MNe5aJOw1@c1mBVELvQNpAgAepBqZaQ2KjhDBrrAyjc0v6GF0MUhyz8QzD1IdUhbdr1j1Zu2LYpt/OHrpo2uuLbUAvL2zENg2hZlXajqluwD6sDWY9TwETmRqRf4WuIF2PA1NaKJps5pXnrpv/eVtvzHVIaTt1gZ/h0tCovrbkmZjoclKWzf7RS/sx1IbLrBEmO9gsTiX1gZ1WJHCss7TxlhulemT3IsgvQghea7I4P1@DhWnrrLRRZKMtzNmJSmsiPj20lJVpfLncRmQU3YrBzp98PtQKCNKYU/77FQvPZkKKJ/cvFTFVrcLMry/YCIQPuKP9njPFFTmpD5ag2EtwLCMUZ7t92odlydmpWmS8BtWzWkgCtGhj5FVrVOWcNAHRUiUU9dUXYQcyiffVjLgQQRlHoMY58CjMfTDQ8SHo6jVcRWmzCBG0g8pouB4vR06wmSMxXC52YYrRJdZwTts4wLa352PTWYcUtqawE1Wi0mFmiSpa4TxOcAQbtNDaRkD3Af7b9@k9gZ94WW/DihThZo0kzJYRbE2bcT5yCKY4gQORyOx2O@bFRMy67W6o3cs5nrFiv5/w "C (gcc) – Try It Online")
Managed to squeeze this under 800 with some variable reuse. Opted to store the font as an array of `int`s, as although storing it as one long string looked like an attractive idea so many of the 8-bit chunks of the font weren't a nice convenient ASCII character that the escape codes were taking up more characters than the `int` array did.
Edit: Got under 700 by switching to a string encoding after all - somewhat inspired by many of the other responses here I cobbled together a base-92 representation using (most of) the printable ASCII characters. The representation does include backslashes which need an extra to be escaped but that only happens once in the font.
Other than that there isn't much that's too flashy going on - the input (consisting of the first command-line argument) is copied into a stack array, minus any characters that aren't in the font and with lowercase letters replaced with their uppercase versions, what "pixel" character each full letter starts on is computed (using `__builtin_popcount` has a painfully long name but was still better than any method of counting on bits I could think of), and then the printing goes through line by line. The compiler of course outputs several times the program length in warnings.
Somewhat degolfed below for your viewing pleasure:
```
//The defines are listed here for reference. Some are replaced in the below code but I still use F() because it's long.
#define S strlen
#define V v[1][i]
#define A putchar(32);
#define F(x)(((G(x,0)*92+G(x,1))*92+G(x,2))*92+G(x,3))*92+G(x,4)) //How to lookup a font character given an input char x
#define G(x,y)(f[(x-(x<58?48:55))*5+y]-35) //Used for looking up the individual parts of a character font
i, j, l; // Declaring some int variables for later use.
main(c,v) char**v; { // Declaring afterwards lets us have the int arg default without declaring it
l = strlen(v[c=1]); // Using l as a local variable to shorten S(v[1]) and also giving c an initial value here where there was a spare 1, saving a character over writing the full c=1 init in a later for loop.
char t[l+1], *p=t, *x[l]; // Declaring char arrays and char*s and char* arrays. t is oversized if there are any invalid characters in the input, but that's not important for golfing.
char *f="$dKqK&>%Q3&R`ms&RYXg#gAB/&b_R/$n>Pw&]?vO$cbu+$ccG#$csC+&X7sS$n0w[&X+={&b^%s&b^$W$n3qS%(4\\_&^Bjg&^Bj/%(Pec$xx%S%+L`/%*jjw$cel7&X7oS$NWLO&X7u3$n.U+&^BhG%(')k%'|*/%(+:'%%UO;%%U=K&]`{+"; // The font, encoded base-92 with 5 characters to a letter in the order 0123456789ABCDEF... etc.
*x=t; // The first character's "pixels" will start at the beginning of the valid input.
for(; i<strlen(l); i++){ // Speaking of which, now validate the input.
v[1][i] > 96 ? v[1][i] -= 32 : v[1][i]; // Change lowercase characters to uppercase. If they aren't actually lowercase characters but have ascii value >96, they won't end up valid after this either and will be edited out on the next line. The false case does nothing, but since with the macro it is one character using the ternary operator saves a character over an if statement even though that case ends up redundant.
(v[1][i]>47)&(v[1][i]<58)|(v[1][i]>64)&(v[1][i]<91)?*(p++)=v[1][i]:v[1][i]; // If the character is now either a numeral or an uppercase letter, set the next spot in the t array by way of the pointer p and then increment said pointer.
}
*p=0; // Add the null terminator to the t array, our validated input string.
for(;c<strlen(t);) { // Now find out at what index each letter should start getting "pixels" from.
x[c++] = ((__builtin_popcount(F(t[c-1])+x[c-1]-t)%strlen(t))+t; // Use the builtin to get the number of on bits/pixels in the previous letter, then add that to the previous letter's starting pixel and take the modulus strlen() of the valid string.
}
for(c=6; --c;){ // Now start the actual printing. For each line...
for(i=0; i<strlen(t); i++){ // For each letter...
for(j=5, l=1<<c*5+3; j--;) { // For each pixel of the 5 on this line...
if((l>>=1) & F(t[i]) { // If it is on...
putchar(*x[i]++); // Print it and increment the pixel-fetching pointer for this letter.
!*x[i]?x[i]=t:x; // If said pointer hit the end of the valid input go back to the beginning.
} else {
putchar(32); // If it is an off pixel, print a space.
}
}
putchar(32); // After a letter, print two spaces.
putchar(32);
}
puts(p); // This is the cheapest way in character count I could come up with to output a newline. p currently points to the end of t, so it is an empty string and puts just adds a newline.
}
}
```
[Answer]
# Excel VBA, 816 bytes
An anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the console.
As far as I am aware, this is the first VBA answer to use `base64` compression.
```
For i=1To[Len(A1)]:c=Mid(UCase([A1]),i,1):y=y &IIf(c Like"[0-9A-Z]",c,""):Next:l=Len(y):Set d=New MSXML2.DOMDocument:Set d=d.createElement("b64"):d.DataType="bin.base64":d.Text="HxHxCSEqRkVUjLvGSJSK0cUYIyGEfB8cfFH66Ju0kkHoo3cxRhdnzTHGuuOHEMIouYyYEPI/IeTH+GN8ccIHIYf/Qw6/jzH6ByF8PvroY/zR+fCic9FFh4gI30UPnw8efiG+Mj6c4D90wX9CCHe5Tgc=":b=d.nodeTypedValue:For i=0To 112:k=Right("00000" &Evaluate("=Dec2Bin("&b(i)&")"),8)&k:Next:For i=1To 5:For j=1To l:c=UCase(Mid(y,j,1)):Z=c Like"[0-9]":s=s &IIf(c Like"[A-Z]",Mid(k,IIf(Z,1,25*(Asc(c)-55)+5*i),5)&" ",IIf(Z,Mid(k,25*(Asc(c)-48)+5*i,5)&" ","")):Next:s=Replace(Replace(s,0," "),1,"#") &vbLf:Next:Do:i=InStr(1+(g*l+h)*6+g,s,"#"):p=(p-e)Mod l:e=i<(g*l+h+1)*6+g:s=IIf(e,Left(s,i-1)&Replace(s,"#",Mid(y,p+1,1),i,1),s):g=g-(0=e):h=h-(g>4):g=g Mod 5:Loop While InStr(1,s,"#"):?s
```
*Note: This answer depends on the `Microsoft XML, v3.0` VBA reference*
### Example I/O
```
[A1]="'0123456789"
For i=1To[Len(A1)]:c=Mid(UCase([A1]),i,1):y=y &IIf(c Like"[0-9A-Z]",c,""):Next:l=Len(y):Set d=New MSXML2.DOMDocument:Set d=d.createElement("b64"):d.DataType="bin.base64":d.Text="HxHxCSEqRkVUjLvGSJSK0cUYIyGEfB8cfFH66Ju0kkHoo3cxRhdnzTHGuuOHEMIouYyYEPI/IeTH+GN8ccIHIYf/Qw6/jzH6ByF8PvroY/zR+fCic9FFh4gI30UPnw8efiG+Mj6c4D90wX9CCHe5Tgc=":b=d.nodeTypedValue:For i=0To 112:k=Right("00000" &Evaluate("=Dec2Bin("&b(i)&")"),8)&k:Next:For i=1To 5:For j=1To l:c=UCase(Mid(y,j,1)):Z=c Like"[0-9]":s=s &IIf(c Like"[A-Z]",Mid(k,IIf(Z,1,25*(Asc(c)-55)+5*i),5)&" ",IIf(Z,Mid(k,25*(Asc(c)-48)+5*i,5)&" ","")):Next:s=Replace(Replace(s,0," "),1,"#") &vbLf:Next:Do:i=InStr(1+(g*l+h)*6+g,s,"#"):p=(p-e)Mod l:e=i<(g*l+h+1)*6+g:s=IIf(e,Left(s,i-1)&Replace(s,"#",Mid(y,p+1,1),i,1),s):g=g-(0=e):h=h-(g>4):g=g Mod 5:Loop While i<InStrRev(s,"#"):?s
012 567 6789 0123 34 45678 9012 34567 234 567
3 45 8 0 4 5 6 9 3 8 5 6 8 9
6 7 8 9 123 567 78901 0123 4567 9 789 0123
90 1 0 4 8 2 4 8 9 0 0 1 4
234 12345 56789 9012 3 5678 012 1 234 5678
```
### Ungolfed and Explained
The major part of this solution storing the large font as a base 64 string. This is done by first converting the font to binary, where `1` represents an on pixel and `0` represents an off pixel. For example, for `0`, this is represented as
```
### 01110
# ## 10011
0 -> # # # -> 10101 --> 0111010011101011100101110
## # 11001
### 01110
```
With this approach, the alphanumerics can then be represented as
```
0: 0111010011101011100101110 1: 1110000100001000010011111
2: 1111000001011101000011111 3: 1111000001001110000111110
4: 0011001010111110001000010 5: 1111110000111100000111110
6: 0111110000111101000101110 7: 1111100001000100010001000
8: 0111010001011101000101110 9: 0111010001011110000111110
A: 0111010001111111000110001 B: 1111010001111101000111110
C: 0111110000100001000001111 D: 1111010001100011000111110
E: 1111110000111001000011111 F: 1111110000111001000010000
G: 0111110000100111000101111 H: 1000110001111111000110001
I: 1111100100001000010011111 J: 1111100100001000010011000
K: 1000110010111001001010001 L: 1000010000100001000011111
M: 1000111011101011000110001 N: 1000111001101011001110001
O: 0111010001100011000101110 P: 1111010001111101000010000
Q: 0110010010101101001001101 R: 1111010001111101001010001
S: 0111110000011100000111110 T: 1111100100001000010000100
U: 1000110001100011000101110 V: 1000110001010100101000100
W: 1000110001101011101110001 X: 1000101010001000101010001
Y: 1000101010001000010000100 Z: 1111100010001000100011111
```
These segments were concatenated and converted to MSXML base 64, rendering
```
HxHxCSEqRkVUjLvGSJSK0cUYIyGEfB8cfFH66Ju0kkHoo3cxRhdnzTHGuuOHEMIouYyYEPI/IeTH+GN8ccIHIYf/Qw6/jzH6ByF8PvroY/zR+fCic9FFh4gI30UPnw8efiG+Mj6c4D90wX9CCHe5Tgc=
```
The subroutine below takes this, back converts to binary, and uses this a reference from which to build an output string, line by line, grabbing first the top 5 pixels of each character, then the second row and so on until the string is constructed.
The subroutine then iterates over the output string and replaces the 'on' pixels with characters from the input string.
```
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Embiggen Function
''
'' @Title : Embiggen
'' @Author : Taylor Scott
'' @Date : 15 June 2018
'' @Desc : Function that takes input, value, and outputs a string in which
'' value has been filtered to alphnumerics only, each char is then
'' scaled up to a 5x5 ASCII art, and each 'pixel' is replaced with
'' a char from value. Replacement occurs letter by letter, line by
'' line
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function EMBIGGEN(ByVal value As String) As String
Dim DOM As New MSXML2.DOMDocument, _
bytes() As Byte
Dim isNum As Boolean, _
found As Boolean, _
index As Integer, _
length As Integer, _
line As Integer, _
letter As Integer, _
pos As Integer, _
alphanum As String, _
char As String, _
filValue As String, _
outValue As String
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Filter input
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
For letter = 1 To Len(value) Step 1 '' Iterate Accross `Value`
Let char = Mid$(UCase(value), letter, 1) '' Take the nth char
'' If the char is alphnumeric, append it to a filtered input string
Let filValue = filValue & IIf(char Like "[0-9A-Z]", char, "")
Next letter
Let length = Len(filValue) '' store length of filValue
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Convert Constant from Base 64 to Byte Array
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
With DOM.createElement("b64") '' Construct b64 DOM object
Let .DataType = "bin.base64" '' define type of object`
'' Input constructed constant string shown above
Let .Text = "HxHxCSEqRkVUjLvGSJSK0cUYIyGEfB8cfFH66Ju0kkHoo3cxRhdnz" & _
"THGuuOHEMIouYyYEPI/IeTH+GN8ccIHIYf/Qw6/jzH6ByF8PvroY/" & _
"zR+fCic9FFh4gI30UPnw8efiG+Mj6c4D90wX9CCHe5Tgc="
Let bytes = .nodeTypedValue '' Pass resulting bytes to array
End With
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Convert Byte Array to Byte String
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
For index = 0 To 112 Step 1
'' convert each byte to binary, fill left with `0`s and prepend
Let alphanum = _
Right("00000" & Evaluate("=Dec2Bin(" & bytes(index) & ")"), 8) & _
alphanum
Next index
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Construct Embiggened Binary String of Input Value
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
For line = 1 To 5 Step 1 '' iterate across lines
For letter = 1 To length Step 1 '' iterate across letters
'' take the corresponding letter from
Let char = UCase(Mid(filValue, letter, 1))
If char Like "[0-9]" Then '' if it is a number,
'' Add the 5 bit corresponding to number at line
Let outValue = outValue & _
Mid$(alphanum, 25 * Val(char) + 5 * line, 5) & " "
ElseIf char Like "[A-Z]" Then '' if it is a letter,
'' Add the 5 bits corresponding to letter at line
Let outValue = outValue & _
Mid$(alphanum, 25 * (Asc(char) - 55) + 5 * line, 5) & " "
End If
Next letter
Let outValue = outValue & IIf(line < 5, vbLf, "")
Next line
Let outValue = Replace(Replace(outValue, 0, " "), 1, "#")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Replace #s with Input Value
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Let pos = 0 '' Reset position in filValue
Let line = 0 '' Reset line index
Let letter = 0 '' Reset letter index
Do
'' Find the index of the first `#` starting at line and letter
Let index = _
InStr(1 + (line * length + letter) * 6 + line, outValue, "#")
'' Iterate position in filValue if a `#` is found in that letter & line
Let pos = (pos - found) Mod length
'' check to see if found index is in the correct letter
Let found = index < (line * length + letter + 1) * 6 + line
'' iff so, replace that # with letter in filValue corresponding to pos
Let outValue = IIf(found, _
Left(outValue, index - 1) & _
Replace(outValue, "#", Mid(filValue, pos + 1, 1), index, 1), _
outValue)
'' if not found, them iterate line
Let line = line - (found = False)
'' iterate letter every five iterations of line
Let letter = letter - (line > 4)
'' Ensure that line between 0 and 4 (inc)
Let line = line Mod 5
'' Loop while there are '#'s in outValue
Loop While InStr(1, outValue, "#")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Output
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Let EMBIGGEN = outValue
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
'' Clean Up
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Set DOM = Nothoing
End Function
```
]
|
[Question]
[
Given a prime `P` greater than `10`, your program or function must figure out its divisibility rule `x`, defined as the integer with smallest absolute value which yields a multiple of the original prime when multiplied by the last digit of the prime and added to the rest of the original prime.
## Example
Given an input `31`, the last digit is `1` and the rest of the number is `3`. Thus your program must find the integer `x` with minimum absolute value such that `1*x + 3` is a multiple of `31`. In this case, `x=-3` works, so the program or function would return `-3`.
Given an input `1000003`, the last digit is `3` and the rest of the number is `100000`. Thus your program would find `x=300001` because `3*300001+100000 = 1000003` which is a multiple of `1000003`.
## Mathematical Background
The value of `x` can be used as a divisibility test. If a number `N` is divisible by `P`, then adding `x` times the last digit of `N` to the rest of `N` will yield a multiple of `P` if and only if `N` is divisible by `P` in the first place.
For `P=11`, we get `x=-1`, which is equivalent to the well-known divisibility rule for `11`: a number is divisible by `11` alternating difference of its digits is divisible by `11`.
## Rules
* The output may be in any form that clearly encodes both the sign and value of the output.
* The input prime will be between 10 and 2^30.
* You do not need to handle if the input is not a prime or is not in the range.
* You do not need to handle if both `x` and `-x` are valid outputs (should not happen).
* Brute force is permitted, but more creative solutions are appreciated.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code **in each language** wins! Do not let answers in golfing languages discourage you from posting in other languages.
## Test Cases
```
Input Output
11 -1
13 4
17 -5
19 2
23 7
29 3
31 -3
37 -11
41 -4
43 13
47 -14
53 16
59 6
61 -6
67 -20
71 -7
73 22
79 8
83 25
89 9
97 -29
101 -10
103 31
107 -32
109 11
113 34
127 -38
131 -13
1000003 300001
2000003 600001
2999999 300000
9999991 -999999
```
[Answer]
## JavaScript (ES6), ~~32~~ ~~25~~ 23 bytes
```
f=
n=>(3/(n%5*2-5)*n+1)/10
```
```
<input type=number min=1 oninput=o.textContent=this.value%5*(this.value%2)?f(this.value):``><pre id=o>
```
`3/(n%5*2-5)` would be written `9/n(mod -10)` if I had access to balanced modulo division. Edit: Saved 2 bytes thanks to @EgorSkriptunoff
[Answer]
# [Python 2](https://docs.python.org/2/), 27 bytes
```
lambda n:(n%5*2-5^2)*n/10+1
```
[Try it online!](https://tio.run/##LY7BboMwEETP2a/YSyWSkNa7tjGOxJ9UrUBtFCTiokAV9evpGOLL7JsZ2zv@zdefpMuleV@G9tZ9tZzORXrxBz35D90f0puYoyyPaz98s5xpNzX39vHZp/F3Lva0S2XX3Nqx6NNcTq/TOPSw4Y93ONw1zaVI@5JTydvQLSLMJyGxzI4kADxJZFZSWIEUsyWbW5Cci5DL6MihIZbc6jryGSvyuFFRlSuQnKmhkDFQQEWVAio11Rk81YBIcS1GEiN4zEAtW@xlAj5WaGR8LNjTYk/Nbo2tc9kizQdRFiF9YvXEuJ4tNbQRLm7DPw "Python 2 – Try It Online")
The operations are done left to right: `(((n%5)*2)-5)^2`.
I used my arithmetic brute forcer to find the expression `n%5*2-5^2` to perform `{1:-1,3:3,2:-3,4:1}[k]`, taking the negative inverse of a residue mod 5 into the range `[-2..2]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes
```
,N⁵æiAÞḢ
```
[Try it online!](https://tio.run/##y0rNyan8/1/H71Hj1sPLMh0Pz3u4Y9H///8NDUDAGAA "Jelly – Try It Online")
### Explanations
```
,N Get [Input, -Input].
⁵æi Modular inverse of 10 mod each of [Input, -Input].
AÞ Sort by absolute value.
Ḣ First.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
∧.ℤ≜×₁₀-₁;?%0∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HHcr1HLUsedc45PP1RU@OjpgZdIGVtr2oAlPn/39DI/H8UAA "Brachylog – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 69 54 53 bytes
**Edit:** -15 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
**Edit:** -1 byte by using recursion
```
f=lambda a,x=-1:(a%10*x+a/10)%a and f(a,-x-(x>0))or x
```
[Try it online!](https://tio.run/##HY/BDoMgEETP7VfsxURbTEFRxMT@SNMDjTEladEYD/Tr6SwHdnbfkFnYfsd7DU1Ky/Rx39fsyIk41WosXaHkJV7dTcmqAA4zLaUTdazLeJdVte4U04LqyQd6KCVItTgGxwpq0DfQFrwF01ANptF30A5eD9ZjNlADZsAG6AC1nCM5VHKqzCO4yksaHtu8MndsaC4ds45Zz/c4XZn8LHYHdm0uzPIOa5/j@bTtPhzkBf7oq/QH)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~31 29~~ 27 bytes
```
lambda n:3/(n%5*2-5)*n/10+1
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPylhfI0/VVMtI11RTK0/f0EDb8H9BUWZeiUKahqGhpg6QNAaT5mDSEkQaGWv@BwA "Python 2 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ 9 bytes
*Saved way too many bytes thanks to an observation by @xnor*
```
_*AÉ vU}c
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=XypBySB2VX1j&input=MTAwMDAwMw==) May take a couple of seconds on larger inputs.
### Explanation
```
_ *AÉ vU}c Implicit: U = input integer
Z{Z*A-1 vU}c Ungolfed
Z{ }c Loop through each integer Z in [0, -1, 1, -2, ...] and yield the first where
Z*A Z times 10
-1 minus 1
vU is divisible by the input.
Implicit: output result of last expression
```
[Answer]
# Java 8, ~~23~~ 21 bytes
```
n->3/(n%5*2-5)*++n/10
```
Port of [*@Neil*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/139698/52210), but -2 bytes thanks to *@Nevay* due to implicit flooring of integers.
[Try it here.](https://tio.run/##jVLBjoIwFLz7Fe9iUjQgUBGJ2f2D9eLReKgFTRUfRKrJxvDtWNCrGV/aJn2dzkybOam78qu64FN@7nSpmob@lOHHiMiwLa4HpQta99uhQVr0K3sr12nddKOxyhpNa2L6oY79XzkTPE4msZ94k@mUZ1HYrV7Q@rYvHfR9416ZnC5OTWzs1fBxuyPlvaQ2/40tLkF1s0HtjmzJggMtosgblD8DJAKkCJABQIwkYsQg0SskMjlHDHPEkCCTCySxQBIpYkjRT6bI5BIxLBFDBvMQwsyFMHQhshHh4MbQqcRO@4L5/Q6VDYW@d6i3r3bUdk8)
[Answer]
# Excel, 25 bytes
```
=.3/(MOD(A1,5)*2-5)*A1+.1
```
(Excel corrects to:
```
=0.3/(MOD(A1,5)*2-5)*A1+0.1
```
)
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 12 bytes
```
3Q5%}5-f*hTf
```
[Try it here!](http://pyke.catbus.co.uk/?code=3Q5%25%7D5-f%2ahTf&input=17&warnings=0)
[Answer]
# [Pyth](https://pyth.readthedocs.io), 14 bytes
```
h/*x-y%QK5K2QT
```
**[Try it here.](http://pyth.herokuapp.com/?code=h%2F%2ax-y%25QK5K2QT&test_suite=1&test_suite_input=11%0A13%0A17&debug=0)**
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 10 bytes
```
~IIT*tR%)h
```
[Try it here!](http://pyke.catbus.co.uk/?code=%7EIIT%2atR%25%29h&input=11&warnings=0)
```
~I - Integers
I ) - filter(^, not v)
T*t - ^ *10 -1
R% - input % ^
h - ^[0]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~44~~ 43 bytes
*(Crossed out 44 is still 44.)* Thanks to Fireflame241 for saving a byte!
```
P=input();i=P/3
while i*10%P-1:i-=1
print i
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8A2M6@gtERD0zrTNkDfmKs8IzMnVSFTy9BANUDX0CpT19aQq6AoM69EIfP/f0swMAQA "Python 2 – Try It Online")
There is exactly one number between `0` and `P-1` which is an inverse of `10`. But if that inverse `u` happens to be greater than `P/2`, then `(u-P)` is also an inverse, and has a smaller absolute value than `u`. So it turns out that we're really looking for the unique number `x` between `-P/2` and `P/2` which is an inverse of `10`.
The code above does exactly that, starting at (the floor of) `P/2`, and stepping
downward until an inverse is reached. This must happen for some number greater than `-P/2` so long as `P` is a prime greater than `10`. More precisely, it will terminate if and only if `P` is coprime to `10`.
**Edit:** It actually turns out that `x` is guaranteed to be between `-P/3` and `P/3`, so the current version starts at `P/3` and steps down from there. See the section labeled **Improved Bound** for an explanation of this.
### Mathematical explanation
It was not immediately obvious to me why the divisibility test worked. Here's an explanation, in case anyone else was wondering.
Let `P` be a prime, greater than `10`, whose last digit is `b`. Thus
`P = 10a + b`
where `a > 0`, and `0 <= b < 10`. In fact `b` is either `1`, `3`, `7`, or `9`, because a prime greater than `10` must end in one of these digits.
Now suppose `bx + a = 0 (mod P)`. Then
`a = -bx (mod P)`
`10a + b = 10(-bx) + b (mod P)`
`0 = 10(-bx) + b (mod P)`
`0 = b(1 - 10x) (mod P)`
Since `P` is prime, the integers `mod P` are an [integral domain](https://en.wikipedia.org/wiki/Integral_domain). So either `b = 0 (mod P)`, or `1 - 10x = 0 (mod P)`.
We know `0 <= b < 10 < P`, so if `b = 0 (mod P)` then `b = 0`. But we said `b` is either `1`, `3`, `7`, or `9`, so this is impossible. Therefore `1 - 10x = 0 (mod P)`, so `10x = 1 (mod P)`. In other words, `x` is the inverse of `10`, modulo `P`.
Now suppose `N` is a nonnegative integer whose last digit is `d`, so `N = 10c + d.` We have a chain of equivalent statements:
`10c + d = 0 (mod P)`
`<==> 10xc + dx = 0 (mod P)`
`<==> c + dx = 0 (mod P)`
QED.
### Usefulness?
I was also wondering whether the divisibility test (given `N = 10c + d`, replace `N` by `dx + c`) would actually be productive in practice. Or at least, does it reliably replace `N` by a number smaller than `N` (in absolute value)?
Suppose `N = 10c + d`, where `c >= 0` and `0 <= d < 10`. Therefore `10c = N - d <= N`. By the triangle inequality,
`|c + dx| <= |c| + |dx| = c + d|x| <= N/10 + d|x|`
`< N/10 + 10|x| <= N/10 + 10P/2 = N/10 + 5P`
Thus if `5P <= 9N/10`, then `|c + dx| < N`.
In particular, if `N >= 6P`, then `|c + dx| < N`. Thus, given `P` we begin by calculating `2P`, `3P`, ..., `6P`, along with `x`. Then given `N`, we run the divisibility test repeatedly until we reach a number less than or equal to `6P`, and check whether the result is any of the numbers `0`, `P`, `2P`, ..., `6P`.
(Of course, whenever we reach a negative number, we replace it by its absolute value, which is fine since `q` is divisible by `P` if and only if `(-q)` is.)
### Improved Bound
I noticed that `|x|/P` never seemed to be close to `1/2`. In fact it seemed like it was always less than `1/3`...or upon closer examination, it was always very close to either `1/10` or `3/10`. The biggest it ever got seemed to be `4/13` (which happens when `P=13` and `x=4`). Why would this be?
Let `u` be an integer and suppose that `10u = kP + 1` for some integer `k`, so `u` is an inverse of `10`, modulo `P`. Then we also know that `k` is relatively prime to `10`, since `k(-P)` is equivalent to `1` modulo `10`.
Now, we know that the inverses of `10` modulo `P` all differ by multiples of `P`, so we can take the integer `u` and either add or subtract multiples of `P` at will, and the result will always still be an inverse of `10` modulo `P`. Suppose we choose to subtract `P` from `u`: we get
`10(u - P) = 10u - 10P = kP + 1 - 10P`
`10(u - P) = (k - 10)P + 1`
In other words, decreasing (respectively, increasing) `u` by `P` corresponds to decreasing (increasing) `k` by `10`. We wish to add/subtract multiples of `P` from `u` until the left-hand side is minimized in absolute value; but the left-hand side is minimized exactly when the right-hand side is minimized, and so we want to add/subtract `10` from `k` until the right-hand side is minimized in absolute value.
But we know that this will happen when `k` is between `-5` and `5`, and therefore (since `k` is relatively prime to `10`) this means `k` is either `-3`, `-1`, `1`, or `3`. (This is the content of @Neil's comment under the OP. **Thanks, Neil!**)
Thus when `|u|` is minimized (i.e., `u=x`), we'll have `x/P = u/P = k/10 + 1/(10P)`, where `k` is either `-3`, `-1`, `1`, or `3`. Therefore `|x|/P <= 3/10 + 1/(10P)`. Equivalently, `|x| <= (3P + 1)/10`.
Further, this inequality is strict at `P=11`, because at `P=11` we have `x=-1` and `k=-1`. The smallest `P` for which equality holds is `P=13` (where `x=4` and `k=3`).
Therefore the largest that `|x|/P` ever gets is `3/10 + 1/(10*13)`, because `P=13` is the first prime for which we have `k=3`, and among those with `k=3`, the `1/(10P)` term is largest when `P` is smallest (i.e., at `P=13`). Therefore, for all `P`, we also have `|x|/P <= 3/10 + 1/130 = 4/13 < 1/3`. This explains why in the above code we can initialize at `i = P/3` rather than having to start at `P/2`.
Further, the bounds in the **Usefulness** section above can now be improved.
*Lemma*: Let `N = 10c + d` where `c > 0` and `0 <= d <= 9`. Then `c + d|x| < N/10 + 9(3P + 1)/10`. (Note the strict inequality.)
Proof of Lemma: by cases. Case I: `d = 0`, so `N = 10c`. Then `c + d|x| = c = N/10 < N/10 + 9(3P + 1)/10`.
Case II: `0 < d <= 9`. Then `10c = N - d < N`, so `c < N/10`. Therefore `c + d|x| < N/10 + d|x| <= N/10 + 9|x| <= N/10 + 9(3P + 1)/10`. QED.
Thus, if `N > 3P` (and `N = 10c + d` as before), then
`3P + 1 <= N`
`9(3P + 1)/10 <= 9N/10`
`N/10 + 9(3P + 1)/10 <= N`
`c + d|x| < N/10 + 9(3P + 1)/10 <= N`
So, if `N > 3P` then `c + d|x| < N`.
Therefore, we only have to find `P`, `2P` and `3P`, along with `x`. Given `N > 0`, while `N > 3P`, we replace `N` by `|c + dx|`, which decreases `N`. Eventually we'll get `N <= 3P`; at that point we stop and check whether `N` is equal to any of the numbers `0`, `P`, `2P`, or `3P`.
We can't do better than `3P` in general. For example suppose `P = 13` and `N = 39`, so `x = 4`. Then replacing `N` by `dx + c = 9(4) + 3` leaves `N` unchanged.
[Answer]
## [Whitespace](http://web.archive.org/web/20150623025348/http://compsoc.dur.ac.uk/whitespace/), 92 bytes
Note that this language's syntax consists of *only whitespace*, so each whitespace character has been prefixed here with S, T, or L (corresponding to Space, Tab, and Linefeed, respectively). These can be removed without losing functionality, but they are included here in order to display it correctly.
```
S S S L
T L
T T S S S L
T T T S L
S S S S T T L
T S S L
S L
T S S S T S T L
T S T T S L
S T S S S S S S T S T L
T S S T T S T S S S S T L
T S S S S S S T S T S L
T S T S T L
S T L
L
L
.
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgYuTi5MTTAMpLiBDgRMoAuQrgEgFTgUQDywF4sJFQEJgATAHKg7SApIGIi6u//8NDQE)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
*Inspired by [Neil's solution](https://codegolf.stackexchange.com/a/139698/61613).*
```
Ì*2%E-3 *UÄ /A
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=zCoyJUUtMyAqVcQgL0E=&input=OTk5OTk5MQ==)
### Explanation:
```
Ì *2%E-3 *UÄ /A
((UgJ*2%E-3)*U+1)/A
U // Implicit U = Input
gJ // Get the char at index -1 (last char)
*2 // Multiply by 2
%E // Mod 14
-3 // Minus 3
*U+1 // Multiply by U+1
/A // Divided by 10
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
ḟȯ¦⁰←*10ݱ
```
[Try it online!](https://tio.run/##FcwhDsJAEEbh@5An9u@0nc45kARPQgiCEHQRaG6Aw1JcdYPgGvQiy9Y9873d@bTPh@NlzXzt8298fF/Tc@6H@XZfKX2G6Z1z3kjIkKOgMqrAhDm1qI3aaYwmaEXruHDDg87ogigqFZ/KIC0daJlVpU3bPw "Husk – Try It Online") A port of [ETHproductions' answer](https://codegolf.stackexchange.com/a/139694).
]
|
[Question]
[
**This is part of a Cops and Robbers challenge. [Go here](https://codegolf.stackexchange.com/q/103182/8478) for the cops' part.**
For the purpose of this challenge, we'll define **whitespace** as *only* linefeeds (0x0A) and spaces (0x20). Note that most languages and regex flavours consider many other characters as whitespace as well, both inside and outside the ASCII range so you might not be able to make use of the corresponding built-ins.
## The Robbers' Challenge
A cop's answer can be cracked by transforming it into a valid program or function (in the chosen language), which performs the task of removing whitespace from an input string, by inserting whitespace into the code. For example if you received the following input:
```
H e l l o,
W o r l d!
```
The program should output
```
Hello,World!
```
After inserting whitespace, the byte count of the solution must not exceed the byte count stated in the cop's answer. You don't have to find the exact same solution as the cop intended, as long as yours is valid by the above constraints.
If you manage this, post an answer with the solution, linking to the cop's answer, and leave a comment on the cop's answer linking back to yours.
The robber who cracks the most cop answers wins. Ties are broken by the sum of sizes of the cracked cop answers (in favour of the robber who cracks longer submissions).
Each cop answer can only be cracked once, and of course, you're not allowed to crack your own answer. If the cop's answer turns out to be invalid before or after being cracked, it is not counted towards the robber's score.
[Answer]
## Haskell, 100 bytes, [by Laikoni](https://codegolf.stackexchange.com/a/103194/34531)
```
main=interact$id doid lines id words
doid oi d o id=do
iddoid<-do oi id
oid<-do o iddoid
do d oid
```
[Answer]
# ><>, 40 bytes, [by DanTheMan](https://codegolf.stackexchange.com/a/103221/62009)
```
v <<
i/\
:=
:
:a?
0/>/
1?o
-=
="
?
;"
>^
```
Really fun to work out.
[Try it on ><>language](https://fishlanguage.com/playground/Bn93nPQBu5Y7wcvsT)
[Answer]
# JavaScript ES6, 199 bytes [by Arnauld](https://codegolf.stackexchange.com/a/103227/32628)
```
s=>eval(atob`ISYgJiAtOkI8Qk97BRBeaxZFShoUZSsiOGkMenNy`.replace(/./g,(c,i)=>String.fromCharCode(c.charCodeAt()^(k+=" S e c r e t C o d e ".split(/\w/)[i%11].length)),k=0)).join``
```
I realized the splitting `"SecretCode"` meant I was looking for 11 numbers that summed to (I assumed) 33. This is a [stars and bars](https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)) problem where the number of spaces are the stars and the letters in `"SecretCode"` were the bars. I did the math to see how many combintations there were to try (1,917,334,783 combinations) and decided to just brute force it, took all day.
There's probably a smarter way to have gone about it, for instance noticing that `k` has to be `33` and `66` for index 10 and 21 respectively, but I'm lazy.
[Answer]
# C, 475 bytes [by rexroni](https://codegolf.stackexchange.com/a/103237/57100)
```
#include<unistd.h>
#define a char
#define b *
#define c write
#define d stdin
#define e stdout
#define f read
#define g (
#define h )
#define i while
#define j if
#define k 0
#define l &
#define m ,
#define n =
#define o ;
#define p 1
#define gpml ml h
#define abo
#define ml d m p
#define jg d o abo
#define lb abo d
#define gf h abo c
#define jgm b e n
#define pml f g
#define gpm lb
int main(){a jg a jgm l jg i g pml k m l gpml h j g d!=' '&&gpm!='\n'gf g p m l gpml o}
```
I might start using some of these defines :)
After the pre-processor the code looks something like this:
```
int main(){
char stdin;
char *stdout = &stdin;
while(read(0, &stdin, 1))
if(stdin !='' && stdin!='\n')
write(1, &stdin, 1);
}
```
[Answer]
## Ruby, 86 bytes + 1 flag = 87 [by histocrat](https://codegolf.stackexchange.com/a/103188/9365)
```
eval"( T $ }{(! // ; : 67 8 ? 32. && )".gsub(/ |(.)/){$1&&$&.ord.^($'.count(' ')).chr}
```
This was really fun, each character in the string passed to `eval` is replaced with the character code (`ord`) XORed `^(...)` against the number of remaining spaces in the string. The resultant code is:
```
$_.tr!(''<<32<<10,'')
```
[Answer]
# RprogN, [by Ataco](https://codegolf.stackexchange.com/a/103196/31347)
This appears to do the trick
```
' ' ` R
"
" ` R
```
[Answer]
# V, 37 bytes, [by DJMcMayhem](https://codegolf.stackexchange.com/a/103203/62346)
```
O VrS200@"kIi|D@"A üî|D@"
```
Unprintables:
```
O <esc>Vr<C-a>S200<esc>@"kIi<C-v><C-v><esc>|D@"<esc>A üî<esc>|D@"
```
[TryItOnline](http://v.tryitonline.net/#code=TyAgICAgG1ZyAVMyMDAbQCJrSWkWFht8REAiG0Egw7zDrht8REAi&input=aGVsbG8geCB3bwoKCnIgICBsZA)
The `ü` really threw me for a loop, I kept expecting both it and `î` to be commands.
```
O # Insert 5 spaces above this line
Vr<C-a> # Change them all to <C-a>
S200<esc> # Replace the line with 200
@" # Play back the 5 <C-a>'s, 200 -> 205
k # ????
Ii<C-v><C-v><esc> # insert "i<C-v>" so our line is now "i<C-v>205"
|D@"<esc> # Delete the line and then run it, which inserts "Í" (ASCII 205)
A üî<esc> # Append " üî" so our line is "Í üî"
|D@" # Delete the line and run it
```
`Í üî` in V translates to `:%s/ \|\n//g` in vim, which globally removes all whitespace. The `Í` command is on the wiki, and the `ü` and `î` are `|` and `n` respectively with their high bit set
[Answer]
# C, 140 bytes [by betseg](https://codegolf.stackexchange.com/a/103185/57100)
```
#include<stdio.h>
int main(){int a=getchar();while(a!=EOF){//\a=getchar();
if(a!=10&&a!=32)//\\putchar(a^10^32);
putchar(a);a=getchar();}}
```
(I also hope I'm doing this right.)
[Answer]
# MATL, 22 bytes [by Luis Mendo](https://codegolf.stackexchange.com/a/103210/31347)
Though I can't be sure why, this seems to [work](http://matl.tryitonline.net/#code=dCcgQCAqICdkbTFlNSVNCmR3JVkKKA&input=WydJJyAzOSAnbSAnIDk3IDEwICdzdHJpbmcnXQ)
```
t' @ * 'dm1e5%M
dw%Y
(
```
I'll have to see if I can work out what it's doing. I figured that the comments had to have line feeds after them and then it was just a matter of getting the spaces in the correct spots.
[Answer]
# MATL, [~~22~~ 21 bytes by Luis Mendo.](https://codegolf.stackexchange.com/a/103210/31516)
Finally... MickyT cracked it while I was writing an explanation, so his answer is the "valid" one. I posted this anyway, in accordance with [this meta post](https://codegolf.meta.stackexchange.com/a/10578/31516).
---
`M` and `Y` are unnecessary and are commented out. It's enough to add 4 whitespace characters, not 5.
```
t' @ *'dm1e5%M
dw%Y
(
```
This is equivalent to the [more compact](http://matl.tryitonline.net/#code=dCcgQCAqICdkbTdkdyg&input=WydUaGlzIGlzICcsIDEwLCAnYScsIDEwLCAnc3RyaW5nJ10):
```
t' @ *'dm7dw(
```
**Partial explanation:**
```
% Implicit input
t % Duplicate input
' @ *' % String with ASCII-values [32 64 32 42]
d % diff, giving [32 -32 10], 32 is space, 10 is newline
m % ismember, checking if the character is 32 or 10
1e5 % 10000, but could just as well be 7
d % Taking the diff of the scalar 1e5, returning an empty matrix []
w % Swap stack in order to use ( below
( % Equivalent to x(y)=[], where x is the input string, and y is the logical
% vector found using ismember (m)
% Implicit output
```
[Answer]
# Whitespace, 68 bytes, [by Ephphatha](https://codegolf.stackexchange.com/questions/103182/significant-whitespace-cops/123333#123333)
* 68 bytes, 21 tabs: `LSSLSSTLSLSTLTSTTTSSSTSTSLTSSTSLSLTSLSSSTSTTSLTSSTLTSLSSLTTTTLSSLSLL`
* 71 bytes, 21 tabs: `LSSLSSLTLTSSSLTTTSSSTSTSLTSSTLTSLSSLTTTSSSTSSSSSLTSSTLTSLSSLTTTTLSSLSLL`
* 72 bytes, 21 tabs: `LSSLSSSTTTTTTLSLSTLTSTTTSLSSSSTSTSLTSSTLTSLSLSSSSTSSSSSLTSSTLTSLTLSSLSLL`
* 65 bytes, 15 tabs (too short): `LSSLSSLSLSTLTSTTTSLSSSSTSTSLTSSTLTSLSLSSSSTSSSSSLTSSTLTSLTLSSLSLL`
Since Whitespace only consists of space, tab, and LF characters (here annotated
as `S`, `T`, and `L`), the entire program needs to be reconstructed, with the
only constraint being that it have exactly 21 tabs to match the cops submission.
I start with a working program, but it's too short and needs 6 more tabs. It
beats the target by 9 bytes, so I could have submitted this as another cop
program, but I don't think it's interesting enough to warrant a second
Whitespace answer.
```
# 65 bytes, 15 tabs
loop: # LSSL
0 dup readc retrieve # SSL SLS TLTS TTT
dup 10 - jz loop # SLS SSSTSTSL TSST LTSL
dup 32 - jz loop # SLS SSSTSSSSSL TSST LTSL
printc # TLSS
jmp loop # LSLL
```
The simplest way to add more tabs would be to use 63 (STTTTTT) as the address
for reading characters instead of 0 (empty).
```
# 72 bytes, 21 tabs
loop: # LSSL
63 dup readc retrieve # SSSTTTTTTL SLS TLTS TTT
…
```
That only adds bytes, though. If we `retrieve` before every usage, we can
eliminate three `dup`s, which have no tabs (SLS). (This is also the only of
these versions without a stack memory leak.)
```
# 71 bytes, 21 tabs
loop: # LSSL
0 readc # SSL TLTS
0 retrieve 10 - jz loop # SSL TTT SSSTSTSL TSST LTSL
0 retrieve 32 - jz loop # SSL TTT SSSTSSSSSL TSST LTSL
0 retrieve printc # SSL TTT TLSS
jmp loop # LSLL
```
We can do better. If we compound the subtractions, 32 (STSSSSS) can be replaced
with 22 (STSTTS), which gains 2 tabs and saves 1 byte. Then, the second branch
doesn't `dup` and the print would obtain an unmodified value with `0 retrieve`,
which gains 3 tabs and adds 3 bytes. For the last tab, a negative sign is added
to one of the zeros.
```
# 68 bytes, 21 tabs
loop: # LSSL
-0 dup readc retrieve # SSTL SLS TLTS TTT
10 - dup jz loop # SSSTSTSL TSST SLS LTSL
22 - jz loop # SSSTSTTSL TSST LTSL
0 retrieve printc # SSL TTT TLSS
jmp loop # LSLL
```
These programs require an implementation, that allows the sign to be omitted for
zero, so will not work with the reference interpreter, which TIO uses.
For this solution and others in Whitespace, see [ws-challenges](https://github.com/thaliaarchi/ws-challenges).
[Answer]
# Befunge-98, 65 bytes [by ninjalj](https://codegolf.stackexchange.com/a/103209/30164)
```
~v >#@
>::':'0--\'[';--!8v1+!
*1+j !j,v >#@
```
[Try it online!](https://tio.run/nexus/befunge-98#Ncr3N9QBAAfwl1WOR0gZxe@sX5xfOWUdLg0jNFEZFZqOEnIUibPO2Xvvvfde732/ANj1Hq/P3x9jhVY4p/aMkglqlUpUiQGSlCGmi@GSJA/VKhVymZ9SoREEucb/fz7rRuMFE1Mzc4uLlyxlVtYyG9vLdvYOVxyvXnNydnG9fsPNXZB7eHp5@4g3ff0U/tKt2wHKwDt3g4JDQsNU4RGR6ntR9x88fBQdExv3OD4h8cnTZ89fvExKTnn1@k1qWnrG23fvM7OyP3z89PnL1xxNbt637/k/CgqLfhZrS0p//S4r/1PxF5Wogg7VqEEt6lAPPRpgQCOa0IwWtKIN7ehAJ7rQjR70og/9GMAghjCMEYwKGMcEJjGFacxgFnOYxwIWsYRlrGAVa1jHBjaxhW3sYBd72McBDnGEY5zglJWsoo7VrGEt61hPPRtoYCOb2MwWtrKN7exgJ7vYzR72so/9HOAghzjMEY5yjOOc4CSnOM0ZznKO81zgIpe4zBWuco3r3OAmt7jNHe5yj/s84CGPeMwTnv4D)
This was a lot of fun. I deduced that since there are few direction-changing commands and no `^<[]?x` or similar, it has to use wrapping. I then wrote a Python script to help with getting the spacing right for the `j`'s.
The code works by taking input (`~`) and duplicating it twice (`::`). It then subtracts 10 (`':'0` or `ord(':') - ord('0')`) and 32 (`'[';` or `ord('[') - ord(';')`). Then, the second result is logically negated (1 if was space, 0 otherwise) and an 8 is pushed.
Now comes the part that needed figuring out what to skip. The `1+!` is skipped by continuing to the next line. `#` skips the `@`. The logically negated result (0 or 1) is multiplied by the 8, and 1 is added.
The code then jumps that many (i.e. 1 or 9) spaces plus one extra as the IP moves. If the character wasn't a space it ends up at the `!`. The character code minus 10 is logically negated (1 if was newline, 0 otherwise). `j` then skips nothing, and the print (`,`) is called and the loop resumes by wrapping vertically.
If the character was a space, the bottom line loops again with `32, 22` as the bottom of stack. The first `j` jumps 705 spaces. Then the line loops a third time. If there are more than two 10's left on the stack (the code only leaves those), the first `j` jumps 100 spaces and the loop repeats. Otherwise, the first `j` jumps to the `!`, a zero is negated, the second `j` jumps over the print and the program continues.
I managed to golf it down to 59 bytes.
[Answer]
## C#6, 201 bytes, [by milk](https://codegolf.stackexchange.com/a/103202/60948)
```
using System.Linq;
_=>string./**/
#if trueJoin
(/*"*//*/""/**//*/"*/",
#else
Concat(//*/,
#endif
from m in" "let p=$@"{@"
"[1]}"from i in(_.Replace(p,@""))where!new[]{p[0]^32^10}.Contains(i)select@i);
```
[repl.it demo](https://repl.it/EqtQ/0)
`trueJoin` is not defined, so only `string.Concat()` remains.
`p` is `"\n"`. `p[0]^32^10` is space. It would have been (a bit) more difficult if it's `p[0]^42` or other similar constants.
[Answer]
# reticular, 43 bytes, [by Conor O'Brien](/a/103214/62101)
```
ISBqv<>>$$4j
E :d/v$v?
c+91d/ v?E
;!?l$/o $
```
[Try it online!](http://reticular.tryitonline.net/#code=SVNCcXY8Pj4kJDRqCkUgOmQvdiR2PwpjKzkxZC8gdj9FCjshP2wkL28gJA&input=SCBlIGwgbCBvLAogVyBvIHIgbCAgZCE)
This was more difficult for me than it should have been because I was too stupid to find the documentation and ended up having to guess how some of the commands worked. So some of this explanation may not be entirely accurate, but this was my basic understanding of the code.
```
I Push all the input on to the stack as a string
S Convert it into a character array.
B Turns that array into individual characters on the stack.
q Reverse the stack so the first letter is on top.
v Move down...
/ ...and turn left.
E :d Duplicate the value and test if equal to space.
v? If it is a space we move down until we wrap to the top.
>$$ Drop the test result and the space.
4j Jump over the next 4 commands (having wrapped to the start).
v Bringing us back to the first down arrow, ready to test the next char.
v$ If it wasn't a space, drop the test result and move down.
c+91d/ Turn left and push a newline (char 10) on to the stack.
v?E If equal, we go down, following the same path as with the space.
/ If not equal, turn down.
l$/ Then turn left, drop the test result, and push the stack size.
;!? If zero (the stack is empty) we terminate.
o$ Otherwise wrap around, drop the stack size, and output the char.
/ Then turn down wrapping around to the top of the program.
v< Then turn left and down to start the process from the beginning again.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 18 bytes cracks [emanresu](https://codegolf.stackexchange.com/a/270001/96266)
```
#ȧ
‛ (#
FṘ₴#
Ṙ‛
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCIjyKdcbuKAmyAgKCNcbkbhuZjigrQjXG7huZjigJtcbiAiLCIiLCIgaGUgbGxvICAgIHdvcmwgZCJd)
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 12 bytes cracks [Alan Breadel](https://codegolf.stackexchange.com/a/270021/108687)
```
#?“" "₉r""₉r
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCIjP+KAnFwiIFwi4oKJclwiXCLigolyIiwiIiwiYSBiIGNcbiBkIiwiMy40LjIiXQ==)
Alan didn’t say how much white space was needed, so I took a wild guess and added one to the string literal and it worked
[Answer]
# C#, 159 bytes [by LethalCoder](https://codegolf.stackexchange.com/a/103247/58106)
```
using System.Linq;s=>string.Join("",string.Join("",s.Split(@"
".Replace(new string((char)0x0D,1),"").ToCharArray())).Select(c=>c+""!=""?c+"":"").ToArray());
```
[repl.it](https://repl.it/EqtQ/2)
The string at the end of line 1 is `" \n"` (space+newline).
```
/*Func<string, string> Lambda =*/ s =>
string.Join("", // No-op
string.Join("", // Join (without whitespace)
s.Split(@" \n".Replace(new string((char)0x0D,1),"").ToCharArray()) // Split on whitespace
).Select(c=>c+""!=""?c+"":"").ToArray()); // No-op
```
[Answer]
# Minkolang v0.15, 88 bytes [by Kritixi Lithos](https://codegolf.stackexchange.com/a/103353/31347)
```
$oI[dd" "=$r'10'=1J,? 1R]r$O3.14
$$$
Cdollars >
$$$
Ceverywhere >x
```
Explanation
```
# Layer 1
$o # input chars onto stack
I # stack length pushed to stack
[ ] # loop popped TOS times (length of string)
dd # duplicate, duplicate
" " # push space to stack
= # equality check
$r # swap
'10' # number 10 to stack (LF char)
= # equality
1J # or
, # not
? # if true jump next
# drop to layer 2
1R # rotates the stack 1 time
r # reverse the stack
$O # output the stack
. # stop
$$$ # Layer 2
> # shift right and then drop to layer 3
$$$ # Layer 3
>x # shift right, pop char off stack and drop to Layer 1 (end loop)
```
]
|
[Question]
[
## Background
Most everyone is familiar with the *Fibonacci numbers* \$F(n)\$:
>
> \$0, 1, 1, 2, 3, 5, 8, 13, 21, ...\$
>
>
>
These are formed by the recursion function \$F(n) = F(n-1) + F(n-2)\$ with \$F(0)=0\$ and \$F(1)=1\$. [A000045](https://oeis.org/A000045)
A closely related sequence is the *Lucas numbers* \$L(m)\$:
>
> \$2, 1, 3, 4, 7, 11, 18, 29, ...\$
>
>
>
These are formed by the recursion function \$L(m) = L(m-1) + L(m-2)\$ with \$L(0)=2\$ and \$L(1)=1\$. [A000032](https://oeis.org/A000032)
We can alternate between the two sequences based on even/odd indices, with the construction
$$A(x) = \begin{cases}
F(x) & x \equiv 0 \pmod 2 \\
L(x) & x \equiv 1 \pmod 2 \\
\end{cases}$$
For example, \$A(4)\$ is equal to \$F(4)\$ since \$4 \bmod 2 \equiv 0\$. We'll call this sequence the *Lucas-nacci Numbers*, \$A(x)\$:
>
> 0, 1, 1, 4, 3, 11, 8, 29, 21, 76 ...
>
>
>
This can be formed by the recursion function \$A(x) = 3A(x-2) - A(x-4)\$ with \$A(0)=0, A(1)=1, A(2)=1\$, and \$A(3)=4\$. [A005013](http://oeis.org/A005013)
## Challenge
Given input \$n\$, output the sequence of \$n+1\$ numbers up to and including \$A(n)\$ as described above. Fewest bytes (or byte-equivalents, such as for [LabVIEW](https://codegolf.meta.stackexchange.com/a/7589/42963), as determined individually on Meta) wins.
## Input
A single non-negative integer \$n\$.
## Output
A list of numbers that correspond to the subsequence of Lucas-nacci numbers from \$A(0)\$ to \$A(n)\$. The list must be in sequential order as described above.
## Rules
* Standard code-golf rules and [loophole restrictions](https://codegolf.meta.stackexchange.com/q/1061/42963) apply.
* [Standard input/output rules](https://codegolf.meta.stackexchange.com/a/1326/42963) apply.
* Input number can be in any suitable format: unary or decimal, read from STDIN, function or command-line argument, etc. - your choice.
* Output can be printed to STDOUT or returned as a result of the function call. If printed, suitable delimiters to differentiate the numbers must be included (space-separated, comma-separated, etc.).
* Additionally, if output to STDOUT, surrounding whitespace, trailing newline, etc. are all optional.
* If the input is a non-integer or a negative integer, the program can do anything or nothing, as behavior is undefined.
## Examples
```
Input -> Output
0 -> 0
5 -> 0, 1, 1, 4, 3, 11
18 -> 0, 1, 1, 4, 3, 11, 8, 29, 21, 76, 55, 199, 144, 521, 377, 1364, 987, 3571, 2584
```
[Answer]
# Jelly, 12 bytes
```
;2U+¥Ð¡-,1ZḢ
```
[Try it online!](http://jelly.tryitonline.net/#code=OzJVK8Klw5DCoS0sMVrhuKI&input=MTg)
### Background
We can extend F and L to -1 by defining F(-1) = 1 and L(-1) = -1. This is consistent with the recursive function.
Our program starts with
```
-1 1
0 2
```
In each step, to form the next pair, we reverse the last pair and add it to the penultimate pair. For example:
```
[0, 2] U+¥ [-1, 1] -> [2, 0] + [-1, 1] -> [1, 1]
```
If we continue this process for a few more steps, we get
```
-1 1
0 2
1 1
1 3
4 2
3 7
11 5
```
The Lucas-nacci sequence is simply the left column.
### How it works
```
;2U+¥Ð¡-,1ZḢ Niladic link. No implicit input.
Since the link doesn't start with a nilad, the argument 0 is used.
;2 Concatenate the argument with 2, yielding [0, 2].
-,1 Yield [-1, 1]. This is [L(-1), F(-1)].
¥ Create a dyadic chain of the two atoms to the left:
U Reverse the left argument.
+ Add the reversed left argument and the right one, element-wise.
С For reasons‡, read a number n from STDIN.
Repeatedly call the dyadic link U+¥, updating the right argument with
the value of the left one, and the left one with the return value.
Collect all intermediate results.
Z Zip the list of results, grouping the first and seconds coordinates.
Ḣ Head; select the list of first coordinates.
```
‡ `С` peeks at the two links to the left: `2` and `U+¥`. Since the leftmost one is a nilad, it cannot be the body of the loop. Therefore, `U+¥` is used as body and a number is read from input. Since there are no command-line arguments, that number is read from STDIN.
[Answer]
## CJam, ~~21~~ 20 bytes
*Thanks to Sp3000 for saving 1 byte.*
```
TXX4ri{1$3*4$-}*?;]p
```
[Test it here.](http://cjam.aditsu.net/#code=TXX4ri%7B1%243*4%24-%7D*%3F%3B%5Dp&input=18)
### Explanation
Simply uses the recurrence given in the challenge spec.
```
TXX4 e# Push 0 1 1 4 as base cases.
ri e# Read input and convert to integer N.
{ e# Run this N times...
1$ e# Copy a(n-2).
3* e# Multiply by 3.
4$ e# Copy a(n-4).
- e# Subtract.
}*
?; e# Discard the last three values, using a ternary operation and popping the result.
]p e# Wrap the rest in an array and pretty-print it.
```
[Answer]
# Perl 6, 42 bytes
```
{(0,1,1,4,{$^b;$^d;3*$^c-$^a}...*)[0..$_]}
```
**usage**
```
> my &f = {(0,1,1,4,{$^b;$^d;3*$^c-$^a}...*)[0..$_]}
-> ;; $_? is raw { #`(Block|184122176) ... }
> f(0)
(0)
> f(5)
(0 1 1 4 3 11)
> f(18)
(0 1 1 4 3 11 8 29 21 76 55 199 144 521 377 1364 987 3571 2584)
```
[Answer]
# Haskell, ~~59~~, ~~57~~, ~~56~~, ~~52~~, 51 bytes
```
l a=2*mod a 2:scanl(+)1(l a)
f n=[l i!!i|i<-[0..n]]
```
Series definition adapted from [this answer](https://codegolf.stackexchange.com/a/89/48962).
Less golfed:
```
fibLike start = start : scanl (+) 1 (fibLike start)
whichStart i = (2*mod i 2)
lucasNacci i = fibLike (whichStart i) !! i
firstN n = [ lucasNacci i | i <- [0..n]]
```
`fibLike start` gives an infinite list, defined: `f(0)=start, f(1)=1, f(n)=f(n-1) + f(n-2)`.
`whichStart i` returns 2 for odd input (Lucas series) or 0 for even (Fibonacci series).
`lucasNacci i` gives the ith Lucas-nacci number.
`firstN n` maps over the list.
One byte saved by Boomerang.
[Answer]
## ES6, 65 bytes
```
n=>[...Array(n)].map(_=>a.shift(a.push(a[2]*3-a[0])),a=[0,1,1,4])
```
Uses the recurrence relation given in the question.
[Answer]
## [Retina](https://github.com/mbuettner/retina), ~~70~~ ~~62~~ 59 bytes
```
1
¶$`1
m`^(11)*1$
$&ff
m`$
f
+`1(f*) (f*)
$2 $2$1
f*
f
1
```
[Try it online](http://retina.tryitonline.net/#code=MQrCtiRgMQptYF4oMTEpKjEkCiQmZmYKbWAkCiBmCitgMShmKikgKGYqKQokMiAkMiQxCiBmKgoKZgox&input=MTExMTExMTExMQ)
* Input is in unary base, *n* 1s.
* `1?` `$`¶` - Create a line for each number from 0 to *n*: `, 1, 11, 111, 1111, ...`
* `m`^(11)*1$` `$&ff` - Append `ff` to odd lines. This will seed the function with L(0)=2.
* `m`$` `f` - Append `f` to all lines (note the space). This seeds the function with 0 and 1 for Fibonacci numbers, and 2 and 1 for Lucas numbers.
* `+`1(f*) (f*)` `$2 $2$1` - Loop: calculate F(n+1) = F(n) + F(n-1) while there are still 1s.
* `f*` - Remove F(n+1) from the end of each line.
* Replace `f`s back to 1s. If this isn't needed and we can stay with `f`s, the length is just 55 bytes.
[Answer]
# Oracle SQL 11.2, ~~218~~ ~~216~~ 201 bytes
```
WITH v(a,b,c,d,i)AS(SELECT 0,1,1,4,3 FROM DUAL UNION ALL SELECT b,c,d,3*c-a,i+1 FROM v WHERE i<:1)SELECT SIGN(LEVEL-1) FROM DUAL WHERE LEVEL-1<=:1 CONNECT BY LEVEL<4UNION ALL SELECT d FROM v WHERE:1>2;
```
Un-golfed
```
WITH v(a,b,c,d,i) AS
(
SELECT 0,1,1,4,3 FROM DUAL
UNION ALL
SELECT b,c,d,3*c-a,i+1 FROM v WHERE i<:1
)
SELECT SIGN(LEVEL-1) FROM DUAL WHERE LEVEL-1<=:1 CONNECT BY LEVEL<4
UNION ALL SELECT d FROM v WHERE:1>2;
```
I managed to gain a few bytes by using (abusing ?) the SIGN function to generate the first 3 elements of the sequence.
[Answer]
# Japt, ~~25~~ ~~22~~ 21 bytes
```
Uò £MgXf2)+X%2*Mg°X)r
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VfIgo01nWGYyKStYJTIqTWewWCly&input=MTg=)
### Background
It's somewhat difficult to create a Fibonacci sequence in Japt, but we have a built-in `Mg` to do it for us. However, this only gives us the Fibonacci sequence, not the Lucas sequence. We can accomplish the Lucas sequence fairly easily using this trick:
```
N F(N-1) F(N+1) F(N-1)+F(N+1)
0 1 1 2
1 0 1 1
2 1 2 3
3 1 3 4
4 2 5 7
5 3 8 11
6 5 13 18
7 8 21 29
```
As you can see, `F(N-1) + F(N+1)` is equal to `L(N)` for all `N`. However, since we only need Lucas numbers on the odd indices, we can combine the two formulas into one:
```
N N-N%2 N+N%2 F(N-N%2) F(N+N%2)*(N%2) F(N-N%2)+F(N+N%2)*(N%2)
0 0 0 0 0 0
1 0 2 0 1 1
2 2 2 1 0 1
3 2 4 1 3 4
4 4 4 3 0 3
5 4 6 3 8 11
6 6 6 8 0 8
7 6 8 8 21 29
```
### How it works
```
Uò £ MgX-1 +X%2*Mg° X)r
Uò mX{MgX-1 +X%2*Mg++X)r
// Implicit: U = input integer
Uò mX{ // Create the inclusive range [0..U], and map each item X to:
MgXf2)+ // Floor X to a multiple of 2, calculate this Fibonacci number, and add:
+X%2*Mg++X) // Calculate the (X+1)th Fibonacci number and multiply by X%2.
)r // Round the result. (The built-in Fibonacci function returns
// a decimal number on higher inputs.)
```
[Answer]
# Mathematica, ~~52~~ 51 bytes
```
If[#>2,3#0[#-2]-#0[#-4],#-If[#>1,1,0]]&/@0~Range~#&
```
Very similar idea to Martin's above, I spent some time trying to find a shorter way of defining the "base cases" for the function. Polynomial interpolation was a bust, so I went for this, using the extension into negatives to yield a fairly short definition.
[Answer]
## Mathematica, 56 bytes
```
f@0=0
f@1=f@2=1
f@3=4
f@n_:=3f[n-2]-f[n-4];
f/@0~Range~#&
```
Very straightforward implementation. Defines a helper-function `f` and then evaluates to an unnamed function which applies `f` to a range to get all the results. This feels unnecessarily cumbersome.
A single unnamed function seems to be one byte longer though:
```
Switch[#,0,0,1,1,2,1,3,4,_,3#0[#-2]-#0[#-4]]&/@0~Range~#&
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 17 ~~18~~ bytes
```
0ll4i:"y3*5$y-](x
```
Almost direct translation of [Martin's CJam answer](https://codegolf.stackexchange.com/a/71439/36398).
[**Try it online!**](http://matl.tryitonline.net/#code=MGxsNGk6InkzKjUkeS1dKHg&input=MTg)
```
0ll4 % push first four numbers: 0,1,1,4
i: % input n and generate array [1,2,...,n]
" % for loop. Repeat n times
y % copy second-top element from stack
3* % multiply by 3
5$y % copy fifth-top element from stack
- % subtract. This is the next number in the sequence
] % end loop
(x % indexing operation and delete. This gets rid of top three numbers
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 51 bytes
```
:0re{:4<:[0:1:1:4]rm!.|-4=:1&I,?-2=:1&*3-I=.}w,@Sw\
```
This takes a number as input and prints to STDOUT the list, with spaces separating each number.
### Explanation
```
§ Main predicate
:0re{...} § Enumerate integers between 0 and the Input, pass the integer
§ as input to sub-predicate 1
w,@Sw § Write sub-predicate 1's output, then write a space
\ § Backtrack (i.e. take the next integer in the enumeration)
§ Sub-predicate 1
:4< § If the input is less than 4
:[0:1:1:4]rm!. § Then return the integer in the list [0,1,1,4] at index Input
| § Else
-4=:1&I, § I = sub_predicate_1(Input - 4)
?-2=:1&*3-I=. § Output = sub_predicate_1(Input - 2) * 3 - I
```
The cut `!` in the first rule of sub-predicate 1 is necessary so that when we backtrack (`\`), we don't end up in an infinite loop where the interpreter will try the second rule for an input less than 4.
[Answer]
# Mathematica, 41 bytes
```
LinearRecurrence[{0,3,0,-1},{0,1,1,4},#]&
```
[Answer]
# Groovy, 50 Bytes
```
x={a,b=0,c=1,d=1,e=4->a<0?:[b,x(a-1,c,d,e,3*d-b)]}
```
This defines the function x, which takes in n as it's first argument and has the base case of the first four numbers in the Fibocas sequence as default arguments for the rest of the function.
a here is n. b, c, d, and e are the next four elements in the sequence.
It decrements n and recurses until n is less than zero-- when it recurses, it adds on to the ultimate return value the first element in its current sequence. The new values for the next four elements in the sequence are given to the recursive call-- the last three elements are shifted over to be the first three, and a new fourth element is generated from two of the previous elements using 3\*d-b.
It delimits new values with list nestings, as groovy can return multiple values by stuffing them into a list-- so each call returns the current first element and the result of recursion, which will be its own list.
[Answer]
# C++ Template Meta Programming, 130 bytes
```
template<int X>struct L{enum{v=3*L<X-2>::v-L<X-4>::v};};
#define D(X,A) template<>struct L<X>{enum{v=A};};
D(0,0)D(1,1)D(2,1)D(3,4)
```
Recursive definitions somehow cry for C++TMP, usage:
```
L<x>::v
```
with `x` being the `A(x)` you like.
[Answer]
# [R](https://www.r-project.org/), 55 bytes
```
A=c(0,1,1,4);for(x in 4:scan()+1)A[x]=3*A[x-2]-A[x-4];A
```
[Try it online!](https://tio.run/##K/r/39E2WcNAxxAITTSt0/KLNCoUMvMUTKyKkxPzNDS1DTUdoytibY21gJSuUawuiDKJtXb8b2jxHwA "R – Try It Online")
* -24 bytes thanks to JayCe
[Answer]
# [Pylons](https://github.com/morganthrapp/Pylons-lang), 19
This is a pretty direct translation of Martin's approach.
```
0114{@-4@-33*-,i}=4
```
How it works:
```
0114 # Push 0, 1, 1, 4 to the stack.
{ # Start a for loop.
@-4 # Get the stack element at index -4
@-3 # Get the stack element at index -3
3 # Push 3 to the stack.
* # Multiply the top two elements of the stack.
- # Subtract the top two elements of the stack.
, # Switch to loop iterations.
i # Get command line args.
} # End for loop.
=4 # Discard the top 4 elements of the stack.
```
[Answer]
# [DUP](https://esolangs.org/wiki/DUP), 32 bytes
```
[a:0 1$4[a;1-$a:][1ø3*4ø-]#%%]
```
`[Try it here!](http://www.quirkster.com/iano/js/dup.html)`
An anonymous lambda that leaves a sequence of numbers on the stack. Usage:
```
8[a:0 1$4[a;1-$a:][1ø3*4ø-]#%%]!
```
# Explanation
```
[ {start lambda}
a: {save input number to a}
0 1$4 {base cases to get us started}
[ ][ ]# {while loop}
a;1-$a: {a--, check if a>0}
1ø3*4ø- {3*stack[n-2]-stack[n-4]}
%% {discard top 2 stack items}
] {end lambda}
```
[Answer]
## Python 2, 71 bytes
```
def a(n,x=0,y=1,z=2,w=1,p=0):
if~n:print[x,z][p];a(n-1,y,x+y,w,z+w,~p)
```
This definitely seems too long. However, I was pleased that I got to use the bitwise `not` operator...twice. Once as kind of a parity flip back and forth, and once to terminate the recursion when `n` reaches `-1`.
The variable `p` will always be either `0` or `-1`, so it will alternate between entries `0` or `-1` of the list. (Choosing entry `-1` of a Python list means choosing the last element.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ŻÆĿÆḞḂ?€
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//xbvDhsS/w4bhuJ7huII/4oKs/8OHxZLhuZgpWf//MCwgNSwgMTg "Jelly – Try It Online")
Close to a literal interpretation of the spec
## How it works
```
ŻÆĿÆḞḂ?€ - Main link. Takes N on the left
Ż - Range from 0 to N
€ - Over each integer k:
? - If:
Ḃ - Condition: k mod 2
ÆĿ - Truthy: kth Lucas number
ÆḞ - Falsey: kth Fibonacii number
```
]
|
[Question]
[
In combinatorics, the [**rook polynomial**](https://en.wikipedia.org/wiki/Rook_polynomial) \$R\_{m,n}(x)\$ of a \$m \times n\$ chessboard is the generating function for the numbers of arrangements of non-attacking rooks. To be precise:
$$R\_{m,n}(x) = \sum\_{k=0}^{\min(m,n)} r\_k x^k,$$
where \$r\_k\$ is the number of ways to place \$k\$ rooks on an \$m \times n\$ chessboard such that no two rooks attack each other; that is, no two rooks are in the same row or column.
The first few rook polynomials on square chessboards are:
* \$R\_{1,1}(x) = x + 1\$
* \$R\_{2,2}(x) = 2 x^2 + 4 x + 1\$
* \$R\_{3,3}(x) = 6 x^3 + 18 x^2 + 9 x + 1\$
* \$R\_{4,4}(x) = 24 x^4 + 96 x^3 + 72 x^2 + 16 x + 1\$
For example, there are \$2\$ ways to place two rooks on a \$2 \times 2\$ chessboard, \$4\$ ways to place one rook, and \$1\$ way to place no rooks. Therefore, \$R\_{2,2}(x) = 2 x^2 + 4 x + 1\$.

(The image above comes from [Wolfram MathWorld](https://mathworld.wolfram.com/RookPolynomial.html).)
The rook polynomials are closely related to the [generalized Laguerre polynomials](https://en.wikipedia.org/wiki/Laguerre_polynomials#Generalized_Laguerre_polynomials) by the following formula:
$$R\_{m,n}(x) = n! x^n L\_n^{(m-n)}(-x^{-1}).$$
## Task
Your task is to write a program or function that, given two positive integers \$m\$ and \$n\$, outputs or returns the rook polynomial \$R\_{m,n}(x)\$.
You may output the polynomials in any reasonable format. Here are some example formats:
* a list of coefficients, in descending order, e.g. \$24 x^4 + 96 x^3 + 72 x^2 + 16 x + 1\$ is represented as `[24,96,72,16,1]`;
* a list of coefficients, in ascending order, e.g. \$24 x^4 + 96 x^3 + 72 x^2 + 16 x + 1\$ is represented as `[1,16,72,96,24]`;
* a function that takes an input \$k\$ and gives the coefficient of \$x^k\$;
* a built-in polynomial object.
You may also take three integers \$m\$, \$n\$, and \$k\$ as input, and output the coefficient of \$x^k\$ in \$R\_{m,n}(x)\$. You may assume that \$0 \leq k \leq \min(m,n)\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test Cases
Here I output lists of coefficients in descending order.
```
1,1 -> [1,1]
1,2 -> [2,1]
1,3 -> [3,1]
1,4 -> [4,1]
1,5 -> [5,1]
2,1 -> [2,1]
2,2 -> [2,4,1]
2,3 -> [6,6,1]
2,4 -> [12,8,1]
2,5 -> [20,10,1]
3,1 -> [3,1]
3,2 -> [6,6,1]
3,3 -> [6,18,9,1]
3,4 -> [24,36,12,1]
3,5 -> [60,60,15,1]
4,1 -> [4,1]
4,2 -> [12,8,1]
4,3 -> [24,36,12,1]
4,4 -> [24,96,72,16,1]
4,5 -> [120,240,120,20,1]
5,1 -> [5,1]
5,2 -> [20,10,1]
5,3 -> [60,60,15,1]
5,4 -> [120,240,120,20,1]
5,5 -> [120,600,600,200,25,1]
```
[Answer]
# JavaScript (ES6), 31 bytes
Expects `(m)(n)(k)`.
```
m=>n=>g=k=>k?m--*n--/k*g(--k):1
```
[Try it online!](https://tio.run/##NYxBCoMwEEX3nmKWM2pSXHSjTaTnKKWIjdLGTCSKUIpnTwNtV@/D479nt3VLHx7zKtjfTRxUdEqz0qOyStvWCZGzEAebjyiEpbqKgw84mRUcKKiahJOCY2JRELwzgL/nr@ef578H6D0vfjJy8iO6EriEi5TyHEL3wpRLlzZlC6igTjuRrtJ1M@KtBEugNAzoCJnQEslgNhMWg0RNqu/ZHj8 "JavaScript (Node.js) – Try It Online")
### How?
Like other answers, this is based on [the formula from Wikipedia](https://en.wikipedia.org/wiki/Rook_polynomial#The_rook_polynomial_as_a_generalization_of_the_rooks_problem), but re-arranged in a recursive-friendly form:
$$k!\times \binom{m}{k}\times\binom{n}{k}=\prod\_{i=1}^{k}\frac{(m+1-i)\times(n+1-i)}{i}$$
[Answer]
# [Python](https://www.python.org), ~~63~~ 50 bytes
```
lambda m,n,k:comb(m,k)*perm(n,k)
from math import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY1BDoIwEEX3nGKWHawLXBhD4knERZEiDcy0GauJZ3FDYvRO3kYo7lz95OX9_x_vcI-d5_Ep--p1je1699kMhurGAGnWfXnyVCvSPebBCqkJYdaKJyATO3AUvMT81xxaL0DgGMTw2apCb7HMAGbM_xggiOM4rQNrOIhKj5j0Pun2ZuViG7X0yPGs4KpAPOLyOY5LfgE)
To place \$k\$ rooks on an \$m\times n\$ chessboard, we choose \$k\$ out of the \$m\$ rows, \$k\$ of the \$n\$ colums and a permutation of the numbers from \$1\$ to \$k\$ representing which rook will be at which place in each row. This gives a total of \$\binom{m}{k}\cdot\binom{n}{k}\cdot k!\$ options.
*-13 bytes thanks to matteo\_c*
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
cṭsƇ×
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPWMlRTElQjklQURzJUM2JTg3JUMzJTk3JmZvb3Rlcj0maW5wdXQ9NSUwQTUlMEE1JmZsYWdzPQ==)
Port of xigoi's Python answer. Takes `k`, then `m`, then `n`.
#### Explanation
```
cṭsƇ× # Implicit input
c # Compute nCr(m, k)
·π≠s # Swap to get the right order
Ƈ # Compute nPr(n, k)
√ó # Multiply together
# Implicit output
```
[Answer]
# [Python](https://docs.python.org/2/), 41 bytes
```
f=lambda m,n,k:k<1or f(m-1,n-1,k-1)*m*n/k
```
[Try it online!](https://tio.run/##ZY2xDsIwDER3vsJj3LpCZmCo4EsQQ1ATiIzdKlRIfH1Iyshwy927u@WzPmY7lBLPT6@3yYOSkYxy4jlDdDowWZUMjJ12tpcSa6CQDLK3e3BMRxx3AM22fxtgycnWOgtGcOnrZDvAjZeND@@QX2Fyv6Imawj2jHgtXw "Python 2 – Try It Online")
Based on the formula in [Arnauld's answer](https://codegolf.stackexchange.com/a/263835/20260). Test cases [from xigoi](https://codegolf.stackexchange.com/a/263831/20260). Outputs `True` for `1` when `k=0`. The code also works in Python 2 or 3, but gives floats in Python 3 that can become imprecise for large outputs.
[Answer]
# [Julia 1.0](http://julialang.org/), ~~39~~ 33 bytes
```
f(k,m,n)=k<1||m*f(k-1,m-1,n-1)n/k
```
[Try it online!](https://tio.run/##bZDRboIwFIbvfYozLwwsB0ZLy3QZZi@wJzBe1FiTDuxMYcsufHfW9qBitoaT8v05/Xrg46s1iv0MwyFp8Ig2rZtXdj4fHz1nDI@@bMZS@9QMh08HBowFp9W@NVZ3SToDvxTCDmrQ36rNk3fdq/ykXKfzpDu1pk8MwjxbzyFNqf3kjO1bmyio17CjLLib4C5eZAzCcl4axgKV53k6iR9qKGCxuJqaYHL/dbyprtOuD6oadhtt91mzhdjo32ehBoYMsjVs/L6dMeQROEEZoSQQEQSBjCAD8FHACS4CQUiKCitCkjCOS2Ly8AJZEYJydJUEfHq4vLrYEleUkI4LLH3KKSNlVaB/WJxQjFZBwO9mEKN2KhE38arCZ59VFMvxaIFceHvY49xyvEES8PuvkpfJJzPJ66/467rdUhVUPFQ49ws "Julia 1.0 – Try It Online")
*-6 bytes and test cases due to @MarcMush*
Similar in spirit to @The Thonnu 's answer. Given a triple \$(k,m,n)\$, there are \$m\times n\$ ways of placing the first rook, and then the problem is reduced to that of the triple \$(k-1, m-1, n-1)\$ since we can just eliminate the file and rank that we placed the first rook on. By the end we will have over-counted by a factor of \$k!\$, since the order of placement of the rooks does not matter.
edit: I made a mistake when copying the code from my IDE so the original solution of 32 bytes was defective :X
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 5 bytes
```
!;c@P
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FksVrZMdApYUJyUXQ0XWRisZKekoRZvqmMQqxUIFAQ)
Takes arguments in the form `k [m,n]`. I didn't manage to come up with anything shorter, but feel like it's possible… But at least this is ASCII-only as a bonus.
```
!;c@P
! Factorial of k
; Join that with
c@ [m,n] choose k (vectorized)
P Product
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 37 bytes
```
f(m,n,k){m=k?m--*n--*f(m,n,k-1)/k:1;}
```
[Try it online!](https://tio.run/##Xc3RCsIgFMbx@z3FxyDQptRuuthme5DqIhbGUbQY3Q2f3ZTGVoGei/PDv4O8D0OMmjnhheWTU7Z3Um59uvNS1nxnm7oNkfwL7kqecUwFoB8jWN6RqltQd0ijqj72pSaryWpWBZ5jQs3KzQ3pnFAKkIDh7ezLe6sYdaanJhnsUe3TlHIN/aRSRbPcEbB8aYW/Py9nX86YKRQhvgE "C (gcc) – Try It Online")
My first C answer (yay!)
Port of Arnauld's JavaScript answer.
*Fixed thanks to @mousetail*
[Answer]
# [Desmos](https://desmos.com/calculator), 25 bytes
```
f(m,n,k)=nCr(n,k)nPr(m,k)
```
[Try It On Desmos!](https://www.desmos.com/calculator/anojjythum)
Takes in \$m,n,k\$ as input. Port of like most of the answers here.
[Answer]
# [R](https://www.r-project.org)\*, ~~37~~ 35 bytes
```
f=\(l)prod(if(l)c(f(l-1)/l[1]^2,l))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMFNp4TMtATbtNK85JLM_DyNCp1KW79QHx-dKjClmZRYnGplBVKjUREdbRgbC5SvBEpWaXIV5ednF-TnVNouLS1J07W4qZxmG6ORo1lQlJ-ikZkGZCVrAEldQ039HKDGOCOdHE1NqFLN4sSCgpxKDQMrEx241dmaMBM1kjWydUx0TDRhGhYsgNAA)\*
or [Try it Online](https://tio.run/##K/pflJ@fXZCfU2n7P802rTQvuSQzP08jR7OgKD9FIzMNyErWAJK6hpr6OdGGsXFGOjmamv@LEwsKcio1DKxMdOB6sjVhRmkka2TrmOiYaAJVAgA) using `function` instead of the shorter `\` notation.
Input is a vector `(k,m,n)`. This allows a compact function definition of `f(l)`, and lets us perform a recursive call with all arguments decremented using just `f(l-1)`, saving quite a few bytes compared to `f(k,m,n)` and `f(k-1,m-1,n-1)`.
To get `m*n/k` we now need to use `prod(l)/l[1]^2`, which may initially seem a bit verbose, but it brings the useful property that `prod(NULL)` is equal to `1`, nicely solving the base case when `k==0` (so `if(l)` doesn't return anything).
\*ATO uses a version of R (version 4.3.1) in which the `if` function errors when the condition has length >1. Versions between 4.1.0 and <4.2.0 just give a warning for this without halting with an error, and the header in the ATO link redefines the `if` function to mimic this behaviour.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
cI¬πe*
```
Inputs in the order \$k,m,n\$.
[Try it online](https://tio.run/##yy9OTMpM/f8/2fPQzlSt//@NuUy5TAA) or [verify all test cases](https://tio.run/##ATAAz/9vc2FiaWX/NUzDo3Z5w5/GknlOwqrDgj8iIOKGkiAiP8SHVWDCqf9jWMKuZSr/LP8).
Or alternatively:
```
c¹!ªP
```
Inputs in the order \$k,[m,n]\$.
[Try it online](https://tio.run/##yy9OTMpM/f8/OeDQTkWt//@NuaJNdUxiAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/W/qc3hxWeXh@ccm@dkrKSTmpSgo2VcCWY/aJoFYfv@T/RQPrQr4r/MfAA).
Both are port of [*@xigoi*'s Python answer](https://codegolf.stackexchange.com/a/263831/52210).
**Explanation:**
```
c # Push the first (implicit) input `nCr` the second (implicit) input,
# aka the number of combinations; aka the binomial coefficient; aka `k choose m`
I # Push the third input
¬π # Push the first input again
e # Pop both, and push their `nPr`, aka the number of permutations
* # Multiply them together: (k nCr m)*(k nPr n)
# (which is output implicitly as result)
```
```
c # Push the first (implicit) input `nCr` the second (implicit) input-pair:
# [k nCr m,k nCr n]
ª # Append
! # the factorial of
¬π # the first input `k`: [k nCr m,k nCr n,k!]
P # Get the product of this list: (k nCr m)*(k nCr n)*k!
# (which is output implicitly as result)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
ƈ?¡JΠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLGiD/CoUrOoCIsIiIsIjRcbjUsIDUiXQ==)
Port of xigoi's Jelly answer. Takes `k`, then `[m, n]`.
*-2 thanks to @JonathanAllan*
#### Explanation
```
ƈ?¡JΠ # Implicit input
ƈ # Compute nCr of both
?¬° # Factorial of k
J # Appended to the list
Π # Take the product
# Implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
≔…⁰NθI÷ΠΣE²⁻NθΠ⊕θ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjebHYuLM9PzNIIS89JTNQx0FDzzCkpL_Epzk1KLNDQ1dRQKNa25Aooy80o0nBOLSzQ880pcMssyU1I1AoryU0qTSzSCS3M1fBMLNIx0FHwz80qLNVBMABmgCTIHptwzL7koNTc1ryQ1RQMspWm9pDgpuRjqoOXRSrplOUqxS40VTBRMIWIA) Link is to verbose version of code. Takes `k` as the first input. Explanation: Uses the same formula as @Arnauld's answer, but works by taking the product of lists instead of recursing.
```
… List from
⁰ Literal integer `0` to
N Input `k`
≔ θ Store in variable
² Literal integer `2`
E Map over implicit range
N Next input `m` or `n`
⁻ Vectorised subtract
θ Stored range
Σ Concatenate the lists
Π Take the product
√∑ Integer divided by
θ 0-indexed range
‚äï Increment to 1-indexed range
Π Take the product
I Cast to string
Implicitly print
```
[Answer]
# [Mathematica 12.2 or later](https://reference.wolfram.com/legacy/language/v13/guide/SummaryOfNewFeaturesIn122), ~~38~~ 26 bytes
Saved 12 bytes thanks to the comment of [@alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)
---
26 bytes version:
```
1##&@@{##2}~Binomial~# #!&
```
---
‚ÄÉ
‚ÄÉ
38 bytes version:
```
{n,m,k}|->k!Binomial[m,k]Binomial[n,k]
```
How to use it?
```
f={n,m,k}|->k!Binomial[m,k]Binomial[n,k]
f[4,3,2]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
->(m,n,k){k>0?f.call(m-1,n-1,k-1)*m*n/k:1}
```
[Try it online!](https://tio.run/##VY6xCoMwGIR3n@LQxUiSmqFLofZBrIO1BkrMr2gdiuTZ06h16HD8/x0fx43z4@M1rrh7UaSWEzdsMUV@07Kpuy61QnEKMkKxzGZ0MhflvO5HWLwISsoznn0ErBH9R0DTt1pPob2sNr9CZoVyKUvLQZW0wf3og5f1MLT0xDEhcByGbUzItzvM7wlxmizWcSQLOQYhivDtFS6OdjbIfwE "Ruby – Try It Online")
I had an idea with a recursive lambda, much like a few others here. My answer is probably the most similar to [xnor's](https://codegolf.stackexchange.com/a/263848/119199) (and falls only one byte short of it :P)
]
|
[Question]
[
The [generalised harmonic number](https://en.wikipedia.org/wiki/Harmonic_number#Generalized_harmonic_numbers) of order \$m\$ of \$n\$ is
$$H\_{n,m} = \sum\_{k=1}^n \frac 1 {k^m}$$
For example, the [harmonic numbers](https://en.wikipedia.org/wiki/Harmonic_number) are \$H\_{n,1}\$, and \$H\_{\infty,2} = \frac {\pi^2} 6\$. These are related to the [Riemann zeta function](https://en.wikipedia.org/wiki/Riemann_zeta_function) as
$$\zeta(m) = \lim\_{n \to \infty} H\_{n,m}$$
Given two positive integers \$n > 0\$, \$m > 0\$, output the *exact* rational number \$H\_{n,m}\$. The fraction should be reduced to its simplest term (i.e. if it is \$\frac a b\$, \$\gcd(a, b) = 1\$). You may output as a numerator/denominator pair, a rational number or any clear value that distinguishes itself as a rational number. You **may not** output as a floating point number.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
## Test cases
```
n, m -> Hₙ,ₘ
3, 7 -> 282251/279936
6, 4 -> 14011361/12960000
5, 5 -> 806108207/777600000
4, 8 -> 431733409/429981696
3, 1 -> 11/6
8, 3 -> 78708473/65856000
7, 2 -> 266681/176400
6, 7 -> 940908897061/933120000000
2, 8 -> 257/256
5, 7 -> 2822716691183/2799360000000
```
[Answer]
# [M](https://github.com/DennisMitchell/m), 4 bytes
```
Rİ*S
```
[Try it online!](https://tio.run/##y/3/P@jIBq3g////G/83BwA "M – Try It Online")
Obligatory trivial answer ;-;
```
Rİ*S Main Link; takes n on the left and m on the right
R Range: [1, 2, 3, ..., n]
İ Inverse/Reciprocal: [1, 1/2, 1/3, ..., 1/n]
* Exponent: [1, 1/2^m, 1/3^m, ..., 1/n^m]
S Sum
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14 bytes
```
HarmonicNumber
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yOxKDc/LzPZrzQ3KbXof0BRZl5JtLKuXZqDg3KsWl1wcmJeXTVXtbGOgnmtDle1mY6CCYg21VEwBdEmOgoWIBoobwiiLXQUjEG0uY6CEVQ9WJ8RVJ0piM9V@x8A "Wolfram Language (Mathematica) – Try It Online")
Naturally.
---
Alternatively, **16 bytes** without the built-in:
```
Tr[Range@#^-#2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P6QoOigxLz3VQTlOV9koVu1/QFFmXkm0sq5dmoODcqxaXXByYl5dNVe1sY6Cea0OV7WZjoIJiDbVUTAF0SY6ChYgGihvCKItdBSMQbS5joIRVD1YnxFUnSmIz1X7HwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Raku](http://raku.org/), 29 bytes
```
{sum((1/1..$^n)X**-$^m).nude}
```
[Try it online!](https://tio.run/##Fck9CoAgAAbQq3yIREYZ0u9gnaMpCdIpK4qGsM5uOb3h7fpYam9vRAadd@dl41jkgnM6rmxIkoyOlvH1mvXrz@kGoQpdD2fwUPUSmO2AbFD0KWSJOlChCrQoA@I//wE "Perl 6 – Try It Online")
This function takes two arguments, `$^m` and `$^n`. `1/1 .. $^n` is a sequence of rational numbers from `1` to the second argument. `X** -$^m` produces the exponentiated cross product of that list with the negative of the first argument. `sum` sums those rational numbers, and `.nude` produces a two-element list of the numerator and denominator of the sum.
[Answer]
# JavaScript (ES7), 68 bytes
A 1-byte shorter, slightly less readable version with a single recursive call. This is otherwise identical to the commented version below.
```
m=>g=(n,N=0,D=1)=>D?g(n-!!n,n?p=N*n**m+D:D,n?q=D*n**m:N%D):[p/N,q/N]
```
[Try it online!](https://tio.run/##PU9LbuJAEN37FJVIkbuhcf/s/hA1bDyz9CZLQiQEhjiCNtgkUhTNDUaazSxn7jHnyQXmCKTtWKlFSa/q1XuvnlYvq3bdVMfzxNeb8rJ1l4Ob7RzypHCM5I5jN8vnO@QnV1ee@PnRFSM/Gh3G@TQP8OTyHk6LmxxPF0dakBMtlpemPD1XTYnibRvjpClXm@/Vvrx79WvEcHKu785N5XcIJ@1xX53R9b2/xsm2br6t1o@oBTeDtwhg4QkcCDRluwQH7UCmiwd6v1mOKb4NnHXt23pfJvs6hOzpi4JA3h1s0QEjjwkUMIaYxqHn4FynB3OI///79f7nd@gxTCF@//szDoI/8EUS0DCZgTBCZJwKba1UkSKQdlOeMs6l4pQLq1ioKCOQdRvDFGdGME211v2KRSkB0@1SybWUKbM0FdYarqyKgg/vFTlVkSEgO6CNZibVkqrMZJ1IpAmIPo5SygRbrdIwVUNIGzSZMVYHc2ql5IJ9ViQGa5FpKjLVxfx6S3OlLOdGDt8NNx8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 69 bytes
Expects `(m)(n)`. Returns `[numerator, denominator]`.
```
m=>g=(n,N=0,D=1)=>n?g(n-1,p=N*n**m+D,q=D*n**m):D?g(0,D,N%D):[p/N,q/N]
```
[Try it online!](https://tio.run/##PU/LrtMwEN3nK0ZXQrFbN/bYiR9F7t0EltncZW@RqjYtQa3TJgUJIf4AiQ1L@A@@5/4An1CcEDGLkT3nzDlnPmw/bftd11xui9Du6/vB389@dfQksMoLVnqkfhUejyQskF18NQuz2XlesqsvxyddlhGMRFa9KulyfeEVu/Jqc@/q68emq0l66FOadfV2/7Y51U@fw44Imt3ap1vXhCOhWX85NTfy8BweaHZouzfb3XvSg1/BlwRgHRicGXR1vwEP/UTm63f8eb@Zc/o6cnZt6NtTnZ3amHKkrysG5bBwIGdKAmVQwRxSnsZegveDHjxC@uf395efP2JPYQnpy69vaRT8Su@KgYHFCqSVskAujXNKJ5pBPkwxF4hKI0fptIiVFAyKAbFCo7BSGG6MGSGR5AzsgOUKjVK5cDyXzlnUTifRB0dF5DqxDNTwMdYImxvFdWGLQSQxDOQYR2tto63ReZzqKaSLmsJaZ6I5d0qhFP8qkZO1LAyXhR5i/j/LoNYO0arpumnnLw "JavaScript (Node.js) – Try It Online")
### How?
The recursive function \$g\$ first computes the unreduced numerator and denominator \$(N,D)\$ of \$H\_{n,m}\$ and saves a copy of the final result into \$(p,q)\$:
```
n ? g(n - 1, p = N * n**m + D, q = D * n**m) : ...
```
When \$n=0\$, it enters its 2nd phase where the GCD of \$(p,q)\$ is computed in \$N\$:
```
... : D ? g(0, D, N % D) : ...
```
When \$D=0\$, it eventually returns:
```
... : [p / N, q / N]
```
[Answer]
# [J](http://jsoftware.com/), 13 bytes
```
1#.(%@^~1+i.)
```
[Try it online!](https://tio.run/##VZDLakIxEIb3fYqhpVhpe5hLMhdBKBRcufIB3JRKdSPkAXz10zmaQ20gm3xf8v@Z0/g4LA6wXsEC3gBhlft9gM/ddjPS0/Dy/LG/0OtxWI7Lh@@vnzOwM1dqbBGisAaDAwjcGBUkEqVGHIq5kpfk2rmjEjqjNTO7CpNR06jdKEImUjBa4QgnjSnD0yhzBrXpiO5izQ29mDStXvX2qCT3zllVPUuZlivjZNZZZBa6h2W1FiLEiHMxu6vO1RrXuQzD3zCMVIPIpc/k//382PgL "J – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
```
*€:@S,:gɗɗP$
```
[Try it online!](https://tio.run/##y0rNyan8/1/rUdMaK4dgHav0k9NPTg9Q@X94uX7Wo4a5@pqR//9HG@somMfqKESb6SiYgGhTHQVTEG2io2ABooHyhiDaQkfBGESb6ygYQdWD9RlB1ZmC@AA "Jelly – Try It Online")
A byte less than `*€µP:¹S,P:g/$`, but the abuse of `ɗ` leads me to believe this can be shorter yet.
```
*€ Raise each 1 .. n to the power of m.
ɗP$ For that list and the product of its elements:
:@ divide each by the product
S and sum;
ɗ for that sum:
, pair it with the product,
: and divide both by
g the GCD of the sum and product.
```
[Answer]
# Java, ~~155~~ 138 bytes
```
int g(int a,int b){return b<1?a:g(b,a%b);}
m->n->{int p=1,d=0,t;for(;n>0;d=d*t+p,p*=t)t=(int)Math.pow(n--,m);return d/g(d,p)+"/"+p/g(d,p);}
```
[Try it online!](https://tio.run/##ZU89b4MwEJ3jX2FFqmSDcRJ1qFQHulXqkClj1cFgoKZgW@ZIFSF@OzWtt95wd@/dx7vr5E1mnfpa9eCsB9wFzCfQPW8mU4G2hicCuansdYWrXo4jvkht8IxwsMiPICGEm9UKD6FKruC1ad8/pG9HOqPda9x1fjNQt7Vn/4i/iaJo8nXICpMVszaAXX5iKj8yEI31RJjiKFSuEkgdc0kOFHIS2uhFwid39puYLGMDFb6GyRusDi1RzNF0f9inLgKxrDuBdtf7CPXA7QTcBWXoDWm4dK6/kycak0dKxe@bS/wQbTe1mySWbPMlnaNWeT69yOeWlEw@lEEELesP)
$$Denominator\_{n, m} = \prod\_{k=1}^n k^m$$
$$Numerator\_{n,m} = \sum\_{k=1}^n \frac {Denominator\_{n,m}} {k^m} = Numerator\_{n-1,m} \times k^m + Denominator\_{n-1,m}$$
# Java + Commons Lang 2, 127 bytes
```
m->n->{org.apache.commons.lang.math.Fraction x=null;for(x=x.ZERO;n>0;)x=x.add(x.getFraction(1,(int)Math.pow(n--,m)));return x;}
```
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, ~~35~~ 24 bytes
```
[ [1,b] 0 rot - v^n Σ ]
```
[Try it online!](https://tio.run/##VVFNT8MwDL33V5g7W@J82AlIuyIuXBCnaUilBJjG2qoNk1C1X8P/4S@V0LUdOFKk2O89PzsveRGrpn@4v727uYK8bauihX0e34Zr2eTla2hhF5oyvJ9SH@W2qJ7D6XEIv/QW6ibE@Fk32zLCdZZ1GaTogEHDES5gsQLllLIoFHuvaSwboKmMRiJqQoHKk0wxQmw6I8RJQumUZMHMA2YCuaQ0goxG1tpIL4zy3iH5qRmevSCKKasTecyyY@kMa0HWWTqrqzTGNAQRueSRycxlPg/hU1/pnOfkVHitUUn536ealSwLZWnWsH/3xEjkEZ0e1zWpHPs1rPHyaQMSmirCAg6PJXx/wabvEn/4vdU@r6GNebFb9j8 "Factor – Try It Online")
*-11 thanks to @Bubbler!*
## Explanation:
It's a quotation (anonymous function) that takes two integers from the data stack as input and leaves a fully-reduced mixed fraction (it's simply the way that Factor is) on the data stack as output.
* `[1,b]` Make a range from `1` to `n`.
* `0 rot` Push `0` and bring `m` to the top of the stack.
* `-` Subtract `m` from `0`.
* `v^n` Raise every element in the range to the `-m` power.
* `Σ` Sum.
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
1#.#\@$^-@]
```
[Try it online!](https://tio.run/##TZC5agMxEIb7PMUQB0wgXuaQ5jAYDAZXqVLbaUJMSGNQ5bdfS15tsgIV0nz8x/yOz8P6ArstrOENELb1bgY4fLwfR1oNq9P@5XOzP4@vT99fP1eQG1yAb9ODnTlTYYsQhd00tD6khESiVIhDsZ4KaANSBxyV0BmtmNmDaEhuSO5IEjKRhFESRzhpNJvUEJ9tqPxZU/8zN/RkUjR71knXGyBzcFX1msw0PYa2bBXVD93Dar4SIsSIuCwwN@RshXNz52WithUj1SBy6cv5V8iTwngH "J – Try It Online")
TFW J beats Jelly...
Used as `n f m`, where `n` and `m` are given as extended-precision integers.
### How it works
```
1#.#\@$^-@] NB. dyadic train; left = n, right = m
#\@$ NB. 1..n in a dyadic context:
@$ NB. reshape m into dimension n, and then
#\ NB. get the lengths of prefixes
^ NB. each raised to the power of
-@] NB. -m
1#. NB. sum of them
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 14 bytes
```
ɾ$eDΠ$/∑$Π":ġ/
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C9%BE%24eD%CE%A0%24%2F%E2%88%91%24%CE%A0%22%3A%C4%A1%2F&inputs=8%0A3&header=&footer=)
[Answer]
# [Nim](http://nim-lang.org/), 81 bytes
```
import math,rationals
func H(n,m:int):any=
var r=0//1;for i in 1..n:r+=1//i^m
r
```
[Try it online!](https://tio.run/##PcvBCsIwDADQe78iR4thtWxT6ejdrxDCcCxg0xGrsK@vHqS3d3nCqVZOW9YCicqKSoWz0PNllrfMcDsIpsBSbCDZo4EPKWg8OeenJSswsIDvOgl6jN45vicDWh/zmn@3x4s1f59xaB5xbB7w2tyjt/UL "Nim – Try It Online")
[Answer]
# Haskell, 28 bytes
```
n#m=sum$map((1%).(^m))[1..n]
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ê☺σ;vù
```
[Run and debug it](https://staxlang.xyz/#p=8801e53b7697&i=+7+,3%0A+4+,6%0A+5+,5%0A+8+,4%0A+1+,3%0A+3+,8%0A+2+,7%0A+7+,6%0A+8+,2%0A+7+,5%0A&m=2)
just another trivial answer.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 27 bytes
```
->n,m{(1..n).sum{|x|x**-m}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ7daw1BPL09Tr7g0t7qmoqZCS0s3t7b2f4FCWrSxjnnsfwA "Ruby – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 91 bytes
```
import math
f=lambda n,m,N=0,D=1:n and f(n-1,m,N*n**m+D,D*n**m)or(N/(G:=math.gcd(N,D)),D/G)
```
[Try it online!](https://tio.run/##PVHJTsMwEL3nK@YWu0ypl8RLpXCK1Ft/ADiUJKUVxIkSIwFVv73Ybosvb@Z55s02/vjD4KQZp8vl2I/D5KHf@UO2rz53/Vu7A4c9biuGdcXXDnauhT1xSx7ZhVss@oca62TQYSLbFdmsqyjw@N60ZIs1pVivNvTiu9nPUAEhEkFTBKIQioglQhmxQDARwz@PaBBkRI0gbvEpT9ziyujTrPseu8Z3bdIWRoiShwRtrVQxiheMc6kCx4VVLLykzRRnRrCgrbVOdOILybWUBbOhN2Gt4cpeVUJ@MrTRzBQ69KhKU6pbmlBKmVhCq@LK2KDBjLGaxdJWSi4Y@y8jyjhUmRRjy5orZTk38t75PZZmzaFrPropTpe/fAldNDlCsrjMabYfJvDYwdHB73EkacsI953QdQbhOYQegoJPXrxCOGHgaPLH6eg82ecnd0Y49WdYPsFpPsPpVvq5q6r59ZzTyx8 "Python 3.8 (pre-release) – Try It Online")
Inputs \$n\$ and \$m\$ and returns the numerator and denominator of \$H\_{n,m}\$ as a tuple.
Uses the formula from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/225865/9481).
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~31~~ 27 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{(⊢÷∨/){⍵,⍨+/⍵÷x}∧/x←⍵*⍨⍳⍺}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q9Z41LXo8PZHHSv0Nasf9W7VedS7QlsfyDi8vaL2Ucdy/YpHbROAXC2g@KPezY96d9UCAA&f=RY65FQIxDERzqlBoRzqtoyFKISOgAHLqoJStBO@uAUXz/ow02m6PK75f0BSiNwfrbcDozSD7ZNxbgvYWILs7I7IbY6rLdn@CpMhglKhSPwgbMaszspTTnIMmOVMKBUbEgU9uyqFqVGhSley1rjCeIjIoLRR95PDvmrh7zopwW6TmDcqsmEVYqixE/xoZgTL893KwezGnrs9X9gM&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f)
`(⊢÷∨/){⍵,⍨+/⍵÷x}∧/x←⍵*⍨⍳⍺` is equivelent to `x←(⍳⍺)*⍵⋄(⊢÷∨/){⍵,⍨+/⍵÷x}∧/x`.
APL translated to Python:
```
from math import *
def H(n, m):
x = [i**m for i in range(1,n+1)] # x←(⍳⍺)*⍵
tmp = lcm(*x) # ∧/x
tmp = (sum(tmp//i for i in x), tmp) # {⍵,⍨+/⍵÷x}
tmp = [e//gcd(*tmp) for e in tmp] # (⊢÷∨/)
return tmp
```
First I make a list from `1` to `n` -- `⍳⍺`.
Then I raise every element of the list to the power of `m` to calculate the value of all the denominators, and assign it to the variable `x` -- `x ← (⍳⍺)*⍵`.
I then calculate the denominator after all the fractions are added together by taking the least common multiple of all the elements of `x` (all the denominators) -- `∧/x`.
Next I create a two element tuple, the second element of which is the denominator -- `{⍵,⍨...}`. The first element is the numerator, calculated as the sum of the denominator divided by each of the original denominators -- `+/⍵÷x`.
Lastly, I simplify the fraction by dividing it by it's gcd -- `(⊢÷∨/)`.
[Answer]
# Excel, 70 bytes
```
=LET(k,SEQUENCE(A1)^B1,d,PRODUCT(k),n,SUM(d/k),g,GCD(n,d),n/g&"/"&d/g)
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnCkQ0jwaai8YU5Ye?e=F4CVhU)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
≔X…·¹NNθ≔Πθη≔Σ÷ηθζ⊞υζ⊞υηWζ«≔﹪ηιζ≔ιη»I÷υη
```
[Try it online!](https://tio.run/##ZY3LCsIwEEXX5iu6nIAuBBdCV6KbLpSiXxDT0Aykic2jhYrfHlNtUXE3M/eeM1wyyw1TMe6cw1pDaXphodBcBYedODNdC1gvs0Lfgj@F5ppSSv/3luZkVlhTBe6hTWf5OV9Ck7z@gB1WAuSIpMKQCmVwEsLvPIK9RCUyGGh2J4vJckxuZUYcJ3pO8A09SGlRe9gz57/@vZSU5jFuyDauOvUE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔X…·¹NNθ
```
Generate the first `n` powers of `m`.
```
≔Πθη≔Σ÷ηθζ
```
Calculate the product, then divide that by each power and take the sum.
```
⊞υζ⊞υη
```
Save the values for later.
```
Wζ«≔﹪ηιζ≔ιη»
```
Find the GCD.
```
I÷υη
```
Divide the saved values by the GCD.
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 111 bytes
```
fmod H is pr RAT . op __ : Nat Nat -> Rat . vars N M : Nat . eq 0 M = 0 . eq(s N)M = 1 / s N ^ M +(N M) . endfm
```
### Example Session
```
\||||||||||||||||||/
--- Welcome to Maude ---
/||||||||||||||||||\
Maude 3.1 built: Oct 12 2020 20:12:31
Copyright 1997-2020 SRI International
Tue May 18 23:37:06 2021
Maude> fmod H is pr RAT . op __ : Nat Nat -> Rat . vars N M : Nat . eq 0 M = 0 . eq(s N)M = 1 / s N ^ M +(N M) . endfm
Maude> red 3 7 .
reduce in H : 3 7 .
rewrites: 17 in 0ms cpu (0ms real) (17206 rewrites/second)
result PosRat: 282251/279936
Maude> red 6 4 .
reduce in H : 6 4 .
rewrites: 40 in 0ms cpu (0ms real) (~ rewrites/second)
result PosRat: 14011361/12960000
Maude> red 3 1 .
reduce in H : 3 1 .
rewrites: 17 in 0ms cpu (0ms real) (~ rewrites/second)
result PosRat: 11/6
Maude> red 2 8 .
reduce in H : 2 8 .
rewrites: 10 in 0ms cpu (0ms real) (~ rewrites/second)
result PosRat: 257/256
Maude> red 5 7 .
reduce in H : 5 7 .
rewrites: 32 in 0ms cpu (0ms real) (~ rewrites/second)
result PosRat: 2822716691183/2799360000000
```
### Ungolfed
```
fmod GENERALIZED-HARMONIC-NUMBERS is
protecting RAT .
op H : Nat Nat -> Rat .
vars N M : Nat .
eq H(0, M) = 0 .
eq H(s N, M) = 1 / (s N ^ M) + H(N, M) .
endfm
```
`H(N, M)` is the naive recursive definition of \$H\_{n, m}\$. Maude's built-in rational number module automatically reduces fractions to lowest common denominator.
There's not *much* golfing we can do because only a handful of characters can separate identifiers (`(`, `)`, `[`, `]`, `{`, `}`, `,`, and space). I've renamed the function operator `H` to `__` (juxtaposition of two values) in the golfed version to save a few bytes.
[Answer]
# MATLAB/Octave, 25 bytes
```
@(n,m)sum(1./sym(1:n).^m)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPJ1ezuDRXw1BPv7gSSFnlaerF5Wr@T7NNzCu25krTMNYx1wRSZjomIMpUxxREmehYaILlDEGUhY4xiDLXMYKoBGswgigxBfL@AwA "Octave – Try It Online")
Anonymous function. Returns accurate value of symbolic type, which can represent real numbers (so rational numbers including).
Unfortunatelly, to my suprise, MATLAB doesn't implement that function, only non-generalized harmonic numbers (so only for ).
]
|
[Question]
[
What general tips do you have for golfing in 2 dimensional programming languages? I'm looking for tips which can be applied to code-golf problems and are specific to 2D programming languages, but not specific to any one language (Responses like "remove comments" and "use the `M` operation" are not answers).
Please post one tip per answer.
[Answer]
# Avoid horizontal gaps
Often, code will leave largs gaps of whitespace to the left hand side of the program, like so.
```
abc
d
e
```
This adds 4 bytes, when this could be avoided by left aligning.
```
cde
b
a
```
If you need to use large gaps of whitespace, try to make them vertical, instead of horizontal.
```
########
# #
# #
# #
```
vs
```
####
#
#
#
#
#
#
####
```
[Answer]
# Carriage Returns Are Bytes Too
The less 2D you can make it, the better. A carriage return is another no-op. Without ignoring the tips from @ATaco and @ASCII-only, try and keep the Y dimension as small as possible.
This
```
###
####
########
```
is better than
```
###
###
###
##
#
#
#
#
```
[Answer]
# Use one dimension when possible
Typically, simpler programs can be written on a single line. For example, the classic cat program could be:
```
>iv
^o<
```
But one could abuse the wrapping behavior and make this:
```
io
```
Or, in languages without such wrapping behavior:
```
> ?oi<
```
(Assuming `?` doesn't pop.) In the case of a non-wrapping language, an explicit loop is often better.
## With jump commands
In 2D languages with jump and conditional jump commands, a program could look like this:
```
abc >de?v;
^hgf<
```
This could also be:
```
abc de?!;hgf04&
```
(if `!` is a trampoline, and `&` is jump to position)
[Answer]
# DRY (Don't Repeat Yourself)
While abstracting with functions is usually longer in Code Golf, it can really help for 2D languages. Try to rework your code so it can re-use the same snippet, entering/exiting it with two different branches of execution.
[Answer]
# Interleave paths
Usually in a 2D language there is an IP that moves according to direction commands. Since spaces are wasted bytes, it is almost always more efficient to rearrange the program so it moves closer to the left as often as possible, saving the need for unnecessary padding spaces.
[Answer]
# Use mirrors
Mirrors can sometimes be used in two paths at the same time (each path bounces off one side of the mirror). This may not seem to help, but it may allow you to rearrange your program, or if you have a lot if direction changes they may be able to be replaced with fewer mirrors.
[Answer]
# Memorize idioms
Here are a few "idioms" that do certain things, depending on the nature of the language.
## Pseudo-linear code
If dynamic code generation is ever required, it may be of use to use the pseudo-linear code model:
```
v
\"line 1"
\"line 2"
.
.
\"line N"
```
Assuming `\` and `v` mean what they usually do.
## Infinite loop
In almost all 2D languages, `><` is an infinite, unbreakable loop. If, for some reason, you need to do this, this is the best way, despite how nice this might look:
```
>v
^<
```
In fact, if you [make your code a 1-liner](https://codegolf.stackexchange.com/a/120987/31957), you could just use `^` or `v`, as such:
```
i?vo;
```
This `v` will send the IP to itself, wrapping around. You may still be able to use this approach in any instance where a directional command points to a series of (relative) no-ops.
## Quine framework
Usually, languages with a string/quote framework can have a quine like this:
```
<quote><generate "><output stack><terminate>
```
For ><>, this would look like:
```
":1-r>o<#
```
Except this one exits with an error as termination. It is probably the shortest [><> quine](https://codegolf.stackexchange.com/a/120991/31957), or, at least, the shortest one that I have found.
]
|
[Question]
[
**This question already has answers here**:
[Shorten text with Run Length Encoding](/questions/7320/shorten-text-with-run-length-encoding)
(28 answers)
Closed 4 years ago.
Write a program uses [run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) to shorten a list of non-negative integers it has to read in.
You can assume the non-negative integers can fit in 32bit signed integers.
**Input Format**
The length, `n`, of the list on the first line.
On the second line, a space-separated list of integers representing the list of integers.
**Output Format**
A space separated list of integers. The first 2 integers represent the first run, the next 2 integers the second run and so on. For each pair of integers representing a run, the first integer represents the length of the run and the second represents the value of the integer in the run.
**Sample Input**
1.
```
5
1 1 3 2 2
```
2.
```
3
1 1 1
```
**Sample Output**
1.
```
2 1 1 3 2 2
```
2.
```
3 1
```
**Limits**
```
0<n<10000
```
[Answer]
# sh - ~~33~~ ~~29~~ 28
```
read;echo`xargs -n1|uniq -c`
```
Usage:
```
$ cat input|sh 1015.sh
2 1 1 3 2 2
```
* `read` skips the first line
* `xargs -n1` reads the reast and outputs each number on one line:
```
1
1
3
2
2
```
* `uniq -c` filters adjacent matching lines (with the `c` switch it also prints the number of adjancent lines) :
```
2 1
1 3
2 2
```
* `echo` sees those numbers as separate arguments and just prints them separated by a space:
```
2 1 1 3 2 2
```
[Answer]
## Perl, 46 ~~56~~ ~~68~~
```
$_=<>;s/(?{$a=1})(\d+)( \1(?{++$a}))*/$a $1/g
```
Run with the `p` command-line option (counted in code size):
```
$ perl -pe '$_=<>;s/(?{$a=1})(\d+)( \1(?{++$a}))*/$a $1/g'
5
1 1 3 2 2
=> 2 1 1 3 2 2
3
1 1 1
=> 3 1
```
[Answer]
## Haskell (~~84~~ 82)
```
import List
main=interact$unwords.(>>= \x->[show$length x,x!!0]).group.tail.words
```
Number of elements in the list is ignored.
[Answer]
# Ruby - 57
```
$><<[*$<][-1].gsub(/(\d+)( \1)*/){"#{$&.split.size} "+$1}
```
Ungolfed:
```
length = STDIN.readline
input = STDIN.readline
print input.gsub(/(\d+)( \1)*/) { |match|
"%d %s" % [ match.split.size, $1 ]
}
```
[Answer]
## Python - 92
Here's my attempt, which is mostly what I had before I posted this question, though for some reason I used a literal space instead of a comma.
```
from itertools import*
r=raw_input
r()
for k,g in groupby(r().split()):print len(list(g)),k,
```
[Answer]
# Scala - 136
```
def f(s:Seq[_]):String=if(s.isEmpty)""else{val(l,r)=s.span(s.head==);l.size+" "+s.head+" "+f(r)}
readLine
println(f(readLine split' '))
```
[Answer]
# Scala - 101 characters
This is based on the regex solution. I didn't know this was valid regex in Java, actually! (Scala's regex is based on Java's)
```
print("(\\d+)( \\1)*".r.replaceAllIn({readLine;readLine},m=>(m.matched split' 'size)+" "+m.group(1)))
```
[Answer]
# R, 33 bytes
Late answer....
```
cat(t(mapply(c,rle(scan()[-1]))))
```
Ungolfed
```
scan()[-1] # read in from stdin [-1] drops first element
rle(..) # perform run length encoding (return list with lengths and values)
mapply(c, list) # converts list to matrix
t() # transposes this matrix so when extracted as a vector is length value ...
cat() # writes to stdout (separated by space)
```
[Answer]
## Python - 106 chars
Very simple conceptually, but some very expensive words weigh it down
```
from itertools import*
input()
print" ".join(`len(list(j))`+' '+i for i,j in groupby(raw_input().split()))
```
[Answer]
**C 101 Characters**
```
#define p printf("%d %d ",c,l)
main(c,i,l){gets(&i);for(c=0;~scanf("%d",&i);l=i)i!=l&&c?p,c=1:c++;p;}
```
[Answer]
**Python 100 Characters**
```
c=l=0
input()
for i in raw_input().split():
if i!=l and c:print c,l,;c=1
else:c=c+1
l=i
print c,l
```
[Answer]
## Python - 110 chars
```
import re;R=raw_input;R()
print" ".join(`len(x[0].split())`+' '+x[1]for x in re.findall(r"((\d+)( \2)*)",R()))
```
[Answer]
# Golfscript - ~~40~~ 39
```
~-1](;(:<1\@{:b={)<}{' '<' '1b:<}if}/;;
```
[Answer]
# CJam, 11 bytes
```
l;l~]e`e_S*
```
[CJam interpreter online](http://cjam.aditsu.net/#code=l%3Bl%7E%5De%60e_S*&input=36%0A1%201%201%201%201%201%203%203%203%203%203%202%202%207%207%207%207%204%204%209%209%209%209%209%209%209%209%209%204%204%208%203%203%203%203%200) (test case provided by [this](/questions/1015/run-length-encoding#comment6753_1015) comment).
Explanation:
```
l;l~]e`e_S*
l Get input line
; Remove ToS
l Get input line
~ Evaluate code
] Wrap the stack in an array (from [-mark)
e` Run-length encode
e_ Flatten
S Space (' ')
* Join
```
[Answer]
## [Retina](http://github.com/mbuettner/retina), 23 bytes
Thanks to @MartinEnder who helped me save 23 (!!) bytes and helped me understand some new features to (hopefully) produce better examples of Retina code in the future!
```
A1`
(\d+)( \1|)*
$#2 $1
```
### Explanation
The first line is AntiGrep with a limit of 1 to remove the first line. Then we match any integer followed by either a space and the same integer or nothing which handles our count correctly, so we can just replace with the number of matches of group 2 (`$#2`), and the original integer (`$1`).
[Try it online!](http://retina.tryitonline.net/#code=QTFgCihcZCspKCBcMXwpKgokIzIgJDE&input=MzYKMSAxIDEgMSAxIDEgMyAzIDMgMyAzIDIgMiA3IDcgNyA3IDQgNCA5IDkgOSA5IDkgOSA5IDkgOSA0IDQgOCAzIDMgMyAzIDA)
[Answer]
# Scala - 141 chars
a purely functional scala solution. i am using 2 hacks here (beginning and end markers = "a", have to cut them off at the end :()
"a" is the program parameter
the full working code is
```
package hstar.randomstuff
import tools.nsc.io.File
/**
* Developed with pleasure :)<br>
* User: HoD<br>
* Date: 28.07.11<br>
* Time: 19:37<br>
*/
object RLEEncoder {
def main(a: Array[String]) {
print(((0,"","")/:(File(a(0)).lines.toSeq(1).split(' '):+"a"))((a,c)=>if(a._2!=c)(0,c,a._3+' '+a._1+' '+a._2)else(a._1+1,c,a._3))._3.drop(4))
}
}
```
the actual logic is
```
print(((0,"","")/:(File(a(0)).lines.toSeq(1).split(' '):+"a"))((a,c)=>if(a._2!=c)(0,c,a._3+' '+a._1+' '+a._2)else(a._1+1,c,a._3))._3.drop(4))
```
[Answer]
# Scala - ~~247~~ 196
(+ 4 separators)
Being a beginner at Scala, I found the challenge interesting for a functional approach, but I fear I haven't took a concise approach. I guess a seasoned Scala coder will make a one liner... Particularly if I missed a useful collection method!
Anyway, here is the golfed version, even if it is out of competition:
```
readLine;val n=(readLine+" z").split(' ')
def g(v:String)={var a=1
(n:String)=>{if(n==v){a+=1;Nil}else List(a,v)}}
var p=g(n.head)
print(n.tail.flatMap{n=>val r=p(n);if(r!=Nil)p=g(n);r}.mkString(" "))
```
I feel the newlines should be counted (as spaces) as here they are mandatory separators. But well, the Python scripts above doesn't count them (while they are mandatory too), so I hadn't either...
The uncompressed version, with comments for my own benefit:
```
// Read the stdin, skipping the first line, returning the second one
// cat input.txt | scala RLE.scala
readLine // Thanks Daniel!
val line = readLine
// Add an arbitrary symbol that is dropped in the process... (trigger last sequence processing)
val numbers = (line + " z").split(' ')
println(numbers mkString " ")
/** Returns a closure to process the given value in the sequence to come */
def getSeq(value: String) =
{
var acc = 1
// Make a closure over value and acc
(n: String) =>
{
if (n == value)
{
acc += 1
Nil
}
else // Different value, return the cumulation so far
{
List(acc, value)
}
}
}
var process = getSeq(numbers.head) // Initial closure
/** Processes the numbers in the sequence. */
def accumulate(n: String) =
{
val p = process(n)
if (p != Nil) // We got a result
{
process = getSeq(n) // We need a fresh function over the new sequence that starts
}
p
}
println(numbers.tail.flatMap(accumulate).mkString(" "))
```
Feels clumsy with ugly hacks (the additional symbol, using head and tail...) but at least it works...
[EDIT] I used some of the tricks shown by Daniel Sobral to shorten a bit my code. I kept my original design/algorithm to be distinctive... :-)
[Answer]
# JavaScript, 126 bytes
```
(x,j=0)=>(x=x.split` `).reduce((a,v,i)=>(v!=x[i-1]?(a[++j]=[]):a[j]).push(v)&&a,[]).reduce((a,v)=>a+v.length+" "+v[0]+" " ,"")
```
I'm guessing this can be reduced further, but I'm just happy it works.
First I split based on the space, then I convert the array from [1,1,1,2,2,3,3] to a series of array representing each run [[1,1,1],[2,2],[3,3]], then I reduce that again to produce the required output of "3 1 2 2 2 3".
[Answer]
# Stacked, noncompeting, 34 bytes
```
([prompt]2*eval)behead flatrle out
```
Confirms strictly with the IO format. [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html)
Or, we can use the builtin for 7 bytes: `flatrle` (or `$flatrle`).
]
|
[Question]
[
>
> Yes, I know there is a [similar question](https://codegolf.stackexchange.com/questions/5136/code-golf-word-unscrambler), but this one specifically concerns any possible words, even with letters left over, while the linked one restricts to a permutation of the input
>
>
>
## Objective
Have you ever had those moments in a Scrabble game where you're staring at your letters, trying to find a good word, and your mind is just blank? Some of us feel cheaty and turn to word unscrambling software like [this one](https://wordunscrambler.me/) to help us. This challenge is to build your own word unscrambler.
Given a list of possible words and a string of characters conforming to the regex `([A-Z]|[a-z])+`, your program has to find all the words whose letters are all found in the scrambled string.
Sample inputs:
```
asto, [as, so, to, oats] -> [as, so, to, oats]
asto, [as, to] -> [as, to]
ast, [as, so, to] -> [as]
zzyzx, [as, to, so] -> []
trom, [as, to, too, or] -> [to, or]
roomt, [as, to, too, or] -> [to, too, or]
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
œ&ƑƇ
```
[Try it online!](https://tio.run/##y0rNyan8///oZLVjE4@1/z@8XMn7UdOayP//o5USi5V0FJSK80FkCZjMTywpVorVUYDJAUWReHCVqCogMhhiJfkQI4vwSv0HSkAEkWgQVVVVWVUBVlyUnwuii/Lzc0uUAA "Jelly – Try It Online")
## How it works
```
œ&ƑƇ - Main link. Takes a list of words L on the left, a word W on the right
Ƈ - Keep those words from L such that:
Ƒ - They are unchanged after taking:
œ& - The multiset intersection with W
```
[Answer]
# [Vyxal 2.6pre1](https://github.com/Vyxal/Vyxal/releases/tag/v2.6.0pre1), ~~5~~ 3 bytes
```
Þ×↔
```
[Don't Try it Online! (the site runs a few commits 2.4.1)](https://lyxal.pythonanywhere.com/?flags=r&code=%C3%9E%C3%97%E2%86%94&inputs=%27zzyzx%27%0A%5B%5B%27a%27%2C%27s%27%5D%2C%5B%27t%27%2C%27o%27%5D%2C%5B%27o%27%2C%27r%27%5D%2C%5B%27m%27%2C%27o%27%2C%27s%27%2C%27t%27%5D%5D&header=&footer=)
Haha builtin go brr.
-2 thanks to Lyxal.
```
↔ # The elements in common between
Þ× # All combinations of the letters
# And the input.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
lambda s,l:[w for w in l if all(w.count(c)<=s.count(c)for c in w)]
```
[Try it online!](https://tio.run/##jY7NTsQwDITvfYq5JZHCSnBcEV5kWaFQWm2ktI4Sl7B9@ZK0YmH5kTjZY38zdjjzica7pTePi7fD84tF0n5/yOgpIsON8HA9rPcy71qaRpatujfp0leurVxWx8UNgSIjdk0@Od/hdt9AJg2vNGjiAIPBBtm9Wq8RbX5yY5hYql0K3rEUuHmAUKpBiG5k9JsXxqzuRdjEJDQOpSlFpCrEOhJkOYljDfh723wPKOLKUvUK/XbkkyzMPJ/nt@ukjd2oQnCk4QfAtL0TP9L4ohsRiQb@r@XL@B0 "Python 2 – Try It Online")
[Answer]
# [Python 3.10](https://docs.python.org/3.10/), 74 bytes
```
lambda w,l:[x for x in l if C(x)<=C(w)]
from collections import*
C=Counter
```
[Attempt This Online!](https://staging.ato.pxeger.com/run?1=fY87DsIwEET7nGLlKkahR4hU7rgCpAghFpZsb2RvlM9VaCIhuBOX4AwEQmN-1ezsPo12jpeqowPa4STT7bkmOV9c1zo3u30OTaKXmxYkOmhBWdCgJIi45atUxA3PIunQQIFalwUptB6UqdDRLBKpwNpS6V6Jt8opS7GMWe4JWQKbcRiF-YdhzxXDnDzLOI9-waN5P3-LCpi-7_o2zJjYgKKxyAdEOL3lQtYhGvoPT62HYdI7)
In versions before 3.10 `C(x)<=C(w)` would have been `not C(x)-C(w)` instead.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
s=>l=>l.filter(w=>w.map(g=c=>g|=w[c]=s.indexOf(c,w[c]+1))|~g)
```
[Try it online!](https://tio.run/##fZFBboMwEEX3PsXssBVi1HVkdl33AMRSHGIoETCRPSo0pb06tZMmJVJVyYvx/99vNOOjeTO@dM2J1j0e7Fyp2au8DUdWTUvW8UHlg@zMideqVHk9qaEotfKy6Q92fKl4mUZh9STE9FWLmayn0njrQcGOGU@YQmF8Cj4U8YKGvIZ1/oe6jBP@hkIdrQfQzdXsfH4/j/dX0b96mpHDbmEQxkbu6tK1Zg6xo/9CN4HtJLmm40L6U9sQT7Z9IjbsPq@s0D2b8pW3TW9B5fDBAErsPQV4CvsUrA47ie4PIUthW0yxURZAtzCGUMULKaXRgu/D6ilAs@2wympx@Ygx0mNg1GKhjPKITc@TRNxp2FrZYn2hoZYeHXEBK0gSUAq4fYTDNIWtiWUsTB5gn2IzfwM "JavaScript (Node.js) – Try It Online")
Input / output words as list of characters.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
->b,a{a.select{|w|d=b*1;w.all?{|c|d[c]&&=''}}}
```
[Try it online!](https://tio.run/##bc9BDoIwEAXQPaeYjVRNbeJWgx6k6WJaMCwgQ9oahLZnryxIxOj2vz@ZfPvUU35U@XTTHAMK13SN8SGOsa708XwdBXbdPUQTa2lUWVaMpZSyLEAydJ4Yh90o0YEj8ASE3inFf9TTJ/0@WfN5nubXpr7gKt5SvwVPyxu7oiXq/T8tlGjQtCEusyIM8JCaA4oeh315MS1ad1ApvwE "Ruby – Try It Online")
Takes the list of tiles as a string; words are input and output as lists of characters. The inconsistent formats can be avoided at a cost of a few extra bytes: [47 bytes](https://tio.run/##bc9BDoIwEAXQPafoRqqm9gAa9CBNF9MCcQEZ0o5BaHv2SgyJGF3Of38yGfcwU26rfLoaAQGkb7rGUohjrCtz5PwySui6W4g21srqsqw4TyllVTDFwRNywXajAs88MkKGQF5r8aOEn/R7Zc3neZqfm/qCq5DDfguEyxm3okPs6Z8WWjZg7yEuf0U2sFYZae/gvGAgexj25fk9HnTKLw "Ruby – Try It Online") to use lists of characters exclusively and [52 bytes](https://tio.run/##bc3BCoMwEATQu1@xlxoQG@i52H5IyGGNigdlS7Il1STfnnoQammv82YY@2yXPDT5fGtrDChdP/WGQ/Sxa9rqcvXSjGidxGm6h2hip4wuy0aIlFJWBSiBjknUcPIKHTgCJiBkp3X9o0yf9Huy5@u6rK9DfcNd2NJ8BKbtxu5oiWb@p4WWPZoxRI7wgEFVrFN@Aw "Ruby – Try It Online") for strings.
All variants work the same way. For each letter of a word, remove the first occurrence of that letter from the list of tiles or return `nil` (falsy) if there is no such tile. The word can be formed if this procedure succeeds for all its letters.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 53 bytes
```
[ <permutations> '[ _ [ subseq? ] with ∃ ] filter ]
```
[Try it online!](https://tio.run/##fZC9asNAEIR7PcXgJlX8APlRypAmjUkljDlfVviw71baXSFLxlWaPGdeRDlQEoIh2WqZb3YHpnbeWKaX1dPz4w2is93Sc9yG5LIcvM5Sl4LnV0ItA5TajpInxZ4k0QGNkNnQSEiGxgW5FvZ7MjhVzg/aHrdFcSqQp@1PWYYyjMHOFGfcl1g4NV78dmT8B5lvf@DllX6zcRzG4yU1zrHy5TDh@K9BmGMOOE8V7hqS2JmzwElLXFXYoIJ229zGA9bog@3w8f6W1zocjATrqZ4bKKNrsJw@AQ "Factor – Try It Online")
In plain English, select all words from the dictionary that appear in any permutation of the scrabble letters.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
Φη⬤鬛№ιλ№θλ
```
[Try it online!](https://tio.run/##JYqxCoAwDER/pWSqUL/ASQTdxL10KCJYiAZj9PdjbW@44z1u3SOvFFF14XSKHRPKxnZ3pke0yZmZxE68xd8O9ORLltg4U@H6oaRT9cBEh4AzHuKdB4RqlyGGELR98QM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
η Word list
Φ Filtered where
ι Current word
⬤ All letters satisfy
№ιλ Count of letter
¬› Does not exceed
№θλ Count available
Implicitly print
```
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
(1 e.[E.e.~#])&(/:~@>)#[
```
[Try it online!](https://tio.run/##bY3BCsIwDIbve4rgwLSwVb0WFUH05MnrEDakQ4QRWHPQHvbqdR11k@EhkD/fl@TpFwpr2GlAyGANuq9cwfF6OXuxAaOKkzKqS29yKVa6O@xlWniZJOb@IKhsaalkKqliC7meDWrYYmWZcLSZotU3MyoyHTLK3ztfKTqI43rPB@jc270iDn/byWAacrC4pWaSIvgntkQNo/8A "J – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
怜˜Ã
```
-2 bytes thanks to *@ovs*.
Inputs in the order `letters, words-list`.
[Try it online](https://tio.run/##yy9OTMpM/f//8LJHTWuOTj4953Dz//9F@fm5JVzRSonFSjpKJflgAkTmFynFAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/8PLHjWtOTr59JzDzf91/kdHRyslFivpKBXnA4kSEJGfWFKsFKsDFAZyY3UUYCrAPAxRmD6IFJp6sDRQpqqqsqoCQ64kH2xdEUhFSVF@Ll4FRfn5uUDjYwE).
**Explanation:**
```
æ # Get the powerset of the (implicit) first input-string of letters
€œ # Get the permutations of each string in this list
˜ # Flatten this nested list to a single list of strings
à # Keep the words from the second (implicit) input-list that are also in this list
# (after which the result is output implicitly)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 49 bytes
```
A`^|(.)(.*\1)*(?<!^.*(?(2)^)(?<-2>.*\1)*\1(.|¶)+)
```
[Try it online!](https://tio.run/##K0otycxLNPyvqhGcoMOlwnVo23/HhLgaDT1NDT2tGENNLQ17G8U4PSClYaQZpwnk6RrZQWRiDDX0ag5t09TW/P8/sbgkXyexWKc4XwfIyE8sKeaCCZXkg5hwSa6qqsqqCogEUISrpCg/F8oryQdqLeIqys/PLUERAgA "Retina – Try It Online") Takes newline-separated input but link is to test suite that splits on commas for convenience. Explanation:
```
A`^|
```
Delete the first line, plus...
```
(.)(.*\1)*
```
... any lines that have more of a particular letter...
```
(?<!^.*(?(2)^)(?<-2>.*\1)*\1(.|¶)+)
```
... than the first line does.
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), ~~10~~ 9 bytes
```
[#*/&,:/:
```
Takes the words on the left and the letters on the right
# Explained
```
/: Each left
,: Membership
*/& And then reduce with multiplication
[# Filter words with this mask
```
`*/ 1 0 0 1 0` is the same as `^./ 1 0 0 1 0` but shorter.
[Answer]
# [Python](https://www.python.org), 88 bytes
```
lambda a,w:filter(" ".join(map("".join,permutations(a))).count,w)
from itertools import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYwxCgIxEEV7TxGmSpbs1iJ4D0EtRt1gZJMJkwmLZ7EJiN7J27gYm_9-897jne5ypVifbnt4FXH9-rObMJwuqNDOG-cnGVmDguFGPuqASUP7No0ciqB4ilmjMWY4U4liZ7NyTEH5xRSiKSsfErF0_36f2EfRndMgTBTAqj1gXgBCbX8ghqMxTaq18Qs)
Assumes the words don't contain spaces, but the `" "` can be changed to any other character that the words won't contain.
Unusually for Python, this declarative approach (map+filter) is shorter than a list comprehension.
[Answer]
# [Perl 5](https://www.perl.org/) + `-F -M5.10.0`, 38 bytes
```
say grep{$t=$_;$t=~s/$_// for@F;!$t}<>
```
[Try it online!](https://tio.run/##FYm7CoAwDAD3foVCV20dnHzg1M1vKBmqCGJKk0VEP91Y4Tg4Loa0tyIEZ7GmEC/Ng/Zd9kNGe2OKBdPkulLz3Y8igMQKWDEqoGzIicCkCDP4j0AvRt7wIKmcVHNbN7a2Hw "Perl 5 – Try It Online")
## Explanation
The letters (first line of input) are implicitly stored in `@F` via the `-F` flag.
We `grep` through the word list (`<>`), temporarily storing the word (`$_`) in `$t`, then `for` each letter in `@F`, `s///`ubstitute it (`$_`) for the empty string, returning a truthy value (which includes the word in the set to be printed by `say`) if `$t` is now empty (all letters of the word were removed because they exist in the input letters).
[Answer]
# [Perl 5](https://www.perl.org/), ~~52~~ 47 bytes
```
sub{$c=pop;grep{$C=$c;!grep{$C!~s/$_//}/./g}@_}
```
[Try it online!](https://tio.run/##jY5PT4NAEMXP5VNMycYFspGTF8kqiUcTe/GmDaEIWBVm3V1jC8Gvjss/28am6Wnmvfm9tytS@XHVkoy36mtVk4QLFEEuU1GTO06SYD7u8x/lk8j3G//Sz5swatrAylA6FsATjZVGyvrFDKo6QXuLYqwVXQK/OXFdsmMtRhzkOr0jjz23wyewqrbV5rBzCAzohGmJxT9K4/BFOfXqPz3GJGKhz83t2Sbu1qYBoNg6JHmNpWLkG@WLGelGuDwkUTDeIcxR8wuSOeGE9AF3AIRclxrecF06lFHWwS6kn3tO32jNbsHG9@fStmbXYHue97B4hMW9MQKraX8B "Perl 5 – Try It Online")
(shaved 5 extra bytes from Dom Hastings' suggestions)
[Answer]
# [K4](https://kx.com/download/), 28 bytes
**Solution:**
```
{y@&x{&/1>(#:'=y)-#:'=x}/:y}
```
**Examples:**
Count letter occurrences, subtract and spit out words that match...
```
q)k){y@&x{&/1>(#:'=y)-#:'=x}/:y}["trom";("as";"to";"too";"or")]
"to"
"or"
q)k){y@&x{&/1>(#:'=y)-#:'=x}/:y}["asto";("as";"so";"to";"oats")]
"as"
"so"
"to"
"oats"
q)k)()~{y@&x{&/1>(#:'=y)-#:'=x}/:y}["zzyzx";("as";"to";"so")]
1b
```
**Explanation:**
```
{y@&x{&/1>(#:'=y)-#:'=x}/:y} / the solution
{ } / lambda taking implicit x and y args
x{ }/:y / apply inner lambda to x and each y
=x / group x
#:' / count length of each group
- / subtract from
( ) / do this together
=y / group y
#:' / count length of each group
1> / 1 greater than subtraction result?
&/ / all
& / indices where true
y@ / index into y with these indices
```
**Alternatives:**
* `{y@&&/'1>(#:''=:'y)-\:#:'=x}`, also 28 bytes
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
ṖvKf↔
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B9%96vKf%E2%86%94&inputs=roomt%0A%5B%22as%22%2C%20%22to%22%2C%20%22too%22%2C%20%22or%22%5D&header=&footer=)
This has to be the first time I've found a use for `K` on strings lol
## Explained
```
ṖvKf↔
Ṗ # All permutations of the input word
vK # and get the divisors (substrings that split the string into more than once piece - idk how this actually makes this work)
f # flatten that
↔ # remove words from the input list that aren't in ^
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
@E{.nyM.p
```
[Try it online!](https://tio.run/##K6gsyfj/38G1Wi@v0lev4P9/pZKi/FwlLqXEYiUdBaWSfAgJpvKLlAA "Pyth – Try It Online")
```
@E{.nyM.p
yM.P // Collect all subsets of all permutations of the input
{.n // -> Flatten and de-duplicate the list
E // Read the word list
@ // Get the intersections of the two lists.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
øVáUl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=%2bFbhVWw&input=WyJhcyIsICJ0byIsICJ0b28iLCAib3IiXQoidHJvbSI)
```
-f flag to output the elements of first input
that return a truthy value when passed through
ø - true if word contains any of:
Vá - permutations of alphabet
Ul - of same length of word hence equal
```
Or [try that](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=%2bFbhVWw&input=WyJhcyIsICJ0byIsICJ0b28iLCAib3IiXQoicm9vbXQi)
]
|
[Question]
[
What general tips do you have for golfing in QBasic? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to QBasic (e.g. "remove comments" is not an answer).
Tips pertaining to the [QB64](https://www.qb64.org/) emulator are also welcome. It has some extra features that aren't in Microsoft QBasic.
[Answer]
# Know your looping constructs
QBasic has several looping constructs: `FOR ... NEXT`, `WHILE ... WEND`, and `DO ... LOOP`. You can also use `GOTO` or (in some situations) `RUN` to loop.
* `FOR ... NEXT` is pretty good at what it does. Unlike in Python, it's almost always shorter than the equivalent `WHILE` or `GOTO` loop, even when it gets a little fancier:
```
FOR i=1TO 19STEP 2:?i:NEXT
i=1:WHILE i<20:?i:i=i+2:WEND
i=1:9?i:i=i+2:IF i<20GOTO 9
```
Note that you don't need to repeat the variable name after `NEXT`, and you can eliminate space between numbers and most following keywords.
* `WHILE ... WEND` is good for when you have a loop that might need to execute 0 times. But if you know the loop will execute at least once, `GOTO` might be one byte shorter:
```
WHILE n>1:n=n\2:WEND
1n=n\2:IF n>1GOTO 1
```
* I only use `DO ... LOOP` for infinite loops (except where `RUN` can be used instead). While it costs the same number of characters as an unconditional `GOTO`, it's a little more intuitive to read. (Note that "infinite loop" can include loops that you break out of using a `GOTO`.) The `DO WHILE`/`DO UNTIL`/`LOOP WHILE`/`LOOP UNTIL` syntax is too verbose; you're better off using `WHILE` or `GOTO` as appropriate.
* `GOTO` is, as mentioned above, the shortest general way to write a do/while loop. Use single-digit line numbers instead of labels. Note that when a `GOTO` is the only thing in the `THEN` part of an `IF` statement, there are two equally terse shortcut syntaxes available:
```
IF x>y GOTO 1
IF x>y THEN 1
```
`GOTO` can also be used to create [more complicated control flows](https://codegolf.stackexchange.com/a/107657/16766). The naysayers refer to this as "spaghetti code," but this is code golf: unreadability is almost a virtue! `GOTO` pride!
* `RUN` is useful when you need to jump to a fixed place in the program and you don't need to keep any of the variables' values. `RUN` by itself will restart the program from the top; with a label or line number, it will restart at that line. I've mainly used it to [create stateless infinite loops](https://codegolf.stackexchange.com/a/47398/16766).
[Answer]
# Divisibility testing
In programs that require you to test whether one integer is divisible by another, the obvious way is to use `MOD`:
```
x MOD 3=0
```
But a shorter way is to use integer division:
```
x\3=x/3
```
That is, `x` int-div `3` equals `x` float-div `3`.
Note that both of these approaches will return `0` for falsey and `-1` for truthy, so you may need to negate the result, or subtract it instead of adding.
---
If you need the opposite condition (i.e. `x` is *not* divisible by `3`), the obvious approach is to use the not-equals operator:
```
x\3<>x/3
```
But if `x` is guaranteed to be nonnegative, we can save a byte. Integer division truncates the result, so it will always be less than or equal to float division. Therefore, we can write the condition as:
```
x\3<x/3
```
Similarly, if `x` is guaranteed to be negative, truncation *increases* the result, and we can write `x\3>x/3`. If you don't know the sign of `x`, you'll have to stick to `<>`.
[Answer]
# Scanner abuse
As in a lot of languages, knowing which characters can and can't be removed is important.
* Any space next to a symbol can be removed: `IF""=a$THEN?0`
* Space can usually be removed between a digit and a letter occurring *in that order*: `FOR i=1TO 10STEP 2`. There are some differences between QBasic 1.1 (available at [archive.org](http://archive.org/details/msdos_qbasic_megapack)) and [QB64](http://qb64.net):
+ QBasic 1.1 allows removal of space between any digit and a following letter. Furthermore, in print statements, it will infer a semicolon between consecutive values: `?123x` becomes `PRINT 123; x`. The exceptions to the above are sequences like `1e2` and `1d+3`, which are treated as scientific notation and expanded to `100!` and `1000#` (single- and double-precision, respectively).
+ QB64 is generally the same, but digits can't be followed by `d`, `e`, or `f` at all unless they are part of a well-formed scientific notation literal. (For example, you can't omit the space after the line number in `1 FOR` or `9 END`, like you can in QBasic proper.) It only infers semicolons in print statements if one of the expressions is a string literal: `?123"abc"` works, but not `?TAB(5)123` or `?123x`.
* Speaking of semicolons, QBasic 1.1 adds a trailing semicolon to a `PRINT` statement that ends with a call to `TAB` or `SPC`. (QB64 does not.)
* `0` can be omitted before or after the decimal point (`.1` or `1.`), but not both (`.`).
* `ENDIF` is equivalent to `END IF`.
* The closing double quote of a string can be omitted at the end of a line.
[Answer]
# Use shortcuts for `PRINT` and `REM`
You can use `?` instead of `PRINT`, and `'` instead of `REM` (comment).
`'` might also come useful when polygloting with languages that support `'` as a part of char or string syntax.
[Answer]
# Know your input methods
QBasic has several ways to get user keyboard input: `INPUT`, `LINE INPUT`, `INPUT$`, and `INKEY$`.
* `INPUT` is your standard multipurpose input statement. The program stops what it's doing, displays a cursor, and lets the user type some input, terminated by `Enter`. `INPUT` can read numbers or strings, and it can read multiple values comma-separated. You can specify a string as a prompt, you can go with the default question-mark prompt, and you can even (I just learned this tonight) suppress the prompt altogether. Some sample invocations:
+ `INPUT x$,y`
Uses the default `?` prompt and reads a string and a number, comma-separated.
+ `INPUT"Name";n$`
Prompts with `Name?` and reads a string.
+ `INPUT"x=",x`
Prompts with `x=` (no question mark! note the comma in the syntax) and reads a number.
+ `INPUT;"",s$`
Suppresses the prompt (using the above comma syntax with an empty prompt string), reads a string, and does not move to the next line when the user hits enter (that's what the semicolon after `INPUT` does). For example, if you `PRINT s$` immediately after this, your screen will look like `User_inputUser_input`.
* One drawback of `INPUT` is that you can't read a string with a comma in it, since `INPUT` uses comma as a field separator. To read a single line of arbitrary (printable ASCII) characters, use `LINE INPUT`. It's got the same syntax options as `INPUT`, except it takes exactly one variable which must be a string variable. The other difference is that `LINE INPUT` does not display a prompt by default; if you want one, you'll have to specify it explicitly.
* `INPUT$(n)` displays no prompt or cursor but simply waits until the user enters `n` characters, and then returns a string containing those characters. Unlike `INPUT` or `LINE INPUT`, the user doesn't need to press `Enter` afterwards, and in fact `Enter` can be one of the characters (it'll give ASCII character 13, known to C-like languages as `\r`).
Most often, this is useful as `INPUT$(1)`, typically in a loop. `INPUT$` is good in [interactive programs where single keypresses do things](https://codegolf.stackexchange.com/a/147623/16766). Unfortunately, it only works with keys that have ASCII codes; this includes things like `Esc` and `Backspace`, but not the arrow keys, `Insert` and `Delete`, and others.
* Which is where `INKEY$` comes in. It is similar to `INPUT$(1)` in that it returns the results of a single keypress1, but different in that:
+ `INKEY$` takes no argument.
+ While `INPUT$(n)` halts execution until the user enters `n` characters, `INKEY$` does not halt execution. If the user is currently pressing a key, `INKEY$` returns a string representing that key; if not, it returns `""`. This means that if you want to use `INKEY$` to get the next keypress, you have to wrap it in a [busy-waiting](https://en.wikipedia.org/wiki/Busy_waiting) loop:2
```
k$=""
WHILE""=k$
k$=INKEY$
WEND
```
+ Both `INPUT$` and `INKEY$` return ASCII characters for keys that correspond to ASCII characters (including control characters like escape, tab, and backspace). However, `INKEY$` can also handle some keys that do not have ASCII codes. For these (saith the help file), "INKEY$ returns a 2-byte string made up of the null character (ASCII 0) and the keyboard scan code."
Clear as mud? Here's some examples. If you use the `INKEY$` loop above to capture a keypress of the left arrow key, `k$` will contain the string `"␀K"` (with the `K` representing scan code 75). For the right arrow, it's `"␀M"` (77). Page down is `"␀Q"` (81). F5 is `"␀?"` (63).
Still clear as mud? Yeah. It's not the most intuitive thing in the world. The help file has a table of scan codes, but I always just write a little program to print the results of `INKEY$` and press a bunch of keys to find out what the right values are. Once you know which characters correspond to which keys, you can use `RIGHT$(k$,1)` and `LEN(k$)` to distinguish between all the different cases you may encounter.Bottom line? `INKEY$` is weird, but it's the only way to go if your program requires non-blocking input or [needs to use the arrow keys](https://codegolf.stackexchange.com/a/49082/16766).
---
1 Not including `Shift`, `Ctrl`, `Alt`, `PrntScr`, `Caps Lock`, and similar. Those don't count. :^P
2 The `WHILE ... WEND` idiom here is what I learned in my QBasic books. For golfing purposes, however, [a `GOTO` loop is shorter](https://codegolf.stackexchange.com/a/147627/16766).
[Answer]
# Combine `Next` Statements
```
Next:Next:Next
```
May be condensed down to
```
Next k,j,i
```
where the iterators for the `For` loops are `i`,`j`, and `k` - in that order.
For example the below (69 Bytes)
```
Input n,m,o
For i=0To n
For j=0To m
For k=0To o
?i;j;k
Next
Next
Next
```
May be condensed down to 65 Bytes
```
Input n,m,o
For i=0To n
For j=0To m
For k=0To o
?i;j;k
Next k,j,i
```
And as far as how this impacts formatting and indentation, I think the best approach to handling this is left aligning the next statement with the outer most for statement. Eg.
```
Input n,m,o
For i=0To n
For j=0To m
For k=0To o
?i;j;k
Next k,j,i
```
[Answer]
# `PRINT` (`?`) has some quirks
Numbers are printed with a leading and trailing space.
Printing adds a linebreak. This behaviour can be altered by adding a comma at the end of the statement to insert a tab instead, or a semi-colon to avoid any insertions.
It is not necessary to use `+` or `;` between distinct expressions when printing, eg. `?1"x"s$` prints the number `1`, with spaces on each side, the letter `x` and the contents of `s$`.
```
?"foo"
?"bar"
?10
?"foo",
?"bar"
?"foo";
?"bar"
?1CHR$(65)
?1" "CHR$(65)
?"A","B
```
Outputs
```
foo
bar
10
foo bar
foobar
1 A
1 A
A B
```
Printing a linebreak can be done with just `?`.
[Answer]
# LOCATE can be really powerful
The `LOCATE` statement allows you to place the cursor anywhere on the screen (within the usual 80x40 character space limits) and print something at that location. [This answer](https://codegolf.stackexchange.com/a/147623/44874) to a challenge really shows this off (and is also combined with a lot of other tips from this topic).
The challenge asks us to output every character a user has pressed in a 16x6 grid. With `LOCATE` this is simply a matter of div and mod over the ASCII code (`a` in this code):
```
LOCATE a\16-1,1+2*(a MOD 16)
```
And then printing the character:
```
?CHR$(a)
```
[Answer]
In QBasic, it is customary to use the `DIM` statement to create variables, giving them a name and a type. However, this isn't mandatory, QBasic can also derive a type by the suffix of the variable's name. Since you can't declare and initialise a variable at the same time, it's often wise to skip the `DIM` in codegolf. Two snippets that are functionally identical\*:
```
DIM a AS STRING: a = "example"
a$ = "example"
```
\* Note that this does create two different variable names.
We can specify the type of the variable by adding `$` to the end of a variable name for strings, `!` for single precision numbers and `%` for doubles. Singles are assumed when no type is specified.
```
a$ = "Definitely a string"
b! = "Error!"
```
Note that this also holds for arrays. Usually, an array is defined as:
```
DIM a(20) AS STRING
```
But arrays also don't need to be `DIM`med:
```
a$(2) = "QBasic 4 FUN!"
```
`a$` is now an array for strings with **11** slots: from index 0 to and including index 10. This is done because QBasic has an option that allows both 0-based and 1-based indexing for arrays. A default array kind of supports both this way.
Remember the twenty-slot array we `DIM`med above? That actually has 21 slots, because the same principle applies to both dimmed and non-dimmed arrays.
[Answer]
# Shortening `IF` statements
`IF` statements are rather expensive, and golfing them down can save a lot of bytes.
Consider the following (adapted from an [answer](https://codegolf.stackexchange.com/a/166106) by Erik the Outgolfer):
```
IF RND<.5THEN
x=x-1
a(i)=1
ELSE
y=y-1
a(i)=0
ENDIF
```
The first thing we can do is save the `ENDIF` by using a single-line `IF` statement:
```
IF RND<.5THEN x=x-1:a(i)=1ELSE y=y-1:a(i)=0
```
This works as long as you don't try to put it on the same line as anything else. In particular, if you have nested `IF` statements, only the innermost one can be one-lined.
But in this case, we can eliminate the `IF` entirely using math. Consider what we actually want:
* If `RND<.5` is true (`-1`), we want:
+ `x` to decrease by 1
+ `y` to stay the same
+ `a(i)` to become 1
* Otherwise, if `RND<.5` is false (`0`), we want:
+ `x` to stay the same
+ `y` to decrease by 1
+ `a(i)` to become 0
Now if we save the result of the conditional in a variable (`r=RND<.5`), we can calculate the new values of `x`, `y`, and `a(i)`:
* When `r` is `-1`, `x=x-1`; when `r` is `0`, `x=x+0`.
* When `r` is `-1`, `y=y+0`; when `r` is `0`, `y=y-1`.
* When `r` is `-1`, `a(i)=1`; when `r` is `0`, `a(i)=0`.
So our final code looks like:
```
r=RND<.5
x=x+r
y=y-1-r
a(i)=-r
```
saving a whopping 20 bytes (40%) over the original version.
---
The math approach can be applied surprisingly often, but when there's a difference in logic between the two cases (e.g. when you need to input something in one case but not in the other), you will still need to use `IF`.
[Answer]
# Sometimes, you should avoid arrays
Arrays in QBasic, when instantiated without `DIM` have only 11 slots. If a challenge requires more than 11 slots (or N slots, where N can be bigger than 11), you should `DIM` the array. Also, let's assume we want to populate this array with data:
```
DIM a$(12)
a$(0) = "Value 1"
a$(1) = "Value 2"
...
```
Even golfed, this can take up a lot of space. On such occasions, it might be cheaper in bytes to do this:
```
a$ = "value 1value 2"
```
Here, we place everything in 1 concatenated string. Later, we access it like so:
```
?MID$(a$,i*7,7)
```
For this approach, it is important that all values are of equal length. Take the longest value and pad out all the others:
```
a$="one two threefour "
```
You don't need to pad the last value, and you can even skip the closing quotes! If the challenge specifies that white-space is not allowed in the answer, use `RTRIM$()` to fix that.
You can see this technique in action [here](https://codegolf.stackexchange.com/a/166554/44874).
[Answer]
# `WRITE` may be useful in place of `PRINT`
`PRINT` is usually the way you'll want to do output, since it's pretty flexible and has the `?` shortcut. However, the `WRITE` command can save you bytes in specific situations:
* When outputting a string, `WRITE` wraps it in double quotes (`"`). If you need output with double quotes, `WRITE s$` is much shorter than `?CHR$(34);s$;CHR$(34)`. See, for example, [the shortest known QBasic quine](https://codegolf.stackexchange.com/a/47119/16766).
* When outputting a number, `WRITE` does not add spaces before and after it like `PRINT` does. `WRITE n` is much shorter than `?MID$(STR$(n),2)`. See, for example, [FizzBuzz in QB64](https://codegolf.stackexchange.com/a/58834/16766).
* When outputting multiple values, `WRITE` separates them with commas: `WRITE 123,"abc"` outputs `123,"abc"`. I can't think of a scenario where this would be useful, but that doesn't mean there isn't one.
Limitations of `WRITE`:
* There is no way to output multiple values without a separator like with `PRINT a;b`.
* There is no way to suppress the newline at the end of output. (You may be able to work around this with `LOCATE`, but that costs a lot of bytes.)
[Answer]
# Sometimes, QBasic mangles inputs to functions. Abuse that!
There's a couple of functions that work on characters instead of strings, but there isn't a `char` datatype in QBasic, there is only the `string ($)` type. Take for instance the `ASC()` function, which returns the ASCII keycode for a character. If we would enter
```
PRINT ASC("lala")
```
only the first `l` would be considered by QBasic. This way, we don't have to bother with cutting a string down to length 1.
Another example comes from [this question](https://codegolf.stackexchange.com/questions/125133/is-this-number-a-repdigit/) where the `STRING$()` function is used in one of the answers.
>
> The STRING$ function takes two arguments, a number n and a string s$, and constructs a string consisting of n copies of the first character of s$
>
>
> @DLosc, [here](https://codegolf.stackexchange.com/questions/125133/is-this-number-a-repdigit/167102)
>
>
>
Note that QBasic, when offered a multi-char string and needing only one char, automatically takes the first char and ignores the rest.
[Answer]
# `Integer` vs `Ulong`
Sometimes you can simply reduce 2 bytes by using this trick:
```
DIM r AS Integer
vs
DIM r AS Ulong
```
This works on most occassions.
]
|
[Question]
[
At runtime, keep prompting for *a line of input* until the user input is **not** the name of an existing file or directory or other file system item, relative to the current working directory. Then return/print that last inputted filename. You may assume that all user inputs will be valid filenames.
### Pseudo-code 1
```
myform = new form("GUI")
myform.mytxt = new editfield("")
myform.ok = new button("OK")
repeat
waitfor(myform.ok,"click")
until not filesystem.exists(myform.mytxt.content)
return(myform.mytxt.content)
```
### Pseudo-code 2
```
LET TEXT = "."
WHILE HASFILE(TEXT) DO
TEXT = PROMPT("")
ENDWHILE
RETURN TEXT
```
### Examples of user input which will cause re-prompting when on TIO:
```
.
..
.env.tio
/
/bin/[
/lost+found
```
### Examples of user input which will return when on TIO:
```
...
env.tio
../../bin/]
/lost/found
```
[Answer]
## Batch, 37 bytes
```
@set/ps=
@if exist %s% %0
@echo %s%
```
(For some reason current Windows 10 `CMD.EXE` corrupts the title when it executes the `%0`.)
[Answer]
## Mathematica, ~~33~~ 28 bytes
```
f:=Input[]/._?FileExistsQ:>f
```
This assumes Mathematica's notebook environment where we can query input from the user with `Input[]`. The user input should be [an actual string literal](https://codegolf.meta.stackexchange.com/a/7634/8478), so e.g. `"ab/cd.ef"` instead of just `ab/cd.ef`. The upside is that the input can be an arbitrary Mathematica expression that computes the input string.
This defines a symbol `f` which, when evaluated performs the required computation and ultimately evaluates to the first non-existent user input. It's essentially a nullary function, where we don't have to include `...[]` to call it.
We can also save a bunch of bytes over a traditional `If` expression by making use of the pattern substitution operator `/.`.
[Answer]
# [Perl 5](https://www.perl.org/) `-ln`, ~~12~~ 10 bytes
-2 bytes thanks to [@DomHastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)
```
#!/usr/bin/perl -ln
-e||1/!say
```
[Try it online!](https://tio.run/##NcoxCoAwDEDRPbdwliY6eAxP4FAqRizUtNiqCJ7d6CL87f3EW@hUDd93S1V2lyoCfrEcWHwEAhq90AAUYi71HHeZ4MeysE0bH/Z0WYqdfWBxKwPCE9M3SFYTRE3fYdtg8wI "Perl 5 – Try It Online")
[Answer]
# Bash, 29
```
read f
[ -e $f ]&&$0||echo $f
```
[Answer]
# PowerShell 2 (through 6), 35 bytes
```
while(Test-Path($x=Read-Host)){};$x
```
`Read-Host` waits for input (if given a string as a parameter, uses the string as a prompt). If the provided input is a filename (or folder name) for one that exists, `Test-Path` returns `$true`, and the do-nothing block `{}` executes, and it re-prompts for input. If `Test-Path` returns `$false` because the input is not an extant file or folder, the do-nothing block does not execute, and the input name is printed.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 62 bytes
```
main(){char b[99];while(scanf("%s",b)&&!access(b,0));puts(b);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7M6OSOxSCEp2tIy1ro8IzMnVaM4OTEvTUNJtVhJJ0lTTU0xMTk5tbhYI0nHQFPTuqC0BMjUtK79/1@PSw@IUvPK9Eoy87n0ufSTMvP0o4GCelz6OfnFJdpp@aV5KRC2PoQNUw0A "C (gcc) – Try It Online")
```
main(){
char b[99]; // Declare buffer b
while (scanf("%s",b)&&!access(b,0)); // Take one line of input, and test if file is accessible (exists)
puts (b); // If doesn't exist, loop ends and print file
}
```
[Answer]
# [Funky](https://github.com/TehFlaminTaco/Funky), 40 bytes
```
tryfor)io.open(s=io.read())catchprint(s)
```
In true funky style, this uses keywords jammed against eachother, unmatching brackets and implicit keywords. Cleaned up, this looks like:
```
try{
while(true){
s = io.read()
io.open(s)
}
}catch(e){
print(s)
}
```
# Breakdown
```
try // Try statement, this one is expected to fail.
for) // for) is a for loop with no arguments, which is functionally equivilent to a while(true) loop, much like for(;;)
io.open( // Try to open a file relative to the CWD. If this fails to find a file, it will throw an error and escape the try/catch
s=io.read() // Read a line from STDIN and store it as s, this will still pass it to the arguments of the call.
)
catch // When io.open fails
print(s)// Print out the last entered line.
```
[Answer]
# [Haskell](https://www.haskell.org/), 76 bytes
```
import System.Directory
f=do x<-getLine;b<-doesPathExist x;last$pure x:[f|b]
```
[Try it online!](https://tio.run/##HYqxDoIwFEX3fsUb3AztLrDpxmDCSBwKfZXG0kfahymJ/17Fm7Ockzvr9ELvS3HLSpGh3xPjIq8u4sQUd2FbQ5Cb6oncuYD12FSGMN01z7fsEkOuvU58WreIkC@D/YyPsmgXoAVDAn6LmKCpwP5l3bjn2IWjFinkDwxvyY6EEmp0QQ1CeUp8trQFI7SQExk8Dl8 "Haskell – Try It Online")
Returns `IO x` where `x` is the inputted name of the file that does not exist.
## Ungolfed
```
import System.Directory
insist = do { file <- getLine;
exists <- doesPathExist file;
if exists then insist else pure file }
```
[Answer]
# [R](https://www.r-project.org/), ~~66~~ 51 bytes
```
while((s=readline())%in%list.files(a=T)){};print(s)
```
*-15 bytes thanks to plannapus*
Runs a potentially infinite loop, where on each iteration
1. A single line of user input is stored in the variable `s`
2. We check if the input is in the list of filenames for the working directory (the `a=T` option for `list.files()` must be used to pick up things like `..`)
3. If `s` is in that list, we go to the next iteration; if not, we break the loop and print `s`.
[Answer]
# [Python 3](https://docs.python.org/3/), 55 bytes
```
import glob
s="."
while glob.glob(s):s=input()
print(s)
```
[Try it online!](https://tio.run/##HYm7DoAgDAD3foVxgsEyuJnwMyREm2hLoD74ekSTyw13qeomPLdGR5Ksw7pLgOJHHOHeaI9/wE@m2KV44nSqsZAysfbUGgJ2Il@oJODABWJgmeJDRSHU2P8L "Python 3 – Try It Online")
-4 bytes thanks to ManfP
-6 bytes thanks to Rick Rongen
[Answer]
# C#, 101 bytes
```
()=>{var s="";try{for(;;System.IO.File.GetAttributes(s=System.Console.ReadLine()));}catch{}return s;}
```
For each of the 4 valid return values:
* [Try it online!](https://tio.run/##RY7BSgQxDIbvfYqwpw5i@wB1FkRYERRBBQ/iodvJaGFsockMLKXPPmbXXQw/OeT/Pkig65ALrmHyRPCGxKCqAiD2HAMsOQ7w5GPSnRwryJJ5PRDjj9nNKdwQl5i@tjBCD6vu@m1dfAHqNxvH5VDHXLRzZ@Hh2ezihOYe@ZbF28@MpKk/13c5UZb6Bf3wGBPqrutcC57Dd20FeS4JyLVVPnDq/42L9l4i48kbxTwSTbXVKCPBtBiOWVll9zHZD2WnTHw15jkNAhh1AYyxkiPz@cfYE/ML "C# (.NET Core) – Try It Online") (returns '...')
* [Try it online!](https://tio.run/##RY7BSgMxEIbveYqhp4Ri8gBxCyJUBEVoBQ/SQ5qd1cCaQGZ2oYQ8@5rWFoefOcw3H/ye7nzKuPjREcE7EoMoAoDYcfAwp9DDqwtRqnYs0Fab/YkYf/R2iv6eOIf4tYEBOlik6jZldhmoW60s51MZUpbWXoXnN70NI@on5Adu3nFiJEndFT@mSKnhHbr@JUSUSilbvWP/XWpGnnIEsnVpDaz4r3HTPnJgvHhDM88fVdRFC92CcdYckjDCHEM0n8KMiXg9pCn24ga1Ni1nfvjj5sJ/AQ "C# (.NET Core) – Try It Online") (returns 'env.tio')
* [Try it online!](https://tio.run/##RY7BSgQxEETv@YpmTxnE5APiLIiwIiiCCh7EQzbTswbGBNI9A0vIt4@964pN0YeqelCBrkMuuIbJE8EbEoOqCoDYcwyw5DjAk49Jd2JWkCf3eiTGb7ObU7ghLjEdtjBCD6vu@m1dfAHqNxvH5VjHXLRzF@Dh2ezihOYe@ZaF28@MpKm/xHc5UZb4Bf3wGBPqrutcC57DV20FeS4JyLVVFjj1P@MPey@R8cyNQp4aTbXVKCPCtBiOWVll9zHZD2WnTHw15jkNUrCik//569uz/wM "C# (.NET Core) – Try It Online") (returns '../..bin/])
* [Try it online!](https://tio.run/##RY7BagMxDETv/gqRk02p/QHOBkohJdBSaAI99OR4talhY4OlXQjG375x05QKIYYZPRhPjz5lXPzoiOCAxCCKACB2HDzMKfTw5kKUqpkF2mmzvxDjWW@n6NfEOcTTBgboYJGq25TZZaButbKcL2VIWVp7B3bvehtG1C/IT9y448RIkrp7/JwipRZ/oOtfQ0SplLLVO/bfpWbkKUcgW5fWwIr/Gn/YZw6MN25o5M9HFXXRQrfFOGsOSRhhjiGaL2HGRPwwpCn2v9rc9BU "C# (.NET Core) – Try It Online") (returns '/lost/found)
# Ungolfed
```
() =>
{
var s = "";
try
{
for(;; System.IO.File.GetAttributes(s = System.Console.ReadLine()));
}
catch {}
return s;
}
```
## Explanation
relies on the fact that File.GetAttributes() throws an exception if file system object specified in its argument doesn't exist.
[Answer]
# Powershell 3.0, 75 bytes
```
$x=1;while($x){$i=Read-Host;$x=Test-Path("$PSScriptRoot\$i")};Write-Host $i
```
First attempt; I'm sure there are a few optimizations I could make.
A slightly more readable form:
```
$x=1; # Make sure we enter our while loop.
while($x){ # While we keep getting file names,
$i=Read-Host; # Get input from the user
$x=Test-Path("$PSScriptRoot\$i")}; # Combine our path with the user input, and see if it already exists.
Write-Host $i # Return the final (valid) file name.
```
[Answer]
# Java 9, 87 bytes
```
v->{String s;for(;new java.io.File(s=System.console().readLine()).exists(););return s;}
```
## Ungolfed
[TIO's JVM apparently has no system `Console`](https://tio.run/##JcoxDoMwEETROpxiSlyEPsoZqCijFBtjIRPjtdgFKYo4u7MK1Ujz30w7XbmEPI/vW60@kQh6ihnfBijbK0UPUVKbneOIxVo76Brz9HiC1kncnwLDRzQsHW/aFcuazJ2X5yycQuvc3eTRHJdafw), so it's not testable there (see [`System.console()`](https://docs.oracle.com/javase/9/docs/api/java/lang/System.html#console--)).
```
import java.util.function.*;
class Main {
public static void main(String[] args) {
Function<Void,String> f =
v->{
String s;
for(;new java.io.File(s=System.console().readLine()).exists(););
return s;
}
;
System.out.println(f.apply(null));
}
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~158~~ 118 bytes
```
require('readline').createInterface({input:process.stdin}).on('line',s=>require('fs').existsSync(s)||--console.log(s))
```
[Try it online!](https://tio.run/##VYy9DgIhEIR7XuQgCvQm2ltbWnGwpxiye7LcxZ/z2REtTJxMJpNJvrm42bHPcSwaKUCtGa5TzCC7DC6kiNAp41svsMcCeXAe5DPiOJXNmMkDs@ESIr6UIZTdl1jzdvf7Gbg9wC1y4cMdvWS1LFp7QqYEJtGpLapWI0wz4GxKJGGF7SPao7CJuKwGmjCIPrmz/oR4fCX@mTc "JavaScript (Node.js) – Try It Online")
Credit to @ConorO'Brien for coming up with shorter version. Inlined objects instead of using consts and utilizing error exit condition instead of explicitly exiting.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~100~~ 94 bytes
```
import System.IO,System.File
Start w#(s,w)=evalIO getLine w
#(b,w)=fileExists s w
|b=Start w=s
```
[Try it online!](https://tio.run/##LYtBCoNAEATvvmLRiwH1B96SgCAY8AWjGc3C7K44E42Qt2digrfuqu6eELy6cH8SGgfWq3VTmMW0Gwu6omqyI10tYdQK7G5NUs7WU4kLUNWYEaW2Hs0aJWn348M@vbwsCxve6bsrj1/JqgX6pRAboviBRCH@9APByJp3mle1njcPzvb8LzcCGcLsvg "Clean – Try It Online")
**single-expression version:**
```
import System.IO,System.File
Start w=(\(s,v)=(\(b,w)|b=Start w=s)(fileExists s v))(evalIO getLine w)
```
[Try it online!](https://tio.run/##NYpBCsIwEEX3PUXoKoHaG3SnQqFQoVs3aZ3WwCSRzpha8OyOVXT13@P9AcEG8fFyR1DeuiDO3@LMqluJwZd1W/zo6BCyju3WlkqfNRXJfLYvFvPsq38ho8fteXg4YlKkkjEaksW6VRNw4wKoxYiUEFLJLmb5FRBj/hpGtBPJrpdd3ch@Dda7gb5yQstjnP0b "Clean – Try It Online")
[Answer]
# Perl 6, 39 bytes
```
my$f=".";while $f.IO.e {$f=get};say $f;
```
This works in the REPL, but it doesn't seem to work properly in TIO.
[Answer]
# PHP, 43 bytes
```
<?for(;file_exists($f=readline()););echo$f;
```
Run as CLI. Quite easy to understand.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~40 39~~ 37 bytes
```
{}while File.exist? gets.chomp
$><<$_
```
[Try it online!](https://tio.run/##KypNqvz/v7q2PCMzJ1XBDUjopVZkFpfYK6SnlhTrJWfk5xZwqdjZ2KjE//@vx6UHRKl5ZXolmflc@lz6SZl5@tFc@jn5xSXaafmleSlcUEkA "Ruby – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 17 bytes
```
{⍞}⍣{~⎕NEXISTS⍺}⍬
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBNWPeufVPupdXF33qG@qn2uEZ3BI8KPeXUChNVx6XHpAlJpXpleSmc@lz6WflJmnH82ln5NfXKKdll@al8IFkyzJSI0vKEotiy9PLM4riU/LzEnNS8xNBQA)
[Answer]
# [Kotlin](https://kotlinlang.org), 67 bytes
```
val f={var s="."
while(java.io.File(s).exists()){s=readLine()!!}
s}
```
[Try it online!](https://tio.run/##XUsxDsIwENvvFWmnRIjLjtSViY2RKVXT9iBcUJIGpKpvDwExIdmWLds3nxxxGRcWd0MsswkmTKIyHsQ5BeJJiRUe1STHcpRKwVaycWLs1joWsWuxhedMzsqryQbJ4/ETokL7ophivayxC9YMJ2IrVdNsELdSELDCcsZEHjTonvgr@gLa@Zh2o194gN6Zef@R3@avRnwD "Kotlin – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), 35 bytes
```
{While[FileExists[x:=Prompt[]],0]x}
```
[Try it online!](https://tio.run/##JYexCoAgFAB3f6XwNQeONbc1PByslB6URr5CiL7dhOA47gyzmVebXavyM660WeyLukSRI6ZWDWfYD0at60anNw8neUZXPkshC9bfkikIEDCRBxSwhciVC5df/oa/TXTLBw "Attache – Try It Online")
## Alternative solutions
**35 bytes:** `{If[FileExists[x:=Prompt[]],$[],x]}`, recursive function.
**37 bytes:** `{NestWhile[p:=Prompt,p[],FileExists]}`, iterative function.
[Answer]
# [Min](https://min-lang.org), 38 bytes
```
"." :a (a exists?) ("" ask @a) while a
```
Leaves last entered filename on the stack.
## Explanation
```
"." ; Put . on the stack. Every directory should contain this...
:a ; Assign to a
(a exists?) ; A quot that checks if a exists in current directory
("" ask @a) ; Read line from stdin, assign to a
while ; Do the second quote while the first leaves true on the stack
a ; Leave a on the stack
```
[Answer]
# SmileBASIC, 27 bytes
```
INPUT S$EXEC!CHKFILE(S$)?S$
```
]
|
[Question]
[
# The Challenge
Given an integer `n>0` output a `n+1 X n+1` matrix containing all integers from `1` to `2n` as shown in the test cases bellow
# Test Cases
```
n=1
1 2
2 2
n=2
1 2 4
2 3 4
4 4 4
n=5
1 2 3 4 5 10
2 3 4 5 6 10
3 4 5 6 7 10
4 5 6 7 8 10
5 6 7 8 9 10
10 10 10 10 10 10
n=10
1 2 3 4 5 6 7 8 9 10 20
2 3 4 5 6 7 8 9 10 11 20
3 4 5 6 7 8 9 10 11 12 20
4 5 6 7 8 9 10 11 12 13 20
5 6 7 8 9 10 11 12 13 14 20
6 7 8 9 10 11 12 13 14 15 20
7 8 9 10 11 12 13 14 15 16 20
8 9 10 11 12 13 14 15 16 17 20
9 10 11 12 13 14 15 16 17 18 20
10 11 12 13 14 15 16 17 18 19 20
20 20 20 20 20 20 20 20 20 20 20
```
I think that the pattern is pretty easy, so let's see who will give the shortest answer in bytes.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
# Rules
**Input** must be an integer (**1-indexed**)
**Output** can be a **matrix** (as shown in the test cases) or a **list of lists**
[Answer]
# [R](https://www.r-project.org/), 53 bytes
```
function(n)rbind(cbind(outer(1:n,1:n,`+`)-1,2*n),2*n)
```
Uses the `outer` "product" to generate all sums of the range `1,...,n` as a matrix, subtracts `1` from each, then `bind`s `2*n` as a column on the right and a row on the bottom, recycling as needed, and returns a matrix as the result.
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7MoKTMvRSMZTOaXlqQWaRha5emAcIJ2gqauoY6RVp4mmPifpmGk@R8A "R – Try It Online")
# [R](https://www.r-project.org/), 78 bytes
More naive implementation.
```
function(n){m=matrix(2*n,n+1,n+1)
for(i in seq(n))m[1:n,i]=(0:(2*n))[1:n+i]
m}
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7M61zY3saQos0LDSCtPJ0/bEIQ1udLyizQyFTLzFIpTC4GqNHOjDa3ydDJjbTUMrEAqNTVBAtqZsVy5tf/TNEA6NEw1/wMA "R – Try It Online")
[Answer]
# Mathematica, ~~61~~ 46 bytes
```
ArrayFlatten@{{##-1&~Array~{#,#},2#},{2#,2#}}&
```
thanx @alephalpha for -15 bytes
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 10 bytes
```
:&+q,!GEYc
```
[Try it online!](https://tio.run/##y00syfn/30pNu1BH0d01Mvn/f0MDAA)
### Explanation
```
: % Input n (implicit). Push range [1 2 ... n]
&+ % matrix of pairwise additions
q % Subtract 1
, % Do twice
! % Transpose
GE % Push 2*n
Yc % Concatenate that value to all rows, thus extending the matrix
% End (implicit). Display (implicit)
```
[Answer]
# [Haskell](https://www.haskell.org/), 48 bytes
```
f n=[[i..n-1+i]++[2*n]|i<-[1..n]]++[2*n<$[0..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6OlNPL0/XUDszVls72kgrL7Ym00Y32hAoGAsVsVGJNgBz/@cmZuYp2CrkJhb4KhQUZeaVaKQpGBpo/gcA "Haskell – Try It Online")
[Answer]
# Octave, ~~38~~ ~~37~~ 35 bytes
```
@(n)[(x=1:n)+x'-1 z=~x'+2*n;z' 2*n]
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPM1qjwtbQKk9Tu0Jd11ChyrauQl3bSCvPukpdAUjF/k/MK9Yw1fwPAA "Octave – Try It Online")
or
```
@(n)~(k=blkdiag((x=1:n)+x'-1,0))*2*n+k
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPs04j2zYpJzslMzFdQ6PC1tAqT1O7Ql3XUMdAU1PLSCtPO/t/Yl6xhqnmfwA "Octave – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
+þḶ;€Ḥ;ḤzḤG
```
[Try it online!](https://tio.run/##y0rNyan8/1/78L6HO7ZZP2pa83DHEmsgrgJi9////5sCAA "Jelly – Try It Online")
[Answer]
## JavaScript (ES6), 64 bytes
```
f=
n=>[...Array(n+1)].map((_,i,a)=>a.map((_,j)=>n-i&&n-j?i-~j:n+n))
```
```
<input type=number min=0 oninput="t.innerHTML=f(+this.value).map(a=>`<tr>${a.map(b=>`<td>${b}</td>`).join``}</tr>`).join``"><table id=t>
```
[Answer]
# Java 8, 99 bytes
Lambda from `Integer` to `int[][]` (e.g. `Function<Integer, int[][]>`). Surprisingly resistant to golfing.
```
n->{int p=n+1,o[][]=new int[p][p],i=0,r,c;while(i<p*p)o[r=i/p][c=i++%p]=r<n&c<n?r-~c:2*n;return o;}
```
[Try It Online](https://tio.run/##XZBNa8MwDIbP6a/QZSNpU@8Ddmnijl0GO/SyHkMOnutk6lzZOEq7Urq/nrkfMBjoIHj1Ss@rtdqqqfOG1quvwfcfFjVoq7oOFgoJDqPEB9wqNtCx4ig2SMrCOtpEz2hF05NmdCRer035RmxaE3JA4qqu6jm0ht8VtWahOOA3yIGm80NUwUuaPOTuNCXJ7M4OX8fKUd7nIdfF7hOtSbH0Y5@5Kki8i7qWOJnc@FqGkm51Sc9h@qNnj2MqguE@ELjiOCTFKMJfEl3Ztw5XsIm50mUEobaqQYW2y04xk8YFSM/IENwOZv@ohfLe7tOn7DKdLPcdm41wPYv4IWJL6d9TXkJQ@06wu9xJ48IsK6LtOIp1HH4B)
## Ungolfed lambda
```
n -> {
int
p = n + 1,
o[][] = new int[p][p],
i = 0,
r, c
;
while (i < p * p)
o[r = i / p][c = i++ % p] =
r < n & c < n ?
r - ~c
: 2 * n
;
return o;
}
```
## Acknowledgments
* -1 byte thanks to Kevin Cruijssen
[Answer]
# [Python 2](https://docs.python.org/2/), ~~64~~ ~~62~~ 61 bytes
*-3 bytes thanks to Mr. Xcoder.*
```
lambda n:[range(i+1,i-~n)+[n*2]for i in range(n)]+[[n*2]*-~n]
```
[Try it online!](https://tio.run/##PcuxDoMgFEbh3af4RxGaCImLCU9CGTCK3qS9EmTp0ldHY5PO3znpU7adTY32WV/hPc0BPLoceF1aklrR48tCOu6Mj3sGgRg/ZeGlu6G7Gl/LcpQDFk4rGIVBQfe@af7X7SNSJi6ILYl6Ag "Python 2 – Try It Online")
I'm probably missing a key pattern though.
# [Python 2](https://docs.python.org/2/), 76 bytes
```
lambda n:[[[n*2,i-~j][n-i and n-j>0]for j in range(n+1)]for i in range(n+1)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjo6Ok/LSCdTty4rNjpPN1MhMS9FIU83y84gNi2/SCFLITNPoSgxLz1VI0/bUBMslokm9r@gKDOvRCFNw1TzPwA "Python 2 – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 18 bytes
```
+m+rd+QdyQSQ]*]yQh
```
Maybe I am missing an obvious pattern (cc [@totallyhuman](https://codegolf.stackexchange.com/a/140824/59487))...
**[Test Suite.](https://pyth.herokuapp.com/?code=%2Bm%2Brd%2BQdyQSQ%5D%2a%5DyQh&input=1%0A2%0A3%0A4%0A5&test_suite=1&test_suite_input=1%0A2%0A5%0A10&debug=0)**
**["Pretty print" Test Suite.](https://pyth.herokuapp.com/?code=j%2Bm%2Brd%2BQdyQSQ%5D%2a%5DyQh&input=1%0A2%0A3%0A4%0A5&test_suite=1&test_suite_input=1%0A2%0A5%0A10&debug=0)**
[Answer]
# [Proton](https://github.com/alexander-liao/proton), ~~48~~ 44 bytes
*-4 bytes thanks to @totallyhuman!*
```
n=>[(i+1..i-~n)+[n*2]for i:0..n]+[[n*2]*-~n]
```
[Try it online!](https://tio.run/##KyjKL8nP@59m@z/P1i5aI1PbUE8vU7cuT1M7Ok/LKDYtv0gh08pATy8vVjsaLKIFlIz9X1CUmVeikaZhqKnJBWMbIbFNkdiGBpqa/wE "Proton – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 54 ~~63~~ ~~67~~ bytes
```
function(n)cbind(rbind(sapply(1:n-1,'+',1:n),2*n),2*n)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTzM5KTMvRaMITBYnFhTkVGoYWuXpGuqoa6vrAFmaOkZaUOJ/moaRJleahimIMDTQ/A8A "R – Try It Online")
Thanks to @Guiseppe for the pointer for sapply and the 9 bytes
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~17~~ 16 bytes
```
õ_óU pU*2ÃpUô@*2
```
[Try it online!](https://tio.run/##y0osKPn///DW@MObQxUKQrWMDjcXhB7e4qBl9P@/qYJuIAA "Japt – Try It Online")
[Answer]
# [Recursiva](https://github.com/officialaimm/recursiva), 50 bytes
* Only 10 bytes shorter than python and thus it is official, Recursiva is not a golfing-language at all... It is an esolang though. :D
```
|{Ba+++++'PJ" "W+Z~}B+~}'Va'+}'Va'AD'VaJ" "W*;aADa
```
[Try it online!](https://tio.run/##K0pNLi0qzixL/P@/ptopURsE1AO8lDiVwrWj6mqdtOtq1cMS1bXBpKMLkATLaVknOroA9RgaAAA "Recursiva – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~119~~ ~~116~~ ~~115~~ 107 bytes
```
i,j;f(n){for(;j<n;j++,printf("%d\n",2*n))for(i=0;i++<n;printf("%d\t",j+i));for(;j=i--;printf("%d\t",n*2));}
```
[Try it online!](https://tio.run/##fc1BCsIwEIXhfU4hASHTpJAEuhp7EzdSiUzAsdS4Kj17TFVoFWmW//uYdPWl63ImEzEohjHcBoXxwBi1Nv1AnIKS@/ORpfEVA8w7tRZJ64JWIEkTNQHg@0JLdf0zc@XLPOXriViBGMWuvP6R7kpy6yTgKwTlAD@5tDl9Qb9AvwmbBTab0NnV3/YvFZPITw "C (gcc) – Try It Online")
[Answer]
# [Röda](https://github.com/fergusq/roda), 44 bytes
```
f n{seq 1,n|[[seq(_,_1+n-1)]+2*n];[[2*n]*n]}
```
[Try it online!](https://tio.run/##K8pPSfz/P00hr7o4tVDBUCevJjoayNKI14k31M7TNdSM1TbSyou1jo4GUUBU@z83MTNPoZqLM03DVFOhRqGgKDOvRCNek6v2PwA "Röda – Try It Online")
Explanation:
```
f n{seq 1,n|[[seq(_,_1+n-1)]+2*n];[[2*n]*n]}
f n{ } /* Function f(n) */
seq 1,n /* Sequence 1..n */
| /* For each _1: */
seq(_,_1+n-1) /* Sequence _1.._1+n-1 */
[ ] /* As list */
+2*n /* Append 2*n */
[ ] /* Push to the stream */
[2*n] /* List [2*n] */
*n /* Multiplied by n */
[ ] /* Push to the stream */
```
[Answer]
# Dyalog APL, 29 bytes
Requires `⎕IO←0`
```
{(S,⍨1+¯1 ¯1↓∘.+⍨⍳⍵+1)⍪S←2×⍵}
```
[Try it online!](http://tryapl.org/?a=%u2395IO%u21900%u22C4%7B%28S%2C%u23681+%AF1%20%AF1%u2193%u2218.+%u2368%u2373%u2375+1%29%u236AS%u21902%D7%u2375%7D5&run)
## How?
* `1+¯1 ¯1↓∘.+⍨⍳⍵+1` the upper-left portion of the array
* `(S,⍨...)⍪S←2×⍵` the corner
[Answer]
# ><>, 84+2 Bytes
+2 for -v flag
Prints with tabs between values, and newlines between rows. Also prints a trailing tab on the last line.
[Try it online](https://tio.run/##S8sszvj/39CqyEqtSE3TPsYAwtKwj6lTsXIw0spLzDfUVuRKNNDTB8oY1NnoGZprG@ZbxijEAOWBSDvPEqiCS0FBIQZsgjVEm4L@////dcsUDA0A)
```
1:r:&r&)?\0:r:&r&(?\~$:@2*nao1+!
a0./:r:0~<.17+1o9\ \$:@$:@+n9o1+
\&r&)?;$:@2*n /
```
## Pre-golfing
```
1>:r:&r&)?\0> :r:&r&(?\~$:@2*nao1+\
\+1o9n+@:$@:$/
\ /
\~0>:r:&r&)?;$:@2*n9o1+\
\ /
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 22 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
∫HA.∫a+}.«¹}¹.I.«r∙rο+
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjJCSEEuJXUyMjJCYSslN0QuJUFCJUI5JTdEJUI5LkkuJUFCciV1MjIxOXIldTAzQkYr,inputs=NQ__)
leaves output on the stack, which you can view in the console
[Answer]
# Jelly, 14 bytes
```
R+’r@R;€Ḥz0;€Ḥ
```
[Try it online!](https://tio.run/##y0rNyan8/z9I@1HDzCKHIOtHTWse7lhSZQBluP///98UAA)
[Answer]
# [Perl 5](https://www.perl.org/), 56 bytes
```
$,=$";say($_..$_+$"-1,$"*2)for 1..($"=<>);say(($"*2)x$")
```
[Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybo4sVJDJV5PTyVeW0VJ11BHRUnLSDMtv0jBUE9PQ0XJ1sZOE6xGAyxRoaKk@f@/6b/8gpLM/Lzi/7q@pnoGhgYA "Perl 5 – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 59 bytes
```
Array(n+1){c->Array(n+1){r->when(n){c,r->n*2;else->1+c+r}}}
```
[Try it online.](https://tio.run/##rZDLCoMwEEX3fsXgKtEqjdBNH4Euuui6XxDER1qdSIx9IPn2NFgE93V2l3vPWcxDmUaik22ntIG7eIp0MLJJoyAoB4RWSCRCV/0ezlqLz/FmtMSKUxgD8NcKn9@E0bRU@iLyGkaAzk9Mg2Qi@tSoH0SkoRTATuC8CUO6FGVriXZridj2L5Od/zjJcA9XNBRObuIJxoyOecIXSSf8VRdI0BcbHzDKDkXTFwlncR5ra61zXw "Kotlin – Try It Online")
[Answer]
# Clojure, 153 135 bytes
List of lists? Yay, Lisp
```
(fn[n](loop[r[] i 0 d (* 2 n)](if(= i n)(conj r(conj(repeat n d)d))(recur(conj r(conj(vec(map #(+ i %)(range 1(inc n))))d))(inc i)d))))
```
Ungolfed:
```
(defn a[n]
(loop [r[] i 0 d (* 2 n)]
(if(= i n)
(conj r(conj(repeat n d)d))
(recur
(conj r
(conj (vec (map #(+ i %)(range 1(inc n)))) d))
(inc i)
d))))
```
Anonymous function that takes the input as argument and returns a list of lists.
Output of n=5:
```
[[1 2 3 4 5 10] [2 3 4 5 6 10] [3 4 5 6 7 10] [4 5 6 7 8 10] [5 6 7 8 9 10] (10 10 10 10 10 10)]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
FLN+I·¸«ˆ}·¸I>.׈
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fzcdP2/PQ9kM7Dq0@3VYLYnja6R2efrrt/39TAA "05AB1E – Try It Online")
**Explanation**
```
F # for N in [0 ... input-1]
L # push range [1 ... input]
N+ # add N to each
I·¸« # append input*2
ˆ # add to global list
} # end loop
·¸ # push [input*2]
I>.× # repeat it input+1 times
ˆ # add to global list
# implicitly output global list
```
[Answer]
# J, 29 bytes
```
(}:@(][\1+i.@+:),]#+:),.>:#+:
```
## ungolfed
```
(}:@(] [\ 1+i.@+:) , ]#+:) ,. >:#+:
```
## explanation
```
(}:@(] [\ 1+i.@+:) NB. make the inner part of the matrix
1+i.@+: NB. 1..2*n, where n is the input
(] [\ 1+i.@+:) NB. fork: infixes (sliding window) of length n, over 1..2*n
(}:@ NB. remove last element
, ]#+:) NB. add a row of 2*n to the end
,. >:#+: NB. add a column of 2*n to entire result above
```
[Try it online!](https://tio.run/##y/r/P81WT0Gj1spBI1YhOkbBUDtTz0HbSlNBRyFWGUzrKdhZAVlcqckZ@QppCoYQhro6TMAIXcD0/38A "J – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 23 bytes
```
;;Rnkp@;r♀+@;τ;(♀q)@α@q
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9/aOigvu8DBuujRzAZtB@vzLdYaQFahpsO5jQ6F//@bAgA "Actually – Try It Online")
Explanation:
```
;;Rnkp@;r♀+@;τ;(♀q)@α@q
;; two copies of input
R range(1, input+1)
n copy input times
kp@ push stack to list, remove first element
;r push range(input)
♀+ pairwise addition (add the value in the range to each value in the corresponding list)
@; duplicate input again
τ; input*2, duplicate that
(♀q) append input*2 to each list
@α@q append a row of input*2
```
[Answer]
# [Clojure](https://clojure.org/) v1.8, 97 bytes
```
#(conj(mapv(fn[i](conj(vec(range i(+ % i)))(* 2 %)))(range 1(inc %)))(vec(repeat(inc %)(* 2 %))))
```
[Try it online!](https://repl.it/Kotn/0)
# Explanation
```
(range 1(inc %)) Numbers from 1 to 'n'
(mapv ... (range 1(inc %))) For each one of these numbers
(fn[i](conj(vec(range i(+ % i)))(* 2 %))) Create the numbers from 'i' to (n+i-1), convert to vector and insert '2*n' to the vector
#(conj ... (vec(repeat(inc %)(* 2 %)))) Insert to the previous vector a vector of repeated '2*n's
```
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 93, 82 bytes
```
SUBROUTINE M(n)
PRINT*,(CHAR(10),(i-1+j,i=1,n),2*n,j=1,n)
PRINT*,(2*n,j=1,n+1)
END
```
[Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/gcE@bsHOfoqOHM5O/r4KPhqGGrCWEZwlimcZWigyeXq5/I/ONQpyD80xNPPFSiYp8kVEOTpF6Klo@Hs4RgEUqSjkalrqJ2lk2lrqJOnqWOklaeTBWbCVcKFtA0hRv4HAA "Fortran (GFortran) – Try It Online")
]
|
[Question]
[
In this challenge you will take two lists as input and you will *zip* them. The zip can be defined with this recursive expression:
\$
\mathrm{zip}(a,b) = \begin{cases}
\left[\,\,\right] & a = \left[\,\,\right] \\
[a\_0]\mid\mid\mathrm{zip}(b, t) & a = [a\_0] \mid\mid t
\end{cases}
\$
or this Haskell program if you would like:
```
zip [] _ = []
zip (x:xs) ys = x : zip ys xs
```
In simple terms you create a list which alternates between elements of the two input lists, starting with the first element of the first list, then the first element of the second list and so on, until one of the lists doesn't have the next element, then you stop.
For example if we zip `[1,2,3,4,5]` and `[11,12,13]` we get `[1,11,2,12,3,13,4]`. Every element appears in the output except `5`, which is missing because the second list ran out before we reached it.
## Task
As input you will take two lists of positive integers and output the result of *zipping* them as described above. I use the term "first" and "second" when referring to the inputs, but you may take the two lists in the opposite order (although this choice must be consistent, you cannot e.g. swap the order of the inputs depending on what they are).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code as scored in bytes.
## Test cases
```
[] [] -> []
[] [1,2,3] -> []
[1,2,3] [] -> [1]
[1,2] [3] -> [1,3,2]
[1,2,3,4,5] [11, 12, 13] -> [1,11,2,12,3,13,4]
[9,9,9] [8,8,8] -> [9,8,9,8,9,8]
[1,2,3] [4,5,6,7] -> [1,4,2,5,3,6]
```
---
As a word of advice if your language has a built-in which solves the task try and solve the task without the builtin and post both solutions as a single answer. It's more interesting to read solutions like that and it will almost certainly be more fun for you to golf.
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
```
def f(X,Y):print X.pop(0);f(Y,X)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNxVSUtMU0jQidCI1rQqKMvNKFCL0CvILNAw0rdM0InUiNKHqatLyixQSFTLzork0omN1FKJjNXWALEMdIx1jENdEx1THDJuYjjlE1EAHXW2sFZcC2EqlaCUuhZKiSqs0Da1ETS6F1Irk1IISiHOUYmPylCBugLkZAA)
Ends with an error.
## [Python](https://www.python.org), 35 bytes
```
f=lambda X,Y:X and X[:1]+f(Y,X[1:])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ldNscxJzk1ISFSJ0Iq0iFBLzUhQioq0MY7XTNCJ1IqINrWI1oUpTC4oy80o00jSiY3UUomM1NbngAoY6RjrGIFETHVMdMzxSOuYokgY6GDohlsHcBwA)
No error.
# [Whython](https://github.com/pxeger/whython), 33 bytes
```
f=lambda X,Y:[X.pop(0)]+f(Y,X)?[]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWNxXTbHMSc5NSEhUidCKtoiP0CvILNAw0Y7XTNCJ1IjTto2OhClMLijLzSjTSNKJjdRSiYzU1ueAChjpGOsYgURMdUx0zPFI65iiSBjoYOiGWwVwHAA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ζ˜#R`
```
Input-lists in reversed order.
1 byte is added to deal with the edge case of two empty input-lists, which otherwise would result in an empty string. Otherwise the two trailing bytes could have been `н` (pop and push first inner list) instead.
[Try it online](https://tio.run/##yy9OTMpM/f//3LbTc5SDEv7/jzY01DE00jE0juWKNtQx0jHWMdExjQUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCscvRBf/PbTs9Rzko4b/O/@jo6Fid6NhYHQUww1DHSMcYwoMwYXLGEEmolKGOoZGOoTFMg46JjilExkIHCIHCljpACBECyumY6ZgjDI8FAA).
**Explanation:**
```
ζ # Zip/transpose the two (implicit) input-lists, with space " " as filler
˜ # Flatten this list of pairs
# # Split it on spaces
R # Reverse the list of lists
` # Pop and push the lists to the stack
# (after which the top list is output implicitly,
# or the (implicit) input-list if both lists were empty)
```
[Answer]
# [Haskell](https://www.haskell.org), 19 bytes
```
(a:x)#y=a:y#x
o#_=o
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dY9NCoJQFIXnreKAgQVP6L8QXEBrEImX3VLU-8R3o1xLEyfRAlpJw3aTFUEETc7k45yPc7ok2maU501z3svWW1x72j_2nTrQfu0cO8ZZBeZN7rdCp4wAG9NBWaUs6IURHLTh-wiXLLSjKuoDngcm2lhoZiNaUsNYU6z3liB1SYgTijOq2imy7AoyNgdIQqCilBp5asW1oJwKajXPykfZRThUIzV-iSdqqmbRf6Tm33CgfpvvY5_rDw)
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~37~~ 28 bytes
*-9 bytes thanks to [@DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)*
```
[H|T]+B+[H|Y]:-B+T+Y.
A+_+A.
```
[Try it online!](https://tio.run/##VUy7CoNAEOzzFWKl3JygeQsRzjQpLC0ixxJsEgSNhwppxF@/rDFFwjI7M8zsmq6t24fsX5W1@jLmJFLBXFAsU5GLIlgpcRMqsLFsSlNX/eDpjJLEy05aIR3PBMUnV9zbrikHz50MnMk4MuE9PV3MLVzJ96G1JmhizBwiwvpjFvVN2DD9BNhgO9dDOGHEWKIjeFgcwPP3hevYYU9EfmDf "Prolog (SWI) – Try It Online")
Port of the Haskell solution.
[Answer]
# [R](https://www.r-project.org), 36 bytes
```
f=\(a,b)if(sum(a))c(a[1],f(b,a[-1]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZA9DoJAEIVj6yUkxGImeRTDnxCjFwGKlWQTCy0UTmODhYfS0zgLEgPRTF6z7337JnO7X7ru0TY2yJ5ruyvJ4MBHS9f2RIa5JlNIBUsHmCKQinnIvhYrSzUxVLytTUO-F-y9oirPPi9HSxAi-uMP3pyXScDZU14QIZx9ghhJ3ybwJFTNEXExcUnR8JfOoePIDDoTKNeXj36srIVIsZnVxGonWpL2xHCn8bZv)
---
Slightly longer, but without recursion:
### [R](https://www.r-project.org), 43 bytes
```
\(a,b,x=rbind(c(a,0),c(b,0)))x[!cumsum(!x)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZDBCoJAEIbp2kuknnZohMbUlLAXUQ-6IXTQgyn4Ll0s6KHqaZp1i3AphmHY_f9v_mUv13a8Vcm97yo3eqwzUWCJQ9KWp-YoJJ82gFKUPACG1JZ9fe5rYQ-Qa-S5WFXsUyaAvSw64VjuwUrzrHFg-ZEIPdz-0bVm8jQzKHnOE27RM5agj8GURmiRx20ipGyknMTmLx0jlyIj5JpBMd-8-8eTORBD3BkxPssBh4QTof9pHPV8AQ)
[Answer]
# [J](http://jsoftware.com/), 19 18 17 16 bytes
```
0(i.~{.]),@|:@,:
```
[Try it online!](https://tio.run/##bY4xb4NADIV3fsVTF4JkUMwdJJzUKlKlTpmyRkxVUMjSpUOkVP3r9BkOyhAZ352fPz98G16KtMNrQArBFoGZF3g/HT@G7aYvfh9Fm8nhJxwkDFly@bx@IU2RB3R22/FEVJRwk76RoJm1Rm01oKzKudFB3CyrCWqwOvj/UY/KrNV6GukG@yUJNmN0LBizn@d0xfl6vYWZ1dglSXK599/c6dyCX/7Gc3yrlOIWIVaR0ElhHQkVxzJi4qUyAxVuylwYtbYaoYSIN8IguhfGRDV8xlz9lo5Sy2428pQr2tTt8Ac "J – Try It Online")
*-1 thanks to ovs!*
Consider `1 2 3 4 f 8 9`:
* `,:` Laminate with 0-fill:
```
1 2 3 4
8 9 0 0
```
* `|:@` Transpose:
```
1 8
2 9
3 0
4 0
```
* `,@` Flatten:
```
1 8 2 9 3 0 4 0
```
* `0(i.~{.[)` Take everything up to the first 0:
```
1 8 2 9 3
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 40 bytes
```
^
;
+`;(\d+),?(.*);(.*)
$1,;$3;$2
,?;.*
```
[Try it online!](https://tio.run/##LYq7CoAwFEP3@x0Vqgbhtj7J4OhPiCjo4OIg/n9tRQ6cEJL7eM5rC5md1rAIpVxp573MMdqqyJkkRkHjaZxgZFVICBQqHLx8Zgr@BTUaqkId1MuACHtE/m@c0aJ7AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^
;
```
Start with an empty output list.
```
+`
```
Until the first input list is empty, ...
```
;(\d+),?(.*);(.*)
```
... match the first element of the first input list, the rest of the first input list and the second input list, and...
```
$1,;$3;$2
```
... move the first element of the input list to the output list and swap the rest of the first input list with the second list.
```
,?;.*
```
Delete the input lists.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes
Anonymous tacit prefix function taking a list of two lists.
```
((>+2×⌊)/≢¨)⍴⍉∘↑
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X0PDTtvo8PRHPV2a@o86Fx1aofmod8uj3s5HHTMetU38n/aobcKjvqlewf5@QBGNR719j7qaH/WuASo6tN4YqAIoGRzkDCRDPDyDNQ2gag@tUFdQBxnRueBRV9ujrkX/09SjYxWiY9W5IAxDHSMdYwgPwoTJAXlANrKUjomOKUiHoY6hkY4hVMZSBwiBohY6QIhqDlC5jpmOeaw6AA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 51 bytes
```
sub f(@a,@b){if @a {@a[0],|f(@b,@a[1..*])}else{()}}
```
[Try it online!](https://tio.run/##bYy9CsIwFIX3PkXGRg7FW7UqLnmPkCGBFIQOYnCQmGePp7hElLPc@52fW7wvU63pEdTcGw8TdL7OyniVjbdbhxdxAG8Zho3TJS4p5l6XUi9d8k@2rIN1uv0EI3YN@vxfKSKCnxD2OKwDAhkhrX0GResE6s82i5hwXJ2uvgE "Perl 6 – Try It Online")
[Answer]
# [HBL](https://github.com/dloscutoff/hbl), 6.5 bytes
```
?.(211.'?,(2.
```
The `branch` macro isn't implemented in the online interpreter at the moment, so here's a 7.5-byte equivalent without it:
```
?.(1(1.)('?,(2.
```
[Try it!](https://dloscutoff.github.io/hbl/?f=0&p=Py4oMSgxLikoJz8sKDIu&a=KDEgMiAzIDQgNSkKKDExIDEyIDEzKQ__)
### Explanation
The longer version implements the spec directly:
```
?.(1(1.)('?,(2.
? If
. The first argument is truthy:
(1 Cons
(1.) The head of the first argument to
('? A recursive call with
, The second argument and
(2. The tail of the first argument
Otherwise, return the first argument (empty list)
```
The `branch` macro (`2`, in golfed HBL) takes several expressions and restructures them into a function call with two arguments. With six expressions, it works like this:
```
(2 a b c d e f) -> (a (b c) (d e f))
```
In this case, we have:
```
2 1 1 . '? , (2.) -> (1 (1 .) ('? , (2.)))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
f=->a,b{r,*a=a;r ?[r,*f[b,a]]:a}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5RJ6m6SEcr0TbRukjBPhrITItO0kmMjbVKrP1foJAWHW2oY6RjrGOiYxqrE21oqGNopGNoHBvLhZADigNldcx0zGHCIJVgmdj/AA "Ruby – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 139 bytes
```
l=[1...a.length+b.length]
g(A)=join(A,0l)[ceil(l/2)]
L=\{\mod(l,2)=1:g(a),g(b)\}
f(a,b)=\{a.\length=0:a,L[1...\min(\{L=0:l,l.\max+1\})-1]\}
```
Holy crap, it took me forever for me to get an actually working solution for this challenge in Desmos. I don't know if I'm severely overcomplicating this or what, but I got it to work so...
¯\\_(ツ)\_/¯
I'll see if I can golf this some more later, too tired to think about this right now :P
[Try It On Desmos!](https://www.desmos.com/calculator/gooyj6brzs)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/xskbanqi0p)
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 21 bytes
```
(a:b)#c=a:c#b
[]#_=[]
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z86VjneNjqWSyPRKklTOdk20SpZOel/bmJmnoKtQkFRZl6JgopCtKGOkY5xrIIykGUCZPwHAA "Curry (PAKCS) – Try It Online")
The Haskell answer almost works in Curry, but because of non-determinism it matches any prefix of the result. We can restrain it by adding two more bytes.
[Answer]
# APL+WIN, 27 bytes
Prompts for two lists as a nested vector
```
(^\0≠v)/v←,⍉⊃(⌈/⍴¨v)↑¨v←,¨⎕
```
[Try it online! Thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv0ZcjMGjzgVlmvplQEGdR72dj7qaNR71dOg/6t1yaEWZ5qO2iUAKJHdoBVDvf6Aurv9pXBqPetdoggkuGMdQwUjBGMyFsOCyQK6mBpKMgomCKVC5oYKhkYIhRNxSAQg1NSwUgBDZCKBKBTMFc00A "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
UMθ⮌ιW§θⅉ⟦I⊟ι
```
[Try it online!](https://tio.run/##FcqxCoMwEADQvV@R8Q6uw2k7ORWnDgXpVo4MhwYMxERjsP37FOf3xlnzmDTU@tK1T8uicYKNzNsdLu8OPGJ3@c4@OAOP8oyT@538AUQ0Q/axgPS6FxjSemaLXa0iwtRQSze6WxJm4oa4tdbW6xH@ "Charcoal – Try It Online") Takes input as a pair of lists. Explanation:
```
UMθ⮌ι
```
Reverse each of the two lists.
```
W§θⅉ
```
Cyclically index the lists according to the number of values already output and repeat until that list is empty.
```
⟦I⊟ι
```
Output the "next" value from that list on its own line.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
Uses Kevin Cruijssen's method from their [05AB1E answer](https://codegolf.stackexchange.com/a/244065/53748).
```
z⁶FḲḢ
```
A monadic Link that accepts a pair of lists, `[a, b]`, and yields a zipped list.
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//euKBtkbhuLLhuKL/w4fFkuG5mP//W1s5LDgsN10sWzRdXQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/7/qUeM2t4c7Nj3csei/zuH2o5Me7pzxqGmNZhaQeNQwR0HXTuFRw9zI//@jo6NjdaJjY7l0wAxDHSMdYwgPwoTJAXlANrKUjomOKUiHoY6CoREQQ@UsdYAQKG6hA4SoJgE16JjpmAMFYwE).
### How?
```
z⁶FḲḢ - Link: pair of lists [a,b]
⁶ - space character
z - transpose [a,b] with space-filler
F - flatten
Ḳ - split at spaces
Ḣ - head
```
[Answer]
# [Factor](https://factorcode.org/), ~~43~~ 39 bytes
```
[ f pad-longest vmerge { f } split1 . ]
```
[Try it online!](https://tio.run/##bZFdS8MwFIbv8ytedt/UVt2XKAh@3kxwejU2CNlpU2ybmMS5Mba/XtMOkeHOS@DkOS/nkJxMSK9t8z59njyO4ejzi2pJjtPaW@EgnNPSoRJe8RW1VvdngjNl4X1R5zCWvN8YW9QehcYVY1uGENugXXd2R/cEKc6P6C/Z/qMtO@W9wOWhV4IkRXJsGXVqy8NOp0e1LfoYdNUda2bIYMQyKnWdk/NYVWRzCr4sOLrHJuCYN9nhX24qYVgvivb7/XWIxWIxu5/c4eUBb6@306d5AC0P5ShiUyIo740bx7HUS8p1mXHnhfygtVQiDORSV7GI0/RsOOzHo8Eo6SPTFqIGrU0pauELXUNn@FYbeFU4tDtSCIkiS7zHDgvgzQ8 "Factor – Try It Online")
## Explanation
```
! { 1 2 3 4 5 } { 11 12 13 }
f ! { 1 2 3 4 5 } { 11 12 13 } f
pad-longest ! { 1 2 3 4 5 } { 11 12 13 f f }
vmerge ! { 1 11 2 12 3 13 4 f 5 f }
{ f } ! { 1 11 2 12 3 13 4 f 5 f } { f }
split1 ! { 1 11 2 12 3 13 4 } { 5 f }
. ! { 1 11 2 12 3 13 4 }
```
[Answer]
# JavaScript (ES6), 33 bytes
```
f=([v,...a],b)=>v?[v,...f(b,a)]:a
```
[Try it online!](https://tio.run/##dY9NDoIwEEb3noJlm4wlw59igh6EdFEQjIRQI4br1yl1oWHsZBZt35uvHcxi5vZ5f7z2k712zvWVqBdQShkNjazOyyVse9GAkfpkXGun2Y6dGu1N9KLWENVayohZcUxXO4ZHSCDdSiwfWDbE88gJHmfmBwFSAtgUyCBfn4cQYUK9zggSegI9hMRt/BKovHsEqp9o75d0@un/H6R0KODwJYfojICcggvt3g "JavaScript (Node.js) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
↑_ΣT0
```
[Try it online!](https://tio.run/##yygtzv5/aFvuo6bG/4/aJsafWxxi8P///@jo6Fid6FggBtGGOkY6xmAOkAWk4GwdYx0THVOQCkMdQyMdQ4iEpQ4QAhkWOkCIUApkABXrmOmYx8bGAgA "Husk – Try It Online")
Input is list of the two lists.
`T`ransposes using `0` to fill shorter rows, flattens (`Σ`) the result, and `↑` takes the longest prefix with all elements that are truthy using the function `_` (=negate; it would have been more-intuitive to use the `I`dentity function here, but for reasons that I don't understand this doesn't seem to work).
Pretty-much the same approach as [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/244065/95126) but independently found.
Note that the [Husk](https://github.com/barbuz/Husk) interpreter will not accept input consisting of only empty lists, presumably since it's unable to infer their type. The TIO link above successfully runs all the test cases (including the first, only-empty-lists one), since these are grouped together and run side-by-side, allowing the interpreter to infer that all lists are of numbers; but it fails when given the first test case on its own. I can't currently see a way to avoid this.
[Answer]
# x86 machine code (32-bit), 39 bytes
```
\x31\xC0\x89\xC5\x55\x87\x2C\x24\x39\xCD\x74\x19\xFF\x34\xAE\x8F\x04\x87
\x45\x40\x87\x2C\x24\x39\xD5\x74\x0A\xFF\x34\xAB\x8F\x04\x87\x45\x40\xEB
\xE0\x5D\xC3
```
[Try it online!](https://tio.run/##lVJtT9swEP6c/IqbEcKGFBLaDljpJGhB4suGgE9rqijkhVoKSZQ4LKPqX193Z5dSNgkxyYnvHj/33IsddR6iaLkl8yhr4gROaxXLYn/2dRkEoVKVvG9UEgSc10mkZJFztq@SVjEhBESzsILgWZaTqW0Ngflt1/Pbkeu3xye49/22j9/xkd8ejvDr4TnhY789QttD@/ISMbTPLpCHttsjPrMtILUeRvfcfxXGfaPgnm0onG8qvMZenL@oXaDXx9yjLhssaxUqGYHMFWD9nPbduFaORnbrKnKNmSW5@wp6a9ATMLctcqqBbeGo6scggKciQ9ksAW5bFiubegbb28l96ee@YgRFYZbpia2RsigNh7wvwIYh45Uw9phxrEk4wG4Zp5rIjBinosi816hHZqxRDwMF1lMlqqlyKm1h26tWnwoZQ1lhyWFVhb9My2iuW9IdlY2iW@U78x0SSosKNFPCENwBbqdEHcDentR8SyumnG3HzAGUm8gpBVoyxUD4NCQ6dMDMy7JSTFBzpOLCl1Y0SrMXNq3V4cLPN0@xha04SWWewI@r6@D65urbHR/f3jlwezNy9R/V4wLmvrkRyjjU17rBquVzUqScHAEH0DNxm7incTFAlY0xaQmaDuIL@DnTt@sK26ZMj6HMuZnbyxgaU7xRpZsWuvuBKS2ceK47Ree1k9ABrkc8mYr5Qrz1xEep2MmhA913I9acD@dYRTg0rv5fCfHMw0Pv/ZwnDtB6G3vsAK3/L5bKcOCzA0cmdvXOXXwky99RmoUP9bLz2D1cdr53/wA)
The algorithm is quite straightforward, but 32-bit x86 *really* needs more registers. Some ugly stack hacks are used to cope with the lack of registers.
The test cases in TIO relies on a GCC extension supporting C arrays of length 0. ISO C and C++ forbid 0-length arrays.
Since OP didn't specify the upper bound of integers, I tried to find some clever way using an array of bytes, and interleaving them with [`pdep`](https://www.felixcloutier.com/x86/pdep) or some SSE shuffle instruction, but that ended up using too many bytes.
```
# edi: dst, esi: arr0, ecx: len0, ebx: arr1, edx: len1
# eax: return, ebp: clobber
0: 31 c0 xor eax,eax
2: 89 c5 mov ebp,eax
4: 55 push ebp
5: 87 2c 24 xchg DWORD PTR [esp],ebp
8: 39 cd cmp ebp,ecx
a: 74 19 je 0x25
c: ff 34 ae push DWORD PTR [esi+ebp*4]
f: 8f 04 87 pop DWORD PTR [edi+eax*4]
12: 45 inc ebp
13: 40 inc eax
14: 87 2c 24 xchg DWORD PTR [esp],ebp
17: 39 d5 cmp ebp,edx
19: 74 0a je 0x25
1b: ff 34 ab push DWORD PTR [ebx+ebp*4]
1e: 8f 04 87 pop DWORD PTR [edi+eax*4]
21: 45 inc ebp
22: 40 inc eax
23: eb e0 jmp 0x5
25: 5d pop ebp
26: c3 ret
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 38 bytes
```
f(a,b)=if(a,concat(a[1],f(b,a[^1])),a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU_LCsJADPyVpQfZhelh66s96I8sUdLCSqHUpdSD3-KlIOI3-Tdm2yoigWSGmQnJ7Rm4q4-nMAyPS-_T_LXwmlGaXR1ndW4r7jU7S_C6BLuDJWPAZnbfOYTmqlmlexW6uhWvSiJJVMVNoz0Ui18550g6xTYiiwzLiU7wqwqN81fECusxZGEz2FkqIBVRDqm_XZLABlsimk_9PPgG)
`a[^1]` means skiping the first item in `a`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 27 bytes
```
read x<$1&&echo $x&&f $2 $1
```
[Try it online!](https://tio.run/##lY/bboMwDIbv8xSeloVGC@ocDi0S7HKXe4G2k9gGajWpqwrSIlGenTlAUTfaHWSC4t@ffzvPabFu8omsmn2WvoKJOQqRvazfgRshcuAaODY1u4ZdWpQZJSQd0o83cCpzmzw@JAnWJtZCXE2fluW02u032xL4Xe0cug63YCyHeNIWcnBuiuXWAQQNnhzJkWTtcNf90kMl@S39C3c66ix/YZeL/gM/nvL7BPAhOLMdAmrAH9sjG@PWuY1/PayTaQ8IYSYZy8ymZIsV0Ofe07@9o9LKG4Q@6wnsFMp7ApVHaY8pXwXWABW9ic7AoC2jJZAgwiNFQehcUXRURNf@nIwlRxWq2dHIJzkgm3DVfAI "Bash – Try It Online")
Port of pxeger's [python solution](https://codegolf.stackexchange.com/a/244055/15469) to Bash.
Input lists are taken as files (one entry per line). Output is one entry per line. Output contains extra blanks, which may be illegal and could be fixed at the price of some bytes, but I liked the simplicity of the translation.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 45 bytes
```
param($a,$b)for(;$a){$h,$t=$a
$a,$b=$b,$t
$h}
```
[Try it online!](https://tio.run/##bVBNS8MwGL73VwQJ0sDbQ/elYxSqRQ9eFLebiGRdSpVtqUmmwtbfXt8k7TY3ExKS5ytPW8lvoXQplssol0o0tEi2TcUVX4WUA52zQqpwQjnb0hKoSSgPHJ7QOV4DWtZNHQRpGBAcaZiGDEi3MfiLxtCD/hl1hDrRCefAfuvv4/3UCgMYejoGEvdwderY8rGVxKg6No4Bp1NdA053GuOpXf/Xw3dgBFdt@ADxIUaPGAsY2ZF7qe54XkaP8w@RG7J1AbR4V9oAoVrkcr3Ag/ipkBYLkhD6NvEiJfRmaRC5pEVr6RxeYIQ2GdcCJakPtuPGZjj1ZI/dWsxbPVi7/eVpmm20kSvf7vUoZbrJc6E1@sKuyI5kcv0llJnJ6EHLNSOR@ER63/1McChwMcOuxJa9sFX2zU8tJMrkqsIH9cH73P2Htkj3BXXQ/AI "PowerShell Core – Try It Online")
One test case returns `1` instead of `[1]` as PowerShell tends to flatten arrays
*-1 byte thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy)*
[Answer]
# [Julia 1.0](http://julialang.org/), 25 bytes
```
a^b=@show(a[1])b^a[2:end]
```
[Try it online!](https://tio.run/##VY7bbsIwDIbv@xS@TCSvksthYxITL7AnqApyIRNBUajSMODpi7OGw@Iksn9/@Z3DyVmmyzDwul2u@v3xrLimRrdrrqtP43fN8HMMYMF6CIZ3znrTK12ALMYWN2hgCX3nbFT2KSfR/LIr1beJXHYcelMq9dfSeuS6YH10/v4shivIJ2DLcbuHDcjsf5guRBnqBmS/fcldpJywwslDyFUmaFSkzgThRMqM4RRnyYCQKqQHQalJqU@CCLxACQE/UGKkFpLm8zJU/HCO73ejqcgzsZk3Nw "Julia 1.0 – Try It Online")
prints the values and ends with an error
# [Julia 1.0](http://julialang.org/), 30 bytes
```
>(b)=[]
>(b,a,A...)=[a;A>b...]
```
[Try it online!](https://tio.run/##XY1rasMwEIT/@xT7U4KtYPNqQ7EgB@gJgilrooKKUIztlt7eHcVqWqrVY2f2Y/T@kaLK17J409v23DV4WfnknIPU55Pv0XbL23WkSDHTGPSSYg6TsQ1hKff8yoFamoYUZxN/7WKGT03OvIRZ3aDjFJwxt5G1KzeMMc8p31xLrSfTey2f/xtXl1pE2ibky3LuCPvB425KL7zh7d2oqhKyOtCVEN5CVox3vC8BwrJhuRNShlLmAgTwkVEAnxi1Uke09fz5FHl84MefoB3sPWIO3Tc "Julia 1.0 – Try It Online")
expects `b>a...`, returns an actual list
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 68 bytes
Takes `0`-terminated arrays as input.
```
f(a,b)int*a,*b;{for(;*a;!*b?a=b:b++)printf("%d %d "+3*!*b,*a++,*b);}
```
[Try it online!](https://tio.run/##hVHJTsMwEL37K4YgJHsyINKym5QfqLhxqirkhUAkSFDacon87cFOoERJVGRbtuctHuuZ01djmibjirTIiy0qQi3rrKy4RCWPUD@oVN/pOBaflcczHp1Y8DOK5@hRQhXHXiKka47zwrzv7Avcb7Y2L8/eFox9lbmFVvmsqor7HVAJqBnA7xvCnwF67lFrKiRzjAXBh8oLHow6XeexWqd1Kwyeq7Wozx0dvCc0ozlNVaeZF3Q5Qm4pjMPOj0/LpT84AtT/Njnd1PA@0XZCyYySMXBDYQyr4S9XdD3uEdH4ZSX7ycOkimyqJaCRYHyy1gcB9V9CbYpofDj90AiifqUj2QEJ0sWelvHw8J6x22541GGOueYb "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
Zf0€÷^
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJaZjDigqzDt14iLCIiLCJbMTEsMTIsMTNdXG5bMSwyLDMsNCw1XSJd)
Looks like 05AB1E beats Vyxal this time. Takes input in reversed order.
```
Zf0€÷^ # Leaving out this comment makes the explanation kinda feel empty
Z # Zip the lists
f # Flatten
0€ # Split on 0
÷ # Push every item
^ # Reverse the stack
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
Zf:0ḟẎ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJaZjow4bif4bqOIiwiIiwiWzExLDEyLDEzXVxuWzEsMiwzLDQsNV0iXQ==)
A slightly different approach. Still 6 bytes.
```
Zf:0ḟẎ # Leaving out this comment makes the explanation kinda feel empty
Z # Zip the lists
f # Flatten
: # Duplicate the top of the stack
0ḟ # Index of the first 0
Ẏ # Take everything up until that index
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
Zf0€h
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJaZjDigqxoIiwiIiwiWzExLDEyLDEzXVxuWzEsMiwzLDQsNV0iXQ==)
Takes input in reversed order. Returns 0 for the case of 2 empty lists, so does not meet the spec.
```
Zf0€h # Leaving out this comment makes the explanation kinda feel empty
Z # Zip the 2 lists
f # Flatten them
0€ # Split on 0
h # Get the first item
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
íV c óÏ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=7VYgYyDzzw&input=WzEgMiAzIDQgNV0KWzExIDEyIDEzXQotUQ)
```
íV c óÏ :Implicit input of arrays U & V
íV :Interleave U with V, padding V with null
c :Flatten
ó :Partition before elements
Ï :That are falsey
:Implicit input of first element
```
## 5 bytes
By taking input as a 2D array, with the order reversed.
```
ÕcÔóÏ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=1WPU888&input=WwpbMTEgMTIgMTNdClsxIDIgMyA0IDVdCl0KLVE)
```
ÕcÔóÏ :Implicit input of 2D array
Õ :Transpose, padding the first array with null
c :Flat map
Ô :Reverse
óÏ :As above
:Implicit input of first element
```
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 5 bytes
```
Zf0sh
```
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJaZjBzaCIsIiIsIlszXVxuWzEsMl0iLCIzLjQuMCJd)
takes input in reverse order
[Answer]
# [Arturo](https://arturo-lang.io), 42 bytes
```
f:$[a,b][([]=a)?->a->@[a\0]++f b drop a 1]
```
[Try it](http://arturo-lang.io/playground?MkTYyC)
```
f:$[a,b][ ; a function f taking two lists a and b
([]=a)? ; is a empty?
->a ; if so, return a
-> ; otherwise,
@[a\0] ; the first element of a as a list
++ ; concatenated with
f b drop a 1 ; the result of calling f with b and a without its first element
] ; end function
```
[Answer]
# [Uiua](https://uiua.org), 9 bytes [SBCS](https://www.uiua.org/pad?src=0_7_1__IyBTaW5nbGUtYnl0ZSBjaGFyYWN0ZXIgZW5jb2RpbmcgZm9yIFVpdWEgMC44LjAKIyBXcml0dGVuIGhhc3RpbHkgYnkgVG9ieSBCdXNpY2stV2FybmVyLCBAVGJ3IG9uIFN0YWNrIEV4Y2hhbmdlCiMgMjcgRGVjZW1iZXIgMjAyMwojIEFQTCdzICLijbUiIGlzIHVzZWQgYXMgYSBwbGFjZWhvbGRlci4KCkNPTlRST0wg4oaQICJcMOKNteKNteKNteKNteKNteKNteKNteKNteKNtVxu4o214o21XHLijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbUiClBSSU5UQUJMRSDihpAgIiAhXCIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX7ijbUiClVJVUEg4oaQICLiiJjCrMKxwq_ijLXiiJril4vijIrijIjigYXiiaDiiaTiiaXDl8O34pe_4oG_4oKZ4oan4oal4oig4oSC4qe74paz4oeh4oqi4oeM4pmtwqTii6_ijYnijY_ijZbiipriipviip3ilqHii5XiiY3iip_iioLiio_iiqHihq_imIfihpnihpjihrvil6vilr3ijJXiiIriipfiiKfiiLXiiaHiip7iiqDijaXiipXiipziipDii4XiipniiKnCsOKMheKNnOKKg-KqvuKKk-KLlOKNouKsmuKNo-KNpOKGrOKGq-Kags63z4DPhOKInuK4ruKGkOKVreKUgOKVt-KVr-KfpuKfp-KMnOKMn-KVk-KVn-KVnCIKQVNDSUkg4oaQIOKKgiBDT05UUk9MIFBSSU5UQUJMRQpTQkNTIOKGkCDiioIgQVNDSUkgVUlVQQoKRW5jb2RlIOKGkCDiipc6U0JDUwpEZWNvZGUg4oaQIOKKjzpTQkNTCgpQYXRoVUEg4oaQICJ0ZXN0MS51YSIKUGF0aFNCQ1Mg4oaQICJ0ZXN0Mi5zYmNzIgoKRW5jb2RlVUEg4oaQICZmd2EgUGF0aFNCQ1MgRW5jb2RlICZmcmFzCkRlY29kZVNCQ1Mg4oaQICZmd2EgUGF0aFVBIERlY29kZSAmZnJhYgoKIyBFeGFtcGxlczoKIwojIFdyaXRlIHRvIC51YSBmaWxlOgojICAgICAmZndhIFBhdGhVQSAi4oqP4o2PLuKKneKWveKJoOKHoeKnuyziipdAQi4iCiMgRW5jb2RlIHRvIGEgLnNiY3MgZmlsZToKIyAgICAgRW5jb2RlVUEgUGF0aFVBCiMgRGVjb2RlIGEgLnNiY3MgZmlsZToKIyAgICAgRGVjb2RlU0JDUyBQYXRoU0JDUwo=)
```
↙⊗0.♭⍉⬚0⊟
```
[Try it!](https://uiua.org/pad?src=0_7_1__ZiDihpAg4oaZ4oqXMC7ima3ijYnirJow4oqfCgpmIFtdIFtdCmYgW10gWzEgMiAzXQpmIFsxIDIgM10gW10KZiBbMSAyXSBbM10KZiBbMSAyIDMgNCA1XSBbMTEgMTIgMTNdCmYgWzkgOSA5XSBbOCA4IDhdCmYgWzEgMiAzXSBbNCA1IDYgN10K)
Port of Jonah's [J answer](https://codegolf.stackexchange.com/a/244077/97916).
]
|
[Question]
[
Letters of the words want fairness.
They decided to appear same number of times in a sentence equally.
Example:
```
Priorities
```
Will become:
```
Ppprrioooritttieeesss
```
Each letter appears 3 times, as the most common letter was `i`, appearing 3 times.
It does not matter where you put the repeated letters, as long as they are next to a similar letter.
I.e.:
`Pppriooorritttieeesss` is OK (the 'r' letter)
`Ppprioororitttieeesss` is not OK (the 'r' letter)
Another example:
```
invoice
```
Will become:
```
innvvooiccee
```
Another example:
```
Remittance Advice
```
Will become:
```
Rrremmmiitttaannncce Adddvvvice
```
Space, comma, question mark, quotation, etc. are not considered letters for this challenge. Only need to consider [a-zA-Z]. Just once space is enough, and the order of the letters should remain the same.
The capitalization of letters does not matter, upper and lower case are countes as the same letter. That is: `Pip` has 2 'P's and 1 'I', so it will become `Piip`.
It is case insensitive letters can be in any form, `Piip=piip=piiP=PiiP`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
[Answer]
# [R](https://www.r-project.org/), 106 bytes
```
function(s){for(A in L<-LETTERS)s=sub(A,strrep(A,max(x<-+s-+Map(gsub,L,'',s,T))-x[A]--1),s,T);s}
"+"=nchar
```
[Try it online!](https://tio.run/##PcmxDoMgFIXh3acwLEKEoXN1YHCjibFuTQdKob2DYLhoTJo@OzVt0u1854/Ztdkt3iQIniJ7uRCpLMGXqhGqG8duODNscblRyTHFaOd9THqjWyNqFPVJz/SxZ654VXHkI2Niu8irEAf25RHfBalJ681Tx@wo6SOECAksElbsBr8GMPaHwU6QkvbGlvK@/u8eZsLyBw "R – Try It Online")
Base R approach :
* stealing some ideas from [@J.Doe R+stringr approach](https://codegolf.stackexchange.com/a/173341/41725), I saved 26 bytes !
* another 5 bytes saved using @J.Doe suggestion to abuse R `+` operator
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
lDáÙSйls¢Zα>×.;
```
[Try it online!](https://tio.run/##ATIAzf9vc2FiaWX//2xEw6HDmVPDkMK5bHPColrOsT7Dly47//9SZW1pdHRhbmNlIEFkdmljZQ "05AB1E – Try It Online")
**Explanation**
```
l # convert input to lowercase
D # duplicate
á # keep only letters
Ù # remove duplicates
S # split to list of chars
Ð # triplicate
¹ls¢ # count the occurrences of each letter in lowercase input
Zα # absolute valuue with max occurrence
> # increment
× # repeat each unique char that many times
.; # replace the first occurrence of the char in lowercase input with this
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 82 bytes
*-3 bytes thanks to nwellnhof*
```
->\a{a.=lc.=subst($_,$_ x a.comb(/<:L>/).Bag.values.max+1-a.comb($_))for 'a'..'z'}
```
[Try it online!](https://tio.run/##LY7NC4IwGMbP@le8jNGUdNKlQ6ZQ5w7RORhva8bALzYVS/zbzUWHh@fjd3laZcr9Ur1hU0AGS5zfcUKelZJntn/YLqAiogJGQC6b6hEkx8MlT0J@xhcfsOyV5RWO213851SEYdEYYMg4Zx82L6nvOmmNbozutLIkAqLrodFSuXhTle46rKWC03P4jeSqWwKT762/KK6/qJNIfa8IKIarW3TEn5cv "Perl 6 – Try It Online")
Takes a mutable string and modifies it in place.
### Explanation:
```
->\a{ # Anonymous code block that takes a mutable string }
a.=lc; # Lowercase
for 'a'..'z' # For each letter
.=subst( ) # Substitute
$_, #The first occurrence of the letter with
$_ x #The letter repeated
a.comb(/<:L>/).Bag.values.max # The count of the most common letter
+1 # Plus 1
-a.comb($_) # Minus the count of that letter already in the string
```
[Answer]
# JavaScript (ES6), 112 bytes
```
s=>(m=g=F=>s.replace(/[a-z]/gi,c=>F(c.toLowerCase())))(c=>g[c]=c+c.repeat(m-g[c]),g(c=>m=(n=g[c]=-~g[c])<m?m:n))
```
[Try it online!](https://tio.run/##bYu9CsIwFEZ3n8LNG@zPLt6KCJ0cxLV0CLe3IdIkJQkVHHz12NZN/MZzzveQkwzk9Rhz6zpOPaaAFRhUWGMVCs/jIImhbGT@akulM8KqBiqiu7on@4sMDGIezFw11CLtaXmxjGDyhYhMLdIgWFyL/L3iozmZgxUikbPBDVwMTkEPu5vXzuuoOeyE2PxIbSenif@YOxsdo7TE23M3fZv0AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
s => ( // s = input string
m = // m = max. number of occurrences of the same letter
g = F => // g = helper function taking a callback function F
s.replace( // (also used to store the # of occurrences of each letter)
/[a-z]/gi, // for each letter c in s:
c => F( // invoke F():
c.toLowerCase() // with c.toLowerCase()
) // end of call to F()
) // end of replace()
)(c => // invoke g() (second pass):
g[c] = // update g[c] to a non-numeric value
c + // append c once, unconditionally
c.repeat(m - g[c]), // and append c as many times as required to reach m
// (any subsequent iteration with the same letter will
// lead to c.repeat(m - g[c]) --> c.repeat(NaN) --> '')
g(c => // invoke g() (first pass):
m = (n = g[c] = -~g[c]) // increment g[c], save the result in n
< m ? m : n // and update m to max(m, n)
) // end of first pass
) // end of second pass
```
[Answer]
# [J](http://jsoftware.com/), ~~33~~ ~~56~~ 46 bytes
```
t=:~:tolower
(#~1+t*~:(*>./-])t*1#.e.)@toupper
```
[Try it online!](https://tio.run/##HYyxCsIwFEX3fsXDDmmjRrtGUqKbi4i7g8QXjGhTkmcdpP31GnLgwoUD5zmfDgIWApgFJRmsYJSwhbSZlJwk@Zf/YiisklU5NUvik6x4Kzbra028KQWKWpP/9D2GnKqLmELAzsH54MhhZDt27AbvDKZ3wbcj4rfOIPwy@/uQ1JhhBZqH11a3EOc/ "J – Try It Online")
Couldn't find a way to avoid using `~:tolower` twice.
### How it works
```
t=:~:tolower Auxiliary function: isupper
tolower Is lowercase version of itself...
~: different from itself?
(#~1+t*~:(*>./-])t*1#.e.)@toupper Main function
toupper Convert to uppercase
e. Build 2D array by comparing to itself
1#. Row-wise sum; Count occurrences
t* A) Filter by isupper (needed for finding max count)
>./-] Compute max of A) minus each element of A)
~: Nub sieve; 1 if first occurrence, 0 otherwise
* Filter first occurrences only
t* Filter by isupper again, to ban non-alphabets from duplicating
1+ Add one to preserve given chars
#~ Duplicate
```
[Answer]
# [R](https://www.r-project.org/) + stringr, 108 bytes
I am not very good at `stringr`. Returns a mixture of lower and upper case since the question says it doesn't matter.
```
function(x){for(l in L<-letters)x=sub(l,strrep(l,max(s<-stringr::str_count(tolower(x),L))-s[L==l]+1),x,T);x}
```
[Try it online!](https://tio.run/##JcwxC8IwEIbh3V9ROiWYDK61Hdw7iLiJSI0XOYgXuVxrQPztMej2Pt/wcfG9LX4mJxhJZf32kVVokJqxtwFEgJPOQ5qvKpgkzPCs8ZiySr2tRrpz19W4uDiTKIkhvoDrkxm1tuk0DkM4rzfaZHPU2/wpXrV7xsgoCKnVq2qkJaKDPw7wQJGJHDS72/Kbyxc "R – Try It Online")
## Explanation
```
function(x){
for(l in letters){ # Iterate through builtin vector "a", "b", "c"...
# Generate a 26-long integer vector for how many a's, b's, c's in lower case string
s = stringr::str_count(tolower(x),letters)
# Take the max of this
m = max(s)
# Repeat the letter in the iteration enough times to make the word 'fair'
new.l = strrep(l,m-s[letters==l]+1)
# Substitute the first instance only of the letter in the string for the repeated letter
# This is case insensitive (the T at the end)
# Notice we calculate the max letter frequency each loop
# This is inefficient but doesn't change the answer and avoids bytes
x=sub(l,new.l,x,T);
}
x # Return the substituted string
}
```
[Answer]
# [K4](http://kx.com/download), 35 bytes
**Solution:**
```
{x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x}
```
**Examples:**
```
q)k){x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x}"Priorities"
"PPPrrioooritttieeesss"
q)k){x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x}"invoice"
"innvvooiccee"
q)k){x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x}"Remittance Notice"
"RRRemmmiittaaanncce Noootice"
```
**Explanation:**
Might be golfable with a different approach, will keep thinking
```
{x@o@<o:(&^x),/(|/#:'g)#'g:" "_=_x} / the solution
{ } / lambda taking implicit argument x
_x / lowercase input
= / group
" "_ / drop space from keys
g: / save as g
#' / take each
( ) / do this together
#:'g / count occurances in each group
|/ / take the maximum
,/ / flatten with
(&^x) / indices where input is null (ie " ")
o: / save as o
< / indices to sort o ascending
o@ / apply these to o
x@ / apply these indices to original input
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ 32 bytes
```
⭆↧θ⁺§θκ×ι∧№βι∧⁼κ⌕↧θι⁻⌈Eβ№↧θλ№↧θι
```
[Try it online!](https://tio.run/##bY1BCsIwEEX3niLLCcQTuCqiIFgQ9QJjOujQJLVNUnv7OLWrgrMZ5s//79sXDrZDV8pl4JDglmQ9a3zDufvQYDES9Nqoi8sRqnQKDU3QG9WKdmdPEdioKjSw77LEH0ax1oty6DO6CK1RR5Zzzfu5ag5CrXFinz3MpZJfQGu307P930c4y@xKuZLnlDBYUlUzsqVN2Y7uCw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
↧ Lower case
⭆ Map over characters and join
κ Current index
θ Input string
§ Original character
⁺ Concatenate with
ι Lowercased character
× Repeated
ι Lowercased character
β Lowercase alphabet
№ Count
∧ Logical And
ι Lowercased character
θ Input string
↧ Lower case
⌕ Find
κ Current index
⁼ Equals
∧ Logical And
β Lowercase alphabet
E Map over characters
λ Current character
θ Input string
↧ Lower case
№ Count
⌈ Maximum
⁻ Minus
ι Lowercased character
θ Input string
↧ Lower case
№ Count
Implicitly print
```
[Answer]
# Java 11, ~~190~~ ~~176~~ 162 bytes
```
s->{s=s.toUpperCase();char m=2,i=64,a[]=new char[127];for(int c:s.getBytes())m-=m+~++a[c]>>-1;for(;++i<91;)s=s.replaceFirst(i+"",repeat((i+""),m-a[i]));return s;}
```
-14 bytes thanks to *@Nevay*.
Output is in full uppercase.
[Try it online.](https://tio.run/##hVFNT9wwEL3zK0a51FY@IKhq1aZZqSAqFakU9eOU5jDrHcAQO5E9WbRCy19fnKwB9VD1EnlmXt7Me@8W15jfru52qkPv4Rtq@3AAoC2Tu0JFcDGVAD/ZaXsNSsSHl1Xobw/CxzOyVnABFmrY@Xzx4GtfcP97GMidoichK3WDDkx9nOn63dsMm7a2dA9TtymP37fVVe9E2Anqoy@uiU82TF5IafLapI9pio1qF4u8nHFVmupPH8pKTmscDV0484t2noVOkyQLHUIWcyEzk2OjWykrRzw6C77a7qrp6mFcduHqePy61yswQXzU17SAMirfeCZT9CMXQxhxZ4UtlEgune6dZk0@kbMZ/4ZqG/gV/Rf3g4xmRhts/7xav/4x23x4CGdm7JBpBechNSjLmEoRJQcmCeghlvthNndFMA74hsCjIVgGe3PVj9NkSQpHTy@U2ts3DL2FX1@/w4b4NeCY/F/sYeamDYBmpttbFr2eIt7DxEvae1wrn4MTyZ@jJAssUeh29wQ) (NOTE: `String.repeat(int)` is emulated as `repeat(String,int)` for the same byte-count, because Java 11 isn't on TIO yet.)
**Explanation:**
```
s->{ // Method with String as both parameter and return-type
s=s.toUpperCase(); // Convert the input-String to full uppercase
char m=2, // Max occurrence (+1), starting at 2
i=64, // Index integer, starting at 64 ('A'-1)
a[]=new char[127]; // Create a count-array of size 127 (printable ASCII chars)
for(int c:s.getBytes()) // Loop over the characters of the String as integers
m-=m+~++a[c]>>-1; // Increase the occurrence-counter of the char by 1 first
// And if it's larger than the max-2, increase the max by 1
for(;++i<91;) // Loop `i` in the range ['A', 'Z']
s=s.replaceFirst(i+"",// Replace the first char `i` in the string with:
(i+"").repeat( // That same character repeated
m-a[i])); // The max(+1) minus its array-occurrence amount of times
return s;} // Then return the now modified String as result
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
ḟ§Ë#f√MṘO´πL¹m_
```
[Try it online!](https://tio.run/##ASoA1f9odXNr///huJ/Cp8OLI2biiJpN4bmYT8K0z4BMwrltX////0JlIGJlZXM "Husk – Try It Online")
Brute force, so very slow.
## Explanation
```
ḟ§Ë#f√MṘO´πL¹m_ Implicit input, say s = "To do"
m_ Convert to lowercase: t = "to do"
L¹ Length of s: 5
´π All length-5 combinations of [1..5]:
[[1,1,1,1,1], [1,1,1,1,2], [2,1,1,1,1], ..., [5,5,5,5,5]]
O Sort them lexicographically:
[[1,1,1,1,1], [1,1,1,1,2], [1,1,1,1,3], ..., [5,5,5,5,5]]
MṘ For each, replicate letters of t that many times:
["to do", "to doo", "to dooo", ..., "tttttooooo dddddooooo"]
ḟ Find the first string that satisfies this:
Example argument: x = "tto ddo"
f√ Letters of x: "ttoddo"
Ë They have equal
§ # number of occurrences in x: true (all have 2).
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-h`, 27 bytes
*-3 bytes from @ETHproductions*
```
;v
ñ oC ó¥ ú £=iXÎpXèS)UbXg
```
---
**Trying to explain**
```
;v Convert implicit input to lowercase
ñ oC ó¥ ú £=iXÎpXèS)UbXg Main function. Implicit lowercase input => "priorities"
ñ Sort => "eiiioprrst"
oC Remove non alphabetical chars
ó¥ Split on different letters => ["e","iii","o","p","rr","s","t"]
ú Right-pad each to the length of the longest with space => ["e ","iii","o ","p ","rr ","s ","t "]
£ For each X in this array:
XèS Count the number of spaces in X
XÎ Get the first character in X
p ) Repeat it (number of spaces) times
example the mapped value "e " will become "ee"
i Insert this into U at
UbXg the first index of (first character in X) in U
= Set U to the result
```
[Try it online!](https://tio.run/##AToAxf9qYXB0//87dgrDsSBvQyDDs8KlIMO6IMKjPWlYw45wWMOoUylVYlhn//8iUHJpb3JpdGllcyEiIC1o)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 89 bytes
```
->s{1while(a=s.scan /\w/).map(&g=->x{s.scan(/#{x}/i).size}).uniq[1]&&s[a.min_by &g]*=2;s}
```
[Try it online!](https://tio.run/##bY5NC4JAGITv/oqFwI/IFbvGCv2DiG4msdqmL@Rq@65fqb/dDCk6NMxhZg4Po6q4m25scgPs/SaDu7A5Q4oJl8Q7N55Dc17aZsrcoO2X3fZWfTt64FCEpxgdWkl4hH5kmhhymoO8xB0x02jNtjscp9A6ZYBkNidaoLY21kFBoUCDwLmArAtIxJyOIgetuUwE2V/rZeNkVmxF7xv9oIay0khuoYrG6RdjfDHGH4zxwbwA "Ruby – Try It Online")
I tried different approaches, but what really saves a lot of bytes is adding one character at a time.
### How:
```
->s{
1while # 1 is a nop to the while
(a=s.scan /\w/) # For all the letters in the string
.map(&g=->x{s.scan(/#{x}/i).size}) # Count occurrences ignoring case.
.uniq[1] # Break out of loop if all equals
&&s[a.min_by &g]*=2 # Otherwise duplicate the letter
# with the lowest count
;s} # Return the string
```
[Answer]
# Powershell 6, 123 bytes
*It uses a char range `'a'..'z'`. See script for previous Powershell below.*
```
param($s)for(;'a'..'z'|%{
if($d=($s-replace"[^$_]").Length-$n){if($d-gt0){1}else{$s=$s-replace"^(.*$_)","`$1$_"}}}){$n++}$s
```
Explained test script:
```
$f = {
param($s) # a parameter string
for(; # loop while exists at least one letter...
'a'..'z'|%{ # for each letter
$d=($s-replace"[^$_]").Length-$n # let $d is a difference between a number of current letter and current $n
if($d-gt0){ # if the difference > 0
1 # then return a object to increase $n on next iteration
}
if($d-lt0){ # if the differenct < 0
$s=$s-replace"^(.*$_)","`$1$_" # append the current letter after a last instance of the letter. Use "^(.*?$_)" regexp to append it after a first instance of the letter.
}
}){
$n++ # increment $n if exists at least one letter number of witch greather then $n
} # and make next iteration of the 'for'.
$s # return modified string if all letters in the string occur the same number of times
}
@(
,('Priorities', 'Ppprrioooritttieeesss', 'PPPriooorritttieeesss')
,('invoice', 'innvvooiccee')
,('Remittance Advice', 'Rrremmmiitttaannncce Adddvvvice', 'RRRemmmitttannnce Aadddvvviicce')
) | % {
$s,$e = $_
$r = &$f $s
"$($r-in$e): $r"
}
```
Output:
```
True: Pppriooorritttieeesss
True: innvvooiccee
True: Rrremmmitttannnce Aadddvvviicce
```
# Powershell 5.1-, 133 bytes
```
param($s)for(;97..122|%{$_=[char]$_
if($d=($s-replace"[^$_]").Length-$n){if($d-gt0){1}else{$s=$s-replace"^(.*$_)","`$1$_"}}}){$n++}$s
```
[Answer]
# [Red](http://www.red-lang.org), 252 bytes
```
func[s][a: charset[#"a"-#"z"#"A"-#"Z"]t: parse s[collect[any[keep a | skip]]]m: copy
#()foreach c t[c: form c either n: m/:c[m/:c: n + 1][m/:c: 1]]d: last sort extract next
to-block m 2 foreach c s[prin c: form c if n: m/:c[loop d - n[prin c]m/:c: d]]]
```
[Try it online!](https://tio.run/##TY5NasMwEIX3PsVD3rQUU9KldrlByTJCC3U0xsK2JKRpaErv7so0JN0M72eYbwr77cTe2G7U2/gZyVRrnAZNrlQW0yunhl59q14dd3FWVjTyXqIaSsvCJMbFq5mZMxx@UOeQrbVrO5LyteufnsdU2NEEghjSaHZtmoNMXBA11ldNZh8aES842Js5WOs1FlcFNRUBf0lxJIhNdJKGjyXRjBVveBCqySVEPDBhvCOWlDI8BsTbkv3j@PbutieCEeq9hFSCBK6qu4chXlIg/peceA0iLhLj6C97t/0C "Red – Try It Online")
Ridiculously long solution...
## Explanation:
```
f: func [ s ] [
a: charset [ #"a" - #"z" #"A" - #"Z" ] ; letters
t: parse s [ ; parse the string
collect [ any [ keep a | skip ] ] ; and keep only the letters
]
m: copy #() ; initialize a map
foreach c t [ ; for each character in t
c: form c ; the character as a string
either n: select m c [ m/:c: n + 1 ] ; increase the count if already in map
[ m/:c: 1 ] ; otherwise create a map entry with count 1
]
d: last sort extract next to-block m 2 ; convert the map to a block; extract only the
; numbers and take the last of the sorted block
foreach c s [ ; for each character in the input
c: form c ; the character as a string
prin c ; print it (with no space nor newline)
if n: select m c [ ; if c is a key in the map
loop d - n [ prin c ] ; print the character again up to d times
m/:c: d ; set the count to max (flag it as used)
]
]
]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~140~~ 137 bytes
```
x=>[...x=x.toLowerCase()].map(F=c=>(F[c]=-~F[c],F[c]>w?w=F[c]:w,c),w=0).map(c=>x=x.replace(c,c.repeat(c>'`'&c<'{'?w-F[c]+1:1),F[c]=w))&&x
```
[Try it online!](https://tio.run/##bYxBC4JAFITv/YrooLukS16tp4fAU4fuIrQ8n7GhrqyLKwT9dWvtFl1mBuabechJjmjUYONe17Q0sMyQlUKIGWZh9UU7Mmc5EuOV6OTACkDIWFFiBfHLW@Qlc7kDH1IXIY8cHPhKf1j/Y2hoJRLDCH0maRlm4S0M8BQ@w9zFfrpP0oSvb@A4D4J5OaLuR92SaPWdNWx3NUobZRWNO843v63qJ62Q/lWGOmWt7JG2sp6@0PIG "JavaScript (Node.js) – Try It Online")
+33 bytes from my first solution for those never-ending additional constraints. JS sucks at case-insensitive string manipulations you know.
-3 bytes back Thanks @Arnauld.
## Explanation
```
x => // The function.
[...x = x.toLowerCase()].map(f = c => (// - Iterate among each character...
// - Additional constraint 2
f[c] = -~f[c], // - Add one to the character counter
f[c] > w ? w = f[c] : w, // - Update the maximum count if necessary
c // - Return back the character for the use in
// the next map function
), w = 0) // - The counters
.map(c => // - Iterate again...
x = x.replace( // - Repeat the first appearance of
c, // - Each character
c.repeat( // - Needed number times
c > '`' & c < '{' // - Additional constraint 1
? w - f[c] + 1 // - If this is letter, repeat
: 1 // - If not, stay as is
), // - That should've been clearly stated
f[c] = w // - And set the counter so that no further
// replacements are done on this character
) // - (w - f[c] + 1 = 1 in further iterations)
) && x // - Return the result
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~77~~ 70 bytes
```
{s:i|$($!.min(*{*}).key)|$/$/|until [==] ($!=.lc.comb(/<:L>/).Bag){*}}
```
[Try it online!](https://tio.run/##FY6xCsIwFEXn9iueEGxSJN0crBF0dhBXEakxlYdNIkkslLbfHtPpXg7nwv0q122jHmDdgoij3@FEKFlxjYaWYzkz/lEDm0hFqulnAnZwE@IOSRG8k1xa/aTVfnc@VIyfmjdLkzm21kFxcWgdBlS@2ECBprco1VKvSmMIjZEKjq9@gTDmWbpAPAggjzrPWko8S@mbhdb5HP8 "Perl 6 – Try It Online")
Taking G B's approach of inserting a character until all characters appear the same number of times. Receives a string that is modified in-place.
If underscores can be treated like letters, the regex can become `/\w/`, saving two bytes.
### Explanation
```
{
.lc.comb(/<:L>/).Bag # Create Bag of letter/count pairs
($!= ) # Store temporarily in $!
... until [==] .values # Until all counts are equal
s:i| | | # Replace (ignoring case)
$($!.min(*.value).key) # letter with minimum count
$/$/ # with itself doubled
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~97~~ 117 bytes
```
s=input().upper()
S=''
for c in s:S+=c+c*(max(map(s.count,map(chr,range(65,91))))-(S+s).count(c))*('@'<c<'[')
print S
```
[Try it online!](https://tio.run/##JY7BCsIwEETv@YrQyyZtLSgqKC3oH4g9eqrravfQJCRpqV9fU3wwMAwDM@4be2t2C9oXNVmWLaFh48aodDU6R15p0TYA4m29RMlGhnNbNFhgroZuTnIqVGhHE8vVY@9L35kPqeOhPG11YqPaIuh/R6HWuYIL1FjDA7Rwnk2U7ZKWBc2Ecv2R7xe4ebaeI1MAAWwmy0jJ3WngGDuDJK@v6Z91MvGEHw "Python 2 – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~246~~ ~~223~~ ~~220~~ ~~210~~ ~~208~~ ~~193~~ 188 bytes
Compiler flag `-DF=;for(i=0;b[i];i++` `-DB=b[i]` (29 bytes)
Added mixed case support.
```
f(char*c){char m,i,s,*b,a[255]={0};s=asprintf(&b,c)F)B=tolower(B),a[B]++F,a[B]>a[m]?m=B:0)F)a[B]^a[m]?b=realloc(b,s+i),bcopy(&B,b+i+1,s),a[B]++:(m=B);puts(b);}
```
[Try it online!](https://tio.run/##NY5da8MgFIb/SulF0WohG/Sm4kal5HrsNmSgTtsDGoO6jhHy1@dMw67eD55zePVBOzlcS7FI32TcazwtuvEUaKJ7RWX3fDz2fGpmlrhMY4QhW7RTVOMWC56DC98mIoErKXpC2oe@yM73r56LU1Oxpfl4NIpHI50LGimaCGCqdBh/0E5QRYA80fT/5oTqMWbjV05IYTYXL2FAeLJoC8M9gDZbzGqoe0KEDCat@Q3G1bwbDznLQZvN@fO@8nP51dbJayqHi@Cqg76aljMbIgLesKVhQMgf "C (clang) – Try It Online")
[Answer]
# Pyth, ~~31~~ 30 bytes
```
JeSm/Qd=r0QVQ=tQ=+k*N-J/+kQN)k
```
[Try it here](http://pyth.herokuapp.com/?code=JeSm%2FQd%3Dr0QVQ%3DtQ%3D%2Bk%2aN-J%2F%2BkQN%29k&input=%22Priorities%22&debug=0)
### Explanation
```
JeSm/Qd=r0QVQ=tQ=+k*N-J/+kQN)k
=r0Q Convert input to lowercase.
JeSm/Qd Find the count of the most common character.
VQ ) For each character in the input...
=tQ ... remove that character from the input...
=+k*N-J/+kQN ... append copies to k until we have enough.
k Output.
```
[Answer]
# [C (GCC)](https://www.gnu.org/software/gcc/) - 175 Bytes
```
f(char*s){int c[999]={0},i=0,m=0,k,L;while((L=s[i++])&&(k=++c[L<97?L+32:L]))m=k>m?k:m;i=0;while(L=s[i++])for(L=L<97&&L>64?L+32:L,putchar(L);isalpha(L)&&++c[L]<=m;)putchar(L);}
```
**Ungolfed**
```
f(char *s) {
int c[999]={0},i=0,m=0,k,L; // Array used like a dictionary, temp vars
while((L=s[i++])&&(k=++c[L<97?L+32:L])) // store letter counts
m=k>m?k:m; // calculate max occurance
i=0; // reset string index
while(L=s[i++]) // iterate string
for(L=L<97&&L>64?L+32:L,putchar(L);isalpha(L)&&++c[L]<=m;) // set character L to lowercase if in alphabet, print always once, repeat if in alphabet
putchar(L); // print character
}
```
[Try it online!](https://tio.run/##dY4xT8MwEIX3/goTkGXjIEWAqFLXjRiRPCDWkCEyTnNK7FS2W4Yovz04UBBLh5Pe3b3v6am7vVLz3BDV1u7W0xFsQKrM87wSYzalILLUxOlSyT9b6DUhUvgSGKsoxqQTjKlSbvN1IdnD/UZWlBrR7UzRbQyP8Bn6Y5rBxWUBMJa7p8czlh6OYWlAJOXg6/7Q1lFi/J1ebYXh9J9jmpeWpgZLKBpXCDUkebGnAZR@zxLK4yW6PUl@dPy@OhgcBND@guFNGwihtkqj54/T5SA1DD1aenhUXF3f/LqcDkdnUcZX0/wF)
[Answer]
**Kotlin Android, 413 bytes**
```
var l: List<Char> = w.toList().distinct();val h = HashMap<Char, Int>();var x='m';var n=0;for(z in l.indices){var c=0;for (i in 0.rangeTo(w.length-1)){if(l[z]==(w[i]))c++};h.put(l[z],c);if(n<c){n=c}};for(entry in h){h.replace(entry.key,n-entry.value)};var v=ArrayList<Char>();for(i in 0.rangeTo(w.length-1)){if(h.containsKey(w[i])){for(p in 0.rangeTo(h.get(w[i])!!)){v.add(w[i])};h.remove(w[i])}else{v.add(w[i])}}
```
[Try online](http://rextester.com/live/PCPID64484)
Explanation
step 1 --> Select list of distinct chars.
step 2 --> Get count of every char in string and select max char frequency.
step 3 --> get difference in frequency of chars with respect to max char frequency
step 4 --> place chars with respect to positions in string.
Happy Solving !
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 145 bytes
```
x=>x.ToLower().Select((a,b)=>x.IndexOf(a)==b&char.IsLetter(a)?a+new String(a,x.GroupBy(d=>x.Count(e=>e==d)).Max(d=>d.Key)-x.Count(d=>d==a)):a+"")
```
[Try it online!](https://tio.run/##hY7BTsMwEETvfEWVA/KqrT8AcKpSQRURBKJIPW/spVhq15W9oe7Xh7jAmevMe6OxaW6THx57tndJoufdrHng/kARuz39RnUtlMQM2dRZv4c2nCgq0BvakxWlcNZBaRp2lF8@FIIx3bX9xKib1JLISCMscMp0mmwui6OT9TqG/nh/Vq7Iq9CzKDI1GeMA9DPmUjj9RGeY//UlMQYBbnBaVTDcXm2jF2o9k/r5OoJsUVR5rKrX6MMIeEoVAPxHv9HBiyBbmizdl7d0kYZv "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~185~~ ~~173~~ 170 bytes
```
function($s){$m=max($a=count_chars($s=strtolower($s),1));foreach(str_split($s)as$c)$o.=str_repeat($c,($b=$a[$d=ord($c)])!=($a[$d]=$m)&&$d>96&&$d<123?$m-$b+1:1);return$o;}
```
[Try it online!](https://tio.run/##PZBhS8MwEIY/218Ry7EmWMUqCNplw38w/DrHyNLUBtZcuNymIP72mg70073v897xwsUhTst1HKJwREh7chGJffiQ96oV0As99adg2WOQkNQ3jHo0XxKMtngKvLeDoZQTnZgYj/jpaN6rG6XaHskZO8gc7VM8ep4Tk8AqwLv5YG5zJmNbSzhoMFvoNFKXgdqpay0vZKdhVIsFdKvnp3ksm4fHNYy3cLhpXhrVkuMTBcD2Z/qvFNviqtqQR/LsXarqbH04o7fuot/c6JlNsE68duc/uvGxKnbCJAEsVOHsgFnVohR6Jco6v0MCq@zfQ9lOvw "PHP – Try It Online")
Ungolfed (and un-ternaried and un-optimized).
```
function f($s) {
$s = strtolower( $s );
$a = count_chars( $s, 1 );
$m = max( $a );
foreach( str_split( $s ) as $c ) {
if ( $c < 'a' or $c > 'z') { // is non a-z
$n = 1;
} elseif ( $a[ord($c)] == $m ) { // already has max number
$n = 1;
} else {
$n = $m - $a[ord($c)] + 1; // add this many chars
}
$o .= str_repeat( $c, $n );
$a[ord($c)] = $m; // has reached the max
}
return $o;
}
```
]
|
[Question]
[
This challenge was originally sandboxed by Magic Octopus Urn; I adopted and posted it with his permission.
*This is the cops' thread. The robbers' thread is [here](https://codegolf.stackexchange.com/q/154742/61563).*
## The challenge
* **Step One:** Write a piece of code (function or full program) which checks for [primality](https://en.wikipedia.org/wiki/Primality_test).
* **Step Two:** Remove pieces of your code by replacing characters with the symbol `█`.
* **Step Three:** Post the redacted code on the cops thread.
* **Step Four:** Wait for your code to be cracked and try to crack other's code.
For example, the Groovy code `{it.isPrime()}` could become `{██.is█████()}`.
(This one would be stupidly easy to crack; also, I know, `.isPrime()` is not a Groovy method.)
---
## Scoring
You must include your program's score in its submission. The score is defined as the ratio of redacted characters to characters. So if your program had 20 characters and 5 were redacted, your score would be 0.25. The Groovy code above would have a score of 0.5.
---
## Rules
* Your program only needs to handle *positive integers.* It should output a truthy value if the number is prime and a falsy value otherwise. Please specify in your answer what it outputs.
* Your code may not contain any comments or unnecessary whitespace.
* No hashing or cryptographic obfuscation.
* Your code may be no more than 50% redacted (at least 1/2 the characters must be shown). This means that the *highest* possible score is 0.5.
* If your answer is not cracked within a week you may mark it safe and edit in the intended crack.
---
## Winning
The winner will be the lowest-scoring uncracked answer within two weeks of posting. In the case of a tie, whichever has the most votes will win. This thread is always open to more submissions, but the winner chosen after two weeks will be permanent.
[Answer]
## 8086 DOS COM, 87 bytes, score 19/87 ~= 0.2183
[Cracked](https://codegolf.stackexchange.com/a/154980) by [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob)
```
1└╣██1█╛ü ¼<█t<< u≈¼<█t█,0|/<██+ô≈ßô☺├δδâ√█|█╞█S█Y╣██9┘t█ë╪1╥≈±○╥t█Aδ∩╞█S█N┤█║S█═!├A
$
```
This is a COM program; expects number as a command line argument, outputs Y or N. Limit: 65535 because 16 bit processor (sizeof(int) would be 2). Newline is 0x0D 0x0A on this platform. Yes you count 20 █ instead of 19 █. One of them's a real █ and has not been substituted. Muhahaha.
The space in position 10 is actually a NUL byte. The symbol for NUL is the same as space in the old VGA font.
[Answer]
# [Swift 4](https://swift.org), score 26 / 170 ≈ 0.153, safe
```
func p(n:Int)->Bool{func █(_ █:Int,_ █:Int)->Int{var h=(1...l).map{$0██m██
while(m=h.count,m██).1{h=[Int](h[█...])};return m}
return █>██&(█.███).index█j█n██0)>=█0}█=██l}
```
[Try it online!](https://tio.run/##TU9BCsIwELz3FTmIZEFTBT2opAdvXr2KSKmRRNK0NKkVSu@@wAf6kbgxIkJ2djI7O7C2Uxe38P7SmoLU1Kx3xsE021aV7j/a6/mgp4BhMvkx9CD2t7whktM5Y0wDK/O6H83Qga@MLemk0oKWXLKiajHhqwOb95IfMONI5QEFTDjCsGmEaxtDyiH5MhxlcWVMgy3yT4IyZ3FHdsUyUZxBxkMbEHiU9ODTlOxFrfNCECeVJZ1ykjhhHSlyK2xSN8o4Gq5fAvz9VgDevwE)
## Intended Crack
```
func p(n:Int)->Bool{func j(_ l:Int,_ k:Int)->Int{var h=(1...l).map{$0},m=l
while(m=h.count,m>k).1{h=[Int](h[k...])};return m}
return n>1&&(2..<n).index{j(n,$0)>=$0}==nil}
```
## Ungolfed
```
func p(n:Int)->Bool{
func j(_ l:Int,_ k:Int)->Int{ // Modulus function (l mod k)
var h=(1...l).map{$0},m=l // Create an array h of size l
while(m=h.count,m>k).1{ // While h has more than k elements:
h=[Int](h[k...]) // Remove k elements from h
}
return m // Return the length of h (equal to k if l divides k)
}
return n>1&& // Test if n > 1
(2..<n).index{j(n, $0)>=$0}==nil // and no number from 2 to n-1 divides n
}
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 37/540 bytes (score: 0.06851) ([Cracked](https://codegolf.stackexchange.com/a/155238/69059) by Nitrodon)
```
>>>>>+>,[>++++++[-<-------->]<+>,]<[-[█<█<]++++++++++<]>[-]>>██[>█>>█>]+[<]<<[<]>█<<+>>[>]█>[>]█+[<]<<[<]>-█>]>>[->]<[-[[<]<]++++++++++<]>[-]>[<█]>]>[>]<[[█]<]<<<<<[<]<<██>>[>]<█[->+<]<█>>[>]<[-[[<]<]++++++++++<]>███>[<<]>[[[>]>████[<]<[-[[<]<]++++++++++<]>[-]>[█<]>]>[>]<[[-]>+[>]<-<[<]<]+<<<<<[<]>[[>]+[[>]>]>[>]>[-<+>]<[<]<[>+[<]>>-<<<<<[[<]<]>>███████>[[█]>]<]<[[<]<]<[█]>]>>>[[>]<->>]]>[[>]>]<<[[[█]<]<]<<<[█]<<█>>>[>]█[-[[<]<]++++++++++<]>>[[>]+[------->++<]>.+.+++++.[---->+<]>+++.>>]>[>]+[------->++<]>++.++.---------.++++.--------.
```
[Try it online!](https://tio.run/##fVJBagMxDHyQYxPa6zAfETq0hUII9FDoH/KCPDAf2WikXSdpQ8Xu2pJGGnm8799vh6/Pn4/jslDWuDO2NOvoq9ERCYd1u5xP0OttGpzWnYxwPKY1HXozOBAfuYgeNLoytdzSPeGRFlWwKPGXwcTsgTOhNIqrAbIHUPzJoX30ikLM0NO2VZMjQSwWyFtQXfDfQKnEHCgiTbuOgm@jUV1btk5o1IYWnqhQWwj2AmchHya4G9Hq/CpLINZAXJwlMenFRgk7JZJItS85Vv2fnmsddrv5jI02Mj2sYhGSxzrOL3ATeGy/Ts/K6Y5lednvX68 "brainfuck – Try It Online")
Prints "prime" if prime, "not prime" if composite. Technically works for arbitrary integers but times out on TIO for numbers above 6000
[Answer]
# [Functoid](https://github.com/bforte/Functoid), score = 14 / 223 ≈ 0.062780 [safe]
```
Y(yG(BK██)(B(S(BS(C(BC(C(BB(B(v
S(CB█)(█C█B>vK BSBB())█K(BS(S?
>(KZ)(C(C(Bv>██ > v██<
█)Sg3I)$; @>B(BS(b(C(BBI)Iv>(█g
())I)))I)IBB(C(b(CB(C())))<v)█C
I))I))0)))(C(BC(B(BB)(C(BBv>)))
]I))))I))> >)█ $;@ >I)(B
```
Takes input as command-line argument and outputs `True` (prime) or `False`, [try it online!](https://tio.run/##LU8xDsIwDNzzigwd7A3UsZWpnAFFGTOBxAKIigUWiMQPeAEP5CPhnBLFTnzO3TmX5@30uF/Pte7otSVN388bm0kpk2YKpMGSAigOtbYuUkColOS9ZrSZUSej5I0TSnumRiyyKPr/EkRZoNGZVp77yN3gJ1FjH5tb5FjEXGYH5cgWES7B@nYA4bGYZ3CxvVgBWcaFjrYrzAG6g/HtibQBeJmmGyarIr5aa133Pw "Functoid – Try It Online")
**Hint (added 4 days after posting):**
>
> The first and 4th `█` are a red herring: The intended (and most likely *every*) solution's IP will follow the first line and reach the `?` character.
>
>
>
### Solution
```
Y(yG(BKL2)(B(S(BS(C(BC(C(BB(B(v
S(CBO)( C B>vK BSBB())OK(BS(S?
>(KZ)(C(C(Bv>O) > vY <
^)Sg3I)$; @>B(BS(b(C(BBI)Iv>(yg
())I)))I)IBB(C(b(CB(C())))<v)-C
I))I))0)))(C(BC(B(BB)(C(BBv>)))
]I))))I))> >)2 $;@ >I)(B
```
[Try it online!](https://tio.run/##LU@xCgIxDN37FR1uSAZB78Y7oqSDhAo3dDpBBxUPF120cF9fk2ohafJe3kt7/zyv79fjVsoEyx44HloEhgScIAAHS6xAdtrziOCDZ8rRe05KII7RRtPWEcQjQhVkGtH/D2nkyQ/ujGnuBJve74hNc6negpIJltmpl6CFqG8w1i5FcMi4Ck4qv9b@9zD14FrqOgXdydQ2QnUttpqbfme16JdKKZvuCw "Functoid – Try It Online")
### Explanation
Due to the randomness that comes from `?` it's not possible to flatten the program. Here's the flat program with a question mark where a random expression will be:
```
Y(yG(BKL2)(B(S(BS(C(BC(C(BB(B(?(yg(KZ)(C(C(BB(BS(b(C(BBI)I))))(C(BC(b(C(BBI)I)))I))(C-))))I))I))0)))(C(BC(B(BB)(C(BBI)(B]I))))I)))2$;@
```
Full program:
```
Y{trial_division} -- fix-point of {trial_division}
2 -- apply 2 (begin division with 2)
$ -- apply argument (work with the supplied input)
; -- print result as boolean
@ -- terminate program
```
The `{trial_division}`:
```
y -- recursive function with two arguments x,y
G -- | base predicate: x >= y
(BKL2) -- | base function: BKL2 x y
| -> K(L2) x y
| -> L2 y
| -> 2 <= y
{recursive_call} -- | recursive call
```
`{recursive_call}`, taking arguments `f` (self-reference), `x` and `y` (note `0` is the same as `False`)
```
B (S(BS(C(BC(C(BB(B{divides}I))I))0))) (C(BC(B(BB)(C(BBI)(B]I))))I) f x y
-> (C(BC(C(BB(B{divides}I))I))0) x y (BC(B(BB)(C(BBI)(B]I)))) f I x y)
-> (C(BC(C(BB(B{divides}I))I))0) x y (BC(B(BB)(C(BBI)(B]I)))) f I x y)
-> (C(BB(B{divides}I))I) x y 0 (BC(B(BB)(C(BBI)(B]I)))) f I x y)
-> (C(BB(B{divides}I))I) x y 0 ( B(BB)(C(BBI)(B]I)) f x I y)
-> {divides} x y 0 ( C(BBI)(B]I) f x y )
-> if x `divides` y then 0 else C(BBI)(B]I) f x y
-> f (B]I x) y
-> f (] x) y
-> f (x+1) y
```
`{divides}` is `?(yg(KZ)(C(C(BB(BS(b(C(BBI)I))))(C(BC(b(C(BBI)I)))I))(C-)))` where `?` is randomly chosen (depending on the random direction) from:
* `Y`
* `S(CBO)(CBO)`
* `S(SB(KO))(BBSBKO)`
These are all equivalent to each other, so `{divides}` becomes the fix-point of:
```
y -- recursive function with two arguments x,y
g -- | base predicate: x > y
(KZ) -- | base function: KZ x y
-- | -> 0 == y
{recursive_call} -- | recursive call
```
`{recursive_call}` is a pretty obfuscated expression that basically just does `f x (y-x)`
[Answer]
# Mathematica, 97 bytes, score 0.2989690722 ([Cracked](https://codegolf.stackexchange.com/a/154750/69850))
```
f[x_]:=(██ToString███████████████;StringMatchQ[████Infinity,RegularExpression@"█\█\█{█\█+, ███"])
```
Strings! Regex! Primes?
There *is* such a thing as a primality checking regex, but that's not whats happening here.
This has been [cracked](https://codegolf.stackexchange.com/a/154750/60042), but the way I intended was quite different, so I won't reveal the intended solution yet.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 0.(142857) ([cracked](https://codegolf.stackexchange.com/a/154835/41024))
```
25██26█966836897364918299█0█1█65849159233270█02█837903312854349029387313█ị██v
```
[Try it online!](https://tio.run/##JY3BCYBAEANbutvc7W4K8iO@BTsQ/NuM1WgjZ0RI8phAMk/Lso1h/Tl3yVxB94QnA95Y00jBIlfZewp2GmDxwWKKRLAA1bI3NBYjMlCh6r6Of3sd@nkB "Jelly – Try It Online")
Repost of my other answer, this time with a few more bytes revealed to avoid unintended cheats.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), Score: 0.15 (86 bytes)
I revealed several more characters. I thought the winning criterion was *highest* score, not *lowest*.
```
@(x)eval([(str2num(cell2mat([cellstr(reshape('0█1███1█0█0█00',████))])')█'█')','(x)'])
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IztSwxRyNao7ikyCivNFcjOTUnxyg3sUQjGsQCimoUpRZnJBakaqgbPJrWYQjEEARiGcCwgboOXAKINDVjNdU1gQx1ENZU11EHWqQeq/k/TcNIkytNwxhEmIAIUxBhpvkfAA "Octave – Try It Online")
Good luck =)
[Answer]
# Python 3, 388 bytes, .155, Cracked
Last-minute crack. Yes, this is the Miller-Rabin test.
I suppose probabilistic tests are allowed, uncertainty 2^-100
Well, a great hint in the previous sentence though
Made return value 0 as COMPOSITE and 1 as PROBABLY PRIME
\*368 > 388 : Fixed the problem when z<4
```
import ██████
def f(z):
if z<4:return z>>1
d,s,n,e,c=██z,0,z,0,50
while not ██1:d//=2;s+=1
while n>0:n//=2;e+=1
███████████()
while c>0:
a=0
while a<2or a>z-█:
a,b=0,e
while b>0:a=a*2+██████████████(0,1);b-=█
x,r=███(█,█,z),██s
if ██x and x!=██z:
while r>0:
x,r=███(█,█,z),██r
if not ██x:return 0
elif x==██z:break
else:return 0
c-=█
else:return 1
```
Solution:
```
import random
def f(z):
if z<4:return z>>1
d,s,n,e,c=~-z,0,z,0,50
while not d&1:d//=2;s+=1
while n>0:n//=2;e+=1
random.seed()
while c>0:
a=0
while a<2or a>z-1:
a,b=0,e
while b>0:a=a*2+random.randint(0,1);b-=1
x,r=pow(a,d,z),~-s
if ~-x and x!=~-z:
while r>0:
x,r=pow(x,2,z),~-r
if not ~-x:return 0
elif x==~-z:break
else:return 0
c-=1
else:return 1
```
[Answer]
# [095](https://github.com/nosekill/095), score 0.20512820512 [Safe]
```
1id#█#=(DD#█#█{d_█%(█D0█]D}██s]D1.=[1s]
```
Prints 1 if prime, 0 if composite
Solution:
```
1id#2#=(DD#2#-{d_.%(rD0R]D}drs]D1.=[1s]
```
[Answer]
# Node JavaScript, score: 0.4
[Here's where it works.](https://tio.run/##fU9bCsIwEDyNkmALSWpMSh8epPRjbftRP6KJDzyCJ/CAXiQmJAgtWthlZh/D7hzhDpfOjOdrqk79YK0Z9G00w/v1XA5WliywWs1GZvQddPgnfeBZA@WMUoc7mZE4Q5B0uKqh6RrSLn@COvx7Axd99S02qtDVxIAQggea8902aTjxhnie@E9a3DhocQFRpGsy8YhUpR2Cy7XLVKfxKARUK70PLOoQzQTl/oRkgiSMMSkxAmytpfQD) Full program that takes input from first command line argument, and outputs to stdout.
Hopefully, a not-so-difficult solution to start this off.
Using [this snippet](https://tio.run/##fU/RCoIwFH3vKyQqdslsruYUnX2ISKxl5MtqK6H6gr6gD@xHbKIERQm7nLNz7@HeY6rNta41HyWeKcTWk3thToOjoz15qNQZDZ@P@xCcuRVO5a3wzof1rq5NoavSFLbX/0iSkJal6qtlykZBm3/WC3wJKCK@bzEIF7jrIeFK4KnIZIbz/kuQhN8TEG/5@zNVseYfARhjtKURDZZuRnETiEZuc0kOmYUcYtGZdIo/MiLFtUVha2JrpmfdUtGiGutVyzof8hfMp82KkDDsEkLCEJCAFw) to calculate score.
```
require███████████2<<2██>n█████rin█(b████████x)█████(9211█6830)██(a,c)=>a[c[0]██████████(c)]███████);d=███+n;q=████27775██9564,[502█59,█6])[█]);a=██q>0████r(n=q█a█&█-q-██)a██n%q?██0██(137152█8270,22288)(a)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 0.(142857)
```
25██26█9668368973649182992051██5849159233270202█837903312854349029387313█████
```
[Try it online!](https://tio.run/##PY3BCcAwDANXcqTYsQbqp2SBbtAJOmAXSQ2BwqHHIaHzmPNaC/4@d4GoUEQyUoPR1RISzNsueJZygcQwGEolh4xsSO/sMog52LgHP6tePg "Jelly – Try It Online")
Takes a command-line argument.
False = `0`
True = `1`
[Answer]
# JavaScript, 103 bytes, score 0.1923
`x=>{if(x<4)return(!0);for(y=x>>>Math.log10(p=████;--y-1;(p=x/y%1)████if(██&&(███))break████return(███)}`
Returns a boolean.
[Unintended crack](https://codegolf.stackexchange.com/questions/154742/cops-and-robbers-redacted-primality-robbers-thread/154819#154819)
[Answer]
## Javascript, score 0.1894093686354379
```
let t=[2,3,3,3,3,3,3,5,7,5,7,5,7,7,11,12,13,11,13,13,1,2,17,13,2,3,17,19,23,29,19,19,41,23,23,29,23,"","",29,7,31,31,524,31,37,33,34,41]; function r(a, b) {█████████████████████████████████████████████████████████████};function l(t){let a=0;let b=[];while(true){b.push(t[a]);█████████████;if(!t[a]){return█████};function p(v) {let i=0;let a=r(2,v██);for (i in a){if(v%(█████████a█i██)==0){return false;}};return true;};function f(v){if(l(t).indexOf(v)!=-1){return true;}else{return p(v)};};
```
Good luck. :p
call f with the prime you want to check.
[Answer]
# ><>, score 0.096, [cracked by Jo King](https://codegolf.stackexchange.com/a/154979/61384)
```
:1@v>~~:?1n;█$-1<█?=2:}*{█@:$@:
```
Intended crack:
>
>
> ```
> :1@v>~~:?1n;
> $-1<^?=2:}*{%@:$@:
> ```
>
>
>
>
[Answer]
# Brain-Flak, Score: 35/134 = 0.2612 ([cracked!](https://codegolf.stackexchange.com/a/154825/69059))
`(({████){██[████)█>(({}))<>}<>{}███{}((██({}))█████{}]██)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})██[██()██(()█[()]██{}██}{}<>{})`
Returns 1 for prime, 0 for composite.
This is a very hard language to try this challenge in, as the formatting is so restricted that it takes effort not to make it obvious what the missing character is.
This is a very hard language to solve this challenge in, as it is ridiculously hard to read.
[Answer]
# [Java 1.4+](http://openjdk.java.net/), 24/145 (0.16551724137)
```
class X{public static void main(String[]args){System.out.println(new String(████████[Integer.parseInt(args[0])]).matches("█████████████")?███);}}
```
[Try it online!](https://tio.run/##y0osS9TNL0jNy0rJ/v8/OSexuFghorqgNCknM1mhuCSxBEiV5WemKOQmZuZpBJcUZealR8cmFqUXa1YHVxaXpObq5ZeW6BUAxUty8jTyUssVIIo0Hk3rwIqiPfNKUtNTi/QKEouKU4EcDZBp0QaxmrGaermJJckZqcUaSrh0oyElTXs4W9O6tvb/f5P/hiYA "Java (OpenJDK 8) – Try It Online")
---
Weirdest way I've seen to prime check in Java by far lol.
[Answer]
# Japt, 19 bytes, 0.315789... score, Safe
I don't know if I obscured more of this than I needed to, costing myself a better score.
```
█h8575¥█
█UâÊ█Ê█ █2
```
`[View solution](https://ethproductions.github.io/japt/?v=1.4.5&code=I2g4NTc1pSMK51XiynHKxCBuMg==&input=OA==)` (Explanation coming soon)
[Answer]
# C, 34/76 = 0.447368, Safe
```
int p(int n){int r███████2;██r███r++)███+███n;████&███r));return███████n██;}
```
Having this many blanks means that I will be much more likely to get an unintended crack than the intended one.
### Solution:
>
> `int p(int n){int r=1,e=n%2;for(;(r++)*(r++)<n;e=e&&(n%r));return e?n>1:n<3;}`
>
>
>
explanation:
>
> `e` holds a boolean value of whether or not the number is not prime (with a few special case exceptions). `r` iterates through the odd numbers less than or equal to the square root of `n`. `return e?n>1:n<3;` handles the special cases when `n` is `1` or `2`.
>
>
>
[Answer]
# [M](https://github.com/DennisMitchell/m), score: 4/22 = .1818..., [cracked](https://codegolf.stackexchange.com/questions/154742/cops-and-robbers-redacted-primality-robbers-thread/156382#156382) by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)
```
███“;;█»VOḣ2S⁵++3Ọ;”Pv
```
~~This may end up with an unintended crack, we'll have to see.~~ It did.
Dennis' solutions is
```
ÆPø“;;“»VOḣ2S⁵++3Ọ;”Pv
```
[Try it online!](https://tio.run/##y/3//3BbwOEdjxrmWFsDiUO7w/wf7lhsFPyocau2tvHD3T1A0bkBZf///zcCAA)
I will leave my solution hidden for someone to crack. My hint to Dennis on his robber submission was the word "zoo".
[Answer]
# C, 66 bytes, 29 redacted, score 0.439
```
i;p(n){█████2███████ 0███████2;███;███)if(████)return 0;return 1;}
```
Just a simple C submission; I'll see how long this one takes before I post a really evil one.
[Answer]
# [Pyth](https://pyth.readthedocs.io), score: ~0.(461538) (13 bytes) ([Cracked](https://codegolf.stackexchange.com/a/154818/59487))
```
█]█Q ██Q{█M█P
```
[Try to crack it here!](http://pyth.herokuapp.com/?code=q%5DtQ+%23aQ%7B%2aMyP%0A%E2%96%88%5D%E2%96%88Q+%E2%96%88%E2%96%88Q%7B%E2%96%88M%E2%96%88P&input=70&debug=0)
[Answer]
## sh + coreutils, score 19 / 143 ~= 0.1328
[cracked](https://codegolf.stackexchange.com/a/154914/14306)
```
e█ec█s█ █c "██████WyAkKHNoIC1jICJg█WNobyBabUZqZEc5eWZIUnlJQ2█2SnlBblhHNG5m██JoYVd3Z0t6SjhkMk1nTFhjSyB8YmFzZTY0IC1kYCIpIC1lcSAxIF0K█b█se6███d`"
```
[TIO](https://tio.run/##S0oszvj/P/XRtI7UZCBRDMQKQJysoAQk0VB4pWO2t4dfvqezYZans1c6SMgvP6nSKTEpNKowyjXZNDU8yjM0L8cr0AgoZxScl@OUlJPh4edumgsxwSs/MizFOMqgxCw4KyPbN9swL8QtIyu40skiMtetKiok0gBodnaks2cBkM5JDnas8HQz8AZqTAK5LdUM7pSUBKX//wE)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), score 29 / 140 = 0.207
`({}██()██<>){██({}[()])██{}{}███({<({}[()])><>({})<>}{}██████{}██){(({})){({}[()])<>}{}}<>([{}()]{}<>{})<>}(<>██{}({}████)((){[()]██{}██}{})`
[Try it online!](https://tio.run/##VUzLCYAwDF0nObhByCLFQz0IonjwGnJ3Agd0kRjbRiw8eMn7TUde9mHe8moGovd1OgArE6M0RTQBjk0XjWSxKFwm9hOJ//6H0FDgTTm1Wsmrd5Oo/@JnXQHiqEK/iAAob7mf9h00ewA)
Outputs 1 for prime and 0 for non-prime.
[Answer]
# [Tampio](https://github.com/fergusq/tampio) (imperative), score: 24/51 = 0.5
```
Luku on alkuluku,jos ████████████e███████ on █████.
```
This is an obvious solution, I hope no one here understands Finnish.
[Answer]
# [Tampio](https://github.com/fergusq/tampio) (imperative), score: 26/223 = 0.11659...
```
Luvun kokonaislukuarvot ovat riippuen siitä,onko se yksi,joko listan,jonka alkioita ovat yksi █████████████████████,alkiot tai █████ liitettynä sen alkutekijöihin.Luku on alkuluku,jos sen kokonaislukuarvojen summa on nolla.
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), score: 0.288288... [Safe]
```
Đ2⇹█ŘĐĐŁ███⇹ʀĐ↔Đ5Ș↔⇹██=█ŕĐ↔Đ5Ș↔Đř█⇹█████↔Đ4Ș5Ș⇹██⇹3Ș°04Ș↔█3ȘĐŁ█3Ș05Ș↔█⇹04Ș0↔⇹██=█ŕ↔ŕĐĐŁ██↔██↔ŕŕŕŕ█↔████↔ŕŕŕ██¬¬
```
Outputs "True" if prime, "False" if not
Forgot to mention that it is a probabilistic test.
Solution:
```
Đ2⇹⁻ŘĐĐŁ₂`⁻⇹ʀĐ↔Đ5Ș↔⇹Ǥ1=?ŕĐ↔Đ5Ș↔Đř²⇹%∈2*⁻↔Đ4Ș5Ș⇹⁻₂⇹3Ș°04Ș↔+3ȘĐŁ⁺3Ș05Ș↔+⇹04Ș0↔⇹%+=?ŕ↔ŕĐĐŁ⁺⁺↔ł:↔ŕŕŕŕ;↔⁺⁻±?↔ŕŕŕ:;¬¬
```
This implements the Solovay-Strassen primality test.
[Try it online here!](https://tio.run/##K6gs@f//yASjR@07H03rODrjyIQjE442AplQ1L7zVMORCY/aphyZYHpiBpCGKAQiW5D6qShyQK0zIZoQBkAQSM7kxAyQMrhk@07jEzMObTAwgZg7rQPIhVoOZBmYwoSBCkFqDDAtB4qAXIDkYogGMOPoVAhEEUaVhHAPrTm05v9/Q0tzAA)
[Answer]
# Ruby, 27/73 = 0.369863
```
def p n;███████(██n.times████a[2..-1].map{|s|█.██n████s}██.█*█|██})█);end
```
This should be fun.
[Answer]
# [Python 3](https://docs.python.org/3/), score: 0.386363, [cracked](https://codegolf.stackexchange.com/questions/154742/cops-and-robbers-redacted-primality-robbers-thread/156225#156225)
```
p=lambda x,i=2:█████or(x%i and ████████)████
```
Going for the *really* low hanging fruit at first. I'll come up with a cheeky answer soon.
user71546 made it "work" with
```
p=lambda x,i=2:i>=x or(x%i and p(x,i+1))or 0
```
...but that was unintended. Original code was
```
p=lambda x,i=2:i>x/2or(x%i and p(x,i+1))or 0
```
Neither work for x<2, turns out. Oops.
[Answer]
# JavaScript (ES7), 297 bytes, 103 redacted, .347
```
M=(N,X=N,F=(n,a=█████)=>a>1e-20?█████+F(n,█████████):1,G=(n,a=█████)=>a>1e-20?█████+G(n,███████):n==2?0:G(n-1),H=(n,a=█████)=>a>1e-20?█████-H(n,███████):0,I=n=>████████I(████),J=n=>I(n)*████+H(█████████-1),K=(n,l=n|0)=>(n-l>=.5)+l,L=(a,b)=>██████████(a)+█(b)████,Z=L(--N,N)██)=>L(Z,████M(N,X)██)██
```
My previous Python answer was too straightforward, so here's an evil one ;)
The logic behind is straightforward though.
[Answer]
# Python 3, 48 bytes, 24 redacted, .5
```
def p(x):
return ███(██████████████████(█,██))
```
Just a simple answer, probably gonna be solved in under 24 hours.
]
|
[Question]
[
## Definition of Additive Primes:
* Numbers which have exactly 2 divisors are called *Prime* numbers.
* Numbers which are prime and their sum of digits is also a prime number are called ***[Additive Primes](http://prime-numbers.wikia.com/wiki/Additive_Primes)***
---
## Task:
Given an integer `x`, compute all the additive primes amongst the first `x` prime numbers, with `2` being considered both the first prime and additive prime number. The numbers are represented in base 10.
## Rules:
* The output consists of all the additive primes amongst the first `x` primes
* `0 < x < 151`, for this challenge, for functionality purposes
* Since the additive primes are all integers, decimals are not allowed (e.g.: you should output `2`, not `2.0`) and they must not be displayed as a fraction.
---
## Examples:
`10 -> 2 3 5 7 11 23 29`
**Explanation:**
The first 10 primes are `2 3 5 7 11 13 17 19 23 29`, and only `2 3 5 7 11 23 29` have their sum of digits prime numbers, those being, respectively `2,3,5,7,2,5,11`, so they are **additive primes**
Following the explanation from `example 1`, other test cases may be:
```
2 -> 2 3
25 -> 2 3 5 7 11 23 29 41 43 47 61 67 83 89
7 -> 2 3 5 7 11
```
---
## Leaderboard:
```
var QUESTION_ID=112088,OVERRIDE_USER=59487;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left;font-family:"Helvetica Neue"}table thead{font-weight:700;font-family:"Helvetica Neue"}table td{padding:5px;font-family:"Helvetica Neue"}
```
```
<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>
```
---
**NOTE:** Please read the newly-edited rule 1, it brings changes to the output format slightly
---
Your code should be as short as possible, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Good luck!
[Answer]
# [Röda](http://github.com/fergusq/roda), ~~136~~ 135 bytes
```
f n{P=[2]S=[2]seq 3,863|{|i|{P|{P+=i;s=0;((""..i)/"")|parseInteger _|s+=_;S+=i if[s in P and not(i in S)]}if{|p|[i%p>0]}_}if[#P<n]}_;S}
```
[Try it online!](https://tio.run/nexus/roda#FYpRC8IgFEb/ysUIlMUaG0Vg9t6b4KMMGeTiPmQ29@b1ty8HH4fvwNlmCFkr249mR/I/GE6360CZkLKuaxTKpDrJOWNti@LMmKA4Lck/w@rffgFHqVFOmloCzjYBBtAwhReE78pxVyPGgnOmSBaP8dGNxVW3B30P9UpTts9Uswwz7y8CCOKCYQUHZfsD "Röda – TIO Nexus")
It's a function that returns the requested additive primes.
Usage: `main { f(25) | print ap for ap }` The code uses version 0.12, which is in branch `roda-0.12`.
Ungolfed:
```
function f(n) {
primes := [2]
ultraprimes := [2]
seq(3, 863) | for i do
break if [ #primes = n ]
if [ i%p != 0 ] for p in primes do
primes += i
sum := 0
((""..i)/"") | parseInteger _ | sum += digit for digit
ultraprimes += i if [ sum in primes and not (i in ultraprimes) ]
done
done
ultraprimes
}
```
[Answer]
## Pyke, ~~9~~ 7 bytes
```
~p>#Yss
```
[Try it online!](https://tio.run/nexus/pyke#@19XYKccWVz8/7@hAQA "Pyke – TIO Nexus")
The single byte `is_prime` was only pushed 3 hours ago. [Github commit](https://github.com/muddyfish/PYKE/commit/aa38ccfb54780cdede75462b8e848c0068edf0fe).
```
~p - All the prime numbers
> - first input of them
#Yss - filter(^)
Y - digits(^)
s - sum(^)
s - is_prime(^)
```
[Answer]
## Python 2, 124 118 bytes
With help from Riker:
```
n,f,P=input(),filter,lambda n:all(n%i for i in range(2,n))
f(lambda x:P(sum(map(int,`x`)))&P(x),f(P,range(2,n*n))[:n])
```
Original:
```
n,o,c,P=input(),0,2,lambda n:all(n%i for i in range(2,n))
while o<n:
o+=P(c)
if P(sum(map(int,`c`)))and P(c):print c
c+=1
```
Checking primality in Python ain't fun.
[Answer]
# [Perl 6](https://perl6.org), 53 bytes
```
{grep *.comb.sum.is-prime,grep(*.is-prime,0..*)[^$_]}
```
[Try it](https://tio.run/nexus/perl6#VY7LToNAFIb38xT/wjQM0EEGCm1IjVvXuhM1LRwNCZcJMxibpr6YO18MB2pj3J3L93/nDJrwnogiY4OtHkibjDUHLIquJGzH41tPCq4oumYv9NCISi9VXzXkTwvH/euvhXD54/PVy9NptIJbY1UaW9RVS9rhYuaD/D7gotlNyUlpB6UX8O8vcdcanjFV71p452zGXrv@4lnewEFetWowPjz6UFQYKsFxZIA9l/ekh9rYe9PjzgxaH2D/K4lUfcCZ8HEJ@/icMXYa5eSXiBiTq98SK6QIQ8gIcoM4RBwhTpGESFKsI6w3jKX/2R8 "Perl 6 – TIO Nexus")
## Expanded:
```
{
grep
*.comb.sum.is-prime, # find the ultra primes from:
grep(
*.is-prime, # find the primes
0..* # from all integers
)[ ^$_ ] # grab only the first x primes
}
```
If this challenge were changed so that you took the first *x* ultraprimes this could be shortened to just
```
{grep({($_&.comb.sum).is-prime},0..*)[^$_]}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~96~~ 87 bytes
```
p=-input(),0;m=k=1
while sum(p):
m*=k*k;k+=1;p+=m%k,
if m%k*p[int(`k`,36)%35]:print k
```
*Thanks to @xnor for golfing off 9 bytes!*
[Try it online!](https://tio.run/nexus/python2#DchBCoAgEADAu6/Yi6BmkEQdkn1JBF6KZDOWUnq@eRumMvbx5pKVtoNPSOjEd8Zrh7ckxXoRkAySIU8dOs8dJklWQDygwfAa76wCBTvOWo7TtvDTBqhWNw0/ "Python 2 – TIO Nexus")
[Answer]
## Mathematica, ~~61~~ 47 bytes
```
Prime@Range@#~Select~PrimeQ@*Tr@*IntegerDigits&
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆNDS$€ĖÆPM
```
**[Try it online!](https://tio.run/nexus/jelly#@3@4zc8lWOVR05oj0w63Bfj@///fyBQA "Jelly – TIO Nexus")**
### How?
A slightly different approach...
```
ÆNDS$€ĖÆPM - Main link: n (>0) e.g. 10
ÆN - nth prime number 29
€ - for each in range(1,nth prime) [1, 2, 3, ..., 27, 28, 29]
$ - last two links as a monad
D - decimal digit list [[1], [2], [3], ...,[2,7], [2,8], [2,9]]
S - sum [1, 2, 3, ..., 9, 10, 11]
Ė - enumerate [[1,1],[2,2],[3,3],...,[9,27],[10,28],[11,29]]
ÆP - is prime? (vectorises) [[0,0],[1,1],[1,1],...,[0,1], [0,0], [1,1]]
M - indices of maximal elements [ 2, 3, ..., 29]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ÝØ¨vySOp—
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3947uEZh1aUVQb7FzxqmPL/v5EpAA "05AB1E – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ÆN€DS$ÆP$Ðf
```
[Try it online!](https://tio.run/nexus/jelly#@3@4ze9R0xqXYJXDbQEqhyek/f//38gUAA "Jelly – TIO Nexus")
Explanation:
```
ÆN€DS$ÆP$Ðf Main link (args: z)
ÆN€ Generate first z primes.
DS$ Take the digital sum.
ÆP Check if it's prime.
$ Join last two links and make a monad.
Ðf Only keep elements which conform to the criterion above.
```
[**I got outgolfed.**](/a/112099/41024)
[Answer]
# MATL, ~~15~~ 13 bytes
*2 bytes saved thanks to @Luis*
```
:Yq"@V!UsZp?@
```
Try it at [**MATL Online**](https://matl.io/?code=%3AYq%22%40V%21UsZp%3F%40&inputs=10&version=19.8.0)
**Explanation**
```
% Implicitly grab input as a number (N)
: % Create an array [1...N]
Yq % Get the k-th prime for each element k in that array
" % For each element in this list
@ % Get the current element
V!U % Break it into digits
s % Sum up the digits
Zp % Determine if this is a prime number
?@ % If it is, push the value to the stack
% Implicit end of for loop and implicit display of the stack
```
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$12\log\_{256}(96)\approx\$ 9.877 bytes
```
FtxFmC@p'pSf
```
[Try it online!](https://fig.fly.dev/#WyJGdHhGbUNAcCdwU2YiLCI3Il0=)
Explanation:
```
t # take the first
x # x items from
mC # all positive integers
F # filtered by
@p # is prime,
F ' # then filter those by
S # the sum of
f # the digits
p # is prime
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 97 bytes
```
p()(factor $1|wc -w)
for((;++n,c<$1;)){((`p $n`-2||(c++,`p $[n%10+n/10%10+n/100]`-2)))||echo $n;}
```
[Try it online!](https://tio.run/nexus/bash#@1@goamRlphckl@koGJYU56soFuuyZWWX6ShYa2tnaeTbKNiaK2pWa2hkVCgoJKXoGtUU6ORrK2tA@JG56kaGmjn6RsawGiDWKAKTU3NmprU5Ix8oAbr2v///xuZAgA "Bash – TIO Nexus")
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), 10 bytes (CP437)
```
@▓_π;░_}Σp
```
This would be much shorter if I had vectorization or a component for the first N primes, but alas, I did not before this challenge (but I do [now](https://github.com/MiningPotatoes/Ohm/commit/56a37f4e8ac71400b5ccf5db0a5fd53a687d0c33)!).
Explanation:
```
@▓_π;░_}Σp Main wire, arguments: a
@▓ ; Map...over the range (1..n)
_π nth prime
░ Select from ToS where...
_}Σ The sum of all digits
p is prime
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 120 bytes
```
for($n=$args[0];$n){for(;'1'*++$i-notmatch($s='^(?!(..+)\1+$)..')){}if('1'*([char[]]"$i"-join'+'|iex)-match$s){$i};$n--}
```
[Try it online!](https://tio.run/nexus/powershell#HY1BCsIwEADfYlnYXUOCFTyV0ofECKFYu4IJJD0IMW@P1uswzLQlJoIwgk@PbE9ugMBlZwP2eFQKRIe4vfw2rwR5xBtNBzJG8bVXwMYgc6my0G6TnVefrHMdSKefUQIq/Mj9zfofgMwFpP4WWtfW2vnyBQ "PowerShell – TIO Nexus")
Prime checking in PowerShell sucks.
The outer `for` loop goes from input `$n` down to `0`. In the inner loop, we use a [prime generator](https://codegolf.stackexchange.com/a/57636/42963) on `$i`, then check `if` the digit-sum (`-join'+'|iex`) is also a prime. If so, we put `$i` on the pipeline. In either case, we decrement `$n--` and the outer `for` loop continues. The resulting `$i`s are gathered from the pipeline and an implicit `Write-Output` happens at program completion.
[Answer]
# Bash + GNU utilities + bsd-games package, 69
```
primes 2|sed -rn 'h;s/./ + &/g;s/.*/expr &|factor/e;/\w\s/!{x;p};'$1q
```
[Try it online](https://tio.run/nexus/bash#PY3LCoMwFET3fsVURKElvY0gXQT6JW4kXquLmjQ3UKH229MH1FkNZw7M4AIiS7SdMKYZNc7QJ9QNdKMNepfhE7ajQ15sorrkPy4coRS2Ifkw3VhQr8I9VJhRjUboSDigpOu37okXH1CuQ2ejC8SG2kcrtHsuxr9MVeh7@l9mvZs5vQE).
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 59 bytes
```
f(x)=[p|p<-vector(x,i,prime(i)),isprime(vecsum(digits(p)))]
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P02jQtM2uqCmwEa3LDW5JL9Io0InU6egKDM3VSNTU1MnsxjCBkoWl@ZqpGSmZ5YUaxRoamrGgjQbGWgCAA "Pari/GP – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
ʁǎ'∑æ
```
[Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgceOJ+KIkcOmIiwiIiwiMTAiXQ==), or [verify more test cases](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiyoHHjifiiJHDpiIsIiIsIjJcbjI1XG43Il0=).
Explanation:
```
ʁ # Range from 0 to n-1
ǎ # Nth prime (vectorising)
' # Filtered by:
∑ # The digit sum
æ # Is prime
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
♪╒g¶<gÅΣ¶
```
[Try it online.](https://tio.run/##ASYA2f9tYXRoZ29sZv//4pmq4pWSZ8K2PGfDhc6jwrb//zEwCjIKMjUKNw)
**Explanation:**
Since the input is guaranteed to be within the range \$[1,150]\$, where the \$150^{th}\$ prime is \$877\$, we'll use this to our advantage. (Although using `ó` (\$2^n\$ builtin using the implicit input) instead of `♪` would have worked as well, but would be way too slow for larger inputs.)
```
♪╒ # Push a list in the range [1,1000]
g # Filter it by:
¶ # Check if the number is a prime
< # Then only keep the first (implicit) input amount of prime numbers
g # Filter it again,
Å # using 2 characters as inner code-block:
Σ # Get the digit-sum of the current integer
¶ # Check if it's also a prime
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
fȯṗΣd↑İp
```
[Try it online!](https://tio.run/##ARkA5v9odXNr//9myK/huZfOo2TihpHEsHD///8y "Husk – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èj}jU fÈìx j
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yGp9alUgZsjseCBq&input=MTA)
[Answer]
# [Factor](https://factorcode.org/) + `math.primes math.unicode math.text.utils`, 47 bytes
```
[ nprimes [ 1 digit-groups Σ prime? ] filter ]
```
[Try it online!](https://tio.run/##LYxNCsIwFIT3nmIuYLAFEXThUty4EVeli5C@1tD8mbyAIp7G@3ilWLS7Gb75ppeKfSyX8/F02MJKvooQtaX0z0x3Fpm1mXt2WvmOkOiWyalpFiIxPybHMUaKjgx2iyeqFWrUa2zwKg3c/NmgQqcHzcsh@hwSPm/80B4tem2YItpiZUBiqUZRvg "Factor – Try It Online")
## Explanation:
It's a quotation (anonymous function) that takes an integer from the data stack as input and leaves a sequence of integers on the data stack as output.
* `nprimes` Obtain a list of the first n primes.
* `[ ... ] filter` Take elements from the list that match a predicate.
* `1 digit-groups` Obtain a list of digits from an integer.
* `Σ` Sum a sequence.
* `prime?` Is it prime?
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅpʒSOp
```
[Try it online](https://tio.run/##yy9OTMpM/f//cGvBqUnB/gX//xuZAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w60FpyYF@xf8r9X5H21ooGOkY2SqYx4LAA).
**Explanation:**
```
Åp # Get a list of the first (implicit) input amount of primes
ʒ # Filter this list by:
S # Convert the prime to a list of digits
O # Sum them together
p # Check if this sum is a prime
# (after which the filtered list is output implicitly as result)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
:YqtFYA!XsZp)
```
Try it at [**MATL Online!**](https://matl.io/?code=%3AYqtFYA%21XsZp%29&inputs=25&version=19.8.0)
### Explanation
```
: % Range [1 2 ... n], where n is implicit input
Yq % Array of first n prime numbers
t % Duplicate
FYA % Convert to decimal digits. Gives a matrix, where each original
% number corresponds to a row. Left-pads with zeros if needed
!Xs % Sum of rows
Zp % Is prime? (element-wise)
) % Use as logical index into the array of the first n prime numbers
% Implicitly display
```
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 months ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
This comes from <http://programmers.blogoverflow.com/2012/08/20-controversial-programming-opinions/>
"Given that Pi can be estimated using the function \$4 \times (1 - 1/3 + 1/5 - 1/7 + \cdots)\$ with more terms giving greater accuracy, write a function that calculates Pi to an accuracy of 5 decimal places."
* Note, the estimation must be done by calculating the sequence given above.
[Answer]
## JavaScript, ~~46 58 56~~ 45 bytes
*ES6 update*: Turns out there's more features available to us now that five years have passed.
```
let f=(i=0,a=0)=>i>1e6?a:f(i+4,a+8/-~i/(i+3))
```
This version (**45** bytes; yes, the `let` is required) works in ES6 strict mode *in theory*. In practice, you can run it in V8 (e.g. with node) with `--use-strict --harmony-tailcalls`; the Proper Tailcalls feature isn't widely implemented yet, alas. However, it's specified behaviour, so it should be fine.
If we want to stick to what's widely implemented, and not require strict-mode, we can simply use the ES6 fat-arrow syntax for functions but otherwise retain the same implementation as before (suggested by Brian H) for a cost of **48** bytes.
```
a=>{for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}
```
The choice of name for the single parameter doesn't *really* matter, but we might as well pick one of the names we use so as to minimise the global-scope pollution.
---
```
function(){for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}
```
This version is a function expression; add two characters (e.g. " `f`") if you want it named. This version clobbers the globals `a` and `i`; this could be prevented if we added "`a,i`" to the parameter list.
Makes use of a reformulated version of the algorithm in order to circumvent the need for subtraction.
```
1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...
(3/3 - 1/3) + (7/35 - 5/35) + (11/99 - 9/99) + ...
2/3 + 2/35 + 2/99 + ...
2/(1*3) + 2/(5*7) + 2/(9*11) + ...
```
Here's a "plain" version without this adjustment:
```
function(){for(a=0,i=1;i<1e6;i+=2)a+=[,4,,-4][i%4]/i;return a}
```
which clocks in at ~~*64*~~ **62** characters.
Thanks to @ardnew for the suggestion to get rid of the `4*` before the `return`.
---
### History
```
function(){for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a} // got rid of `i+=4`; restructured
// Old versions below.
function(){for(a=0,i=1;i<1e6;i+=4)a+=8/i/-~-~i;return a} // got rid of `4*`
function(){for(a=0,i=1;i<1e6;i+=4)a+=2/i/-~-~i;return 4*a}
```
[Answer]
## Python 59 bytes
```
print reduce(lambda x,p:p/2*x/p+2*10**999,range(6637,1,-2))
```
This prints out 1000 digits; slightly more than the required 5. Instead of using the prescribed iteration, it uses this:
```
pi = 2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + 5/11*(2 + ...)))))
```
The `6637` (the innermost denominator) can be formulated as:
```
digits * 2*log2(10)
```
This implies a linear convergence. Each deeper iteration will produce one more binary bit of *pi*.
***If***, however, you insist on using the *tan-1* identity, a similar convergence can be achieved, if you don't mind going about the problem slightly differently. Taking a look at the partial sums:
*4.0, 2.66667, 3.46667, 2.89524, 3.33968, 2.97605, 3.28374, ...*
it is apparent that each term jumps back and forth to either side of the convergence point; the series has alternating convergence. Additionally, each term is closer to the convergence point than the previous term was; it is absolutely monotonic with respect to its convergence point. The combination of these two properties implies that the arithmetic mean of any two neighboring terms is closer to the convergence point than either of the terms themselves. To give you a better idea of what I mean, consider the following image:

The outer series is the original, and the inner series is found by taking the average of each of the neighboring terms. A remarkable difference. But what's truly remarkable, is that this new series also has alternating convergence, and is absolutely monotonic with respect to its convergence point. That means that this process can be applied over and over again, ad nauseum.
Ok. But how?
Some formal definitions. Let *P1(n)* be the *nth* term of the first sequence, *P2(n)* be the *nth* term of the second sequence, and similarly *Pk(n)* the *nth* term of the *kth* sequence as defined above.
*P1 = [P1(1), P1(2), P1(3), P1(4), P1(5), ...]*
*P2 = [(P1(1) +P1(2))/2, (P1(2) +P1(3))/2, (P1(3) +P1(4))/2, (P1(4) +P1(5))/2, ...]*
*P3 = [(P1(1) +2P1(2) +P1(3))/4, (P1(2) +2P1(3) +P1(4))/4, (P1(3) +2P1(4) +P1(5))/4, ...]*
*P4 = [(P1(1) +3P1(2) +3P1(3) +P1(4))/8, (P1(2) +3P1(3) +3P1(4) +P1(5))/8, ...]*
Not surprisingly, these coefficients follow exactly the binomial coefficients, and can expressed as a single row of Pascal's Triangle. Since an arbitrary row of Pascal's Triangle is trivial to calculate, an arbitrarily 'deep' series can be found, simply by taking the first *n* partial sums, multiply each by the corresponding term in the *kth* row of Pascal's Triangle, and dividing by *2k-1*.
In this way, full 32-bit floating point precision (~14 decimal places) can be achieved with just 36 iterations, at which point the partial sums haven't even converged on the second decimal place. This is obviously not golfed:
```
# used for pascal's triangle
t = 36; v = 1.0/(1<<t-1); e = 1
# used for the partial sums of pi
p = 4; d = 3; s = -4.0
x = 0
while t:
t -= 1
p += s/d; d += 2; s *= -1
x += p*v
v = v*t/e; e += 1
print "%.14f"%x
```
If you wanted arbitrary precision, this can be achieved with a little modification. Here once again calculating 1000 digits:
```
# used for pascal's triangle
f = t = 3318; v = 1; e = 1
# used for the partial sums of pi
p = 4096*10**999; d = 3; s = -p
x = 0
while t:
t -= 1
p += s/d; d += 2; s *= -1
x += p*v
v = v*t/e; e += 1
print x>>f+9
```
The initial value of *p* begins *210* larger, to counteract the integer division effects of *s/d* as *d* becomes larger, causing the last few digits to not converge. Notice here again that `3318` is also:
```
digits * log2(10)
```
The same number of iteratations as the first algorithm (halved because *t* decreases by *1* instead of *2* each iteration). Once again, this indicates a linear convergence: one binary bit of *pi* per iteration. In both cases, 3318 iterations are required to calculate 1000 digits of *pi*, as slightly better quota than 1 million iterations to calculate 5.
[Answer]
## Java (67 chars)
```
float r(){float p=0,s=4,i=1E6f;while(--i>0)p+=(s=-s)/i--;return p;}
```
Note that this avoids loss of significance by adding the numbers up in the correct order.
[Answer]
# Mathematica 42 39 34 33 31 26 32
**Archimedes' Approach** 26 chars
```
N@#*Sin[180 Degree/#]&
```
This reaches the criterion when input is 822.
Question: Does anyone know how he computed the Sin of 180 degrees? I don't.
---
**Leibniz' Approach** (Gregory's series) 32 chars
This is the same function the problem poser gave as an example.
It reaches the criterion in approximately one half million iterations.
```
N@4Sum[(-1)^k/(2k+1),{k,0,10^6}]
```
---
**Madhava-Leibniz Approach** 37 chars
This variation uses a few more characters but converges to criterion in only 9 iterations!
```
N@Sqrt@12 Sum[(-1/3)^k/(2k+1),{k,0,9}]
```
[Answer]
## APL (14)
```
4×-/÷1-⍨2×⍳1e6
```
[Answer]
## Haskell, 32
```
foldr(\k->(4/(2*k+1)-))0[0..8^7]
```
>
> GHCi> foldr(\k->(4/(2\*k+1)-))0[0..8^7]
>
> 3.141593130426724
>
>
>
Counting a function name it's
## 34
```
π=foldr(\k->(4/(2*k+1)-))0[0..8^7]
```
[Answer]
## R - 25 chars
```
sum(c(4,-4)/seq(1,1e6,2))
```
[Answer]
## C (GCC) (44 chars)
```
float p(i){return i<1E6?4./++i-p(++i):0;}
```
That's 41 chars, but it also has to be compiled with `-O2` to get the optimiser to eliminate the tail recursion. This also relies on undefined behaviour with respect to the order in which the `++` are executed; thanks to ugoren for pointing this out. I've tested with gcc 4.4.3 under 64-bit Linux .
Note that unless the optimiser also reorders the sum, it will add from the smallest number, so it avoids loss of significance.
Call as `p()`.
[Answer]
**J, 26 chars**
+/+/\_2((4 \_4)&%)>:+:i.100
Moved from 100 items of sequence to 1e6 items. Also now it's a code tagged and could be copypasted from browser to the console without errors.
```
+/+/_2((4 _4)&%)\>:+:i.1e6
```
[Answer]
# Clojure - 79 chars
```
(fn [](* 4(apply +(map #(*(Math/pow -1 %1)(/ 1.0(+ 1 %1 %1)))(range 377000)))))
```
This creates a function of no arguments which will calculate a float which approximates pi correctly to five decimal places. Note that this does not bind the function to a name such as `pi`, so this code must either be evaluated in place with `eval` as `(<code>)` or bound to a name in which case the solution is
```
(defn p[](* 4(apply +(map #(*(Math/pow -1 %1)(/ 1.0(+ 1 %1 %1)))(range 377000)))))
```
for 82 chars
### About
```
(defn nth-term-of-pi [n] (* (Math/pow -1 n) (/ 1.0 (+ 1 n n))))
(defn pi [c] (* 4 (apply + (map nth-term-of-pi (range c)))))
(def pi-accuracy-constant (loop [c 1000] (if (< (pi c) 3.14159) (recur (inc c)) c)))
; (pi pi-accuracy-constant) is then the value of pi to the accuracy of five decimal places
```
[Answer]
# Javascript - 33 Characters
```
p=x=>4*(1-(x&2))/x+(x>1?p(x-2):0)
```
Call `p` passing a positive odd number `x` and it will calculate Pi with `(x-1)/2` terms.
[Answer]
## Ruby - 82 chars
```
def f(n,k=n)k>0?(f(n,k-1)+f(n+1,k-1))/2:n<0?0:f(n-1,0)+(-1)**n/(2*n+1.0)end;4*f(9)
```
Try it : <https://repl.it/LQ8w>
The approach uses the given series indirectly using a numerical acceleration approach. The resulting output is
`pi ≈ 3.14159265161`
vs.
`pi = 3.14159265359`
It starts with
```
f(n,0) = 1/1 - 1/3 + 1/5 - ... + ((-1)**n)/(2*n+1)
```
And then, since this is alternating, we can accelerate the convergence using
```
f(n,1) = (f(n,0) + f(n+1,0))/2
```
And it repeatedly applies this:
```
f(n,k) = (f(n,k-1) + f(n+1,k-1))/2
```
And for simplicity, `f(n) = f(n,n)`.
---
## Ruby - 50 chars
If you don't mind running for a really long while, then you could simply use
```
def f(n)n<0?0:f(n-1)+(-1)**n/(2*n+1.0)end;4*f(1e7)
```
or
```
a=0;for k in 0..1e7 do a+=(-1)**k/(2*k+1.0)end;4*a
```
[Answer]
# VBA - 80 105 characters
From the VBE immediate window:
```
s=-1:x=1:i=3:While Left(4*x,7)<>3.14159:x=x+((1/i)*s):s=-s:i=i+2:Wend:Debug.?4*x
```
Using `Left()` instead of `Round()` saves a character but also makes it more accurate to the definition of the challenge.
I'm getting my character count from Notepad++. I do see that other systems may count differently.
The algorithm below is easier to read:
```
Sub p
s=-1:x=1:i=3
While Left(4*x,7)<>3.14159
x=x+((1/i)*s)
s=-s
i=i+2
Wend
Debug.?4*x
Debug.?"Pi to 5 places solved in ";(i-1)/2;" steps."
End Sub
```
*If you want to test this code and have Microsoft Excel, Word, Access, or Outlook installed (Windows only), press Alt+F11 to open the VBA IDE. Insert a new code module (Alt+I,M) and clear out `Option Explicit` if shown at the top. Then paste in the code and press F5 to run it. The results should appear in the Immediate Window (press Ctrl+G if you don't see it).*
[Answer]
## C, 69 chars
```
float p,b;void main(a){b++<9e6?p+=a/b++,main(-a):printf("%f\n",4*p);}
```
* Run with no command line parameters (so `a` is initialized to 1).
* Must be compiled with optimization.
* `void main` is strange and non-standard, but makes things work. Without it, the recursion is implemented as a real call, leading to a stack overflow. An alternative is adding `return`.
* Two characters `4*` can be saved, if running with three command line parameters.
[Answer]
## Python - 56 chars
Meh, My python-fu is not strong enough. I couldn't see any more shortcuts but maybe a more experienced golfer could find something to trim here?
```
t=s=0
k=i=1
while t<1e6:t,s,i,k=t+1,k*4./i+s,i+2,-k
```
[Answer]
## Python (49)
```
print 4*sum((-1)**i/(2*i+1.)for i in range(9**6))
```
```
**3.14159**453527
```
[Answer]
# PHP - 56 55 chars
```
<?for($j=$i=-1;1e6>$j;){$p+=($i=-$i)/($j+=2);}echo$p*4;
```
I don't know that I can get it much smaller without breaking the algorithm rule.
[Answer]
## Perl - 43 39 chars
not sure the rules on anonymous subroutines, but here's another implementation using @FireFly's series construction
```
sub{$s+=8/((4*$_+2)**2-1)for 0..1e6;$s}
```
```
sub p{$s+=(-1)**$_*4/(2*$_+1)for 0..1e6;$s}
```
[Answer]
# Befunge, 129 bytes
```
p08p109p^v*86%+55:<$$$<
\$\>:#,_@>+\55+/:#^_"."
v>p"~"/:"~"%08p"~"/00p:2\4%-*"(}"
8^90%"~":+2:+g90*+g80*<
>*:**\/+>"~~"00g:"~"`!|
```
[Try it online!](http://befunge.tryitonline.net/#code=cDA4cDEwOXBedio4NiUrNTU6PCQkJDwKXCRcPjojLF9APitcNTUrLzojXl8iLiIKdj5wIn4iLzoifiIlMDhwIn4iLzAwcDoyXDQlLSoiKH0iCjheOTAlIn4iOisyOitnOTAqK2c4MCo8Cj4qOioqXC8rPiJ+fiIwMGc6In4iYCF8&input=)
In case anyone is wondering, it's an elephant.

[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
*_4ṁ\↑^9 9z*İ_İ1
```
[Try it online!](https://tio.run/##yygtzv5/eLuhlqEBCDxqavyvFW/ycGdjzKO2iXEmCpZVWkc2xB/ZYPj/PwA "Husk – Try It Online") using series of only 6561 (9^4) terms (times-out on TIO for longer series).
Output is a rational number expressed as a fraction: TIO header multiplies by 100,000 and rounds to nearest integer.
```
*_4ṁ\↑^9 9z*İ_İ1
*_4 # multiply by -4:
ṁ # sum of series of
\ # reciprocals of
↑^9 9 # first 387420489 (9^9) terms of
z* # pairwise products of
İ_ # powers of -1 (-1,1,-1,1,...) and
İ1 # odd numbers (1,3,5,7,9,...)
```
[Answer]
# [jq](https://stedolan.github.io/jq/), 34 characters
```
[range(1;1e6;4)|1/.-1/(.+2)]|add*4
```
Sample run:
```
bash-5.2$ jq -n '[range(1;1e6;4)|1/.-1/(.+2)]|add*4'
3.1415906535898936
```
[Try it online!](https://tio.run/##yyr8/z@6KDEvPVXD0Now1czaRLPGUF9P11BfQ0/bSDO2JjElRcvk//9/@QUlmfl5xf91dfNKc3J0M/MKSksA "jq – Try It Online")
[Answer]
## Java - 92 84 chars
I cannot beat by far Peter Taylor's result, but here is mine:
```
double d(){float n=0,k=0,x;while(n<9E5){x=1/(1+2*n++);k+=(n%2==0)?-x:x;}return 4*k;}
```
Ungolfed version:
```
double d() {
float n = 0, k = 0, x;
while (n < 9E5) {
x = 1 / (1 + 2 * n++);
k += (n % 2 == 0) ? -x : x;
}
return 4 * k;
}
```
Edit: Saved a few characters using ternary operator.
[Answer]
**Ruby - 54 chars**
```
def a()p=0;1000000.times{|i|p+=8/(4*i*(4*i+2))};p;end;
```
My first try on console
```
def a()i=1;p=0;while i<2**100 do p+=8/(i*(i+2));i+=4;end;p;end;
```
63 chars.
[Answer]
## Perl (76 chars)
```
$y=1e4;for$x(0..1e4-1){$y--while sqrt($x**2+$y**2)>1e4;$a+=$y}print 4*$a/1e8
```
(Result: 3.14159052)
Not the shortest possible solution, but maybe interesting. It's a geometrical one. I calculate the area under a circle.
I got another funny approach, but it's really slow. It counts the number of discrete points in a square that are below a quarter circle and calculates pi from it:
```
$i=shift;for$x(0..$i){for$y(0..$i){$h++if sqrt($x**2+$y**2)<$i}}print$h*4/$i**2
```
It expects the number of iterations as command line argument. Here you can see how run time relates to accuracy. ;)
```
$ time perl -e '$i=shift;for$x(0..$i){for$y(0..$i){$h++if sqrt($x**2+$y**2)<$i}}print$h*4/$i**2' 100
3.1796
real 0m0.011s
user 0m0.005s
sys 0m0.003s
$ time perl -e '$i=shift;for$x(0..$i){for$y(0..$i){$h++if sqrt($x**2+$y**2)<$i}}print$h*4/$i**2' 1000
3.14552
real 0m0.354s
user 0m0.340s
sys 0m0.004s
$ time perl -e '$i=shift;for$x(0..$i){for$y(0..$i){$h++if sqrt($x**2+$y**2)<$i}}print$h*4/$i**2' 10000
3.14199016
real 0m34.941s
user 0m33.757s
sys 0m0.097s
```
[Answer]
# k (25 chars)
~~4\*+/%(i#1 -1)*'1+2*!i:1000000~~
Slightly shorter:
```
+/(i#4 -4)%1+2*!i:1000000
```
[Answer]
# CJam - 21
```
1e6{WI#4d*I2*)/}fI]:+
```
Pretty straightforward calculation of the given series.
CJam is <http://sf.net/p/cjam>
[Answer]
# Julia - 30 characters
```
sum(4./[1:4:1e6] - 4./[3:4:1e6])
```
[Answer]
# SQL, 253 bytes
```
DECLARE @B int=3, @A varchar(max), @C varchar(max)='1'
WHILE @B<100000
BEGIN
SELECT @C=@C+(select case when (@B-1)%4=0 then'+'else'-'end)+
(SELECT cast(cast(1.0/@B as decimal(9,8)) as varchar(max)))
SELECT @B=@B+2
END
EXECUTE('SELECT 4*('+@C+')')
```
I would provide a SQL Fiddle, but this goes too many loops deep finding the 1/3 1/5 1/7 etc. fractions and gives errors lol. However, if you change `@B<100000` to `1000` then it runs (obviously not to the same number of digits of accuracy).
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 25 bytes
```
7.?,{2*)2.-1??./\/\-}*)4*
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/31zPXqfaSEvTSE/X0N5eTz9GP0a3VkvTROv/fwA "GolfScript – Try It Online")
```
7.? # Push 7^7=823543, we just need an odd number bigger than 136120
,{ }* # For every number k from 1 to 823542
2*) # 2*k+1
2.-1??./ # sqrt(2)/sqrt(2)=1.0 this number is just 1, but it is a float
\/ # 1.0 / (2*k+1)
\- # Subtract the sequence from this number
) # Add 1 because 1/1 was skipped
4* # Multiply by 4
```
Output:
```
3.141593867855424
```
[Answer]
# [Desmos](https://www.desmos.com/calculator), 30 bytes
```
4\sum_{n=0}^{9^6}(-1)^n/(1+2n)
```
[Try it on Desmos](https://www.desmos.com/calculator/nivxhndq6p)
Pretty self-explanatory coding of the sequence. An array-based method, while it sounds like it should be more efficient, runs into Desmos' limitations on array length.
]
|
[Question]
[
# Introduction
A quine is a program that outputs its own source code. For example, a well-known Python quine is `_='_=%r;print(end=_%%_)';print(end=_%_)`. Running it outputs `_='_=%r;print(end=_%%_)';print(end=_%_)`, therefore it is a valid quine. An error quine is similar to a regular quine, however it must output to STDERR. In Python (for example), this could be achieved by replacing both instances of `print` in the above code with `exit`. A polyglot is a program that is valid in multiple languages.
# Challenge
Write two **full programs** in two programming languages of your choice. The first one should be a quine, and the second an error quine. When concatenated (in any order, you can pick), it should form a Hello, World! program in a third programming language.
# Example
Say you have a language `A`\* in which a valid quine is `123`, and another language `B`\* where `abc` is an error quine. Then, `123abc` (or `abc123`) should be a valid Hello, World! program in language `C`\*. If this is the case, your answer should look similar to the following:
---
# A, B, C, score 3
## A, 3 bytes - Quine
```
123
```
[Try it online!](https://tio.run "placeholder link")
## B, 3 bytes - Error quine
```
abc
```
[Try it online!](https://tio.run "placeholder link")
## C, 6 bytes - Hello, World!
```
123abc
```
[Try it online!](https://tio.run "placeholder link")
## Explanation (optional)
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sem mi, dignissim a odio vehicula, tincidunt ultrices tellus. Etiam luctus scelerisque urna, ac sodales nisl rhoncus at. Cras ac accumsan velit. Integer eget mi nec diam suscipit pretium a ac massa. Praesent at enim nec nisl molestie aliquet nec sed lorem. Duis iaculis condimentum dui at ullamcorper. Fusce molestie iaculis dolor. Cras vel metus dictum, aliquam quam sit amet, gravida tortor. Praesent maximus quam porttitor, vulputate magna eu, rhoncus nunc. Sed accumsan dui ut sapien semper finibus. Nulla eget dictum justo.
---
# Scoring
Your score is the arithmetic mean of the lengths of the two quines (i.e. half the length of the Hello, World! program).
# Rules
* All three programming languages used must be different.
* The Hello, World! program should output exactly `Hello, World!`. A trailing newline is allowed.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, except for storing information in the file name; if done so in either one of the quines, it will add <length of file name> bytes to the length of both that program and the Hello, World! program, therefore adding half of <length of file name> to your score. If done in the Hello, World! program, it adds the same amount to your score and bytecount for it, but not for either one of your quines. Note that, if you're not doing this, the file name will be assumed to be `.code.tio` even if not running on TIO.
* The regular quine **must** output to STDOUT and the error quine **must** output to STDERR. If STDOUT and STDERR do not exist in your language(s), use the closest equivalent(s). However, the Hello, World! program may output using any of the [standard I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Also, the quine and Hello, World! programs may output anything to STDERR, and the error quine may output anything to STDOUT.
* If possible, please link to an online interpreter (e.g. [TIO](https://tio.run)) to run your program on.
* Please explain your answer. This is not necessary, but it makes it easier for others to understand.
* Neither one of the quines may output a trailing newline unless that newline also occurs in the source code.
* Languages newer than the question are allowed. This means you could create your own language where `a` is a quine, `b` is an error quine, and `ab` is Hello, World!, and post an answer in that language with score 1, but expect many downvotes.
* Non-programming languages are allowed. A non-programming language is a language which doesn't satisfy both of these conditions:
+ Able to take two integers as input and print their sum
+ Able to take one integer as input and print a truthy value if it is prime, and a falsy value if it is not
* Different versions of the same language may be used. For example, your quine could be in Python 2 and your Hello, World! program in Python 3.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
\*Fun fact: these are all actual languages!
[Answer]
# C, Bash, C++, score 174.5 175
## C, 301 bytes - Quine
```
#include<stdio.h>
int main(){
#ifdef __cplusplus
printf("Hello, World!"
#else
char*c="#include<stdio.h>%cint main(){%c#ifdef __cplusplus%cprintf(%cHello, World!%c%c#else%cchar*c=%c%s%c;printf(c,10,10,10,34,34,10,10,34,c,34,10,10%c#endif%c);}//";printf(c,10,10,10,34,34,10,10,34,c,34,10,10
#endif
);}//
```
[Try it online!](https://tio.run/##lYzLCsIwEEX3@YqaEmilWqXuqq79A5el3CQ2ENPSx0r89phoKEpXwh2YGc492NwAa2NloCcujsPIVbttzkSZMbrXyiTpg8RKciGjqkKnp8EP6XoHyIRehNZtFl3bXvMVJbHQgyBo6n6NE11YGb60DEsvQxAz/JgZHO3dDEHuPo4uA45svwspDj7zjvnyBsOVZEjLZ57Tf7rkUyXvprUv)
## Bash, 48 49 bytes - Error quine
```
.code.tio: line 1: .code.tio:: command not found
```
[Try it online!](https://tio.run/##S0oszvj/Xy85PyVVryQz30ohJzMvVcHQSgEhZKWQnJ@bm5iXopCXX6KQll@al8L1/z8A) (the trailing newline was added, see comments)
## C++, 349 350 bytes - Hello, World!
```
#include<stdio.h>
int main(){
#ifdef __cplusplus
printf("Hello, World!"
#else
char*c="#include<stdio.h>%cint main(){%c#ifdef __cplusplus%cprintf(%cHello, World!%c%c#else%cchar*c=%c%s%c;printf(c,10,10,10,34,34,10,10,34,c,34,10,10%c#endif%c);}//";printf(c,10,10,10,34,34,10,10,34,c,34,10,10
#endif
);}//.code.tio: line 1: .code.tio:: command not found
```
[Try it online!](https://tio.run/##lYzLDoIwEEX3/YoR0kQMokRXoK79A5eE3LbSpLSEx8r47QhKfISVyUwyc3PuQVWtr0Df@9rCdEIemlZoFxUnpm1LZa7tMrgxXyshFWUZKtM147KqHgC19M7SGBfSxdVGLDzmS9NIhiKvVzh6MyvHl5Zj7uWYxBw/Zo6BHt0ck3xIBjqdcITxdprdfpz3jfc3GqzQiiNI75uN90@Xvars2YzghIxa7RIy2kqKE/pECcGVZW4FWdeScp0VrO8f)
---
# Explainations and notes
The **C** *quine* is inspired by [this](https://rosettacode.org/wiki/Quine#C) C quine (the short version), and contains C++ code for the *Hello, World!*.
The **Bash** *error quine* works due to the TIO implementation, but given that error messages are generally implementation defined, it might be hard to print them in some standard way (other than directly outputting to stderr, which is just like a *regular quine*... how unoriginal would that be). The submitted Bash program may be an invalid Bash program, but it is still a valid *error quine* in Bash. (Edit: note the trailing newline that is now legal to output.)
The **C++** *Hello, World!* doesn't output a trailing newline, but the challenge doesn't require it. After the preprocessor preprocessing, the only code source left is the `main` function with a simple `printf` call.
What was used in this answer are similarities between C and C++, very useful for polyglots (C is not *entirely* contained by C++, but it is contained enough) (for example: the usage of the C standard library is almost the same in these two languages which allows for a single `#include` directive, the `main` function definition is also similar enough to factorize the beginning and end out of the preprocessor-picked variations). The preprocessor and the `__cplusplus` macro are almost necessary at this point as they allow the C and C++ interpreters (or compilers, whatever) to pick only a specific subset of the program. The trailing line comment `//` ensures that the concatenation with a TIO Bash error doesn't upsets the C++ parser as it will completely ignore it.
I didn't find a way to to golf it even further. An other approach or a different set of languages are probably to be considered. For example, maybe using [Argh!](https://esolangs.org/wiki/Argh!) or INTERCAL for the *error quine* (or any other language in which error output is part of the language specification (these languages are rare, even among esolangs)). It might also be more interesting to use an other strategy than this """polyglot""" that makes each language ignore the code designed for the other languages instead of actually running most of the code.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), [gnuplot](http://www.gnuplot.info/), [Underload](https://esolangs.org/wiki/Underload), score: 33.5
## [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) (Quine)
```
ÿ'ÿ\_'ÿ\_
```
[Try it online.](https://tio.run/##y00syUjPz0n7///wfvXD@2PiwcT//wA)
## [gnuplot](http://www.gnuplot.info/), 58 bytes (Error quine)
```
(Hello, World!)S
^
".code.tio", line 2: invalid command
```
With one leading and two trailing newlines.
[Try it online.](https://tio.run/##S88rLcjJL/n/n0vDIzUnJ19HITy/KCdFUTOYK45LSS85PyVVryQzX0lHISczL1XByEohM68sMSczRSE5Pzc3MS@Fi@v/fwA)
## [Underload](https://esolangs.org/wiki/Underload), 67 bytes (Hello, World!)
```
ÿ'ÿ\_'ÿ\_
(Hello, World!)S
^
".code.tio", line 2: invalid command
```
With two trailing newlines.
[Try it online.](https://tio.run/##K81LSS3KyU9M@f//8H71w/tj4sEEl4ZHak5Ovo5CeH5RToqiZjBXHJeSXnJ@SqpeSWa@ko5CTmZeqoKRlUJmXlliTmaKQnJ@bm5iXgoX1///AA)
### Explanation:
**MathGolf:**
```
ÿ # Push a string of four characters:
'ÿ\_ # "'ÿ\_"
'ÿ # Push character "ÿ"
\ # Swap the top two values on the stack
_ # Duplicate the top value on the stack
# (after which the entire stack joined together is output implicitly)
```
**gnuplot:**
I've never used gnuplot before, but I simply tried random languages on TIO that contains `(Hello, World!)S` for the Underload program, and result in an error quine at the same time, of which gnuplot was one of the few, and the shortest I could find.
It will ignore the leading newline, and then complain about the `(Hello, World!)S` being invalid on line 2. Everything after that is fortunately enough ignored.
**Underload:**
Underload will simply print everything between `(...)S`, which is the intended `Hello, World!` in this case. It does give an error due to the rest of the program, but we can ignore STDERR and only look at the STDOUT, which [is allowed by default](https://codegolf.meta.stackexchange.com/a/4781/52210).
[Answer]
# [Y](https://github.com/ConorOBrien-Foxx/Y), [nameless language](https://github.com/bforte/nameless-lang), [Deadfish~](https://github.com/TryItOnline/deadfish-), 4.5
## [Y](https://github.com/ConorOBrien-Foxx/Y), 3 bytes
```
Uwp
```
[Try it online](http://conorobrien-foxx.github.io/Y/): Copy-paste the code from above (or type it manually), and click on the 'timeout run' button.
## [nameless language](https://github.com/bforte/nameless-lang), 6 bytes
```
[[0]]
```
With trailing newline.
[Try it online.](https://tio.run/##y0vMTc1JLS7@/z862iA2luv/fwA)
## [Deadfish~](https://github.com/TryItOnline/deadfish-), 9 bytes
```
[[0]]
Uwp
```
[Try it online.](https://tio.run/##S0lNTEnLLM7Q/f8/OtogNpYrtLzg/38A)
### Explanation:
**Y:**
```
U # Begin scanning, ignoring any links, and record as string once another `U` is
# encountered, while starting the string itself with a leading "U"
wp # "wp"
U # Wraps around to the start of the program again, finishing the string "Uwp"
w # No-op
p # Print the stack
```
I'm pretty sure Y is the language with the shortest [proper quine](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) available, of just 2 bytes with `Up`.
**nameless language:**
nameless language is a brainfuck derivative using 0s and 1s in 4-bit parts for the builtins. It will also debug the pointers to STDERR by default, which starts with `[[0]]` for empty programs.
**Deadfish~:**
Basically every character we used in the Deadfish~ program is a no-op, except for the `w`, which is the builtin to print `Hello, World!` to STDOUT.
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), [><>](https://esolangs.org/wiki/Fish), [Help, WarDoq!](https://esolangs.org/wiki/Help,_WarDoq!), score 16
## V, 6 bytes (Quine)
```
H2aH2a
```
[Try it online!](https://tio.run/##K/v/38MoEYj@//8PAA "V (vim) – Try It Online")
```
H # move cursor to first non-blank character (effectively no-op)
2a # twice append
H2a # literal characters
```
---
## ><>, 26 bytes (Error quine)
```
something smells fishy...
```
[Try it online!](https://tio.run/##S8sszvj/vzg/N7UkIzMvXaE4NzUnp1ghDShcqaenx/X/PwA "><> – Try It Online")
Note the trailing newline. Quoting from [Esolangs](https://esolangs.org/wiki/Fish):
>
> Although there are multiple reasons an error may occur, there is only one error message: *something smells fishy...*
>
>
>
---
## Help, WarDoq!, 32 bytes (*Hello, World!*)
```
H2aH2asomething smells fishy...
```
[Try it online!](https://tio.run/##S85KzP2fmmhgaxVYreSR4Zrqk@OfH14eVOSSoqPomBhQEFioFFgTDZRSUkrNyclXSoxW1/GJDU5UCi9XUsovykkBiSj6xMZa5WpZJURXF2UWZWrXgqk4EJVbACKrgFRgQmC4aoJPrHZqkVWdn1atlUfdfyDwMEoEouL83NSSjMy8dIXiXKA9xQppmcUZlXp6elwA "CJam – Try It Online") Link is to an interpreter in CJam identical to the reference implementation described at [Esolangs](https://esolangs.org/wiki/Help,_WarDoq!). The code (without the trailing newline, due to technical limitations) can also be [run](http://cjam.aditsu.net/#code=l%3AQ%7B%22HhEeLlOoWwRrDd%2C!AaPpQq%22Q%7C%5B%22Hh%22%22ello%22a%5B%27%2CL%5DSa%22Ww%22%22orld%22a%5B%27!L%5D%5D%3Am*%3A%60%5B%7Briri%2B%7D%7Briri%5E%7D%7Brimp%7D%7Brizmp%7DQ%60Q%7B%5C%2B%7D*%60L%5D%2Ber%3A%7EN*%7D%3AH%7E&input=H2aH2asomething%20smells%20fishy...) from the CJam interpreter linked at Esolangs, but it unhelpfully combines STDOUT and STDERR into one output field.
```
H # print 'Hello, World!'
2 # ignored
a # throws an error: attempts to read two integers from STDIN and XOR them
H2asomething smells fishy... # (not executed)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), [><>](https://esolangs.org/wiki/Fish), [Stax](https://github.com/tomtheisen/stax), score = 48 43
## [Ruby](https://www.ruby-lang.org/), 60 bytes (quine)
```
"Hello, World!"
puts <<2*2,2
"Hello, World!"
puts <<2*2,2
2
```
[Try it online!](https://tio.run/##KypNqvz/X8kjNScnX0chPL8oJ0VRiaugtKRYwcbGSMtIx4gLr6QR1///AA "Ruby – Try It Online")
## [><>](https://esolangs.org/wiki/Fish), 26 bytes (error quine)
```
something smells fishy...
```
[Try it online!](https://tio.run/##S8sszvj/vzg/N7UkIzMvXaE4NzUnp1ghDShcqaenx/X/PwA "><> – Try It Online")
## [Stax](https://github.com/tomtheisen/stax), 86 bytes (hello world)
```
"Hello, World!"
puts <<2*2,2
"Hello, World!"
puts <<2*2,2
2
something smells fishy...
```
[Try it online!](https://tio.run/##Ky5JrPj/X8kjNScnX0chPL8oJ0VRiaugtKRYwcbGSMtIx4gLr6QRV3F@bmpJRmZeukJxLlBhsUJaZnFGpZ6eHtf//wA "Stax – Try It Online")
*-5 score thanks to Dingus*
[Answer]
# Objective-C++/NASM/ARM Assembler, score ~~114.5~~ 115.5
## Objective-C++ (clang) `-fmodules`, quine, ~~188~~ 187 bytes
```
@import std;int main(){auto s="@import std;int main(){auto s=%c%s%1$c;printf(s,34,s,R%1$c(%3$s)%1$c,10);}%4$c";printf(s,34,s,R"(
.macro instruction x;.print"Hello, World!";.endm@)",10);}
```
Includes trailing newline.
I would post a link but unfortunately modules appear to be borked on both TIO and Wandbox.
When Travis decides to wake up, I will link a non-interactive demo.
You will see why I need Objective-C++ in a moment.
## NASM, error quine, ~~42~~ 44 bytes
```
t.:1: error: parser: instruction expected
```
Just your standard NASM error quine.
Requires the program to be named `t.`
The length depends on the filename, but nasm will only properly quine if the filename contains a dot and the first character isn't a dot.
[Try it online!](https://tio.run/##S0oszvifnFiiYKdQoqdgY6Pg6u/2v0TPytBKIbWoKL/ISqEgsag4FUhn5hWXFJUml2Tm5ymkVhSkJpekpnD9Byrn4spLLM4Fav8PAA)
## ARM Assembler (clang), Hello World, ~~230~~ 231 bytes
Uses the `.print` GAS directive.
```
@import std;int main(){auto s="@import std;int main(){auto s=%c%s%1$c;printf(s,34,s,R%1$c(%3$s)%1$c,10);}%4$c";printf(s,34,s,R"(
.macro instruction x;.print"Hello, World!";.endm@)",10);}
t.:1: error: parser: instruction expected
```
[Try it online!](https://tio.run/##fYw9a8QwEER7/wpF2GCDZGLuKouDK1OnSb0n7xmBPszuHhhC/nqUu6QJKVLNMO8x3voIea31HNJWSBTL4kIWlSDkfniHmxTFJ/0/7nzH3dR6t9EdXns2h6Nh8/rY@u7Q8vBoZnoe3Ed3bL3@K@q@GRN4KipkFrp5CSWr3Y3fnn7BGItRb4Xi8qTdiHlJ50H/HDYyztOskKjQrDYgxnv@/sF9Qy@4NLV@@muElau1ArSinICSzSWjRbiEandgxnSJSNX6Lw)
## Explanation
First, let's ungolf the Obj-C++ quine and remove the actual quine part to show what is going on:
```
@import std;
int main()
{
auto fmt = "...";
printf(fmt, '"', fmt, R"(...)", '\n');
}
```
So the ObjC++ quine is a fairly standard C++ quine, although it uses the Objective-C `@import` extension and a raw string literal. Other than that, there really isn't that much to explain.
You may ask, "why are you using `@import`? If you have modules, you can just do `import`".
The answer is that, in ARM assembly, `@` is a comment. And that is the magic (and literally the only reason we are using ObjC++).
So first, we make the ARM assembler completely ignore the first line *while also* `@import`ing `printf`.
I'd *love* to just use ObjC so I can have my implicit int, but `.print` requires a quoted string. I don't see any way to do this without raw string literals. üò≠
As for the assembly thing, I decided to use code from BOTH the NASM quine and the Obj-C++ quine, which I believe was the intended meaning of having the programs concatenated.
I could save a lot of bytes by just commenting out the NASM code though (it would go down to a score of 96, but I prefer this more creative solution.
For the assembler, I define a macro `instruction`:
```
.macro instruction x
.print "Hello, World!"
.endm
```
Then, when I append the NASM quine, it is parsed as a bunch of labels followed by `instruction expected`:
```
.t:
1:
error:
parser:
instruction expected
```
which calls the `instruction` macro I just defined, executing the compile-time `.print "Hello, World!"` statement.
---
For the reference, here is the more boring one which comments out the NASM line.
# Objective-C++/NASM/ARM Assembler, boring version, score 96
## Objective-C++ (clang) `-fmodules`, quine, 149 bytes
Note: newline is no longer necessary.
```
@import std;int main(){auto s="@import std;int main(){auto s=%c%s%1$c;printf(s,34,s,R%1$c(%3$s)%1$c);}";printf(s,34,s,R"(
.print"Hello, World!"@)");}
```
## NASM, error quine, 44 bytes
```
t.:1: error: parser: instruction expected
```
Just like before, needs the filename to be `t.`.
## ARM Assembler (clang), Hello World, 192 bytes
```
@import std;int main(){auto s="@import std;int main(){auto s=%c%s%1$c;printf(s,34,s,R%1$c(%3$s)%1$c);}";printf(s,34,s,R"(
.print"Hello, World!"@)");}t.:1: error: parser: instruction expected
```
[Try it online!](https://tio.run/##fYoxC8IwEEZ3f0UMLbTQCEWnlkJHZxfnM72WQJqUuxME8a8bW0cHp@/jvWeN9RCmlHo3L5FEsQytC6JmcKEon3CXqLjT/3Vuc87rzLYLrXIsuDqeKq4uGyvyY8bl9sr2pX8LXewOX6TP6H2s1DWSH/a6L/Way6GpG4VEkRq1ADGu6wIL3a24GBQ@FrSCwy6ltx09TJyMEaAJpQOaTYgBDcLNJfMAZpxvHikZ@wE)
This version removes the trailing newline and just comments out the NASM error. The .print is directly run instead of requiring the macro.
However, the ARM program will still do the same thing without the NASM program. Therefore, I am (at least personally) going by the higher score because I feel it is more in the spirit of the challenge and not an ugly hack.
[Answer]
# [Perl 5](https://www.perl.org/), [PHP](https://php.net/), [Perl 4](https://www.perl.org/) Score 84
## [Perl 5](https://www.perl.org/), 75 bytes (Quine)
```
eval($s='printf(-1**2+1?"Hello, World!":"eval(\$s=%c%s%c);#",39,$s,39);');#
```
[Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHQ6XYVr2gKDOvJE1D11BLy0jb0F7JIzUnJ19HITy/KCdFUclKCawwBqhSNVm1WDVZ01pZScfYUkelGEhqWqsD@f//AwA "Perl 5 – Try It Online")
## [PHP](https://php.net/), 93 bytes (Error Quine)
```
PHP Parse error: syntax error, unexpected 'Parse' (T_STRING) in Command line code on line 1
```
[Try it online!](https://tio.run/##K8go@P8/wCNAISCxqDhVIbWoKL/ISkGhuDKvJLECwtVRKM1LrShITS5JTVFQB6tTV9AIiQ8OCfL0c9dUyMxTcM7PzU3MS1HIycxLVUjOT0lVyM@DcAy5/v//l19QkpmfV/xft0iBplYBAA "PHP – Try It Online")
## [Perl 4](https://www.perl.org/), 168 bytes (Hello World)
```
eval($s='printf(-1**2+1?"Hello, World!":"eval(\$s=%c%s%c);#",39,$s,39);');#PHP Parse error: syntax error, unexpected 'Parse' (T_STRING) in Command line code on line 1
```
[Try it online!](https://tio.run/##JcpBC4IwGIDhe7/iaylTWwerS0p06JBdQkrwEsTYvkCYm2wW9uuX6OWFB94Ordp7j1@uosAdaWcb3b@jTZok23V6IgUqZRjUxiq5JBmZxud4hiJ0oYjzFWG7Awvc2Dino8uihJJbh4DWGpsBuJ/u@TCTwUfj0KHoUQKdPgpR9XpU9@vtEkOj4WzalmsJqtEIwkgEo2ekC@// "Perl 4 – Try It Online")
## EXPLANATION:
**EDIT**: Due to OP's decision about PHP errors I had to resort to more traditional tricks, sorry. Welcome to the classical comment!
* the difference between the quine and HelloWorld is that in Perl 4 the minus operator takes precedence over exponentiation (`-1**2+1` will be 2 and then truthy), while the contrary in Perl 5 (`-1**2+1` will be 0 and then falsy)
* The error quine is nothing special, notice the trailing newline
* Nothing more for the third, uses a comment
[Answer]
# [Python 3](https://docs.python.org), [><>](https://esolangs.org/wiki/Fish), [Befunge-93](https://github.com/catseye/Befunge-93), score 54
## [Python 3](https://docs.python.org), 82 bytes - Quine
```
"!dlroW ,olleH">':#,_@';_='"!dlroW ,olleH">\':#,_@\';_=%r;print(_%%_)';print(_%_)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/X0kxJacoP1xBJz8nJ9VDyU7dSlkn3kHdOt5WHV0qBiIXA5JULbIuKMrMK9GIV1WN11SHc@I1uf7/BwA "Python 3 – Try It Online")
```
"!dlroW ,olleH">':#,_@';_='"!dlroW ,olleH">\':#,_@\';_=%r;print(_%%_)';print(_%_) # full program
"!dlroW ,olleH">':#,_@'; # singleton comparison statement (effectively NOP)
_= # set variable _ to...
'"!dlroW ,olleH">\':#,_@\';_=%r;print(_%%_)'; # literal
print(_ # output _ with a trailing newline...
% # with the %r replaced by...
_ # _'s value...
# including quotes...
% # and the %% replaced by %
) # end function call
```
## [><>](https://esolangs.org/wiki/Fish), 26 bytes - Error quine
```
something smells fishy...
```
[Try it online!](https://tio.run/##S8sszvj/vzg/N7UkIzMvXaE4NzUnp1ghDShcqaenx/X/PwA "><> – Try It Online")
```
s... # trimmed program
s # invalid command, causes fatal error "something smells fishy...\n"
... # unreachable code
```
## [Befunge-93](https://github.com/catseye/Befunge-93), 108 bytes - Hello, World!
```
"!dlroW ,olleH">':#,_@';_='"!dlroW ,olleH">\':#,_@\';_=%r;print(_%%_)';print(_%_)
something smells fishy...
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X0kxJacoP1xBJz8nJ9VDyU7dSlkn3kHdOt5WHV0qBiIXA5JULbIuKMrMK9GIV1WN11SHc@I1uYrzc1NLMjLz0hWKc1NzcooV0jKLMyr19PS4/v8HAA "Befunge-93 – Try It Online")
```
"!dlroW ,olleH">':#,_@... # trimmed program
" # push charcodes of...
!dlroW ,olleH # literal...
" # separately onto stack
" # end literal
> # move right
' # NOP (unrecognized command)
: # duplicate top of stack when going right, NOP when going left
# # skip over next command in current direction
, # output top of stack as a character when going left, NOP when going right
_ # pop top of stack, go left if nonzero
@ # terminate
... # unreachable code
```
]
|
[Question]
[
Challenge Description:
An anagram is a word or phrase formed by rearranging the letters of another word or phrase. For example, "listen" and "silent" are anagrams. In this challenge, your task is to write a program or function that takes a list of strings as input and returns the unique anagrams.
Write a program or function that takes a list of strings as input and returns the unique anagrams, preserving the order of appearance. Your solution should handle lowercase letters (a-z) only.
Examples:
| Input | Output |
| --- | --- |
| `["cat", "act", "tac", "dog", "god"]` | `["cat", "dog"]` |
| `["a", "ab", "abc", "abcd"]` | `["a", "ab", "abc", "abcd"]` |
| `["cat", "dog", "tac", "god", "act"]` | `["cat", "dog"]` |
The input list contains five strings. The strings "cat", "act", and "tac" are anagrams of each other, and "dog" and "god" are anagrams of each other. The output should contain only one representative from each group of anagrams, preserving the order of appearance. Hence, the output is `["cat", "dog"]`.
Requirements:
The input list can contain duplicate strings, and they should be considered as separate entities.
The output should contain only one representative from each group of anagrams, preserving the order of appearance.
The input list may contain an arbitrary number of strings.
The input list and the output list can be empty.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes is the winner.
Good luck!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṣ€Ḣƙ
```
A monadic Link that accepts a list of lists and yields a list of lists containing the first of each anagram.
**[Try it online!](https://tio.run/##y0rNyan8///hzkWPmtY83LHo2Mz/h9sj//@PVkpOLFHSUVBKyU8HUSWJySCquCSxCEQXJZYUg@hkKJ2enwKiEpNLlGIB "Jelly – Try It Online")**
### How?
```
Ṣ€Ḣƙ - Link: list of lists, Words
Ṣ€ - sort each word
ƙ - group Words by sorted_words and apply to each:
Ḣ - head
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 32 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4 bytes
```
⁽sġvh
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJBPSIsIiIsIuKBvXPEoXZoIiwiIiwiW1wiY2F0XCIsIFwiYWN0XCIsIFwidGFjXCIsIFwiZG9nXCIsIFwiZ29kXCJdXG5bXCJhXCIsIFwiYWJcIiwgXCJhYmNcIiwgXCJhYmNkXCJdXG5bXCJjYXRcIiwgXCJkb2dcIiwgXCJ0YWNcIiwgXCJnb2RcIiwgXCJhY3RcIl0iXQ==)
Works well.
## Explained
```
⁽sġvh
⁽sġ # Group by sorting each word - groups based on first appearance of each word
vh # Get the first word in each group
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 28 bytes
```
->l{l.uniq{|z|z.chars.sort}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkevNC@zsLqmqqZKLzkjsahYrzi/qKS29n@BQlp0tFJyYomSjoJSYjKYKklMBlEp@ekgKj0/RSk29j8A "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.¡{}€н
```
[Try it online](https://tio.run/##yy9OTMpM/f9f79DC6tpHTWsu7P3/P1opObFESUdBKTEZTJUkJoOolPx0EJWen6IUCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vUMLq2sfNa25sPe/zv/oaKXkxBIlHQWlxGQwVZKYDKJS8tNBVHp@ilKsjkK0UiJYSRKETIZSUDmoAVAtUANAOqGmxsYCAA).
Or alternatively:
```
€{DÙkè
```
[Try it online](https://tio.run/##yy9OTMpM/f//UdOaapfDM7MPr/j/P1opObFESUdBKTEZTJUkJoOolPx0EJWen6IUCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/0dNa6pdDs/MPrziv87/6Gil5MQSJR0FpcRkMFWSmAyiUvLTQVR6fopSrI5CtFIiWEkShEyGUlA5qAFQLVADQDqhpsbGAgA).
**Explanation:**
```
# EXAMPLE INPUT: ["cat","tac","dog","god","act"]
.¡ } # Group the words in the (implicit) input-list by:
{ # Sort the characters of the word
# STACK: [["cat","tac","act"],["dog","god"]]
€ # Then map over each group of words:
н # And only leave the first one
# STACK: ["cat","dog"]
# (after which the list of remaining words is output implicitly)
€ # Map over each word of the (implicit) input-list:
{ # Sort the characters of the word
# STACK: ["act","act","dgo","dgo","act"]
D # Duplicate this list of individually sorted words
# STACK: ["act","act","dgo","dgo","act"],["act","act","dgo","dgo","act"]
Ù # Uniquify the copy list of strings
# STACK: ["act","act","dgo","dgo","act"],["act","dgo"]
k # Pop both, and get the indices of the remaining strings
# STACK: [0,2]
è # Use those indices to index into the (implicit) input-list of words
# STACK: ["cat","dog"]
# (after which the list of remaining words is output implicitly)
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 7 bytes
Anonymous tacit prefix function.
```
⊣/∧¨⊢⌸⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXYv1HHcsPrXjUtehRzw4g@T/tUduER31TvYL9/R51zNB41Nv3qKv5Ue@aR71bDq03ftQ2ESgZHOQMJEM8PIM1gWqgqv@nqUcrJSeWKOkoKCUmg6mSxGQQlZKfDqLS81OUYtW5QMoSwYqSIGQylILLQg2BaoMaAtINNTlWHQA "APL (Dyalog Extended) – Try It Online")
`⊣/` the first elements of
`∧¨` the each-sorted
`⊢⌸` grouping of
`⊢` the argument
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 4.5 bytes (9 nibbles)
```
.=~$~`<$/
```
```
.=~$~`<$/
=~ # group
$ # the input
~ # without sorting the groups
`<$ # by the results of sorting each element
. # then map over this list of lists
/ # folding over each list
# (implicitly) returning the left-hand argument
# (so returning the first element of each)
```
[](https://i.stack.imgur.com/D9ewd.png)
[Answer]
# JavaScript (ES6), 43 bytes
```
a=>a.filter(s=>a[q=[...s].sort()]?0:a[q]=1)
```
[Try it online!](https://tio.run/##HchLCsMwDADRqxSvbGhEsw04OYjxQsgfUkyUWqLXd5Ou3jBv/KJQ30@dDk55FD/Qrwhlb5q7lavDxwcAkAjCXa2L22u5ZvSzG8SHcMvQuNpigyFU83wYpD@KdJO43lROJjo3fg "JavaScript (Node.js) – Try It Online")
### Alternate versions (same size)
```
a=>a.filter(([...s])=>a[s.sort()]?0:a[s]=1)
```
[Try it online!](https://tio.run/##HchLCsMwDADRqxSvJGhFsw24PYjxQvhHiomKJXp9J@nqMfPhH2sa29ceu@Qyq5/sX0x161YGQCAijXiuoKQyDDC@n@tZ0S84k@wqvVCXBhWCS2zufnOc/hiniyztokl2EXEe "JavaScript (Node.js) – Try It Online")
```
a=>a.filter(([...s])=>a[s.sort()]^(a[s]=1))
```
[Try it online!](https://tio.run/##HctbCsMwDETRrRR/yZAKugBnI8YFIT9IMVGxRLfvOvk63IH50I@Ux/G15ym5zBomhZ2wHt3KAIiIqMmvKSqqDAOf3rAihZf3k@VU6QW7NKgQHZO57eGIb4z4Iku7aJJdWp8/ "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.filter(s => // for each string s in a[]:
a[ // test a[q]:
q = // where q[] is the array
[...s] // made of the characters of s
.sort() // sorted in lexicographical order
] ? // if a[q] is already defined:
0 // discard this entry
: // else:
a[q] = 1 // set a[q] and keep this entry
) // end of filter()
```
[Answer]
# [Perl 5](https://www.perl.org/) `-nlF`, 23 bytes
```
$k{"@{[sort@F]}"}||=say
```
[Try it online!](https://tio.run/##K0gtyjH9/18lu1rJoTq6OL@oxMEttlaptqbGtjix8v//5MQSrpT8dK6SxGSu9PwUrsTkkn/5BSWZ@XnF/3V9TfUMDA3@6@bluAEA "Perl 5 – Try It Online")
Input and output are one word per line.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
hM.gS
```
[Try it online!](https://tio.run/##K6gsyfj/P8NXLz34//9opeTEEiUdBaXEZDBVkpgMolLy00FUen6KUiwA "Pyth – Try It Online")
### Explanation
```
hM.gSkQ # implicitly add k and Q
# implicitly assign Q = eval(input())
.g Q # group Q by lambda k
Sk # sort k
hM # take the first element of each group
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 2 bytes
```
üO
```
[Try it online!](https://tio.run/##yygtzv7///Ae/////0crJSeWKOkoJSaDyJLEZCCZkp8OJNPzU5RiAQ "Husk – Try It Online")
A not particularly clever solution, but seeing that Husk could solve this with half the bytes of other golfing languages I had to post it.
### Explanation
```
üO
ü Remove duplicates from the list, keyed on
O the sorted strings
```
Basically `ü` does exactly what we need for this challenge: for each value in the input list, discard it if it is the same as any previous value when a function is applied to it. The function we use for this comparison is here simply the sorting function.
[Answer]
# [Scala](https://www.scala-lang.org/), 80 bytes
Golfed version. [Try it online!](https://tio.run/##XY7NasMwEITvforFJ4mWkFydypB7ezI5hR62@kNFkVvtkqQYP7srpbiUnj5mdnZ2SWPEZXx7t5rhBUOCqQEw1sG5CIHZUweHnPHrNHAOyb/KDo4pMKh7EuCCEWKgajwXiFYjt4/Qor6DUVeY0Vf40bTyd82UfEiaDwl9xjOVCidq10/ko9zjmMT/WJ3OTVMbXDfYz/Uz1f8RoJar6qcLZiA1WF59IffXjQuRbRY31QcnSNw2NGa2RkrY9juwkSxM9KBWf7992s1yXublGw)
```
w=>{var s=Set[String]();w.filter(x=>if(s(x.sorted)) 0>1 else {s+=x.sorted;0<1})}
```
Ungolfed version. [Try it online!](https://tio.run/##XVBBbsMgELz7FSufsJr6AZEcKT03p6jqocphC2uLCkO00FRV5Le7gElqhQPLzM4sA16iwXl2n18kAxxQW7hWAIp6GCMQyIPfwp4Zfz@OgbUdTs0W3qwO0GUlwAUNGO0T8RqLqCWGegM1ylwCylSUG1IZnKqbu01FvbYy7C0OjKOPI5hGd6EbIdLgRX@OlwdjxaMndaeqZH5w/zhWMX6KtUq/hqtXMHgiG4kDnkt7Ay/OGUJ7EkuIPLDttQnEcM0Qul1uLS/yjgOp98zndrswRaJ7EOmWVjob4v968W9oGujReCpSiseSLa2c7amDlQGedxD4m5q7KKECpuq2T9VUzfMf)
```
object Main {
def main(args: Array[String]): Unit = {
val list = List("cat", "act", "tac", "dog", "god")
val distinctAnagrams = removeAnagrams(list)
println(distinctAnagrams)
}
def removeAnagrams(words: List[String]): List[String] = {
var seen = Map[String, Boolean]()
words.filter { word =>
val sortedWord = word.sorted
if (seen.contains(sortedWord)) false
else {
seen += (sortedWord -> true)
true
}
}
}
}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~38~~ 33 bytes
```
#&@@@#~GatherBy~Sort@*Characters&
```
Thanks to @att!
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1nNwcFBuc4dJFrkVFkXnF9U4qDlnJFYlJhcklpUrPY/oCgzr8QhzaFaKTmxRElHQQkoAaJKEpNBVEp@OohKz09Rqv0PAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org), 70 bytes
```
\(x)x[match(unique(y<-sapply(x,\(s)intToUtf8(sort(utf8ToInt(s))))),y)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY33WI0KjQronMTS5IzNErzMgtLUzUqbXSLEwsKcio1KnRiNIo1M_NKQvJDS9IsNIrzi0o0gBotQvI980qAUiCgU6kZCzXtU5pGsoZScmKJko6CUmIymCpJTAZRKfnpICo9P0VJU1OZMxqmCiQeywXWlwjWlQQhk6EURDkQROOSh-pGMg9hK8g6qFNw2QoVAVJQFgGtCIVgQyA-X7AAQgMA)
String manipulation isn't something R is good at.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Could be [4](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=/PEg1Q&input=WyJkb2ciLCAiY2F0IiwgImFjdCIsICJ0YWMiLCAiZG9nIiwgImdvZCJdCi1R) if Japt had a built-in for grouping *without* sorting.
```
üñ mÎñ@bX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/PEgbc7xQGJY&input=WyJkb2ciLCAiY2F0IiwgImFjdCIsICJ0YWMiLCAiZG9nIiwgImdvZCJdCi1R)
```
üñ mÎñ@bX :Implicit input of array U
ü :Group & sort by
ñ : Sorting
m :Map
Î : First element
ñ :Sort by
@ :Passing each X through the following function
bX : First index of X in U
```
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 116 bytes
```
a=>a.Aggregate(new Dictionary<string,string>(),(d,i)=>{d.TryAdd(string.Concat(i.OrderBy(m=>m)),i);return d;}).Values
```
[Try it online!](https://tio.run/##VZHdSsQwEIWvN08x7FUCtS9QW1h/ERQFRS/EizGZjYE20Um6UpY@e22XqOzVkDPfDGdOdDzRUU99dN7C4xATdeWt81@VOJLOQ9uSTi74WF6TJ3a6EkK3GCM8cLCMHezFKiZMTsMuOAN36LyMiectr2@AbKOakYXJkvOffYIaPH3Dn7hfa0zrAtYm2KUk1EuxwSwF9aGXkfzKSB5YyLESKyGy9ave69Pf/QXcXPq@I8b3lrLaNLCFesK6wXJjLZPFRHJxdeEOJyMPGS3yhFSFNIVTdbM35RMPG2PyqXNSfrYnXXnPhvhskF3ddErNcMWUevZgqlGVz9j2FKdKbAMT6g@QO2QIcyiwlYdklPoP38fQUvnCLtH8OSSDqsQoxukH "C# (Visual C# Compiler) – Try It Online")
[Answer]
# [Python 3](https://python.org), 91 bytes
```
def h(l):s=set();return[w for w in l if(x:=''.join(sorted(w)))not in s and (s.add(x) or 1)]
```
[Attempt This Online](https://ato.pxeger.com/run?1=dVBLTsMwEN1zisGb2FKoxA4F-SRRZBl_UqPWruIpCSo9CZts4CRcorchjhPKAmbhJ828z4zfPw-vuA1-vHyhiSiUjCYCh_oGpqI1URJJCUSqGVCqBDq0CdqgSVPCDym1G1auUjkLn_KrFlgU_82u6l-e1-CUuGzzV3DzcUR793CptbGwpTtWRR4NUvbYGTx2vu7Bhg56cB524CwdKl4Um-fgPI2hQ6NpzxjzARMjgvQaaNxIrenAYFLeszXizVkQwsu9EQI4h0KIvXReiKKaL0g5rXsxvgQzHIyaHa9fnEmpZIymw2nbmc2SVxaUYMlpbZ_hlsMpD84k7zCOGb8B)
I wonder whether the filter expression can be shortened further.
[Answer]
# [Haskell](https://www.haskell.org/), 64 bytes
```
import Data.List
s=sort
a=map head.groupBy((.s).(==).s).sortOn s
```
[Try it online!](https://tio.run/##FcoxCoQwEEbh3lMMYhGb3GCaZcsFz/BjJIY1mZAZEU@fXasHH2@Hfrfj6D3lKs3oDYP/JLVBWf8wgDMq7RuCj03O@rqd8zp7xzw/faalkPaMVLi2VGzCdEkLOq4wChIpSiCsNvYf "Haskell – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 17 bytes
```
!x=unique(sort,x)
```
[Try it online!](https://tio.run/##dY1BCsIwEEXX9hTjrFIIAQ9Q8QKeQLsY21FGQlKTVHr72rRFEXEW8@H/P/PuvRXaDeO4HareyaNnFX1IeijHqw8gIA4CU2vFcVRlAdOQZqiAn2SNOnIi01GIbFTsrCQlGs8Jy3Lphql59@KM2s6xUaQR17AL4pJ1iqDaQ1i8A8XIIeXDiVGwa8cTNpRQA1IzS6ImS@tvWW6@xRo271K26@KENF9clt2sslb/ZcXXlw8qM1b@D@oF "Julia 1.0 – Try It Online")
input and output are a list of lists of characters
28 bytes with a list of strings as input and output: [Try it online!](https://tio.run/##dY1RDoIwDIaf5RRlT1uCSzwAxgt4AuShskpqloHbMNweGRCNMfahf9N@/f/7YBkP4zTlYzk4fgwkeX8MnY@yYq11rYpRTbfOAwM78ITGsqMgVQZzYUFQAj3RanmmiLpHH0jL0FuOkgtxiUKplfUzmeMy9p5dtE4ilEfw6/mEIZCPCZsdM3JmqkSDURQgsFkkYpPEdG2StjOiht0bSus6qwQuH9e1N5ts6L9b9uXyiUoZW/5P1As "Julia 1.0 – Try It Online")
[Answer]
# C (gcc), 277 bytes
```
#define C(A,L)for(int i=A=0;L[i];L[i++]==t&&++A);
i,j,k,x,y,r,t;D(char*a,char*b){for(r=k=0;(t=a[k])||b[k];++k){if(!a[k]||!b[k]){++r;break;}C(x,a)C(y,b)x-y!=0&&++r;}}
main(int c,char**v){for(i=1;i<c;++i){for(j=i-1;j>0;--j){D(v[j],v[i]);if(r==0)goto B;}printf("%s ",v[i]);
B:1;}}
```
[Try it online!](https://tio.run/##LY/NboMwEITveQpI1cgbGwmu2boSIce8AeJgzE8NLVSORUHAq9c1pJcdabQ736wMaimtfSnKSnWll5CY3aHqNVGd8RSPeYj3VGXboDTj3JxOlMaAB8Ua1rKRTUwzgzciP4Q@C7ZLDvMWoXnrzonhIm0zWJbcCVLawqwq4m/msvibCTOlGnNdihbXhIxMQEImlsMYTD4PN6TGdf0Sqtt7ySfmPIC3gxSPUL1Jl62e5IarIMLmPcQgaGC@kSFtMja4RwAdW3MeQt2b3rvi@q1dZEWOrw/v@L9yuF4ix7PWSmFs0dfWCGnrvrBCml9ZfYr6YYOfPw)
Readable version:
```
#define C(A,L)for(int i=A=0;L[i];L[i++]==t&&++A);
i,j,k,x,y,r,t;
D(char*a,char*b){
for(r=k=0;(t=a[k])||b[k];++k){
if(!a[k]||!b[k]){++r;break;}
C(x,a)
C(y,b)
x-y!=0&&++r;
}
}
main(int c,char**v) {
for(i=1;i<c;++i){
for(j=i-1;j>0;--j){
D(v[j],v[i]);
if(r==0)goto B;
}
printf("%s ",v[i]);
B:1;
}
}
```
Explanation:
Not the most efficient approach but light on code: go through each item in the list (given as arguments), compare to each prior item using a difference function D, and print if none of them matched.
To check matching, the difference function goes through each character in the first string and counts the number of occurrences in either string of that character. If at any point either that number differs or we have finished processing one string while the other is still going, we consider the two non-matching.
To save bytes, I added the counting macro C, which accumulates into variable A the number of occurrences of global character t in list L.
-
# C (gcc), 303 bytes (alternate answer)
```
typedef unsigned long long u;n,i,j,k,z;u t;u y(n){return n==1?1:z*y(n-1)+1;}s(char* v){for(k=t=0;v[k];++k)t+=y(v[k]-96);}main(int c,char *v[]){long f[c];for(i=1;i<c;++i)for(j=0;v[i][j];++j>z&&++z);for(i=1;i<c;++i){s(v[i]);for(j=n,k=0;j>0;--j){f[j-1]==t&&++k;}if(k)continue;printf("%s ",v[i]);f[n++]=t;}}
```
[Try it online!](https://tio.run/##ZY5BbsMgEEWvgiI1ggBS2FRqKelBkBcI2xRIxpGNXdmWr15qku66mJFm5v8333Jnbc5pvjd106IRBu@gqdG1A/dsowTmWWCRLXJEaa8ZA1n7Jo09IFBKfIr35bQvuSBUyG3A9sv0JzSRte16HFVSZznpWElKI0lUzbhM/O2VyO1mPGAPCVlWXOg06Yqsj8ettpUsBK@E9B92t3tS5vDg@UqHggyX5XikdCH/tOuAi@x5CApY3I3hcpachz2bDlxUSqXijnLzLY7EdpA8jI2893uoFh9eBnRgfxQNlFYqyW3LOVuTct25nIzNrquzsenHtlfjhsy/fwE "C (gcc) – Try It Online")
Readable version:
```
typedef unsigned long long u;
n,i,j,k,z;u t;
u y(n){return n==1?1:z*y(n-1)+1;}
s(char* v){for(k=t=0;v[k];++k)t+=y(v[k]-96);}
main(int c,char *v[]) {
long f[c];
for(i=1;i<c;++i)for(j=0;v[i][j];++j>z&&++z);
for(i=1;i<c;++i){
s(v[i]);
for(j=n,k=0;j>0;--j){f[j-1]==t&&++k;}
if(k)continue;
printf("%s ",v[i]);
f[n++]=t;
}
}
```
Explanation:
For sufficiently short strings, this alternate approach will work. We are calculating a signature, which is something like a checksum but reserving non-overlapping number ranges for the potential counts of each letter, for each given list item. We go through the items and then, each time we encounter a novel signature, we print the item and store the signature.
These signatures as currently calculated get *really* large *really* fast, so this will only work for short words. Realizing this, I switched to the other approach, but still thought it was interesting enough to include.
I suspect that with a little more work, this could not only work for arbitrarily-long arguments, but also do so with a lighter footprint than the first approach!
[Answer]
# [Arturo](https://arturo-lang.io), 32 bytes
```
$=>[gather&=>sort|map[k,v]->v\0]
```
[Try it!](http://arturo-lang.io/playground?QZ0kU8)
Collect input strings in a dictionary where the key is the sorted string and the value is a list of strings that sort to that key, then map each dictionary entry to its first value. Input is taken as a list of lists of code points.
[Answer]
# Excel, 99 bytes
```
=LET(r,ROW(A:A),b,BYROW(A:A,LAMBDA(s,CONCAT(SORT(MID(s,r,1))))),FILTER(A:A,(b<>"")*MATCH(b,b,0)=r))
```
Note: This takes quite a long time to run on my weak machine and sometimes just locked Excel. For the sake of the screenshots below, I changed the range references from `A:A` to just `A1:A10`. The logic is all the same, though.
Input is one string per cell in column A.
* `LET(r,ROW(A:A)` creates an array of values 1 to 1,048,576 and assigns it to the variable `r`.
* `b,BYROW(A:A,LAMBDA(s,CONCAT(SORT(MID(s,r,1)))))` takes each string, splits it into pieces, sorts those pieces, and then combines them back into a string. The array of all these new, sorted strings is assigned to the variable `b`.
* `FILTER(A:A,(b<>"")*MATCH(b,b,0)=r)` filters out the values where that result array `b` is blank and then only returns the strings from the input array where their index in the input matches the first instance of their sorted string in the sorted string array `b`.
[](https://i.stack.imgur.com/nIjgM.png)
There are probably shorter ways to do this and I welcome someone pointing them out.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 53 bytes
```
$args|?{($k="$($_|% t*y|sort)")-notin$s-and($s+=,$k)}
```
[Try it online!](https://tio.run/##dY7dToMwFMfveYqTprpW6SMQMWbeauTCC2OWrnSMDelsS6YBnh1XvsYW7EVPcs7/43dQR6nNVmYZE0rLBm@CssFcJ6Z6KAneBwgTvKpuwN79VkZpSxFlubJpjg3jeUywuQ98vKd1U3teSDw4PR9CEhIkuEU@IC7aYblwI1aJG4mKEXW6QeX2lE7tvDWvu1/0Y3D9d6QzAH1lD@Cae6o5AAoVPCu95GLLXtY7KSyUbSY@Kh0bH7D8OZy2MoYA8Ko7aWmKzJ4Wt3gDYSvsDoP20URWp3niPKOf7VSaw8JfTEOmyj72UvfxGj0Vxqqvju4z7PDciwohpDHTkjGOye/ritH37oDB2Vr0q0L3lgPzXPaoeut4z@gXitqrveYP "PowerShell Core – Try It Online")
Takes the words arguments using splatting, returns a list or words.
It works by building a list of keys for each word by sorting its letters alphabetically:
e.g. `cat` has the key `a c t`
Then for each word `$_`, if the word's key `$k` is not in the list `$s`, add `$k` to `$s` and return `$_`
[Answer]
# [Factor](https://factorcode.org/) + `sets.extras`, 22 bytes
```
[ [ sort ] unique-by ]
```
Factor has the perfect combinator for this, `unique-by`, which returns a list of the first unique values in a list after a function has been applied to each element. Requires Factor build ~2207+ for `sort`, hence this won't work on TIO or ATO.
[](https://i.stack.imgur.com/PfqF2.png)
[Answer]
# [simply](https://github.com/ismael-miguel/simply), ~~105~~ 100 bytes
Yes, it's very long, but makes use of the built-in `&marsagain`.
(It's an anagram for `&is_anagram`, that happens to be 1 byte shorter.)
```
fn($x){$A=[]each$X in$x{$L=0each$a in$A if!$L$L=&marsagain($X$a)if!$L$A=&array_concat($A$X)}send$A;}
```
Defines an anonymous function that takes an array of strings and returns an array of strings.
---
---
## Ungolfed
This is the same code, but ungolfed.
### Code-like
```
anonymous function($words) {
$anagrams = [];
each $word in $words {
$in_the_list = false;
each $anagram in $anagrams {
unless $in_the_list then {
$in_the_list = &is_anagram($word, $anagram);
}
}
unless $in_the_list then {
$anagrams = &array_concat($anagrams, $word);
}
}
return $anagrams;
};
```
### English-like
```
Set the variable $fn to an anonymous function with arguments($words)
Begin.
Set the variable $anagrams = [].
Foreach $word in $words
Begin.
Set the variable $in_the_list to false.
Foreach $anagram in $anagrams
Begin.
Unless $in_the_list then
Begin.
Set the variable $in_the_list to the result of calling the function &is_anagram with the arguments ($word, $anagram).
End.
End.
Unless $in_the_list then
Begin.
Set the variable $anagrams to the result of calling the function &array_concat with the arguments ($anagrams, $word).
End.
End.
Return the value of $anagrams.
End.
```
Both variants do the same.
---
---
## Testing it
To test it, you have to assign it to a variable, E.g.:
```
$fn = fn($x){$A=[$x->0]each$X in$x{$L=0each$a in$A if!$L$L=&marsagain($X$a)if!$L$A=&array_concat($A$X)}send$A;};
// Copy-paste from the tests
$result = call $fn(["cat", "dog", "tac", "god", "act"]);
// Should output ["cat","dog"]
echo &json_encode($result);
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
WSF⬤υ⊙⁺ικ⁻№ιμ№κμ⊞υιυ
```
[Try it online!](https://tio.run/##JYxBCgMhDEX3OUWWEewJZjV01UVB6AnEaVUm1eIkLT29Vfp378H7IfkWqufePynzHelSXio3ablEMgYftSGtzKQW1/Ilx3pQtrgbi9dcBpyrFpnqOdQf9glz6PRIM81mATc@hdQsvQcv4IOA@ABbjRDrBv305h8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:
```
WS
```
Repeat for each input string.
```
F⬤υ⊙⁺ικ⁻№ιμ№κμ
```
If none of the unique anagrams so far are anagrams of this string, then...
```
⊞υι
```
... add this string to the list of unique anagrams so far.
```
υ
```
Output the final list of unique anagrams.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ñṠ€h
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWKw9vfLhzwaOmNRlLipOSi6GiC24qRyslJ5Yo6SgoJSaDqZLEZBCVkp8OotLzU5RiIWoB)
#### Explanation
```
ñṠ€h # Implicit input
ñṠ # Group by sorting
€h # First item of each
# Implicit output
```
]
|
[Question]
[
Write a program to replace all occurrences of "force" with "first" and all occurrences of "first" with "force", keeping the original case for all character positions:
```
"ForcefoRcefOrcE" -> "FirstfiRstfIrsT"
"FirstfiRstfIrsT" -> "ForcefoRcefOrcE"
```
The rest of the string must stay unchanged, and so running your program twice shall return the original string:
```
"thirst of forces" -> "thirst of firsts" -> "thirst of forces"
```
Your program should work on any initial string. So as a hint, you better avoid using magic characters as intermediate representation, because if you try a three pass replacement (`"force" -> "zzzzz", "first" -> "force", "zzzzz" -> "first"`), it will fail on strings containing `"zzzzz"`.
You should support the full range of characters allowed in a definition of a String by your programming language (in most cases, it's Unicode). Example, using JSON-style representation for non-printable characters (\u + 4 digits):
```
"\u0000\u0001\u0002\u0003the Force of the firsT"
|
V
"\u0000\u0001\u0002\u0003the First of the forcE"
```
[Answer]
## JavaScript (ES6), ~~93~~ 88 bytes
```
f=
s=>s.replace(/force|first/gi,s=>s.replace(/./g,c=>s[s.search(c)^1]||c,s="oicsetOICSET"))
```
```
<textarea oninput=o.textContent=f(this.value)></textarea><pre id=o>
```
Edit: Saved 5 bytes by optimising the unchanged letter case.
[Answer]
# [Retina](https://github.com/m-ender/retina), 33 bytes
```
iT`\OC\E\ocetsiTSI`Ro`first|force
```
[Try it online!](https://tio.run/nexus/retina#@58ZkhDj7xzjGpOfnFpSnBkS7JkQlJ@QlllUXFKTll@UnPr/v29ipUJJRqqCG4irkJSqUJ5ZkqFQmV8KAA "Retina – TIO Nexus")
Edit: Saved 5 bytes thanks to @MartinEnder for pointing out what `Ro` does.
[Answer]
# [Perl 5](https://www.perl.org/), 52 bytes
51 bytes of code + `-p` flag.
```
s%first|force%$&=~y/oceOCEistIST/istISToceOCE/r%eig
```
[Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@F@smpZZVFxSk5ZflJyqqqJmW1epn5@c6u/smllc4hkcog@hIEL6Raqpmen//4dkpCq45Rc5uyokJ@amKqRlBhWHAAA "Perl 5 – TIO Nexus")
Nothing too crazy going on. Find the occurrences of `force` and `first` non-case-sensitive (`s%force|first%%gi`), and then transliterates the characters to convert one to the other.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 61 bytes
Requires `⎕IO←0` which is default on many systems. Can be four *characters* shorter using the Unicode symbol `⍠` instead of `⎕OPT` .
```
(t←'force' 'first')⎕R{(m∊⎕A)c¨t⊃⍨~t⍳(c←819⌶)⊂m←⍵.Match}⎕OPT 1
```
[Try it online!](https://tio.run/nexus/apl-dyalog#U9Z71DfV0/9R2wSD/2lAUqMESKin5Rclp6orqKdlFhWXqGsClQRVa@Q@6ugCshw1kw@tKHnU1fyod0VdyaPezRrJQC0WhpaPerZpPupqygXyHvVu1fNNLEnOqAVq8A8IUTD8/z9NQd0NbCwXiAU2GMRKyw@CiqVlBsHE/IuSXSEsz6LiEBDL3NAUZIG6UkypARCASUMwaQQmjUsyUhXA5ivkpymAOCC3hygRrxfkIrheoEGuQL0A "APL (Dyalog Unicode) – TIO Nexus")
[Answer]
# PHP, 88 Bytes
[Online Versions](http://sandbox.onlinephpfunctions.com/code/7e93753dcfb53bde47d01c4cacfb3abaeaa1a1c6)
```
<?=preg_replace_callback("#first|force#i",function($t){return$t[0]^first^force;},$argn);
```
# PHP, 110 Bytes
```
<?=preg_replace_callback("#first|force#i",function($t){return strtr($t[0],iIsStToOcCeE,oOcCeEiIsStT);},$argn);
```
[Answer]
# Java 10, ~~318~~ ~~310~~ ~~284~~ ~~279~~ ~~277~~ ~~271~~ 256 bytes
```
String c(String s){var x=s.toLowerCase();int i=x.indexOf("force")+1,j=x.indexOf("first")+1,t=i>0&j>i|j<1?1:-1;var y=s.toCharArray();return-j<i?s.substring(0,i=t<0?j:i)+(y[i++]-=t*6)+y[i++]+(y[i++]+=t*16)+(y[i++]+=t*15)+c(s.length()>i?s.substring(i):""):s;}
```
-34 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##hZFNb8IwDIbv/AqrhylZR0U3jQOloAltEtIQUuHGOISSDnesmRKXUTF@O2vDh8SF5mDFzuvXyZNUbEQzXX4d4rUwBkYCs10DwJAgjOEwIY3ZJ8TstDF8txEatqHxSL2rX6kHwkjGA8wIMNx6mC3ldpwwJ1E6lg53/Yf0qozakC1TiL3WXdrDv7Tr9/1O0w8q68JaD1ZCv2gtitJaS8p11ky72DeeyRfGXoW1HjCkbqufdpC7rJih686bId23uXtMzkW3LPptfpU@czdmxlvL7JNWjPeurZF3HId3TLA/BI2Sxk@@WJc0TlA2CpfwXYI6QZnNQfAKGsCkMCS/PZWT91Me0TpjMXPejih4cEtz5HJTk6io1ifBqN5nrOPXOs1Qm2mN5iNvlctG38ZHG59oJcG@GVQCVVJ9ep3ZSBQXLcFCwi/SCgqV1/RNq56hntB5mCV5mTyOBq@Xk2E0mV4SFQ1qYNbcyrbuG/vDPw)
**Explanation:**
```
String c(String s){ // Recursive method with String as both parameter and return-type
var x=s.toLowerCase(); // Temp String as lowercase of the input
int i=x.indexOf("force")+1, // Index of "force" + 1 (becomes 0 if NOT present; >=1 if it is present)
j=x.indexOf("first")+1, // Index of "first" + 1 (becomes 0 if NOT present; >=1 if it is present)
t=i>0&j>i|j<1?1:-1; // Temp integer: -1 if "force" is found first; 1 if "first" is found first
var y=s.toCharArray(); // Convert the string to a character-array
return-j<i? // If either "force" or "first" is found:
s.substring(0,i=t<0?j:i) // Return the substring before that (if any) + ('f' or 'F')
+(y[i++]-=t*6) // + 'i'↔'o' or 'I'↔'O'
+y[i++] // + 'r' or 'R'
+(y[i++]+=t*16) // + 's'↔'c' or 'S'↔'C'
+(y[i++]+=t*15) // + 't'↔'e' or 'T'↔'E'
+c(s.length()>i?s.substring(i):"") // + a recursive call for the rest of the input-String (if any)
: // Else:
s;} // Return the input-String as is
```
[Answer]
## CJam, 66 bytes
```
qY5m*_"force"{f{_eu}3/:z{~?}f%}:K~\"first"K.{[\]:P~@\/\f/P~@\f*\*}
```
Goes through every case variation of "first" and "force" and tries to split on it. If it can, it then joins it back with the reverse words.
Pseudocode:
```
input_chars = list(read_all_input()) # CJam: q
power = cartesian_power(2, 5) # CJam: Y4m*_
def case_variations(s): # CJam: {...}:K
temp0 = [[i, j, upper(j)] for i, j in zip(power, s)] # CJam: f{_eu}3/
temp1 = map(transpose, temp0) # CJam: :z
ret = []
for i in ret:
for j in i: # CJam: {...}f%
ret.append(j[1] if j[0] else j[2]) # CJam: ~?
return ret
force_var = K("force") # CJam: "force"{...}:K~
first_var = K("first") # CJam: \"first"K
for force, first in zip(force_var, first_var): # CJam: .{...}
current = [force, first] # CJam: [\]:P~
input_chars = list_split(input_chars, force) # CJam: @\/
input_chars = [list_split(i, first) for i in input_chars] # CJam: \f/
input_chars = [list_join(i, force) for i in input_chars] # CJam: P~@\f*
input_chars = list_split(input_chars, first) # CJam: \*
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Is there is a way to use a reduce across slices of length 5 instead?*
```
®‘©ị“Ɓu“¡Ḣƭ»
Œlœṣ¢œṣ€¢j€¢j¢Œu⁸=ŒuT¤¦
```
**[Try it online!](https://tio.run/nexus/jelly#@39o3aOGGYdWPtzd/ahhzrHGUiB5aOHDHYuOrT20m@vopJyjkx/uXHxoEZh61LTm0KIsCAkUmlT6qHGHLZAKObTk0LL///8ruWUWFZcolGSkKqSBWWn5RcmpEDJFwc0/yNlVCQA)**
### How?
```
®‘©ị“Ɓu“¡Ḣƭ» - Link 1 helper that fetches the next word to use: no arguments
® - recall value from register (initially zero)
‘ - increment
© - place the result into the register
“Ɓu“¡Ḣƭ» - literal dictionary compressed string list ["first","force"]
ị - index into (1-indexed and modular)
- so this link first yields "first", then "force", then "first" and so on.
Œlœṣ¢œṣ€¢j€¢j¢Œu⁸=ŒuT¤¦ - Main link: list of characters, S
Œl - convert S to lower case
œṣ - split on sublists equal to:
¢ - call the last link (1) as a nilad ("first")
œṣ€ - split €ach on sublists equal to:
¢ - call the last link (1) as a nilad ("force")
j€ - join €ach with:
¢ - call the last link (1) as a nilad ("first")
j - join with:
¢ - call the last link (1) as a nilad ("force")
¦ - apply a link to sparse indices:
Œu - convert to upper case
¤ - nilad followed by link(s) as a nilad:
⁸ - chain's left argument, S
Œu - convert to upper case
= - equal to S? (vectorises)
T - truthy indexes (indexes at which input is upper case)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 47 bytes
```
5W:qB!"o['first';'force']@!32*-cZ}_Zt5M_6MoZt|c
```
[Try it online!](https://tio.run/nexus/matl#@28ablXopKiUH62elllUXKJurZ6WX5Scqh7roGhspKWbHFUbH1Vi6htv5psfVVKT/P@/um9ipUJJRqqCG1Cdq0JSqkJ5ZkmGQmV@qUJ@HlgizRNokEJ@mgJQpToA "MATL – TIO Nexus")
This uses negative values as the intermediate step, and after the two passes it takes the absolute value.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~36~~ 35 bytes
```
K"first"srVjJ"force"mjKcdJcr0QKqVr1
```
[Try it online!](http://pyth.herokuapp.com/?code=K%22first%22srVjJ%22force%22mjKcdJcr0QKqVr1&input=%22The+fIrSt+of+the+First+of+the+fORCE+of+the+FIRST+of+the+FoRCe%22&debug=0)
Pyth is not especially good at string manipulations.
[Answer]
# Flex (lexer), 72 bytes
```
%%
#define x(a) yytext[a]^=
(?i:first|force) x(1)6;x(3)16;x(4)17;ECHO;
```
To compile and run:
```
flex first.l
gcc lex.yy.c -lfl # -ll on Macs, apparently
./a.out
```
[Answer]
# Python 2, 171 bytes
I wanted to try to do this using built-ins, but it can't beat the messy method with all the splitting and zipping.
```
import re,string as g
def f(s):f="istISTECOeco";l=re.split("(first|force)",s,0,re.IGNORECASE);l[1::2]=[t.translate(g.maketrans(f,f[::-1]))for t in l[1::2]];print"".join(l)
```
I think it's pretty clear what I'm doing here. Split the string on instances of first and force (case-insensitive), replace those instances with versions translated using str.translate, and join it back into a string again.
[Try it online!](https://tio.run/nexus/python2#LY4xa8MwFIT3/oqHJglUE6ebjIcS3JIlgSSbY4Jw3nPVKpKRXsjS/@46pjd8cBx33ORuY0wMCXXm5MIANsPwckUCklkZqoXLvD2ems0e@ygqXycs8ugdSyHJpcy/FFOPSuisV3oOt5@7/aHZvB8bVfm2NGbd1S0XnGzI3jLKobjZH1y8JE2tMa9lp9Q8AwwuwH@pq8b5EAtRfEcXpFcTyWQfFxfGO0ulpvN9NWthuXC98I2/ED7ioUeIBE/zvHn6Aw "Python 2 – TIO Nexus")
[Answer]
# Python 2.7, ~~173~~ 165 bytes
8 bytes saved by quintopia
This one got gross:
```
lambda S:`[(t[0],t[0].upper())[t[1]]for t in zip("".join("first".join(s.replace("first","force")for s in S.lower().split("force"))),[l.isupper() for l in S])]`[2::5]
```
[Try it online](https://tio.run/nexus/python2#RY5NC8IwDIbv@xWhpxZKUcHLYEe9Cu5YCtatZZW6ljYy8M/PdijmkI@XPHmz2s7r533U0Lc3SVHuFK9JvGI0iTImUe6VsiEBgpvh7SIlRDyCmymxLmX8DlkkE70ezE/mpECDIayyubK98GGpR0WO3iH9LTDGpRcufy2hAn4DFFM3eWjbo1p76ECScyVsuJZ0ScOpmOBU3SBY2K5lwmHTRkBT9EFnA4vDKbwQTKkmwRLSSFTz/6ttoERMbkawNDNe9K4rbR3Y@gE)
Breaking it down step by step:
1. `S.lower().split("force")`: take the string, unify to lowercase, split into substrings separated by `"force"`
2. `s.replace("first","force")for s in <STEP 1>`: Replace all `"first"`'s with `"force"`
3. `_`.join("first".join(<STEP 2>)`[2::5]`_`: replace all `"force"`'s with `"first"` by recombining the `"force"` delineated substrings with `"first"` and rejoin into single string (underscores added to get tick marks correct)
4. `zip(<STEP 3>,[(2,1)[l.isupper()]for l in S])`: zip each character of replaced phrase with case encoding of original string (2 for lowercase, 1 for uppercase)
5. `_`[(t[0],t[0].upper())[t[1]==1]for t in <STEP 4>]`[2::5]`_`: Restore original casing, converts list to string (underscores added to get tick marks correct)
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~201~~ ~~183~~ ~~226~~ 214 bytes
Had some bugs...
Still needs to be golfed down quite a lot
(saved 12 thanks to ceilingcat)
```
char*s,*p,*q;main(i,v)char**v;{puts(s=v[1]);do{p=strcasestr(s,"first");q=strcasestr(s,"force");if(p&&(!q|p<q))p[1]+=6,p[3]-=16,p[4]-=15;else if(q)q[1]-=6,q[3]+=16,q[4]+=15;s=p&&(!q|p<q)?p:q;}while(s++);puts(v[1]);}
```
[Try it online!](https://tio.run/nexus/c-clang#XY6xTwMhHIX/FbyhgYMbatVBSjp5iYNL7WKaDoickFwL3I9eY2r/bFcRzsU4vZeXLy9fUkYONbDaszrwvbQHbNlIprUe@dkfI2AQ43a@I/zNnb2AOCgJOgcGVnV2gFgRHv7vblA677bDfjbDV@HTLwMhPv9Qccf8drFrxLyUm1Juue5Bo0wHEjLTZCZkhhYmZIYWBsSfr5W/D/xyMrbXGCglfFL9Fb2klKon@YGi0ah1a6XRq0YnGw16cUfkOtRm7w2SERXRh/Zx/byZqobqW3W9fIfU7BfXXwfXKKmM/gE "C (clang) – TIO Nexus")
[Answer]
# C# 273 bytes
```
string c(string s){var x=s.ToLower();int i=x.IndexOf("force")+1,j=x.IndexOf("first")+1,t=i>0&j>i?0:j>0?1:0;return i>0|j>0?s.Substring(0,t>0?(i=j):i)+(char)(s[i++]-(t>0?-6:6))+s[i++]+(char)(s[i++]+(t>0?-16:16))+(char)(s[i++]+(t>0?-15:15))+c(s.Length>i?s.Substring(i):""):s;}
```
[Try it online!](https://tio.run/nexus/cs-mono#jVJNi8IwEL37K4YeloRqaXfRQ0v1IC4UFKEV9uB6qDW1U9xmSVI/cP3tbj@0rLBgcxgy772ZTF4S7UIpYXbuAEgVKozgKpXAbAsRuW0kPe9DAUdXGgs@5QcmCHUwU4Du0fCyDTvOY6LFXERMo7rVTR9gFFJVsHJxaL6kQxyZdjo0R5ZtOoKpXGRQED8lJI0gX9enErOrCoSgm1IbqU6iJBSUyCXq@qpHSq43sAeU6jX0KNBrgTWwrVLyL9e3rX7BFdc0pizbqqSY7O8ASG1No7Z0LleA73y9K7y5WbTnuIFZiNnNouUKQlpaCBCcpGJfxphnku@Y8SFQsSlmjEREe68tos5zZe1aC2XM/ZY9Y/Tb9pyLaNJO6Qm5aKX8zM1iVdGq4msV31TCoPIFeAxlUn6Ydi1n4ampULBmcECVwInnbaqf1Lc4flGWeiJQ98mrR2uuMffHk4bx/GDRJNwf31/s0rlcfwE "C# (Mono) – TIO Nexus")
Direct port of [Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/118234/44998), turns out when it comes to getting the char in a string at a given index, C# is much golfier than java (`s[i++]` instead of `s.charAt(i++)`)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 41 bytes
```
r"first|force"_d"i1o s1c t1e"¸m²®+ZuÃq}'i
```
[Try it online!](https://tio.run/nexus/japt#@1@klJZZVFxSk5ZflJyqFJ@ilGmYr1BsmKxQYpiqdGhH7qFNh9ZpR5Uebi6sVc/8/1@pJCNVwQ2kViE/TQHEAWkPUQIA "Japt – TIO Nexus")
This would be considerably shorter if Japt had a sane transliterate function...
Alternate version:
```
r"first|force"_d"io sc te"¸®¬¸²Ã®+ZuÃq}'i
```
[Try it online!](https://tio.run/nexus/japt#@1@klJZZVFxSk5ZflJyqFJ@ilJmvUJysUJKqdGjHoXWH1gDJTYebD63Tjio93FxYq575/79SSUaqghtIvUJ@mgKIAzIiRAkA "Japt – TIO Nexus")
[Answer]
# C#, 235 chars
```
string a(string s){var l=s.ToLower();int f=l.IndexOf("first"),F=l.IndexOf("force"),m=f<F&f>-1?f:F>-1?F:f;return ++m>0?s.Substring(0,m)+(char)(s[m]^6)+s[m+1]+(char)(s[m+2]^16)+(char)(s[m+3]^17)+(s.Length-m>5?c(s.Substring(m+4)):""):s;}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
gsub(/first|force/i){$&.tr(s="iIsStTEeCcOo",s.reverse)}
```
[Try it online!](https://tio.run/nexus/ruby#U1YsKk2qVNAt@J9eXJqkoZ@WWVRcUpOWX5Scqp@pWa2ipldSpFFsq5TpWRxcEuKa6pzsn6@kU6xXlFqWWlScqln7/z9YsUJJRqqCm2dQcIiCG4jvllkUXKIANA1onAJQhbMrAA "Ruby – TIO Nexus")
[Answer]
# Java, 382 bytes *non-comptent*
[**Try Online**](http://ideone.com/agFhBI)
```
String f(String t){String s="";for(String w:t.split(" "))if(w.equalsIgnoreCase("force")|w.equalsIgnoreCase("first"))s+=" "+w.charAt(0)+(char)(w.charAt(1)+(w.charAt(1)=='o'|w.charAt(1)=='O'?-6:6))+w.charAt(2)+(char)(w.charAt(3)+(w.charAt(3)=='c'|w.charAt(3)=='C'?16:-16))+(char)(w.charAt(4)+(w.charAt(4)=='e'|w.charAt(4)=='E'?15:-15));else s+=" "+w;return s.substring(1,s.length());}
```
[Answer]
**C# (269 Bytes)**
```
string s(string z){var u=z.ToUpper();var a=new[]{"FIRST","FORCE"};return String.Join("",u.Split(a,StringSplitOptions.None).Aggregate((c,n)=>c+(u.Substring(c.Length,5)==a[0]?a[1]:a[0])+n).Select((c,i)=>Char.IsLower(z[i])?Char.ToLower(c):c));}
```
yet another c# solution, only the second-smallest because I declared two variables and so can't use lambda syntax. oh well, I had fun. :)
explanation:
* upshift the original string, then split on "FORCE" and "FIRST".
* aggregate
the results and on every split, find the five-character substring that was used to split the original string using the length so far of the string being
aggregated. if it was "force" make it "first" and vice versa
* select all the characters of the newly created all caps string and
check if the original string was lowercase at the same index. if yes, return lowercased character at that index in the new string, otherwise return the uppercase character
]
|
[Question]
[
With the given text below, there are some words in the text that repeats several times in the text. Use any programming language to write a short code that compresses the text to display it. Or in other words, use the smallest number of bytes to display the text.
The Text is:
```
Peter Piper picked a peck of pickled peppers.
A peck of pickled peppers Peter Piper picked.
If Peter Piper picked a peck of pickled peppers,
Where's the peck of pickled peppers Peter Piper picked?
```
[Answer]
# [R](https://www.r-project.org/), 106 bytes
```
"["=gsub
cat(1["Peter Piper picked",2[" peck of pickled peppers","1 a2.
A2 1.
If 1 a2,
Where's the2 1?"]])
```
[Try it online!](https://tio.run/##HYqxCoAgFEV3v@LxlgpE0D2isa2tQRpKnxUFidr3m7UcOOfekDNqbLf4rMwsqZYaR0oUYDx8oT/MSRa50giezAm3@9tFtrgvl4gcJSxKsF6BFGxw8Cln006BqghppzJ0OM9Nzi8 "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~80 73 72 68 67 61~~ 57 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“¡ŀṪ]ṃ{yṁ“Ñ3$ṘW5Ḍż⁸¢Hŀ“³ḌM“¡FỊİg“ÑɲʋØƥþƈƘ}“ṣɠ»“Ƙ9~ḷ’ṃFḊ”?
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDC482PNy5Kvbhzubqyoc7G4FChycaqzzcOSPc9OGOnqN7HjXuOLTI42gDSO1moIgvWJPbw91dRzakg1Wf3HSq@/CMY0sP7zvWcWxGLVDs4c7FJxcc2g1kHZthWfdwx/ZHDTOBFrg93NH1qGGu/f//AA "Jelly – Try It Online")**
### How?
```
“...“...“...“...“...“...»“Ƙ9~ḷ’ṃFḊ”? - Main Link: no arguments
“...“...“...“...“...“...» - list of compressed strings
- = [" Peter Piper picked",
- " peck of pickled peppers",
- ".\nA",
- ".\nIf",
- ",\nWhere's the",
- " a"]
“Ƙ9~ḷ’ - base 250 literal X = 2331781969
ṃ - base decompress - i.e. use the list of strings as if
- they were the digits [1,2,3,4,5,0]
- X in base 6 is [1,0,2,3,2,1,4,1,0,2,5,2,1], so:
- [" Peter Piper picked",
- " a",
- " peck of pickled peppers",
- ".\nA"," peck of pickled peppers",
- " Peter Piper picked",
- ".\nIf",
- " Peter Piper picked",
- " a",
- " peck of pickled peppers",
- ",\nWhere's the",
- " peck of pickled peppers",
- " Peter Piper picked"]
F - flatten
Ḋ - dequeue (remove the leading space)
”? - literal '?' character (causes print of previous)
- implicit print (of the '?' character)
```
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~73~~ 71 bytes
```
00000000: 0b48 2d49 2d52 08c8 2c00 9205 99c9 d9a9 .H-I-R..,.......
00000010: 290a 890a 05a9 c9d9 0af9 6960 819c d414 ).........i`....
00000020: 20bf 0028 5fac c7e5 884b 4a01 d31c 3d2e ..(_....KJ...=.
00000030: cf34 0552 8cd7 e10a cf48 2d4a 552f 5628 .4.R.....H-JU/V(
00000040: c948 25c1 227b 00 .H%."{.
```
[Try it online!](https://tio.run/##dY9BSwQxDIXv/oqHIKzgxLTTzjSC93G9LehV23S6CHrckz9@zDi74MV3eKQl@fJSTqV8zsfT17LwWQ/gEhJ8DWIWPTipPZUZ4jlCRAVVsgA0dU/dgeiONl1tBGcML5yRVuNorSpVwLkJBhkYyYmiBheAW7ro4/0Pw68MLg1WJsSWFTrOESmFgpDZofZO0Vc/w4LQ7m0dft6bPV4YvTG09cEi2BlJ64jZWSJt230Z9t8QB9sACnT4jTF1@5f7192ZEVaGrP1RHbwfiyXCP6Lphq6/aVl@AA "Bubblegum – Try It Online")
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 114 bytes
```
print(`0 a1.
A1 0.
If 0 a1,
Where's the1 0?`.replace(/\d/g,n=>+n?' peck of pickled peppers':'Peter Piper picked'))
```
[Try it online!](https://tio.run/##Hcm9DoIwFAbQnae4WyEiP6uJEkc3NhcHmvZDKlBubhsTn76i48l56bcORhzHY2BnIevmZ3xSYnE@5kNDuq2ya0tNld1G@rHM7hMEKlCcsEc3VAJetEFeP2z9LP35cvCdIoaZaRuJnZkX2N3MkKBOqkeEUO92/hdWFUVKXw "JavaScript (SpiderMonkey) – Try It Online")
I would claim this answer is from [ovs](https://codegolf.stackexchange.com/users/64121/ovs), anyway, 19 bytes saved.
Thanks [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), saves 3 bytes.
[Answer]
# [Python 2](https://docs.python.org/2/), 115 bytes
```
a="Peter Piper picked"
b=" peck of pickled peppers"
print a,"a%s.\nA"%b+b,a+".\nIf",a,"a%s,\nWhere's the"%b+b,a+"?"
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9FWKSC1JLVIISCzAEgWZCZnp6YocSXZKikUpCZnK@SngcVyUlOA/AKgkmIlroKizLwShUQdpUTVYr2YPEcl1STtJJ1EbSUgxzNNSQcioxOTF56RWpSqXqxQkpEKV2Ov9P8/AA "Python 2 – Try It Online")
Prints multiple commas-separated strings to put spaces in between them.
---
# [Python 3](https://docs.python.org/3/), 115 bytes
```
print("1 a2.\nA2 1.\nIf 1 a2,\nWhere's the2 1?".translate({49:"Peter Piper picked",50:" peck of pickled peppers"}))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8lQIdFILybP0UjBEEh5pimABHRi8sIzUotS1YsVSjJSgVL2SnolRYl5xTmJJaka1SaWVkoBqSWpRQoBmQVAsiAzOTs1RUnH1MBKSaEgNTlbIT8NLJiTmgLkFwDVFCvVamr@/w8A "Python 3 – Try It Online")
Python 3's `translate` does the heavy lifting. Using non-printable characters with single-digit ASCII value should save two bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~64~~ ~~60~~ ~~58~~ 57 bytes
```
“¡ŀṪ]ṃ{yṁ“Ñ3$ṘW5Ḍż⁸¢Hŀ»j⁾ a,Ṛẋ2ż“³ḌM“¡FỊİg“ÑɲʋØƥþƈƘ}»FḊ”?
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDC482PNy5Kvbhzubqyoc7G4FChycaqzzcOSPc9OGOnqN7HjXuOLTI42jDod1Zjxr3KSTqPNw56@GubiOgDFD3ZqAaX7Axbg93dx3ZkA7Wf3LTqe7DM44tPbzvWMexGbWHdrs93NH1qGGu/f//AA "Jelly – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 99
* 4 bytes saved thanks to @manatwork.
```
echo "${P=Peter Piper picked} a${p= peck of pickled peppers}.
A$p $P.
If $P a$p,
Where's the$p $P?"
```
[Try it online!](https://tio.run/##HYpBCoAgFET3nuITQpvoBhIt27lrXTqiGPRJd9HZ7eNmhnnzzqPE1uDiTYN@rbGoeMgmluTkMvxHh37ZEMNlukOnF7xsFql8s1o1k7az2oKU2DypPeLBWKhG9HMZWvsB "Bash – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~99~~ 87 bytes
-12 bytes: turns out 2 substitutions are shorter which is basically the same as everyone else's solution (except Bubblegum?)
```
i1 a0.
A0 1.
If 1 a0,
Where's the0 1?Í0/ peck of pickled peppers
Í1/Peter Piper picked
```
[Try it online!](https://tio.run/##K/v/P9NQIdFAj8vRQMFQj8szTQHE1eEKz0gtSlUvVijJSAVK2Esf7jXQVyhITc5WyE9TKMhMzs5JTQHyCwpSi4q5Dvca6geklqQWKQRkAgXA8qkp//8DAA "V – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~120~~ ~~117~~ 116 bytes
```
a,b="Peter Piper picked"," peck of pickled peppers"
exit(f"{a} a{b}.\nA{b} {a}.\nIf {a} a{b},\nWhere's the{b} {a}?")
```
[Format strings](https://tio.run/##K6gsycjPM/7/P1EnyVYpILUktUghILMASBZkJmenpijpKCkUpCZnK@SngUVyUlOA/AKggmIlrtSKzBKNNKXqxFqFxOqkWr2YPEcgpQDkA5meaQowCZ2YvPCM1KJU9WKFkoxUqBJ7Jc3//wE "Python 3 – Try It Online") were shorter than [addition(129 bytes)](https://tio.run/##RYqxDoMwDER3vsLy4qJULJ1RxcjmrUuWKhglogpWyMLXp1EYWE7v7p6e2e/xVQqPyJIlAQetqcFtsmCnI4KK22Bf2/aTpXatylHPFGJ@sCH4klFDg41TAyDDrc7rhZeATxs/XpLQAdkL3uqb@lL@ "Python 3 – Try It Online") and a [join(140 bytes)](https://tio.run/##RYqxDsIwDER3vsLy4laKujBXiJHNGwNlQK2rhCLHSrPw9SFKB5bTu7tn3@yjnkvhEVmyJOBgNS3Mmyx4shHBZN4grm37yFK7VWWvZwqaO6LhHYN2D3YEL3LmaJj02gDIcau39cBDQDfp3UsS2iF7wb96oWffl/ID "Python 3 – Try It Online").
-3 thanks to Jo King,
-1 thanks to Jonathan Allen
[Answer]
# [Java (JDK)](http://jdk.java.net/), 123 bytes
```
v->"".format("%s a%s.%nA%2$s %1$s.%nIf %1$s a%2$s,%nWhere's the%2$s %1$s?","Peter Piper picked"," peck of pickled peppers")
```
[Try it online!](https://tio.run/##PY5BSwMxEIXv@yuG0OCubAN6rVa8CB6EQkEP4iFmkza72SQkk4Ui/e3rdC1eZua99zG8Xk5y3XfDbMcYEkJPWhS0TpjiFdrgxe2miuXbWQXKyZzhTVoPPxXA1c0okdYUbAcjZfUek/WHzy@Q6ZCbBQV4ub57eCeu/UO2YOBxntZbxoQJaZRYM55B8iy4f@b3qwz8bnURr2a5KCKz5f7jqJO@yYBH/Y89sZbtNOoEOxtpRqsG3ZEJUasBglkcpzvSkYDMmnmzdNufMupRhIIiUi@sjZAxulPti3NNc4HO1Xn@BQ "Java (JDK) – Try It Online")
[Answer]
# Twig, 105 bytes
This uses a simple replacement to fill in the gaps.
Twig's `replace()` filter allows you to define the values to replace as the keys of an hash.
Luckly, it also works with arrays, as they have numerical keys.
```
{{"0a1.
A1 0.
If 0 a1,
Where's the1 0?"|replace(["Peter Piper picked"," peck of pickled peppers"])|raw}}
```
The `|raw` is needed to avoid escaping, which turned `Where's` into `Where's`.
You can try it on <https://twigfiddle.com/phqpts>
---
Since this is compiled down to PHP, the equivalent for PHP would be:
```
<?php
$array = array("Peter Piper picked", " peck of pickled peppers");
$string = "0 a1.
A1 0.
If 0 a1,
Where's the1 0?";
echo str_replace(array_keys($array), $array, $string);
```
Which can be shortened significatively.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 104 bytes
```
/ a/=~$a="Peter Piper picked a peck of pickled peppers"
puts"#$a.
A#$' #$`.
If #$a,
Where's the#$' #$`?"
```
[Try it online!](https://tio.run/##LYmxCoAgFAB3v@KhgkvkF0Q0trW19qoXiUEPtaGlXzeJlju4C9d852wBbfNobORAiQIMjgvZLZ5WQGBaPJzbF45SmLj8KAVfKUqlsRad0gaUnmrRb8VYiXGnQCZC2ul/rcz5BQ "Ruby – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 86 bytes
```
/1/Peter Piper picked//2/ peck of pickled peppers/1 a2.
A2 1.
If 1 a2,
Where's the2 1?
```
[Try it online!](https://tio.run/##HYoxDoAgEAR7XnGdjfECHzCWdnTWBJZANJF4/B9Pm0lmduUKUiBjsGWPjod8bcpW44nE7Jga4kl3/tOFpN70IWwpuMVsjuxi9kyfzuYoeDAJ9QId1jFe "/// – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 123 bytes
```
f(){printf("%s a%s.\nA%2$s %1$s.\nIf %1$s a%2$s,\nWhere's the%2$s %1$s?","Peter Piper picked"," peck of pickled peppers");}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oCgzryRNQ0m1WCFRtVgvJs9R1UilWEHVUAXE8UwDs4BSQEGdmLzwjNSiVPVihZKMVLgyeyUdpYDUktQihYDMAiBZkJmcnZoCFFQoSE3OVshPA4vkpKYA@QVABcVKmta1/4G2KuQmZuZpaHJVc3ECXWLNVfsfAA "C (gcc) – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 166 bytes
```
import StdEnv,Text;f="peck of pickled";g="picked";u="peppers";p="Peter Piper";s=join" "[p,g,"a",f,u+".\nA",f,u,p,g+".\nIf",p,g,"a",f,u+",\nWhere's","the",f,u,p,g+"?"]
```
[Try it online!](https://tio.run/##VY69CsIwFIVfJdzFwasvUIoIOggOBQUHdQjpTY3NH0kq@vLGtC66fec7ZzhCE7fZuHbQxAxXNivjXUjskNqtfeCRnqmSNXgSPXOSeSV6TS1UXXGFRxzG2nsKESpfQ0OJAmtUEVDF@u6UBQZnjx0CB5Q4zGF5sesJsegp7iTg3wQv9nSjQLMICOlGP/MVXPMh8fKyZjG/hdS8i3mx2@fNy3KjxDc0mifpgvkA "Clean – Try It Online")
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~101~~ 100 bytes
```
s/^/0 a1.\nA1 0.\nIf 0 a1,\nWhere's the1 0?/
s/0/Peter Piper picked/g
s/1/ peck of pickled peppers/g
```
[Try it online!](https://tio.run/##HYqxDkBAEER7X7GdBnv3BaLU6TQiETeOkHOxfP9ZmpnMeyNwpQ9PSsIjG5psNYTGktFqF/pAMYR@xYVc6F6hquZM2HCHGxd1W9SM27zDsVdhmSLmnc7lpwec7qgnYZ/SCw "sed – Try It Online")
-1 byte thanks to @DigitalTrauma
[Answer]
# jq, 110 characters
(106 characters code + 4 characters command line options)
```
"1 a2.
A2 1.
If 1 a2,
Where's the2 1?"|gsub("1";"Peter Piper picked")|gsub("2";" peck of pickled peppers")
```
Sample run:
```
bash-4.4$ jq -nr '"1 a2.
A2 1.
If 1 a2,
Where'"'"'s the2 1?"|gsub("1";"Peter Piper picked")|gsub("2";" peck of pickled peppers")'
Peter Piper picked a peck of pickled peppers.
A peck of pickled peppers Peter Piper picked.
If Peter Piper picked a peck of pickled peppers,
Where's the peck of pickled peppers Peter Piper picked?
```
[Try it online!](https://tio.run/##yyr8/1/JUCHRSI/L0UjBUI/LM00BxNXhCs9ILUpVL1YoyUgFStgr1aQXlyZpKBkqWSsFpJakFikEZBYAyYLM5OzUFCVNqLQRUFqhIDU5WyE/DSyXk5oC5BcAlRYraf7//183rwgA "jq – Try It Online")
[Answer]
# SQL Server, 211
```
declare @a char(18)='Peter Piper picked'
declare @b char(24)=' peck of pickled peppers'
declare @c char=char(10)
print @a+' a'+@b+'.'+@c+'A'+@b+' '+@a+'.'+@c+'If '+@a+' a'+@b+','+@c+'Where''s the'+@b+' '+@a+'?'
```
[db<>fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=aa49cadbe030dbd774f61739617e7400)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~60~~ 56 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╣lF╤╨┴+Y╟W╪▄,○F«↑•L°T»`┼◄ü√}x
[Answer]
## Windows Batch, 179 bytes
```
4D534346000000009C00000000000000
2C000000000000000301010001000000
000000004200000001000100DF000000
000000000000544DB5682000612E6261
7400E59D45D15200DF00434B73484DCE
C85708482D492D5208C82C00920599C9
D9A9290A890A05A9C9D90AF96960811C
A048416A0150BE588F970BA2C911970A
2CC6C13579A69164990E4C5F78466A51
AA7AB14249462A09D6DA0300
extract %0 .bat
.bat
```
Self-extracting Cabinet file using Batch/CAB polyglot.
The blank line is needed for the batch file processor to find the actual batch code, but can be LF alone instead of CR/LF.
The Cabinet file is just a series of "@echo <string>" lines, and the '@' symbol suppresses the "echo" itself from being displayed.
[Answer]
# T-SQL, 137 bytes
```
SELECT p+a+k+'.
A'+k+' '+p+'.
If '+p+a+k+',
Where''s the'+k+' '+p+'?'
FROM(SELECT'Peter Piper picked'p,' a'a,' peck of pickled peppers'k)b
```
That last return before the `FROM` is for readability only, the rest are part of the string concatenation.
Different method than [SeanC's SQL solution](https://codegolf.stackexchange.com/a/174066/70172).
[Answer]
# [Kotlin](https://kotlinlang.org), 150 bytes
```
var s="Peter Piper picked"
var z=" peck of pickled peppers"
var v=s+" a"+z
var x=z+" "+s
print(v+".\n"+"A"+x+".\n"+"If "+v+",\n"+"Where's the "+x+"?")
```
[Try it online!](https://tio.run/##NY1BDoIwEEX3nGIyGyE1HsBYDUt3JC7cuGlggAYszbQSxHj2Wmvc/Myb/5I/TH7UJrQPA3elTa64c3somdXzcPGsTXcs4BVmxeAkVuSJodI2ptX1QA1m32qVCJbqAaY2/UdqItuouZ8wSycQFIo14SLXiChcZuOEz2eBu5tBgSWK5X@f22jEZpvo2hPTxoHvCZJ0wiK8wwc "Kotlin – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 85 bytes
```
1 a0.¶A0 1.¶If 1 a0,¶Where's the0 1?
1
Peter Piper picked
0
peck of pickled peppers
```
[Try it online!](https://tio.run/##K0otycxL/P@fy1Ah0UDv0DZHAwVDIOWZpgAS0Dm0LTwjtShVvVihJCMVKGXPZcgVkFqSWqQQkFkAJAsyk7NTU7gMuBQKUpOzFfLTwCI5qSlAfgFQQfH//wA "Retina 0.8.2 – Try It Online") Same idea as everyone else.
[Answer]
# [Red](http://www.red-lang.org), 116 bytes
```
prin rejoin[a:"Peter Piper picked"" a"b:" peck of pickled peppers"".^/A"b" "a".^/If "a" a"b",^/Where's the"b" "a"?"]
```
[Try it online!](https://tio.run/##LYuxCoNAEER/ZZnGJsTeJqRMJzYWonB6I54GXVb//7wLaYY3wxujjw1910e1sItxPcLeuQo1L5rUQVNqmDZ6QBzGCqKcNjnm3/ylT12TdQLPoXxjhMBl/MwZ8gePoWwXGotTroV/5YU@xhs "Red – Try It Online")
## Explanation:
The job is done by the `rejoin` funcion, which reduces and joins a block of values.
```
prin rejoin [ ; print the reduced (evaluated) and joined block
a: "Peter Piper picked" ; save the text to a
" a" ; literal " a"
b: " peck of pickled peppers" ; save the text to b
".^/A" ; literal newline followed by "A"
b ; " peck of pickled peppers"
" " ; literal " "
a ; "Peter Piper picked"
".^/If " ; literal ".^/If "
a ; "Peter Piper picked"
" a" ; literal " a"
b ; " peck of pickled peppers"
",^/Where's the" ; literal "," folowwed by a newline by "Where's the"
b ; " peck of pickled peppers"
" " ; literal " "
a ; "Peter Piper picked"
"?" ; literal "?"
]
```
[Answer]
# [J](http://jsoftware.com/), 121 bytes
```
echo('1 a2.',CR,'A2 1.',CR,'If 1 a2,',CR,'Where''s the2 1?')rplc('1';'Peter Piper picked';'2';' peck of pickled peppers')
```
[Try it online!](https://tio.run/##LUs9C4MwFPwrb7sGgmDWDqU4uUkX5xJPYhV8RP9/fFqHO@7zVwpjWh@o5Rsq@Obj8Q5S37Id5Sz83/WJmcAme6JtXnBZl2hfPNFxZ5ZuUmOd4szBwmAQZZxlHa904WBebbTBlXIA "J – Try It Online")
[Answer]
# [PHP](https://php.net/), 107 bytes
```
<?=($a="Peter Piper picked")." a".($b=" peck of pickled peppers").".
A$b $a.
If $a a$b,
Where's the$b $a?";
```
[Try it online!](https://tio.run/##HYpBCoAgEEX3nmIYBioIL1ASLdu5a601oRg0lPc3a/Mfn/ckSCnjZFpyBi1nvsFGqStxS7xjpxEc6pa8QRDeElzH707e65eaPl@k1UweyGm1HBXgyPdqDXxz80AO/MsJh1Je "PHP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~78~~ ~~76~~ ~~74~~ 72 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
’0 a1.
A10.
If0 a1,
W€Î's €€10?’TS.•1~¼ ¿•“±æ€‚ ÿÇì“'p0ǝ„íδŒ™„r¾Ð«‚ðì:¦
```
[Try it online.](https://tio.run/##yy9OTMpM/f//UcNMA4VEQz0uR0MDPS7PNBBHhyv8UdOaw33qxQpAGogMDeyB6kKC9R41LDKsO7RH4dB@IOtRw5xDGw8vAylpmKVweP/h9sNA1hz1AoPjcx81zDu89nDfoS1HJz1qAaqcV3Ro3@EJh1YDVR7ecHiN1aFl//8DAA)
**Explanation:**
```
’0 a1.
A10.
If0 a1,
W€Î's €€10?’ # String "0 a1.\nA10.\nIf0 a1,\nWhere's the10?"
TS # 10 to digits: ["1","0"]
.•1~¼ ¿• # String "pickled"
“±æ€‚ ÿÇì“ # String "neck of ÿ pepper", where the "ÿ" will
# automatically be replaced with the top value of the stack
'p0ǝ # Replace the character at index 0 with a "p":
# "peck of pickled pepper"
„íδŒ # String "peter pipe"
™ # Titlecased: "Peter Pipe"
„r¾Ð # String "r picked"
« # Merge them together: "Peter Piper pickled"
‚ # Pair them together:
# ["peck of pickled pepper","Peter Piper pickled"]
ðì # Prepend a space before each:
# [" peck of pickled pepper"," Peter Piper pickled"]
: # Replace the ["1","0"] with this list of strings
¦ # Remove the leading space (and output implicitly)
```
[See this 05AB1E tip of mine](https://codegolf.stackexchange.com/a/166851/52210) to understand why:
* `’0 a1.\nA10.\nIf0 a1,\nW€Î's €€10?’` is `"0 a1.\nA10.\nIf0 a1,\nWhere's the10?"`
* `.•1~¼ ¿•` is `"pickled"`
* `“±æ€‚ ÿÇì“` is `"neck of ÿ pepper"`
* `„íδŒ` is `"peter pipe"`
* `„r¾Ð` is `"r picked"`
[Answer]
# [Haskell](https://www.haskell.org/), 132 bytes
```
g x y=x++y++x
p=g"Peter Piper picked"
q=g" peck of pickled peppers"
a=g" ".("a"++).q
f=p(a".\nA"++p".\nIf "++a",\nWhere's the")++"?"
```
[Try it online!](https://tio.run/##HYrBCoMwEETv@YplL1W2@Aeh9FjoQfDQi5egGyPadE1S0K9PYy/DmzfjTFx4XXOeYIdD70QH0a5ET9hy4gDtLCVlHhYeUW3Fg/CwwMf@5cpj6VI@EZU5V2wqNEhUN5uyWiqDTe/vRcgJDwsFDV57/3Ic@BIhOcaaCG@Y32b2oEG@qUvh6cHmHw "Haskell – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~123~~ ~~118~~ 116 bytes
```
v=>@"0 a1.
A1 0.
If 0 a1,
Where's the1 0?".Replace("0","Peter Piper picked").Replace("1"," peck of pickled peppers")
```
[Try it online!](https://tio.run/##XY9BSwMxEIXv8yuGXNzAGnbPa6tSUASFRQ89h@ysHRqTmEkLUvrb1yiI4uXBx/sO7zm5dDHTchAOr/jyIYXeBvhLZhO9J1c4BjH3FCiz@2c8cngfwHkrguMJpNjCDu8OwV1xKK2UXOU1zitcjqv1jerQ9gZue@wMPMz4hS1sd5TpQrDsqBbXyjxT8tZRozrVqpEKZRw51Uzs9jQp/Wv01cBEbo9x/q49TZVTtUXpZYCfTcfIEz5ZDo2GE2zqpejJbDMXqieomZte6wHOcF4@AQ "C# (.NET Core) – Try It Online")
Inspired by @Olivier Grégoire's [java answer](https://codegolf.stackexchange.com/questions/173965/text-compression/173980#173980)
5 bytes saved by @sebbs
[Answer]
# [PHP](https://php.net/), 102 bytes
Basically just change the repeater words or sentences with numbers, and then apply **php-strtr**
```
<?=strtr("0 a 1.
A 1 0.
If 0 a 1,
Where's the 1 0?",["Peter Piper picked","peck of pickled peppers"]);
```
[Try it online!](https://tio.run/##HcmxCoQwFETRPl8xvEaFIFqvIpZ2dhaLxaIjEQUfSf4/uja3OFedptR0bYg@@lwq/FCXpkeNqjTDhhesmRw9s4Do@F@d2K@MjPQYd32q@3JwFSvK5cC1vXByhVKfH2QuPind "PHP – Try It Online")
Or
# [PHP](https://php.net/), 144 bytes
```
<?=strtr("0 1 25 a 3 of 2l5 4.
A 3 of 2l5 4 0 1 25.
If 0 1 25 a 3 of 2l5 4,
Where's the 3 of 2l5 4 0 1 25?",[Peter,Piper,pick,peck,peppers,ed]);
```
[Try it online!](https://tio.run/##K8go@P/fxt62uKSopEhDyUDBUMHIVCFRwVghP03BKMdUwUSPyxGJpwBRocflmaaARbEOV3hGalGqerFCSUYqpjZ7JZ3ogNSS1CKdgMwCIFmQmZytU5AKJgqAAsU6qSmxmtb//wMA "PHP – Try It Online")
]
|
[Question]
[
## Goal
You are given an integer `n` (`n > 1`). You must output how many permutations of the integers `1` to `n` there are which start at `1`, end at `n`, and don't have two consecutive integers which differ by 1.
Alternatively, if you take the complete graph `K_n` and remove the edges of the path `1-2-3-...-n` you must count the Hamiltonian paths from `1` to `n` in the remaining graph.
The examples will use `f(n)` for a function that takes in `n` and outputs the number of valid permutations, but your submission can be a function or a program.
---
## Examples
For `n = 6`, a possible solution is `1-3-5-2-4-6`
However, `1-3-5-2-6-4` is not a valid solution since it does not end with `6`.
In fact, for `n = 6`, there are only 2 solutions (`1-4-2-5-3-6` is the other one).
Hence `f(6) = 2`.
---
For `n = 4` the only permutations which start in `1` and end in `4` are `1-2-3-4` and `1-3-2-4`. In both of them the `2` is adjacent to the `3`, giving consecutive integers which differ by 1. Therefore `f(4) = 0`.
---
## Test cases
```
f(6) = 2
f(4) = 0
f(8) = 68
f(13) = 4462848
```
---
## Winning criterion
This is code-golf, the shortest answer wins.
[Answer]
# Mathematica, 58 bytes, polynomial(*n*) time
```
Abs[Sum[(k-1)Hypergeometric2F1[k,k-#,2,2](#-k)!,{k,#}]-1]&
```
### How it works
Rather than iterating over permutations with brute force, we use the [inclusion–exclusion principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle) to count them combinatorially.
Let S be the set of all permutations of [1, …, n] with σ1 = 1, σ*n* = *n*, and let S*i* be the set of permutations σ ∈ S such that |σ*i* − σ*i* + 1| = 1. Then the count we are looking for is
|S| − |S1 ∪ ⋯ ∪ S*n* − 1| = ∑2 ≤ *k* ≤ *n* + 1; 1 ≤ *i*2 < ⋯ < *i**k* − 1 < *n* (−1)k − 2|S*i*2 ∩ ⋯ ∩ S*i**k* − 1|.
Now, |S*i*2 ∩ ⋯ ∩ S*i**k* − 1| only depends on *k* and on the number *j* of runs of consecutive indices in [*i*1, *i*2, …, *i**k* − 1, *i**k*] where for convenience we fix *i*1 = 0 and *i**k* = *n*. Specifically,
|S*i*2 ∩ ⋯ ∩ S*i**k* − 1| = 2*j* − 2(*n* − *k*)!, for 2 ≤ *j* ≤ *k* ≤ *n*,
|S*i*2 ∩ ⋯ ∩ S*i**k* − 1| = 1, for *j* = 1, *k* = *n* + 1.
The number of such index sets [*i*1, *i*2, …, *i**k* − 1, *i**k*] with *j* runs is
(*k* − 1C*j* − 1)(*n* − *k*C*j* − 2), for 2 ≤ *j* ≤ *k* ≤ *n*,
1, for *j* = 1, *k* = *n* + 1.
The result is then
(−1)*n* − 1 + ∑2 ≤ *k* ≤ *n* ∑2 ≤ *j* ≤ *k* (−1)*k* − 2(*k* − 1C*j* − 1)(*n* − *k*C*j* − 2)2*j* − 2(*n* − *k*)!
The inner sum over *j* can be written using the [hypergeometric 2F1 function](https://en.wikipedia.org/wiki/Hypergeometric_function):
(−1)*n* − 1 + ∑2 ≤ *k* ≤ *n* (−1)*k*(*k* − 1)2F1(2 − *k*, *k* − *n*; 2; 2)(*n* − *k*)!
to which we apply a Pfaff transformation that lets us golf away the powers of −1 using an absolute value:
(−1)*n* − 1 + ∑2 ≤ *k* ≤ *n* (−1)*n*(*k* − 1)2F1(*k*, *k* − *n*; 2; 2)(*n* − *k*)!
= |−1 + ∑1 ≤ *k* ≤ *n* (*k* − 1)2F1(*k*, *k* − *n*; 2; 2)(*n* − *k*)!|.
### Demo
```
In[1]:= Table[Abs[Sum[(k-1)Hypergeometric2F1[k,k-#,2,2](#-k)!,{k,#}]-1]&[n],{n,50}]
Out[1]= {1, 0, 0, 0, 0, 2, 10, 68, 500, 4174, 38774, 397584, 4462848,
> 54455754, 717909202, 10171232060, 154142811052, 2488421201446,
> 42636471916622, 772807552752712, 14774586965277816, 297138592463202402,
> 6271277634164008170, 138596853553771517492, 3200958202120445923684,
> 77114612783976599209598, 1934583996316791634828454,
> 50460687385591722097602304, 1366482059862153751146376304,
> 38366771565392871446940748410, 1115482364570332601576605376898,
> 33544252621178275692411892779180, 1042188051349139920383738392594332,
> 33419576037745472521641814354312790,
> 1105004411146009553865786545464526206,
> 37639281863619947475378460886135133496,
> 1319658179153254337635342434408766065896,
> 47585390139805782930448514259179162696722,
> 1763380871412273296449902785237054760438426,
> 67106516021125545469475040472412706780911268,
> 2620784212531087457316728120883870079549134420,
> 104969402113244439880057492782663678669089779118,
> 4309132147486627708154774750891684285077633835734,
> 181199144276064794296827392186304334716629346180848,
> 7800407552443042507640613928796820288452902805286368,
> 343589595090843265591418718266306051705639884996218154,
> 15477521503994968035062094274002250590013877419466108978,
> 712669883315580566495978374316773450341097231239406211100,
> 33527174671849317156037438120623503416356879769273672584588,
> 1610762789255012501855846297689494046193178343355755998487686}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
qtq:Y@0&Yc!d|qAs
```
[Try it online!](https://tio.run/##y00syfn/v7Ck0CrSwUAtMlkxpabQsfj/fwsA "MATL – Try It Online")
For inputs exceeding `12` it runs out of memory.
### Explanation
```
q % Implicitly input n. Push n-1
tq % Duplicate and subtract 1: pushes n-2
: % Range [1 2 ... n-2]
Y@ % Matrix with all permutations, each in a row
0 % Push 0
&Yc % Append n-1 and predend 0 to each row
! % Tranpose
d % Consecutive differences along each column
| % Absolute value
q % Subtract 1
A % All: true if all values in each column are non-zero
s % Sum. Implicitly display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṖḊŒ!ð1;;⁹IỊṀðÐḟL
```
A monadic link.
**[Try it online!](https://tio.run/##ASsA1P9qZWxsef//4bmW4biKxZIhw7AxOzvigblJ4buK4bmAw7DDkOG4n0z///84 "Jelly – Try It Online")**
### How?
```
ṖḊŒ!ð1;;⁹IỊṀðÐḟL - Link: number n
Ṗ - pop (implicit range build) -> [1,n-1]
Ḋ - dequeue -> [2,n-1]
Œ! - all permutations of [2,n-1]
ð ðÐḟ - filter discard those entries for which this is truthy:
1; - 1 concatenated with the entry
;⁹ - ...concatenated with right (n)
I - incremental differences
Ị - is insignificant (absolute value <=1)
Ṁ - maximum
L - length (the number of valid arrangements)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~19~~ 18 bytes
```
o2 á è_pU äÉ m²e>1
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=bzIg4SDoX3BVIOTJIG2yZT4x&input=OA==) I would not recommend testing on anything larger than `10`.
### Explanation
```
o2 á è_ pU äÉ m² e>1
o2 á èZ{ZpU ä-1 mp2 e>1}
: Implicit: U = input integer
o2 : Create the range [2..U-1].
á : Generate all permutations of this range.
èZ{ } : Check how many permutations Z return a truthy value:
ZpU : Push U to the end of Z.
ä-1 : Push 1 to the beginning of Z, then take the difference
: of each pair of items.
m : Map each item X to
p2 : X ** 2. This gives a number greater than 1 unless the
: item is 1 or -1.
e>1 : Return whether every item in this list is greater than 1.
: This returns `true` iff the permutation contains no
: consecutive pairs of numbers.
: Implicit: output result of last expression
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
L¦¨œʒ¹1Š)˜¥Ä1å_}g
```
[Try it online!](https://tio.run/##ASYA2f8wNWFiMWX//0zCpsKoxZPKksK5McWgKcucwqXDhDHDpV99Z///OA "05AB1E – Try It Online")
[Answer]
## Haskell, ~~76~~ 65 bytes
Saved 11 bytes thanks to @xnor.
Using the result for `Q_rec` on page 7 of @ChristiaanWesterbeek's find, we get
```
f 1=1
f n|n<6=0
f n=sum$zipWith((*).f)[n-5..][n-4,1,10-2*n,4,n-2]
```
I don't understand how their next result `ha` relates to this, but after speeding up (first by memoization, see earlier versions, then as below) I get their numbers.
While the above is okay for `n=20`, it is essentialy an example how not to do recursion. Here is a faster version (only for `n>=6`) that also would only need constant memory - if only the numbers didn't keep increasing...
```
f n=last$foldl(#)[1,0,0,0,0][6..n]
l#n=tail l++[sum$zipWith(*)l[n-4,1,10-2*n,4,n-2]]
```
That gives
```
Prelude> f 50
1610762789255012501855846297689494046193178343355755998487686
Prelude> f 500
659178618863924802757920269977240274180092211041657762693634630044383805576666007245903670780603497370173231423527767109899936008034229541700392144282505597945561328426013937966521561345817045884498867592832897938083071843810602104434376305964577943025310184523643816782047883794585616331928324460394146825636085453532404319881264974005968087265587062691285454120911586459406436421191277596121471930913837355151842093002557978076653884610826296845041929616496533544124347765641367732716560025553179112645454078955409181466212732427071306363820080109636358537270466838558068527692374178581063316309789026101221004745226182671038004326069705775312654329754698423385241664984156235692539255677944294995403233446243315371404887473868003155621849544566385172835597260848972758443874423271017007843907015007416644383573987606586308556317833384896267539628278571497402655322562624217658332870157802254043614726316296058329670971054977099155788604175817828380564156329839201579006169173002756295957371639199917376529472990059986681882194726437566769717959443857298155265292535858523609764515938314672724480762724541633037484152303637096
```
It's no problem to also get `f 5000` but I don't want to paste the result...
---
BTW, it's possible to not use fancy math and still not use (ultra) brute force. First, instead of looking at all permutations, look at partial permutations and only extend them when they are not already invalid. It's no use to look at all permutations starting with `1 6 5`. Second, some partial permutations like `1 3 5 7` and `1 5 3 7` have exactly the same valid continuations, so handle them together. Using these ideas, I could compute the values up to `n=16` in 0.3s.
[Answer]
# Python, 125 bytes
```
from itertools import*
lambda n:sum(p[-1]-p[0]==n-1and all(~-abs(x-y)for x,y in zip(p,p[1:]))for p in permutations(range(n)))
```
[Answer]
# Mathematica, 66 bytes
```
Count[Permutations@Range@#,x:{1,__,#}/;FreeQ[Differences@x,1|-1]]&
```
## Explanation
`Function` with first argument `#`.
```
Count[ (* Count the number of *)
Permutations@ (* permutations of *)
Range@#, (* the list {1, ..., #} *)
x:{1,__,#} (* of the form {1, __, #} *)
/; (* such that *)
Differences@x, (* the list of differences of consecutive elements *)
FreeQ[ (* is free of elements of the form *)
1|-1 (* 1 or -1 *)
]]&
```
[Answer]
# Javascript (ES6), ~~100~~ ~~74~~ ~~72~~ 60 bytes
```
f=n=>n--<6?!n|0:f(n)*--n+4*f(n--)-2*f(n--)*--n+f(n)*++n+f(n)
```
Below is the version before the golf-mastery of @PeterTaylor
```
f=n=>n<6?n==1|0:(n-4)*f(n-5)+f(n-4)-2*(n-5)*f(n-3)+4*f(n-2)+(n-2)*f(n-1)
```
Thanks to the answer from @ChristianSievers that managed to draft a Haskell solution from a [paper](http://algo.inria.fr/libraries/autocomb/graphs99.ps) that I found after googling '0, 2, 10, 68, 500, 4174, 38774, 397584', here's a Javascript version that does not permutate too.
Usage
```
for (i=1; i<=20; i++) {
console.log(i, f(i))
}
1 1
2 0
3 0
4 0
5 0
6 2
7 10
8 68
9 500
10 4174
11 38774
12 397584
13 4462848
14 54455754
15 717909202
16 10171232060
17 154142811052
18 2488421201446
19 42636471916622
20 772807552752712
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes
```
{⟦₁pLh1&~tLs₂ᶠ{-ȧ>1}ᵐ}ᶜ|∧0
```
[Try it online!](https://tio.run/##AToAxf9icmFjaHlsb2cy//974p@m4oKBcExoMSZ@dExz4oKC4bagey3Ipz4xfeG1kH3htpx84oinMP//OP9a "Brachylog – Try It Online")
### Explanation
```
{ }ᶜ Output = count the number of outputs of:
⟦₁pL L is a permutation of [1, …, Input]
Lh1 The head of L is 1
&~tL The tail of L is the Input
Ls₂ᶠ Find all sublists of length 2 of L
{ }ᵐ Map on each sublist:
-ȧ>1 The elements are separated by strictly more than 1
| Else (no outputs to the count)
∧0 Output = 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~109~~ ~~107~~ 102 bytes
```
q=lambda s,x,n:sum(q(s-{v},v,n)for v in s if(v-x)**2>1)if s else x<n;f=lambda n:q({*range(2,n)},1,n-1)
```
[Try it online!](https://tio.run/##NcxLDoIwEAbgq8yOGTI1Fl2hcpcaqTaB4VFsME3PXiHG7f/4xs/yGuSU83TrTH9/GPC8stT@3eOEXsWQOLCQHWYI4AQ8OItBrVSWVaPJ2S1pO9/CepWL/SNSTxjL2cizxWq7J9YsSlPeHbc7v@7M@kj1ODtZsIgJVAMxFYdt1ZsFHYNFR0T5Cw "Python 3 – Try It Online")
Removed four bytes by not trying to one-line the function (as suggested by @shooqie) and another byte by replacing `abs` with a square.
(Requires Python 3.5+)
[Answer]
# [Python 2](https://docs.python.org/2/), 136 bytes
-10 bytes thanks to @ovs.
```
lambda n,r=range:sum(x[0]<1and~-n==x[-1]and 2+~any(abs(x[i]-x[i+1])<2for i in r(n-1))for x in permutations(r(n)))
from itertools import*
```
[Try it online!](https://tio.run/##PYxBCsIwEEX3PcXsmthGbBERabxIzSKlrQ6YSZmmUBG9ekw3bj48/uNNr/DwVMdR3@LTuq63QCVrtnQfLvPixNoeTFNZ6r@KtF5bVZkEUBdfSy9huzkZaFSaojKyqUfPgIAELEhVUm68bjwN7JZgA3qaRTqllNnI3gGGgYP3zxnQTZ7DLv4b7bE8lWdzyQAmRgqQvz@grvD@5PskORsEljAKlDL@AA "Python 2 – Try It Online")
[Answer]
# Mathematica, 134 bytes
```
(s=Permutations@Range[2,#-1];g=Table[Join[Prepend[s[[i]],1],{#}],{i,Length@s}];Length@Select[Union@*Abs@*Differences/@g,FreeQ[#,1]&])&
```
test cases n: 2 to 12
>
> {0, 0, 0, 0, 2, 10, 68, 500, 4174, 38774, 397584}
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 105 bytes
```
lambda n:reduce(lambda a,i:a+[i*a[-5]+a[-4]+2*(1-i)*a[-3]+4*a[-2]+(i+2)*a[-1]],range(2,n),[0,1]+4*[0])[n]
```
[Try it online!](https://tio.run/##LYpBDoIwEEWvMmHV0sHQihsSvEidRRXQSWQgDS4M4ewV1M1/@S9ves@PUVzqm0t6huHaBpA6du3r1qn/D8h1MJ7z4IsTmW0rMi5XtmC9uyOZaqcjo9i4r7NEGIPcO@VQNPoS7V75krQXSv0YgYEFfo1FZ3UNU2SZIVtWaM6wrNlhy4YwK0boFWudPg "Python 2 – Try It Online")
This is based on [Philippe Flajolet's paper](http://algo.inria.fr/libraries/autocomb/graphs99.ps) discovered by [@Christiaan Westerbeek](https://codegolf.stackexchange.com/users/58434/christiaan-westerbeek); it's much faster and two bytes shorter than my [Python 3 solution](https://codegolf.stackexchange.com/a/130059/25319) which enumerates the possible permutations. (In Python 3, `reduce` has annoyingly been moved to `functools`.)
There is a much shorter version using numpy's dot product, but that overflows quite rapidly and requires numpy to have been imported. But for what it's worth:
```
lambda n:reduce(lambda a,i:a+[dot([i,1,2-2*i,4,i+2],a[-5:])],range(2,n),[0,1]+4*[0])[n]
```
]
|
[Question]
[
### Introduction
Let's say that **S1** = `a...b` and **S2** = `..c..`. If we place them on top of each other, we get:
```
a...b
..c..
```
We merge both strings, with the `.` as the liquid character (which can overlapped). We get this:
```
a.c.b
```
If one of the string is longer than the other, we just apply the same algorithm:
```
a.....b
..c..
becomes:
a.c...b
```
and
```
a.....b
..c.......
becomes:
a.c...b...
```
If two characters collide, we just use the bottom character, e.g.
```
a..b
...c
becomes:
a..c
```
### The Task
Given two non-empty strings, output the **merged** string. **Note**, you can assume that the input only contains **periods** and **lowercase letters** (or uppercase letters if that is more convenient).
### Test cases
```
Input Output
a....b ..c... a.c..b
aaaaaa bbbbbb bbbbbb
ab.ab. b.b.b. bbbab.
a.......b c c.......b
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
## CJam, 9 bytes
```
leul.e>el
```
[Test it here.](http://cjam.aditsu.net/#code=leul.e%3Eel&input=ab.ab.%0Ab.b.b.c)
### Explanation
Makes use of the fact that `'.' < upper case letters < lower case letters`. This way, when taking the element-wise maximum between two strings, any letter overrides a `.`, but we can make a letter from the second input override a letter from the first if we upper case the first. Confusing? Here's one of the test cases as an example:
```
ab.ab.
b.b.b.
```
Convert first to upper case:
```
AB.AB.
b.b.b.
```
Take the element-wise maximum:
```
bBbAb.
```
Convert back to lower case:
```
bbbab.
```
And here is how the code does that:
```
l e# Read first line.
eu e# Convert to upper case.
l e# Read second line.
.e> e# Take element-wise maximum. If the lengths are different, the additional elements
e# from the longer list are just appended.
el e# Convert back to lower case.
```
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Œu»Œl
```
Input via command-line arguments.
[Try it online!](http://jelly.tryitonline.net/#code=xZJ1wrvFkmw&input=&args=YWIuYWIu+Yi5iLmIuYw)
### Explanation
This is a direct port of [my CJam answer](https://codegolf.stackexchange.com/a/74810/8478) (see that for an explanation why this works):
```
Œu # Convert first argument to upper case.
» # Element-wise maximum between both strings.
Œl # Convert result back to lower case.
```
[Answer]
# Javascript ES6, ~~52~~ 55 chars
```
(a,b)=>b.replace(/\./g,(m,i)=>a[i]||m)+a.slice(b.length)
```
Test
```
f=(a,b)=>b.replace(/\./g,(m,i)=>a[i]||m)+a.slice(b.length)
;`
a....b ..c... a.c..b
aaaaaa bbbbbb bbbbbb
ab.ab. b.b.b. bbbab.
a.......b c c.......b
c a....b a....b
`.split('\n').filter(Boolean).map(s=>s.split(/\s+/)).every(a=>f(a[0],a[1])==a[2])
```
[Answer]
# Pyth, 11
```
smenD\.d.TQ
```
[Try it online](http://pyth.herokuapp.com/?code=smenD%5C.d.TQ&input=%22a...d.b%22%2C%22b.c..%22&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=smenD%5C.d.TQ&input=%22a...d.b%22%2C%22b.c..%22&test_suite=1&test_suite_input=%22a....b%22%2C%22..c...%22%0A%22aaaaaa%22%2C%22bbbbbb%22%0A%22ab.ab.%22%2C%22b.b.b.%22%0A%22a.......b%22%2C%22c%22&debug=0)
[Answer]
## Seriously, 10 bytes
```
,û,Z`M`MΣù
```
[Try it online!](http://seriously.tryitonline.net/#code=LMO7LFpgTWBNzqPDuQ&input=J2FiLmFiLicKJ2IuYi5iLic)
Uses the same strategy as [Martin's CJam answer](https://codegolf.stackexchange.com/a/74810/45941)
Explanation:
```
,û,Z`M`MΣù
,û get first string, uppercase
,Z get second string, zip with first string
`M`M map maximum
Σù join and uppercase
```
[Answer]
# Octave, 50 bytes
```
function c=m(a,b)c=b;c(a>0)=a;i=b>46;c(i)=b(i);end
```
[Answer]
## Haskell, ~~43~~ 42 bytes
```
(a:b)#(c:d)|c<'a'=a:b#d|1<2=c:b#d
a#b=a++b
```
Usage example: `"ab.ab." # "b.b.b."` -> `"bbbab."`.
How it works:
* if both list are non-empty, pick the the head of the 1st list if the head of the 2nd list is `"."`, else pick the head of the second list. Append a recursive call with the tails of the lists.
* if at least one list is empty, append both lists.
Edit: @Lynn saved a byte. Thanks!
[Answer]
# Python 2, 47 bytes
```
lambda s,t:`map(max,s.upper(),t)`[2::5].lower()
```
[Answer]
# Julia, 101 bytes
```
f(s,t,r=i->rpad(i,max((n=endof)(s),n(t)),"."))=join([min(a,b)<90?max(a,b):b for(a,b)=zip(r(s),r(t))])
```
This is a function that accepts two strings and returns a string.
We compute `m` as the maximum length of the two inputs, then define a function `r` that right pads its input with `.`s to length `m` and store that as a function argument. We then `zip` the right padded inputs and check the minimum (as defined by the ASCII code) of each pair. If it's a `.`, we use whichever character has the bigger code, otherwise we use whichever came from the second input. The resulting array is `join`ed into a string and returned.
[Answer]
# C, ~~106~~ 89 bytes
```
i,j,k;f(s,z)char*s,*z;{for(i=0,j=k=1;j|k;i++)putchar((k=k?z[i]:0)>46|!(j=j?s[i]:0)?k:j);}
```
Test live on [**ideone**](http://ideone.com/qeMuFK).
[Answer]
# [Retina](http://github.com/mbuettner/retina), 55
```
$
+`(.?(\S* )(\w)|(\S)(\S* ).?)(\S* .*)
$2$5$6$3$4
```
Line 5 is a single space. Line 6 is an empty line (with no trailing newline).
[Try it online.](http://retina.tryitonline.net/#code=JAogCitgKC4_KFxTKiApKFx3KXwoXFMpKFxTKiApLj8pKFxTKiAuKikKJDIkNSQ2JDMkNAogCg&input=YS4uLi4uLi5iIGM)
I started this one in GNU sed, (with the -r option). Straightforward port to Retina once I got the regexes figured out. The sed version is:
```
s/$/ /
:
s/(.?(\S* )(\w)|(\S)(\S* ).?)(\S* .*)/\2\5\6\3\4/
t
s/ *//
```
[Answer]
# Python 2, 70 bytes
```
lambda x,y:"".join([k if k!="."and k else j for j,k in map(None,x,y)])
```
[Try it here!](https://repl.it/BtHT/3)
First we create zip both strings into one list. If the second string is longer than the first, it is padded with `None` (`map(None,x,y)` does that).
Then we iterate over this list with `j` being the character from the first string and `k` the one from the second string. We choose `k` if it's not a dot and otherwise `j`.
This could be 61 bytes if I could output the result as list of characters instead of a string.
[Answer]
# Perl, 48 + 3 = 51 bytes
```
s/\./substr($^I,$.=pos,1)||$&/ge;$_.=substr$^I,$.
```
Bah cannot find a shorter solution. (Same approach as @Qwertiy's JavaScript's answer).
Requires `-pl` and takes input from `stdin` and `-i`
```
$ perl -i'a...ce' -ple's/\./substr($^I,$.=pos,1)||$&/ge;$_.=substr$^I,$.' <<< '..b.d..f'
a.b.de..f
```
[Answer]
# PHP>=7.1, 58 Bytes
```
for([,$x,$y]=$argv;~$c=$y[$i++];)$c<_?:$x[$i-1]=$c;echo$x;
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/e1e60f860f4e7a5cea314496f5abfb3f7c09a3c3)
[Answer]
# q/kdb+, ~~43~~ 40 bytes
**Solution:**
```
lower{l:max(#:)each(x;y);upper[l$x]|l$y}
```
**Example:**
```
q)lower{l:max(#:)each(x;y);upper[l$x]|l$y}["a..b..";"...c"]
"a..c.."
```
**Explanation:**
```
(#:) // k equivalent of count
max (#:) each(x;y) // takes each string, count the length, return maximum
l$x // whites-space pad string x to length l
| // take the maximum (per Martin's strategy)
upper[...] // convert padded string 1 to uppercase
lower{...} // convert result of function to lowercase
```
**Notes:**
I'm taking taking advantage of *"Given two non-empty **strings**"* and assuming that inputs are strings. In kdb `"c"` is an atom, `(),"c"` is a string, otherwise need to add 6 bytes to the score, as we cannot use `$` to pad an atom...
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~86~~ 76 bytes
*-10 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
f(x,y)char*x,*y;{for(;*x|*y;putchar(0[y=*y?y:x]-46?*y:*x),x++,y++)x=*x?x:y;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU9RasMwDP22T6EFBo7jmBTGKAkhF9gNujIcs6yBLS1JyuR1vcdgP_npoXqbyV4yJsu8Z_np2fq-2KcXa6fpchybdH19aAQqF9ud6SUq6YpTs-9FIfGT-OE4-guRbVwpXeVy3KZ395V0ucRYYZIolyQxlhIrzF1xnj2_2m6EN9N2IoYTZ94CcLPKsq0CN-NHwIIzzt537esziMGarhHR7QAhIwVIclLGcFNCugpe7NCTeZA9jsv-JyVD5icCFygNMIgo8vzM-Py_6dobTVGD1pYQjIeamxBQh5iBm1pTQq398kU68dAeHCzYhc_VxVX_OVOj1r9P_wA)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
f=([a,...b],[c,...d])=>a+c?(c>'.'?c:a||c)+f(b,d):d
```
[Try it online!](https://tio.run/##RY9BDoIwEEX3PUV3tAEHdakpJF6jkjgdwGAqJZS48u5YKOprk/n582eaPvCFnsZumHa9q5t5bpXQmAGAqTJNi6grqQpMqRRUJJCUdML3m2TaCpPV8lTP5xtDWCY4AIXKV3DRhuEKNyuxEzVDA@FyA8v5dYIVt60LiW/Q12LEt8f@RIPdwA@2m0Ry7RMJbWenZhQX52yDvYQnDsKrwm@h/OrTXEYbVUGu9yEI1t1FK1Dvqwz1IfxcoT5WUrL5Aw "JavaScript (Node.js) – Try It Online")
]
|
[Question]
[
Given a strictly positive integer, `N`, produce an output satisfying the following:
* Produce an array of length N.
* Every string (i.e. "word") in the array is of length N.
* Every letter in the word is unique.
* Every first letter of the words are unique between each other.
* The remaining items of each word are equal to each other.
## Example output
For an input of e.g. `3`:
```
cba
dba
eba
```
## Specification
* Trailing whitespace is totally allowed.
* The "letters" don't have to be from the lowercase alphabet, as long as they aren't whitespace.
* The maximum `N` you need to support is 13, since there are 26 letters in the lowercase alphabet.
* The separator of your array can be anything, as long as you will never involve that character for every possible input from 1 to 13. You can also just output a literal array.
* Letters have to be 1 character long.
* Letters are case-sensitive, e.g. `a` and `A` can appear on the same line.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
V>QG+N<Gt
```
[Try it online!](https://tio.run/##K6gsyfj/P8wu0F3bz8a95P9/UwA "Pyth – Try It Online")
* `V>QG` For each letter in the last `Q` (the input) elements of the lowercase alphabet:
* `+N>Gt` Append that letter to the first `Q-1` elements of the lowercase alphabet
For `Q=13`, the output looks like this:
```
nabcdefghijkl
oabcdefghijkl
pabcdefghijkl
qabcdefghijkl
rabcdefghijkl
sabcdefghijkl
tabcdefghijkl
uabcdefghijkl
vabcdefghijkl
wabcdefghijkl
xabcdefghijkl
yabcdefghijkl
zabcdefghijkl
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
NθUOθ⮌β↓…βθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLPyknPy9do1BHISi1LLWoOFUjSRMoHFCUmVeiYeWSX56no@BcmZyT6pyRX6CRpKNQCJT@/9/4v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `N`.
```
UOθ⮌β
```
Print a square of size `N` filled with the reversed lowercase alphabet.
```
↓…βθ
```
Print the first `N` lowercase letters downwards.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 58 bytes
```
i,j;f(n){for(i=n;i;)putchar(j++?j>n?j=!i--,10:j+63:i+77);}
```
[Try it online!](https://tio.run/##BcHBCoAgDADQe19htw0TEiGhYX1LCNYGrYg6Rd9u72W35lwrd0IFFN9yXMBJiQnP587bcoFYO8uks6SWnet8P4odwsg2RqSvst5mX1gBzduYAj4gNV/9AQ "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
lambda n:['%xopqrstuvwxyz'[:n+1]%i for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlpdtSK/oLCouKS0rLyisko92ipP2zBWNVMhLb9IIVMhM0@hKDEvPVUjTzP2f0FRZl6JQpqGoSYXjGmEYBoaILGNNf8DAA "Python 2 – Try It Online")
Chooses a hex digit (`0123456789abc`) for the first character, and the last half of the alphabet for the rest.
---
Another 53-byter that does the same thing, using `map`:
```
lambda n:map('%xopqrstuvwxyz'[:n+1].__mod__,range(n))
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjexQENdtSK/oLCouKS0rLyisko92ipP2zBWLz4@Nz8lPl6nKDEvPVUjT1Pzf0FRZl6JQpqGoSYXjGmEYBoaILGNNf8DAA "Python 2 – Try It Online")
---
Another 53-byter, this time using Python 3 f-string:
```
lambda n:[f'{i:x}copqrstuvwxyz'[:n]for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjpNvTrTqqI2Ob@gsKi4pLSsvKKySj3aKi82Lb9IIVMhM0@hKDEvPVUjTzP2f0FRZl6JRpqGoaYmF4xthMQ2NEDmGGtq/gcA "Python 3 – Try It Online")
---
If numeric characters are not allowed:
### [Python 2](https://docs.python.org/2/), ~~58~~ 57 bytes
*-1 byte thanks to @dingledooper !*
```
lambda n:['%copqrstuvwxyz'[:n+1]%(i+65)for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlpdNTm/oLCouKS0rLyisko92ipP2zBWVSNT28xUMy2/SCFTITNPoSgxLz1VI08z9n9BUWZeiUKahqEmF4xpimAaGmv@BwA "Python 2 – Try It Online")
Choose the first letter from the first half of the alphabet, and the last letters from the last half of the alphabet.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes
```
AÂSìδ£I£
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f8XBT8OE157YcWux5aPH//8YA)
Haha! With the expert help of Kevin, I beat Pyth once again!
## Explained (with Docs Descriptions)
```
A| 'abcdefghijklmnopqrstuvwxyz'
Â| Bifurcated a. Push a, reversed(a)
S| Cast a to a list of characters / digits.
ì| Merge b with a if both are lists, else prepend b to a. Push a.prepend(b)
δ| Outer Product. Get the next command and apply it double-vectorized.
£| Head. Push a[0:b]
I| Input
£| Head. Push a[0:b]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
n=>(q=`opqrstuvwxyz,`.slice(13-n)).replace(/./g,t=>i.toString(++i)+q,i=10)
```
[Try it online!](https://tio.run/##DctLDsIgEADQ6zCBUhvX00t4gRKkZAxh@Iytenns8i3eyx2u@0ZFpszPMHYcGVdVceNSW5f3cX6@P7PZnsgHtdynDGBbKMldnO0cjeBKVvghjXJUWhPoagiXGwzPuXMKNnFU@5UBxh8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 83 bytes
```
n->{for(int i=n,j=0;i>0;)System.out.printf("%c",j++>0?j>n?10+(j=--i-i):j+63:i+77);}
```
[Try it online!](https://tio.run/##bU5La4QwEL77KwZhITYalIUumOoeeuqhpz2WHtKoy2R1IiYulMXfbtPFUig9DPP4XmPUVWWmuaw4jHbyYMIuZo@96GbSHi2JBxnpXjkHrwoJbhHAOH/0qMF55UO7WmxgCBg7@Qnp/PYOajq75E4FeCH/bMnNQztBB9VKWX3r7MSQPGBFqalyiXUuk9On8@0g7OzFGHx8x@KdjlPDeZ0fTU3HIufMVFmGGSal4Y/7EvnhkMhllfek4AqbbSEB4amCYh8Gzn9@AfgvpCl3FKeAidxInVBat6Nnv6e/up7Yhi3Rdy3rFw "Java (JDK) – Try It Online")
I was able to make a one-liner, but it's 100 bytes long and works only on Java 13+ if that can inspire anyone to golf further...
```
n->(" %sNOPQRSTUVWXY".substring(0,n+2)).repeat(n).formatted((Object[])"ABCDEFGHIJKLM".split("",n+1))
```
[Try it online!](https://tio.run/##dY7bTgIxEIbveYpJE5JWoBG9c1kSTygKouIxhIuyBzLrbrdpZzchhmdfK6J3XjTTmfm@yZ@pWvWy@KPBwpSWIPO9rAhzmVY6Iiy1PAhaUa6cg6lCDZ8tAFOtcozAkSJf6hJjKPyOz8miXi@WoOzaiR0KMNY02p8a/ABDSCFsdG/IGbTd3ez@4XH@9Pzy@vbOpKtWbgfxw67uHAkhbWISRVwLmZa2UERJzPlslSURLZaCnZ6dX1yOrq7HN7eTqfdNjsQZ83JfiCbYRfAicNQEGPYDQBiE0D/2n07nNyRArSzYMJXKmHzDUQT7@XzjKClkWZE0PhelnLXjE5@7rVkXsAv2D/3HyDXfI9vW99s2Xw)
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 52 bytes
```
[nAP1-d0<M]sL?dsnCo[d96+POO^OO^Bd*/-ODln-^/d0<L]dsMx
```
[Try it online!](https://tio.run/##S0n@/z86zzHAUDfFwMY3ttjHPqU4zzk/OsXSTDvA3z8OiJxStPR1/V1y8nTj9IGKfGJTin0r/v83NAYA "dc – Try It Online")
Input is on stdin, and output is on stdout.
**Output for 13:**
```
mBA9876543210
lBA9876543210
kBA9876543210
jBA9876543210
iBA9876543210
hBA9876543210
gBA9876543210
fBA9876543210
eBA9876543210
dBA9876543210
cBA9876543210
bBA9876543210
aBA9876543210
```
**How it works:**
```
[ Start a macro.
n Pop a number and print it.
AP Print a newline.
1- Decrement top of stack by 1.
d0< If top of stack > 0,
M then continue by calling macro M.
]sL End macro and save it in register L.
? Input number and push it on stack.
dsn Store top of stack in n.
Co Change output radix to base 12.
[ Start a macro.
d96+P Print the character with
ASCII code 96 + (top of stack).
(This will be a lower-case letter,
since 97 = 'a'.)
OO^OO^Bd*/-ODln-^/ Push (12^12 - (12^12)/(11*11)) / (12^(13-n)).
In base 12, this is the leftmost n-1 digits
of BA9876543210 (or 0 for n=1).
d0<L If this number > 0, call macro L to print it,
decrement the value of n at the top of stack,
and go back to the top of the loop M.
]dsMx End macro, save it in register M, and execute it.
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 38 26 bytes
```
.+
*.
Y`.`l
L$`.
$=
Y`a`Rl
```
*-12 bytes thanks to @Neil*
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS0uPKzJBLyGHy0clQY9LxRbIS0wIyvn/39AYAA "Retina – Try It Online")
This works by generating the beginning of 'abc...' length N, then repeating it and substituting the first letter for something from 'zyx...'
```
.+ This converts the number into unary, using dots
*. ^
Y`.`l A cyclic transliteration: replace all dots with something from a-m
L$`. Repeat per N with a line break at the end
$= ^
Y`a`Rl Finally, transliterate each 'a' with something from z-n
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;ÆîEhCgX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O8buRWhDZ1g&input=MTMKLVI)
```
;ÆîEhCgX :Implicit input of integer U
Æ :Map each X in the range [0,U)
î : Slice to length U
; E : Printable ASCII
h : Replace first character (space) with
; C : Lowercase alphabet
gX : Character at index X
```
[Answer]
# B (asm2bf dialect), 136 bytes
```
p(c){asm("rclr1,r4");asm("outr1");}g(){asm("in r1");}n;c 65;d;i;main(){i=n=g();while(i--){p(c++);d=65+n;while(d-n-65<n-1)p(d++);p(10);}}
```
Output assembly:
```
#!/usr/bin/env bfmake
stk 16
org 0
db_ 0
db_ 65
db_ 0
db_ 0
#PAGE_SIZE = 16
#MM_BASE = 5
#call("alloc")
mov r4, r6
#call("_main")
end
@alloc
#alloc("r6", "r5")
ret
@_p
rclr1,r4
outr1
ret
@_g
in r1
ret
@_main
psh 3
psh 0
#call("_g")
mov r2, r1
pop r1
sto r1, r2
pop r1
sto r1, r2
@L1
mov r2, 3
rcl r1, r2
dec r1
sto r2, r1
inc r1
jz_ r1, %L2
psh r4
#call("alloc")
mov r2, 1
rcl r1, r2
inc r1
sto r2, r1
dec r1
sto r6, r1
mov r4, r6
#call("_p")
#free("r4")
pop r4
psh 2
psh 65
rcl r1, 0
mov r2, r1
pop r1
add r1, r2
mov r2, r1
pop r1
sto r1, r2
@L3
rcl r1, 2
psh r1
rcl r1, 0
mov r2, r1
pop r1
sub r1, r2
mov r2, 65
sub r1, r2
psh r1
rcl r1, 0
mov r2, 1
sub r1, r2
mov r2, r1
pop r1
lt_ r1, r2
jz_ r1, %L4
psh r4
#call("alloc")
mov r2, 2
rcl r1, r2
inc r1
sto r2, r1
dec r1
sto r6, r1
mov r4, r6
#call("_p")
#free("r4")
pop r4
jmp %L3
@L4
psh r4
#call("alloc")
sto r6, 10
mov r4, r6
#call("_p")
#free("r4")
pop r4
jmp %L1
@L2
ret
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47 bytes
```
->n{a=*?`..?z;(1..n).map{|i|a[i]+a[14,n-1]*''}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtFWyz5BT8@@ylrDUE8vT1MvN7GguiazJjE6M1Y7MdrQRCdP1zBWS129tvY/SIWhsaZeamJyBkhNgUIaUFXtfwA "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-na`, 42 bytes
```
say$_,(A..Z)[0..$F[0]-2]for(N..Z)[0..$_-1]
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIlXkfDUU8vSjPaQE9PxS3aIFbXKDYtv0jDDy4Yr2sY@/@/ofG//IKSzPy84v@6vqZ6BoYG/3XzEgE "Perl 5 – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~62~~ 59 bytes
```
dc -e'[nAP1-d0<M]sL?dsnCo[d96+POO^OO^Bd*/-ODln-^/d0<L]dsMx'
```
[Try it online!](https://tio.run/##S0oszvj/PyVZQTdVPTrPMcBQN8XAxje22Mc@pTjPOT86xdJMO8DfPw6InFK09HX9XXLydOP0gYp8YlOKfSvU//83NOYCAA "Bash – Try It Online")
Input is on stdin, and output is on stdout.
---
---
Here's the original, longer answer:
```
echo {a..m}`echo {o..z}|tr -d \ `|fold -14|cut -b 1-$1|sed $1q
```
[Try it online (62 bytes)](https://tio.run/##S0oszvj/PzU5I1@hOlFPL7c2AcLO19Orqq0pKVLQTVGIUUioScvPSVHQNTSpSS4tUdBNUjDUVTGsKU5NUVAxLPz//78ZAA "Bash – Try It Online")
Input is passed as an argument, and output is on stdout.
[Answer]
# [Befunge-93](https://github.com/catseye/FBBI), ~~53~~ 51 bytes
```
&:v
< <>:: v:::\,+*77:
| ^-1,+*88<_$$\1-0.:
@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X82qjMtGwcbOykoBDMqsrKxidLS1zM2tuGoUFOJ0DYEcCwubeBWVGENdAz0rLof//w2NAQ "Befunge-98 (FBBI) – Try It Online")
`0` is my two character delimiter. Outer loop outputs N'+(7\*7) in ascii, sets M to N (this requires a swap) then enters inner loop. Inner loop outputs M+(8\*8) in ascii and decrements M. On exiting inner loop outputs `0` and decrements N' (this requires a swap). `|` and `_` are the loop condition instructions respectively. `:` is often used to make copies since most operations - from arithmetic to conditional check, destroy the value they operate on by popping it out of the stack
Befunge is stack based with a single instruction pointer that points to a character in the code. It has a travelling direction that can be changed via arrows <>^v
Befunge-98 submission by ovs, 43 bytes
```
&:>:77*+,\:>:: v
.:|;-1,+*8;^;8<_$$\1-0
@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X83KzsrcXEtbJwbIsFIo49KzqrHWNdTR1rKwjrO2sIlXUYkx1DXgUlBw@P/fBAA "Befunge-98 (FBBI) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~14~~ ~~12~~ 11 bytes
```
←ẊM:M↑½…"az
```
[Try it online!](https://tio.run/##AR8A4P9odXNr///ihpDhuopNOk3ihpHCveKApiJhev///zEw "Husk – Try It Online") Splits the alphabet into two halves, truncates each half to the size of the input, and then recombines them in the proper way.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~98~~ 88 bytes
-10 thanks to @ceilingcat
```
c,d,i,j;f(n){for(c=65,i=n,d=c+n;i--;puts(""))for(j=!putchar(c++);j<n-1;)putchar(d+j++);}
```
[Try it online!](https://tio.run/##NYsxDoMwDEXncgpgihVn6EAXN1svEjkKddQaVGgXxNUbQGrH997/7HrmUhgjCmZKRmFJw8uwv3QoXjF6tkriHI3veTJtC3D07Jud@R72qbVA@aruTPB30ebDrkV0rp9B1HwGiVAv1SmZDqhay5fTI/RTcbfR/24b "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Øa;€Ṛ$ḣḣ€
```
A monadic Link accepting an integer in \$[1,13]\$ which yields a list of lists of characters.
**[Try it online!](https://tio.run/##y0rNyan8///wjETrR01rHu6cpfJwx2IgAnL@H26P/P/fHAA "Jelly – Try It Online")**
### How?
```
Øa;€Ṛ$ḣḣ€ - Link: integer, N
Øa - lower-case alphabet
$ - last two links as a monad:
Ṛ - reverse (the alphabet)
;€ - concatenate that to each of (the alphabet)
ḣ - head to index (N)
ḣ€ - head each to index (N)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~66~~ 60 bytes
```
f=(n,k=n*n)=>k?Buffer(k--%n?[97+k%n]:[10,123-k/n])+f(n,k):''
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfbNk8rT9PWLtveqTQtLbVII1tXVzXPPtrSXDtbNS/WKtrQQMfQyFg3Wz8vVlM7DaRD00pd/X9yfl5xfk6qXk5@ukaahrGmJheqiAmGiCFQ0X8A "JavaScript (Node.js) – Try It Online")
[Answer]
# Google Sheets, 76 bytes
```
=ArrayFormula(Char(Row(Offset(78:78,,,A1)))&Join(,Char(Row(Offset(65:65,,,A1
```
When you exit the cell, Sheets will automatically add the 5 trailing parentheses. Input is in cell `A1`. Output is wherever you put the formula and the `N-1` cells below it.
`Row(Offset(78:78,,,A1))` gives us an array from `78` to `78+N-1`.
`Char(Row(~))` turns that array into their ASCII equivalent (capital letters).
`Char(Row(Offset(65:65,,,A1)))` does the same thing for the range `65` to `65+N-1`.
`Join(Char(~))` combines that second array into a single string.
`ArrayFormula(~)` makes these functions input and output arrays instead of a single value.
[](https://i.stack.imgur.com/EkLoe.png)
[Answer]
# [MATLAB/Octave], 35 bytes
```
char([N+[1:N]',ones(N,1)*[1:N]]+64)
```
First create a column vector ranging from N+1 to 2N with N+[1:N]. Make a column vector with all values equal to one and length N, and multiply by a row vector containing values 1 to N to make a matrix of N columns with all rows equal to 1:N. Concatenate the first vector with your matrix, add 64 to all digits and use char to turn every row into a string.
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
(\t->t.(:['n'..])<$>t['a'..]).take
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyOmRNeuRE/DKlo9T11PL1bTRsWuJFo9EczWK0nMTv2fm5iZp2CrkJLPpaCQm1jgG69QUFoSXFLkk6egkaZgqIlV2BS7sKGx5v9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 22 bytes
```
'[,65>_W%qi<_,(@<am*N*
```
[Try it online!](https://tio.run/##S85KzP3/Xz1ax8zULj5ctTDTJl5Hw8EmMVfLT@v/f0NjAA "CJam – Try It Online")
This works by generating the Cartesian product of the each of the last `n` characters of the alphabet and a singular array containing a string with the first `n-1` characters of the alphabet. For example, the following is outputted for 13:
```
ZABCDEFGHIJKL
YABCDEFGHIJKL
XABCDEFGHIJKL
WABCDEFGHIJKL
VABCDEFGHIJKL
UABCDEFGHIJKL
TABCDEFGHIJKL
SABCDEFGHIJKL
RABCDEFGHIJKL
QABCDEFGHIJKL
PABCDEFGHIJKL
OABCDEFGHIJKL
NABCDEFGHIJKL
```
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/), 360 bytes
```
absently,i jot out words,A-Z
moving a pen mindlessly about a page
i am making my art,i`m doing a poem
i ensure i can never do patterns at first
i`d alter a chr i am using
i`d say i am not consistent,cause i`m using a perfect copy i forged when i end a certain verse
o yes,i reckon i am doing A-Z lazily
o yes,i admit
o yes,i am silly
i compose tripe,o yes i do
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?RZBBdsMwCET3PgUHcFc9Qa/RlbGEExoJ/AROnnP5FNl57VLMn9EAzkbiZR8ZftRBN4eHtmzj18f3UPXOcgGElQQqSy5kVnbAuXMxxgsNDFih4q2TNbTmI08Vsr6tSjUYEtsaAUNCAaE7tSAiwJ2aGKDDws184CkDlhiGNV0bHOmbRdYhGe7nSKJsUjE2j/5jws0ifXqzR@W2UOrQ2i2LtgtleFxjk94m93xqjiwQZYwGhZ0sztAo3VTOX84l4hRQ8Mll/4MwV/b/VwXjEnKsp3XVqOKNVxoPIKKyvj5fM@Zf)
This works by filling the entire memory with the negative of the inputted number (as that's the shortest way to copy it to multiple cells), then outputting the first character - which is decremented each iteration - and then the last few ASCII characters up to ASCII 255.
Warning: this takes a long time to run, even for small inputs. Such is the price to pay for a short length.
]
|
[Question]
[
# The challenge
Make 2 programs which convert decimal to and from base 94, or a bidirectional program.
# Base 94?
Base 94 is like any other base, but instead of 0 to 9 and letters, it uses ASCII characters 33 to 126. Not 127 because `chr(127)` is DEL. Not 32 because that's a *space*.
# Examples
```
0 - ! or empty string
1 - "
93 - ~
94 - "!
2020 - 6O
14233221 - 2-n8
```
# Scoring
For two programs, the score will be the sum of the byte count of both of the programs.
The bidirectional program is simply just the byte count. Consider it like a -50% to the score.
[Answer]
# [Haskell](https://www.haskell.org/), 42 + 31 = 73 bytes
**To base 94: 42 bytes**
```
(l!!)
l="":tail[s++[c]|s<-l,c<-['!'..'~']]
```
[Try it online!](https://tio.run/##FcixDsIgEADQ3a84GhM0haY9utiUL0EGQkSJ14ZIx8ZP99ThLe8R6vNGxMle@URCnA9km2baQiZX29ZFv9dZk4qzdlLIrpNv6T0vIa9gobzyusERllAggesVDAou5mdUgD3@Y0RjEAfPn5go3CvrWMoX "Haskell – Try It Online")
Instead of using modular arithmetic, we generate the list `l` of all strings in the desired order and index into it.
The recursive definition of `l` is similar to [this one](https://codegolf.stackexchange.com/a/74293/20260) for generating all strings, but modified to output strings in the desired order by appending the new character, and with a `tail` to prevent the analogue of leading zeroes.
**From base 94: 31 bytes**
```
foldl(\n->(94*n-33+).fromEnum)0
```
[Try it online!](https://tio.run/##y0gszk7NyfmfbhvzPy0/JyVHIyZP107D0kQrT9fYWFtTL60oP9c1rzRX0@B/bmJmnoKtQkFRZl6JgopCbmKBQrpCtJKSjlIMiKgDMxSBpJk/kDDSzbNQiv3/LzktJzG9@L9uckEBAA "Haskell – Try It Online")
Iterates over the characters `c` of the string, updating the current value `n` to `94*n-33+fromEnum c`.
[Answer]
# [Python 2](https://docs.python.org/2/), 40 + 45 = 85 bytes
**To base 94: 40 bytes**
```
f=lambda n:n*"?"and f(n/94)+chr(n%94+33)
```
[Try it online!](https://tio.run/##DcfNCoQgEADgu08hQTCzHcoZLwaxz2I/olCzEkb09Lbf7ctPiT@hWsO0@2NevZZRPs238bLqANI7i90ST5DW2Y4Z6x3Tvmkz5jNJgQBJ8lUAEeugjHKsnFU00D@WmInMCw "Python 2 – Try It Online")
Python 3 would need 1 extra byte for `//` in place of `/`.
**From base 94: 45 bytes**
```
g=lambda s:s>''and g(s[:-1])*94+ord(s[-1])-33
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P902JzE3KSVRodiq2E5dPTEvRSFdozjaStcwVlPL0kQ7vygFyAXxdI2N/5dnZOakKhhaFRRl5pVopGtk5hWUlmhoamr@V1dU51JXAuI6EA3imPkDCSPdPAt1AA "Python 2 – Try It Online")
**Both to and from base 94: 86 bytes**
```
h=lambda x:x*'?'and h(x/94)+chr(x%94+33)if x<''else x>''and h(x[:-1])*94+ord(x[-1])-33
```
[Try it online!](https://tio.run/##NcpNCsIwFATgfU4RBXlJS7F5L4gp/hzBA4iLaisJ1LTUinHj1WO6cDEzfDDDZ7K9xxjtvqsf16bmoQoZHKH2DbcirI2W@c2OIqyMzomku/OwA2i7Z8vDAf6/c1Woi8zSpx@bxFkFUXxb17VcVcPo/CSscH54TUJKGUummCFmNMMSEzQSISoGC2CwTPnOO2NzSoWF38IP "Python 2 – Try It Online")
A Frankenstein's monster stitched from the two above functions that turns out just barely longer than their byte total. Since this function accepts both numbers and strings, care must be taken not to produce an error caused by an illegal operation by acting on the wrong type.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), (34 + 44) = 78 bytes
The 'Decimal to Base94' function prints the Base94 number to STDOUT, whereas the 'Base94 to Decimal' function actually returns the integer.
---
### Decimal to Base94:
```
f(n){n&&f(n/94)+putchar(n%94+33);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOk9NDUjrW5poaheUliRnJBZp5KlammgbG2ta1/7PzCtRyE3MzNPQVKjmUkjTMNC0VoApU4/JU9e0BokaYhW1NMYubIJV2MjACIfhJkbGxkZGWOyo/Q8A "C (gcc) – Try It Online")
### Base94 to Decimal:
```
n;f(char*s){for(n=0;*s;n=n*94+*s++-33);n=n;}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/POk0jOSOxSKtYszotv0gjz9bAWqvYOs82T8vSRFurWFtb19hYE8S3rv2fmVeikJuYmaehqVDNpVBQBOSnaSippsTkKekoAFlKmprW2MRjcMrU4daiiEvKzB@XjJFungVYrvY/AA "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), Score 10 bytes
*-4 bytes overall thanks to @KevinCruijssen*
## [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
žQ¦Åв
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6L7AQ8sOt17Y9P@/oYmRsbGRkSEA "05AB1E – Try It Online")
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
žQ¦Åβ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6L7AQ8sOt57b9P9/tJKRko6Cki6IyAMRFkqxAA "05AB1E – Try It Online")
[Answer]
# [W](https://github.com/A-ee/w), 4 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
Encoding/Decoding program, it's bidirectional.
```
lpQB
```
# Explanation
```
lp % All printable characters, including the space.
Q % Extract all of the string except for the first item.
B % Convert the input to/from base 94 using the custom base.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~44~~ 43 + 32 = 75 bytes
-1 byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor).
**Base 10 to base 94:**
```
g 0=""
g n=g(div n 94)++[['!'..]!!mod n 94]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P13BwFZJiStdIc82XSMls0whT8HSRFNbOzpaXVFdTy9WUTE3PwUsGPs/NzEzT8FWISWfSwEICooy80oUVBTSFQxNjIyNjYwM0YSNDIwM/gMA "Haskell – Try It Online")
**Base 94 to base 10:**
```
foldl(#)0
n#c=n*94+fromEnum c-33
```
[Try it online!](https://tio.run/##y0gszk7NyfmfbhvzPy0/JyVHQ1nTgCtPOdk2T8vSRDutKD/XNa80VyFZ19j4f25iZp6CrUJKPpcCEBQUZeaVKKgopCsoGenmWSihC5r5K/3/l5yWk5he/F83uaAAAA "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Base-94 I/O as an array of characters. Output for `0` is an empty array, input for `0` can either be an empty array or `["!"]`.
```
;ìEÅ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O%2bxFxQ&input=WwoxNDIzMzIyMQpbIjIiLCItIiwibiIsIjgiXQpdLW1S)
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, Score 37 + 70 = 107 bytes
---
# Base 10 to Base 94: 37 bytes
```
dc<<<94o$1p|sed 's/\b \|$/ 33+P/g'|dc
```
[Try the test suite online!](https://tio.run/##NYxBCsIwEEX3nuJTAl2IpJnJJhA9gwfoxibRuplI4zJ3H6vg5sN78P5ya6ve6wbBUzDBITCCB020gydmIncAct0HKGmtOAkGIzhfMPxkK28Y0ZxijMFX4169lYyx2XnB3I0F8/FqH2PPSfG/@aa5SlHVDw "Bash – Try It Online")
Input is passed as an argument, and output is on stdout.
This works for inputs from \$0\$ through \$94^{23}-1.\$
This is probably sufficient, since \$94^{23}-1\$ is a huge number (46 decimal digits long — `2409576021839340871044919550282633620681129983` in base 10, or `~~~~~~~~~~~~~~~~~~~~~~~` in base 94), and this is already much larger than most languages can handle.
---
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 34 + 43 = 77 bytes
# Encoder
```
f(n){n&&f(n/94)|putchar(n%94+33);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOk9NDUjrW5po1hSUliRnJBZp5KlammgbG2ta1/7PzCtRyE3MzNMoy89M0eSq5lIAgjQNIwMjA01rrtr/AA "C (gcc) – Try It Online")
# Decoder
```
r;f(int*s){for(r=0;*s;)r=r*94+*s++-33;s=r;}
```
Takes a wide string as argument.
[Try it online!](https://tio.run/##S9ZNT07@/7/IOk0jM69Eq1izOi2/SKPI1sBaq9has8i2SMvSRFurWFtb19jYuti2yLr2P1CdQm5iZp5GWX5miiZXNZcCEBQUAYXTNJRUU2LylHQU0jR8lMz8lTQ1rblq/wMA "C (gcc) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 80 bytes
```
{FromCharacterCode[#~IntegerDigits~94+33]&,FromDigits[ToCharacterCode@#-33,94]&}
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78X52mk15r@7/arSg/1zkjsSgxuSS1yDk/JTVauc4zryQ1PbXIJTM9s6S4ztJE29g4Vk0HpBIiFB2Sj6LFQVnX2FjH0iRWrfZ/QFFmXkl0WrShiZGxsZGRYayOkoKCkk46slBs7P//AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 or 7 bytes
## Base 10 to base 94: 5 bytes
```
⍘N✂γ¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITNfwzCsoLfErzU1KLdLQ1FEIzslMTtVI11Ew1NTUtP7/39DEyNjYyMjwv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of decimal digits optionally wrapped in `[]`. Explanation:
```
N Cast input to number
⍘ Base conversion from custom base
γ Printable ASCII (including space)
✂ ¹ Slice off the first character
Implicitly print
```
## Base 94 to base 10: 6 bytes
```
I⍘S✂γ¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxODW4BMhP1/DMKygtgbI1dRSCczKTUzXSdRQMNYHA@v9/I908i/@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Note: Due to the way Charcoal parses input, if the input looks like JSON then Charcoal will input it as JSON instead of a literal string. To avoid that, quote the input and wrap it in `[]`s, e.g. to input `[0]` use `["[0]"]`. Explanation:
```
S Cast input to string
⍘ Base conversion from custom base
γ Printable ASCII (including space)
✂ ¹ Slice off the first character
I Cast from integer
Implicitly print
```
## Bidirectional: 7 bytes
```
⁺ω⍘A✂γ¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMgp7RYo1xHwSmxODW4BCiUruGZV1BaoqGpoxCck5mcqpGuo2CoCQTW//9HKxnp5lkoxf7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as JSON wrapped in `[]`s. Explanation:
```
A Input JSON element
⍘ Base conversion to or from custom base
γ Printable ASCII (including space)
✂ ¹ Slice off the first character
⁺ω Concatenate empty string (casts result to string)
Implicitly print
```
[Answer]
# [Python 2](https://docs.python.org/2/), 53 + 46 = 99 bytes
**Base 10 to base 94:**
```
n=input();r=''
while n:r=chr(n%94+33)+r;n/=94
print r
```
[Try it online!](https://tio.run/##LY2xDoMwEEP3@4pbqoAYgIQFUEa6dukPtOlJoFaX6BTU8vVponayLT3b4YirZ52cfxBaVEolthuHPVb1LFYpeK/bi5AnsW6Vik/j0BhTNzJza8cBgmwcUVJuwp@9yk4TIEY5iiDShxyWByjeUYi4XM6LiJcfcBe6PVMHPYwG8qjudA6DNkbr/gs "Python 2 – Try It Online")
**Base 94 to base 10:**
```
lambda s:reduce(lambda a,b:a*94+ord(b)-33,s,0)
```
[Try it online!](https://tio.run/##LU09D4IwFNz7K54ubRUSA8YoCSOuLI4uLX0EIrbNo0RZ/OtIo8N9JZc7P4fO2WxpnEEogTjnrC3vy6Ce2igYC0IzNSj@WSW6ULvLce/ICC3TPE/G5CAXT70N0Ire@ikIKVncYa@uHxBuNGHBAALNUQDwjQ3EQxZ9gz5AVV8rIke/giZUj4VvOOPbFZ@oMZzqlbLUnvkX "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~47 + 51 = 98~~ 40 + 42 = 82 bytes
*Saved 12 bytes, inspired by @ovs 's suggestion.*
*Saved 1 byte by replacing `len(s)` with `s>[]`, stolen from [@xnor's Python answer](https://codegolf.stackexchange.com/a/203050/92237).*
```
f=lambda n:n*`n`and f(n/94)+chr(n%94+33)
g=lambda s:s>[]and ord(s.pop())-33+g(s)*94
```
[Try it online!](https://tio.run/##NY5BboMwEEX3PsUECckOhiY2qgpScoJKPUAUNRRKYgkGy@NNNr069VB1M57//5sv@2d8LGjWdTxN3fw1dIAt7m9463CAUeJLU6uifwSJeVMX1ipx/weppfPlytwSBkmVX7xUqrS2uEtS@6Ze3eyXEIGeJMS4BJgcfoNDNiqKg8NWAKCGTw0EJ5g7LymGFAXn9UZX5CcXUy2DCXEYJbKgd0cxGZceuLnfaq9MmeSmD3C@gazHvyMf0j1k@QA5QVmeYdsyyEGiJo1Gk1HrAUrYiWOamWhsen5EU7PaCXMwnL5@iGNtrDWGKVPi2y8)
`f` takes in an integer, and returns the base 94 string. Returns the empty string for `0`.
`g` takes in a list of characters, and returns an integer. If input is a empty list (representing an empty string), `False` is returned in stead of `0`, which is functionally equivalent in Python.
### [Python 2](https://docs.python.org/2/), 82 bytes
This is the bidirectional function that combines the previous 2 functions, with the same total byte count. Utilize the fact that in Python 2, `0 < positive int < empty list < non-empty list`.
```
f=lambda n:n>[]and ord(n.pop())-33+f(n)*94or n<[]and n*`n`and f(n/94)+chr(n%94+33)
```
[Try it online!](https://tio.run/##JY5BbsMgEEX3nGJiyRLEOE3AquqoyQkq9QBR1Dh2rSDZY8SwyaZXdweygfn/vz/gn/GxoFnX8TR1833oAI94vlw7HGAJg8SdX7xUqra2GiWqbdssAfDzReD2hrc0cPTWNqrqH0Fi2TaVtWp1s19CBHqSECO3Joe/4DAZO4qDw6MAQA0/GghOMHdeUgwcBed1pnfkJxf5@QQy4jDyH1jQl6PIxqWHtLnPa6@JMuyOMucZfOlc8oH7UJQDlAR1fYY8FVCCRE0ajSaj1j3UsBEHPgvRWr7@RNsktRFmb1L6/i0OjbHWmESZGj/@AQ "Python 2 – Try It Online")
**Input/output**: If `n` is a list of characters, return the converted integer. If `n` is an integer, returns its base 94 string.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 33 + 34 = 67 bytes
## Encode (33):
```
f=->n{n>0?f[n/94]+""<<n%94+33:""}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/OwD4tOk/f0iRWW0nJxiZP1dJE29jYSkmp9n9BaUmxQrSBjqGOpbGOpYmOkYERkGNiZGxsZGQYq5ebWKChlqb5HwA "Ruby – Try It Online")
## Decode (34):
```
->s{i=0;s.bytes{|x|i=i*94+x-33};i}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664OtPWwLpYL6myJLW4uqaiJtM2U8vSRLtC19i41jqz9n9BaUmxQrS6orqOuhIQ14FoEMfMAEgY6eZZqMfq5SYWaKilaf4HAA "Ruby – Try It Online")
Thanks Value Ink, as usual, for some byte trimming.
[Answer]
## [K (ngn/k)](https://bitbucket.org/ngn/k), 9 + 10 = 19 bytes
## To base 94, 9 bytes
```
`c$33+94\
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NKiFZxdhY29Ik5n@auoKBgqGCpbGCpYmCkYERkGNiZGxsZGT4HwA "K (ngn/k) – Try It Online")
## From base 94, 10 bytes
```
94/-33+`i$
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NytJEX9fYWDshU@V/mrqGkpK1UgyIqAMzFIGkmT@QMNLNs1DS5PoPAA "K (ngn/k) – Try It Online")
## [J](http://jsoftware.com/), 15 + 13 = 28 bytes
## To base 94, 15 bytes
```
[:u:33+94&#.inv
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61KrYyNtS1N1JT1MvPK/mtyKXClJmfkK2hYp2kqqNkBlRoqWBorWJooGBkYATkmRsbGRkaGXP8B "J – Try It Online")
## From base 94, 13 bytes
```
94#._33+a.i.]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/LU2U9eKNjbUT9TL1Yv9rcilwpSZn5CtoWKdpKqjZKagrqlsrqCuBiDowC8w38weRRrp5Fupc/wE "J – Try It Online")
[Answer]
# x86 32-bit machine code, 14 + 17 = 31 bytes
atoi: explicit-length string input, pointer and length. Returns `uint32_t`
itoa: pointer to the end of a buffer, returns pointer to the first digit. Only works for non-negative `int32_t` - would cost 1 extra byte to `xor edx,edx` before div instead of `cdq` to sign-extend.
objdump -d -Mintel disassembly of both functions with machine code (the actual answer) and the source. Comments added manually.
```
;; input: char *RDI, size_t RCX
;; returns: unsigned EDX
;; clobbers: EAX temporary to load digits
08049000 <atoi_b94>:
8049000: 31 c0 xor eax,eax ; EAX = 0 so lodsb zero-extends to 32-bit
8049002: 99 cdq ; EDX = 0 = total
08049003 <atoi_b94.loop>:
8049003: ac lods al,BYTE PTR ds:[esi]
8049004: 6b d2 5e imul edx,edx,0x5e ; total *= base
8049007: 8d 54 02 df lea edx,[edx+eax*1-0x21] ; total += char_to_int(digit)
804900b: e2 f6 loop 8049003 <atoi_b94.loop>
804900d: c3 ret
```
You could call atoi from C if you declare the return value as a 128-bit integer, or a struct. itoa uses different calling convention.
```
;; input: unsigned EAX, char *RDI=end_ptr
;; result: converts into base94 in printing order in the buffer
;; returns: RDI=pointer to the first digit. Caller knows where the end is because it passed that arg
;; clobbers: EDX
0804900e <itoa_end_base94>:
804900e: 6a 5e push 0x5e
8049010: 59 pop ecx ; ECX = base
08049011 <itoa_end_base94.toascii_digit>: ; do{
8049011: 99 cdq
8049012: f7 f1 div ecx ; EAX = quotient, EDX = remainder
8049014: 83 c2 21 add edx,0x21
8049017: 4f dec edi
8049018: 88 17 mov BYTE PTR [edi],dl ; *(--p) = digit
804901a: 85 c0 test eax,eax ; }while(x)
804901c: 75 f3 jne 8049011 <itoa_end_base94.toascii_digit>
804901e: c3 ret
```
next address is 0x1f, total size = 0x1f - 0 = 31 bytes.
Some of the comments use 64-bit registers; I switched to 32-bit to save 2 bytes in single-byte `dec edi` vs. `dec rdi` REX opcode modrm.
[**Try it online!**](https://tio.run/##hVVNb@M2EL3rV0wPBezEcuKPtpsYOrgb7yJANgGStAjaDQRKGtlsZFJLUrGTon@96ZCUbDn2ojoIIjmceTPvzYhpjcukeAlzppdvb7lUS2ZgdvUJcI1pZVhSIIwAYOI2R8Mw4aZ1FmicL1EYUMgyZ9w6o331ArE2TJlgMi9kwop6aR1eT@@@BAH5hl@ndzPAbxWcjYM/Zrc3F5efL@/dxmjkLSYT4KKszDmkC6bg6Pbisgeav2Js4PbjQ2Oj0FRK6HOohOZzgRnMLjaHKQFIUNHpbPoABpelVIwAGgmFZBlkfM6N3gBlRvI4IUTNx7lztJYKANm6Z1@w@0yc5whOQVufmU7gFZUMcW1QZNpG8hV0ntLsG3zvmVjgzlNEtwwrgn4hZekheM/fu9iKSPlzQUFvp74IfFkVBD6z4O3L1X3fgwsIRxEkTKOPiAzqi3/SG45d8iFsyHpsXTyOHEmxkTFF77iydmvgsgRwmbg10fWe3i1x04feluyIsolLo7ZE66qwapDiGZXRPk@L92xM31Aq2uBiDlJlqOyOWSAkVZ6j2hOL9V9KukCW5MVa5lxp4xXRB/jIioLOnoRcaVgtUKEzIkzANSSYskojUGOUjPopo0NqIqbmB5RHcmwExo1ksc3Lww7erT3XZaUXdYf4ta0gUZGug6BPF3TKeexwnu8TmUn4@3@lRnZSFC@wkupJA00AEFKEAufM8Ge0hcU5YacyYEFZ2kxdEzQycgEy/lzDOhiAzCKFS8aFZSMiIax8ca3E@/2zvmupk2hw6vXAsgwawW005gNh6k/4gTDaSKLG97Hl/MvdReiZ3NVDzyVrlwlLn1ZMUW/mSi43rMrcfWpD1zyLS@kSJPXzxx5kxU7co04Yll3KxYX2KRiksH5SvB8UE/iHVMQL7Ky7E2f8l3ilvtihM5hYiVKaTpn6gDC3LTT5McOcC4T72d3979MrGAxH459@/uVDML26/HwN48BP3ZakBqceyVcBLLfCr9P2LbIRstyodFsFKgERr30L64omES16NNlaJnY@1mC8AKmD9gS/NU@dlHjQLrXzMd7jOI6vb@OV4gY9ZSeVVidcpEWV4Qn9xE4qwbXJ4tGwv9hxl5C7wZ67PCPa7u4vbn67jz9dXs2ub1oDr5l4ujweDWnoDR5rOdflcMk3AzV9T3KBYm4WdnKFrvo98DCt7iyVX4UfysLqBE7XH04PSNpl2hn0ai32oJE3oem264Wa74MgB/Vga4/xtB7joc9nFy@suFnIyjiIAleF1VXUHJJCfN@2WsNxu/1duq1l2dSlrQKNhpwlRRu2ZXnQKsSBOlDB19zEcyWrstNI/IfIhexYUTWb3W43eHv7N80LNtdvYVZvR4PxcDQaDgf/AQ "Assembly (fasm, x64, Linux) – Try It Online") with a test harness that converts an assemble-time-constant value to a string and back, prints the result, and checks for integer equality. Change the assembler command line option to `-dTESTVAL=94` or whatever to test other values. If it prints the right string and exit status is `0`, it worked.
I used FASM on TIO so I could make 32-bit code; TIO's will only assemble 64-bit object files with NASM/YASM, but FASM can output an executable directly, no linker involved.
---
For "normal" asm [atoi](https://stackoverflow.com/questions/19309749/nasm-assembly-convert-input-to-integer/49548057#49548057) and [itoa](https://stackoverflow.com/questions/13166064/how-do-i-print-an-integer-in-assembly-level-programming-without-printf-from-the/46301894#46301894), see my answers on those linked SO questions. Golfing them was straightforward, with only one significant change: use explicit-length strings for itoa so we can use `loop` instead of having to check for a terminator before `tot = tot*base + digit`. And turning `itoa` into a function that just does the conversion into the caller's buffer.
I also made the `94` and `33` assemble-time symbolic constants (in the TIO link)
I had hoped we might get some use out of `stosb`, but we need to go backwards, and I couldn't justify having `atoi` depend on DF=0 while having `itoa` use `std` without `cld`. Also, getting the remainder into AL means swapping with EDX, but then we need to swap back for the next `div`.
```
;; alternate worse version for after DIV
std
xchg eax, edx
add al, ZERODIGIT ; 2 bytes
stosb ; *p-- = digit. would also need a scasb or inc edi at the end to fix
xchg eax, edx
cld
```
That's *nearly* break-even, IIRC one byte longer, but does `*p-- = digit` instead of the `*--p = digit` that we actually want. (Caller could change to pass a pointer to the last element of the buffer, instead of past the end, but I don't think we can justify returning a pointer to the uninitialized space below the first digit. So that would cost an extra `inc edi` after the loop.
[Answer]
# [Raku](https://raku.org) (raku -p) 60+42 Bytes = 102 Bytes
```
# convert base-10 to base-94
$!='';while $_ {$!=(chr $_%94+33)~$!;$_=$_.Int div 94};$_=$!
# convert base-94 to base-10
$!=0;$!=94*$!+$_-33 for $_.comb».ord;$_=$!
```
[Answer]
# [Red](http://www.red-lang.org), 68 + 58 = 126 bytes
## To base 94, 68 bytes
```
f: func[n][head either n > 0[append f n / 94 #"!"+(n % 94)][copy""]]
```
[Try it online!](https://tio.run/##FcyxCsMgFIXhPU9xaim0lFKjWdIhD9H1cgfRK2YxIsnQp7fmbB/8nCqhfSUQDy1@EI/sKTMlcQGy7kkqMhZocqVIDoidb8wTruqinveMW8eDyW/lpxRzi1sV51PPSGPEbM/YaNMxGWuNGZkG9JW65h3UQ/Va1HnMA7c/ "Red – Try It Online")
## From base 94, 58 bytes
```
g: func[s][either""= s[0][(-33 + take/last s)+(94 * g s)]]
```
[Try it online!](https://tio.run/##PY3NCsIwEITveYp1T9USFCvSCvoKgtdlhdBuf9BGSeLVV4@RVucyHwMz46SJF2mIY3eA9mVr8kwyhF4c4hE8bZgyXRSQQzA3Wd@ND@CXeVbtYAVdQubYPpyYugcPpCAJcbLrD97/YDHT/jzDVtsSFU/FpxtsAEp7YxpDfcLvBSuOHw "Red – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~36~~ 32 + ~~26~~ 23 = 55 bytes
**To base 94:** (Commandline options: `-Minteger -n`)
```
do{print chr$_%94+33}while$_/=94
```
[Try it online!](https://tio.run/##K0gtyjH9/z8lv7qgKDOvRCE5o0glXtXSRNvYuLY8IzMnVSVe39bS5P9/QxMjY2MjI8N/@QUlmfl5xf91fYHqU9NTi/7r5gEA "Perl 5 – Try It Online")
**From base 94:** (Commandline Options: `-pF`)
```
map$\=$\*94-33+ord,@F}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlxlYlRsvSRNfYWDu/KEXHwa22@v9/I908i3/5BSWZ@XnF/3V9TfUMDA3@6xa4AQA "Perl 5 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 62 + 27 = 89 bytes
**To Base 94:**
```
param($a)for(;$a){$a-=$r=$a%94
$a/=94
$n=[char]($r+33)+$n}"$n"
```
[Try it online!](https://tio.run/##RY9dCsIwEITfc4o1rDalLdYkqEXiFTyAiASJP1DTGgWFWq9ek1bwab6dnYWdunoadz@bsuzwURUSFDRdrZ2@MtTxsXJs5bVBnSl0CvW4kAT1VAWxans4a7dj6BIh4gRtS9HSriV4LE@/Zf7iC3lI4T/NBGF5ClEUp4TNPNCeCuHxM6AM7qhnnvMQnm@GuORCcB6ueGaXUQxvGDcEAC@2TgHNq/YNcB8cZ@6eJzD0CgHv0qCQrYcoTcKn254zc@tvdqTtvg)
**From Base 94:**
```
$args|%{$n=$n*94+$_-33}
+$n
```
Expects input via [splatting](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting).
[Try it online!](https://tio.run/##Rc7RCoIwFAbg@z3FSY6ZqaDbqLwweoMeIEIklgY2bV4kqL362pTo7js//4G/bd5CdZWoa4131TxTDhkMGgtVdqM7oMxQblMeYB4xNpEApZ4I3usyu9yqQl3jnu75LYT/lTCy8bwQYj80cIySWR@jlC3hyprP3p2NaUyXOo3kwX5wyhiliQ8juAMBwIdsQ0DRt2Ye5jZRojNew2/2yVRM7tgqRMel7AR262V2JF7z15VM@gs)
[Answer]
# [Julia 1.0](http://julialang.org/), 40+46=86 bytes
### To Base 64, 40 bytes
```
!x=reverse(join('!'.+digits(x,base=94)))
```
### From Base 64, 46 bytes
```
~x=sum(@. 94^(length(x)-1:-1:0)*((x...,)-'!'))
```
[Try it online!](https://tio.run/##VY1BCoMwFET3nsJk4/9Wg8ZQaovgDXqBUrA0aMQqGG2z8uqpUAoJzGLgMfP6dVBNbqwlpprlW85aQj@pESISscNTtWrRYJJHo2VVCkS8bKbS6wtqFpbiDoMc26UDg2l@3pNhDGAYYwmm@wOirXU3fUICGQa/ugElFIPgD3IH3KhLysJBm0eEN/L@eMZd1/HqyQQvCs5dJ0/HE0X7BQ "Julia 1.0 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 172 bytes
```
def t(n):return"0"if n<1 else t(n//94).lstrip("0")+''.join(map(chr,range(33,127)))[n%94]
def f(n):return ord(n)-33 if len(n)<2 else f(n[1:])+(ord(n[0])-33)*(94**(len(n)-1))
```
[Try it online!](https://tio.run/##TY3LCoMwFET3fkUQivf6zgOK4p@IC6mxWuxVYrro16exLtrlYc7MbG87rSSdG/TILBDWRtuXobAM55FRw5ledn0kRVEpzJfdmnkDH2MSRfljnQme/Qa3yaSmp7sGKVMurojY0qVSXXAMj79htprBUyYl8weLJg@NOF@81vK6wwS@Ult2h4cxVCqO4XQzjug2M5MFC1wJKYXgmPruHyIG7gM "Python 3 – Try It Online")
Based off [this](https://stackoverflow.com/questions/2267362/how-to-convert-an-integer-in-any-base-to-a-string) answer on StackOverflow
]
|
[Question]
[
A [variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity) (also referred to as **[VLQ](https://en.wikipedia.org/wiki/Variable-length_quantity)** or `uintvar`) is a way to encode up to a 28 bit integer value using only as many bytes as necessary. This was used in [MIDI file format](https://www.csie.ntu.edu.tw/%7Er92092/ref/midi/#vlq) as a way to minimize the size of certain event data.
The way it works is fairly simple. As a big-endian series of bytes, the most significant bit (MSB) of each byte is a `1` to indicate that another VLQ byte follows. The remaining 7 bits of each byte make up the decoded value.
**Example (from Wikipedia):**
`[ 0x86, 0xc3, 0x17 ] => 106903`
[](https://i.stack.imgur.com/WbC4p.png)
Additional references: [Wikipedia](https://en.wikipedia.org/wiki/Variable-length_quantity).
**Challenge:**
Given a variable-length quantity, convert it to it's integer value.
**Input:**
A list of one to four bytes or a 32-bit value type representing a valid VLQ of an integer.
**Output:**
The integer value of the VLQ input.
**Rules and scoring:**
* This is code-golf, so shortest answer in bytes for *each language* wins.
* [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) and [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) apply.
* [Loopholes forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) (of course).
* Please provide link with a test for your code ([TIO.run](https://tio.run/), etc).
* A clear explanation for your answer is highly recommended.
* Built-ins that handle this conversion are not banned, however *not* using them is a lot more interesting.
**Test cases:**
```
Input (VLQ) Output (int)
[ 0x00 ] => 0
[ 0x07 ] => 7
[ 0x7f ] => 127
[ 0x81, 0x00 ] => 128
[ 0xC0, 0x00 ] => 8192
[ 0xff, 0x7f ] => 16383
[ 0x81, 0x80, 0x00 ] => 16384
[ 0x86, 0xc3, 0x17 ] => 106903
[ 0xbd, 0x84, 0x40 ] => 1000000
[ 0xff, 0xff, 0x7f ] => 2097151
[ 0xC0, 0x80, 0x80, 0x00 ] => 134217728
[ 0xFF, 0xFF, 0xFF, 0x7F ] => 268435455
```
Note: you are not required to use hex literals to represent a byte as your input or output. You may use decimal literal (`[ 129, 128, 0 ]`), integer (`0x80818000`) or any other reasonable byte/octet representation if better suited to your platform. Format is flexible as long as it represents 1-4 byte/octets.
Golf away!
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 8 bytes
```
128(⊣⊥|)
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R2wRDIwuNR12LH3UtrdEEihxaoXNohYaBpoa5poahEZiwVAByDS2NQJSRqakCXBioFSxlbKJgaGmqYGQMZFsAhY2NFMxMIGoR6oH6QeqhemByMPl/@QUlmfl5xf91iwE "APL (dzaima/APL) – Try It Online")
### How:
```
128(⊣⊥|) ⍝ Anonymous function
128 | ⍝ Input modulo 128
⊣⊥ ⍝ Decoded from base 128
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 24 bytes
```
a->fromdigits(a%128,128)
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9R1y6tKD83JTM9s6RYI1HV0MhCB4g1/ycWFORUaiQq6NopFBRl5pUAmUogjpJCmkaipqZOdLRBhYFBrI4CiDaH0OZpENrCUEcBIetsgMxLSwPxUFVaoKiwMAPxko1BpCHU5KQUsDoTEGmCYhKqeRC7LAwwTXVzA/GQSXO32FjN/wA "Pari/GP – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
128#.128|]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DY0slPWARE3sf00urtTkjHyFNDU9OwUDa3NrQyMQtgSyDS2NgKSRqakCTAyoBSRubKJgaGmqYGRsbWgBFDQ2UjAzAauDqwXqBKmFqIfJQGW5/gMA "J – Try It Online")
Taking inspiration from J Salle's APL answer.
* `128|]` Remainder of the input numbers divided by 128
* `128#.` Interpreted as the digits of a base 128 number
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
```
Fold[128#+#2&,#~Mod~128]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@98tPycl2tDIQllb2UhNR7nONz@lDsiNVfsfUJSZVxLtmVeSmp5aFFwC5KVHK@soGJrpKBjFKujaKbhFK8fGKqgp6DtwVVcb1OooVJuDCEMjKGWpowAWNbQ0grKMTE2BBiDJA22CKTI2AXItgfJGxmC@BUjaGKjTzASuFUU/yFSwfoQhCEVwlbX/AQ "Wolfram Language (Mathematica) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes
```
#~Mod~128~FromDigits~128&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@1@5zjc/pc7QyKLOrSg/1yUzPbOkGMRV@x9QlJlXEu2ZV5KanloUXALkpUcr6ygYmukoGMUq6NopuEUrx8YqqCnoO3BVVxvU6ihUm4MIQyMoZamjABY1tDSCsoxMTYEGIMkDLYIpMjYBci2B8kbGYL4FSNoYqNPMBK4VRT/IVLB@hCEIRXCVtf8B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
%Ø⁷ḅØ⁷
```
[Try it online!](https://tio.run/##y0rNyan8/1/18IxHjdsf7mgF0/8Ptz9qWuP@/390tEGFgUGsDpcCiGEOZZinQRkWhjoKSAqcDVC4aWkgLppiC1Q1FmYgbrIxiDSEmZ@UAlZpAiJNUE1DMxNio4UBFpPd3EBcZNLcLTYWAA "Jelly – Try It Online")
Equivalent to [alephalpha's Pari/GP answer](https://codegolf.stackexchange.com/a/189476/59487).
Method: Given \$n\$, output \$n \mod 128\$, converted from base \$128\$ to decimal.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
žy%žyβ
```
[Try it online!](https://tio.run/##yy9OTMpM/X9u6/@j@ypVgfjcpv@1h3b/j442qDAwiNVRANHmENo8DUJbGOooIGSdDZB5aWkgHqpKCxQVFmYgXrIxiDSEmpyUAlZnAiJNUExCNQ9il4UBpqlubiAeMmnuFhsLAA "05AB1E – Try It Online")
ಠ\_ಠ Why do both Jelly and 05AB1E have 2-byte constants for `128`? Well... It's \$2^7\$. But surely those bytes could be used for something better, right?
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
å→♂á╣>nt
```
[Run and debug it](https://staxlang.xyz/#p=861a0ba0b93e6e74&i=[0]%0A[7]%0A[127]%0A[129,+0]%0A[192,+0]%0A[255,+127]%0A[129,+128,+0]%0A[134,+195,+23]%0A[189,+132,+64]%0A[255,+255,+127]%0A[192,+128,+128,+0]%0A[255,+255,+255,+127]&a=1&m=2)
Algorithm:
* Convert each byte to fixed-width 7 bit array.
* Flatten bit arrays into one.
* Convert bit array back to number.
[Answer]
# [Python 3](https://docs.python.org/3/), 58 49 bytes
*-9 bytes thanks to @Chas and @ar4093*
```
lambda x:int("".join(bin(a|128)[3:]for a in x),2)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKjOvRENJSS8rPzNPIwmIE2sMjSw0o42tYtPyixQSFTLzFCo0dYw0/xcUgZSmaUQbVBgYxGpqciELmKMJmKehCVgY6mDR52yATTQtTQeXCRZYNViYAUWTjYGEIbpDklJAukyAhAlWa7DbBXaXhQFOC93cdJAJczeg/H8A "Python 3 – Try It Online")
or
```
lambda x:int("".join(f"{a%128:07b}"for a in x),2)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKjOvRENJSS8rPzNPI02pOlHV0MjCysA8qVYpLb9IIVEhM0@hQlPHSPN/QRFIaZpGtEGFgUGspiYXsoA5moB5GpqAhaEOFn3OBthE09J0cJlggVWDhRlQNNkYSBiiOyQpBaTLBEiYYLUGu11gd1kY4LTQzU0HmTB3A8r/BwA "Python 3 – Try It Online")
Input via list of integers.
Python's `bin` function adds "0b" to the beginning of the string, so those have to be taken off before they can be concatenated. It also doesn't keep leading zeros, so if there aren't any (aka the last byte) those have to be added back in. And if there is a leading one (aka all but the last byte) that must be removed as well. Thanks to @Chas for figuring out that by always setting the first bit, I can just remove the first three characters and be done.
Apparently (according to @ar4093) the `format` function allows not only not having the '0b' prefix, but also removing the first bit and padding to 7 characters all at the same time.
[Answer]
# JavaScript (ES6), 29 bytes
*-2 bytes thanks to @Shaggy*
Takes input as an array of bytes.
```
a=>a.map(p=c=>p=p<<7|c&127)|p
```
[Try it online!](https://tio.run/##jZDBDoIwEETvfgUnAwniblvYklgvJvyE8VCrNRqVRo3h4L@jaNCAou5hTvMys7PRZ300h7U7Dfb5YllaVWo11tFOO98po8ZOudGILqaPjIKLK02@P@bbZbTNV771p977QQHgzYLAGw496P3lp9pPf/nJ1v5bqa8EFBLDRiNk8gcxgSYhMWU/EGvDZq2ES97B1JVkK6ZiRDeTVG7DK8XnXAhJCt1B88U9SFQqXkFwv07q8Uz7JQYpYYxvVL2XhI9PccGQ6MPmUGRZ2FLKnmmJFDwWcVxeAQ "JavaScript (Node.js) – Try It Online")
[Answer]
# APL+WIN, 22 bytes
Prompts for a vector of integers:
```
2⊥¯32↑,0 1↓⍉(8⍴2)⊤¯4↑⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4bPepaemi9sdGjtok6BgqGj9omP@rt1LB41LvFSPNR15JD602AMkA9/4Gq/6dxGXClcRkamQNJI1NTBQjL0MJSwdDYSMHMBCoMw0BpAA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
¯4↑⎕ Pad the vector to 4 integers from the right.
⍉(8⍴2)⊤ Convert to a matrix of 8 bit values.
,0 1↓ drop the MSBs and flatten to a vector.
2⊥¯32↑ pad bit vector to 32 bits starting at LSB and convert back to integer.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü╫ôà¡k2Wù}a☺
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=81d79385ad6b3257977d6101&i=[0]%0A[7]%0A[127]%0A[129,+0]%0A[192,+0]%0A[255,+127]%0A[129,+128,+0]%0A[134,+195,+23]%0A[189,+132,+64]%0A[255,+255,+127]%0A[192,+128,+128,+0]%0A[255,+255,+255,+127]&a=1&m=2)
### Unpacked (14 bytes) and explanation:
```
rk128%128i^#*+
r Reverse 'cuz big-endian
k Fold from the left using block:
128% Modulize by 128
128i^# Push 128 to the power of (one plus the iteration index)
* Multiply
+ Add to the total
Implicit print
```
Stax has builtin base conversion, but it only works on strings. It *almost* works on lists of integers, though; the problem is in Stax's handling of `0`.
A string is a list of integers. When you're using such a list as a string, any zeroes are automatically converted to 32 as a nice shorthand for spaces. Since the builtin `|b` for base conversion treats its operand as a string rather than as a raw list of integers, any case with a zero will fail.
### 10 bytes, fails on zeroes
```
Ç┘_A♥∙QZ►╣
{128%m128|b Unpacked
{128%m Modulize each by 128
128|b Convert from base 128
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=80d95f4103f9515a10b9&i=[0]%0A[7]%0A[127]%0A[129,+0]%0A[192,+0]%0A[255,+127]%0A[129,+128,+0]%0A[134,+195,+23]%0A[189,+132,+64]%0A[255,+255,+127]%0A[192,+128,+128,+0]%0A[255,+255,+255,+127]&a=1&m=2)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 48 bytes
Takes an integer in big-endian order as input, which is the same order as a byte array.
```
f(i,j){for(j=0;j|=i&127,i&128;j<<=7,i>>=8);i=j;}
```
[Try it online!](https://tio.run/##fZPfT8IwEMff91dcNJh2Vul@QEtGeVDDE/HNxAR5mINKFxwGppLg/nVnO1jcHLNZLu3dp9@77nLR1UsU5blEisR4L9cbFAsaxF9CXTguI8byIB4Ohd6PRoLjQIk4yPJzlUSr9/kChtt0rtbXy5H16wo3b2FXJYvUuC2VpPAaqgR9rNUcw97qdqfQXHRHKcxAjIC2E@xAsFaCyQOhi28wdMcdUsmjn3aCuaVVhjsD9wQkJakm63vcq1BlIl6TMpRfp/omHnnGOsenObQ/oHWx53kh5hvrl2K0WDXuUFS9NJcOmNNzoADLx3F6ojrPdx3GXA4lOx6TP5aNj6J97ns9v9fTLEC0DDdgb6czsbdMIcg4pjO8N@IZafhY08fGTV/Zq2ak7FAzUpbZpsZbbx5acXtsRTN@c1ftQVvm9vynfvz/Kn@07h8mE73JCNh2qk0U6JMZLVsRiANLn8z0pmIbgJ0GkF5emlkzV5VAGrSxccdCIlvhggd42@iARGc70aH8kYBEO1xsAXXe8VNyRmCZrpOVuaKz6A@btJmV5d@RXIUv2/zq8wc "C (gcc) – Try It Online")
## [C (gcc)](https://gcc.gnu.org/), 53 bytes
If a byte array is needed:
```
f(c,j)char*c;{for(j=0;j|=*c&127,*c++&128;j<<=7);c=j;}
```
[Try it online!](https://tio.run/##fZPfb9sgEMff/VecOnUCQhf8I4GI0Id1ylO1t0mTsjx4pDRYmVMl7hYp878@D5xYs@t4yDrB3YfvHT7Qd89aV5VBmmZYb9I90fJkdnuUKSaz34ro92HEKdGjkZsImc3nimOpVSbL6p3N9fZ1/QTzQ7G2uw@b@@CfK92/pGObPxXeHdi8gB@pzdHPnV1jOAXj8RL6gx0ZgxWoe2DDBD8TfJDg5ky4ynsMO4qQtvK4Q11hHlibEeEsugIZQ9vJprGIW1STSHSkPJV0qamP69jb8HK0kE1nrCv2fV2LJd4mjRirR4c7F9UtLWIzHk5CqMHmcIJdqS5OopDzSEDDLhb0jeWLi@hUJPEkmUwcC@CvDpDDcqVOgS8EecdyhU9evKQ9H@/7@KLva3rVjzQd6keaMofUxODOcyseLq3oxz9@avdgKPNw/ms//v8qb7Q@f3l8dJOSAiGFM1q6lX9axFLIZOBW/u0W6iCBFBKK0ci/Nb/VKuRAgr07UwaRAtc8wMveBQy6OapbJr5SMOiI6ymg21f8Lb@hsCl2@RYRi10W92GftgzK6o822/T5UN39@gs "C (gcc) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~14~~ 13 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
♣%hrx♣▬^mÅε*Σ
```
Input as a list of integers.
[Try it online.](https://tio.run/##y00syUjPz0n7///RzMWqGUUVQOrRtDVxuYdbz23VOrf4//9og1iuaHMgNjSCkJY6IBFDSyMwbWRqqoOQMTSygMgam@gYWprqGBmDOBZACWMjHTMTqHokPUBTQHpg@mCyMBUA)
I have the feeling this can be shorter.. It's a bit annoying that MathGolf has a 1-byte builtin for the constant `128`, but no base-conversion (except for binary/hexadecimal).
**Explanation:**
```
♣% # Take modulo-128 on each value in the (implicit) input-list
h # Push the length of the list (without popping the list itself)
r # Pop and push a list in the range [0, length)
x # Reverse the list to (length, 0]
♣▬ # Take 128 to the power of each value in this list
^ # Zip the two lists together to create pairs
mÅ # Map each pair to (using the following two commands):
ε* # Reduce by multiplication (so basically the product of the pair)
Σ # After multiplying each pair, take the total sum
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# [PHP](https://php.net/), 42 bytes
```
foreach($argv as$a)$r=$r<<7|$a&127;echo$r;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLUhOTMzRUEovSyxQSi1USNVWKbFWKbGzMa1QS1QyNzK1TkzPyVYqs////b2hs8t/Q0vS/kTEA "PHP – Try It Online") and [verify all test cases](https://tio.run/##XVJbb4IwFH6WX3Fimk0TEstFwaDbwzKzhyXz3RlToQwWKaQU57Ltt7tTqFPHwwn5bucrtMqq4@y@yirLIorXqoY5rKzeCuiBwtqGXq83GgHtkOCMBAZJz5DjGjB07Gu744Yd80DBRsZQyITO1O2oNLVPecY08ULvMjCkbSxtFUbgg1FMNBd7ejrBn4JOptRkbJM2w9fTP2fQ9rmscFUEJS6dBs7YOR3g3OSyj47yfNcJAjcE02mxsP/NYGG07iT0vbE/HqN2HVlWWkrO4mwA5h@wGt9gCF8WAMprrqCpgIt9LktRcKEAHaAtoA1anyv4KJtdAlsOshGQyrKAuCwKJhLY5YIDk2815vE4K@G9LsWGi7hM@AAJyT43BasGtwmy/HBrt9uHNvRf1fwO@hH6OlUj6ixPlW5qA8HI/YquYRi1NfOi2THFDb42vdHbAniziIqOp7N2GKsJGxI5J3I2C74Ju8FbFOmKREZHU3b5tNw8vjzrErieqwGRuFBvlFyvuPgulvVz/AU).
Input via command line args, output to `STDOUT`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~10~~ 8 bytes
Takes input as an array of integers.
```
muIÑ ìIÑ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=rqRuRw&code=bXVJ0SDsSdE&input=WyIweDg2IiwiMHhjMyIsIjB4MTciXQ) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=rqRuRw&code=bXVJ0SDsSdE&input=WwpbIjB4MDAiXQpbIjB4MDciXQpbIjB4N2YiXQpbIjB4ODEiLCIweDAwIl0KWyIweEMwIiwiMHgwMCJdClsiMHhmZiIsIjB4N2YiXQpbIjB4ODEiLCIweDgwIiwiMHgwMCJdClsiMHg4NiIsIjB4YzMiLCIweDE3Il0KWyIweGJkIiwiMHg4NCIsIjB4NDAiXQpbIjB4ZmYiLCIweGZmIiwiMHg3ZiJdClsiMHhDMCIsIjB4ODAiLCIweDgwIiwiMHgwMCJdClsiMHhGRiIsIjB4RkYiLCIweEZGIiwiMHg3RiJdCl0tbVI) (header in both converts from input format used in challenge)
Saved 2 bytes by taking inspiration from [alephalpha's solution](https://codegolf.stackexchange.com/a/189476/58974).
```
muIÑ ìIÑ :Implicit input of integer array
m :Map
u : Modulo
I : 64
Ñ : Multiply by 2
ì :Convert to decimal
IÑ : From base 64*2
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
I↨﹪θ¹²⁸¦¹²⁸
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXDNz@lNCdfo1BHwdDIQhNCampa//8fHa1gUOFsoAMkLZBIAwOF2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array. Explanation:
```
θ Input array
﹪ ¹²⁸ Elementwise modulo 128
↨ ¹²⁸ Convert from base 128
I Cast to string for implicit print
```
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
```
f=lambda a:a>[]and a[-1]%128+f(a[:-1])*128
```
[Try it online!](https://tio.run/##dZLPboMwDMbP4yl8mQJbNiXhTwISXCrxEhmHdBANiVJUItQ9PQulVLSsPliyvp8@27K7X/NzbNk46rRRh32pQCUqk4VqS1DygxavlIl37SqZ2MJ7s9Voqt7sVF/1kII8qM6tBtVg89l3TW1clGbI80AfT2CgbgEh5EjYBjkTAgWkGZBnOp91/kTnetYpeyTIWVC86mCn3hA7siYEjdkG0Rqv20S@8G/M0kLc2UxMsGaiSf32p0yv61ASxWRttC8vRsGUg8WIXGJFzcPcj8RIzGlIwWLLQoL8M5UfMMo5EzCTeY4fMs@vhpEI/DAIQ3u15Z5fLfIkTYrCcaajKjxMZ709QeK8dKe6NVaAAYN9FW/8Aw "Python 2 – Try It Online")
[Answer]
## Windows Batch, 76 bytes
```
:a
@set/ax="%1&127",y=y*128+x
@if %2. neq . @shift&goto:a
@echo %y%
```
Pass parameters prefixed with "0x" and space between (e.g. 0xC0 0x80 0x80 0x00).
[Answer]
# ARM Thumb-2 machine code, 16 bytes
```
00 02 c0 01 04 c9 52 06 00 eb 52 60 f9 d2 70 47
```
Assembler source with pseudo-C:
```
.syntax unified
.arch armv7-a
.globl vlq
.thumb
.thumb_func
// Input: r1: array of **uint32_t** containing VLQ bytes
// Output: r0
vlq:
// initial accumulator
movs r0, #0 @ acc = 0;
.Lloop: @ do {
// Shift accumulator for next value
lsls r0, r0, #7 @ acc = acc << 7;
// Load next vlq byte, advance ptr
ldmia r1!, {r2} @ tmp = *ptr++;
// Shift left so the continuation
// bit is in the carry
lsls r2, r2, #32 - 7 @ carry = tmp & 0x80;
@ tmp = tmp << (32 - 7);
// Insert it into the accumulator,
// not affecting the flags (wide)
add.w r0, r0, r2, lsr #32 - 7 @ acc = acc + (tmp >> (32 - 7));
// If there is no carry, loop again
bcs .Lloop @ } while (carry);
// Return
bx lr @ return acc;
```
This function can be called from C with a dummy parameter to place `data` in `r1`.
```
uint32_t vlq(uint32_t dummy, const uint32_t *data);
// Note: uint32_t, not uint8_t
const uint32_t vlqs[] = { 0x86, 0xC3, 0x17 };
printf("%u\n", vlq(314159 /* dummy */, vlqs));
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 40 bytes
```
->a{a.map{("%08b"%_1)[1..]}.join.to_i 2}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3NXTtEqsT9XITC6o1lFQNLJKUVOMNNaMN9fRia_Wy8jPz9Ery4zMVjGoh6vcWKLhFRxtUOBvoKBhUWCCRBgaxsRA1CxZAaAA)
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 40 bytes
Port of [my Ruby answer](https://codegolf.stackexchange.com/a/253522/11261), just for fun.
```
:*&(:%&"%08b"|~:[]&(1..))|:join|~:to_i&2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWNzWstNQ0rFTVlFQNLJKUauqsomPVNAz19DQ1a6yy8jPzgCIl-fGZakYQ9XsLFNyiow0qnA10FAwqLJBIA4PYWIiaBQsgNAA)
## Explanation
```
:* & ( # Map with…
:% & "%08b" | # Format (%) as binary padded to 8 digits, then
~:[] & (1..) # take range of characters 1..end
) | # then
:join | # join, then
~:to_i & 2 # convert to int as base 2
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5 bytes (10 nibbles)
```
`@;128.@%
```
```
`@;128.@%$@ # = program with implicit arguments added
`@ # convert from base
128 # 128
; # (and save that value)
@ # the input values
. # each
%$ # modulo
@ # the saved value of 128
```
[](https://i.stack.imgur.com/V5qrm.png)
]
|
[Question]
[
Given a list of positive integers \$\mathcal I=I\_1,I\_2,I\_3,...,I\_n\$ and a base \$b>1\$ return their "carry-less sum", i.e. represent \$\mathcal I\$ in base \$b\$ and sum digit-by-digit discarding carry.
Worked example:
```
I = 13, 2, 9; b = 3
```
In base 3:
```
111
+ 2
+ 100
-----
= 210
```
and back to base 10:
```
desired output: 21
```
More test cases:
```
I=[1000, 576, 23, 1, 141], b=12 => 1573
I=[1000, 576, 23, 1, 141], b=2 => 307
I=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], b=4 => 11
I=[1, 2, 3, 5, 8, 13, 21, 34, 55], b=5 => 77
I=[900, 100], b=10 => 0
```
This is code-golf shortest function or program per language wins.
Standard rules and loopholes apply.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 11 bytes
```
{x/x!+/'x\}
```
[Try it online!](https://ngn.codeberg.page/k#eJx1zDESwjAQQ9E+p/hUwFDY8nqzgbNQ5wyeYbg76wyUqNWT9sdrlHG6lfN4vpflsqN2RbVWPFaaIdTFkYI8bKL/JpHVmKanoWF0nJVg456r75Em8R/xLGU0Yan9IBEfTF4cRw==)
First time writing a curried function in K...
Works exactly like [coltim's answer](https://codegolf.stackexchange.com/a/251295/78410), except for how the function is called. This one is a monadic function that takes the base and returns another monadic function that takes an array and returns the answer. You can call it like
```
(f 12) 1000 576 23 1 141
f[12][1000 576 23 1 141]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 56 bytes
```
f=lambda I,b:sum(I)and sum(I)%b+b*f([x//b for x in I],b)
```
[Try it online!](https://tio.run/##jcvRCoIwFMbx@57iuwm2OuCmTivwAfYM4oVDRkJOMQN7@nWyuyAIzsXH4fefnst1DFmMvrq1g@taWHKX@2MQVrahw2ft3dEdvKjXJHHw44wVfYBtyMk4zX1YhBe2qrVSimDKgpBmBM2X64bgKp1KuftLfkMGBCY5cwL7knAinLlQW5D/CMzmNK@Uf9m7N1tgpIwv "Python 3 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 18 bytes
```
R($+R*:SgTDa)%aFDa
```
Takes the base, followed by the integers, as command-line arguments. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJSKCQrUio6U2dURGEpJWFGRGEiLCIiLCIiLCIxMiAxMDAwIDU3NiAyMyAxIDE0MSJd)
### Explanation
>
> [This challenge is] a good example of why base-conversion builtins should be little-endian
>
> - [ais53](https://chat.stackexchange.com/transcript/message/61848059#61848059)
>
>
>
```
R($+R*:SgTDa)%aFDa
a is first command-line arg; g is list of args
Sg All but the first command-line argument
TDa Convert each to a list of integers representing base-a digits
R*: Reverse each list of digits
$+ Add the lists of digits together itemwise
( )%a Take each digit sum mod a
R Reverse again
FDa Convert from base-a digits to decimal
```
[Answer]
# [R](https://www.r-project.org), 42 bytes
```
`/`=\(I,b)`if`(s<-sum(I),I%/%b/b*b+s%%b,0)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hY_BCsIwDIbvPkVACu3MWLOtdoL13nfwUCoUPHhx7mm8TMH38erbGLcp4kUIJPx8X0LOl2N_Te7WnVLePLJQBLeVHqMK-xRku87b7iC9Qi8KEYuYxUUrREStJuOepHc7SVprBGOXCGWFQFw1KYToqFRzcBsgY6vZP3hiK23fKCMIDNUsILBhERqEFTt6UOppPf0aZgCJp5Kz6rXADIYZDfu58Z3S-Fffj_0J)
The same approach as other recursive answers.
Renaming the function to `/` makes `I%/%b/b*b` evaluate in the correct order (first `%/%`, then `/`, then `*`) and saves a byte compared to `f(I%/%b,b)*b`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
bUS%Uḅ
```
[Try it online!](https://tio.run/##y0rNyan8/z8pNFg19OGO1v@Hl@trRv7/H80VHW1oYGCgo2BqbqajYGSso2AIRCaGsUDSKFYHjzRUFsjQUQCKmwDV6CgAFZnrKFjoKFgClRkAVZmgqjIFSxoCWUZAMWOQJlOgKtNYrlgA "Jelly – Try It Online")
```
b Convert each to base b
U reversed,
S sum corresponding digits,
% mod b,
U reverse back to big-endian,
ḅ convert from base b.
```
>
> a good example of why base-conversion builtins should be little-endian
>
>
>
-- [ais523](https://chat.stackexchange.com/transcript/message/61848059#61848059)
Incidentally, having to reverse twice only costs one byte due to dyadic chaining rules requiring something between `%` and `ḅ` anyways, but in cases like this I'd have to agree that
>
> I like the monadic link rules, but not the dyadic link rules
>
>
>
-- [ais523](https://chat.stackexchange.com/transcript/message/57320257#57320257)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
WΣθ«⊞υι≧÷ηθ»I↨⮌﹪υηη
```
[Try it online!](https://tio.run/##HYy7DoIwFEBn@hV3vE3qoEyGycfiQEJwJAwNNPQmtZW@HIzfXtHlnOXkTFr6yUlTykuTUYD39MCVc3izqktBYxJAvGFVK5@nEGixPS064s3GK2WalQAtYN2KD@s82YgXGSKeZVDYq6z85tbNybjfSXP@B29KGYZ9LeAg4DgKqMeyy@YL "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WΣθ«
```
Repeat until the (sum of the) input list is zero.
```
⊞υι
```
Push the sum to the predefined empty list.
```
≧÷ηθ
```
Vectorised integer divide the input list by the input base in place.
```
»I↨⮌﹪υηη
```
Vectorised modulo the list of sums by the input base, then interpret that as a number in the input base, and output the result. (The `Reverse` is there because base conversion isn't little-endian as it "should" be...)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
τR∑Ṙ$%¹β
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLPhFLiiJHhuZgkJcK5zrIiLCIiLCIxMlxuWzEwMDAsIDU3NiwgMjMsIDEsIDE0MV0iXQ==)
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
[#.[|[:+/#.inv
```
[Try it online!](https://tio.run/##JYyxDsIwDET3fMWVDhHCBLsNLbHEhMTExBoxISpggI2p/566VDov957vXVKlcusqTd67VfADjgoPAkPttgGn6@Vcch3ymHWzq8Pr8ytr5x735xctBkhLaAhpaaSZK2Ym7PvOiFGxRFl4nPH/wUA0iWBWTzjYhHlcJg "J – Try It Online")
* `#.inv` base digits
* `[:+/` sum elementwise
* `[|` mod by base
* `[#.` back to base 10
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes
```
{y/y!+/'y\x}
```
[Try it online!](https://ngn.codeberg.page/k/#eJyFzz1PwzAQBuA9v+KQkGiEU+fsuE5jlZ2drVRqGpw26kcgTlGiCn47Z3ehA2L1+9yd37q4jHy8e+QP4+vwFUUvxeV+OX53RQ1TGMy63ZvJui6bgxnMaLp45c1yghIEzI2MjcBVeEjTFJSegZCAgBkaFLFBpeUfMaUy1deQdknIQMEMNOQwB0xNRtP4K1YU+KsIkqQyKjaaxiMe7fr+3RWcV+2b3baHeur6strbodqVp62dVu2Rf5yt65v25LhQKHLJq7LrxuRgnUvc+Zhsm097SspkUzqbbKLoebFEyUAwmK8YbBYSFk90+hpQFea7UE4Gma8TFArPfOd/YHDU/srCHQIZYQakNYOcLpNPA8/CWrzVKqDwS3qTflgFrbzW+gcuOm6M)
* `y\x` convert list input `x` to base-`y`
* `+/'` sum each "row" of the above
* `y!` mod the sums by `y`
* `y/` convert back from base-`y` (to base-10)
[Answer]
# JavaScript (ES6), ~~53~~ 52 bytes
Expects `(base)(list)`.
```
b=>g=a=>(a=a.map(n=>(s+=n,n/b|0),s=0),s&&s%b+b*g(a))
```
[Try it online!](https://tio.run/##jc2xDoIwEIDh3ae4RdLKCS1Qq0N5EeNQEIgGC7HGyXfHq9FEmWya5tLk@@9s79bX19N4W7vh2EytmSpTdsaaklljk4sdmaPZx8ahS6uH4OhNeKLIL6u4WnXMcj7Vg/ND3yT90LGWyYyzvRRCICi9QchyBEm3kAfO4XPSFKTS@eLXwr82F3pOi0CJIBAqKIBABY2wRdhRQ4REWCvnUn1L9QKSpoz@8hBSb6n19AQ "JavaScript (Node.js) – Try It Online")
Or **51 bytes** with BigInts:
```
b=>g=a=>(a=a.map(n=>(s+=n,n/b),s=0n),s&&s%b+b*g(a))
```
[Try it online!](https://tio.run/##nc5BDoIwEAXQvafoRtIKQgvU6qJcxLhoEYgGB2KN18cZdANLm/xJm@a/zN29Xaift/G1h@HaTK2dvK0662zFnXXpw40c8B5iCwlkXiTBSsAZRWHrY7/ruBNiqgcIQ9@k/dDxlqscBD8rKSUkTJsDzrzAoSilgosQbHGyjCltis2SYX8whTRrpZwVKmOoXxKHIdBgjpgTmXImaRm1RvQa0b@iokdOP8Xs6u9aiBgzfQA "JavaScript (Node.js) – Try It Online")
### Commented version
```
b => // outer function taking the base b
g = a => // inner recursive function taking the list a[]
( a = // update a[] (and compute the sum at the same time):
a.map(n => // for each entry n in a[]:
( s += n, // add n to the sum s
n / b | 0 // compute floor(n / b)
), //
s = 0 // start with s = 0
), // end of map()
s && // if the sum is not 0:
s % b + // compute the sum modulo the base
b * g(a) // add the product of the base and the result
) // of a recursive call with the updated list
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 34 bytes
```
b->g(a)=if(a,g(a\b)*b+vecsum(a)%b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dY5NCsJADIWvEgpCR1Po9MfWRXuRcZAZsaWgMtRW8CxuCiJewMt4G1-1GxdCSF7e-wK5Ppxpm03thltFxb3vqiB_eTYoa9-Ioql8w1BrK-Z2cd5tT_0B_syKiXwa5_YX31BQkmubYwfpjYtHOFWRFuhSC8GklJJhGDKl2ZIpipkkKpEaPdJj_i-eUggm-AkYJkAZU860AhaCSH6p9BNKqAhePB6lIFKtp9-H4Tvf)
A curried function that takes input as `(base)(list)`.
[Answer]
# [Desmos](https://www.desmos.com/calculator), 77 bytes
```
k=[0...floor(max(log_bl))]
f(l,b)=total([mod(floor(l/b^i).total,b)fori=k]b^k)
```
Function \$f(l,b)\$ takes in a list of positive integers \$l\$ and a base \$b\$.
Not too sure what little endian big endian is all about so I just did it my own way.
[Try It Online!](https://www.desmos.com/calculator/tchugtvooo)
[Try It Online! - Prettified](https://www.desmos.com/calculator/vqcwkhh9cm)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
Total@PadLeft@IntegerDigits@##~Mod~#2~FromDigits~#2&
```
[Try it online!](https://tio.run/##dc29CsIwFAXg2T6FEOh0hfw0rR2UDCIICgXdxCG0aQ3YFurdavPqMVVwczznO9zbarybVqMtta83/tKjfqhCV0dTozp0aBoz7Gxj8akIcae@coS7/dC33zKk2BeD7fBKVttaKXKL3bnUnRujkQngkE@LxWspIERKKcgsBS6AAUvYFIDxf/KBcEBAAhJSyGANOTA6W/IzGdr5DwMRZnJGGU3@DQ "Wolfram Language (Mathematica) – Try It Online")
Input `[I, b]`.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~10~~ 9 bytes (18 nibbles)
*Edit: -2 nibbles thanks to bug-fix in nibbles compiler (thanks [Darren Smith](https://codegolf.stackexchange.com/users/94929/darren-smith)!) allowing ``@` (convert from base) to work correctly on 2d lists*
```
`@@.\`'.$\`@_$%+$_
```
```
. # Map over
$ # the elements of arg1
\ # reversing
`@ $ # the digits in base
_ # arg2.
`' # Now transpose this,
\ # reverse it,
. # and map over each list
+$ # sum
% _ # modulo arg2.
`@ # Finally, convert from base
@ # arg2
```
[](https://i.stack.imgur.com/E6jeM.png)
[Answer]
# [Haskell](https://www.haskell.org/), ~~54~~ 51 bytes
```
b!l=sum[b^w*mod(sum$map(`div`b^w)l)b|w<-[0..sum l]]
```
[Try it online!](https://tio.run/##hY7LCsJADEX3/YoruFBJZR4dx4J@SanYUsHiTCvWx8Z/H@O4sK6ELELuOUmO1XA6OBdCPXHb4eaLevdY@L6ZcT/11Xm2b9r7nodzN6@fj01aiOWSM7iyDL5qO2zR9AnOl7a7YgpoTFBITYryEmkKJb@hVDEUQhCMXRGUJkiuTEZWGquT0a4/uBZ2TGeRZorAXMYOgSVLWBNy1sTniBxL5kcykeXv@W0evHeYKFmbhBc "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~88~~ 73 bytes
```
i;s;f(l,b,n)int*l;{for(s=i=0;i<n;l[i++]/=b)s+=l[i];s=s?s%b+b*f(l,b,n):0;}
```
[Try it online!](https://tio.run/##lVPZbtswEHzPVywECNBBIzqrJoyah6JfYQuBRVOpEJs2TAV1a/jXqy4P2QqRlwq26N2ZWS5nabZ4ZWwceyppF2xJS0TYiyHa0nO3Pway7uuE9k@Cbpd9HDf3dRvKuMagobKWz9Jv4zaahI8JvYyoht26F0EI5zvARyUGLoeXZNlADec0J5AReLjQj3Bq4SRJCJTVF2QhM8VPkbrc7D@4ueXqXZFVoIIASioCX7EPFCWupnA0pabqzjGXqxKlq2mNRvWRaZ1i3UiRZklDMn4Qe3C7ZnbN7Vq4Owgjlv0fvu8CUyO8t2FkYwJzPHXw1MEzB88cPHfw3MELBy/CWdP8dOBs4BvTtnIuLSs8XZ6g9SmGVWXZbC/kAOzn@hjhm7M3fjQib3X6ka1OD9/xW3oE5nHuWTXeVAjUhr3Y8BPKEmp/Pk3NTq3c2r1mKMSxZoe6mLm0t6FhOTM4zWnoHAZhURzNZ3D73nVLMUvu@I4dfgcqj0PGKxKJ0JFMFdtPK0qEO6tvCbhqjvDVdVd/s8lahPYIffrwylHP4YikLvB86W/Q8v5Z@f7oLXEZ8I8/23JiNgT8DSy@qbcvV8LTzUlynSWvazkJL3eX8S/rtutXOS5@/QM "C (gcc) – Try It Online")
Inputs a pointer to an array on integers, a base, and the length of the array (because pointer in C carry no length info).
Returns the carry-less sum.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
вí0ζOR¹%¹β
```
Inputs in the order \$b,\mathcal I\$.
[Try it online](https://tio.run/##ASQA2/9vc2FiaWX//9Cyw60wzrZPUsK5JcK5zrL//zMKWzEzLDIsOV0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJhxa@f/CpsNrDc5t8w86tE710Lpzm/7r/I@OjjY01jHSsYzVMY7VUQDyDAwMdEzNzXSMjHUMdQxNDGN1DI1wyUAlgPqNdUx0THXMdMx1LHQsdQwNYnVMkORMgaIgawx1jIHKTGN1TMGSlkADgabGgtTHAgA).
**Explanation:**
```
в # Convert the values in the second (implicit) input-list to the base of the
# first (implicit) input-integer as inner lists
í # Reverse each inner list
ζ # Zip/transpose; swapping rows/columns,
0 # with 0 as trailing filler digit for unequal length lists
O # Sum each inner column-list
R # Reverse the list back
¹% # Modulo each value by the first input-base
¹β # Convert this list from the first input-base to a base-10 integer
# (which is output implicitly as result)
```
[Answer]
# [Perl 5](https://www.perl.org/), 52 bytes
```
sub f{$b=pop;&sum&&&sum%$b+$b*f((map$_/$b|0,@_),$b)}
```
[Try it online!](https://tio.run/##hZFRS8MwEIDf@yuOEUurEZOmsa4luh@gjz7NUQy0UlybkHagzP116yVzD@5FSMLlvi93B7GN28p5Hnca2j3RyhpbxeOuj2N/XhB9RfRlmyT9qyX1DdFfjK7qlBKdHubWuCQCWK@5oJBRWG4oCFD3kPENPQLGGAVZ3CJHh@PKkQHPvMZlIf4RgydYcdJCHxRylCmgXVC4w87oM9TzUJaf2zJIYUrMCf9Yoi29XZxqL/0EOIcfj3nCfkF2DgTGUbpH2H8mQDoKRONuPiykoGBF6iowIG9mwkSbYC5YkHpiXTdMAf69gVLHKg@wAPP@MiygxKhxzji8VNFh/jZ26swwztdPj904leXz1G0V/tQP "Perl 5 – Try It Online")
```
sub f {
$b = pop; #extract the base $b from the end of the param list
&sum #&sum returns the sum of the input list @_
#since &sub without parens uses @_ as params
#if sum > 0
&&
&sum % $b + #then return last base $b digit of the sum plus
$b * #$b times
f( (map$_/$b|0,@_), $b ) #the recursive result for the same list
#but with last digit removed from each list elem
#else return 0
}
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 129 bytes
```
param($n,$b)$r=@{}
$n|%{do{$r[$i++]+=$_}while($_=[Math]::Floor($_/$b))$i=0}
$l=$r.Count
-join($r|% V*|%{"+$_%$b"+"*$b"*--$l})|iex
```
[Try it online!](https://tio.run/##jZFBS8NAEIXv@RVDmWq22WjWtkaFQLDoTRQVL6WUJF1pJM3WTYJCmt9eZxOtVTw4hOzy5ntvBnat3qQuljLL3ERpucXnoN6uIx2tbMw5xgx1ENaNhfmmXy9UjXqKqePMnADnzdsyzaSN82B6E5XL2cXFdaaUJuGYjAzTwCNjFqA@mqgqLy33RaW5jXrTh6cB5fUcnPcx7jm9Af0HrotZwzapfN82lhXaFlBxCO3QFkMOJxzOGQdzE2y/53keh7F/Sg1qCvpGgkBBBjH2h/9hCR16/g@yEzmMiOdABp/DGa1AFo@1shB/GsYt125M2tD4x6yVff/XLhTnmTBBN49ZDDZwrfRVlCzd2/hFJiXUrQHzahXTO3HAOCokHfJ9TW25gABw3jFaFlVWknCAzztHZ2iB6d3DpCpKteqiZ2GXbeqhShJZFGDSPmNc@fo9ZQc@yqKcUKABvya0rwqHHA5hx10axlSwt4Cp@y59b1Lbaqxm@wE "PowerShell Core – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 76 bytes
```
I+B+O:-sumlist(I,S),S>0,maplist([A,A//B]>>!,I,Q),Q+B+W,O is S mod B+B*W;O=0.
```
[Try it online!](https://tio.run/##Hcu9CoMwGEbhW/m6afOqif0DSwNmyxQkg4M4CIUSMI0YSy8/lcKZHjjLGubwKuLXpaSZYqYp4sfPLm6Zhs1hJYeflj8MLdqqUqOUB2h0Obp96GHIRbLkw5MUU8f@bh68TE1Bg@Ccgy63K6g@gcTeWYysZga0rO69ZSYv0w8 "Prolog (SWI) – Try It Online")
-3 thanks to Jo King
More interesting, without `sumlist` or `maplist`:
# [Prolog (SWI)](http://www.swi-prolog.org), 86 bytes
```
E+H-[H|T]-B-[H//B|Y]:-E-T-B-Y.
0-A-_-A.
I+B+O:-S-I-B-Q,S>0,Q+B+W,O is S mod B+B*W;O=0.
```
[Try it online!](https://tio.run/##DYnLCoMwEEX3fsUs22YmJvYFKS0YEHQVJIKIhG4KJdA2ooVu/Pc0cOFwzp3m8ApPWn4@xorVNNZr50gn5rleB6eooi75wDNBJd2p5FnDNDOKLDXpaNHeBLYp9WjAL2DhHR6gmd71F3MVPCqCUQohEI7nE0KxR5BpB@lYwQzCNPvPd2O2PP4B "Prolog (SWI) – Try It Online")
[Answer]
# [Julia](http://julialang.org/), 35 bytes
```
i^b=any(i.>0)&&sum(i)%b+b*(i.÷b)^b
```
[Try it online!](https://tio.run/##hctBCgIxDAXQvafIxqHVIEmndXShFxEL011kLIM6oCfzAB6spu4EQcji8//LaRqk53spEtOuzw8jqz3ZprlOZyN2npZpodXrmWxMZbxIvg3ZHJiIEEK3RnAtAut5PkIEdnb2X30hHRF09koR1HYIG4StaqrY/8LhY1iT066tv6HiYMsb "Julia 1.0 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 161 bytes
```
\d+
$*
{`^([1,]+)(;1+)
$1$2;$1
T`,`_`;.*
^([1,]+;(1+);)\2*
$1
\G((?=.*?;((1)+))\2|1|(,))
$3$4
}`^,+;
;
{`\G(;1+;)|1(?<=(1+);1+)(?=1*;)
$1$2
}`^(;1+;1*);
$1
r`1\G
```
[Try it online!](https://tio.run/##dY27TgNBDEV7f4WLQfLMWNF6HwmRibbMD9CxhEEiRZoUER2bb1/uDkhUSHZzz/H17fx5ub4vD1KYlukjU0j0VU7yYvqao7jlSMFC68HouWh5K75J9MtdgD1ObYJD01FkPGzS6CIWc0Q@2ywa0dCFnu7lpNnJ0Q8VzR5nk/HpUFuwuLbkP/9WuzqWoq/tt2LTcVmsU26V984dWdM0ysNuiwixYXpztvY/AlCvEfXAyuA75Uf0wWic@z9hqHl9h6xb/cF5@AY "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert to unary.
```
{`
}`
```
Repeat until all of the input numbers have been reduced to zero.
```
^([1,]+)(;1+)
$1$2;$1
```
Duplicate the input list.
```
T`,`_`;.*
```
Sum the duplicate copy.
```
^([1,]+;(1+);)\2*
$1
```
Reduce it modulo the base.
```
\G((?=.*?;((1)+))\2|1|(,))
$3$4
```
Integer divide the list by the base.
```
^,+;
;
```
Remove the list if it's zero.
```
{`\G(;1+;)|1(?<=(1+);1+)(?=1*;)
$1$2
}`^(;1+;1*);
$1
```
Convert the sums from the input base.
```
r`1\G
```
Convert to decimal.
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 72 bytes
```
:: f ( I b -- n ) I Σ dup 0 > [ b mod I [ b /i ] map b f b * + ] when ;
```
[Try it online!](https://tio.run/##dc7BTsMwDAbg@57i3w2YNuKmWaATu6Jedpk4oR1Km7KKLiltKjRNPA3vwyt1bqvtgESkRLbz2XKepN7V3cs23jxH@DC1NSVKlyZlg0Pi98OzaG2Rusygqo33x6ourEdjPltjU9NghXgT4d2VeRdFyHGDGG@Yz2Fxy@HvD7K2gsAar1w/uIyLfXRfYMfzKw5zvneYcf61Nxar7gSSCPCIb0j@XeDPmeJpjYAm7IQQUHqJQIJAIXELBZeewZHS8h95haOUQveQyxIhFJbQeOAtSLANRzuOpKtTLPplCZJbFEM1wMFp3Z0B "Factor – Try It Online")
* `:: f ( I b -- n ) ... ;` Define a word (function) named \$f\$ that takes two arguments from the data stack and returns one. The double `::` as opposed to `:` enables lexical variables inside the definition.
* `I Σ dup 0 >` Is the sum of \$I\$ greater than zero?
* `[ ... ] when` If so, then call `[ ... ]`.
* `b mod` Take the sum of \$I\$ (which is still on the data stack thanks to `dup`) modulo \$b\$.
* `I [ b /i ] map` Divide each number in \$I\$ by \$b\$ (integer results only) and place the result on the data stack.
* `b f` Call \$f\$ on the above list with the same original base, \$b\$.
* `b *` Multiply the result of the above call by \$b\$.
* `+` Add the sum of \$I\$ modulo \$b\$ which is still on the data stack.
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 109 bytes
```
;=j!=bP;W=xP E++"=x"=j+1j"Ex";=r=m=s 1;Ws;=s=i 0;W<i j;=s+sE+"x"=i+1iE++++"=x"i"/x"i" b";=r+r*m%s b=m*m bO-rT
```
[Try it online!](https://knight-lang.netlify.app/#WyI7PWohPWJQO1c9eFAgRSsrXCI9eFwiPWorMWpcIkV4XCI7PXI9bT1zIDE7V3M7PXM9aSAwO1c8aSBqOz1zK3NFK1wieFwiPWkrMWlFKysrK1wiPXhcImlcIi94XCJpXCIgYlwiOz1yK3IqbSVzIGI9bSptIGJPLXJUIiwiMTJcbjEwMDBcbjU3NlxuMjNcbjFcbjE0MSJd)
-1 byte thanks to Aiden Chow
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 20 bytes
```
0{⍺⊥⍺|+/⍵⊤⍨⍺⍴⍨⌈⍺⍟⌈/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/LzmxqKjyUduE6ke9ux51LQWSNdr6j3q3Pupa8qh3BUiwdwuI0dMBZs8HMkDStf//AwA "APL (Dyalog Classic) – Try It Online")
**Usage:**
```
ncarry←{⍺⊥⍺|+/⍵⊤⍨⍺⍴⍨⌈⍺⍟⌈/⍵}
3 ncarry 13 2 9
21
12 ncarry 1000 576 23 1 141
1573
2 ncarry 1000 576 23 1 141
307
4 ncarry 1 2 3 4 5 6 7 8 9 10
11
5 ncarry 1 2 3 5 8 13 21 34 55
77
```
]
|
[Question]
[
# Introduction
Super Mario 64 has a heavily overcomplicated RNG, ably explained [here](http://youtu.be/MiuLeTE2MeQ) by Pannenkoek.
I thought it might be interesting to implement it.
# Challenge
Implement the RNG function, except for the two special cases. (Not part of the below description; everything below is what you should implement.)
Input and output are both 16-bit integers.
The standard C implementation is as follows. `&` is bitwise-AND, `^` is bitwise-XOR. Shifts have higher precedence than bitwise operations, so `(s0 & 0xFF)<<1 ^ input` does the left-shift before XORing with `input`.
```
rng(input) {
s0 = (input & 0xFF) << 8; // shift low byte to high
s0 = s0 ^ input;
input = (s0 & 0xFF) << 8 | (s0 & 0xFF00) >> 8; // swap 8-bit halves
s0 = (s0 & 0xFF) << 1 ^ input;
s1 = s0 >> 1 ^ 0xFF80;
if(s0 & 1) input = s1 ^ 0x8180; // XOR with one of 2 constants
else input = s1 ^ 0x1FF4; // depending on s0 odd or even
return input;
}
```
In math notation, where \$\oplus\$ is bitwise XOR and \$x\_L\$ is \$x\$ mod 256:
\begin{equation}
\text{rng}(a):= \text{let } \begin{array}{l} b = 256a\_L \oplus a \\
c = 256b\_L \oplus \lfloor b/256 \rfloor \\
d = 32256 \text{ if $c$ odd, } 57460 \text{ otherwise}\end{array}
\text{ in }
b\_L \oplus \lfloor c/2 \rfloor \oplus d.
\end{equation}
# Example input and output
The number just before an arrow should be taken to the number just after it, so \$f(1789)\$ should be \$0\$, and \$f(0)\$ should be \$57460\$.
\$22026\$ and \$58704\$ map to each other.
```
12567 -> 60400 -> 1789 -> 0 -> 57460 -> 55882 -> 50550
64917 -> 43605 -> 21674 -> 46497 -> 45151
22026 <-> 58704
```
# Rules
Shortest code wins.
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# x86 32-bit machine code, 21 bytes
```
89 C8 30 C4 86 C4 D1 E8 73 04 66 35 74 9E 66 35 74 E0 30 C8 C3
```
[Try it online!](https://tio.run/##ZVFfT8MgHHwun@JnjQlsnWk3p8tqfTHZmy8@mThdGKUthlJT2kmz7Ktbwbn57@UXuDvuDmCjnLG@PxWKyTblcK2bVFTnxQ36BUmx/ovVQuX/dEI1DkOrFW2sYt02fLXCOKO6YVRKQsAqIMNuUhIjqkvA9z5G2dwrqw1wagLgzCDPVDXQIgAq7ZoV@XGji3ovi5D3ohjoL61FQjOLZuFzaKLF4gLp@Q9isfgm9rAMgFm7mjeI@LYKcp1KKtS@XJ0zKyhoDYOB3WwI2iLPMQYSiMbTy6sAuhh5aQWv9imaDPtnAvwATJJhQ0gMb4WQHLCBkwSm4XQa2hAPeQf1Ut1RVgjFgVUpn7sKnvMO96bbgw7OwvGD9e0SjFulRa54@llsQDLyaIbDJxLvDmGdCwvN7cS5HR2wbbbuGq7JUrmGjrT3bmvl0nao799ZJmmu@1E5GdthvyWxZ7n8AA "C (gcc) – Try It Online")
Uses the `fastcall` calling convention – argument in ECX, result in EAX.
In assembly:
```
f: mov eax, ecx
xor ah, al
xchg ah, al
shr eax, 1
jnc s
xor ax, 0x8180^0x1FF4
s: xor ax, 0xFF80^0x1FF4
xor al, cl
ret
```
Simplifications used:
* The XOR constants are combined.
* The `<< 1` cancels out with the later `>> 1`.
* The check `s0 & 1` is the same as the bit shifted out by the `>> 1`.
---
# x86 16-bit machine code, 18 bytes
```
89 C8 30 C4 C1 C8 09 73 04 35 74 1E 35 74 E0 30 C8 C3
```
In assembly:
```
f: mov ax, cx
xor ah, al
ror ax, 9
jnc s
xor ax, 0x8180^0x1FF4^0x8000
s: xor ax, 0xFF80^0x1FF4
xor al, cl
ret
```
Compared to the 32-bit program, this one saves two bytes by not needing operand-size prefixes.
One more byte is saved by combining the "swap bytes" and "shift right by 1" parts into a rotation right by 9 bits. This leaves [the bit that the original program would shift out] at the top of the register instead; fortunately, that is the same bit that is used to choose between the XOR constants, so it can be corrected for by adjusting those constants.
[Answer]
# JavaScript (ES6), 45 bytes
```
n=>(q=n>>8^(n&=255))/2^n<<7^n^57460^q%2*40564
```
[Try it online!](https://tio.run/##JcrBjoIwGATgu08xl9XWAGKlRYPtbZ@CtEmDICr5q6JejM@O3extvpk5@5cfm/vp@kgpHNqp0xNpw26ajNk6RnMtpOR8JRzt96UjJ8tC5e72I5ZFLlUxVTVqrIVUZYISNolSxW4dJf8lRC5Ugg0s7Czrwv3XNz1jNSjBBZZDG7xnwNA@4KFR2yoq/liFS5pWoFh2jDiHz67PsY/x79EEGsPQZkM4Mp@dw4nYAqnBgsf5w6cv "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₁‰`Ðr^‚₁β2‰`Ž$×*Žâ∊α^^
```
-12 bytes thanks to *@CommandMaster*
[Try it online](https://tio.run/##yy9OTMpM/f//UVPjo4YNCYcnFMU9apgF5J3bZAQSOLpX5fB0raN7Dy961NF1bmNc3P//hkamZuYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R02Njxo2JByeUBT3qGEWkHdukxFI4OhelcPTtY7uPbzoUUfXuY1xcf91/kcbGpmameuYGZgYGOgYmltY6hjomJqbmAFJUwsLIx0zE0tDcx0TYzMDUx0jQzNzEx0ToJC5jpGRgZGZjqmFuYFJLAA).
**Explanation:**
05AB1E lacks bitshift builtins, so instead we'll use modulo/multiply where applicable.
```
₁‰ # Divmod the (implicit) input-integer by 256
# (since the input is guaranteed to be a 16-bit integer)
` # Pop and push both the quotient and remainder to the stack
Ð # Triplicate the remainder
r # Reverse the stack from q,r,r,r to r,r,r,q
^ # Bitwise-XOR the remainder and quotient together
‚ # Pair the r and r^q together
₁β # Convert it from a base-256 list to a (base-10) integer
2‰ # Divmod it by 2
` # Pop and push quotient and remainder separated to the stack
Ž$× # Push compressed integer 25204
* # Multiply it to the remainder
Žâ∊ # Push compressed integer 57460
α # Take the absolute difference of the two values
^ # Bitwise-XOR it to the quotient
^ # Bitwise-XOR it to third remainder-copy that was still on the stack
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž$×` is `25204` and `Žâ∊` is `57460`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~53~~ 52 bytes
```
q;f(n){q=n>>8^(n&=255);n=q/2^n<<7^n^57460-q%2*'bt';}
```
[Try it online!](https://tio.run/##fVBhb4IwEP3ur7iQOEEhlkoBg/hl2a@YkLhaHNlWhTYZmeGvj53Qkblka9L2@u7de73j3pHzrquSwpbOpUrldhvntrxLKWNOItNqSXO52US5zFkUhMSrpnQ@e9KzpO1KqeFtX0rbgcsEcF0BLZRWjxmkcPEpCyMXQhIQ4oIfxWsXMOh18GJxTDEbrH0kBauQMBeoH0YBvhBFkFJCQ2TGEQnaZLQQzVlwLQ6Dy//yjDBG/pAPmM98I2/MjAs/SaWBP@/rOZ6Cv4h6MLN2zQPdNet73Mxy4ed7ZZnq4lSDff1oKQ@iwTKSmHADqvwQp8L@bsFZGmA@IgksFj3b6cWGyY7TRbVhwj0lS26yCrOFrZ1bVCA6jux32blGSmFb0wN4W8BzqnYSG9MuKHfsXaWpyIxsO2m7T1687o@q896/AA "C (gcc) – Try It Online")
*Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/250175/9481).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 173 bytes
```
.+
16$*0$&$*
+`(1+)\1
$+0
01
1
.*(.{8})(.{8})
$2$1
(?<=1.{7})(1|(0))
$#2
1$
11001111001110100
^((.{8}).{7}).
$+0${1}1110000001110100
+`1(.{15})(1|(0))
0$1$#3
1
01
+`10
011
1
```
[Try it online!](https://tio.run/##RY69CsJAEIT7eY2scsnBsZO/i6BY@hIisbCwsRC7mGc/9xLFLWZh9tthnrfX/XFNG3caU/BgL5XKVir40dGXZ0K8QgkiVC5Mw1yuCqmFcMf9gWGK5vLttDS7qEEBqUp@VW3h4tbHhQ45VibOC5Lnh/mRxrH7J6pQisYKWAu75jZWJ6VeW@MZhx3aptcO3RC1/QA "Retina 0.8.2 – Try It Online") Link includes less slow test cases. Explanation:
```
.+
16$*0$&$*
```
Convert to unary, but also prefix 16 `0`s, so the binary value below has at least 16 digits.
```
+`(1+)\1
$+0
01
1
```
Convert to binary.
```
.*(.{8})(.{8})
$2$1
```
Swap the bottom eight bits with the next eight, and discard any remaining zeros.
```
(?<=1.{7})(1|(0))
$#2
```
XOR the top eight bits into the bottom eight bits, i.e. toggle any digit seven digits after a `1`.
```
1$
11001111001110100
```
Append `0x8180 ^ 0x1FF4` if the value ends in a `1`.
```
^((.{8}).{7}).
$+0${1}1110000001110100
```
Replace the value with two copies shifted eight bits and one bit right and also append `0xFF80 ^ 0x1FF4`.
```
+`1(.{15})(1|(0))
0$1$#3
```
(Destructively) XOR all of the values together.
```
1
01
+`10
011
1
```
Convert to decimal. Note that this takes `O(n²)` time, which makes the test cases take up to 25 seconds each on TIO, so I've also written a Retina 1 port but using fast binary to decimal conversion: [Try it online!](https://tio.run/##RY07TgNBEETzuoYba3ZGanWN52cJyyGXQGYJCEgIgGy9PhYH4GLLrA2ig2qp9Pr1@8vn69szlzv3MC4awOJNtp4Io2MYHgmZOBuMINQ7ndo83BIShXDH@wN1qr3l2dnQ600EBaQZ@ZvWF07udniltYvjbKv9Cq3zB4aPkR1l/peaUDY7qDsenPr1i9KLi@IH2Yp/wmU8QcP3l4i6ZWHMpaJY6jbWtoch11R65tYiStqzIu2KZUSWmpB6VRGjxYLcqqUf "Retina – Try It Online") Link includes test cases.
[Answer]
# [MIPS III](https://n64brew.dev/wiki/MIPS_III_instructions), ~~68~~ ~~60~~ ~~52~~ 48 bytes
```
308800ff
00044a02
01285026
00085a00
016a5825
000b1042
00481026
316c0001
15800000
38429e74
03e00008
38427e00
```
Source:
```
rng: # a0 = seed
andi $t0, $a0, 0xFF # s_lo
srl $t1, $a0, 8 # s_hi
xor $t2, $t1, $t0 # s_lo ^ s_hi
sll $t3, $t0, 8 # s_lo << 8
or $t3, $t3, $t2 # c = (s_lo << 8) | (s_lo ^ s_hi)
srl $v0, $t3, 1 # c / 2
xor $v0, $v0, $t0 # xor with s_lo
andi $t4, $t3, 1 # c odd
bne $t4, $0, exit
exit: xori $v0, $v0, 0x9E74 # xor twice if branch taken, eff. nop
# 7E00 ^ E074
jr $ra
xori $v0, $v0, 0x7E00
```
Well I had to, didn't I? Even if MIPS is a terrible golfing language as far as assembly languages go, due to every single instruction being 4 bytes ([wasting instruction encoding bits](https://student.cs.uwaterloo.ca/%7Eisg/res/mips/opcodes)) and requiring unintuitive instruction re-ordering to not waste branch delay slots. It still beats out whatever actually was on the game ROM since I didn't have all of the mentioned Nintendo's [extraneous / unreachable code](https://github.com/n64decomp/sm64/blob/1372ae1bb7cbedc03df366393188f4f05dcfc422/src/engine/behavior_script.c#L39-L66).
-8 bytes from combining left and right shifts as in the math notation in the question. Also rewrote the comments to be much easier to follow.
-8 bytes from being smarter about `c` calculation thanks to m90.
-4 bytes from [rearranging instructions](https://n64brew.dev/wiki/MIPS_Assembly#Branch_Delay_Slot) to avoid a `nop` in the return jump branch delay slot. Here the control flow is weird: the branch (with offset 0) to a label at the delay slot causes the xor instruction to be executed twice if the branch is taken, once as part of the delay slot and again after branching, acting effectively as a no-op. AFAICT this is the intended behavior (at least supported by the MARS simulator).
[Answer]
## Batch, 58 bytes
```
@cmd/cset/a"q=%1>>8^(n=%1&255),q/2^n<<7^n^57460^q%%2*40564
```
Another port of @Arnauld's JavaScript answer.
[Answer]
# [Python](https://www.python.org), 55 bytes
```
lambda n:(q:=n>>8^(n:=n&255))//2^n<<7^n^57460^q%2*40564
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1BDoIwFETXeoofE02rIFhpi41wEWwTjKI1-tGKiZ7FDYnRO3kbIbia9xYz8_ycH9W-xPpVJKv3rSr8-CuP-Wm9yQEVuagE0zQ2BBsYMc4pDQJmcLmUBg2XkQjNZcjGUchF9K_fitKB9RAsQpbBjHEhPZCgPchARItZY7wzxkImPJiD1qrfOzuLFRmAn8JgeigtkuxaOWKpnnSgkqIxCu3BvZ13Oe62BKmmtDuv6y5_)
I'm late to the party, but yet another port of @Arnauld's JavaScript answer.
[Answer]
# SM83/Z80, 24 bytes
Input in `bc`, output in `bc`.
```
79 A8 41 CB 19 1F 38 08
EE 74 F5 80 EE 9E 4F F1
A8 41 4F 78 EE 7E 47 C9
```
Explanation and disassembly:
First, here's the pseudocode I used for this.
```
s0 = r << 8;
s0 ^= r;
r = swab(s0); // A
s1 = r & 1;
r >>= 1; // B
if(!$1) r ^= 0x9E74;
r ^= s0 & 0xff // C
r ^= 0x7E00 // D
```
Now the assembly:
```
sm64rng:
;; r starts in bc
ld a,c ;; 79
xor b ;; A8
ld b,c ;; 41
;; now s0 in ab, r in ca, after line A.
rr c ;; CB 19
rra ;; 1F
;; now s0 & 0xff in b, r in ca, s1 in cf, after line B.
jr c, ifodd ;; 38 08
xor $74 ;; EE 74
push af ;; F5
ld a,c ;; 79
xor $9E ;; EE 9E
ld c,a ;; 4F
pop af ;; F1
ifodd:
;; now s0 & 0xff in b, r in ca, before line C.
xor b ;; A8
;; now after line C.
ld b,c ;; 41
ld c,a ;; 4F
ld a,b ;; 78
;; r now in ac
xor $7E ;; EE 7E
;; now after line D
ld b,a ;; 47
;; r now in bc
ret ;; C9
```
Note that this doesn't work on Z80studio, because the bit instructions are currently badly broken and `rr c` doesn't work properly, because it messes up the flags (and taken jumps go to the place two bytes before they should). But after some fixing of the Javascript, it can be tested!
[Answer]
# [Rust](https://www.rust-lang.org/), ~~141~~ ~~90~~ ~~79~~ ~~75~~ 74 bytes
Saved 67 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
---
Golfed version. [Try it online!](https://tio.run/##rVDBcoIwFLz7Fa/OtIMO1CQlAYt66xf02NEO0oiZQmQg1HaQb6ePoON46K05JO/t2@xuUtaV6XYa8lhpZwLNCCCTBkqdwhK6U14b0M81FSdvhXujN0t9z7hYLMJID@WUbfRjdYyL9@2PkZUzifSMbXjgC@IhYco4I37bRagMMJvBy3ecF5mEuopTCUdl9pCqL6lB6aI2laX1EYaWYow3ijaBC4L4hLhAg3DuAhbWAw8ehgwPwjlZRwBWYXco4cFKoNC5QrHGDvtVlEqbTN8546YFbwVNO3YHT7d/vWPLyWSI3Y5urpzRa0rWpxT@nGJK/0kQ7gKjIvCxQ7QHOeV0Hf0djf1vNPzn10ImKs4giSsJ5gDJXiafsFXehyplYtRB4zCPi0Lp9FZjzBhhAhYX697TQhfPK5OHAfFvmRbqmW33Cw)
```
|mut n:u16|->u16{n^=n%256<<8;n=n%256*2^n.swap_bytes();n/2^57460-n%2*25204}
```
Ungolfed version. [Try it online!](https://tio.run/##rVJNj5swEL3nV7zNYRUkorUpELYkuTXXSu2lUrUrETBglRgUO5ut0vz2dIzzQar2Vi62Z96892aY7U6b06lU2KpqstkZSNXtzEfseOxhurQnDiPQ1wgDC9Csz6bXoObnQB/RDAtMehY8gr2vVh7mcyQpnp6ga1kaNO0e659GwLSoZVVf6l4XTt1ROwriosyQCL8GIcY8LJcX9n3WIZmupUGdNW9CDwzdk3C8DqU0JwghiMlmLCxhZxcl@lKOhwUYDrBCheiEKqSq0CqbbosC7RbiTSgf3z5/wV6amnICbYkAeau0yZRxfoa9aSeXcJJDnz1CNFqcR/4XKF@twgv0NqbRcTSif7jJpJp4rpZsfnrPNl0jsNNZJZynSpJHV6OvP9A97Qy@8yCKZz5iFjLmg8@SZx90iWZhbI8oSQI6WBSxlxTORkmdPzqXUp1vRHbroNtKZRr1MBkfjnalDsex7zT9fuv6q@elg6auJV76h8vAuozDZ04uww8xi3wEPJ6F9KKoDUY84i/pv60F/9cazflrJ3KZNcgz3e90Xov8B9ZyWsityI1sFSU3WdfRxtxzjIOABTHmF2mr2YcumjdklMxYeI/sQxZ5PJ1@Aw)
```
fn rng(mut input: u16) -> u16 {
let mut s0: u16;
let s1: u16;
s0 = (input & 0xFF) << 8; // shift low byte to high
s0 ^= input;
input = (s0 & 0xFF) << 8 | (s0 & 0xFF00) >> 8; // swap 8-bit halves
s0 = (s0 & 0xFF) << 1 ^ input;
s1 = s0 >> 1 ^ 0xFF80;
if s0 & 1 != 0 { // depending on s0 odd or even, XOR with one of 2 constants
input = s1 ^ 0x8180;
} else {
input = s1 ^ 0x1FF4;
}
input
}
fn main(){
// Example usage with given inputs
let inputs1 = [12567, 60400, 1789, 0, 57460, 55882, 50550];
for &input in &inputs1 {
println!("{} -> {}", input, rng(input));
}
println!();
let inputs2 = [64917, 43605, 21674, 46497, 45151];
for &input in &inputs2 {
println!("{} -> {}", input, rng(input));
}
println!();
// Special case to check bi-directional mapping
println!("22026 <-> {}", rng(22026));
println!("58704 <-> {}", rng(58704));
}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 51 bytes
It's a direct port of [Arnauld's Javascript answer.](https://codegolf.stackexchange.com/a/250175/72767)
```
$_=($t=$_>>8^($_&=255))/2^$_<<7^$_^57460^$t%2*40564
```
[Try it online!](https://tio.run/##NY5BDsIgEEX3XENswKQ6QxlAA/UEXgFWLkwa2ygbE88ugqmbn5@8efmzXB8TlcJTEDwHnsbRRcFTFxSRlAcVefLe1oxktYHI81btNJDRZbNKQvBXaE5TvHf1WK4dY4N/8G7dkHIg64ysgdGQhraYOzwPA5I6Oay8oCJjmQENwNC6IwP2e4AROac@85Jv8/1Z@gvtAaH0y/QF "Perl 5 – Try It Online")
]
|
[Question]
[
Take this array:
```
[1, 2, 6, 4, 4, 1, 0, 0, 2, 0, 4, 1, 4, 2, 4, 8, 1, 2, 4]
```
There are quite a few places where `[1, ..., 2, ..., 4]` appears, where `...` is any number of items. These include `[1, 2, 6, 4]`, `[1, 0, 0, 2, 0, 4]`, `[1, 0, 0, 2, 0, 4, 1, 4]`, and `[1, 2, 4]`. The shortest of these is simply `[1, 2, 4]`.
**Task:**
Given two arrays of any (reasonable) data type you choose, find the shortest slice of the first which contains all items in the second in order. There is guaranteed to be at least one such slice.
If there are multiple, you may return any one of them. Neither array will be empty. Duplicate items may appear in the second list.
**Test cases:**
```
[1, 2] [1, 2] -> [1, 2]
[2, 1, 3, 2] [1, 2] -> [1, 3, 2]
[1, 2, 4, 8] [1, 4, 8] -> [1, 2, 4, 8]
[0, 1, 1, 0, 0, 1, 1, 1, 0] [0, 1, 0] -> [0, 1, 1, 0]
[1, 5, 3, 7, 1, 3, 3, 5, 7] [1, 3, 5, 7] -> [1, 3, 3, 5, 7]
[1, 2, 5, 1, 3, 5] [1, 5] -> [1, 2, 5] OR [1, 3, 5]
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ẆŒPi¥ƇḢ
```
[Try it online!](https://tio.run/##y0rNyan8///hrrajkwIyDy091v5wx6L/h5frH530cOcMlUdNayL//4@ONtRRMIrVUYDQIEa0kY4CkGOMIQ5i6SiY6ChYQMXBTLCUAVgLEBmAkSGcC5I1gDJhhpiCDTeH2WIMFjGHmgnjIdloClNpClVjGhsLAA "Jelly – Try It Online")
-1 byte thanks to Unrelated String
```
ẆŒPi¥ƇḢ Main Link
Ḣ Find the first
Ẇ slice (ordered by length)
Ƈ where
i the right list's index is truthy (occurs in)
ŒP the powerset (stable ordered)
```
1-indexing saves me a byte, thank you Dennis!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
⟨s⊇⟩ᶠlᵒh
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8FcWPutofzV/5cNuCnIdbJ2X8/x8dHW2oo2AUq6MAoUGMaCMdBSDHGEMcxNJRMNFRsICKg5lgKQOwFiAyACNDOBckawBlwgwxBRtuDrPFGCxiDjUTxkOy0RSm0hSqxjQ2NhYA "Brachylog – Try It Online")
```
⟨ ⟩ᶠ Find every
s substring of the first input
⊇ containing the second input as a substring.
lᵒ Sort by length
h and take the first.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
◄Lfo€⁰ṖQ
```
[Try it online!](https://tio.run/##yygtzv7//9H0Fp@0/EdNax41bni4c1rg////ow11jGL/RxvpGOoYA1kA "Husk – Try It Online")
yes another carriage in the 8-byte golflang answer train.
[Answer]
# [J](http://jsoftware.com/), 64 bytes
```
]{~0({.+i.@>:@g)@>@{[:(]/:(g=.{:-{.)&>)@(#~]=/:~&.>)@,@{[:<@I.=/
```
[Try it online!](https://tio.run/##RY7BCsIwDIbvPkVQ2Fbssm6zTIIdBUEQPHmVncRNvfgAhb16TVvGaAr/n/9LyNdvMR/BEOQgQQHxLxHO99vFD25WhcP9B21PdhK2t@5BxVBRMRl0VDoUWS9ssZsHU9GcIRsZmJO9oqm82Lye7x/U0PLT0EFJ0QQ5Qi1BS2gldDLoNhZ3umWqYTBO6EQ3MU6oTpDitA4nU5SKQRURLiVXHey69gDHtDiIcWmtecyalPg/ "J – Try It Online")
Well 8-byte folks, let's *square* the byte count, shall we?
I could save bytes here by just trying every possible subset, but this approach seemed more interesting, and for most inputs is likely faster.
## the idea
Consider `1 3 5 7 f 1 5 3 7 1 3 3 5 7`:
* Create an equality table:
```
1 0 0 0 1 0 0 0 0
0 0 1 0 0 1 1 0 0
0 1 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0 1
```
* Get indexes of ones:
```
┌───┬─────┬───┬───┐
│0 4│2 5 6│1 7│3 8│
└───┴─────┴───┴───┘
```
* Cartesian product:
```
┌───────┬───────┬───────┬───────┬
│0 2 1 3│0 2 1 8│0 2 7 3│0 2 7 8│ ...etc...
└───────┴───────┴───────┴───────┴
```
* Filter only elements that are ordered:
```
┌───────┬───────┬───────┬───────┬───────┐
│0 2 7 8│0 5 7 8│0 6 7 8│4 5 7 8│4 6 7 8│
└───────┴───────┴───────┴───────┴───────┘
```
* Sort by difference between first and last element:
```
┌───────┬───────┬───────┬───────┬───────┐
│4 5 7 8│4 6 7 8│0 2 7 8│0 5 7 8│0 6 7 8│
└───────┴───────┴───────┴───────┴───────┘
```
* Take first element, and construct full range between first and last:
```
4 5 6 7 8
```
* Use those to index into the input:
```
1 3 3 5 7
```
[Answer]
# JavaScript (ES6), ~~89 87~~ 83 bytes
*Saved 4 bytes thanks to @tsh*
Expects `(haystack)(needle)`.
```
a=>b=>a.reduce((r,_,i)=>b.every(x=>j=a.indexOf(x,j)+1,j=i)/r[j-i]?a.slice(i,j):r,a)
```
[Try it online!](https://tio.run/##dZBRb4MgFIXf@yt4hOwWtZa4LMH9hCZ7bcjCFBuI0Qa7xv16R2npnKXkvnDO5cs5GHmWQ2X18bTu@lpNDZ8kL794KalV9XelMLbwCZo4kaqzsj945KXhkuquVuOuwSMY8pKB4Zokdm/WWrxLOrTaPdXOerMgyVT13dC3irb9ATd4nwHaCBQ75J9JCEoSdFVWC8YGkNPzCOkZI49hLpuAtoBe45jgzKLcxCUp9YHcpH6y@1WQYKYz0t96LBPzcYvQMfdKIa6Z7rd5tSDGC7JAYmJRkD3@tRd3H4HMxPQL "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = haystack
b => // b[] = needle
a.reduce((r, _, i) => // for each entry at position i in a[]:
b.every(x => // for each entry x in b[]:
j = // update j to:
a.indexOf(x, j) // the index of x in a[], starting at j
+ 1, // to which we add 1
j = i // starting with j = i
) // end of every()
/ r[j - i] // test whether r[j - i] is defined
? // if successful:
a.slice(i, j) // update r[] to the current slice of a[]
: // else:
r, // leave r[] unchanged
a // start with r[] = a[]
) // end of reduce()
```
---
# JavaScript (ES6), ~~91~~ 89 bytes
*Saved 2 bytes thanks to @tsh*
Expects `(needle)(haystack)`.
```
b=>g=(a,n)=>a.some((_,i)=>`${s=a.slice(i,i+n)}`.match(`^${b.join`,(.*,)*`}$`))?s:g(a,-~n)
```
[Try it online!](https://tio.run/##fZDNbsIwEITvfQofcvDSxfxGoEqmj1CJK3Kxk4ZgFOyqRr0gePXgOgkBFLryZcajz7PeqV/l0h/9fegb@5WVG14mfJFzqtAAXyjm7D6jdI3aKxkdHfdWodOMatSvBk6S7dUh3VL5GR0TtrPaSKSsh9CTp0gCvLu33MP6ZwNlao2zRcYKm9MNXY2QjAUJA3fqYQDIYECqwMu/jDESb0w6SC1j8gQzRTIXbZXWeFKlDjyShqHCsCZV6s8IZ3SVoia1ga5OvmuMZCaqTnEwZs2O18vb1RqzAxbf/3UI1m@I7gW9/7FsyLEoLw "JavaScript (Node.js) – Try It Online")
### How?
We turn the needle `b[]` into a regular expression:
```
RegExp(`^${b.join`,(.*,)*`}$`)
```
Example:
```
[1, 4, 8] ~> /^1,(.*,)*4,(.*,)*8$/
```
We recursively look for the smallest `n` such that there exists a slice `s[]` of `a[]` of length `n` that matches this regular expression.
[Answer]
# JavaScript (ES6), 93 bytes
```
a=>b=>a.reduce(r=>1/r[p=b.map((m,j)=>t=m-a[i]?p[j]:j?p[j-1]:i),++i-t]?a.slice(t,i):r,a,i=p=0)
```
[Try it online!](https://tio.run/##dU9LbsMgFNznFCxBwR/s0FSucI5QqVuLBUkc6bl1ijCJlNM7NjGkRKqEHjNPM8PQqasaDga0TQYNx9b0v@fv9jaexKhEvRe1Sk17vBxabETNMtNosU97pTHuaUdEbUWfqAbkTjedrLr5SpisgND1GhIrdyodfmCyWwqkMlRREFrkZNQGzhafcMMoKih6o2jjzkRzdwo3H5uNo9N8d3TGknjrBMkHyjIU@CoK98pI9kdTuMzyH2UZi1losogfMC4wr56W3OWHf7FA54TcwyXhKY4f5a7J1lct3Wa7dAgsqu23r@W5D@GLnb/05xJ9fvkULlfjHQ "JavaScript (SpiderMonkey) – Try It Online")
For inputs \$ a\left[1\dots N\right] \$ and \$ b\left[1\dots M\right] \$
Let matrix \$p\_{N\times M}\$ be
$$ p\_{i,j}=\begin{cases}
i & b\_j=a\_i \land j=1 \\
p\_{i-1,j-1} & b\_j=a\_i \land j>1 \land i>1 \\
p\_{i-1,j} & b\_j\ne a\_i \land i > 1 \\
-\infty & \text{otherwise} \\
\end{cases} $$
the minimal length of output \$L\$ is
$$ L = \min\_{i \in 1\dots N} i-p\_{i,M}+1 $$
And the output is
$$ a\left[p\_{i,M}\dots i\right] $$
where \$i\$ is the value for minimal \$L\$.
This solution works in \$ O\left(M^2\right) \$ time and \$ O\left(N\right) \$ extra memory.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
ÞS'ṗ⁰c;Þg
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyIiLCIiLCLDnlMn4bmX4oGwYzvDnmciLCIiLCJbMSwyLDUsMSwzLDVdXG5bMSw1XSJd)
```
Þg # Shortest
ÞS # sublist
' ; # where
ṗ # powerset
c # contains
⁰ # input
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Œé.ΔæX.å
```
[Try it online](https://tio.run/##yy9OTMpM/f//6KTDK/XOTTm8zFPv8NL//6MNdAyB0EAHQgNZsVxgMYNYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P@jkw6v1Ds35fCyCL3DS//X6vyPjo421DGK1QGTsToK0dFGOoY6xqhCQIaOiY4FWAhEgwUNgOoMdQx0IDSQBZQ2ANNQPaZAY8zBhhkD2eZg3RAW3FBTsLQpWMoUIWwGtMUEargREIPYJhA36IDdAnEckI6NBQA).
**Explanation:**
```
Œ # Get all sublists of the (implicit) input-list
é # Sort these sublists by smallest to largest length
.Δ # Find the first sublist which is truthy for:
æ # Get the powerset of this sublist
I.å # And check if it contains the second input-list
# (after which this shortest found result is output implicitly)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 94 bytes
Using `iter` to check if `s` is a subsequence of `b` is a trick I've first seen on [this answer](https://codegolf.stackexchange.com/a/217976/64121).
```
def f(a,b,i=0):l=len(a);s=a[i%l:][:i/l];x=iter(s);return s*all(v in x for v in b)or f(a,b,i+1)
```
[Try it online!](https://tio.run/##VY/NasMwEITveYq9BKRkof6JSbDRkwgdZCoTgZCDpBb36d3Vujn0ovmY1Q6zr5/yXGO3759ugUVYnNGrRo5BBReFlVNWVvtzGI0e/Ucw06Z8cUlkOSVXvlKEfLEhiG/wETZY1gSMsyT6y7u2ci8ulwwKtNYtdgb5JdEdttj/c0jxhg92qlavoV8tNngoEZkN67ExUMadk3riO@8e9E4ceDrwZDDGnGpVizDXttxuPAG8ko9F1N50gdx/AQ "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes
```
≔E⌕Aθ⊟η⟦¹ι⟧ζF⮌η«FζF⌕A…θ§κ¹ι⊞υ⟦⁻Σκλλ⟧≔υζ≔⟦⟧υ»≔⌊ζε≔⊟εδI✂θδ⁺δ⊟ε
```
[Try it online!](https://tio.run/##PU/BioMwED3Xr8hxAlnQc08iLOyhIO1RchAzrUPT2BpTui777dmJ1Q0TknmPee9N17djN7Q2xtJ7ujg4tHf4JGdKa@GhRD3coZdSiaZQgjR/ZrnPzsMo4IhPHD0mWvxkuwWbpVjeTaH67ixWPYuwVjl9OYMvuCpRJEniwTr4HgLLH8gFD6dwgytTNl3NTrs1Vngbb22jlQjc/2ZbbHJ04@GZB5GJFU7xkSHDUD2Sm6Bq/QQnSx2mSIY3tOxr3puiTGcfY9PkHHKpfKniv2Xnlcy1jh9P@wc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔E⌕Aθ⊟η⟦¹ι⟧ζ
```
Get the last element of the array to match and find all of its indices in the array to search, yielding an array `[1, i]` for each position. These values relate to the length and start position of a slice of the array to search, initially only containing the last element of the array to match.
```
F⮌η«
```
Loop over the remaining elements in reverse order.
```
Fζ
```
Loop over the matches so far.
```
F⌕A…θ§κ¹ι
```
Loop over all the positions of the next element in the prefix of the current match.
```
⊞υ⟦⁻Σκλλ⟧
```
Save the new match length and start position.
```
≔υζ≔⟦⟧υ
```
Move the working list back to the list of matches and clear the working list again.
```
»≔⌊ζε≔⊟εδ
```
Get the match with the shortest length and get its start position.
```
I✂θδ⁺δ⊟ε
```
Output the slice of that length at that position.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 34 bytes
```
1A`
,
.$*
~)`^
1G`¶Lw`
N$`
$.&
1G`
```
[Try it online!](https://tio.run/##LYwxDsIwDEV3nyOggqwqThNaKRNTF8TCjszAwMKAkNg4Vg/Qi4XvBFm2n77/9@v@fjxvUjbdRTN1sxY5KjH1bk/fnV5JZl2X00fp7JRcvzWhFOHAB44oYY8KaOMIijyx3WOukzCNKEAd/izNly0xkcel/ZFG2cjDlZAYa24Aj1narvlU9QQt/QA "Retina – Try It Online") Takes two newline-separated lists of distinctive words (i.e. no word is contained in another word) but link is to test suite that splits on semicolons for convenience. Explanation:
```
1A`
```
Delete the array to search.
```
,
.$*
```
Replace each comma with a regex for arbitrary content.
```
^
1G`¶Lw`
```
Prefix a command to delete the array to match and list all overlapping matches in the array to search.
```
~)`
```
Evaluate the result on the original input.
```
N$`
$.&
```
Sort the matches by length.
```
1G`
```
Take the first.
[Answer]
# [R](https://www.r-project.org/), ~~95~~, 94 bytes
#### Assuming `combn` always returns sorted indexes
At the moment the assumption is valid in all R versions, but is not documented; the alternative (longer) solution is reported at the bottom of the answer
* -1 byte thanks to @Dominc van Essen
```
function(v,s,`+`=length){for(x in combn(+v,+s,,F))if(all(v[x]==s)&+v[T]>+(y=x:x[+x]))T=y;v[T]}
```
[Try it online!](https://tio.run/##fVBdC4IwFH3vV1wIYpfdQDMpivXYaxC@iVBJK8EmZMki@u2mw9kH1rgPO2c7Z@fsXEpRyquKL0mmWEE5bfhGpHt1uBzxLrMz05AoiLPTTjFeEM@JloiJZNs0ZUWoIyFyHPAiDKIFZzehZzrkOkIMxG1es49Sspi5BCOEzkUfpwh9GC4AGrJXi0cEFfC6LP6IvVZf3yAYE0x/6O3R5@MNbywcE6Eax4zbQqwtHLt/t3hJ2hS@STWxdTzDTLBJYeF3C8u/dfGthY/fXfzOjzT8al2h0ArLJw "R – Try It Online")
## Unrolled code with explanation:
```
function(v,s){ # take full vector v and the vector to search s
r=v # init shortest slice r to full vector v
for(x in combn(length(v), # for each combination x of length(s) elements taken
length(s),,F){ # from the vector of indexes 1:length(v)
# (we assume x is sorted ascending)
a=v[x:x[+x]] # get the slice between first and last index in x
if(all(v[x]==s) & # if the values of the combinations == s and
length(r) > length(a)) # the slice is shorter than r
r=a # store the new slice
}
r # return the shortest slice
}
```
---
Version without assumption:
# [R](https://www.r-project.org/), 107 bytes
```
function(v,s,r=v,`+`=length){for(x in combn(+v,+s,,F)){y=sort(x);if(all(v[x]==s)&+r>+(a=v[x:x[+x]]))r=a};r}
```
[Try it online!](https://tio.run/##fVDLasMwELznKxYCZRdtwYljUhqUY6@FXo0hjolSgyuD7BqVkG93bWE5D5yIPWhGmtGMTKtkq351VuelxoYrNrLhndjJ4qCP9TedVGnQQq4hK3/2GkXDomL@IDr9yao0NVra5ArTosAmtomUFb0IsxWYyg6/21jYJCEyMj1vzLlVmOGCYUkwufjmlGAOr1uAgZz14iVDB8IpiyficNT3NxhWDG8P9P7o9vGBdxaBi9BN4GYxQuotAr@/trhIxhSRS7X2dULHrGlI4eF9C89fdYm8RUT3XaLJj3T851eHYi9s/wE "R – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ã æÈà deV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4yDmyOAgZGVW&input=WzIgMSAzIDJdClsxIDJd)
```
ã æÈà deV :Implicit input of arrays U=haystack & V=needle
ã :Sub-arrays of U
æ :Get the first that returns true
È :When passed through the following function
à : Combinations
d : Any
eV : Equal to V
```
[Answer]
# GForth, 241 bytes
```
: s 1 /string ;
: d 2drop ;
: o 2over ;
: h over >r begin o drop c@ scan 2>r s 2r> 2 pick 0= over 0= 2* or ?dup until nip 2nip 1+ swap r@ - r> -rot or ;
: f 2dup 2>r begin o o h dup r@ u< if 2rdrop 2>r else d then s dup 0= until d d 2r> 1+ ;
```
[Try it online!](https://tio.run/##bU9BbsMgELz3FXNuZdXgWqmSJs1XXBvbqDGgBSfPdwd8aaUiYGd3Z9hh9JLmahpz2LYjIhReYxLrJpyejhigB/GhYA/t70YKnlHgRfBlJuvYK7T@ith3DpqNCC0XaATbf6M@7wJG/Qwv@BzWgNUle4OzATpf6gXx0QXIFRWorcSnzM0DRxqhQv@a6Oki10hfP2DJkGIic8wtGppPs3E0klmcvI8b8qf4Oqed@OOE0Ek0lesWg9jdTbWY5d@aLubGP70k5/xymsU/6DNB6X0TatXsSaNL4@0dKh8C5rVSNY@qiWqg5JnWNgfVNO2BMl4ouMhbFlCW2iNL2w8 "Forth (gforth) – Try It Online")
## Formatted & commented version
also a bit ungolfed
```
: s 1 /string ;
: d 2drop ;
: o 2over ;
\ find the first match. if there is no match, return a string with the maximum length (-1)
: h ( target container -- caddr u )
\ store the start address of the string on the return stack
over >r
begin
\ remove characters from the front of the string until
\ the string starts with the same character as
\ the target string (or until it is empty)
o drop c@ scan
\ remove a character from the front of the target string
2>r s 2r>
\ some magic that gives -1 if the target string is empty,
\ -2 if the container string is empty, and 0 otherwise
2 pick 0= over 0= 2* or
\ duplicate the top of the stack if it isn't zero
?dup
\ exit the loop if the top of the stack is something other than zero
until
\ get rid of everything on the stack except for new address of the string
\ if there was a match, this will be the address of the end of the match.
nip 2nip
\ use this and the saved start address to reconstruct the match.
1+ swap r@ - r> -rot
\ if we didn't get a match, use the magic from before to replace the length with -1
or ;
: f ( target container -- caddr u )
\ store the current shortest match on the return stack.
\ since it is given that there will be a match in the array,
\ we put that on the return stack first
2dup 2>r
begin
\ find the first match, and compare its length to
\ the length of the match on the return stack
o o h dup r@ u< if
\ if it is shorter, replace the string on the return stack with it
2rdrop 2>r
else
\ otherwise, discard it
d
then
\ remove a charachter from the front of the string
s
\ if there are no more charachters in the string, exit the loop
dup 0=
until
\ get rid of everything and retrive the stored match
d d 2r>
\ there's an off by one error here somewhere. rather than fix it, just add one.
1+ ;
```
```
[Answer]
# [R](https://www.r-project.org/) >= 4.1.0, 139 bytes
```
\(x,y,`~`=\(a,b)paste(a,collapse=b))(u<-combn(1:sum(x|1),2,\(z)if(grepl(y~" .* ",(v=x[z[1]:z[2]])~" "))v,F))[order((m=lengths(u))/!!m)][1]
```
[Try it online!](https://tio.run/##PYtLCoMwFACvEl29V15booggzbaXEMFPE1vQRIwRleLVrXXhbphh@k2JTTldDR@jYaKZ8jUXpyioxK6wg9ypMk1TdFaKEhHc41qZttTAE@tamL4cKaDzW/CjoO5l18C8@ux2YT7BKKZ0SXmWLGmQZbh75iOO9ERMTf@SPUArGqnr4W3BId49r8VsHzYFFXBiEbGQWEyMHxAeJkb6x5AiihG3Hw "R – Try It Online")
A function that takes the `x` as the vector to look within and `y` as the vector to look for. Returns a length 1 list containing the shortest matching contiguous subsequence of `x`. TIO link replaces `\` with `function` since TIO is running an earlier version of R.
[Answer]
# Python 3.8, 152 bytes
The [other python answer](https://codegolf.stackexchange.com/a/226829/71357) is too good - but just leaving mine here anyway
```
from itertools import*
f=lambda a,b:min(((Y:=c[0][0]),(Z:=c[-1][0]),a[Y:Z+1],Z-Y)[::-1]for c in combinations(enumerate(a),len(b))if[*zip(*c)][1]==b)[1]
```
older uncondensed version
```
from itertools import*
def f(a,b):
#print(*permutations(a), sep='\n')
combis = [*combinations(enumerate(a),len(b))]
#print(combis)
F=[(combi[0][0],combi[-1][0]) for combi in combis if [*zip(*combi)][1]==b]
#print(F)
s,e = min(F, key=lambda i:i[1]-i[0])
#print(s,e,a,a[s:e+1])
return a[s:e+1]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes
```
(c=___;#1/.{c,x:Shortest[PatternSequence@@Riffle[#2,c]..],c}:>{x})&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPZNj4@3lrZUF@vOlmnwio4I7@oJLW4JDogsaQktSgvOLWwNDUvOdXBISgzLS0nNVrZSCc5Vk8vVie51squuqJWU@1/QFFmXolDWnS1oY6CUa0OhIrlQhHWUTDVUQAyjIEMiBLT2tj/AA "Wolfram Language (Mathematica) – Try It Online")
No brutal force, just patterns usage
]
|
[Question]
[
## Introduction:
*I have loads of different ciphers stored in a document I once compiled as a kid, I picked a few of the ones I thought were best suitable for challenges (not too trivial, and not too hard) and transformed them into challenges. Most of them are still in the sandbox, and I'm not sure yet whether I'll post all of them, or only a few. Here is the second one (the [Computer Cipher](https://codegolf.stackexchange.com/q/176931/52210) was the first one I posted).*
---
For the [Trifid Cipher](https://en.wikipedia.org/wiki/Trifid_cipher) (without using a keyword) the alphabet (and an additional wildcard) is divided into three 3 by 3 tables:
```
table 1: table 2: table 3:
|1 2 3 |1 2 3 |1 2 3
-+----- -+----- -+-----
1|a b c 1|j k l 1|s t u
2|d e f 2|m n o 2|v w x
3|g h i 3|p q r 3|y z
```
A text we want to encipher is first character by character encoded into table-row-column numbers. For example, the text `this is a trifid cipher` becomes:
```
t h i s i s a t r i f i d c i p h e r
table: 3 1 1 3 3 1 3 3 1 3 3 2 1 1 1 1 3 1 1 2 1 1 2
row: 1 3 3 1 3 3 1 3 1 3 1 3 3 2 3 2 3 1 3 3 3 2 3
column: 2 2 3 1 3 3 1 3 1 3 2 3 3 3 3 1 3 3 3 1 2 2 3
```
We then put everything after one another row by row in the table above in groups of three:
```
311 331 331 332 111 131 121 121 331 331 313 133 232 313 332 322 313 313 132 333 313 331 223
```
And those are transformed back to characters using the same tables:
```
s y y z a g d d y y u i q u z w u u h u y o
```
One thing to note, the input-length should be coprime to 3. So if the length is a multiple of 3, we append one or two trailing spaces to make the input-length not a multiple 3 anymore.
## Challenge:
Given a string `sentence_to_encipher`, encipher it as described above.
You only have to encipher given the `sentence_to_encipher`, so no need to create a deciphering program/function as well. I might make a part 2 challenge for the deciphering in the future however (although I have the feeling it's to trivial/similar to the enciphering process).
## Challenge rules:
* You can assume the `sentence_to_encipher` will only contain letters and spaces.
* You can use either full lowercase or full uppercase (please state which one you've used in your answer).
* You can choose to append either one or two trailing spaces when the input-length is 3 to make it not a multiple of 3 anymore.
* I/O is flexible. Both input and output can be a string, list/array/stream of characters, etc.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: "this is a trifid cipher"
Output: "syyzagddyyuiquzwuuh uyo"
Input: "test"
Output: "utbk"
Input: "output"
Possible outputs: "rrvgivx" (one space) or "rrzcc lr" (two spaces)
Input: "trifidcipher"
Possible output: "vabbuxlzz utr" (one space) or "vabbyzv rx ie " (two spaces)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ ~~26~~ 25 bytes
```
⁶Øa;3ṗ¤,©Ṛy;⁶$L3ḍƊ¡ZFs3®y
```
[Try it online!](https://tio.run/##y0rNyan8//9R47bDMxKtjR/unH5oic6hlQ93zqq0Bgqq@Bg/3NF7rOvQwii3YuND6yr/H25/1LRGIfL/f6WSjMxiBSBKVCgpykzLTFFIzizISC1S0lFQKkktLgHR@aUlBaVgFkQJVAUA "Jelly – Try It Online")
### How it works
```
⁶Øa;3ṗ¤,©Ṛy;⁶$L3ḍƊ¡ZFs3®y Main link. Argument: s (string)
⁶ Set the return value to space.
Øa; Append it to "a...z".
3ṗ¤ Yield the third Cartesian power of [1, 2, 3].
,© Pair the results and store the pair in the register.
The register now holds
[[[1, 1, 1], ..., [3, 3, 3]], ['a', ... ,'z', ' '].
Ṛ Reverse the outer array.
;⁶$ Append a space to s...
L3ḍƊ¡ if the length is divisible by 3.
y Transliterate according to the mapping to the left.
ZFs3 Zip/transpose, flatten, split into chunks of length 3.
®y Transliterate according to the mapping in the register.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
≔E⁺θ× ¬﹪Lθ³⌕βιθ⭆⪪E⁺÷θ⁹⁺÷θ³θ﹪鳦³§⁺β ↨³ι
```
[Try it online!](https://tio.run/##ZY7BCoMwEETv/YrgaYX05Kl4spSCUItgfyA1QRfSRM0q/ft01UIPncMuO7Dzpu3V1HplYyxCwM5BpQao7RxglOKBLxMgEYkUd09QeT1bDzfjOuphTKXIUpYUV3QanlLgeoxpfqgndAQN8erWwGawSL/o0tEFF9RmhZz459/NtiQeXyhusN0vqHTavPcsxnJBds8qGMi2Eqw8RjKB4nGxHw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔ Assign
θ Input string
⁺ Concatenated with
Literal space
× Repeated
θ Input string
L Length
﹪ Modulo
³ Literal 3
¬ Logical not
E Mapped over characters
ι Current character
⌕ Position found in
β Lowercase alphabet
θ To variable
θ List of positions
÷ Vectorised integer divide by
⁹ Literal 9
⁺ Concatenated with
θ List of positions
÷ Vectorised integer divide by
³ Literal 3
⁺ Concatenated with
θ List of positions
E Map over values
ι Current value
﹪ Modulo
³ Literal 3
⪪ Split into
³ Groups of 3
⭆ Map over groups and join
β Lowercase alphabet
⁺ Concatenated with
Literal space
§ Cyclically indexed by
ι Current group
↨ Converted from
³ Base 3
Implicitly print
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~180~~ ~~176~~ ~~174~~ ~~165~~ 163 bytes
```
lambda s:''.join(chr(32+(33+a*9+3*b+c)%59)for a,b,c in zip(*[iter(sum(zip(*[(c/9,c/3%3,c%3)for c in map(o,s+' '[len(s)%3:])]),()))]*3))
o=lambda c:(ord(c)%32-1)%27
```
[Try it online!](https://tio.run/##dU/LboMwELzzFSsqhA20UbGqKkj5hvae5mAbE9wS7PpBgn@eElIpaauu9rI7szszenSt6sup2bxNHT2wmoKt0vThXcke8dYgUuaIkJxm65xkLOc4eVrjRhmgBSs4yB6C1CjbSicMsv6ALiPiq3XBVyQhBU/IcrCQD1QjVdg8hXTbiR5ZnJBqh3e4QBjjXUYwjtTm2wmvkDI1mjVJef@Ik/J50kb2DhoUu1ZamJuCM7KRNXCpW2FiHN29eKe9q@BasR3HQPd1PY5efvpw9L4FP6o4iq4PhXX/XHvHPm6paqGcya/KWsk6AZeVrSA2ZtjL4RQDUr0AqykXGOb4MxA4h87MiDuqC2LxrYMlyDXHr@ezpXigjPlTFwJ4Z/5KnOExDGBOIAX8FJq@AA "Python 2 – Try It Online")
Input can be upper or lower. Output is uppercase
[Answer]
# Pyth, ~~34~~ 33 bytes
```
m@+G;id3csCmtj+27x+G;d3+W!%lz3zd3
```
Full program. Input is expected as lowercase, output is a character array. Try it online [here](https://pyth.herokuapp.com/?code=m%40%2BG%3Bid3csCmtj%2B27x%2BG%3Bd3%2BW%21%25lz3zd3&input=this%20is%20a%20trifid%20cipher&debug=0), or verify all test cases at once [here](https://pyth.herokuapp.com/?code=m%40%2BG%3Bid3csCmtj%2B27x%2BG%3Bd3%2BW%21%25lz3zd3&test_suite=1&test_suite_input=this%20is%20a%20trifid%20cipher%0Atest%0Aoutput%0Atrifidcipher&debug=0).
```
m@+G;id3csCmtj+27x+G;d3+W!%lz3zd3 Implicit: z=input(), d=" ", G=lowercase alphabet
lz Length of z
% 3 The above, mod 3
W! If the above != 3...
+ zd ... append a space to z
m Map the elements of the above, as d, using:
+G; Append a space to the lowercase alphabet
x d Find the 0-based index of d in the above
+27 Add 27 to the above
j 3 Convert to base 3
t Discard first element (undoes the +27, ensures result is 3 digits long)
C Transpose the result of the map
s Flatten
c 3 Split into chunks of length 3
m Map the elements of the above, as d, using:
id3 Convert to decimal from base 3
@+G; Index the above number into the alphabet + space
Implicit print
```
Alternative 34 byte solution: `sm@+G;id3csCm.[03jx+G;d3+W!%lz3zd3` - rather than +27 and tail, uses `.[03` to pad with 0 to length 3. Can be 33 if the leading `s` is dropped.
*Edit: saved a byte by dropping leading `s` as character arrays are valid output*
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~153~~ ~~145~~ ~~138~~ 131 bytes
```
->a{a<<" "if a.size%3<1;a.map{|c|[(b=(c.ord%32-1)%27)/9,b%9/3,b%3]}.transpose.join.scan(/.{3}/).map{|x|((x.to_i(3)+65)%91+32).chr}}
```
[Try it online!](https://tio.run/##LYzrioMwFIT/9ymCEJr0ckRDu8javojIckwjplATkgjdNXl2624XhpmB@Rg3dd9Lf1mOV5yxrjOS6Z4geP2jqKiLT4QH2jnK2LDuwiQYd6OiPBaclh88rw4drXKxumgTBIejt8YruBs9gpc4shxmkXL@fnlGxp4QzJdmgu/PJ06rYi9KDnJwKS3NJguD9mQVkuB0r29Eajsolx3WSfnwm2YKdvprb@Sf2LSgUA5zDNGSvgnrJzrf7rbbtLwA "Ruby – Try It Online")
A quick and naive approach, works with lowercase text. Inputs and outputs arrays of characters.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 192 bytes
```
s->{String T="",R=T,C=T,r=T;for(int c:s){c-=c<33?6:97;T+=c/9;R+=c%9/3;C+=c%3;}for(var S:(s.length%3<1?T+2+R+2+C+2:T+R+C).split("(?<=\\G...)"))r+=(char)((Byte.valueOf(S,3)+65)%91+32);return r;}
```
[Try it online!](https://tio.run/##bVDfa9swEH7PX3EYDNLsqDRmLbGjhs2wsYdRSPzW9EFT7USZIxvpHAjBf3sqxSZ0rELH3Xf33c@9OIrp/u3vRR3axiDsHWYdqpp9ySb/@apOS1SN/jRo0ZTi4EOyFtbCb6E0nCcAbfenVhIsCnTq2Kg3OLgYWaNRevvyCsJsLb1SAX6MLRZyJ8zLazyQnqDiFzt9Og8QCh4E8YoXce7E8CKrGkOURpCppWc55XKRJMuHdP6YFRGXd/Ns5VQ4v0uy3BtJ1vuMozCwTolldam3uAuTxf2yiGbRykkezdLCWTlltq0VkoAsF3yz@ckYowGlJuLEz0gJ@X7Ckh1F3ZXPFVnHCY0evtJwfh8lM5qZEjujwWT9JbtueFsbS4sW@Li4fwHulAX3BThS5Q4lVbsrTRB/oLisj7jpsO3@8QypY@bo7ofefunxhL5OOsxAbyOsTxbLA3M1WetYWJHgl3blU4BNEFon@vnaL73hUAfxtUwMFRNtW5@IRwyb3F3nmzHiRCilQ/9@4qW/vAM "Java (JDK) – Try It Online")
Very naive approach. Takes a lowercase `char[]` as input but outputs a `String`.
## Explanations
```
s->{ // char[]-accepting lambda
String T="", // declare variables Table as an empty string,
R=T, // Row as an empty string,
C=T, // Column as an empty string,
r=T; // result as an empty string.
for(int c:s){ // for each character
c-=c<33?6:97; // map each letter to a number from 0 to 25, space to 26.
T+=c/9; // append the table-value to Table
R+=c%9/3; // append the row-value to Row
C+=c%3; // append the column-value to Column
} //
for(var S: // For each token of...
(s.length%3<1?T+2+R+2+C+2:T+R+C) // a single string out of table, row and column and take the space into account if the length is not coprime to 3...
.split("(?<=\\G...)")) // split every 3 characters
r+=(char)((Byte.valueOf(S,3)+65)%91+32); // Parses each 3-characters token into a number, using base 3,
// and make it a letter or a space
return r; // return the result
}
```
## Credits
* -14 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [R](https://www.r-project.org/), 145 bytes
```
function(s,K=array(c(97:122,32),rep(3,3)))intToUtf8(K[matrix(arrayInd(match(c(utf8ToInt(s),32[!nchar(s)%%3]),K),dim(K))[,3:1],,3,byrow=T)[,3:1]])
```
[Try it online!](https://tio.run/##LY7BCsIwDIZfZQ4GCcSD60Ed7gFk13kaO9RuZQXXljZDffpZdRBI/nz5@RNWnV32q16sYuMsRGpqGYJ8g4LzsTqUJYkSKYweBAlENJZbd2N9gqabJQfzgt/91Q6QtJqScUm4dVfLEDHZu51VkwxJFIXokRqkwczQIHYkqkNPJOj@Du5Zt9umxzVK7x/fL3KeTMxSySylaTNkyvhpDDnlPEZOzS3sl@/w5xtG0rh@AA "R – Try It Online")
I/O as strings; adds one space. The strange repetition of `[,3:1]` is because R's natural array indexing is somewhat different.
[Answer]
# APL+WIN, 102 bytes
```
⎕av[n[c⍳(⊂[2]((⍴t),3)⍴,⍉⊃(c←⊂[2]c,(,⍉9 3⍴c←9/⍳3),[1.1]27⍴⍳3)[(⎕av[n←(97+⍳26),33])⍳t←t,(3|⍴t←⎕)↓' '])]]
```
Explanation:
```
t←t,(3|⍴t←⎕)↓' ' Prompts for input and applies coprime condition
(⎕av[n←(97+⍳26),33]⍳ Indices of characters in APL atomic vector
c←⊂[2]c,(,⍉9 3⍴c←9/⍳3),[1.1]27⍴⍳3) Create a matrix of table, row column for 27 characters
⊂[2]((⍴t),3)⍴,⍉⊃ Extract columns of c corresponding to input and re-order
c⍳ Identify Column indices of re-ordered columns
⎕av[.....] Use indices back in atomic vector to give enciphered text
```
Example of screen shot of test case:
```
⎕av[n[c⍳(⊂[2]((⍴t),3)⍴,⍉⊃(c←⊂[2]c,(,⍉9 3⍴c←9/⍳3),[1.1]27⍴⍳3)[(⎕av[n←(97+⍳26),33])⍳t←t,(3|⍴t←⎕)↓' '])]]
⎕:
'output'
rrvgivx
```
[Answer]
**SAS, 305 bytes**
A hearty 'oof' for this SAS monstrosity. There's a lot of random string formatting that I thought I could avoid going into this; I'm sure there are better ways of doing some of this.
```
data;input n:&$99.;n=tranwrd(trim(n)," ","{");if mod(length(n),3)=0then n=cats(n,'{');f=n;l=length(n);array a(999);do i=1to l;v=rank(substr(n,i,1))-97;a{i}=int(v/9);a{i+l}=mod(int(v/3),3);a{i+l*2}=mod(v,3);end;f='';do i=1to l*3by 3;f=cats(f,byte(a{i}*9+a{i+1}*3+a{i+2}+97));end;f=tranwrd(f,"{"," ");cards;
```
Input is entered on newlines after the cards statement, like so:
```
data;input n:&$99.;n=tranwrd(trim(n)," ","{");if mod(length(n),3)=0then n=cats(n,'{');f=n;l=length(n);array a(999);do i=1to l;v=rank(substr(n,i,1))-97;a{i}=int(v/9);a{i+l}=mod(int(v/3),3);a{i+l*2}=mod(v,3);end;f='';do i=1to l*3by 3;f=cats(f,byte(a{i}*9+a{i+1}*3+a{i+2}+97));end;f=tranwrd(f,"{"," ");cards;
this is a trifid cipher
test
output
trifidcipher
```
Outputs a dataset containing the output in the variable `f`, along with a bunch of helper variables/array values.
[](https://i.stack.imgur.com/T7dbm.png)
Ungolfed/explanation:
```
data;
input n : & $99.; /* Read a line of input, maximum 99 characters */
n=tranwrd(trim(n)," ","{"); /* Replace spaces with '{' (this is the ASCII character following 'z', so it makes it easy to do byte conversions, and lets us not have to deal with spaces, which SAS does not like) */
if mod(length(n),3)=0then n=cats(n,'{'); /* If length of n is not coprime with 3, add an extra "space" to the end */
f=n; /* Set output = input, so that the string will have the same length */
l=length(n); /* Get the length of the input */
array a(999); /* Array of values to store intermediate results */
do i = 1 to l; /* For each character in the input... */
v = rank(substr(n,i,1))-97; /* Get the value of the current character, from 0-26 */
a{i}=int(v/9); /* Get the table of the current character and store at appropriate index, from 0-2 */
a{i+l}=mod(int(v/3),3); /* Get the row of the current character, from 0-2 */
a{i+l*2}=mod(v,3); /* Get the column of the current character, from 0-2 */
end;
f='';
do i = 1 to l*3 by 3; /* For each character in the output... */
f=cats(f,byte(a{i}*9+a{i+1}*3+a{i+2}+97)); /* Convert values back from base 3 to base 10, and convert back into ASCII value */
end;
f = tranwrd(f,"{"," "); /* Replaces our "spaces" with actual spaces for final output */
/* Test cases */
cards;
this is a trifid cipher
test
output
trifidcipher
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~146 141 139~~ 136 bytes
I/O is in lowercase.
```
s=>'931'.replace(/./g,d=>Buffer(s.length%3?s:s+0).map(c=>(o=(c>48?c-16:26)/d%3+o*3%27|0,++i)%3?0:(o+97)%123||32),i=o=0).split`\0`.join``
```
[Try it online!](https://tio.run/##bYzLaoQwGIX3fQo3YtI48ZIyFyEO9Dm6MMRE/yH1D0mcle9uhUIXZeCszvnO91BPFXUAn04Ljma3co@yL26iKXgw3iltSMWrqRxl/7laawKJ3JllSnMu7rGLrKb8W3miZU9QEt1/XO/61Jy79kyrMRcM30XeXra6ZAzo8ak7gux2oXnTim0TLS1Bojws0TtIw1c98AfCMgy7xiWiM9zhRCwp0gwxO6KyFMDCmGnwswkFpW//SRPTixrX5NdXw6/vT7f/AA "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input string
'931'.replace(/./g, d => // for each digit d = 9, 3 and 1:
Buffer( // create a buffer from:
s.length % 3 ? // if the length of s is coprime with 3:
s // the original input string
: // else:
s + 0 // the input string + an extra '0'
) //
.map(c => // for each ASCII code c from this Buffer:
( o = // update o:
( c > 48 ? // if c is neither a space nor the extra '0':
c - 16 // yield c - 16 (which gives 81 .. 106)
: // else:
26 // this is the 26th character (space)
) / d % 3 + // divide by d and apply modulo 3
o * 3 % 27 | 0, // add o * 3, apply modulo 27, coerce to integer
++i // increment i
) % 3 ? // if i mod 3 is not equal to 0:
0 // yield 0 (NUL character)
: // else:
(o + 97) % 123 // convert o to the ASCII code of the output letter
|| 32 // or force 32 (space) for the 26th character
), // end of map()
i = o = 0 // start with i = o = 0
).split`\0`.join`` // end of replace(); remove the NUL characters
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g3Öð׫SAð«3L3㩇ø˜3ô®Að«‡
```
Since no one posted a 05AB1E answer yet, I figured I'd post my own solution. I see now it's very similar to [*@Dennis♦*' Jelly answer](https://codegolf.stackexchange.com/a/177377/52210), even though I came up with it independently before I posted the challenge.
Input as string, output as a list of characters. Adds one space if the length is divisible by 3.
[Try it online](https://tio.run/##yy9OTMpM/f8/3fjwtMMbDk8/tDrY8fCGQ6uNfYwPLz608lHDwsM7Ts8xPrzl0DqwOFDgv4u916OGOQoaSof3K2kCWTr/80tLCkpLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnl4gr2SwqO2SQpK9v/TjQ9PO7zh8PRDq4MdD284tNrYx/jw4kMrHzUsPLzj9Bzjw1sOrQOLAwX@u9h7PWqYo6ChdHi/kiaQpfO/JCOzWAGIEhVKijLTMlMUkjMLMlKLuEpSi0u48ktLCkpLuCAyEAkA).
**Explanation:**
```
g3Ö # Check if the length of the (implicit) input is divisible by 3
# (results in 1 for truthy or 0 for falsey)
# i.e. "out" → 1
# i.e. "test" → 0
ð× # Repeat a space that many times
# i.e. 1 → " "
# i.e. 0 → ""
« # And append it to the (implicit) input
# i.e. "out" and " " → "out "
# i.e. "test" and "" → "test"
S # Then make the string a list of characters
# i.e. "out " → ["o","u","t"," "]
# i.e. "test" → ["t","e","s","t"]
A # Push the lowercase alphabet
ð« # Appended with a space ("abcdefghijklmnopqrstuvwxyz ")
3L # Push list [1,2,3]
3ã # Cartesian repeated 3 times: [[1,1,1],[1,1,2],...,[3,3,2],[3,3,3]]
© # Save that list of triplets in the registry (without popping)
‡ # Transliterate, mapping the letters or space to the triplet at the same index
# i.e. ["o","u","t"," "] → [[2,2,3],[3,1,3],[3,1,2],[3,3,3]]
# i.e. ["t","e","s","t"] → [[3,1,2],[1,2,2],[3,1,1],[3,1,2]]
ø # Zip, swapping all rows/columns
# i.e. [[2,2,3],[3,1,3],[3,1,2],[3,3,3]] → [[2,3,3,3],[2,1,1,3],[3,3,2,3]]
# i.e. [[3,1,2],[1,2,2],[3,1,1],[3,1,2]] → [[3,1,3,3],[1,2,1,1],[2,2,1,2]]
˜ # Flatten the list
# i.e. [[2,3,3,3],[2,1,1,3],[3,3,2,3]] → [2,3,3,3,2,1,1,3,3,3,2,3]
# i.e. [[3,1,3,3],[1,2,1,1],[2,2,1,2]] → [3,1,3,3,1,2,1,1,2,2,1,2]
3ô # Split it into parts of size 3
# i.e. [2,3,3,3,2,1,1,3,3,3,2,3] → [[2,3,3],[3,2,1],[1,3,3],[3,2,3]]
# i.e. [3,1,3,3,1,2,1,1,2,2,1,2] → [[3,1,3],[3,1,2],[1,1,2],[2,1,2]]
® # Push the triplets from the registry again
Að« # Push the lowercase alphabet appended with a space again
‡ # Transliterate again, mapping the triplets back to letters (or a space)
# (and output the result implicitly)
# i.e. [[2,3,3],[3,2,1],[1,3,3],[3,2,3]] → ["r","v","i","x"]
# i.e. [[3,1,3],[3,1,2],[1,1,2],[2,1,2]] → ["u","t","b","k"]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 42 bytes
```
;Êv3 ?UpS:U
m!bS=iC)®+27 ì3 ÅÃÕc ò3 £SgXì3
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=O8p2MyA/VXBTOlUKbSFiUz1pQymuKzI3IOwzIMXD1WMg8jMgo1NnWOwz&input=WyJ0IiwiaCIsImkiLCJzIiwiICIsImkiLCJzIiwiICIsImEiLCIgIiwidCIsInIiLCJpIiwiZiIsImkiLCJkIiwiICIsImMiLCJpIiwicCIsImgiLCJlIiwiciJdCi1Q)
The core of this answer comes from a deleted answer by Shaggy, but he never came back to handle inputs of length divisible by 3 so this is a [fixed version](https://ethproductions.github.io/japt/?v=1.4.6&code=O8p2MyA/VXBTOlUKbSFiUz1pQymuKzI3IOwzIMXD1WMg8jMgo1NnWOwz&input=WyJ0IiwiciIsImkiLCJmIiwiaSIsImQiLCJjIiwiaSIsInAiLCJoIiwiZSIsInIiXQotUA==).
Explanation:
```
; #Set C to the string "abcdefghijklmnopqrstuvwxyz"
Ê #Get the length of the input
v3 ? #If it is divisible by 3:
UpS # Add a space
:U #Otherwise don't add a space
#Store the result in U
S=iC) #Set S to C plus a space
m #For each character in U:
!bS # Get the position of that character in S
® Ã #For each resulting index:
ì3 # Convert to base 3
+27 Å # Including leading 0s up to 3 places
Õ #Transpose rows and columns
c #Flatten
ò3 #Cut into segments of length 3
£ #For each segment:
Xì3 # Read it as a base 3 number
Sg # Get the letter from S with that index
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 178 bytes
```
s=>{int[]a={9,3,1},b=(s.Length%3>0?s:s+0).Select(c=>c<97?26:c-97).ToArray();s="";for(int i=0,k,l=b.Length;i<l*3;s+=(char)(k>25?32:97+k))k=a.Sum(p=>b[i%l]/a[i++/l]%3*p);return s;}
```
[Try it online!](https://tio.run/##XY9Na4QwEIbv/RVBEJI161qlFY2J9NJTD4XtTTzEbFyDrkomHsqyv90KW@gHDAw8vO/DjIK9ArO@LqMqwFkznim6b4FaxFfg4mpGV9WSXzOa0McbbTiG8E2PZ9f5iYhKyCGISHjUg1YOKy5UkaVl/JyrfZaS8GN6sVZ@YsKAex5rJ4s3ITI8oj0dePOtYqYYdgmDgGPVSUtwL@KnMonzLA16Qnouw@NywTMXTWX8oT7IygTBYaj9ZDcTZrVb7IiA3Vb28L7d73CLPdcZQNtItL3UmhNSZu609Qj5HdLg/pJpcfPyj90FP/31Cw "C# (Visual C# Interactive Compiler) – Try It Online")
Less golfed... It's still confusing :)
```
// s is an input string
s=>{
// powers of 3
int[]a={9,3,1},
// ensure the length of s is coprime to 3
// and convert to numbers from 0-26
b=(s.Length%3>0?s:s+0).Select(c=>c<97?26:c-97).ToArray();
// reset s to collect result
s="";
// main loop
for(
// i is the main index variable
// k is the value of the encoded character
// l is the length
int i=0,k,l=b.Length;
// i continues until it is 3x the length of the string
i<l*3;
// convert k to a character and append
s+=(char)(k>25?32:97+k)
)
// compute the trifid
// (this is the confusing part :)
k=a.Sum(p=>b[i%l]/a[i++/l]%3*p);
// return the result
return s;
}
```
]
|
[Question]
[
*Related: [Let's design a digit mosaic](https://codegolf.stackexchange.com/questions/167337/lets-design-a-digit-mosaic), [Print/Output the L-phabet](https://codegolf.stackexchange.com/questions/87064/print-output-the-l-phabet). [Sandbox post here](https://codegolf.meta.stackexchange.com/a/16667/78039)*
Given 2 inputs `C = columns and rows, S = starting point` output a matrix as follow:
```
Input 4, 3
1 2 3 0
2 2 3 0
3 3 3 0
0 0 0 0
```
**Explanation**
**Given** `C = 4, S = 3`
1) Create a `C x C` matrix filled with `0`
```
4 columns
4 _____|____
| |
r --0 0 0 0
o | 0 0 0 0
w | 0 0 0 0
s --0 0 0 0
```
2) Fill with `S` values within row and column `S`, then subtract 1 from `S` and repeat until `S = 0`. This case `S = 3`
```
Column 3
S = 3 |
v
0 0 3 0
0 0 3 0
Row 3-->3 3 3 0
0 0 0 0
Column 2
S = 2 |
v
0 2 3 0
Row 2-->2 2 3 0
3 3 3 0
0 0 0 0
Column 1
S=1 |
v
Row 1-->1 2 3 0
2 2 3 0
3 3 3 0
0 0 0 0
Final Result
1 2 3 0
2 2 3 0
3 3 3 0
0 0 0 0
```
---
**Rules**
* Assume `C >= S >= 0`
* The output can be a matrix, list of lists, array (1-dimensional or 2-dimensional) etc.
* You can take inputs via any [default I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* Your program, function, etc... may be 1-indexing or 0-indexing. Please specify which one is.
**Note** Explanation is 1-indexing
---
Winning criteria [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
»>⁴¬×»µþ
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//wrs@4oG0wqzDl8K7wrXDvv/Dp0f//zT/Mw "Jelly – Try It Online")
## How it works
**Jelly's Outer Product Atom (`þ`)**
You can think of Jelly's outer product atom, `þ`, as a quick (operator) that, given integer arguments \$X\$ and \$Y\$ (in this case \$X=Y=\text{first argument }\$), produces the following matrix of tuples:
$$\left[\begin{matrix}
(1, 1) & (2, 1) & (3, 1) & \cdots & (X, 1) \\
(1, 2) & (2, 2) & (3, 2) & \cdots & (X, 2) \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
(1, Y) & (2, Y) & (3, Y) & \cdots & (X, Y)
\end{matrix}\right]$$
It also applies the link right before it to all pairs, let's call it \$\:f\$, which behaves like a function which takes two arguments, producing something like this:
$$\left[\begin{matrix}
f(1, 1) & f(2, 1) & f(3, 1) & \cdots & f(X, 1) \\
f(1, 2) & f(2, 2) & f(3, 2) & \cdots & f(X, 2) \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
f(1, Y) & f(2, Y) & f(3, Y) & \cdots & f(X, Y)
\end{matrix}\right]$$
**How is it relevant to the task at hand?**
This works by noticing that every value in the expected output is just a table of maximal indices, or \$0\$ if this maximum exceeds our second argument. Therefore, we can create the following link to perform this mapping:
```
»>⁴¬×» – Dyadic (2-argument) link.
» – Maximum of the X, Y coordinates.
>⁴ – Check if this exceeds the second argument of the program.
¬ – Negate this boolean.
×» – And multiply by the maximum, computed again.
```
[Answer]
# [R](https://www.r-project.org/), ~~47~~ 41 bytes
```
function(C,S,m=outer(1:C,1:C,pmax))m*!m>S
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0/DWSdYJ9c2v7QktUjD0MpZB4QLchMrNDVztRRz7YL/p2mY6BhrcoEoA83/AA "R – Try It Online")
1-indexed. Generates the outputs for `S==C` (no zeros) then zeroes cells which have a value `>S` using matrix multiplication (thanks Giuseppe for 4 bytes!).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 31 bytes
```
@(C,S)(u=max(t=1:C,t')).*(u<=S)
```
Anonymous function that returns a matrix. Uses 1-based indexing.
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bw1knWFOj1DY3sUKjxNbQylmnRF1TU09Lo9TGNljzf5qGiY6x5n8A "Octave – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~47~~ 45 bytes
-2 bytes by changing the output format to one-dimensional list.
```
c&s|x<-[1..c]=[sum[j|j<=s]|j<-x>>=(<$>x).max]
```
[Try it online!](https://tio.run/##VZBBS8NAFITv/oqhlJJAExB7kiQgepJ60YOHNMiS3dptN2@X3beYQv973EoUvLzDzHzM8A4inJQxkx6c9YwnwaLc6sDIEGlvjfTIURSwZM4gpaSS2FsP5xXzGTayizz1q3AZq6K9Lcu@q9sQh/Z4OVZ16NItxqaps2rZjHk5iLGbBqEJNaS9Adp@HTpUBQbh4JWQKPFlvQxIAD4VP1piRRxS1ihOkRANJ7rHClcx1b@x3xIWaeXrj3u/o8XV8Zp@gX/BHaVob32ynKVUxXZG0oiXjxnMWJzU@0EbhYwsp10Ujcmx/HtM9hzDVQ/OaH5gbPK5LZ82uPsG "Haskell – Try It Online")
## Explanation
The term `x >>= (<$> x) . max` is a golfed version of
```
concat [ max i <$> x | i <- x ]
```
which evaluates to `[1,2,3,4..c, 2,2,3,4..c, 3,3,3,4..c, ..., c,c,c,c..c]`. Now we only need to force the values to `0` once they exceed `s` which we achieve with `sum [ j | j <= s]`.
[Answer]
**APL(Dyalog Classic), 12 bytes**
```
{⍺ ⍺↑∘.⌈⍨⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpHvbsUgPhR28RHHTP0HvV0POpd8ah386PerbX//5sopCkYc6mrc5kBGSYA)
Any tips on turning this into a train are welocome.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 12 bytes
```
o×⎕≥o←∘.⌈⍨⍳⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe1//uHpj/qmPupcmv@obcKjjhl6j3o6HvWueNS7GSgMUvM/jcuEyxgA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# JavaScript (ES6), 61 bytes
Takes input in currying syntax `(c)(s)`, where *s* is 1-indexed. Returns a 1-dimensional array.
```
c=>s=>[...Array(c*c)].map((_,k)=>(k=k%c>k/c?k%c:k/c)<s?-~k:0)
```
[Try it online!](https://tio.run/##Fcy9DoIwFEDhnafooOm9UqqJTsSWOPgCrmKEXH6EIiWUGA3BV0ecvjOdOn2ljvqqG4LWZvlcqJmUdkpfpZSnvk8/QBvCm3ymHcBdGFQajDJr0mZL0WK4iEcXBV8T7nAecjcwxYAEc8iUZlAAISztM85x@Qz0gEtent8dJBDHmS8iHFcjTVMiGC85oqxt1QKPW46eR7Z1tsllY0v4z@Eg2B5x/gE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁴Ri»µþ
```
A full program\* taking integers `C` and `S` which prints the Jelly representation of a list of lists of integers as defined (1-indexed).
**[Try it online!](https://tio.run/##AR0A4v9qZWxsef//4oG0UmnCu8K1w77/w6dH//8xNv8xMQ "Jelly – Try It Online")** (formats the result of the dyad as a grid of numbers for easier reading)
### How?
```
⁴Ri»µþ - Main Link: C, S
þ - outer product with:
µ - the monadic function (i.e. f(x,y) for x in [1..C] for y in [1..C]):
» - maximum (of x and y)
⁴ - program's 4th argument = 2nd input = S
R - range = [1,2,3,...S]
i - first index of (the maximum) in (the range) or 0 if not found
- as a full program: implicit print
```
---
\* The reason this is a full program is down to the use of the program argument access, `⁴`. As a dyadic link this code would rely on how the program which is using it is called.
Reusable dyadic link in 8 bytes (taking S on the left and C on the right): [`RiⱮⱮ»þ`}`](https://tio.run/##y0rNyan8/z8o89HGdUB0aPfhfQm1/w8vd///39Dwv6EZAA "Jelly – Try It Online")
Reusable dyadic link in 8 bytes (taking C on the left and S on the right): [`RiⱮⱮ⁹»þ¤`](https://tio.run/##y0rNyan8/z8o89HGdSDUuPPQ7sP7Di35f3i5@///hob/Dc0A "Jelly – Try It Online")
[Answer]
# Java 10, 88 bytes
```
C->S->{var r=new int[C][C];for(;S>0;)for(int s=S--;s-->0;)r[S][s]=r[s][S]=S+1;return r;}
```
[Try it online.](https://tio.run/##jZFBS8QwEIXv/oo5tmjCFhXB2IIsCB4EIcfSQ@y2S2o3Lcm0Wpb@9jrdprgHFSGEx8yb8L1JpXrFqt37lNfKOXhR2hwvABwq1DlU1OUd6pqXnclRN4Y/efHwbLDYF/bqfyZtMM3SLEmghHjaskSy5NgrCzY2xcepvc3oiLKxgZDJRoSzojq4WDImHGNz0aYyS10WW7pIxvIyErbAzhqwYpwEsdNpu7ea8H2KvtE7OFCyQKLVZp9moMI5JRlpFodXqmJQctW29RDchl5ch6H41XWzuqK/XNFmtd0ttnEBPCc7n/NrIloi/fSQfhEzNtyvrVMHQA4OiwNvOuTt/EJtgu//eLRWDY5js@QO1Ir6w5SnG6cv)
**Explanation:**
```
C->S->{ // Method with two int parameters and int-matrix return-type
var r=new int[C][C]; // Result-matrix of size `C` by `C`
for(;S>0;) // Loop as long as `S` is not 0 yet:
for(int s=S--;s-->0;) // Inner loop `s` in the range (`S`, 0]
// (and decrease `S` by 1 in the process with `S--`)
r[S][s]=r[s][S]=S+1; // Set the values at both {`S`,`s`} and {`s`,`S`} to `S+1`
return r;} // Return the result
```
[Answer]
# [PHP](http://www.php.net/), 92 bytes
This is "1-indexing".
```
<?list(,$c,$s)=$argv;for(;$i++<$c;print"\n")for($j=0;$j++<$c;)echo$s<$i||$s<$j?0:max($i,$j);
```
To run it:
```
php -n <filename> <c> <s>
```
Example:
```
php -n collapsing_matrice.php 8 6
```
Or [Try it online!](https://tio.run/##JclBCoMwEEbhu8i/SDAFV0WciBdxI6GtE9okJEFceHZHpKsH30trErHTl0tVBs6g6BFL/mz0jlkRuG0tHKXMoTZzaPTN8GNH8P@lX26NKBZ8HHf81A2/ZVdgA69JRHp5njFVjqHII1w "PHP – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▓╜.→,cΘ○╤æ
```
[Run and debug it](https://staxlang.xyz/#p=b2bd2e1a2c63e909d191&i=4,+3%0A6,+0%0A0,+0%0A2,+2&a=1&m=2)
How it works:
```
R(Xm]i*xit+J Full program, implicit input.
R 1-based range of S
( Right-pad with zeroes to length C
X Save to X register
m Map (same as [here](https://codegolf.stackexchange.com/a/167360)):
] Wrap in list
i* repeat by iteration index
xit Remove first elements from X register
+ Append
J Stringify each element, and join by space
```
[Answer]
# Excel VBA, 65 bytes
An immediate window function that takes input from `[A1:B1]` and outputs to the range `[C1].Resize([A1],[A1])`.
```
[C1].Resize([A1],[A1])=0:For s=-[B1]To-1:[C1].Resize(-s,-s)=-s:Next
```
### Input / Output
Input is in range `[A1:B1]`
[](https://i.stack.imgur.com/8eC5y.png)
[Answer]
# [J](http://jsoftware.com/), 18 bytes
```
,~@[{.[:>./~1+i.@]
```
Much longer than both APL solutions.
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F@nziG6Wi/ayk5Pv85QO1PPIfa/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@golCmoIxhGkGZJr8BwA "J – Try It Online")
[Answer]
# MATLAB, 58 bytes (Thanks to anonymous user)
```
function o=f(c,s);o=zeros(c);for j=s:-1:1;o(1:j,1:j)=j;end
```
Just filling the elements of matrix with appropriate number, running a loop. Maybe possible to be cleverer with `arrayfun`
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 85 bytes
```
c=>s=>{var r=new int[c,c];for(;s>0;)for(int j=s--;j-->0;)r[s,j]=r[j,s]=s+1;return r;}
```
[Try it online!](https://tio.run/##dVCxasMwEN39FUfoIGM7JEOhVJGXlk4tFDp0MB6MIgcJW4I7JSUYf7sr22niUvqG0/HuvdOTJGXSoRpkUxHBe9RFEEC@8loCqmrvbHOGjzN51a5fjlbutPXpXyKUIi3zHGoQ0SBFTiLvThUCCqu@prFMZclrh4xTvuHx2AUajKAs4ybLRhILSk0psDAplYKSLUflj2gBeT/ABTxahjw5vYe3SltGHrU9FCVUeKB40szPGTFmkSDggf@i2kDVTMbsPr4NQjSYsukw3aRgeOh2IMORJPFVdlt@NZnRwMHMarNU/@DydU/OkmvU@hO1V@xu1bWFDjeVj8/bHmC1SPOf6VVbxRa6PpprP3wD "C# (.NET Core) – Try It Online")
A port of [Kevin Cruijssen's answer](https://codegolf.stackexchange.com/a/168879/70347), which was much better than mine.
[Answer]
# [Python 2](https://docs.python.org/2/), 58 bytes
```
lambda C,S:[-~max(i%C,i/C)*(i%C<S>i/C)for i in range(C*C)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUcFZJ9gqWrcuN7FCI1PVWSdT31lTC8SyCbYDsdPyixQyFTLzFIoS89JTNZy1nDVj/6ekpim4aQB1alpxcToq2CqkgTlcnAVFmXklICNhTEcuTnQTNK2gUtGZWs5WQKztHMvF5aZhomOsyfUfAA "Python 2 – Try It Online")
Outputs a 1D list of length `C*C`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Eθ⪫IEEθ⌈⟦ιλ⟧∧‹λη⊕λ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUCjUEfBKz8zT8M5sRgiABX0TazIzC3N1YjO1FHIidXU1FFwzEvR8EktLtbI0VHIAPI985KLUnNT80pSUzRyNDVBSpQUlIC09f//0SY6Csax/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. 3 bytes used to convert the output to decimal and format it nicely. Explanation:
```
θ Input `C`
E Map over implicit range
θ Input `C`
E Map over implicit range
λ Inner index
ι Outer index
⌈⟦ ⟧ Maximium
E Map over results
λ Current value
η Input `S`
‹ Less than
λ Current value
⊕ Incremented
∧ Logical AND
I Cast to string
⪫ Join with spaces
Implicitly print on separate lines
```
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 67 bytes
```
import StdEnv
$n s=[[if(i>s||j>s)0(max i j)\\i<-[1..n]]\\j<-[1..n]]
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLJU@h2DY6OjNNI9OuuKYmy65Y00AjN7FCIVMhSzMmJtNGN9pQTy8vNjYmJgvO/h9ckgg0wlZBRcFEwej/v@S0nMT04v@6nj7/XSrzEnMzk4sB "Clean – Try It Online")
Defines `$ :: Int Int -> [[Int]]` giving an answer using 1-based indexing.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 37 bytes
```
{((^$^c+1 Xmax^$c+1)Xmin$^s+1)X%$s+1}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMjTiUuWdtQISI3sSJOBcjSjMjNzFOJKwaxVFWAVO3/4sRKhTQNvWiDWB0FvWjDWE29ovyS/CKwiKZeVn5mnoZSTJ6Spo4CiFJIyy/i0jDRUTDW1OHSMDTSUTDXtP4PAA "Perl 6 – Try It Online")
Returns the matrix as 1-dimensional array.
[Answer]
# Mathematica 44 bytes
```
Table[If[i <= s && j <= s, Max[i, j], 0], {i, c}, {j, c}]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
T0:´ṪYḣ⁰`R0
```
[Try it online!](https://tio.run/##AR4A4f9odXNr//9UMDrCtOG5qlnhuKPigbBgUjD///8z/zQ "Husk – Try It Online") The function takes `S` followed by `C`.
]
|
[Question]
[
**This is part of a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. [Go here](https://codegolf.stackexchange.com/q/144600/8478) for the cops' part.**
## The Robbers' Challenge
A cop's answer can be cracked by removing any subset of characters from the Haystack program, so that it outputs `Needle` instead of `Haystack` (while still being a valid submission in the same language). You don't have to find the exact same solution as the cop intended, as long as yours is valid by the above constraints.
If you manage this, post an answer with the solution, linking to the cop's answer, and leave a comment on the cop's answer linking back to yours.
The robber who cracks the most cop answers wins. Ties are broken by the sum of sizes of the cracked cop answers (in favour of the robber who cracks longer submissions).
Each cop answer can only be cracked once, and of course, you're not allowed to crack your own answer. If the cop's answer turns out to be invalid before or after being cracked, it is not counted towards the robber's score.
## Examples
Here are a couple of simple examples in different languages:
```
Ruby
Haystack: puts 1>0?"Haystack":"Needle"
Delete: XXXXXXXXXXXXXXX
Needle: puts "Needle"
Python 2
Haystack: print "kcatsyaHeldeeN"[-7::-1]
Delete: XXXXXXXX XX
Needle: print "eldeeN"[::-1]
```
Note that the subset of removed characters doesn't have to be contiguous.
[Answer]
# JavaScript, 85 bytes (ES6)
Cracks [Arnauld's answer](https://codegolf.stackexchange.com/a/144614/3845)
```
f=(k=b=x=35)=>x--?f(k*4853461&268435455):k&2?'N'+(k^12408877).toString(b):'Haystack'
```
### "Needle" demo
```
f=(k=b=x=35)=>x--?f(k*4853461&268435455):k&2?'N'+(k^12408877).toString(b):'Haystack'
console.log(f())
```
### Explanation
The original function was:
```
f=(k=b=x=35)=>x--?f(k*74837258394056219&268435455):k&2?'N'+(k^124038877).toString(b):'Haystack'
```
which is more readable as:
```
f = (k=b=x=35) => {
if (x--) {
return f(k*74837258394056219&268435455);
} else {
if (k&2) {
return 'N'+(k^124038877).toString(b);
} else {
return 'Haystack';
}
}
}
```
Note that when `n=21625674`, then `n.toString(35)` is `'eedle'`.
The 35 in the input probably cannot be changed to a subset (because we want a base large enough to contain all the letters 'del', so we need a base that's at least 22). So the numbers to change are `74837258394056219`, `268435455`, and `124038877`. We want to replace them with numbers a, b, c, each formed with a subset of the digits of the original numbers, such that the function `g(k) = (k * a & b)`, starting with `k=35` and iterated 35 times, and then XORed with c, gives `21625674`.
For this one, after thinking a bit, as the lengths are small (the maximal `a` has length 17, `b` and `c` have length 9), I just used brute-force :-) Wrote [a C++ program](https://gist.github.com/shreevatsa/82ef6bc5a513dea5b51436253793c2ff) to generate all possible numbers `a`, `b`, `c` formed as subsets of the original numbers, iterate through all `a` and `b`, and check whether the required `c` was in the set. Runs in about 15 seconds, and the only output is `a=4853461`, `b=268435455`, `c=12408877` (turns out the number `b` doesn't need to be changed). I'm not sure whether there's a more clever way of inverting this function.
[Answer]
# [Haystack](https://github.com/kade-robertson/haystack), 82 bytes
Cracks [HyperNeutrino's Answer](https://codegolf.stackexchange.com/a/144607/68261)
```
0\1-c\
/
?10F17+c8F+4+cd8F+3+c6-c1+c,c2+c8+c|
0 \1++c,c|
F/c++2F8
c\8F+2+cd
```
[Try it online!](https://tio.run/##FcoxDoAgEETRfk9BPxJYNGpnxyloyFCYWGpjwt1xnWaSn3fW934qrzFiUc8iwdnk0Jh1A/eMBWx2M7h6KjgxWQe7uGi0KP7WJQcCKe/CYtxMG@MD "Haystack – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 96 bytes
Cracks [Funky Computer Man's answer](https://codegolf.stackexchange.com/a/144608/69059).
```
([((((()()())){}){}){}](()[()]({}([(((()()()){}))[]])[]({}({}()(((()(({}){}){}){}){}())))[]))())
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyNaAwQ0QVBTs7oWgmKBItEamrEa1bUQBRB5oJxmdGwsEIMkgEgTIqcB0wdBIJOAajRBWv7//6/rCAA "Brain-Flak – Try It Online")
This was a fun challenge.
The -24 at the beginning which converts `y` to `a` in the original is now used to convert `e` to `M`, which is then converted to `N` in place by changing the entire end loop to `())`. The first pushed letter `k` was changed to `e` simply by removing a push-pop that adds 6 to it. The rest mostly just fell into place, with some humorous missteps along the way (including one program whose output was `Meddle`).
Comparison of the two programs:
```
Haystack: ([((((()()())){}){}){}](()([()](()({}([((((()()()){})))[]])[]({}({})[{}]()({}((()(({}){}){}){}){}())))[][][][][][]))[]))(((()[]){}){({}[()()])}{})
Needle: ([((((()()())){}){}){}](() [()] ({}([ (((()()()){})) []])[]({}({} ()( ((()(({}){}){}){}){}())))[] )) () )
```
[Answer]
## Haskell
Cracks [@Laikoni's answer](https://codegolf.stackexchange.com/a/145206/34531).
```
s=map;hay=zipWith;a=head;h=s a.(hay(scanr id).s a<*>s(succ<$))$words"Haysta ayst ackH ays k ayst"
```
[Try it online!](https://tio.run/##HYmxDoMgFEV/5cU4QAd/AHF26Nah8w2YPIIi4WEa@/NUu9yccy5D4rKurYndkA3jtN@Q36GygeUF3rAVwqCuR4lDKhS8Hq40PiZRcjg39lr3n7146WacUkH3Elycb6L4965tCIks5aO@ankm4vYD "Haskell – Try It Online")
Original code:
```
hays=map;hay=zipWith;stack=head;h=stack{-
hay.(hays.(stackany hay$or id).stack hay
<*>hays(sum$stack haystack<$>hay))-}$words
"Haystack Hayst ackH aysta ckH aystac k"
```
replacing removed characters with underscores:
```
___s=map;hay=zipWith;__a__=head;h=s______
_a_.(hay__(s__c_an_______r id).s____ _a_
<*>___s(su_____c________c_<$____))__$words
"Haysta__ _ayst ackH ays__ _k_ ayst____"
```
How `Needle` is constructed: the string at the end of the code is split into words. The first char of each word is incremented as many times as there are characters in the word, e.g. `Haysta` -> `H` plus 6 chars -> `N`.
[Answer]
# [Hexagony](https://www.esolangs.org/wiki/hexagony), 17 bytes, [H.PWiz](https://codegolf.stackexchange.com/a/145337/60483)
```
];N@cl;e;;(\.s.;_
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/z/W2s8hOcc61dpaI0avWM86/v9/AA "Hexagony – Try It Online")
## Comparison with original:
```
];N.@cl;e@;;(\H/;ya;_.>s.;t//<._ original
];N @cl;e ;;(\ . s.; _ modified
```
## Visualisation:
```
] ; N
@ c l ;
e ; ; ( \
. s . ;
_ . .
```
## Explanation
Bonus marks - uses all 6 IPs and all but one of the cells!
[](https://i.stack.imgur.com/ggzPb.png)
The IP #0 starts by heading right along the black path into the `]`.
We then transition to IP #1, which heads along the red path, printing `N` with `N;` then wrapping back into the `]` again.
We then transition to IP #2, which heads along the blue path, storing `e` in the current memory cell, then along the green path, executing (with a reflection at `\`) `;;(;` which prints `ee`, decrements the memory cell from `e` to `d` then prints `d`.
The IP continues along the orange path, executing `Nl;se` which prints `l`, and stores `e` in the current memory cell. It continues along the brown path, printing the `e` with `;`. By this point we have already printed `Needle`, so the rest is just finishing. The IP stores `c`, then hits `]`.
[](https://i.stack.imgur.com/eKOou.png)
We then transition to IP #3, which heads along the blue path, hitting `\`, bouncing into `_` which bounces into `]`.
We then transition to IP #4, which heads along the green path, bouncing on `_`, then `\` and branching to `]` (since `c` is positive).
Finally, we transition to IP #5, which stores `e` then exits with `@`.
[Answer]
# [Python 2](https://docs.python.org/2//It4CCRttzSriD349Vaa0wxveJNbfSWZe@cjp1KVfI/cLrmwVDVN9p1YIGxc4D9gGBwYY7hF9UhFsWI5HZvTp9EGYMi767yTNo40eU0j7qMtHvF8sWtZ5bmDcdohRuz9Bw "Python 2 – Try It Online"), 123 bytes
Cracks [agtoever's Answer](https://codegolf.stackexchange.com/a/144682/46523)
```
import numpy
print "".join([dir(numpy)[int(i)][0] for i in numpy.poly1d([-143/2e1,-31,14,131,61,184])(numpy.arange(-3,3))])
```
[repl.it](https://repl.it/MRuh/3)
Comparison:
```
print "".join([dir(numpy)[int(i)][1-0] for i in numpy.poly1d([-1*1433/252e1,-3232/1920.,4026./72/2/3.,613/(6*4.)*1,-4723./1.8e2,-9763/120.,-2689/(-1+5*17.),1+138*.4*2])(numpy.arange(-12/3,13%9))])
print "".join([dir(numpy)[int(i)][ 0] for i in numpy.poly1d([-1 43 /2 e1,-3 1 , 1 4 , 1 3 1 , 6 1 ,1 8 4 ])(numpy.arange(- 3, 3 ))])
```
I had a lot of fun finding solutions that printed `Meedle` and `Needlf` by fitting a polynomial to the median of the indices of the numpy symbols that start with each of the letters in `Needle`. I then tried to find similar coefficients with subsets of the original program by hand, but I ended up having to resort to brute forcing one to find a valid solution.
[Answer]
## [Hexagony](https://github.com/m-ender/hexagony), 19 bytes, [Martin Ender](https://codegolf.stackexchange.com/a/144625/75557)
```
[@;(...e<l.a;./;N>;
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/z/awVpDT08v1SZHL9FaT9/az876/38A)
### Comparison with original
```
H[@;(...e<l.a;./$.>;\sN;\ac.>).;;;._y
[@;(...e<l.a;./ ; N > ;
```
### Unfolded code
```
[ @ ;
( . . .
e < l . a
; . / ;
N > ;
```
So, I've never written anything in Hexagony, but I figured with only 37 bytes that I could come up with the crack. Martin, I hope you know I put *a lot* of time into trying to figure this out. :)
I may be incorrect, but I will explain what I *think* this code is doing:
The program starts off with `[`, which automatically moves to IP #5. This IP starts in the west corner, heading toward the `[` once again, which moves it to IP #4. From here, it executes `N;e` then heads to the southeast corner and executes `;`, bounces to the right for another `;` then wraps to `(` which decrements the current `e` to a `d`. It then continues (with a wrap) to `...;.` then bounces to the `l` and gets to the `[` one last time, moving to IP #3. It executes `;`, `>` redirects to the northwest to `.` then `<` redirects to the west, hitting `e`, wrapping to `;`, and terminating on the `@`.
Verbose version
```
[ We move to the previous instruction pointer (starting at the e and moving NE)
e e is entered into the current memory cell
( Decrements the memory cell to d
[ We move to the previous instruction pointer (starting at the N and moving NW)
N N is entered into the current memory cell
; Outputs N
e e is entered into the current memory cell (IP now wraps to the SE corner)
; Outputs e
/ Mirrors IP to the east
; Outputs e (IP now wraps to ( on NW edge)
( Decrements the memory cell to d
... No-ops (IP now wraps to ; on SW edge)
; Outputs d
. No-op
/ Mirrors IP to the NW
l l is entered into the current memory cell
. No-op
[ We move to the previous instruction pointer (starting at the ; and moving west)
; Outputs l
> Redirects the IP NW
. No-op
< Redirects the IP west
e e is entered into the current memory cell (IP now wraps to ; on the NE corner)
; Outputs e
@ Terminates the program
```
I am so glad that you used a normal hexagon size for the Needle program; I was checking size 19 programs (for a length-3 side hexagon) when I realized you could remove any number of characters and it would automatically fill the hexagon with `.`s at the end, which would make it dramatically more difficult to crack. As it is, Hexagony is an evil language for this challenge because (mostly) any character that is removed changes the whole execution path of the program. That being said, I enjoyed trying to come up with this, even if I did end up brute forcing it at the end. :)
[Answer]
# Javascript, 91 bytes
```
_=>(+{}+[])[+[]]+([][[]]+[])[3]+([][[]]+[])[3]+([][[]]+[])[2]+(![]+['t'])[2]+([][[]]+[])[3]
```
Cracks [this](https://codegolf.stackexchange.com/a/144629/36445). It actually was fun.
```
let f =
_=>(+{}+[])[+[]]+([][[]]+[])[3]+([][[]]+[])[3]+([][[]]+[])[2]+(![]+['t'])[2]+([][[]]+[])[3]
console.log(f())
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Cracks [Jonathan Allan's Answer](https://codegolf.stackexchange.com/a/144615/46523)
```
“¡#ɦṢÞɠ»ḟ“¡pṄ»
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDC5VPLnu4c9HheScXHNr9cMd8sFjBw50th3b//w8A "Jelly – Try It Online")
Comparison:
```
“¿ọ⁽ṅ*FỊ⁼g£¡#!ʋzoɦṪ£ṢÞḲÐɠ`”m3⁾“»jVḟ“¡!pṄ»
“ ¡# ɦ ṢÞ ɠ » ḟ“¡ pṄ»
```
I used `œc` to iterate through various subsets of the literal strings, used `tr -d` for each possible filter, and `grep`ed for Needle. Using the assumption that none of the used characters in the first string were used in the answer let it find an answer in under 15 seconds.
[Answer]
# [Python 2](https://docs.python.org/2/), 73 bytes
Cracks [user71546's Answer](https://codegolf.stackexchange.com/a/144697/46523).
```
a,b,s=2707385038437,0b10000000,""
while a>0:
s=chr(a%b)+s
a//=b
print s
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P1EnSafY1sjcwNzYwtTA2MLE2FzHIMnQAAJ0lJS4yjMyc1IVEu0MrLgUim2TM4o0ElWTNLWLuRQS9fVtk7gKijLzShSK//8HAA "Python 2 – Try It Online")
Solved with [this](https://tio.run/##lVKxbsMgEN39FYjFUKMI7KZOIrlT1bFTtygDxCShIhABUdWvdzlbiZo2S7Gx7Pfu3r07fPpKB@/qYej1Dlm9l5b4YPbGScvQp0mHF211Mt5FuipQXgbCHLmlUNchPvGwgk7n4NB7OOufORfhKRxJ19@Ter6j9CptvEpdZNZ8A0I36Rn7k3zb1VqsNr86A4gW/8mgRWGOJx8SMkmH5L2NhYwpMDU9WOxwzXnL26dmMefLulk0zWP@mDcNF4@tWC5FO68xw4LDxWHDLTCLOhHK8JvWvdW42PmAlEXGoSDdXhOYGFShcB4jqYG8@pht/VFl26NPMvmxlRhPT8WZ7HtiXCIYzz68yVKasprSqQwIqZgjZccn8S1AgGRIPqjKh55s86zM5WcZu86byNEQOoWsjkrJVJ5BWU1MVbKyUlANXjEuh@Eb "Python 2 – Try It Online") program.
[Answer]
# Java (OpenJDK 8), 191 bytes
[Cracks Luke Steven's answer](https://codegolf.stackexchange.com/a/144737/58106)
```
String d(){int h=3905055,m=55,s=15443;String d="0"+h*2+""+m*20+""+s*7,x="",y;for(int g=0;g<d.length();g+=3){y="";for(int e=0;e<3;e++)y+=d.charAt(e+g);x+=(char)Integer.parseInt(y);}return x;}
```
[Try it online!](https://tio.run/##PY7BToQwEIbP@hRNTy3FBpclxnR78OjB0x6Nh0rHwgqFtGWlITw7Fo1e5s/355vJXNRV3Q0j2Iv@3OpOeY9eVGuXcXrv2hr5oEKK69Bq1KeenINrrXl9Q4ou5@gD9HyYAh9TG4iFr59tQrkmlIr1Zvv1UcIlGaiR5WNRFVWV9zINL@@r47EUf5bEBWZNdmAYsz47FHv67CGfJcZ5FB@DI/sVIwthTpp3YE1oCBWGyZIuMVn/DiQHTqUAxmhkUvO6Ue4pEGCGiplJsjN9tgEMOD4q5yEBielrB2FyFs1ivd3W7Rs "Java (OpenJDK 8) – Try It Online")
Deleted chars:
```
int h=3609000-5055+911,m=557558,s=15441301-157*10000
xx xxx xxxx xxxx x xxxxxxxxxxxx
```
This makes `d` evaluate to `078101101100108101`, which spells `Needle`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 149 bytes
Cracks this: <https://codegolf.stackexchange.com/a/144790/74216>
Module was quite small, so I wrote a multi-threaded birthday thing and hoped for the best.
Edit: And after that found an even shorter answer.
```
x='hxDKFQOoqJLuVNW'
s="n=x.to_i 36;x.bytjs.jach_cons(3){|a,b,c|n+=n*b%c;n*=a^b};puts n%8675309==1388649 ?'Njjdlj':'Haystack'"
eval s.tr ?j,s.size.chr
```
[Try it online!](https://tio.run/##BcHBCoIwGADgu08xAlmZjGJlmgwvEVFhdKlbsi1Bl8zynzHLnt2@r2lFNwyW4cJuDtvzqX7tj@0lvWIH2EgzS0ydlYgGsSWiMwqI4rLIZK1hTCffnvvCl72eMu0JV8baY/wmfvGzNYC0GwarJZ1FjM1pGAaLCCU4VepeKbzGO96B4fKBR07@5hUCYhqUKB8IlJ@cyKIZhj8 "Ruby – Try It Online")
Changes:
```
x='yGwztsPXhxDkBKlCYdFjQnpUROfoHvqmTgbaJSLcEiZrIAuMVNW'
x=' hxD K F Q O o q J L u VNW'
# and here's some more variants for extra pwnage:
x=' G tsPx KlCYd Qn U o v mT a SLc I u NW'
x=' w s D BKl dF QnpU O ba SLcEiZrI MV '
x='yGwz s Xh Dk K C F npU O Hvq b L rIAu V W'
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 34 bytes
```
93 9 2*+432212+ 47*4242160 7 2++*P
```
Cracks [this](https://codegolf.stackexchange.com/a/144776/32381). [TIO](https://tio.run/##S0n@/9/SWMFSwUhL28TYyMjQSFvBxFxLwcTIxMjQzEDBXMFIW1sr4P9/AA).
I started by getting the numerical representation of Haystack (5215583380252484459) and Needle (86197399743589). Next, I did a factorisation of the latter, which is 47\*432323\*4242169. From this, it was quite easy to reconstruct those numbers.
Marking the characters used:
```
6 93 3 9 2 2**+*+483622 1 2 3 3*+3*+89 47*+*+3 5 2* 269 158 9**107 97*2 4*++2 3 3*+42 14 2**+*+5*+5 2148 1 6 2*+*+68262 5 280 7 2 3 3*+5 2**+*+*+*+P
XXX XXX XX X X XX X X X XXXX X X XX X X XXXXX X XX X
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 151 bytes
Cracks [Kevin Cruijssen's Answer](https://codegolf.stackexchange.com/a/144750/46523)
```
v->{String h="H";int x=7;return new String(new byte[]{(byte)((-~-~-~-~-~-~1^x++*x)+15),new Byte("10"+h.length())})+new StringBuffer("elde").reverse();}
```
[Try it online!](https://tio.run/##RU89b4MwEN37K06e7kpBZag6IDpk6pIskbpEqeTAEUgdg2zjEiH616lRkCKfdV/vnt67SC/jtmN9KX/mQklrYSsbPT4BNNqxqWTBsFtagL0zjT5DgV9tU4KnLEyn8ENYJ11TwA405DD7@GNcwXUuPkUWqGDI3zPDrjcaNP@uZLiUp5vjw3HEJRNi/Pd46fcQRc8DRekbvSzYTcCgSF9FVCeK9dnVSDRR9KDc9FXFBgWrkgUlhj0by0jZNGd3sV1/UkHsqtkvZq7BM97vD0eQtBq@WcfXpO1d0oWVQ50UqHulaPU@zf8 "Java (OpenJDK 8) – Try It Online")
Comparison:
```
v->{String h="Haystack";int x=-7;return x<0?h:new String(new java.math.BigInteger(new byte[]{(byte)((~-~-~-~-~-~-~-~-~-~1^-x++*x)+151),new Byte("2"+"1+\"0+\"".length()+(x=h.length()*4/x)+"-x-7")}).toByteArray())+(new StringBuffer("hidden".substring(++x%3^4,--x-x--).replaceFirst("dd","e"+(char)(x*211%+93))).reverse());}
v->{String h="H ";int x= 7;return new String( new byte[]{(byte)(( -~-~-~-~-~-~ 1^ x++*x)+15 ),new Byte(" 1 0 " + h.length() ) }) + new StringBuffer(" e l d e" ) .reverse() ;}
```
I feel like the last part wasn't intended.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 102 bytes
```
(((((((((()()()){}){}){}){}()){}()))()()<>)(()()()){}())<>((()((){}<>)))(({})[(((()()){}())(){}){}()])
```
Cracks [H.PWiz's answer](https://codegolf.stackexchange.com/a/144611/69059).
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMONEFQs7oWjsA8IAGWsLHTRCgBEjZ2YC0aQB5QCqhGA6gnGmoORIkGzJhYzf///@smAwA "Brain-Flak – Try It Online")
```
((((((((((()()()){}){}()){}){}()){}()))<({}[(()()()()){}])(([[]]({})<>)<>)>((()()())){}{})[()]))<[[]()]>((()){}){}((){}[][(<>){}<>])(<>){}(({}<>()[()])[(((()()()){}<[()]>)<(()){}>{}){}()])
(((((((((()()()){}){} ){}){}()){}())) ()() <>) (()()()) {} () ) < >((() ((){} <>) ) ) (({} )[(((()() ){} () ) () {} ){}()])
```
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 21 bytes
```
(78)"e"sl(100)"l"l&o;
```
[Try it online!](https://tio.run/##y6n8/1/D3EJTKVWpOEfD0MBAUylHKUct3/r/fwA "Ly – Try It Online")
Cracks [LyricLy's answer](https://codegolf.stackexchange.com/a/145341/69059).
[Answer]
# Java by [Johnathan S.](https://codegolf.stackexchange.com/a/145841/55735)
```
import java.util.*;interface Main{static void main(String[]args){Stack<Hay>s=new Stack();s.add(new Needle());System.out.println(s.get(s.indexOf(new Hay())+1).a);}}class Needle extends Hay{{a="Needle";}}class Hay{String a="Haystack";public boolean equals(Object o){return getClass().equals(o.getClass());}}
```
[TiO](https://tio.run/##RY8xT8MwEIX/ipXJBmGJ2ZSFhaV0yIgYLvE1curYwXcpraz@9mC3FSwnve/ePb0b4QhPccYw2sO6ummOicVYoF7Yef1gXGBMe@hRbMGFTAzsenGMzoqpANlycmH4/II0kMotQ394eYfzK20C/oirlsqQBmtlJR@I1qNUyrRnYpx0XFjPJYN9kKQH5DJdsHja7a8HJay4H5@VBmUul94D0T1F4IkxWKqenGHT3HDzZ6v8VlCUbVFU@zRmXjpfvuhi9AhB4PcCnuSuG7FnEVVOyEsKopR5qzlS6bsl6n9W26zrLw)
Simply remove the loop that adds the Hay and nothing will be left on the stack but the needle.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `o`, cracks [emanresu A's answer](https://codegolf.stackexchange.com/a/233751/101522)
```
‛₍∞
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=o&code=%E2%80%9B%E2%82%8D%E2%88%9E&inputs=5%0A3&header=&footer=)
Simply pushes the string `Needle` in compressed form, then prints it implicitly.
Characters removed:
```
‛Ha:₍₴Cv∑∑Ṙ⌊√‹½⇩⇩²C:₴«•∞yλ;ß4ġ∆Ė_□∴9«øc:3Ẏ$4ȯ∇ppĖ5e
XXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
Kr."Dn2û"2+Kr."EL8"Z
```
cracks [this](https://codegolf.stackexchange.com/a/144616/48934).
[Try it online!](http://pyth.herokuapp.com/?code=Kr.%22Dn2%C3%BB%C2%82%222%2BKr.%22EL8%22Z&debug=0)
[Answer]
# [T-SQL by phroureo](https://codegolf.stackexchange.com/a/144807), 757 bytes
```
seleCT 'Needle'
```
Somehow I don't think that was the intended solution. Uses the characters surrounded by `{}`:
```
create table a(l int,c int)
in{se}rt into a va{l}u{e}s (1,10),(2,1),(3,8),(4,0)
go
;CREATE FUN{CT}ION b(@ varchar(max)) returns varchar(max) as
begin return{ '}char('+@+'),'''','end
go
;CREATE FU{N}CTION h(@ varchar(max),@a varchar(max), @b varchar(max), @c varchar(max), @d varchar(max), @e varchar(max), @f varchar(max), @g varchar(max), @h varchar(max))
r{e}turns varchar(max) as
b{e}gin
return replace(replace(replace(replace(@,@a,@b),@c,@d),@e,@f),@g,@h)
end
{d}ec{l}ar{e} @x varchar(max),@ int=1,@y varchar(99)={'}'
,@D varchar(4)='Ha',@O varchar(4)='ys'
,@T varchar(3)='ta',@A varchar(4)='ck'
WHILE @<=4
BEGIN
set @y+=(SELECT dbo.b(c+100)from a where l=@)+' '
set @+=1
END
SELECT @x='select
left(dbo.h('''+@D+@O+@T+@A+''','+ left(@y,len(@y)-1) +'),char(56))'
execute(@x)
```
[Answer]
## PHP
Cracks [Titus answer](https://codegolf.stackexchange.com/a/145847/72733)
```
for($i=1;$c=H_aNyesetdalcek[$i+=2];)echo$c;
```
[Try it online](http://sandbox.onlinephpfunctions.com/code/988f9f07b8b34be9be492c2fdfaa9d99828ea919)
]
|
[Question]
[
**This question already has answers here**:
[Finding Local Extremes](/questions/22252/finding-local-extremes)
(21 answers)
Closed 3 years ago.
Given an array of positive integers, output an array of all the elements that are greater than or equal to the adjacent ones. Most elements will have two adjacent elements; the first and last element are special cases, as they only have one adjacent element.
You may assume that the array contains at least two elements.
Test cases:
```
Input | Output
[4,2,6,12,4,5,4,3] | [4,12,5]
[1,2] | [2]
[1,2,3,2,1] | [3]
[3,2,1,2,3] | [3,3]
[4,4] | [4,4]
[2,4,4,4,1] | [4,4,4]
[2,3,3,4] | [3,4]
[4,3,3,4] | [4,4]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins!
[Answer]
# [Python](https://docs.python.org/2/), 54 bytes
```
f=lambda l,*p:l and l[:p<=l[:1]>=l[1:2]]+f(l[1:],l[0])
```
[Try it online!](https://tio.run/##bZDBbsMgDIbvPIWVS8JmTYPQHqKxF2EcmNpokYCiJm01qe@e2WyTFmkgG/v/xC9w@Vw@Tlmv62hjSO@HABEfyhAh5ANEN5QXS1n5VzrUoL1/HDuuPEb37OU626ZpnEGNe1QaDe4oeg9wB1JJ2XnhFGpSNouw/ibYUyj/l/REqsp0S5CZQfOPH6vC8Rt4bx2rVik5bG9XV@PpG0KMpzPcYMowP80lTkvXvuVWDgJoKsmmULrjNUS8/dJ7KyVDu1xKPHaRm/TTJG7KecoL0MiktQnJpdbrFw "Python 2 – Try It Online")
I/O is with tuples rather than lists.
---
**[Python](https://docs.python.org/2/), 57 bytes**
```
f=lambda l,p=0:l and l[:[p]<=l[:1]>=l[1:2]]+f(l[1:],l[0])
```
[Try it online!](https://tio.run/##bZDBasMwDIbvfgqRS2IqRu24PYS6L@Lp4NKFBhzHNGGl0HfPZI9BA7MQEv9n/8hKz@U2Rb2uvQ1@vFw9BEx23wXw8QrBdS7RyXJVdOaiOk2065vcEQa3J7nOtqoqZ1DjEZVGgwfOlgBewCorBxJOoWZlcxjrX4Itp6J30jIpaqZbgpkZNP/4ZVW4PEOOrWPRCmWH7eviaoi/IUQ/3eEBQ4T5Y05hWJr6M9ayE8CLGe3oU/P17QM@/uirlpJhug9xAV6MtHZEvlv69Qc "Python 2 – Try It Online")
Alt 57:
```
f=lambda l,p=0:l and l[l<[max(p,*l[:2])]:1]+f(l[1:],l[0])
```
[Answer]
## Mathematica 22 Bytes
```
Pick[#,MaxDetect@#,1]&
```
[Answer]
## Haskell, ~~50~~ ~~49~~ 42 bytes
```
f l=[j|i:j:k:_<-scanr(:)[0]$0:l,k<=j,i<=j]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hxzY6qybTKssq2yreRrc4OTGvSMNKM9ogVsXAKkcn28Y2SycTSMT@z03MzFOwVUjJ51JQUCgoyswrUVBRSFOINtEx0jHTMTTSMdExBWLjWAU0BYZABcZAbBiLJgEWBEnG/gcA "Haskell – Try It Online")
`scanr(:)[0]` makes a list of the tails of `(0:l)`, each with a final `0`, e.g. for `l = [4,3,3,4]`: `[[0,4,3,3,4,0],[4,3,3,4,0],[3,3,4,0],[3,4,0],[4,0],[0]]` which is pattern matched agains `i:j:k:_` to extract all lists with at least 3 elements which are named `i`, `j`, and `k`. Keep `j` if its >= `i` and `j`.
Edit: Ørjan Johansen saved 7 bytes. Thanks!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
0;;0»3\f"⁸Ẏ
```
A monadic link taking a list of positive integers and returning the filtered list containing only those which are greater than or equal to all their neighbours.
**[Try it online!](https://tio.run/##y0rNyan8/9/A2trg0G7jmDSlR407Hu7q@///f7SJjpGOmY6hkY6JjikQG8cCAA)**
---
Previous [12 byter](https://tio.run/##y0rNyan8/9/A2tPv6B5PO4OHO1r8fB/u7v7//3@0iY6RjpmOoZGOiY5pLAA):
```
0;INżI>0ḄNMị
```
Previous [13 byter](https://tio.run/##y0rNyan8/9/A2trg4c6Fxr6PmtYc6QYSRiEPd3f///8/2kTHSMdMx9BIx0THVMckFgA "Jelly – Try It Online"):
```
0;;0ṡ3M€ċ€2Tị
```
---
[Answer]
# Dyalog APL, ~~31~~ ~~30~~ ~~28~~ ~~22~~ 21bytes
```
{⍵/⍨(⌈/=2⌷⊢)¨3,/∊0⍵0}
```
[Try it online!](http://tryapl.org/?a=%7B%u2375/%u2368%28%u2308/%3D2%u2337%u22A2%29%A83%2C/%u220A0%u23750%7D4%2C2%2C6%2C12%2C4%2C5%2C4%2C3&run)
Explanation (I'm not good at explaining things):
```
0⍵0 - [0,input,0] (it looks like a face!)
∊ - flatten
3,/ - split into overlapping sections of length 3.
(⌈/=2⌷⊢)¨ - Whether the middle element is the maximum (applied to every section)
⍵/⍨ - index
```
[Answer]
# [Haskell](https://www.haskell.org/), 40 bytes
```
p%(h:t)=[h|h>=p,[h+1]>t]++h%t
_%e=e
(0%)
```
[Try it online!](https://tio.run/##NY7LCsMgEEX3fsUsKiTooja2i4L5EZHiwjChSZA6y/679ZHCcO/MGeaBPr3DtuUc@YBPGo3FL84mSotCuZmcEMiJvXgwgS1muPIxU0iUwIC1WsJNwkOCKlaKe9PJSbCqtP5eUFNVwZl2XEGZ0NX7ih7qBFML7Rzb/XqUm/GzHgQX2H2EBdon@Qc "Haskell – Try It Online")
[Answer]
## JavaScript (ES6), 40 bytes
```
a=>a.filter((e,i)=>!(e<a[i-1]|e<a[i+1]))
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~84 75\*~~ 71 bytes
```
lambda l,k=[0]:[j for x,j in enumerate(l)if(k+l+k)[x+2]<=j>=(k+l+k)[x]]
```
[Try it online!](https://tio.run/##VYm9DsIgGAB3n@IbIXyDBXQw0hdBBowQ@SltCCb16ZGpicMNd7d923stonv16Nkuz5eFjEnps7npCH6tsGOEUMCVz@KqbY5kGjxJLLNE9c64uas4qyMY07caSiOeaIkcrzhxlHgZCEPp6ZhizGnwXyXK4f0H "Python 3 – Try It Online")
---
*\*@LeakyNun saved 9 bytes using a clever operator trick.*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
2ị⁼Ṁ
0;;0ṡ3Ç€Tị
```
[Try it online!](https://tio.run/##y0rNyan8/9/o4e7uR417Hu5s4DKwtjZ4uHOh8eH2R01rQoDi////jzbRMdIx0zE00jHRMQVi41gFAA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ ~~14~~ 13 bytes
```
ü‹0¸«sĆÁü›+_Ï
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8J5HDTsNDu04tLr4SNvhRhB3l3b84f7//6NNdIx0zHQMjXRMdEyB2DgWAA "05AB1E – Try It Online")
**Explanation**
```
ü‹ # pairwise comparison for less than
0¸« # append 0
s # swap input to top of stack
Ć # enclose, append the head of the list
Á # rotate right
ü› # pairwise comparison for greater than
+ # add the two boolean lists
_ # logical negate
Ï # keep only elements of input that are true in the resulting list
```
**Previous 15 byte solution**
```
¬s¤)˜Œ3ùεZQ1è}Ï
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0JriQ0s0T885Osn48M5zW6MCDQ@vqD3c//9/tImOkY6ZjqGRjomOKRAbxwIA "05AB1E – Try It Online")
**Explanation**
```
¬ # get head of input
s¤ # get tail of input
)˜ # wrap stack in flattened list
# produces the input list with the first and last element duplicated
Œ3ù # push sublists of length 3
ε # apply transformation on each triple
ZQ # ... check each element for equality to the max
1è # ... get the middle element
} # end transform
Ï # keep only elements of input that are true in the resulting list
```
[Answer]
# R, 44 bytes
```
pryr::f(x[(x>=c(0,x)&x>=x[-1])[1:sum(x|1)]])
```
which evaluates to the function:
```
function (x)
x[(x >= c(0, x) & x >= x[-1])[1:sum(x | 1)]]
```
Compares `x` to `c(0,x)`, so with `x` shifted one position to the right. Also compares `x` to `x[-1]`, so one position shifted to the left. These both are `TRUE` if there is a maximum there. `&` to take the AND of these booleans. Because of the wrapping nature of R's vectors when they are not the same length, we have to truncate the result at the length of `x`, which is found by taking `sum(x|1)`. We then plug in the boolean vector, taking only the true indices of `x` and return that.
Note, because these logical operations are done with unequal length vectors, R will complain. A lot. But the correct output will be there amidst the warnings:
```
> pryr::f(x[(x>=c(0,x)&x>=x[-1])[1:sum(x|1)]])(c(4,2,6,12,4,5,4,3))
[1] 4 12 5
Warning messages:
1: In x >= c(0, x) :
longer object length is not a multiple of shorter object length
2: In x >= x[-1] :
longer object length is not a multiple of shorter object length
3: In x >= c(0, x) & x >= x[-1] :
longer object length is not a multiple of shorter object length
```
[Answer]
# [R](https://www.r-project.org/), 42 bytes
```
function(x)x[c(d<-diff(x),0)<=0&c(0,d)>=0]
```
[Try it online!](https://tio.run/##RYxLCoQwEET3cxDphhLy6XFlvIi4SmhwoyAK3j6TDEEpCt4rmj6yhqzXFs913@jme46Uxj6tqsVgeAymi2SQeApmyUqRBA4DrIPgW@qZP3W2cC/Bl9rmf65bc4E0qj9q7OO@RJ67ZvkH "R – Try It Online")
2 bytes shorter than [JAD's solution](https://codegolf.stackexchange.com/a/132547/86301). `diff` computes successive differences; then keep only the entries greater than both neighbours.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
-.b*YqYeSN.:++0Q03Q0
```
To be golfed...
[Test suite.](http://pyth.herokuapp.com/?code=-.b%2aYqYeSN.%3A%2B%2B0Q03Q0&test_suite=1&test_suite_input=%5B4%2C2%2C6%2C12%2C4%2C5%2C4%2C3%5D%0A%5B1%2C2%5D%0A%5B1%2C2%2C3%2C2%2C1%5D%0A%5B3%2C2%2C1%2C2%2C3%5D%0A%5B4%2C4%5D%0A%5B2%2C4%2C4%2C4%2C1%5D%0A%5B2%2C3%2C3%2C4%5D&debug=0)
[Answer]
# [R](https://www.r-project.org/), 68 bytes
```
function(a)a[a==sapply(1:length(a),function(i)max(c(0,a,0)[i+0:2]))]
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRMzE60da2OLGgIKdSw9AqJzUvvSQDKKwDV5KpmZtYoZGsYaCTqGOgGZ2pbWBlFKupGfs/DShoomOkY6ZjrmOiYwrExpqa/wE "R – Try It Online")
[Answer]
# [PHP](https://php.net/), 67 bytes
```
for(;$g=$argv[+$i];$l=$g)$g<$l|$g<$argv[++$i]?:$r[]=$g;print_r($r);
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJReZhutpKuko2QCxEZAbAbEhkZQAVMobawUa/0/Lb9Iw1ol3RasK1pbJTPWWiXHViVdUyXdRiWnBkRCZEBS9lYqRdGxQFnrgqLMvJL4Ig2VIk3r//8B "PHP – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina), 51 bytes
```
\d+
$*
^
M!`(?<=(^|1+) )(\1\d*)\b(?! 1\2)
^¶
%`1
```
[**Try it online**](https://tio.run/##K0otycxL/P8/JkWbS0WLK45LgctXMUHD3sZWI67GUFtTQVMjxjAmRUszJknDXlHBMMZIkyvu0DYuLtUEw///TRSMFMwUDI0UTBRMgdgYAA)
[Answer]
# q, 39 bytes
```
{x where x = -1 _ next 3 mmax x,last x}
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
úâH◄(☼bM•Å
```
[Run and debug it](https://staxlang.xyz/#p=a3834811280f624d078f&i=[4,2,6,12,4,5,4,3]%0A[1,2]%0A[1,2,3,2,1]%0A[3,2,1,2,3]%0A[4,4]%0A[2,4,4,4,1]%0A[2,3,3,4]%0A[4,3,3,4]&a=1&m=2)
It produces output as newline separated values on standard output.
Unpacked, ungolfed, and commented, it looks like this.
```
f filter each value in input using the rest of the program; implicitly printing kept values
x0|S input pre- and post-pended with zero
3B split into batches of 3
i@ get the i-th batch, where i is the iteration index
|M= is the current value equal to the max from the batch?
```
[Run this one](https://staxlang.xyz/#c=f+++++%09filter+each+value+in+input+using+the+rest+of+the+program%3B+implicitly+printing+kept+values%0A++x0%7CS%09input+pre-+and+post-pended+with+zero%0A++3B++%09split+into+batches+of+3%0A++i%40++%09get+the+i-th+batch,+where+i+is+the+iteration+index%0A++%7CM%3D+%09is+the+current+value+equal+to+the+max+from+the+batch%3F&i=[4,2,6,12,4,5,4,3]%0A[1,2]%0A[1,2,3,2,1]%0A[3,2,1,2,3]%0A[4,4]%0A[2,4,4,4,1]%0A[2,3,3,4]%0A[4,3,3,4]&m=2)
**Updated:** Just found a 9-byte solution. Will update explanation later:
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▀▓ûa¥╓╧↨⌐
```
[Run and debug it](https://staxlang.xyz/#p=dfb296619dd6cf17a9&i=[4,2,6,12,4,5,4,3]%0A[1,2]%0A[1,2,3,2,1]%0A[3,2,1,2,3]%0A[4,4]%0A[2,4,4,4,1]%0A[2,3,3,4]%0A[4,3,3,4]&a=1&m=2)
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 37 bytes
```
map{$_>=$F[++$i]&$_>=$p&&say;$p=$_}@F
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaJd7OVsUtWltbJTNWDcwpUFMrTqy0VimwVYmvdXD7/99EwUjBTMHQSMFEwRSIjf/lF5Rk5ucV/9f1NdUzMDT4r5sIAA "Perl 5 – Try It Online")
]
|
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/22468/edit)
**Task:**
You must create an interpreter that can parse snippets of a programming language. The language does not need to be complex, but it must include the following syntactical elements:
* Ability to assign and read variables (could be as simple as `a`-`z` being premade variables)
* If statements (elseif and else are not required)
* Loops (counting to an arbitrary number, user access to counter is not required)
* Simple math with variables (addition, subtraction, multiplication, division, greater/less than, equals)
* Print statements
**Rules:**
* You may not copy the syntax of another popular language.
* You need to write your own interpreter, not modification of another interpreter.
* You can write your interpreter in any language.
* Write a 99-bottles-of-beer example program in your language (see [here](http://99-bottles-of-beer.net/lyrics.html))
* This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the most upvoted answer wins.
[Answer]
## DogeScript
The 99 bottles of beer program:
```
many amaze 99 time
such scare bottles-of-beer
such scream on-the-wall
many despair 13 time
such fail take-one-down-pass-it-around
wow
so amaze
so scare
so scream
so despair!
so amaze
so scare
so despair!
much amaze
so fail
so despair!
so amaze
so scare
so scream
so despair!
so despair!
very amaze
wow
```
The PHP interpreter:
```
<?php
$input=fopen('php://stdin', 'r');
//pre-process input
$input=preg_replace("/ +/", " ", $input); //replace any multiple spaces by a single space
//split into instructions by newlines
$instructions=explode("\n", $input);
$loopstartpoint= -1;
$variables=array();
$activevariable="";
for($instrpointer=0; $instrpointer<count($instructions); $instrpointer++)
{
$tokens=explode(" ", $instructions[$instrpointer]);
switch($tokens[0])
{
case "wow":
if($loopstartpoint<0)
{
$loopstartpoint=$instrpointer+1;
}
else
{
if($variables[ $activevariable ])
{
$instrpointer=$loopstartpoint;
}
else
{
$loopstartpoint= -1;
}
}
break;
case "so":
if(substr($tokens[1], -1)=="!")
{
echo chr($variables[ substr($tokens[1], 0, -1) ]);
}
else
{
echo $variables[ $tokens[1] ];
echo " ";
}
break;
case "very":
$activevariable=$tokens[1];
break;
case "much":
if(!isset($variables[ $tokens[1] ]))
$variables[ $tokens[1] ]=0;
if(count($tokens)==2)
{
$variables[ $tokens[1] ]--;
}
else
{
for($loop=0;$loop<$tokens[2];$loop++)
{
$variables[ $tokens[1] ]--;
}
}
$activevariable=$tokens[1];
break;
case "many":
if(!isset($variables[ $tokens[1] ]))
$variables[ $tokens[1] ]=0;
if(count($tokens)==2)
{
$variables[ $tokens[1] ]++;
}
else
{
for($loop=0;$loop<$tokens[2];$loop++)
{
$variables[ $tokens[1] ]++;
}
}
$activevariable=$tokens[1];
break;
case "such":
$variables[ $tokens[1] ]=$tokens[2];
$activevariable=$tokens[1];
break;
}
}
?>
```
The syntax as it currently stands:
```
wow - start and end loops, end of loop checks if active variable is 0 and loops if not
so without ! - print variable's value
so with ! - print variable's ASCII character
much - decrement this variable
many - increment this variable
such - set variable
very - make variable active
x time - does previous statement x times
Variables are initially 0.
```
Try it [here](http://ideone.com/Gz0ZBT).
Any suggestions for improvement are welcome.
[Answer]
# BrainBack : A stack based compiled language running on BrainFuck
*NB: Spec was changed from "creating a parser" to "create an interpreter" after i posted this answer. This answer is a compiler which also parses source code.*
The name is a pun on *Back* being the opposite of a well known stack based language and *Brain* indicating it's esoteric nature. It looks a little like BrainFuck (though isn't), but it's compiler runs on BrainFuck and it's compiled object code ends up as BrainFuck binaries.
The language: \*==destroys it's arguments
* `"constant"` prints constant
* `#` prints top of stack as number
* `>` duplicates the top of stack
* `<num>` push constant number `<num>` as a value to top of stack
* `<` remove top of stack
* `-` substract topmost from the second topmost\*
* `+` add topmost to second topmost\*
* `!` not toggles positive / zero\*
* `[ ... ]` does a while top of stack not zero, very similar to BrainFuck
99 bottles of beer with correct lyrics in BrainBack:
```
100
[
1 -
> ! [ < 0 0 "No more" ] < [ # 0 ] <
" bottle"
> 1 - [ < 0 "s" ] <
" of beer on the wall, "
> ! [ < 0 0 "no more" ] < [ # 0 ] <
" bottle"
> 1 - [ < 0 "s" ] <
" of beer.
"
> ! [ < 0 0 "Go to the store and buy some more, " ] <
[ "Take one down and pass it around, " 0 ] <
> ! [ < 1 0 0 "99" ] < [ > 1 - > ! [ < < 1 0 0 "no more" ] < [ # 1 - 0 ] ] <
" bottle"
[ < 0 "s" ] <
" of beer on the wall.
"
]
```
The BrainBack compiler, written in [Extended BrainFuck](http://sylwester.no/ebf/)
```
;;; Macros
;; utility function that substracts
;; ^2 from ^0 without reduceing ^2
;; below zero. ^1 needs to be zero
{substract
(<<[->]>[<]>-)
}
;; Main macro is the main program and
;; has the overal structure of the program.
;; every macro here is define in order below.
{main
:i
:wrk
:tmp
:else
:sub
$i+(
; switch ( $wrk ) cases '"#><-+![]9;' using $tmp,$else
$tmp+++++(-$wrk------)+$wrk---; !
($wrk-; "
($wrk-; #
($wrk--------; +
($wrk--; -
($wrk--- $tmp- $else 9+ &substract $tmp+ $wrk; 0-9
($wrk--; ;
($wrk-; <
($wrk--; >
($tmp++++(-$wrk------)+$wrk+; [
($wrk--; ]
(#(-) $tmp(-) no matches)
$tmp (- #match 'cl' &close )
) $tmp (- #match 'op' &open )
) $tmp (- #match 'gt' &dup )
) $tmp (- #match 'lt' &slash )
) $tmp ( #match 'c' &comment )
) $tmp (- #match 0 to 9 &read_number )
) $tmp (- #match 'minus' &sub )
) $tmp (- #match 'plus' &add )
) $tmp (- #match '#' &print_number )
) $tmp (- #match '"' &print_string )
) $tmp (- #match 'not' ¬ )
$i(-)$tmp#,+(-(-$wrk+$i+)))
10+.
}
;; implements close bracket
{close
|" close"(-)
$i.
}
;; implements open bracket
{open
|" open"(-)
$i.
}
;; implements dup/>
{dup
|"dup [->>+<<]>>[-<+<+>>]<
"
(-)
}
;; implements slash/<
{slash
|"slash [-]<
"
(-)
}
;; implements comment
{comment
[,10-]
}
;; implements read_number/<number>
;; makes code that if run makes
;; the constant
{read_number
;TODO: compiler_read_constant_number
$wrk|"number"(-)
# $wrk 6+ (- $i 8-)
~"+>"<.(-)
$i+(-(-$wrk.)
#$else, $tmp 6+ (- $else 8-)
$else(-$tmp+$i+)
$sub 9+ &substract
$else+
$tmp((-) $i(-) $else-)
$else(-|"[->++++++++++<]>[-<+>]<"(-)$i+)
)
$wrk(-)
|"
"(-)
}
;; implements sub/-
{sub
|"sub [-<->]<
"
(-)
}
;; implements add/+
{add
|"#add [-<+>]<
"
(-)
}
;; implements print_number/#
{print_number
|"print [->+<]>[-<+>>+<]>
[>++++++++++<
[->-[>+>>]>[+[-<+>]>+>>]<<<<<]
+>[-]>[-<<+>>]>[-<<+>>]<<]
+<[>-<[<]]>[>]
<[>++++++[-<++++++++>]<-.[-]<]<
"(-)
}
;; implements print_string/"..."
;; this outputs EBF code making the
;; object code EBF
{print_string
|"print >|"(-)
$i(-$wrk+$else+)
$wrk($tmp(-$wrk+)$wrk.,$else(-$tmp+$wrk-$i+)$i(-$else+))
$tmp(-)$else.(-)|"[-]<
"(-)
}
;; implements not/!
;; creates code that negates top of stack
{not
|"not >+<[[-]>-]>[<+>->]<<
"(-)
}
&main
```
To compile BrainBack:
```
bf ebf.bf < BrainBack.ebf > BrainBack.bf
```
To compile a BrainBack program:
```
bf BrainBack.bf < 99.bb > 99.ebf # compile from bb to ebf
bf ebf.bf < 99.ebf > 99.bf # compile from ebf to bf
```
Run the binary:
```
bf 99.bf
```
Here i use [bf](http://pkqs.net/%7Esbeyer/) which is available in most debian distros. `beef` and others can be used as well. Both EBF compiler, BrainBack and its object code becomes quite compatible BrainFuck binaries.
It probably should be extended to print a cell as ascii `.`, be able to read a byte in `,` and to have various `swap` operations to be more useful. It's absolutely needed in order to make a BrainBack compiler or interpreter in BrainBack.
[Answer]
# €
I spend most of my time on PHP scripts and it brought me a question: why am I forced to use `$` for my variables names? `€` is my local currency, so let's use it! Since € is used in many countries, I used some words from EU languages as keywords.
```
€beers gleich 99
€bottles gleich bottles of beer
€bottles_on_the_wall gleich bottles of beer on the wall
mientras €beers topogleich 3
afficher €beers €bottles_on_the_wall
afficher , €beers €bottles
afficher . NETHERLANDS
odejmowanie €beers
afficher Take one down and pass it around, €beers
afficher €bottles_on_the_wall
afficher . NETHERLANDS NETHERLANDS
sartneim
afficher 2 bottles of beer on the wall, 2 bottles of beer. NETHERLANDS
afficher Take one down and pass it around, 1 bottle of beer on the wall.
afficher NETHERLANDS NETHERLANDS
afficher 1 bottle of beer on the wall, 1 bottle of beer. NETHERLANDS
afficher Take one down and pass it around, no more bottles of beer on the wall.
afficher NETHERLANDS NETHERLANDS
afficher No more bottles of beer on the wall, no more bottles of beer. NETHERLANDS
afficher Go to the store and buy some more, 99 bottles of beer on the wall.
afficher NETHERLANDS NETHERLANDS
```
Keywords:
* `gleich` is *equal* in German
* `mientras` is *while* in Spanish
* `topo` is *greater* in Portuguese (update: it should be *maior* instead, thanks to [daHugLenny](https://codegolf.stackexchange.com/users/56258/dahuglenny) for the tip)
* `odejmowanie` is *subtract* in Polish
* `afficher` is *print* in French
* newlines are called `nl` sometimes, and the TLD of `NETHERLANDS` is `nl`, so I defined a constant `NETHERLANDS` to display newlines
I cheated a little bit since there is no `if` keyword, I chose to directly print the last two lines.
## Interpreter in Python
The interpreter won't do more than execute the script to display 99 bottles of beers.
```
# -*- coding: utf-8 -*-
# @see http://stackoverflow.com/questions/12655836/writing-an-xml-file-that-contains-a-euro-symbol-in-python-using-xml-etree/12655861#12655861
# = gleich (german)
# while mientras (spanish)
# > topo (portuguese) (it should be "maior" instead)
# subtract odejmowanie (polish
# print afficher (french)
# newline NETHERLANDS
import sys, codecs
class euro:
symbols = {}
sign = u'€'
def executeLine(self, line):
s = line.split(' ')
if s[0] == 'afficher':
buffer = []
for a in s[1:]:
if (a == ''):
continue
elif (a[0] == self.sign):
buffer.append(str(self.getSymbol(a)))
elif (a == 'NETHERLANDS'):
buffer.append("\n")
else :
buffer.append(a)
sys.stdout.write(' '.join(buffer))
# @see http://stackoverflow.com/questions/4499073/printing-without-newline-print-a-prints-a-space-how-to-remove/4499172#4499172
elif s[0] == 'odejmowanie':
self.setSymbol(s[1], (int(self.getSymbol(s[1])) - 1))
elif (len(s) >= 3) and (s[1] == 'gleich'):
self.setSymbol(s[0], (' ').join(s[2:]))
def executeBlock(self, lines, statement):
while (self.getStatement(statement)):
for line in lines:
self.executeLine(line)
def getStatement(self, statement):
if (statement[1] == 'topogleich'):
return self.getSymbol(statement[0]) >= int(statement[2])
def setSymbol(self, name, value):
name = self.withoutEuro(name)
self.symbols[name] = value
def getSymbol(self, name):
#~ print symbols, withoutEuro(name)
name = self.withoutEuro(name)
if name in self.symbols:
value = self.symbols[name]
return value
else :
print "\n-----\n",'Error: "', name, '"is not in', self.symbols, '-----'
#~ sys.exit()
def withoutEuro(self, string):
return(string.replace(self.sign, ''))
def parseFile(self, f):
linesStack = []
for line in codecs.open(f, 'r', 'utf-8'):
line = line.replace('\n', '').replace('\t', '')
s = line.split(' ')
if (len(s) == 1) & (s[0] == '') :
continue
if (s[0] == 'mientras'):
statement = s[1:]
linesStack.append(line)
elif (s[0] == 'sartneim'):
linesStack.append(line)
self.executeBlock(linesStack, statement)
linesStack = []
statement = ''
elif (len(linesStack) > 0):
linesStack.append(line)
else:
self.executeLine(line)
euro = euro()
euro.parseFile(sys.argv[1])
```
To run it, save both files then run the Python file with the `.eu` script as an argument:
```
python euro.py euro.eu
```
[Answer]
# 1Lang
1Lang is a functional prefix language like LISP or Scheme but without parentheses that makes it a bit harder to read when all unnecessary white-space is removed. Parentheses can be removed since all functions and operators take a known number of parameters.
Braces are required to delimit function body and conditional consequence and alternate code blocks which can consist of a list of statements.
In LISP, Factorial might be defined like this:
```
(defun fact (x) (if (< x 2) 1 (* x (fact (- x 1))) ) )
```
in 1Lang this would be
```
@Fx{ ? < x 2 {1} {* x F -x1} }
```
which can be reduced to
```
@Fx{?<x2{1}{*xF-x1}}
```
1Lang currently supports no side-effects.
1Lang is written in bash so it currently shares some bash limitations such as integer range.
```
a-z are variables. Variable are either integers, strings, or lists.
```
NB: Lists are not fully implemented.
```
A-Z are functions
```
Integers are bash integers (up to -2^32 to 2^31-1 I think). Negative numbers can not be directly used. To enter a negative, subtract it from zero. eg. -5 would be entered as -0 5. This limitation is because 1Lang is a work in progress and negative numbers were not needed for this application. I am considering using ~ as a unary negative operator which would allow -5 to be input as ~5.
White-space is required to delineate integers. eg. +2 3
```
: means assign eg. :c34 to assign 34 to c
+-*/% are binary integer operators eg. +12 34
&|^ are binary bit-wise operators
! is unary boolean not
~ is unary one's complement
? is a if-then-else function-like operator. eg. ?=x3{*xx}{0} is x=3 return x*x else 0
+ is also a binary string concatenation operator eg. +99" bottles"
* is also a string repetition operator eg. *5" hello" or *" hello"5
@ defines a function eg. @Fx{?<x1{1}{*xF-x1}}
```
Function parameter names may overload callers variables.
All variables assigned within a function are local.
Printing is not necessary (although it could be useful) because like LISP every statement returns a value, and last value returned is printed.
```
eg. +2 3 prints 5
```
An unexpected behaviour of prefix notation without parentheses is that string concatenation can actually be easy to write. Say you want to concatenate `"a" " quick" " brown" " fox"`, one might write:
```
+++"a"" quick"" brown"" fox"
```
But a more readable and less error prone method is this:
```
+"a"+" quick"+" brown"" fox" (Note missing + between last terms)
```
or
```
+"a"+" quick"+" brown"+" fox"""
```
99 Bottles of beer code:
```
:b" of beer"
:w" on the wall"
:t"Take one down and pass it around, "
:s"Go to the store and buy some more, "
:c", "
:n".\n"
@Bx{?=x0{+"No more bottles"b}{+x+" bottle"+?=x1{""}{"s"}b}}
@Fx{?=x0{+B0+w+c+B0+n+s+B99+wn}{+Bx+w+c+Bx+n+t+B-x1+w+n+"\n"F-x1}}
F99
```
Function B returns "No more bottles" or "1 bottle" or " bottles" depending on x.
Function F returns normal verses or final verse. A normal verse is concatenated with following verse by recursively calling F with -x1. When x is 0, F returns final verse.
This generates (for F5 meaning start at 5 bottles of beer...):
```
> F5
5 bottles of beer on the wall, 5 bottles of beer.
Take one down and pass it around, 4 bottles of beer on the wall.
4 bottles of beer on the wall, 4 bottles of beer.
Take one down and pass it around, 3 bottles of beer on the wall.
3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.
2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, No more bottles of beer on the wall.
No more bottles of beer on the wall, No more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
<End>
```
## 1Lang interpreter (written in bash) in under 500 lines.
```
#!/bin/bash
LC_ALL=C # else [a-z] and [A-Z] misbehave
# functions return result on stdout
# functions have an environment
# Requirements:
# * minimise size
# -> eliminate delimiters
# -> single letter variables and functions
# -> no precidence
# -> no overloading
# *
# string "text with \characters as per printf"
# numbers 123
# functions F3
# Built-ins +-*/%^ &|~ ! etc.
# assignment :v12 :v"string"
log(){ local m="${l:p}" m="${m//[$NL]/\n}" v="${FUNCNAME[1]}"; echo "$v: l=[${l//[$NL]/\n}] ch=[${ch/[$NL]/\n}] next=[$m]" >&2; }
logr(){ local m="${l:p}" m="${m//[$NL]/\n}" v="${FUNCNAME[1]}"; echo "$v: l=[${l//[$NL]/\n}] ch=[${ch/[$NL]/\n}] next=[$m] ret=[${ret//[$NL]/\n}]" >&2; }
logv(){ local v="${FUNCNAME[1]}"; echo "$v: ret=[${ret//[$NL]/\n}]" >&2; }
logm(){ local m="$1" v="${FUNCNAME[1]}"; echo "$v: ${m//[$NL]/\n} in [${read//[$NL]/\n}]." >&2; }
msg(){ echo -En "$1" >&2; }
msn(){ echo -E "$1" >&2; }
# ==========
# Line layer
# ==========
declare l
readline(){ read -rp"1lang> " l; }
#==================
# Environment Layer
#==================
declare -A v t # variables and variable type
declare ret typ # all bash function return these values
# assign = : var expression
assign(){
local var
readch
var && var=$ret || { logm "ERROR: variable name expected" ; return 1; }
exp || { logm "ERROR: value or expression expected"; return 1; }
v["$var"]="$ret"
t["$var"]="$typ"
}
# get variable value
get(){
local var
var && var=$ret || { logm "ERROR: variable name expected"; return 1; }
ret=${v["$var"]}
typ=${t["$var"]}
}
declare -A func fpar
declare -iA fnum # functions
# define = @ F param* { body }
define(){
local fn par body
readch
fn && fn=$ret || { logm "ERROR: function name expected"; return 1; }
fpar[$fn]= # zero parameters
fnum[$fn]= # zero parameter counter
while var;do # read parameters
fpar[$fn]+=$ret
fnum[$fn]+=1 # cound parameters
done
# get body but remove block delimiters
skip "{" "}" && body="${ret:1: -1}" || { logm "ERROR: function body expected"; return 1; }
readch # skip }
func[$fn]="$body" # store function body
ret="@$fn${fpar[$fn]}{$body}"
typ='f'
}
apply(){
local fn=$ch n c s; local -i N q
readch
N=${fnum[$fn]} # number of parameters
n=${fpar[$fn]} # parameters
s=${func[$fn]} # function body
c=
for((q=0; q<N; q++)){
exp || { logm "ERROR: value expected"; return 1; }
c+="v[${n:q:1}]=\"$ret\"; " # add value to script
c+="t[${n:q:1}]=\"$typ\"; " # add type to script
}
# parse function in a subshell and echo result and type back
# subshell means all variable changes in function are local
c+="parse <<<'$s'; echo -E \"\$typ\$ret\"" # combine type and value
ret=
typ=
ret="$( eval "$c" )" || { logm "ERROR: function application failed"; return 1; }
typ="${ret::1}" # extract type
ret="${ret:1}" # get actual return value
}
# bash oddities:
# [[ 1 -eq 1 ]] -> 0 or success
# [[ 1 -eq 2 ]] -> 1 or failed
# x=1\<2 -> a=1 (true)
# x=1\<1 -> a=0 (false)
# ((1==1)) -> 0 or success
# ((1==2)) -> 1 or failed
# declare -i a; a=1==1 -> a=1 (true)
# declare -i a; a=1==2 -> a=0 (false)
binary(){
local -i iret; local op=$ch a b at bt
readch
exp && { a="$ret"; at=$typ; } || { logm "ERROR: initial expression expected"; return 1; }
exp && { b="$ret"; bt=$typ; } || { logm "ERROR: second expression expected" ; return 1; }
ret=
typ=
case "$at$bt" in
nn) # num op num
case "$op" in
[\*]) iret=a*b;;
[\^]) iret=a**b;;
[\+]) iret=a+b;;
[\-]) iret=a-b;;
[\/]) [[ b -ne 0 ]] && { iret=a/b; } || { logm "ERROR: division by 0" ; return 1; };;
[\%]) [[ b -ne 0 ]] && { iret=a%b; } || { logm "ERROR: modulo division by 0"; return 1; };;
[\&]) iret=a\&b;;
[\|]) iret=a\|b;;
[\#]) iret=a\^b;;
[\=]) iret=a==b;;
[\<]) iret=a\<b;;
[\>]) iret=a\>b;;
esac
ret=$iret
typ='n';; # result is always a decimal number
ss) # string op string
case "$op" in
# [\*]) arith=a*b;; # combine?
# [\#]) arith=${}a**b; type='s';;
[\+]) ret="$a$b"; typ='s';; # concatenate
[\-]) ret="${a//$b}"; typ='s';; # remove substrings
[\=]) [[ $a = $b ]]; ret=$?; typ='n';;
[\<]) [[ $a < $b ]]; ret=$?; typ='n';;
[\>]) [[ $a > $b ]]; ret=$?; typ='n';;
esac;;
ns) # num op string =3"hello" ="hello"3 ="3"3 =3"4"
case "$op" in
[\+]) ret="$a$b"; typ='s';; # concatenate
[\*]) ret=$(eval echo \"\${b[0]\"{1..$a}\"}\"); typ='s';; # repeat b a times
[\=]) ((${#b}==a)); ret=$?; typ='n';; # length b is a
# [\<]) [[ $a < $b ]]; arith=$?; typ='n';;
# [\>]) [[ $a > $b ]]; arith=$?; typ='n';;
esac;;
sn) # string op num *"hello"3 ="3"3 =3"4"
case "$op" in
[\+]) ret="$a$b"; typ='s';; # concatenate
[\*]) ret=$(eval echo \"\${a[0]\"{1..$b}\"}\"); typ='s';; # repeat a b times
[\=]) ((${#a}==b)); ret=$?; typ='n';; # length a is b
# [\<]) [[ $a < $b ]]; arith=$?; typ='n';;
# [\>]) [[ $a > $b ]]; arith=$?; typ='n';;
esac;;
*) logm "ERROR: undefined operation [$op] for [$a] [$at] and [$b] [$bt]"; return 1;
esac
return 0
}
# FIXME: string ops?
unary(){
local -i iret; local op="$ch"
readch
exp || { logm "ERROR: expression expected"; return 1; }
case "$op" in
[\!]) iret=\!ret;;
[\~]) iret=\~ret;;
esac
ret=$iret
typ='n' # result is always a decimal number
}
#==============
# Control Layer
#==============
# iff = ? boolean { consequence block } { alternative block }
# ?<1 2{+4 5}{+1 2}
iff(){
local -i c; local iff ift
readch
exp && c=$ret || { logm "ERROR: value or expression expected"; return 1; }
[[ c -eq 1 ]] && { # true so do consequence
ws
block && { iff="$ret"; ift="$typ"; } || { logm "ERROR: consequence block error"; return 1; }
ws
skip "{" "}" || { logm "ERROR: alternate block expected"; return 1; }
ret="$iff"
typ="$ift"
} || {
ws
skip "{" "}" || { logm "ERROR: consequence block expected"; return 1; }
ws
block || { logm "ERROR: alternate block error"; return 1; }
}
}
#==============
# Symbols Layer
#==============
# fn = [A-Z]
fn(){
# FIXME: make evalu?
[[ $ch = [A-Z] ]] || return 1
ret=$ch
typ='c'
readch
}
# var = [a-z]
var(){
# FIXME: make evalu?
[[ $ch = [a-z] ]] || return 1
ret=$ch
typ='c'
readch
}
# list = ( token* )
# FIXME: not finished and no operators support lists
list(){
local list=$ch prev
readch
while [[ $ch != ')' ]];do
exp || { logm "ERROR: expression expected"; return 1; }
case $typ in
[n]) list+=" $ret";;
[s]) list+="$ret";;
[l]) list+="$ret";;
esac
ws
done
ret="$list$ch"
readch
typ='l'
return 0
}
#============
# Token Layer
#============
# char = ' echoch
#echoch = \ {special echo escape character} | {char}
char(){
readch
case "$ch" in
[\\]) escch || { logm "ERROR: escape character expected"; return 1; };;
?) ret="$ch"; readch
esac
typ='c'
}
# escaped characters are a pain
# use read with -r to read in verbatim - no escaping
# use echo -E to write out verbatim (except \\ may be processed)
declare escchS
declare ECHO='abefnrtv'
# double \\ for a \
escch(){
local ESC="$ch"
readch # skip \
case "$ch" in
[$ECHO]) printf -v ret "%b" "$ESC$ch"; readch;;
[\\]) ret="\\"; readch;;
[\"]) ret="\""; readch;;
[0-7]) onum && { printf -v ret "%b" "$ESC$ret" ; } || { logm "ERROR: octal number expected"; return 1; };;
[xU]) readch; hnum && { printf -v ret "%b" "${ESC}x$ret"; } || { logm "ERROR: hex number expected" ; return 1; };;
?) ret="$ch"
[[ $escchS ]] || {
tidyReadCh
logm "WARNING: only octal, hex, unicode, and [$ECHO\\\"] characters need to be escaped with '$ESC'"
logm "WARNING: [$ch] in [$l] does not need to be escaped"
escchS="OFF"
}
readch
esac
typ='c'
}
# num = digit digit*
# onum = odigit odigit*
# onum = hdigit hdigit*
num(){ local num; num=$ch; readch; while digit;do num+=$ret; done; ret=$num; typ='n'; }
onum(){ local num; num=$ch; readch; while odigit;do num+=$ret; done; ret=$num; typ='n'; }
hnum(){ local num; num=$ch; readch; while hdigit;do num+=$ret; done; ret=$num; typ='n'; }
# digit = [0-9]
# odigit = [0-7]
# odigit = [0-9a-fA-F]
digit(){ [[ $ch == [0-9] ]] || { ret=-1; return 1; }; ret=$ch; typ='s'; readch; }
odigit(){ [[ $ch == [0-7] ]] || { ret=-1; return 1; }; ret=$ch; typ='s'; readch; }
hdigit(){ [[ $ch == [0-9a-fA-F] ]] || { ret=-1; return 1; }; ret=$ch; typ='s'; readch; }
# string = " char* "
# char = escch | {any character}
string(){
skip "\"" "\"" || { logm "ERROR: quoted string expected"; return 1; }
ret="${ret:1: -1}"
typ='s'
return 0
}
# ==========
# Char layer
# ==========
declare ch read
declare -i p L COUNT
readch(){
if [[ p -eq L ]]; then # need more code
readline || { ch=; p=L=0; l="EOF"; return 1; }
l+=$NL;
p=0
L=${#l}
fi
# FIXME: remove once eady - prevents bash consuming all memory
COUNT+=1
((COUNT>100000)) && { logm "FAILSAFE: too many charcters read"; return 1; }
ch="${l:p:1}"
read+="$ch"
p+=1 # queue next character
}
# skip = SS content* ES
# content = ch | escch | skip(SS ES)
# string = " ch* "
skip(){
local s="$1" e="$2" b="$ch"
typ='z' # code fragment
[[ $ch != $s ]] && return # nothing to skip
readch
while [[ -n $ch ]];do
case "$ch" in
$e) b+="$e" ; readch; ret="$b"; return 0;;
$s) skip "$s" "$e"; b+="$ret";;
[\\]) escch ; b+="$ret";;
[\"]) skip "\"" "\""; b+="$ret";;
?) b+="$ch" ; readch
esac
done
ret="$b"
logm "ERROR: unexpected EOF"
exit 1
}
# FIXME: still required?
shopt -s extglob
shopt -u nocasematch
declare NL; printf -v NL "%b" "\n" # echo $NL | hexdump -C
declare WS; printf -v WS "%b" " \n\t\r" # define whitespace
# FIXME: should it set ret and typ?
ws(){ while [[ $ch == [$WS] ]];do readch; done; } # skip any WS
#=====
# eval
#=====
# exp = [0-9] num
# | " string "
# | : assignment
# | @ function definition
# | [-+*/%^] binary operation
# | [&|#<>=] boolean operation
# | [!~] unary operation
# | [A-Z] function application
# | [a-z] variable
# | ? if expression
# | { expression* } block expression
# | ( expression* ) list of expressions
# spare prefix characters [ '$[]_\;, ]
# [v head of list
# ]v tail of list
exp(){
ws
case "$ch" in
[0-9]) num || { logm "ERROR: number expected" ; return 1; };;
# [\']) char || { logm "ERROR: char expected" ; return 1; };;
[\"]) string || { logm "ERROR: string expected" ; return 1; };;
[\:]) assign || { logm "ERROR: assignment expected" ; return 1; };;
[\@]) define || { logm "ERROR: function definition expected" ; return 1; };;
[-+*/%^]) binary || { logm "ERROR: binary expression expected" ; return 1; };;
[\&\|#\<\>=]) binary || { logm "ERROR: binary expression expected" ; return 1; };;
[\!~]) unary || { logm "ERROR: unary expression expected" ; return 1; };;
[A-Z]) apply || { logm "ERROR: function failed" ; return 1; };;
[a-z]) get || { logm "ERROR: variable name expected" ; return 1; };;
[\?]) iff || { logm "ERROR: boolean expression expected" ; return 1; };;
[\{]) block || { logm "ERROR: code block expected" ; return 1; };;
[\(]) list || { logm "ERROR: list expected" ; return 1; };;
'') ret=; logm "ERROR: unexpected EOF" ; return 1;;
*) ret="$ch" ; return 1;;
esac
return 0
}
# block = { code }
block(){
readch # skip {
while [[ $ch != "}" ]];do
exp || {
tidyReadCh
logm "WARNING: ignoring previous error or unknown symbol [$ch]"
[[ errors+=1 -gt 5 ]] && { logm "ERROR: exiting due to too many warnings"; exit 1; }
}
ws
done
readch # skip }
return 0
}
#=====
# repl
#=====
# pass an expression on stdin- not used withing same ebvironment - called by apply
parse(){
p=L # force readline
ch=
read=
readch # clears ch
while [[ $ch && $ch != '.' ]];do
exp || { logm "ERROR: expression expected"; return 1; }
read=$ch
ws
done
# last expression is returned as result
}
tidyReadCh(){
tidyRead
ch="${ch//[$NL]/\n}"
}
tidyRead(){
read="${read//[$NL]}"
}
# repl = eval* EOF
# eval = evalu | readch
repl(){
readch
while [[ $ch && $ch != '.' ]];do
exp && {
tidyRead
msn "> $read" # echo line except for WS
# echo -E "$ret [$typ]"
echo -E "$ret"
read=$ch
} || {
tidyReadCh
msn "> $read"
logm "WARNING: ignoring previous error or unknown symbol [$ch]"
read=
readch
[[ errors+=1 -gt 5 ]] && { logm "ERROR: exiting due to too many warnings"; exit 1; }
}
ws
done
msn "<End>"
}
#=====
# test
#=====
# FIXME: negative numbers
msn "1Lang"
repl <<<'
:b" of beer"
:w" on the wall"
:t"Take one down and pass it around, "
:s"Go to the store and buy some more, "
:c", "
:n".\n"
@Bx{?=x0{+"No more bottles"b}{+x+" bottle"+?=x1{""}{"s"}b}}
@Fx{?=x0{+B0+w+c+B0+n+s+B99+wn}{+Bx+w+c+Bx+n+t+B-x1+w+n+"\n"F-x1}}
F99
'
```
[Answer]
# Half (interpreter/translator in Windows Batch)
I don't know why I'm answering so many puzzles in windows batch, for some sick reason I think I'm enjoying it :P Anyways, this is similar to something I worked on for fun a while ago, a basic language that's translated to windows batch by a script that is also written in windows batch. It's not particularly amazing, but it works.
## 99 Bottles of Beer
```
# Initialize variables
bottles ~ 99
# You can't directly compare a literal value
zero ~ 0
# This makes a point 'loop' that can be jumped to or used as a subroutine
mark loop
write $ bottles
# You only need quotes when you have leading or trailing spaces
print ~ " bottles of beer on the wall,"
write $ bottles
print ~ " bottles of beer."
print ~ Take one down and pass it around,
bottles @ bottles-1
if
bottles equ zero
jump none
endif
write $ bottles
print ~ " bottles of beer on the wall."
print ~
jump loop
mark none
print ~ no more bottles of beer on the wall.
print ~
print ~ No more bottles of beer on the wall,
print ~ No more bottles of beer.
print ~ Go to the store and buy some more,
print ~ 99 bottles of beer on the wall.
```
## Syntax
Only three tokens are recognized on each line, separated by spaces.
# is a comment.
In most cases where a value is needed, a `$` in the second token signifies that the third should be treated as a variable name, whereas a `~` denotes a literal value.
General instructions take the form `<instruction> [$~] <name>`. Setting a variable takes the same form, but is implemented whenever is not recognized.
Defined commands:
* `print` and `write` both write output, but `write` does not add a newline. Needs $ or ~.
* `mark` creates a point that can be jumped to or called as a subroutine.
* `jump` equivalent of goto in batch (or any language for that matter).
* `proc` calls a subroutine. Equivalent of `call :label`.
* `return` returns from a subroutine. Will exit the program when not inside one.
* `if` conditional instruction. Takes comparison from the next line, in the form `<var1> <operator> <var2>`. Operators are the same as `if`'s in batch, ie. `EQU, NEQ, LSS, LEQ, GTR, GEQ`. Will execute instructions after it only if the comparison is true.
* `endif` ends an if statement.
* `cat` concatenates two variables. `cat a b` will store the value of ab in a.
When none of these commands are found, the expression is treated as a variable assignment, using the first token as the variable name. `$` and `~` behave the same as in `print`, but there is also a `@` identifier. This treats the last token as a mathematical expression, passed to `set /a`. It includes most operators. If none of the three identifiers are found, this is a syntax error and the interpreter exits.
## Interpreter (Windows Batch)
The interpreter actually translates the code into windows batch, places it in a temporary file and executes it. While it recognizes syntax errors in the Half language, the resulting batch script may cause issues, especially with special characters like parentheses, vertical bars etc.
```
@echo off
REM Half Interpreter / Translator
if exist ~~.bat del ~~.bat
if not exist "%1" call :error "File not found: '%1'"
set error=
setlocal enabledelayedexpansion
call :parse "%1" 1>~~.bat
if exist ~~.bat if not "error"=="" ~~.bat 2>nul
goto :eof
:parse
set ifstate=0
echo @echo off
echo setlocal
echo setlocal enabledelayedexpansion
for /f "eol=# tokens=1,2* delims= " %%a in (%~1) do (
if "!ifstate!"=="1" (
if /i not "%%b"=="equ" if /i not "%%b"=="neq" if /i not "%%b"=="lss" if /i not "%%b"=="leq" if /i not "%%b"=="gtr" if /i not "%%b"=="geq" call :error "Unknown comparator: '%%b'"
echo if "^!%%a^!" %%b "^!%%c^!" ^(
set ifstate=0
) else (
if "%%a"=="print" (
if "%%b"=="$" (
echo echo.^^!%%c^^!
) else if "%%b"=="~" (
echo echo.%%~c
) else call :error "Unknown identifier for print: '%%b'"
) else if "%%a"=="write" (
if "%%b"=="$" (
echo echo^|set/p="^!%%c^!"
) else if "%%b"=="~" (
echo echo^|set/p="%%~c"
) else call :error "Unknown identifier for write: '%%b'"
) else if "%%a"=="mark" (
if not "%%c"=="" call :error "Unexpected token: %%c"
echo :%%b
) else if "%%a"=="jump" (
if not "%%c"=="" call :error "Unexpected token: %%c"
echo goto :%%b
) else if "%%a"=="proc" (
if not "%%c"=="" call :error "Unexpected token: %%c"
echo call :%%b
) else if "%%a"=="return" (
if not "%%c"=="" call :error "Unexpected tokens: %%b %%c"
if not "%%b"=="" call :error "Unexpected token: %%b"
echo goto :eof
) else if "%%a"=="if" (
if not "%%c"=="" call :error "Unexpected tokens: %%b %%c"
if not "%%b"=="" call :error "Unexpected token: %%b"
set ifstate=1
) else if "%%a"=="endif" (
if not "%%c"=="" call :error "Unexpected tokens: %%b %%c"
if not "%%b"=="" call :error "Unexpected token: %%b"
echo ^)
) else if "%%a"=="cat" (
echo set "%%b=^!%%b^!^!%%c^!"
) else (
if "%%b"=="$" (
echo set "%%a=!%%c!"
) else if "%%b"=="~" (
echo set "%%a=%%~c"
) else if "%%b"=="@" (
echo set/a"%%a=%%c"
) else call :error "Unknown tokens '%%a %%b %%c'"
)
)
)
echo endlocal
goto :eof
:error
echo.Parse Error: %~1 1>&2
set error=1
goto :eof
```
[Answer]
# Flex Bison
Assign variable, if else condition block and some other addition, subtraction operation.
Laxical file `lex.l`
```
%{
#include <stdio.h>
#include <stdlib.h>
%}
var [A-Za-z][A-Za-z0-9]*
digit [0-9]+
comment \*\*[A-Za-z0-9\*\/\+\-\(\)\"\' \t;:=]*\n
%%
print {return(PRINT);}
save {return(SAVE);}
{digit} {yylval=atoi(yytext);return(DIGIT);}
{var} {yylval=strdup(yytext);return(VAR);}
\* {return(M_SIGN);}
\/ {return(D_SIGN);}
\+ {return(A_SIGN);}
\- {return(S_SIGN);}
\( {return(L_BRACE);}
\) {return(R_BRACE);}
= {return(E_SIGN);}
; {return(S_COLON);}
: {return(COMMA);}
\n {return (NW_LINE);}
[ \t] /*skip*/;
{comment} /*skip*/;
%%
```
Parser file `com.y`
```
%{
#include <ctype.h>
#include <stdio.h>
FILE *save_p;
int new_line=1,stack_top=0,trigger=1;
void value_store(int);
int check_srore(char name_var[],int);
void error(int);
struct store
{
int var_value;
char var_name[10];
}info[10];
%}
%token PRINT SAVE S_COLON L_BRACE R_BRACE DIGIT VAR COMMA NW_LINE
%left A_SIGN S_SIGN
%left D_SIGN M_SIGN
%right E_SIGN
%%
commands :
| commands command
;
command : expers
| print
| save
| NW_LINE{new_line++;}
;
save : SAVE expr etest {fprintf(save_p,"%d\n",$2);}
;
expers : store_val equal expr etest{value_store($3);}
;
print : PRINT expr etest {printf("%d\n",$2);}
;
etest : S_COLON
| DIGIT {error(0);}|PRINT{error(0);}|SAVE{error(0);}
| VAR{error(0);}|COMMA{error(0);}
;
store_val : VAR {check_store($1,0);}
;
expr : expr A_SIGN expr { $$ = $1 + $3; }
| expr S_SIGN expr { $$ = $1 - $3; }
| expr M_SIGN expr { $$ = $1 * $3; }
| expr D_SIGN expr { $$ = $1 / $3; }
| L_BRACE expr R_BRACE { $$ = $2; }
| DIGIT
| retriv_var
;
equal : E_SIGN
;
retriv_var : VAR { $$=check_store($1,1); }
;
%%
#include "lex.yy.c"
void error(int temp)
{
char *err[]={
"Statement Missing\n",
"Compund Statement Missing\n",
"Variable need a value\n",
"Invalid Argument\n"
};
printf("In line no.%d:\t%s",new_line,err[temp]);
exit(1);
}
void value_store(int store_val)
{
stack_top--;
info[stack_top++].var_value = store_val;
}
int check_store(char name_var[],int status)
{
int temp = 0;
do{
if(strcmp(info[temp].var_name,name_var)==0)
{
trigger=0;
if(status)
{
trigger=1;
return (info[temp].var_value);
}
}
temp++;
} while(temp<stack_top);
if(trigger)
{
if(status)
{
trigger=1;
error(2);
}
else
strcpy(info[stack_top++].var_name,name_var);
}
else trigger=1;
}
int yyerror(const char *str)
{
fprintf(stderr,"error: %s\n",str);
}
main(int argc, char *argv[])
{
if(argc != 3)
{
error(3);
}
yyin = fopen(argv[1],"r");
save_p = fopen(argv[2],"w");
yyparse();
fclose(yyin);
fclose(yyout);
}
```
Compile
1. List item
2. flex lex.l
3. bison com.y
4. gcc -o compiler com.tab.c -lfl
Run
compiler in.txt ou.txt
Input file
a = 3 + (4 \*7) -9;
print a;
c = a+45;
print c;
\*\*This is comment
save c;
\*\* save c in the file
print c\*(a+32);
Output file
67
[Answer]
I give you:
# Small Instruction Set Interpreter (SISI)
The syntax draws on BASIC and assembly. It has four statements: `set`, `print`, `jump` (unconditional goto), and `jumpif` (conditional goto). Every statement must be preceded by a line number. Supported data types are integers and strings.
The interpreter itself can be found in Python 3 [on Github](http://github.com/dloscutoff/esolangs/tree/master/Sisi) (sisi.py). The 99 Bottles of Beer program is there as well, but I'll reproduce it here:
```
10 set x 99
20 set bottles " bottles "
100 set line x + bottles
110 set line line + "of beer on the wall, "
120 set line line + x
130 set line line + bottles
135 set line line + "of beer."
140 print line
200 set x x - 1
210 set none x = 0
220 jumpif none 400
230 set multiple x > 1
240 jumpif multiple 300
250 set bottles " bottle "
300 set line "Take one down and pass it around, " + x
310 set line line + bottles
320 set line line + "of beer on the wall."
330 print line
340 print ""
350 jump 100
400 print "Take one down and pass it around, no more bottles of beer on the wall."
410 print ""
420 print "No more bottles of beer on the wall, no more bottles of beer."
430 print "Go to the store and buy some more, 99 bottles of beer on the wall."
```
[Answer]
# Interpreter
For instructions on how to run this code, take a look at my other answer: <https://codegolf.stackexchange.com/a/19935/13186>
# 99 Bottles of Beer
## The Program
```
bottles of beer on the wall, @ bottles of beer.
Take one down and pass it around, @ bottles of beer on the wall.
@ bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.
@@@@@@@@@@@@@@
#9.{
!#48.+
!<#57.<#0.^<!<#57.<#1.^<!<#56.<#64.^<
!<#56.<#0.^<!<#56.<#1.^<!<#55.<#64.^<
!<#55.<#0.^<!<#55.<#1.^<!<#54.<#64.^<
!<#54.<#0.^<!<#54.<#1.^<!<#53.<#64.^<
!<#53.<#0.^<!<#53.<#1.^<!<#52.<#64.^<
!<#52.<#0.^<!<#52.<#1.^<!<#51.<#64.^<
!<#51.<#0.^<!<#51.<#1.^<!<#50.<#64.^<
!<#50.<#0.^<!<#50.<#1.^<!<#49.<#64.^<
!<#49.<#0.^<!<#49.<#1.^<!<#48.<#64.^<
!<#48.<#0.^<!<#48.<#1.^<!#1.-<#57.<#64.^<
_
?}
#57.<#0.^<#57.<#1.^<!<#56.<#64.^<
#56.<#0.^<#56.<#1.^<!<#55.<#64.^<
#55.<#0.^<#55.<#1.^<!<#54.<#64.^<
#54.<#0.^<#54.<#1.^<!<#53.<#64.^<
#53.<#0.^<#53.<#1.^<!<#52.<#64.^<
#52.<#0.^<#52.<#1.^<!<#51.<#64.^<
#51.<#0.^<#51.<#1.^<!<#50.<#64.^<
#50.<#0.^<#50.<#1.^<!<#49.<
#94.^<
$
```
[Answer]
# 99ISC
99ISC uses an arbitrarily-sized integer-oriented memory. Memory is indexed by a non-negative integer. All values in memory are initialized with their address. Eg. At runtime, address 0 contains value 0 and address 9 contains value 9.
99ISC has two instructions. The first prints out the 99 Bottles of Beer on the Wall routine. Its syntax is a single line, as below. Execution continues with the next line in the program.
```
.
```
The second instruction is a "subtract and branch if not equal to zero" instruction. Its syntax is a single line, as below.
```
x y z
```
`x` is the address of the number to be operated on, `y` is the address of the number being subtracted, and `z` is the next line to execute if the result of the subtraction is not zero. Otherwise, execution proceeds with the next line.
The presence of the "subtract-and-branch-if-not-zero" instruction makes 99ISC an OISC (One Instruction Set Computer) and therefore Turing complete.
Here is a program that erases the first 10 values in memory and then prints the 99 Bottles of Beer on the Wall routine.
```
1 1 0
2 2 0
3 3 0
4 4 0
5 5 0
6 6 0
7 7 0
8 8 0
9 9 0
.
```
And here is a 99ISC interpreter, in Python.
```
def interpret(filename):
mem = range(0, 10)
print mem
with open(filename) as f:
lines = f.readlines()
ptr = 0
while ptr < len(lines):
line = lines[ptr]
if line.strip() == ".":
for i in range(99,0,-1):
text = str(i) + " bottles of beer on the wall, " + str(i) + " bottles of beer.\nTake one down and pass it around, " + str(i-1) + " bottles of beer on the wall.\n\n"
print text.replace("0", "No more")
else:
toks = map(int, line.split())
mem[toks[0]] = (mem[toks[0]] - mem[toks[1]]) & 0xFF
if mem[toks[0]] != 0:
ptr = toks[2]
else:
ptr += 1
```
[Answer]
## Pogo
<https://github.com/nrubin29/Pogo>
```
method main:void
declare(integer,i,99)
while i > 0
print(i "bottles of beer on the wall")
math(i - 1) i
end
end main
```
]
|
[Question]
[
**Note that this challenge requires no handling or understanding of complex numbers.**
Given a non-empty square matrix where every element is a two-element (Re,Im) integer list, determine (giving any truthy/falsy values or any two consistent values) whether this represents a Hermitian matrix.
Note that the input is a 3D array of integers; not a 2D array of complex numbers. If your language cannot take a 3D array directly, you may take a flat list (and the n√ón or n√ón√ó2 shape if that helps).
A matrix is [Hermitian](https://en.wikipedia.org/wiki/Hermitian_matrix) if it equals its own [conjugate transpose](https://en.wikipedia.org/wiki/Conjugate_transpose). In other words, if you flip it across its top-left to bottom-right diagonal and negate the second element of all the two-element leaf-lists, it is identical to the input matrix. Note that the order of flipping and negating is irrelevant, so you may negate first, and flip afterwards.
### Walk-though example
This example uses JSON with superfluous white-space to ease reading:
```
[[ [2, 0] , [2, 1] , [4, 0] ],
[ [2,-1] , [3, 0] , [0, 1] ],
[ [4, 0] , [0,-1] , [1, 0] ]]
```
Transpose (flip across NW—SE diagonal):
```
[[ [2, 0] , [2,-1] , [4, 0] ],
[ [2, 1] , [3, 0] , [0,-1] ],
[ [4, 0] , [0, 1] , [1, 0] ]]
```
Negate second elements of leaf-lists:
```
[[ [2, 0] , [2, 1] , [4, 0] ],
[ [2,-1] , [3, 0] , [0, 1] ],
[ [4, 0] , [0,-1] , [1, 0] ]]
```
As this is identical to the input, the matrix is Hermitian.
## Test cases
### Hermitian
`[[[2,0],[2,1],[4,0]],[[2,-1],[3,0],[0,1]],[[4,0],[0,-1],[1,0]]]`
`[[[1,0],[2,0]],[[2,0],[1,0]]]`
`[[[1,0],[2,-3]],[[2,3],[1,0]]]`
`[[[42,0]]]`
### Non-Hermitian
`[[[2,0],[2,1],[4,0]],[[2,-1],[3,0],[0,1]],[[4,0],[0,-1],[1,-1]]]`
`[[[0,1],[0,2]],[[0,2],[0,1]]]`
`[[[1,0],[2,3]],[[2,3],[1,0]]]`
`[[[3,2]]]`
[Answer]
# R, ~~71~~ ~~48~~ 47 bytes
```
function(A)all(Conj(t(B<-A[,,1]+A[,,2]*1i))==B)
```
Takes a 3D array of real numbers, make a 2D array of imaginary numbers, transpose, conjugate and compare.
Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312) for reducing the byte count by an astounding 23 bytes, and to [@Vlo](https://codegolf.stackexchange.com/users/30693) for the final 1!
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9Pw1EzMSdHwzk/L0ujRMPJRtcxWkfHMFYbRBnFahlmamra2jpp/k/TSCwqSqzUSNYw0jHSMQFiYx0DIG2gYwjEuoZoDE2dlMxc22QNY6AyI01NTS6EfhMjhLQhUC2aNDHG6xriMR8kgG78fwA "R – Try It Online")
Example:
```
> A <- array(c(2,2,4,2,3,0,4,0,1,0,-1,0,1,0,-1,0,1,0),dim=c(3,3,2))
> A
, , 1
[,1] [,2] [,3]
[1,] 2 2 4
[2,] 2 3 0
[3,] 4 0 1
, , 2
[,1] [,2] [,3]
[1,] 0 1 0
[2,] -1 0 1
[3,] 0 -1 0
> f <- function(A)all(Conj(t(B<-A[,,1]+A[,,2]*1i))==B)
> f(A)
[1] TRUE
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~39~~ ~~34~~ 31 bytes
```
@(x)(y=x(:,:,1)+j*x(:,:,2))==y'
```
[Try it online!](https://tio.run/##JcmxCoAgFEbhvRfp3voTtabkQu8RDSE5tLREaC9vStvHOZe/9@fIQZRSeaHIlCTSjBmG@7P7aZlFUpujrBYWk7MYod0EDbO5JslaUMJganEaFWW84vebRkQkbgK9nD8 "Octave – Try It Online")
Saved 3 bytes thanks to Luis Mendo who informed me about the clarifications in the challenge text.
### Explanation:
In MATLAB and Octave, `'` is the conjugate complex transpose, not the "regular" transpose.
We create a variable `y` inline that's the first layer of the 3D matrix plus the second layer multiplied with the complex unit `j`, i.e. a complex matrix where the real term is the first "layer", and the imaginary is the second "layer". We then check if it equals itself complex conjugate transposed.
This will output a matrix containing only `1` if true, and a matrix containing at least one `0` if false. These are considered true and false in Octave [(Proof)](https://tio.run/##y08uSSxL/f8/M00h2lBHAYgMYnUUUjKLCzTU4QIKmcUKJUWlqeqaOgqpOcWp2OTTEoESYAV5KVwI0wzRTTMkYJohhmn//wMA).
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
lambda m:[[[a,-b]for a,b in l]for l in zip(*m)]==m
```
[Try it online!](https://tio.run/##rU67CgMhEOzvKyzPoOCrCvglFwslSAT15Lgm@XmzioEQjqRJs7OzMztMue@3NYvq9aVGm9zVonRelsUS6oxfN2SJQyGj2Els6yOU@ZSw0TrVsoW8Iz/DhyDMEJgcpoIdABhtVHaJgdSOarAu8eY0eHoL4iPoFcG@26gcPnnsU2Lcpj@UBfiIZz2DEdHtDcfzcdsfZWXLMbg@AQ "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~22~~ ~~15~~ ~~9~~ 7 bytes
```
⍉≡⊢∘-\¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHvZ2POhc@6lr0qGOGbsyhFUBRBQ1jBeNHvVs0jBQMNIGEoaaGCYR1aD2QbQxiG8BFDSCihkC2JhdQr5GCEUivIUQHjMAhfWi9MYgyRlJgqGAIVPCoq8kEpJGLXNeAKGQLwUqghBGEhcU9uF0DtMhIUxMA "APL (Dyalog Unicode) – Try It Online")
Tacit prefix function.
Thanks to Ad√°m for 7 bytes on the Dfn, and to both Ad√°m and ErikTheOutgolfer for ~~putting up with my stupidity~~ helping me find the tacit version.
Thanks to ngn for 2 bytes on the tacit version.
### How?
```
⍉≡⊢∘-\¨ ⍝ Anonymous tacit function.
¨ ⍝ Apply to each element of the argument:
\ ‚çù Cumulative reduction, using
⊢∘- ⍝ Ignore the first element, then negate the second
≡ ⍝ And match
‚çâ ‚çù To the argument's transposition.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~45~~ ~~34~~ ~~33~~ ~~26~~ ~~21~~ 18 bytes
* Saved eleven bytes thanks to [JungHwan Min](https://codegolf.stackexchange.com/users/60043/junghwan-min).
* Saved a byte thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender).
* Saved seven bytes thanks to [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha).
* Saved five bytes thanks to [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha).
* Saved three bytes.
```
#==#Ôèâ&[#.{1,I}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9nWVvl9f6datLJetaGOZ22s2v@Aosy8Eoc0h@rqaiMdg1odIGkIJE2AbCAF5OmCuMZgKQOgFEjQBMoDSxmCVNZyIZljCDUHZoIBXlW6xlBlxliVmRghCynp6uoqcVHBzUAK1R4DsBEGOkZg1SAaqhero/G72RhkSu1/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Java 8, ~~137~~ ~~136~~ ~~134~~ ~~126~~ ~~119~~ 116 bytes
```
m->{int r=1,l=m.length,i=l*l,j,k;for(;i-->0;)r=m[j=i/l][k=i%l][0]!=m[k][j][0]|m[j][k][1]!=-m[k][j][1]?0:r;return r;}
```
-3 bytes thanks to *@ceilingcat*.
Returns `1` if Hermitian, `0` otherwise.
**Explanation:**
[Try it online.](https://tio.run/##tVA9b4MwEN3zK9xIlaA1hI9MQU63bs2SbojBJU5iMCYyJlVE@e30DE63SlXaCnPn9@7Dd6@gZ@rVJyaLXTnkgjYNeqFcdjOEuNRM7WnO0MbAkUC5AzbNzIcqNwG@hx9Oo6nmOdogiQgaKm/dmXRFQixI5QsmD/qIOREPAhe4TPa1chLueesgcRWp0oLwhcjSkvB7cEF2B1yZpYW5f1TGAwqB9q58mD0FK5UoplslkUr6IZkmObVvAiaxA51rvkMVrORsteLykGbUndZZLNCravXxshrh9tJoVvl1q/0TJGpH@rkj2Tv6WrjruggHPQYbgl3CHRwgz8B4DAUQMuTSojEUmszefZzj@SjZDx8L7WPXZ4Lft/Ji2yu@vdcymuq@qRHSsREQ@JmKhv2rwJO@kHDDJlN1gKOxo/G2/@0C/4G@sZnHytvP@uET)
```
m->{ // Method with 3D integer-array as parameter and boolean return-type
int r=1, // Flag-integer `r`, starting at 1
l=m.length, // The size of the 3D input array
i=l*l,j,k; // Index-integers
for(;i-->0;) // Loop over the rows and columns
r=m[j=i/l][k=i%l][0]!=m[k][j][0]
// If the first numbers diagonally aren't equal,
|m[j][k][1]!=-m[k][j][1]?
// or the second numbers aren't negatives of each other:
0 // Set the flag `r` to 0
: // Else:
r; // Leave the flag `r` the same
return r;} // Return the flag `r`
```
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
[:(+-:|:)j./"1
```
[Try it online!](https://tio.run/##JYs7CoAwEET7nGIIgoq/XbVa9CQWFmKQQLCw1bPHjTI8Bt4wProLs4CgxEWKqpFbSt92lmNpbIvcpT1HjUfgLmP27TgxWUZIw6DpkSmkMMavV1ZNml9QEgz6vw4hvg)
## Explanation
```
[:(+-:|:)j./"1 Input: 3d array
j./"1 Reduce by complex combine at rank 1
[: Cap, operate on the 2d array of complex values
+ Conjugate
|: Transpose
-: Match?
```
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
*-7 bytes thanks to H.PWiz.*
```
(==)<*>map(map((0-)<$>)).foldr(zipWith(:))e
e=[]:e
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX8PWVtNGyy43sUADhDUMdDVtVOw0NfXS8nNSijSqMgvCM0syNKw0NVO5Um2jY61S/@cmZuYp2CoUFGXmlSioKKQpRAOhhpGOgoGmDpg2BNEmIL5CLJcCOtCBqNYFqzKG6jIA6cKp2gSuCqLLEGK2Quz/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Zר+⁼
```
A monadic link returning `1` for a Hermitian input and `0` otherwise.
**[Try it online!](https://tio.run/##y0rNyan8/z/q8PTDM7QfNe75//9/dLRCtJGOgkGsgg6YYQhmmIBFYnW4FMDSuhBRY5g6A7A6qLQJQhSqzhCiOxYA "Jelly – Try It Online")**
### How?
```
Zר+⁼ - Link: list of lists of lists, M
Z - transpose
√ò+ - literal = [1,-1]
√ó - multiply (vectorises)
⁼ - equal to M?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
øεεX®‚*]Q
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8I5zW89tjTi07lHDLK3YwP//o6OjjXQMYnWApCGQNAGygRSQpwviGoOlDIBSIEETKA8sZQiiYmMB "05AB1E – Try It Online")
**Explanation**
```
√∏ # transpose
ε # apply to each 2-d array
ε # apply to each pair
X®‚* # multiply by [1,-1]
] # end apply(s)
Q # compare to input for equality
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
->m{m.transpose.map{|l|l.map{|a,b|[a,-b]}}==m}
```
[Try it online!](https://tio.run/##pU67DsMgENvzFf0AiHit9EfSG0BqptCikAxV4NvJQamqSlGWMpzPZ2N5Xu0rj/qW6dVtrl9m8wj@Ge69M36LU5zeiyE2DoZQCylp7VL26xIu44BPEAYEJ8epcEdARguVVWIolaNqrEq8OAG6bw5vOZ8EduqistnkoU2Jdur@L4rwG85qBCOiugu2v4dNz4vKkgKQdw "Ruby – Try It Online")
Port of my [Python answer](https://codegolf.stackexchange.com/a/156752/38592)
[Answer]
# [Perl 5](https://www.perl.org/), -a0 48 bytes
Old counting: 50 bytes (`+2` for `a0`). Not bad for a language that has no builtin transpose (I'm not jealous at all, no sirree)
Give the input matrix on STDIN with `,` between the real and imaginary part, so e.g.:
```
2,0 2,1 4,0
2,-1 3,0 0,1
4,0 0,-1 1,0
```
Will print `1` for hermitian, nothing otherwise
```
#!/usr/bin/perl -a0
say@F~~[map/(\S+,)(\S+)/gc?$1.-$2:(),(/.+/g)x@F]
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2igZ2D9vzix0sGtri46N7FAXyMmWFtHE0Rq6qcn26sY6umqGFlpaOpo6Otp66drVji4xf7/b6RjoGCkY6hgomPAZaSja6hgDBQw0DHkMgHTQAFDoMy//IKSzPy84v@6iQYA "Perl 5 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
=¹mmṀ_T
```
[Try it online!](https://tio.run/##yygtzv7/3/bQztzchzsb4kP@//8fHa1hpGOgqQMkDYGkCZAdqwMS0wVxjcFSBkApkKAJlAeWMgSpjAUA "Husk – Try It Online")
# How?
Note that `†` should work instead of `mm`
, but [there's an annoying bug](https://chat.stackexchange.com/transcript/message/43073150#43073150) that prevents me from using it :(
```
=¹mmṀ_T – Full program. Takes input from Command line args, as a list of lists of tuples.
m T – For each list in the input's tranpose...
mṀ_ – ... Negate the last value of each tuple they contain.
=¹ – Check whether this is the same as the input.
```
[Answer]
# JavaScript (ES6), 53 bytes
*Saved 2 bytes thanks to @Neil*
Returns `false` for Hermitian or `true` for non-Hermitian.
```
m=>m.some((r,y)=>r.some(([a,b],x)=>m[x][y]!=a+[,-b]))
```
[Try it online!](https://tio.run/##tVFBDoMgELz7i54qKRgUr3ruqR8gHNBiYyPQqGn09XYhmLRpY7z0ssvszA5MuMunHOq@fYzE2KtammLRRamTwWoVxz2eUVH2AXGJK4EnmGg@CT6LQyFPHJNKILTU1gy2U0lnb/GRn1Wv27GVRhxR9E41Mec8w1RgqCnUHM7QABEHmacoUG6YB@Sp1Cnhqm@/NPitTnSXmrAgZ5vyPFup6DPjxRryn5zQfr@FeiuKM7/levDYDLovJ3Ou7idf "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~107~~ ~~103~~ 100 bytes
* Saved four bytes thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox); golfed `A[0]` to `*A` twice.
* Saved three bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
j,k,r;f(A,s)int***A;{for(r=0,j=s;j--;)for(k=s;k--;)r|=*A[j][k]-*A[k][j]|A[j][k][1]+A[k][j][1];A=!r;}
```
[Try it online!](https://tio.run/##hZFfC4IwFMWf7VNUEGxrA28GPYwRe@s72B7ENOb8E9OnrM9uUxQMIt/O7@zcuzMWs3scd11GDbU8RZLWWJcNIUTyNq0sssKnmah5xhjHvWEcmB7sSxAZZio0ijlhlNOv0QhB7UfLSS7FxvJ3V0S6RLhdeeMNoojyvIpRrZ9JlaLBxeSA@cqToa8Wjn8nvgN9BmYISvgTwtI4DOPBDN3IcUD4Xw6WysFULpihW8qm9QvtYGp3muH4uId10RRtL4ktdKOj8rze3a7llva/e8Buwbv7AA "C (gcc) – Try It Online")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 13 bytes
```
┬⌠⌠Çá╫k⌡M⌡Mß=
```
[Try it online!](https://tio.run/##S0wuKU3Myan8///RlDWPehYA0eH2wwsfTV2d/ahnoS8IH55v@/9/dHS0kY5BrA6QNASSJkA2kALydEFcY7CUAVAKJGgC5YGlDEEqYwE "Actually – Try It Online")
## How it works?
This submission **actually** makes use of complex numbers. If taking input as a matrix of complex entries was allowed, then it would be [8 bytes](https://chat.stackexchange.com/transcript/message/43075355#43075355).
```
┬⌠⌠Çá╫k⌡M⌡Mß= –> Full program.
┬ –> Transpose.
⌠ ⌡M –> For each list in the input's transpose do the following:
⌠ ⌡M –> For each two-element list of the form [a, b]...
Ç –> Turn it into a complex number (a+bi).
á –> Find its complex conjugate: Push (a-bi).
╫k –> Push [Re(N), Im(N)], so [a, -b].
ß= –> Check whether the result equals the input.
```
[Answer]
# Pyth, 9 bytes
```
qCmm,hk_e
```
Explanation:
```
qCmm,hk_ekdQQ Autofill variables
,hk_ek [a,-b]...
mm dQ ...for each [a,b] in the input (m...Q)'s rows (m...d).
C Transpose.
q Q Is this result equal to the original?
```
[Test suite](http://pyth.herokuapp.com/?code=qCmm%2Chk_e&input=%5B%5B%5B2%2C0%5D%2C%5B2%2C1%5D%2C%5B4%2C0%5D%5D%2C%5B%5B2%2C-1%5D%2C%5B3%2C0%5D%2C%5B0%2C1%5D%5D%2C%5B%5B4%2C0%5D%2C%5B0%2C-1%5D%2C%5B1%2C0%5D%5D%5D&test_suite=1&test_suite_input=%5B%5B%5B2%2C0%5D%2C%5B2%2C1%5D%2C%5B4%2C0%5D%5D%2C%5B%5B2%2C-1%5D%2C%5B3%2C0%5D%2C%5B0%2C1%5D%5D%2C%5B%5B4%2C0%5D%2C%5B0%2C-1%5D%2C%5B1%2C0%5D%5D%5D%0A%5B%5B%5B1%2C0%5D%2C%5B2%2C0%5D%5D%2C%5B%5B2%2C0%5D%2C%5B1%2C0%5D%5D%5D%0A%5B%5B%5B1%2C0%5D%2C%5B2%2C-3%5D%5D%2C%5B%5B2%2C3%5D%2C%5B1%2C0%5D%5D%5D%0A%5B%5B%5B42%2C0%5D%5D%5D%0A%5B%5B%5B2%2C0%5D%2C%5B2%2C1%5D%2C%5B4%2C0%5D%5D%2C%5B%5B2%2C-1%5D%2C%5B3%2C0%5D%2C%5B0%2C1%5D%5D%2C%5B%5B4%2C0%5D%2C%5B0%2C-1%5D%2C%5B1%2C-1%5D%5D%5D%0A%5B%5B%5B0%2C1%5D%2C%5B0%2C2%5D%5D%2C%5B%5B0%2C2%5D%2C%5B0%2C1%5D%5D%5D%0A%5B%5B%5B1%2C0%5D%2C%5B2%2C3%5D%5D%2C%5B%5B2%2C3%5D%2C%5B1%2C0%5D%5D%5D%0A%5B%5B%5B3%2C2%5D%5D%5D&debug=0).
[Answer]
# C, ~~ 111 ~~ ~~ 110 ~~ 108 bytes
*Thanks to @Jonathan Frech for saving a byte and thanks to @ceilingcat for saving two bytes!*
```
i,j,r;f(A,n)int*A;{for(r=i=0;i<n*2;i+=2)for(j=n*2;j;r|=A[i*n+j]-A[j*n+i]|A[i*n-~j]+A[j*n-~i])j-=2;return!r;}
```
[Try it online!](https://tio.run/##jZDLaoQwGEb3PkU6UDD6B3JxLpBm4XPYLIodSwJNS2pXjvPqNsahnaI4E8jtg@@EnJq81fUwGLDgZZOW4LBxbVbKrvnwqVdGUWmeXMalyRXHY2jVeLXSn1RZmczlVpOysuFg9Ckm5Gx1HiNyNhpborj0x/bbuwcv@yE8gN5fjEtx0iUojDFoj18tqzRSqONAgQODIu6EgQgHegnoGDCgvYzVTx/KTbp5fH12G0BNGjmABMYy@QfnE5xF6DRvYDggPsOIawwRYRG3OGKJU0ycgq93C0Bs1t3e74mwNfp2SdRuokc9f6rWMLulD@6vRd3lab@EOUyYAJhVf4uHi6R@@AE)
# [C (gcc)](https://gcc.gnu.org), ~~ 106 ~~ 104 bytes
```
i,j,r;f(A,n)int*A;{for(r=i=0;i<n*2;i+=2)for(j=n*2;j;r|=A[i*n+j]-A[j*n+i]|A[i*n-~j]+A[j*n-~i])j-=2;A=!r;}
```
[Try it online!](https://tio.run/##jdDdaoMwHAXwe58iKwwS/QdMYj8gzUWew3kx3BwJLBupd9a@uouxbB2KraDGA@cHnpp@1PUwGLDgZYM1OGJcm2rZNV8ee2VULs3RpVyaTHEyhlaNn1b6s9KlSV1mK6pLGw6mOseEXmyVxYheTEUsVVxq9eRlPwQcfb4ah0nSJShcY9C@n1pWVkihjkMOHBgU8U0ZiHDIr0E@BgzyXsbqtw/lBm@e317cBlCDowNIECKTfzifcBbR6b7DcEB8xohbhorwEPccseQUk1Pw9W4BiM2628d3omxN3y4NtZv0OM/fVGvMbukH97dDPbTTfok5TEwAZtXf4uE6Uj/8AA)
[Answer]
# [Actually](https://github.com/Mego/Seriously), 13 bytes
```
;┬⌠⌠d±@q⌡M⌡M=
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9/60ZQ1j3oWAFHKoY0OhY96FvqCsO3//9HRCtFGOgoGsQo6YIYhmGECFokFskCCuhBBY5gyA7AyiKwJQhCqzBCiNxYA "Actually – Try It Online")
Explanation:
```
;┬⌠⌠d±@q⌡M⌡M=
; make a copy
┬ transpose copy
⌠⌠d±@q⌡M⌡M for each row:
⌠d±@q⌡M for each cell in row:
d remove last element from list
± swap sign
@q insert at end of list
= compare equality with original
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü♦╧Γ♥├eï∞
```
[Run and debug it](https://staxlang.xyz/#p=8104cfe203c3658bec&i=%5B%5B%5B2,0%5D,%5B2,1%5D,%5B4,0%5D%5D,%5B%5B2,-1%5D,%5B3,0%5D,%5B0,1%5D%5D,%5B%5B4,0%5D,%5B0,-1%5D,%5B1,0%5D%5D%5D%0A%0A%5B%5B%5B1,0%5D,%5B2,0%5D%5D,%5B%5B2,0%5D,%5B1,0%5D%5D%5D%0A%0A%5B%5B%5B1,0%5D,%5B2,-3%5D%5D,%5B%5B2,3%5D,%5B1,0%5D%5D%5D%0A%0A%5B%5B%5B42,0%5D%5D%5D%0A%0A%5B%5B%5B2,0%5D,%5B2,1%5D,%5B4,0%5D%5D,%5B%5B2,-1%5D,%5B3,0%5D,%5B0,1%5D%5D,%5B%5B4,0%5D,%5B0,-1%5D,%5B1,-1%5D%5D%5D%0A%0A%5B%5B%5B0,1%5D,%5B0,2%5D%5D,%5B%5B0,2%5D,%5B0,1%5D%5D%5D%0A%0A%5B%5B%5B1,0%5D,%5B2,3%5D%5D,%5B%5B2,3%5D,%5B1,0%5D%5D%5D%0A%0A%5B%5B%5B3,2%5D%5D%5D&m=1)
]
|
[Question]
[
Your task is to display the below letter "E" shaped ASCII art, given five inputs.
Examples:
Input: `7,2,+,|,-` (Note: You don't have to follow this exact input format, and if you don't use it, then you must explain how your own input format works)
Explanation:
* `7` *total width, including the left and right edge characters.*
* `2` *Number of vertical characters.*
* `+` *The character that should display at the edges.*
* `|` *The character that should display vertically between the edges.*
* `-` *The character that should display horizontally.*
Output of the above example:
```
+-----+
|
|
+-----+
|
|
+-----+
```
---
---
Other examples:
Input: `7,2,@,|,-`
Output:
```
@-----@
|
|
@-----@
|
|
@-----@
```
---
---
Input: `7,2,+,|,#`
Output:
```
+#####+
|
|
+#####+
|
|
+#####+
```
---
---
Input: `8,3,+,|,#`
Output:
```
+######+
|
|
|
+######+
|
|
|
+######+
```
---
---
Input: `8,3,+,@,#`
Output:
```
+######+
@
@
@
+######+
@
@
@
+######+
```
---
---
Input: `9,4,^,$,!`
Output:
```
^!!!!!!!^
$
$
$
$
^!!!!!!!^
$
$
$
$
^!!!!!!!^
```
---
---
Cheating and standard loopholes are not allowed.
Your code must not print anything to STDERR.
Your code may accept any character encoding you choose as the input, but any character encoding you choose must, as a minimum, support [all the 95 printable ASCII characters.](http://www.theasciicode.com.ar/ascii-printable-characters/underscore-understrike-underbar-low-line-ascii-code-95.html)
The shortest code, in bytes, that completes this challenge successfully, is the winning code.
### Leaderboard
```
var QUESTION_ID=92138,OVERRIDE_USER=58717;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~16~~ 14 bytes
```
Í×s.ø©|`×`»D®»
```
**Explanation**
```
Í× # create a string of the correct nr of horizontal chars
s.ø # add the corner char on both sides
© # save in register while keeping it on the stack
|` # push the remaining inputs to the top of the stack
×` # push the correct nr of vertical chars on the stack
» # join on newline (joining the top vertical and horizontal sections)
D # duplicate this
® # push the horizontal part again
» # join everything on newline
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w43Dl3Muw7jCqXxgw5dgwrtEwq7Cuw&input=NwotCisKMgp8)
Saved 4 bytes thanks to Adnan.
[Answer]
# Python, ~~53~~ ~~51~~ 55 Bytes
```
lambda a,b,c,d,e:d.join("\n"*-~b).join([c+e*(a-2)+c]*3)
```
*+4 Bytes thanks to @nimi*
anonymous lambda function, to call it, write `f=` before it. Example:
```
>>> print f(4,1,"€","|","-")
€--€
|
€--€
|
€--€
```
## alternative, 53 Bytes
```
lambda a,b,c,d,e:((c+e*a+c+"\n"+(d+"\n")*b)*3)[:-b*2]
```
## old version with the special case of no input, ~~69~~ ~~65~~ 63 Bytes
yay to changing the requirements mid-challenge...
```
lambda a=1,b=1,(c,d,e)="+|-":d.join("\n"*-~b).join([c+e*a+c]*3)
```
[Answer]
# C, ~~167~~ ~~161~~ 159 bytes
Yeah.
```
#define p putchar
i,j;g(a,c,e){p(c);for(i=2;i++<a;)p(e);p(c);p(10);}h(b,d){for(i=0;i++<b;){p(d);p(10);}}f(a,b,c,d,e){g(a,c,e);h(b,d);g(a,c,e);h(b,d);g(a,c,e);}
```
[Try it on Ideone, with some test cases](https://ideone.com/VpcAY6)
[Answer]
# Ruby, ~~54~~ ~~45~~ 42 bytes
```
->x,y,c,v,h{[c+h*~-~-x+c+$/]*3*((v+$/)*y)}
```
It's an anonymous function that takes the different part of the input as separate parameters and returns the result as a complete string.
For example,
```
f=->x,y,c,v,h{[c+h*~-~-x+c+$/]*3*((v+$/)*y)}
puts f[6, 2, 'Ø', 'V', '>']
```
prints
```
Ø>>>>Ø
V
V
Ø>>>>Ø
V
V
Ø>>>>Ø
```
[Answer]
## Javascript (ES6), 64 bytes
```
(h,v,e,V,H)=>(v=(h=e+H.repeat(h-2)+e)+`
${V}`.repeat(v)+`
`)+v+h
```
### Example
```
let f =
(h,v,e,V,H)=>(v=(h=e+H.repeat(h-2)+e)+`
${V}`.repeat(v)+`
`)+v+h
console.log(f(8,3,'+','@','#'))
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), 18 bytes
```
älJxxÀPjddÀpkäGYGp
```
[Try it online!](http://v.tryitonline.net/#code=w6RsSnh4w4BQamRkw4Bwa8OkR1lHcA&input=QAotCnw&args=NQ+NQ)
[Answer]
# R, 80 bytes
Pretty repetitive :
```
function(h,v,a,b,c)cat(t<-c(a,rep(c,h),a,"\n"),d<-rep(c(b,"\n"),v),t,d,t,sep="")
```
**Ungolfed :**
```
function(h,v,a,b,c)
cat(t<-c(a,rep(c,h),a,"\n"),
d<-rep(c(b,"\n"),v),
t,d,t,
sep="")
```
[Answer]
## Pyke, ~~16~~ 15 bytes
```
*2mtz:zn+Q*' +D
```
[Try it here!](http://pyke.catbus.co.uk/?code=%2a2mtz%3Azn%2BQ%2a%27+%2BD&input=3%0A8%0A%23%0A%2B%0A%7C)
[Answer]
# Pyth, 19 bytes
```
jP*3,++Jw*-E2wJj*Ew
```
A program that takes newline-separated input on STDIN of the corner character, number of horizontal characters, horizontal character, number of vertical characters and the vertical character, and prints the result.
[Try it online](https://pyth.herokuapp.com/?code=jP%2a3%2C%2B%2BJw%2a-E2wJj%2aEw&test_suite=1&test_suite_input=%2B%0A7%0A-%0A2%0A%7C%0A%40%0A7%0A-%0A2%0A%7C%0A%2B%0A7%0A%23%0A2%0A%7C%0A%2B%0A8%0A%23%0A3%0A%7C%0A%2B%0A8%0A%23%0A3%0A%40%0A%5E%0A9%0A%21%0A4%0A%24&debug=0&input_size=5)
**How it works**
```
jP*3,++Jw*-E2wJj*Ew Program.
Jw Get the corner character. Store in J
E Get the number of horizontal characters
- 2 -2
* w Get the horizontal character and repeat it that many times
+ Add J at the beginning of that
+ J and at the end
E Get the number of vertical characters
* w Get the vertical character and repeat it that many times
j Join the above on newlines
, Construct a 2-element list from the horizontal and vertical strings
*3 Repeat it 3 times
P Everything except the last element
j Join the above on newlines
Implicitly print
```
[Answer]
# MATLAB, ~~95 92 91 85~~ 81 bytes
MATLAB 'E' function. (edit: doesn't work on Octave)
```
function a=e(n,m,c,h,v);a(1:n)=h;a=[c a c];a(2:m+1,1)=v;a=[a;a;a];a=a(1:3+2*m,:);
```
And ungolfed:
```
function a=e(n,m,c,h,v); %Declare the function
a(1:n)=h; %Initialise return with top line excluding the corners
a=[c a c]; %Then add corner pieces
a(2:m+1,1)=v; %Next add the first vertical part
a=[a;a;a]; %Repeat three times vertically to get an E with a tail
a=a(1:3+2*m,:); %And then lop off the tail
```
The function should be called like:
```
e(5,2,'*','-','|')
```
Which will return:
```
+-----+
|
|
+-----+
|
|
+-----+
```
This can probably be simplified a bit, I'll keep working on it. I don't like having the entire function declaration to get the input, so will see if I can improve that.
---
* Saved 3 bytes by simplifying generation of first line to first make the line without corners and then add the corners as this reduces the number of times indexing is required.
* Another byte saved by starting with the first corner.
* 6 more bytes by replacing `repmat(a,3,1)` call with `[a;a;a]`.
* Saved 4 bytes by using `a` without specific initialisation (it's already declared in the function declaration) - thanks @LuisMendo
[Answer]
## Perl, 40 + 1 (`-n`) = 41 bytes
*Thanks to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) for saving 14 bytes and allowing the program to work with entry greater than 10.*
```
/.$/;$,=$/.<>x<>;say+($`.$&x(<>-2).$`)x3
```
Need `-n` as well as `-E` (or `-M5.010`) to run.
For instance :
```
perl -nE '/.$/;$,=$/.<>x<>;say+($`.$&x(<>-2).$`)x3' <<< '^$
!
4
9'
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~31~~ 29 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Prompts for horizontal-character, width, junction-character, height, vertical-character – in that order.
```
h↓⊃⍪/3/⊂↑(⍞⍴⍨h←⎕),⊂⍞{∊⍺⍵⍺}⎕⍴⍞
```
`⎕⍴⍞` input-horizontal-character and repeat input-width times (**⍵** below)
`⍞{`...`}` input-junction-character which will be **⍺** in the function...
`∊⍺⍵⍺` flatten [[junction],[horizontals],[junction]]
`⊂` encapsulate so it can be part of a list
`(`...`),` prepend...
`h←⎕` input-height
`⍞⍴⍨` input-vertical-character and repeat it that many times
`↑` make the list of strings into a character table
`⊂` encapsulate (so it can be repeated as a whole)
`3/` repeat it three times
```
╻ ╻ ╻
┗━ ┗━ ┗━
```
`⍪/` concatenate the three pieces vertically
```
╻
┣━
┣━
┗━
```
(this encapsulates them too, so we need to...)
`⊃` remove the encapsulation
`h↓` drop the first **h** (rows)
```
┏━
┣━
┗━
```
[TryAPL online!](http://tryapl.org/?a=H%20w%20J%20h%20V%20%u2190%20%27-%27%205%20%27+%27%202%20%27%7C%27%20%u22C4%20h%u2193%u2283%u236A/3/%u2282%u2191%28V%u2374%u2368h%u2190h%29%2C%u2282J%7B%u220A%u237A%u2375%u237A%7Dw%u2374H&run)
[Answer]
## C, 130 bytes
```
#define p putchar
#define E for(o=0;o++<O;p(10))p(S);
#define W for(p(P),D=0;D++<C-2;)p(_);p(P);p(10);
f(C,O,P,S,_,D,o){W E W E W}
```
### Usage:
```
main(){f(7,2,'+','|','-');}
```
**Output**
```
+-----+
|
|
+-----+
|
|
+-----+
```
[Answer]
# C#, 108 bytes
```
(m,n,e,v,h)=>{string x=e+new string(h,m-2)+e+"\n",y=new string(v,n).Replace(v+"",v+"\n");return x+y+x+y+x;};
```
Anonymous function which generates each horizontal and vertical line and builds the final output.
Ungolfed function:
```
(m,n,e,v,h)=>
{
string x = e + new string(h, m - 2) + e + "\n",
y = new string(v, n).Replace(v + "", v + "\n");
return x + y + x + y + x;
};
```
Full program with test cases:
```
using System;
namespace LetterEWithoutE
{
class Program
{
static void Main(string[] args)
{
Func<int,int,char,char,char,string>f= (m,n,e,v,h)=>{string x=e+new string(h,m-2)+e+"\n",y=new string(v,n).Replace(v+"",v+"\n");return x+y+x+y+x;};
Console.WriteLine(f(7,2,'+','|','-'));
Console.WriteLine(f(7,2,'@','|','-'));
Console.WriteLine(f(7,2,'@','|','#'));
Console.WriteLine(f(8,3,'+','|','#'));
Console.WriteLine(f(8,3,'+','@','#'));
Console.WriteLine(f(9,4,'^','$','!'));
}
}
}
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 15 bytes
*Thanks to @muddyfish for a correction*
```
2-Y"yv!iiY"!yyy
```
[Try it online!](http://matl.tryitonline.net/#code=Mi1ZInl2IWlpWSIheXl5&input=NwonLScKJysnCid8Jwoy)
### Explanation
The stack contents after each step are indicated for clarity, using the first example in the challenge.
```
2- % Implicitly input number of repetitions of the char of the horizontal line.
% Subtract 2
% STACK: 5
Y" % Implicitly input char of the horizontal line. Apply run-length decoding
% STACK: '-----' (string)
y % Implicitly input (from below) the char of the corners. Duplicate onto the top
% STACK: '+', '-----', '+'
v! % Concatenate all the stack horizontally. We now have the horizontal line
% including the corners
% STACK: '+-----+'
iiY" % Take two inputs: char of the vertical line and number of repetitions
% STACK: '+-----+', '||'
! % Transpose. This tranforms the string into a vertical char array, which
% gives the vertical line
% STACK: '+-----+', ['|';'|'] (vertical char array)
y % Duplicate from below: this pushes a new copy of the horizontal line
% onto the top of the stack
% STACK: '+-----+', ['|';'|'], '+-----+'
y % Duplicate from below: this pushes a new copy of the vertical line
% onto the top of the stack
% STACK: '+-----+', ['|';'|'], '+-----+', ['|';'|'],
y % Duplicate from below: this pushes a new copy of the horizontal line
% onto the top of the stack
% STACK: '+-----+', ['|';'|'], '+-----+', ['|';'|'], '+-----+'
% Implicitly display
```
[Answer]
# Java 7, ~~205~~ 129 bytes
```
String c(int w,int h,String a,char b,char c){String r=a,n="\n",l="";for(;w-->2;r+=c);r+=a+n;for(;h-->0;l+=b+n);return r+l+r+l+r;}
```
*-76 bytes thanks to an anonymous stranger.
PS: Don't go edit other people's posts next time. If you have something to golf please leave it as a comment, or if it's using a completely different approach you could make your own answer. Still thanks for golfing away all these bytes, though - whoever you are..*
**Ungolfed & test cases:**
[Try it here.](https://ideone.com/VhFOmi)
```
class M {
static String c(int w, int h, String a, char b, char c){
String r = a,
n = "\n",
l = "";
for(; w-- > 2; r += c);
r += a+n;
for( ;h-- > 0; l += b+n);
return r+l+r+l+r;
}
public static void main(String[] a) {
System.out.print(c(7, 2, "+", '|', '-'));
System.out.print(c(9, 4, "?", '¡', '¿'));
}
}
```
**Output:**
```
+-----+
|
|
+-----+
|
|
+-----+
?¿¿¿¿¿¿¿?
¡
¡
¡
¡
?¿¿¿¿¿¿¿?
¡
¡
¡
¡
?¿¿¿¿¿¿¿?
```
[Answer]
# Bash + coreutils, 105 bytes
```
printf -- "$3`printf -- "$4%.0s" $(seq $1)`$3`printf "\n$5%.0s" $(seq $2)`%.0s\n" {1..3}|sed -n 1,$(($2*2+3))p
```
Assuming the file within which this is stored is named `A.sh`, the usage would be:
```
bash A.sh <Horizontal Segment Length w/out Edge Chars> <Vertical Segment Length> '<Left/Right Edge Char>' '<Char Between Edges>' '<Vertical Char>'
```
The `--` are needed, just in case one of the character inputs happens to be a `-`, and `printf` apparently doesn't handle dashes in the beginning of a string very nice without the double-dashes.
## Explanation
Assuming that the input is `5 2 + * |`...
1. `$3`printf -- "$4%.0s" $(seq $1)`$3`printf "\n$5%.0s" $(seq $2)``
Create the first horizontal segment and vertical segment all together. This would result in:
```
+*****+
|
|
```
2. `printf -- "$3`printf -- "$4%.0s" $(seq $1)`$3`printf "\n$5%.0s" $(seq $2)`%.0s\n" {1..3}`
Repeat the previously created part `3` times over. This now results in:
```
+*****+
|
|
+*****+
|
|
+*****+
|
|
```
3. `printf -- "$3`printf -- "$4%.0s" $(seq $1)`$3`printf "\n$5%.0s" $(seq $2)`%.0s\n" {1..3}|sed -n 1,$(($2*2+3))p`
Finally pipe the previous output to `sed` to get rid of the last 2 line segments by only outputting the first `<Vertical Segment Length>*2+3` lines of the `E`. We finally get the `E` we want:
```
+*****+
|
|
+*****+
|
|
+*****+
```
[Answer]
## PowerShell v2+, ~~60~~ 59 bytes
```
param($a,$b,$c,$d,$e)(,($x="$c$($e*($a-2))$c")+,$d*$b)*2;$x
```
Takes input as individual command-line arguments. Constructs the horizontal string, stores that into `$x` for use later, then forms that into an array with the comma-operator `,`. Performs array concatenation (i.e., adding elements to the end) of `$d` formulated into an array of `$b` elements. That, in turn, is formulated into an array of two elements with another comma operator, and is left on the pipeline. Then, the horizontal `$x` is left on the pipeline. Abuses the default formatting of `Write-Output` to put a newline between elements.
### Example
```
PS C:\Tools\Scripts\golfing> .\the-letter-e-without-e.ps1 5 3 "z" "v" "d"
zdddz
v
v
v
zdddz
v
v
v
zdddz
```
[Answer]
# Python 3, 60 bytes
**A Function**
```
def p(a,b,c,d,e):q=c+e*(a-2)+c;return(q+'\n'+(d+'\n')*b)*2+q
```
**Test Case**
```
>>> print(p(8,2,'+','|','#'))
+######+
|
|
+######+
|
|
+######+
```
[Answer]
# Brainf\*ck, 147 bytes
```
,>,>++++++++[<------<------>>-]<<-->>>,>,>,>+++>++>++++++++++<<[-<<<.<<<[->>+>>>.<<<<<]>>[-<<+>>]>.>>>>>.<[-<<<<<<[->+>>.>>>>.<<<<<<<]>[<+>-]]>>>>]
```
Takes input from stdin as first 5 characters entered. The first two are have 48 subtracted from their ASCII code so 0-9 behave as expected. For numbers > 9, add 48 to the number and use the corresponding character. The other three characters are as specified in the challenge.
I'm sure it's not the optimal solution but life is too short to golf brainf\*ck.
With comments:
```
[
Input: number number corner vertical horizontal
Numbers are single digits; add 48 and use the ASCII character corresponding
to the number you want for numbers > 9.
First number is the number of characters across. Second is the number down.
Layout: {first number-2} {second number} {temp} {a} {b} {c}
]
,>,>++++++++[<------<------>>-]<<-->>>,>,>,
now we should have the first five cells with the specified layout
the 6th will hold 3 as a counter and the 7th 2 and the 8th 10 '\n'
>+++>++>++++++++++<<
[ while the 6th cell is not 0
-
<<<. print corner
<<<[->>+>>>.<<<<<] print horizontal characters
>>[-<<+>>] copy temp back to 1st cell
>.>>>>>. print corner and newline
<
[ If the second counter is not zero
-
<<<<<<[->+>>.>>>>.<<<<<<<] print vertical and newline n times
>[<+>-] copy temp back to 2nd cell
]
>>>>
]
```
Example run:
```
sean@SEANSBOX:~/Dropbox/Code/BF$ ./bf E.b
94^$!
^!!!!!!!^
$
$
$
$
^!!!!!!!^
$
$
$
$
^!!!!!!!^
```
[Answer]
## Lua(5.2), 144 bytes
```
k,a,p,q=loadstring,arg,io.write,print l,d=k"for i=3,a[1]do p(a[5])end",k"for i=1,a[2]do q(a[4])end"b=a[3]p(b)l()q(b)d()p(b)l()q(b)d()p(b)l()p(b)
```
[Try it online! (Coding Ground)](https://goo.gl/9NImBc "Try it!")
It should output something like that right now:
```
+@@@@@+
l
l
+@@@@@+
l
l
+@@@@@+
```
Own input: `7 2 + l @`
You can change the input in project->compile options and there change the values, each value as in the example but not separated by commas but by spaces.
[Answer]
# PHP, 97 bytes
```
list(,$w,$h,$c,$v,$r)=$argv;echo$b=str_pad($a=str_pad($c,++$w,$r)."$c\n",--$h*2+$w,"$v\n"),$b,$a;
```
no loop, only builtins.
Run with `php -r '<code>' <parameters>`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
⇩*+Ǐ∇εJǏ∞⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLih6kqK8eP4oiHzrVKx4/iiJ7igYsiLCIiLCI3XG4tXG5AXG58XG4yIl0=)
```
* # Repeat the horizontal character...
⇩ # Horizontal distance - 2 times
+Ǐ # Prepend and append the corner character
∇ε # Push the vertical character repeated by the amount
J # Append that to the line
Ǐ # Append the first line
∞ # Mirror
⁋ # Join by newlines
```
[Answer]
**Racket 124 bytes**
```
(λ(w h a b c)(for((i 3))(display a)(for((i w))(display c))(display a)(when(< i 2)(displayln "")(for((j h))(displayln b)))))
```
More readable form:
```
(define(f w h a b c)
(for((i 3))
(display a)
(for((i w))
(display c))
(display a)
(when(< i 2)
(displayln "")
(for((j h))
(displayln b)))))
```
Testing:
```
(f 7 2 "+" "|" "-" )
+-------+
|
|
+-------+
|
|
+-------+
```
[Answer]
# C++, 121 Bytes
```
#import<string>
#import<iostream>
#define f(w,h,C,W,H){std::string s(w,W),t;s=C+s+C+"\n";for(int i=h;i--;)t=t+H+"\n";std::cout<<s+t+s+t+s;}
```
Ungolfed:
```
#import<string>
#import<iostream>
#define f(w,h,C,W,H){
std::string s(w,W),t; //define two strings, one empty, one with horizontal characters
s = C+s+C+"\n"; //assemble a horizontal bar
for(int i=h;i--;)
t=t+H+"\n"; //assemble a vertical bar
std::cout<<s+t+s+t+s; //print
}
```
In C++ its not allowed to declare functions without type as in C. But macros that behave just like a function are totally possible. Note also that the ungolfed version will not compile until you add a "\" to each but the last line of the macro.
You might save two additional bytes by removing the {}, but then you can't use the macro twice in a row.
Usage:
```
int main() {
f(4,2,'+','-','|')
f(2,1,'@','#','i')
return 0;
}
```
Output:
```
+----+
|
|
+----+
|
|
+----+
@##@
i
@##@
i
@##@
```
[Try it online](http://ideone.com/Huo2Nw)
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 23 bytes
```
riri)N*r2*\r*\@r**a3*\*
```
[Try it online!](http://cjam.tryitonline.net/#code=cmlyaSlOKnIyKlxyKlxAcioqYTMqXCo&input=NSAyICsgfCAt)
The input is is in the given order, but should be space separated instead of using a comma. Some of the difficulty is getting the input the right order for CJam's [join operation `*`](https://sourceforge.net/p/cjam/wiki/Basic%20operators/#4-join); for comparison rearranging the input in could [save 4 bytes](http://cjam.tryitonline.net/#code=cjIqcmlyKiphMypyaSlOKnIqKg&input=KyA1IC0gMiB8).
If the inputs are dubbed `A B C D E` then the program works something like this:
```
ri e# get A as integer
ri)N* e# create B+1 newlines
r2* e# create 2 Cs
\r* e# join newlines with D (hereafter ND)
\@ e# bring A & Cs to the front
r* e# create A Es
* e# join, puts Es between Cs (hereafter CEC)
a3* e# makes 3 copies of CEC strings
\* e# join, puts NDs between CECs
```
[Answer]
## QBIC, 44 bytes
```
::;;;X=A[q,a-2|X=X+C]X=X+A ?X[1,2|[1,b|?B]?X
```
Explanation
```
::;;; Get the input parameters, 2 numbers and 3 strings
X=A[q,a-2|X=X+C]X=X+A Build the horizontal string: The corner string, x-2 times the filler string and another corner
?X Print the horizontal string
[1,2| Do the next thing twice
[1,b|?B]?X Print the right number of vertical strings, then the horizontal string.
```
[Answer]
# PHP, 94 Bytes
```
<?list($v,$h,$p,$d,$r)=$_GET[a];for($h++;$i<=2*$h;)echo$i++%$h?$d:str_pad($p,$v-1,$r).$p,"\n";
```
Input format an array in the same order as the suggested string
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Can't seem to do better than 18 :\
```
5õ_gVÇX÷¸pW²ùUY é
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=NfVfZ1bHWMO3uHBXsvlVWSDp&input=OCAzICIrIiAifCIgIiMi)
```
[W²ùUY é XpV y]ê ê
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=W1ey%2bVVZIOkgWHBWIHld6iDq&input=OCAzICIrIiAifCIgIiMi)
]
|
[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 4: The Bertrand Paradox
The [Bertrand paradox](http://en.wikipedia.org/wiki/Bertrand_paradox_(probability)#Jaynes.27_solution_using_the_.22maximum_ignorance.22_principle) is an interesting problem, which shows how different methods for picking random chords in a circle can yield different distributions of chords, their midpoints and their lengths.
In this challenge you are supposed to generate random chords of the unit circle, using the "right" method, i.e. one which produces a distribution of chords which is invariant under scaling and translation. In the linked Wikipedia article, "Method 2" is such a method.
Here are the exact rules:
* You should take **one positive integer `N`** which specifies how many chords should be returned. The output should be a list of `N` chords, each specified as two points on the unit circle, given by their polar angle in radians.
* Your code should **be able to return at least 220 different values for each of the two angles**. If your available RNG has a smaller range, you must either first build an RNG with a sufficiently large range on top of the built-in one or you must implement your own [suitable RNG](http://meta.codegolf.stackexchange.com/a/1325/8478). [This page](http://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use) may be helpful for that.
* The distribution of chords must be indistinguishable from the one produced by "Method 2" in the linked Wikipedia article. If you implement a different algorithm to choose chords, please include a proof of correctness. Whatever algorithm you choose to implement, it must **theoretically be able to generate any valid chord in the unit circle** (barring limitations of the underlying PRNG or limited-precision data types).
* Your implementation should use and return either **floating-point numbers (at least 32 bits wide)** or **fixed-point numbers (at least 24 bits wide)** and all arithmetic operations should be accurate within at most 16 [ulp](http://en.wikipedia.org/wiki/Unit_in_the_last_place).
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 STDOUT (or closest alternative), function return value or function (out) parameter.
Output may be in any convenient list or string format, as long as the individual numbers are clearly distinguishable and their total number is always even.
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.
## Visualisation
You can use the following snippet to render the generated lines and inspect their distribution. Simply paste a list of pairs of angles into the text area. The snippet should be able to handle almost any list format, as long as the numbers are simple decimal numbers (no scientific notation). I recommend you use at least 1000 lines to get a good idea of the distribution. I've also provided some example data for the different methods presented in the article below.
```
function draw() {
document.getElementById("output").innerHTML = svg
}
function drawLines() {
lines = document.getElementById("lines").value;
var e = prefix;
//e += '<circle cx="' + offset + '" + cy="' + offset + '" r="' + radius + '" stroke="black" fill="white"/>';
lines = lines.match(/-?(?:\d*\.\d+|\d+\.\d*|\d+(?!\.))/g);
for (i = 0; i < lines.length; i+=2)
{
t1 = parseFloat(lines[i]);
t2 = parseFloat(lines[i+1]);
x1 = Math.cos(t1);
y1 = Math.sin(t1);
x2 = Math.cos(t2);
y2 = Math.sin(t2);
e += '<path stroke="black" stroke-opacity="0.2" d="M ' + (x1 * radius + offset) + ' ' + (y1 * radius + offset) + ' L ' + (x2 * radius + offset) + ' ' + (y2 * radius + offset) + '"/>';
}
e += suffix;
svg = e;
draw();
}
var prefix = '<svg height="450" width="450">',
suffix = "</svg>",
scale = 0.95,
offset = 225,
radius = scale*offset,
svg = "";
```
```
svg {
position: absolute;
}
```
```
Paste line specifications here
<br>
<input id="lines" type="textarea" size="60" oninput='drawLines()' />
<br>
<br>
<div id="output"></div>
```
[*Example data generated with method 1.*](http://pastebin.com/raw.php?i=MuW7XU5j)
[*Example data generated with **method 2.***](http://pastebin.com/raw.php?i=B9Amuxrz)
[*Example data generated with method 3.*](http://pastebin.com/raw.php?i=tqPABmt6)
# 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]
# IA-32 machine code, 54 bytes
Hexdump of the code:
```
68 00 00 00 4f 0f c7 f0 50 db 04 24 58 d8 34 24
f7 d9 78 f1 d9 c0 dc c8 d9 e8 de e1 d9 fa d9 c9
d9 f3 dc c0 d9 eb de ca d8 c1 dd 1a dd 5a 08 83
c2 10 e2 d1 58 c3
```
It uses a (slightly modified) algorithm that Wikipedia described. In pseudo-code:
```
x = rand_uniform(-1, 1)
y = rand_uniform(-1, 1)
output2 = pi * y
output1 = output2 + 2 * acos(x)
```
I use the range `-1...1` because it's easy to make random numbers in this range: the `rdrand` instruction generates an integer between `-2^31` and `2^31-1`, which can be easily divided by 2^31.
I should have used the range `0...1` for the other random number (x), which is fed into `acos`; however, the negative part is symmetric with the positive part - negative numbers produce chords whose span is greater than pi radians, but for the purpose of illustrating the Bertrand paradox, it doesn't matter.
Since the 80386 (or x87) instruction set doesn't have a dedicated `acos` instruction, I had to express the calculation using only the `atan` instruction:
```
acos(x) = atan(sqrt(1-x^2)/x)
```
Here is the source code that generates the machine code above:
```
__declspec(naked) void __fastcall doit1(int n, std::pair<double, double>* output)
{
_asm {
push 0x4f000000; // [esp] = float representation of 2^32
myloop:
rdrand eax; // generate a random number, -2^31...2^31-1
push eax; // convert it
fild dword ptr [esp]; // to floating-point
pop eax; // restore esp
fdiv dword ptr [esp]; // convert to range -1...1
neg ecx;
js myloop; // do the above 2 times
// FPU stack contents: // x | y
fld st(0); // x | x | y
fmul st(0), st; // x^2 | x | y
fld1; // 1 | x^2 | x | y
fsubrp st(1), st; // 1-x^2 | x | y
fsqrt; // sqrt(1-x^2) | x | y
fxch; // x | sqrt(1-x^2) | y
fpatan; // acos(x) | y
fadd st, st(0); // 2*acos(x) | y
fldpi; // pi | 2*acos(x) | y
fmulp st(2), st; // 2*acos(x) | pi*y
fadd st, st(1); // output1 | output2
fstp qword ptr [edx]; // store the numbers
fstp qword ptr [edx + 8];
add edx, 16; // advance the output pointer
loop myloop; // loop
pop eax; // restore stack pointer
ret; // return
}
}
```
To generate two random numbers, the code uses a nested loop. To organize the loop, the code takes advantage of the `ecx` register (outer loop counter) being positive. It temporarily negates `ecx`, and then does it again to restore the original value. The `js` instruction repeats the loop when `ecx` is negative (this happens exactly once).
[Answer]
# Pyth, 25 23 22 bytes
A port of rcrmn's C++11 answer. This is my first usage of Pyth, and I've had plenty of fun!
```
VQJ,*y.n0O0.tOZ4,sJ-FJ
```
23-byte version:
```
VQJ*y.n0O0K.tOZ4+JK-JKd
```
Cut a byte by changing the program to use folds+sums and setting J to a tuple, removing K.
Original:
```
VQJ**2.n0O0K.tO0 4+JK-JKd
```
Cut off 2 bytes thanks to @orlp.
Explanation:
```
VQ loop as many times as the input number
J, set J to the following tuple expression
*y.n0O0 2 * .n0 (pi) * O0 (a random number between 0 and 1)
.tOZ4 .tOZ 4 (acos of OZ (a random number))
,sJ-FJ print the sum of J and folding J using subtraction in parenthesis, separated by a comma, followed by another newline
```
[Answer]
# Julia, 48 bytes
```
n->(x=2π*rand(n);y=acos(rand(n));hcat(x+y,x-y))
```
This uses the method 2 algorithm, like most of the answers thus far. It creates a lambda function that takes an integer input and returns an n x 2 array. To call it, give it a name, e.g. `f=n->...`.
Ungolfed + explanation:
```
function f(n::Int64)
# The rand() function returns uniform random numbers using
# the Mersenne-Twister algorithm
# Get n random chord angles
x = 2π*rand(n)
# Get n random rotations
y = acos(rand(n))
# Bind into a 2D array
hcat(x+y, x-y)
end
```
I really like how the visualizations look, so I'll include one. It's the result of `f(1000)`.

[Answer]
# Pyth, 22 bytes
A port of the C++ answer. I had another 23 byte solution (Now 22!), but it was almost a copy of @kirbyfan64sos's pyth answer with optimizations, so I had to think outside the box a little and creatively (ab)use the fold operator.
```
m,-Fdsdm,y*.nZOZ.tOZ4Q
```
Note that this doesn't work right now because of a bug in the fold operator after the introduction of `reduce2`. I'm putting in a pull request.
```
m Map
, Tuple of
-Fd Fold subtraction on input
sd Fold addition on input
m Q Map over range input
, Tuple
y Double
* Product
.nZ Pi
OZ [0, 1) RNG
.t 4 Acos
OZ [0, 1) RNG
```
For refence this was my other solution which works in the same way: [`VQKy*.nZOZJ.tOZ4,+KJ-KJ`](http://pyth.herokuapp.com/?code=VQKy*.nZOZJ.tOZ4%2C%2BKJ-KJ&input=1000)
[Answer]
# IDL, 65 bytes
Obviously this is the same algorithm as @rcrmn, even though I derived it independently before reading their answer.
```
read,n
print,[2,2]#randomu(x,n)*!pi+[-1,1]#acos(randomu(x,n))
end
```
IDL's randomu function uses the Mersenne Twister, which has a period of 219937-1.
EDIT: I ran 1000 chords through the visualizer above, here's a screenshot of the result:

[Answer]
# C++11, 214 bytes
```
#include<random>
#include<iostream>
#include<cmath>
int main(){using namespace std;int n;cin>>n;random_device r;uniform_real_distribution<> d;for(;n;--n){float x=2*M_PI*d(r),y=acos(d(r));cout<<x+y<<' '<<x-y<<';';}}
```
So this is a straight out implementation of the *right* algorithm from the wikipedia page. The main problem here in golfing is the oh-so-freaking-long names that the random generator classes have. But, in contrast to good ol' rand, it is at least properly uniform.
Explanation:
```
#include<random>
#include<iostream>
#include<cmath>
int main()
{
using namespace std;
int n;
cin>>n; // Input number
random_device r; // Get a random number generator
uniform_real_distribution<> d; // Get a uniform distribution of
// floats between 0 and 1
for(;n;--n)
{
float x = 2*M_PI*d(r), // x: Chosen radius angle
y = acos(d(r)); // y: Take the distance from the center and
// apply it an inverse cosine, to get the rotation
cout<<x+y<<' '<<x-y<<';'; // Print the two numbers: they are the rotation
// of the radius +/- the rotation extracted from
// the distance to the center
}
}
```
[Answer]
# APL, 46 bytes
```
f←{U←⍵ 2⍴∊{(○2×?0)(¯1○?0)}¨⍳⍵⋄⍉2⍵⍴∊(+/U)(-/U)}
```
My first APL program ever! Surely it can be greatly improved (as my overall understanding of APL is lacking), so any suggestions would be fantastic. This creates a function `f` which takes an integer as input, computes the pairs of chord points using method 2, and prints each pair separated by a newline.
You can [try it online](http://tryapl.org/?a=f%u2190%7BU%u2190%u2375%202%u2374%u220A%7B%28%u25CB2%D7%3F0%29%28%AF1%u25CB%3F0%29%7D%A8%u2373%u2375%u22C4%u23492%u2375%u2374%u220A%28+/U%29%28-/U%29%7D&run)!
Explanation:
```
f←{ ⍝ Create the function f which takes an argument ⍵
⍝ Define U to be an ⍵ x 2 array of pairs, where the first
⍝ item is 2 times a random uniform float (?0) times pi (○)
⍝ and the second is the arccosine (¯1○) of another random
⍝ uniform float.
U ← ⍵ 2 ⍴ ∊{(○2×?0)(¯1○?0)}¨⍳⍵
⍝ Create a 2 x ⍵ array filled with U[;1]+U[;2] (+/U) and
⍝ U[;1]-U[;2] (-/U). Transpose it into an ⍵ x 2 array of
⍝ chord point pairs and return it.
⍉ 2 ⍵ ⍴ ∊(+/U)(-/U)
}
```
Note: My previous 19-byte solution was invalid since it returned (x, y) rather than (x+y, x-y). Sadness abounds.
[Answer]
# Java, 114 bytes
```
n->{for(;n-->0;){double a=2*Math.PI*Math.random(),b=Math.acos(Math.random());System.out.println(a+b+" "+(a-b));}};
```
Basic implementation in java. Use as a lambda expression.
[Example usage](http://ideone.com/r0udta)
[Answer]
# Ruby, 72 bytes
My first golf here! I used the same code as everyone, I hope that's okay
```
gets.chomp.to_i.times{puts"#{x=2*Math::PI*rand},#{x+2*Math.acos(rand)}"}
```
[Answer]
# Java, 115 ~~123~~
This is basically the same as most others, but I need a Java score for this hole, so here it goes:
```
void i(int n){for(double x;n-->0;System.out.println(x+2*Math.acos(Math.random())+" "+x))x=2*Math.PI*Math.random();}
```
1000 sample chords can be found at [pastebin](http://pastebin.com/raw.php?i=rpLyzvhj), here are the first five from one run:
```
8.147304676211474 3.772704020731153
8.201346559916786 3.4066194978900106
4.655131524088468 2.887965593766409
4.710707820868578 3.8493686706403984
3.3839198612642423 1.1604092552846672
```
[Answer]
# CJam, ~~24~~ 22 bytes
Similar to other algorithms, here is a version in CJam.
```
{2P*mr_1dmrmC_++]p}ri*
```
An input of 1000 produces a distribution like:

**How it works**
The algorithm is simply `x = 2 * Pi * rand(); print [x, x + 2 * acos(rand())]`
```
{ }ri* e# Run this loop int(input) times
2P*mr e# x := 2 * Pi * rand()
_ e# copy x
1dmr e# y := rand()
mC e# z := acos(y)
_++ e# o := x + z + z
] e# Wrap x and o in an array
p e# Print the array to STDOUT on a new line
```
*Update*: 2 bytes saved thanks to Martin!
[Try it here](http://cjam.aditsu.net/#code=%7B2P*mr_1dmrmC_%2B%2B%5Dp%7Dri*&input=1000)
[Answer]
# Python 3, ~~144~~ 117 bytes
(thanks to Blckknght for the `lambda` pointer)
Using the same method as others:
```
import math as m;from random import random as r;f=lambda n:[(x,x+2*m.acos(r()))for x in(2*m.pi*r()for _ in range(n))]
```
From the Python documentation:
>
> Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 219937-1.
>
>
>
## Output
```
>>> f(10)
[(4.8142617617843415, 0.3926824824852387), (3.713855302706769, 1.4014527571152318), (3.0705105305032188, 0.7693910749957577), (1.3583477245841715, 0.9120275474824304), (3.8977143863671646, 1.3309852045392736), (0.9047010644291349, 0.6884780437147916), (3.333698164797664, 1.116653229885653), (3.0027328050516493, 0.6695430795843016), (5.258167740541786, 1.1524381034989306), (4.86435124286598, 1.5676690324824722)]
```
And so on.
## Visualization

[Answer]
# Perl, 60
```
#!perl -l
use Math::Trig;print$x=2*pi*rand,$",$x+2*acos rand for 1..<>
```
[Answer]
# R, ~~60~~ ~~56~~ ~~53~~ 49 bytes
An extra 4 bytes thanks to @JayCe and changing it to a function.
Using the same basic formula as the others. R uses the Mersenne-Twister method by default, but others can be set. Outputs a space separated list.
```
function(n,y=acos(runif(n)))runif(n)*2*pi+c(y,-y)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT6fSNjE5v1ijqDQvM00jT1NTE8bSMtIqyNRO1qjU0a3U/J@mYWig@R8A "R – Try It Online")
[Answer]
# SmileBASIC, 62 bytes
```
INPUT N
FOR I=1TO N
X=PI()*2*RNDF()Y=ACOS(RNDF())?X+Y,X-Y
NEXT
```
]
|
[Question]
[
Given an integer n, output the following ASCII art to n rows:
```
1+1=2
1+2=3
2+3=5
3+5=8
5+8=13
```
Essentially, the first row is `1+1=2` and the nth row (1-indexed) is \$f\_n + f\_{n+1} = f\_{n+2}\$ where \$f\$ is the Fibonacci sequence, padded so the numbers line up with the previous row.
You may instead output it infinitely. You may output a list of lines.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
## Testcase
The output for 20 should be:
```
1+1=2
1+2=3
2+3=5
3+5=8
5+8=13
8+13=21
13+21=34
21+34=55
34+55=89
55+89=144
89+144=233
144+233=377
233+377=610
377+610=987
610+987=1597
987+1597=2584
1597+2584=4181
2584+4181=6765
4181+6765=10946
6765+10946=17711
```
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
Outputs the sequence indefinitely.
```
a=b=l=1
while 1:print'%*d+%d='%(l,a,b)+`a+b`;l-=~len(`b`);a,b=b,a+b
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9E2yTbH1pCrPCMzJ1XB0KqgKDOvRF1VK0VbNcVWXVUjRydRJ0lTOyFROynBOkfXti4nNU8jISlB0xoobpukAxT//x8A "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~71~~ 66 bytes
-5 thanks to [Sisyphus](https://codegolf.stackexchange.com/questions/243667/fibonacci-triangle/243680?noredirect=1#comment548748_243680)
```
i,j;main(k){for(;;)printf("%*d+%d%n=%d\n",i,j=k-j,k+=j,&i,j+k+k);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9TJ8s6NzEzTyNbszotv0jD2lqzoCgzryRNQ0lVK0VbNUU1z1Y1JSZPSQeo0jZbN0snW9s2S0cNyNPO1s7WtK79/x8A "C (gcc) – Try It Online")
Outputs indefinitely.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
≔E²¦¹ηFN«I⌊η+≔⟦⌈ηΣη⟧η⟦⪫η=
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7FAw0hHwVBTRyFD05orLb9IQcMzr6C0xK80Nym1SENTU6GaizOgKDOvRMM5sbhEwzczLzO3NFcjQ1MTqB4qo6StBOJAzYz2TayAqtFRCAbTsRDjocqjvfIz8zQydBSUbJU0Y4Hitf//Gxn81y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔E²¦¹η
```
Start with two `1`s.
```
FN«
```
Repeat `n` times.
```
I⌊η
```
Output the first element of the old pair.
```
+
```
Output a `+`.
```
≔⟦⌈ηΣη⟧η
```
Replace the pair with the second element and their sum.
```
⟦⪫η=
```
Output the new pair joined with `=` and move the cursor down.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 30 bytes
```
W P[xi::o'+o+:i'=i+o]x.:sX#i+1
```
Outputs forever. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhb7whUCoisyrazy1bXzta0y1W0ztfNjK_SsiiOUM7UNIYqgamF6AA)
### Explanation
```
W P[xi::o'+o+:i'=i+o]x.:sX#i+1
i is 0, o is 1, x is "", s is " " (implicit)
[ ] Put the following in a list:
x The indent: x
i::o Swap i (the smaller number) with o (the larger number)
and return the new value of i
'+ Plus sign
o+:i Add i to o in-place and return the new value of o
'= Equals sign
i+o Add i and o
P Print the list (concatenating its elements by default)
W Loop while the list is truthy (which is always):
#i Length of i
+1 Plus 1
sX That many spaces
x.: Concatenate with x in-place
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 66 bytes @emanresu A
```
a=b=l=1
while l:=len(x:=f"{a:>{l}}+{b}=%d")-3:a,b=b,a+b;print(x%b)
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9E2yTbH1pCrPCMzJ1Uhx8o2JzVPo8LKNk2pOtHKrjqntla7OqnWVjVFSVPX2CpRJ8k2SSdRO8m6oCgzr0SjQjVJ8/9/AA "Python 3.8 (pre-release) – Try It Online")
### Old [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 67 bytes
```
a=b=l=1
while l:=len(x:=f"{a:>{l}}+{b}"):a,b=b,a+b;print(x+f'={b}')
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9E2yTbH1pCrPCMzJ1Uhx8o2JzVPo8LKNk2pOtHKrjqntla7OqlWSdMqUSfJNkknUTvJuqAoM69Eo0I7Td0WKKWu@f8/AA "Python 3.8 (pre-release) – Try It Online")
Based on @dingledooper's Python 2 answer.
[Answer]
# JavaScript (ES8), 79 bytes
```
f=(n,A=B=1,p)=>n?''.padEnd(p)+A+`+${B}=${B+=A}
`+f(n-1,B-A,(A+"").length-~p):''
```
[Try it online!](https://tio.run/##DcRBCsIwEADAu88oQnbZJFiPwlYS8B8NTVKVsgm2eJH69egc5hneYZ1ej7oZKTG1lhlEO/bc64o8yFUpW0O8SYSK5Gik48fv/I/Y7YeRMojptTdOg6OuQ7skmbe7@Va8KNWmImtZkl3KDBnOJ8T2Aw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
A = B = 1, // A, B = Fibonacci variables
p // p = padding length, initially undefined
) => //
n ? // if n is not equal to 0:
''.padEnd(p) + // append p spaces (none if p is undefined)
A + // followed by A
`+${B}=${B += A}\n` + // followed by "+[B]=[B+A]\n" (A is added to B)
f( // followed by the result of a recursive call:
n - 1, // decrement n
B - A, // update A to the previous value of B
(A + "") // add the length of A coerced to a string + 1
.length - ~p // to p
) // end of recursive call
: // else:
'' // stop the recursion
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~90 87~~ 84 bytes
```
N =1
N N =M + (M =N)
OUTPUT =P =DUPL(' ',X) M '+' N '=' M + N
P @X N '=' :(N)
END
```
[Try it online!](https://tio.run/##JYsxC4AgFAZn/RXf9hRbgqbgQYNt@XqDgnNz5ND/x4qmg@PuvtrRzql3I@DRyoeEAJfA4q3ZS9aSwQqORTdHoKF6JFAgCIgJXy7WKJb6GzO7d10l9v4A "SNOBOL4 (CSNOBOL4) – Try It Online")
Outputs infinitely, but experiences integer overflow after a short while.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+2ÆḞ€DżṖ©;⁾+=Ɗ⁶ṁ$®¦F)Y
```
A full program that accepts an integer and prints the result.
**[Try it online!](https://tio.run/##ATQAy/9qZWxsef//KzLDhuG4nuKCrETFvOG5lsKpO@KBvis9xorigbbhuYEkwq7CpkYpWf///zIw "Jelly – Try It Online")**
### How?
```
+2ÆḞ€DżṖ©;⁾+=Ɗ⁶ṁ$®¦F)Y - Main Link: integer, N
) - for each V in [1..N]:
+2 - V add two
ÆḞ€ - Fibbonacci of each of [1..V+2]
D - to decimal digits -> [[1],[1],[2],...,Digits(Fib(V+2))]
call this FibDigits
Ɗ - last three links as a monad - f(V):
Ṗ - pop -> [1..V-1]
© - (copy this to the register)
⁾+= - ['+', '=']
; - concatenate -> [1,2,3,...,V-1,'+','=']
call this Fillers
ż - FibDigits zip with Fillers
¦ - sparse application...
® - ...to indices: recall from register -> [1..V-1]
$ - ...action: last two links as a monad:
⁶ - space character
ṁ - mould like (e.g. [[1,4,4],12] -> [[' ',' ',' '], ' ']
F - flatten
Y - join with newlines
- implicit print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), [19 bytes](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte)
```
ÞF3l(:n‛+=Y∑꘍,nhL›+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnkYzbCg6buKAmys9WeKIkeqYjSxuaEzigLorIiwiIiwiIl0=)
Outputs infinitely.
```
ÞF3l # Take the infinite list of Fibonacci numbers, and get overlapping groups of 3
( # Looping over that...
Y∑ # Interleave...
n # The tuple of three numbers
‛+= # With '+='
: ꘍ # Pad that with the correct amount of spaces, without popping the padding amount
, # Print that
+ # Add to the padding amount (initially 0)
nhL› # The length of the first number in the tuple, plus one.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 30 bytes
```
ÞFẎ3l⟑‛+=fY∑¥$꘍:\=ḟnḢvL₌t¯-h-£
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw55G4bqOM2zin5HigJsrPWZZ4oiRwqUk6piNOlxcPeG4n27huKJ2TOKCjHTCry1oLcKjIiwiIiwiMjAiXQ==)
A big cursed mess of formatting and registering.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 55 bytes
```
1=1
{`.*\+
$.&$*
=
+
\d+.(\d+)
$&=$&$*_$1$*_
:`_+
$.&
```
[Try it online!](https://tio.run/##K0otycxL/P@fy9DWkKs6QU8rRptLRU9NRUuBy5ZLmysmRVtPA0hocqmo2aoAheNVDIEEl1VCPFjd//8A "Retina 0.8.2 – Try It Online") Tries to output indefinitely but runs out of memory after about 50 seconds on TIO. Explanation:
```
1=1
```
Initialise the buffer with a hypothetical previous line.
```
{`
```
Repeat indefinitely.
```
.*\+
$.&$*
```
Replace up to and including the `+` with spaces. (This only applies after the first loop.)
```
=
+
```
Change the `=` into a `+`.
```
\d+.(\d+)
$&=$&$*_$1$*_
```
Append the sum of the two values in unary.
```
:`_+
$.&
```
Convert the unary to decimal and output the result.
[Answer]
# [Python](https://www.python.org), ~~117~~ ~~107~~ ~~103~~ ~~99~~ 88 bytes
```
p="1=1"
while p:=" "*(a:=1+p.find("+"))+eval("f'{%s=}'"%p[a:].replace("=","+")):print(p)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3IwpslQxtDZW4yjMyc1IVCqxslRSUtDQSrWwNtQv00jLzUjSUtJU0NbVTyxJzNJTS1KtVi21r1ZVUC6ITrWL1ilILchKTUzWUbJV0wOqsCooy80o0CjQh5kOtgVkHAA)
Outputs infinitely.
Can probably be much improved.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÌLÅfü3ε„+=.ιJ¯Oú,yнg>ˆ
```
-1 byte after being inspired by [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/243703/52210)
Outputs the first \$n\$ lines.
[Try it online.](https://tio.run/##ATcAyP9vc2FiaWX//8OMTMOFZsO8M8614oCeKz0uzrlKwq9Pw7osedC9Zz7Lhv//MjD/LS1uby1sYXp5)
Or a minor **22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** alternative:
```
ÌLÅfDü3„+=δ.ιJs€g>.¥ú»
```
[Try it online.](https://tio.run/##ATgAx/9vc2FiaWX//8OMTMOFZkTDvDPigJ4rPc60Ls65SnPigqxnPi7CpcO6wrv//zIw/y0tbm8tbGF6eQ)
And the infinite sequence would be **22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** as well:
```
∞Åfü3vy„+=.ιJ¯Oú,yнg>ˆ
```
[Try it online.](https://tio.run/##ASsA1P9vc2FiaWX//@KInsOFZsO8M3Z54oCeKz0uzrlKwq9Pw7osedC9Zz7Lhv//)
**Explanation:**
```
Ì # Increase the (implicit) input-integer by 2
L # Pop and push a list in the range [1,input+2]
Åf # Get the 0-based n'th Fibonacci value for each of these
ü3 # Pop and push all overlapping triplets of this list
ε # Foreach over the triplets:
# (implicitly push the current triplet)
„+=.ι # Intersperse it with "+" and "=" delimiters
J # Join this list together to a string
¯ # Push the global_array (empty by default)
O # Sum it together
ú # Pad the string with that many leading spaces
, # Pop and output this line with trailing newline
y # Push the pair again
н # Pop and push its first item
g # Pop and push its length
> # Increase it by 1
ˆ # Pop and add it to the global_array
```
[Answer]
# [R](https://www.r-project.org/), 76 bytes
```
l=b=1
repeat{cat(sprintf("%*d+%d=%d
",l,T,b,s<-T+b));l=l+nchar(b)+1;T=b;b=s}
```
[Try it online!](https://tio.run/##BcFBCoAgEADAe88QBG23g2fbX/gBV42CRUS9RW@3mb6WEJPbemklzjfFaUbrT52XUXrPoDPpvCkUDMg4ziMAW@uFBGq6YzdswflA7JnGt9YP "R – Try It Online")
Outputs infinitely.
---
If leading whitespace is allowed:
### [R](https://www.r-project.org/), ~~74~~ 69 bytes
```
b=1
repeat cat(sprintf("%*d+%d=%d
",F<-F+nchar(+T)+1,T,b,b<-T+(T=b)))
```
[Try it online!](https://tio.run/##K/r/P8nWkKsotSA1sUQhObFEo7igKDOvJE1DSVUrRVs1xVY1hUtJx81G1007LzkjsUhDO0RT21AnRCdJJ8lGN0RbI8Q2SVNT8/9/AA "R – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 54 bytes
```
K`1+1=2
"$+"+`(\d+)=(\d+)$
$&¶$.%`* $1+$2=$.(*_$2*
A`$
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zvBUNvQ1ohLSUVbSTtBIyZFW9MWTKpwqagd2qaip5qgpaBiqK1iZKuip6EVr2KkxeWYoPL/v5EBAA "Retina – Try It Online") No test suite because of the way the program uses history. Explanation:
```
K`1+1=2
```
Replace the input with the first line of the output.
```
"$+"+`
```
Repeat `n` times.
```
(\d+)=(\d+)$
```
Match `fₙ=fₙ₊₁` from the previous line.
```
$&¶$.%`* $1+$2=$.(*_$2*
```
Append `fₙ+fₙ₊₁=` plus their sum, with the correct amount of indent.
```
A`$
```
Since the program started with one line and appended `n` lines, it now has one line too many, so delete the last line.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~139~~ . . . ~~104~~ 103 bytes
```
_()($[a=b=1];for n in `seq $1`;{ printf "%${s}s";echo -n $a+$b;$[c=a+b,s+=~${#a},a=b,b=c];echo "=$c";})
```
[Try it online!](https://tio.run/##JczBCoMwDADQXwldBko7mLuGfImIJkXRS93MbqX79Srs/ngqttY6Nm2DvbByN9CyH5BgSzDZ/AHsJsrwPrb0XcDdMVsxR3Ncd3gkQPGohH1k8RrM8w/zTUq4qqAchz90jNFRaesIr2c9AQ "Bash – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 89 bytes
```
l!s@[a,b,c]|[x,y,z]<-show<$>s=(l++x++'+':y++'=':z):(' '<$' ':x++l)![b,c,b+c]
f=""![1,1,2]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0ex2CE6USdJJzm2JrpCp1KnKtZGtzgjv9xGxa7YViNHW7tCW1tdW92qEkjZqltVaVppqCuo26gACSugVI6mYjRQs06SdnIsV5qtkpJitKGOoY5R7P/cxMw8BVuF3MQC33iFgtKS4JIinzyFtP8A "Haskell – Try It Online")
`f` is a stream of lines.
*l*`!`*s* formats current line and computes next triplet *s* and leading whitespace *l*
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~49~~ ~~47~~ 45 bytes
```
liX:Y;{[ST*X`_,T)+:T;'+Y:K'=XY+:YN]oK:X;(_}g;
```
[Try it online!](https://tio.run/##S85KzP3/PyczwirSujo6OEQrIiFeJ0RT2yrEWl070spb3TYiUtsq0i8239sqwlojvjbd@v9/Q1MA "CJam – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~102~~ ~~76~~ 72 bytes
```
b;s;f(a){for(a=b=1;s=printf("%*d+%d",s,a,b);a=b-a)printf("=%d\n",b+=a);}
```
[Try it online!](https://tio.run/##NckxDoAgDEDR3VMQEpJWcHBuehOXAsE4iAbciGdHFv/4X1j2EHr3VCmBYEtXAWHPK1W@y5GfBNrM0ZqoXXXiPNLgRfBHNnHL2nnLgvT2MdUpRwZUbVKjBEjT2z8 "C (gcc) – Try It Online")
*Saved a whopping 26 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
*Saved 3 bytes thanks to [m90](https://codegolf.stackexchange.com/users/104752/m90)!!!*
Outputs *forever*!
[Answer]
# [Julia 1.0](http://julialang.org/), ~~66~~ 65 bytes
```
f(a=1,b=1,n=0)=print(" "^n,"$a+$b=$(a+b)
")f(b,a+b,n-~ndigits(a))
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P00j0dZQJwmI82wNNG0LijLzSjSUFJTi8nSUVBK1VZJsVTQStZM0uZQ00zSSdIBMnTzduryUzPTMkmKNRE1NoAma/wE "Julia 1.0 – Try It Online")
prints infinitely. To avoid `Int64` overflow, replace `a=1` with `a=big(1)` (+5 bytes)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~146~~ 141 bytes
```
print("1+1=2")
a=[1,1,2]
w=2
while 1:print(" "*w+str(a[1])+"+"+str(a[2])+"="+str(a[1]+a[2]));del a[0];w+=len(str(a[0]))+1;a.append(a[0]+a[1])
```
[Try it online!](https://tio.run/##PYzBCsMgEETvfoV40m4oWXur7JeIh4UICYiVVJB8vU1NKXN684YpR11f@dF72bdctUJAssoIJo8TTjaIRla0dUtR4vM3kurW4F13zR6DAXXmIvslUn8HozJuiUmyn4NrQClmffn5VICO71xKzMtoYFz2/gE "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mR`](https://codegolf.meta.stackexchange.com/a/14339/), ~~23~~ 22 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Includes a trailing space on each line of output.
```
"+= "¬ËiMg°UÃvÈùT±XÊì
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=Iis9ICKsy2lNZ7BVw3bI%2bVSxWMrDrA&input=MjA)
```
"+= "¬ËiMg°UÃvÈùT±XÊì :Implicit map of each U in the range [0,input)
"+= "¬ : Split "+= " to an array of characters
Ë : Map
i : Prepend
°U : Prefix increment U
Mg : Get the Uth Fibonacci number, 0-indexed
à : End map
v : Modify the first element
È : By passing it through the following function as X
ù : Left pad with spaces to length
T± : Increment T (initially 0) by
XÊ : Length of X
à : End modification
¬ : Join
:Implicit output joined with newlines
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~228~~ ~~226~~ 225 bytes
Saved 3 bytes thanks to the comment of @ceilingcat
---
Golfed version. [Try it online!](https://tio.run/##LYzBqsIwEEV/ZShdTGws9i0rKbgU1K0LecgkTdtIHYPJQhS/va/Gt5jh3DvMCYZGmqabvlgTYU@OwT6i5TbAxvtXazvokOstR6FS6pE@Seq0v5d650I84af4H/GrGK4UzfAyFCysVHNwIyQ@qwZJakmFFnXdYyLJy0q81z1WspI8U4c/K1E@nT@6OGy5tY/ySj7ZML0bIZ2YVRlAtnCiCFlORa5VbrJ32d3ulsyA/u44jrNvmv4A)
```
object Main extends App{def f(n:Int)={def g(a:Int,b:Int,n:Int):List[(Int,Int,Int)]=n match{case 0=>Nil case _=>(a,b,a+b)::g(b,a+b,n-1)};g(1,1,n)};f(20).zipWithIndex.map{case((a,b,c),i)=>(" "*i)+s"$a+$b=$c"}.foreach(println)}
```
Ungolfed version. [Try it online!](https://tio.run/##hVHBTsMwDL33K56qHhIo1bZjpSFxYxJw2YEDmlCSZjQoS0sboQm0by9um45ymJAS23Ls5/fiVgkruq6S71p5PArjoI9eu6LFXV3jOwLoFHqPfdUchH8wrWeWTI4@fGEb51NMhu94yG99Y9zbDusBAuhbsi9TPxtfblyhj9lBEDyGR0CJVoMxkUKmUDyF4VjfgsWIcQW2ImM4xzXaOBHkEknIiYqH9lM03omokZUTSpmt/mAuH3hdYHumF/ruta11w0Q@1sjg/wVxoK9RZQALcha9gidj57nXQdUos9chOfJ8NnlK00zcYMnP@jArWqag4/iv7E9hw368LojPbFd/fmO14H3XuTSjSAtVspq25S1BnqKu@wE)
```
object Main extends App {
def formatList(list: List[(Int, Int, Int)]): List[String] = {
list.zipWithIndex.map {
case ((a, b, c), i) => (" " * (2 * i)) + s"$a + $b = $c"
}
}
def fibonacciSeq(n: Int): List[(Int, Int, Int)] = {
def fibHelper(a: Int, b: Int, n: Int): List[(Int, Int, Int)] = n match {
case 0 => Nil
case _ => (a, b, a + b) :: fibHelper(b, a + b, n - 1)
}
fibHelper(1, 1, n)
}
val formatted = formatList(fibonacciSeq(20))
formatted.foreach(println)
}
```
]
|
[Question]
[
Consider a non-empty binary matrix **M** and a natural number *n*. For the purposes of this challenge, **M** is said to have blockiness *n* if it can be built using adjacent square blocks of size *n*, where each block has equal entries; and it cannot be formed using square blocks of any larger size. Intuitively, *n* can be thought of as the "pixel size" of the matrix.
**Example 1**: let the values of the matrix be represented as `+` and `o` for clarity.
```
++oo++++
++oo++++
oo++++++
oo++++++
```
has blockiness `2`. Although some entries can be considered to belong to larger blocks, `2` is the maximum block size that is valid for all entries. To be specific, the blocks are shown below, using `·` as separator:
```
++·oo·++·++
++·oo·++·++
···········
oo·++·++·++
oo·++·++·++
```
**Example 2**:
```
+++oo+++
+++oo+++
```
has blockiness `1`. Even if any entry can be seen as belonging to some "sliding" block of size `2`, it is not possible to form the matrix using adjacent blocks of that size.
# The challenge
Given a non-empty binary matrix, output its blockiness.
# Rules
* Any two consistent values can be chosen to define the matrix. Input format is flexible as usual (2D array, list of lists of numbers, flattened array and one or two numbers defining its shape, list of strings, ...).
* Input and output means are [flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) as usual. [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Code golf, shortest wins.
# Test cases
See also "inputs in common formats" at the end.
* Blockiness `1`:
```
+
ooo
+o
++
+++oo+++
+++oo+++
ooo+++
ooo+++
++++++
++oooo
ooooo
ooooo
ooooo
ooooo
```
* Blockiness `2`:
```
oo
oo
++++
++++
++oo++++
++oo++++
++oo++++
++oo++++
oo++++++
oo++++++
```
* Blockiness `3`:
```
++++++ooo
++++++ooo
++++++ooo
ooo+++ooo
ooo+++ooo
ooo+++ooo
+++ooo+++
+++ooo+++
+++ooo+++
```
* Blockiness `4`:
```
++++++++
++++++++
++++++++
++++++++
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
```
**Inputs in common formats**:
* [Numerical matrix, Matlab/Octave](https://tio.run/##bVAxDoAgDPxK4@Dg1M5dHEx8BGFwctHNzfj2WoRAAXMM7V17B5zbdYisw7yPi8hN4BAUHhwBMhBQKLXwkzIBQackYOkYqoYKOK9FY@QPaoiWDXEp2cY1@TkiCjXD0BGm@SWSe5VY7quqkc0Dk8z9thnyxbz3r7Kb04/mj3pe)
* [Character matrix, Matlab/Octave](https://tio.run/##bVAxDoAgDPxK46BRl3bu4mDiIwyDk4vGxc34dixKoIA5hvauvQP25dysnaqmP5phbevR2otgRhAYmAmQgYBcKYXphHFwOnkBY8eQNBTBYe0zRn4hhqhZF@eTdVyWHyI@IWUYCkI1v4R3TxLjfUVVsnqgl7ncVkMmmpf@SXZ2ytHwUfcD)
* [Nested list, Python](https://tio.run/##bVAxDsIwDPyK1YFIqEM8W5U6IDEzQuSBqR2AqRvi7cFuo8Rpqstg39l3Sd7P5RXjtXPBjdMHh9u9G6fTxYGgd4/FkRTcBy05j8xzjF@E4EHAEBA8AQJqKQWfhVGojknwpSOoGiygvLYZe1ohht6yGpeSbdwuP0dsQs0QNIRpDonkXiWW@4pqZPPAJFO7bYa4mLf@VfbutKP5o35/)
* [List of strings, Python](https://tio.run/##bVAxDsIwDPyK1QGrwGDPFhIDEm@gUQamdgCxdEGItweHRonTVM7gu7Pvkjzv8yOEa4cOz@Pw5p5Ptw4PL0X97oKCgEccZvRGnqYQPgyOQMuDYyABBo6tNn6vTKyocxKoIIEKcCnJa4sxyb/UkCwb41KyjVvl54hFqBmBhjBgk0juVWK5r6pGNg9MsrTbZsgX89a/yl6ddjR/1PcH)
* [Flattened array (row-major order) and shape (numbers of rows and columns)](https://tio.run/##bVAxDsIwDPyK6YAl1CGeLaQOSLyBRhkYUDMAUxeEeHtwaJo4DboM9p19l@Rxne8hnDu0OExPOl66YdrRbX9CtxLeIwh6HGfsQdjxJfJKeR/Cm8AaEDiwBIaBgGIphTsIExF1SoIpHUPVUAHntcXY8A9iaDQb41Kyjtvk54hFqBmGhlDNXyK5V4nlvqIqWT0wydxuqyFXzFv/Kntz2tH8UZ8v)
* If you think that some common format is missing, leave a comment and I'll try to generate it automatically.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
GCD@@Length/@Split@Join[2#,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9/d2cXBwSc1L70kQ98huCAns8TBKz8zL9pIWUf5fX97rNr/gKLMvJJoZQVdO4W0aOXYWAU1BX0HLoXq6mrj2lodLgUgy0hHAYRgXGMQG8RUADGNkYQhCKIcykVSiEUS1QJ0TUYEzMImDNdjhGG4EcLd5IkhGYgkj@F/THeiKkHxE3b3U0crsh9wBBoOSQwvoUafEY6YIF4eR8TjDH8y5dGFCSRLEuRxhhCehEqxJF5LsSTfUYU4FNbW/gcA "Wolfram Language (Mathematica) – Try It Online")
Take a 2d array of 2's and 3's, or any two values \$a\$, \$b\$ such that \$\{a,b\}\cap\{2a,2b\}=\{\}\$.
Split the array into runs of identical rows and columns, and take the GCD of the lengths of these runs.
Here `` is the postfix operator for matrix transpose.
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
+./@,&I.&(1#.0&,~:,&0)|:
```
[Try it online!](https://tio.run/##tVDBCsIwDL3nK4JCt5Jau@mpMhgIguDJq4gH2RAvObjj8Nfnturm1oEnD01eHi8vSe/VTAc5JhYDVGjQ1m@hcXs87CrSy1SJvRZhNNdGqKdVwsjSVhKK7FEkGrPrjVOb4MlimCvM09JKjCjgIMHzRl9igAgbbeNsgEAOamYeMcRAYxURMdehB55LQ3Incol9d245P0qIByrwOPpYe3w7lXrg0jf41SFhNZrULj@Jhlp38vsOD7nUfdwISVh7U7vvmwTTHdwv@JdCVi8 "J – Try It Online")
Port of [alephalpha's Mathematica answer](https://codegolf.stackexchange.com/a/237032/78410).
```
+./@,&I.&(1#.0&,~:,&0)|: NB. Input: matrix M
& |: NB. For M and its transpose:
0&, NB. M with a zero row prepended
,&0 NB. M with a zero row appended
~: NB. Elementwise unequal of the two
1#. NB. Row-wise sum
I.& NB. Indices; x[i] copies of i
+./@, NB. Concatenate the two results and GCD reduce
```
---
# [J](http://jsoftware.com/), 39 bytes
```
1 i:~0,(2 2$#)\(];.3*/@,@e.0 1+[$1:)"2]
```
[Try it online!](https://tio.run/##tVA9D4IwEN3vV1yQBOphpcWphoTExMnJFYmDgajLDTL715EPBaEkTg69e/f67vNeOdIrMDboYYAhmvqtJO6Oh32l8GaeYeBr1O5CnPxsK6PlOgmSXIaoKHWVEY7OKgFl/ihjifnlykmMqcGi/vfYi7HOOWtQ2Cia8iEQiFHMzBOGGGiqIiLm2gzAqtKQ3Is6x3Z1bjnbCtAjFVgcfUpbfNuVBtC5b/ArQ0A06dQOP4vG2m7l9x4W6lx/uAkSsLG69uebBfMZPAz4l0BULw "J – Try It Online")
The input format is a matrix of 1's and 2's.
### How it works
```
1 i:~0,(2 2$#)\(];.3*/@,@e.0 1+[$1:)"2] NB. input: matrix M having n rows
(2 2$#)\ NB. 3D block, each layer is 2x2 matrix of i where i <- 1..n
(...)"2] NB. For each layer of above and the entirety of matrix M...
];.3 NB. A: Extract ixi blocks of M, padding with zeros
NB. (when some padding exists, the test always fails)
0 1+[$1: NB. B: 3D block having two layers: ixi of 1's and ixi of 2's
*/@,@e. NB. Test if every 2D cell of A exists as a cell in B
NB. i.e. Test if all ixi blocks of M are valid
1 i:~0, NB. Extract the last 1-based index of 1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~52~~ 42 bytes
```
WS⊞υιI⊟Φ⊕Lυ∧ι›⬤υ⬤λ⁼ν§§υ⁻μ﹪μι⁻ξ﹪ξι∨﹪Lυι﹪Lθι
```
[Try it online!](https://tio.run/##TY5BCoMwEEX3PUWWM2hP4EpKW4SWCj1BMEEDY6Ixab19mlQbOpv/@e/PMN3AbWc4hfAeFEkGjZ68ezqrdA@IrPXLAL5kCqtDG0MHJ744aM0EF0VO2rjQWTlK7aSAm9S9i33EktVagCrZ1UqeajVRupOESnaePacFdAxco4Vc4aexc1faLzBGY4Qnk5zCdHIDawbrBr7sYWFP8xOJ5u6ezph3EKsQisKYIs4hm03@TTi@iH8A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of strings. Explanation:
```
WS⊞υι
```
Input the matrix.
```
I⊟Φ⊕Lυ∧ι
```
Output the largest number from `1` to the height of the matrix...
```
›⬤υ⬤λ⁼ν§§υ⁻μ﹪μι⁻ξ﹪ξ
```
... for which each character equals that at the top left corner of its aligned submatrix ...
```
ι∨﹪Lυι﹪Lθι
```
... and which divides both its height and width.
[Answer]
# [J](http://jsoftware.com/), 57 51 50 48 44 43 39 bytes
```
<:@]^:(0 e.[:,[:="1[,;.3~2 2$])^:_<./@$
```
[Try it online!](https://tio.run/##tVA9D4JADN37KxpCgpfiyYfTwSUkJk5OrgQcDMS4dJDZv458KMgdiZPDta8vr6/t3VtHejVqhR76GKDq3lbi4Xw6tqnKilJtAqxkrvxcaSfM/UTGzwgjtxCluqRyl7mtgKZ6NFpidb1xpjFXWGNIHnsai0ReIoAQe0nvHwCBWNTMbDDEQKaKiJi7MAPLpSd5Eo2JbXceODsKiBYqsDj6WFv8MJVmMKZv8KtDQGxMGpZfRUvtePL7DguNafo4AwnYW1On71sF6x08L/iXQrQv "J – Try It Online")
*-4 thanks to Bubbler's idea of using 1-2 encoding to capitalize on automatic 0-padding*
Input is 1-2 matrix.
* `<./@$` - Starting with the smaller dimension of the input (call it `d`)...
* `<:@]` - Decrement `d` while...
* `^:...^:_` - Stuff (elaborated below) that checks if, when we tile the input with `d x d` tiles, any one of them is non-homogeneous:
+ `0 e.` Is 0 an element of...
+ `[:,` The flatten of...
+ `[:="1` The catalog of... (the catalog of a list is all ones only for a homogeneous list)
+ `[,;.3~2 2$]` Each `d x d` tile flattened. Partial tiles are 0 padded, and thus guaranteed to be non-homogeneous.
[Answer]
# [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/doc/1.21/), 92 bytes
```
from numpy import*
f=lambda m,k=1:k<len(m)and f(m,k+1)or all(m==kron(m[::k,::k],eye(k)<2))*k
```
[Try it online!](https://tio.run/##1VE9c8MgDN39Kxgh9YDbjYvHdO3SzeeBNvji4/MU3MS/3sV2jsOuL2nHigOk9yQkIdf7kzUvw9CA1ch02vWo1c6C32VNqbj@OHKkc1kWTO6VMFgTbo6owQF7KogFxJXCuiwl2EBWjMk87DoXvcCS7J8J2cnBQ88yFORyapVA79CJ2R7FQWs8bjAH4D0WX1zh1rjOYzJKJq6fwnl0eHs9AFhgyPHzeaiqoq6zqqJ5WJNWhDsPZ3GzxjWykzYzCyRGRw@64Z9aM0@TSDrlfKzfImYsqS/JE9FYwyLv37zm3MsO1khSRfwZuuz7Drb6vVXPj7HE2pjQPWxd949p/RrZeCmZ3n9k6m8 "Python 3 – Try It Online")
Takes a numpy `ndarray`.
`m[::k,::k]` takes every `k`th element of `m` in both dimensions; `eye(k)<2` is a short way to make a `k`-by-`k` matrix with every entry `True` (which is equivalent to 1 here). With these arguments, `kron` expands each element from `m[::k,::k]` to a `k`-by-`k` block. Next, the equality check with `m` produces a matrix of individual Boolean results if the sizes are the same, or `False` if the sizes are different (deprecated); `all` turns this into a single Boolean representing whether the matrices are the same.
[Answer]
# [R](https://www.r-project.org/), ~~104~~ ~~97~~ ~~90~~ 85 bytes
*Edit: -3 bytes thanks to pajonk*
```
f=function(m,b=nrow(m))`if`(identical(m[i<-1:b<2,i,drop=F]%x%diag(b)^0,m),b,f(m,b-1))
```
[Try it online!](https://tio.run/##1VLBisIwEL3vfwgZGCGjVXYXe/ULvIli09plWJNKrejf16RiqUiayp6Wd8rLm5eZlylrdSjSXzb70ymu8zg/m7TiwgiNKjZlcREaYMf5TnC2NxWnyUHoNS/G9K0WE2TMyuIYLzej6yjj5Eco2ErUgApzZzEmgM4LQidVyVdh2Y9XNhUSLQAJp7jySMhKCAlwYuEXOci7tEV7dsWf3mLZKZQvJs92TbsRzgNmQTiTWchkyMwtnDjqFXvjCQUUKO69a8yjgDl50/cwYBfm640PHcK82cJjtnlPI4R/wvDgunP9Ex7saNRsd30D "R – Try It Online")
Recursive function: tests blockiness `b` starting with number of rows of matrix `m`, and recurses decreasing `b` until it finds one that fits.
Blockiness test consists of calculating the kronecker product (`%x%` function in [R](https://www.r-project.org/)) of each `b`-th element of `m`, and a `bxb` matrix of `1`s: the result should be identical to `m` if `b` is the correct blockiness.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
xø«Åγ¿
```
[Try it online!](https://tio.run/##yy9OTMpM/f@/4vCOQ6sPt57bfGj////R0UY6qNAYAmN1hqRMLAA "05AB1E – Try It Online")
Port of [my Mathematica answer](https://codegolf.stackexchange.com/a/237032/78410).
Take a list of lists of 2's and 3's as input.
```
x # Pop a and push a, 2a
ø # Transpose
« # Concatenate
Åγ # Run-length encode
¿ # GCD
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 118 bytes
```
f=->m,z=$.=m.size{x=[]
(0...$.).step(z){|r|y=[]
(0...m[0].size).step(z){|c|y+=[m[r][c]]*z}
x+=[y]*z}
x==m ?z:f[m,z-1]}
```
[Try it online!](https://tio.run/##1VPNCoMwDL73KTx40E1LvQ66PUjIYRNlOxSGbqC1PrurFrX@oNtxFNrk@5J@SUOz961smpSHZxFI7lIuaP6QSVVwQOIxSqlLfZq/kqcn/UplqhwIAQy7YIuPVXnkICBDiBEPsiaF9ktjcS6cizyloKXCCOsGCECEGOiDBXoZM9JGoPeod9vV8p1lqAkyXjCEsJUE2zM8s1NZJ7tv9ykGtGu0pEZ4qGOi/WOY0Z@2MUfsQoYHYtPuN7D5I84638csb2VSW9ii8sXUvkbWrrKm@I8MEoI0ucb3Sgn1dPTv0T/nAw "Ruby – Try It Online")
* Recursively (starting from one dimension length) try block sizes, return first valid value.
* Reconstructs the matrix by taking a value at each block, repeating it z times to form each block. Finally compare with original input.
Tried a [different approach](https://tio.run/##1VPLisMgFN37FV0NSScVsx1w5kNEigmGFrQTagZSH9@e2khTTUM7XRZB7z3nvi8e/6rT0OBh8y1NVkIoodprnkPFBa87Y7XtMaFAQs7q3VaJfc0znRurbP@JFeyO7KDaX8VTHkrWZh9fjWBdxw@5Az1kQvwYW9kKY1IRROlar7Vz3rJ3AwGElJQW/kGFP0EsvVD4u7yql3PhRylQCXILMJmgBYdYCzyKXdGY9rl8dQlgXGOU6gZPdSS5XzQL@dM25khcyDQglHb/AJsPcdb5cyzSFjb1CLur/G5r/0aWQkVbfEeGAkDHb2astO2qIZK64Qw "Ruby – Try It Online") by slicing each block but ended at 125B
```
->m{(1..m.size).select{|z|x=[]
m.each_slice(z){|s|x+=s.transpose.each_slice(z).map(&:flatten)}
x.all?{|b|b==[b[0]]*z*z}}.max}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 108, 104, 97 bytes
-7 by borowing @m90's better control flow
```
f=lambda M,n=1:n<len(M)and f(M,n+1)or all(X==[*sum(zip(*n*[X[::n]]),())]for X in[M,[*zip(*M)]])*n
```
[Try it online!](https://tio.run/##1VPBasMwDL3nK0xOtmeKw25h/oTcA8IHjyYs4KqhcQfrz2eOU4ydhXY7DkMivfdkSRYav9zHGV/nuVfWnN6PhjQCVVXjm@2QNszgkfTUYy8VO1@IsZa2SgGfrid6G0bKkUMLdY1aM0EZ071XtWRAaATwoGiY5zjOrpvcpMqyBKi0LgCk8CdYlf8L/63u3nIWNlgrkyExOirkjj71Vl4mkTLkfG7fI1YsqS/JE9FYQ5b3b6o1d97BFkmqiC8j874fYJvX2/T8HEu8nQk9wrZ1/5jWr5Gdm5Lp/UdG@80owo4QRaD7NJY6RpZ1cn6dSGAO02gHR5kucrwuyHgZ0FEneh/F5m8 "Python 3 – Try It Online")
[Old version](https://tio.run/##1VPBasMwDL3nK0RgYAd3OOwW8Cf4HjA@eDRhAVcNjTfYDv31zHGKsbPQbsdhSKT39CzJQuOnezvjyzz3wprT69GAZCh4g2DwCMZa0gqhqun9RL6GkVRYqVY1DWpNGaFU9@cLtDCgkkxVIUJSzy1iBM/1RLLrAZ8OV9shkZTOrpvcJMqyVKrWulCKM3@CVfs/89/65i1nYYO1MhkS1TGC78Sn3srzRMlDzsf2TbFiSX1JnojGGrK8f4tac@cdbJGkivgyPO/7DrZ5vU3Pj7HE25nQPWxb949p/RrZuSmZ3n9ktN@MIuwICFDdh7HEUVjWzPk1g8A8T6MdHKG6yPGmgPEyoCOO9V5F528 "Python 3 – Try It Online")
Straight-forward approach; tries successively smaller block sizes until a working one is found.
Old, longer but more readable version:
```
f=lambda M,n=0:n and all(X[i::n]==X[::n]for i in range(n)for X in[M,[*zip(*M)]])and n or f(M,~-n%-~len(M))
```
[Try it online!](https://tio.run/##1VPBasMwDL3nK0RgYBd3OOwW8CfkHjA@eDTZDJ4aElPYDv31zE6KsbPQbsdhiKX39CLJQsOnez/jyzz3wuqP15OGhqHgNYLGE2hrSStNXaMSopXh7s8jGDAIo8a3jiANQOsB2TB5@DIDOTRUKRrkCJ7rScOuR3w6Xm2HpKEUYHbd5CZRlqWUlVKFlJz5s1iVv5n/VjcvnMAu1spkSFTHCL4Tn3orzxMlX3I@tm@KFUvqS/JENNaQ5f1b1Jo772CLJFXEl@F533ewzetten6MJd7OhO5h27p/TOvXyM6fkun9R0b5zSiWHQEBsrtoSxyFsGgubN7CPE@DNY5QVeR4XcAwGnTEsd6r6PwN "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), ~~101 92 90~~ 89 bytes
*Saved 4 bytes thanks to @Neil, and ~~7~~ 8 more bytes from there*
```
m=>m.reduce(o=>++w*m.some(r=>r.some(v=>v-m[y-y%w][x-x++%w],x=0)*++y|x%w,y=0)|y%w?o:w,w=0)
```
[Try it online!](https://tio.run/##1VHLboMwELznK6xIUewAlrm2Mj21P5CjywGBSakwTm3CQ02/nToQIUNR0h4rSzA7s@vZ9b5HVaRjlR1Lr5AJ71LaCRoIrHhyijmUNHCceiewloJDRQM1oIoGlSdY67WbOmSN1ziOAW5DCdo5TntuNrXbmuBs9Cf5ULu1CTrFP06Z4nCb6i0yFlHykuV83xYxJAiXcl@qrDhAhPUxz0q4fi3WCKdSPUfxG9SABuBzBUDOSyAABbyKcqjRo6FiWWiZc5zLA0yhQIb8Qh1jfhiuGCOuOT3yzd81X/8aXc5F7dGgTJixeswgC/l2NOjEqiS95318rRg4qz/LZ2THHia@f8savKcTzBmri/FlyHTuG9zs9WYz3@esaGFDt7h53z@29Wtm4SZre/9RCb8B "JavaScript (Node.js) – Try It Online")
### Commented
```
m => // m[] = input matrix
m.reduce(o => // for each row in m[], using o as an accumulator:
++w * // increment w
m.some(r => // for each row r[] in m[]:
r.some(v => // for each value v in r[]:
v - // compare v with
m[y - y % w] // the top-left corner of the submatrix of
[x - x++ % w], // width w in which we're currently located
// increment x afterwards
x = 0 // start with x = 0
) // end of inner some()
* ++y // increment y
| x % w, // force to fail if w does not divide x
y = 0 // start with y = 0
) // end of outer some()
| y % w // force to fail if w does not divide y
? // if failed:
o // leave o unchanged
: // else:
w, // update it to w
w = 0 // start with o = w = 0
) // end of reduce()
```
[Answer]
# [R](https://www.r-project.org/), ~~143~~ ~~139~~ 132 bytes
Or **[R](https://www.r-project.org/)>=4.1, 118 bytes** by replacing two `function` occurences with `\`s.
```
function(M,k=dim(M))for(n in k:1)if(!any(k%%n,tapply(M,(row(M)-1)%/%n*max(k)+(col(M)-1)%/%n,function(x)sum(table(x)|1)-1)))return(n)
```
[Try it online!](https://tio.run/##1VJBTsMwELzzinKItAtbkYW0AqQ@oTc@YEItWUmcyjgilfr3YAdhWhI3oJ6qucSzM2OPHdPJVScbnVtVa1hTsXpTFawRZW1Az5SeFc@MSsK10DsokkSTFdttuXNaMPWHk84Zk7tE31SihQJvIa/LH5ZCdovvTQVWvJYb971nr0A0G9sYDRo7CZWwRrXg6KuwyCElBySmB3o5nrCbMDHSvcNg5pF@KQLC2nsef3vSA3068B6n9GfKaDmeMQnvXUS8J/oEeE02pok2jnSe8Jyc9ZnZeCZH7zHCoHvfp@kX@Qvzz52/myyH@zOdhcnbOWxxITy6Rtz/nt0n "R – Try It Online")
Bases heavily on the `split` idea from [my answer to *Square chunk my matrix*](https://codegolf.stackexchange.com/a/229851/55372) (although here we have rectangular matices, which are a little trickier).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
SgLR.Δδôøy©δô€`εSDËsgt®Q*}P
```
Inputs as list of strings.
[Try it online](https://tio.run/##yy9OTMpM/f8/ON0nSO/clHNbDm85vKPy0EoQ41HTmoRzW4NdDncXp5ccWheoVRvw/3@0krZ2fr42ECjpIDMhDFRmLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL6P/gdJ8gvXNTIorPbTm85fCOykMrQYxHTWsSzm0NdjncXZxecmhdoFZtwP9anf/R0UraSrE60Ur5@flgWjtfSUdJGyKmra2dnw8kwCJQJlQtRDQfSRrGyIeZlA9m6eCgISrAXJhdMIOgfLDZMDPxioMMgbsAzoSZCnYS3I3obIR/4K7DyoYwkAIDg42wDylIcDKRVecjO4rm3NhYAA).
**Explanation:**
```
S # Convert the (implicit) input-list of strings to a flattened list of
# characters
g # Pop and push its length
L # Pop and push a list in the range [1,length]
R # Reverse it to [length,1]
.Δ # Find the first block-size `y` which is truthy for:
δ # Map over each string in the (implicit) input-list:
ô # Split it into substrings of size `y`
ø # Zip/transpose; swapping rows/columns
δ # Map over each inner list again:
y ô # And split it into blocks of size `y` again
© # Also store block-size `y` in variable `®` (without popping)
€` # Flatten this list of lists of blocks one level down
ε # Map over each `y` by `y` sized block (or smaller, if we couldn't
# divide a row or column into size `y` with builtin `ô`)
S # Convert the current block to a flattened list of characters
D # Duplicate it
Ë # Check if all characters are the same
s # Swap so the list of characters is at the top again
g # Push its length
t # Take the square-root of that
®Q # Check if this is equal to block-size `®`
* # Check if both are truthy
}P # After the map: check if all were truthy
# (after which the found result is output implicitly)
```
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), ~~319~~ 317 bytes
```
mod M is pr LIST{Nat}*(op size to z). ops b n : Nat Nat ~> Nat . var A B M N
W X Y Z :[Nat]. eq b(M,W)= n(M,W s W). ceq n(M,W s N)= n(M,W N)if X A Y B Z :=
M /\ W rem N + z(M)quo W rem N =/= 0 or A + B == 1 and z(X)quo W quo N(z(X)rem W
quo N)== z(X A Y)quo W quo N(z(X A Y)rem W quo N). eq n(M,W s N)= N[owise]. endm
```
To obtain the result, reduce the `b` function with the matrix as a flattened list, and the row length. (Maude has a matrix type, but we're not using it.)
### Example Session
```
Maude> --- Blockiness 1
>
> red b(
> 0,
> 1
> ) .
result NzNat: 1
Maude>
> red b(
> 1 1 1,
> 3
> ) .
result NzNat: 1
Maude>
> red b(
> 0 1
> 0 0,
> 2
> ) .
result NzNat: 1
Maude>
> red b(
> 0 0 0 1 1 0 0 0
> 0 0 0 1 1 0 0 0,
> 8
> ) .
result NzNat: 1
Maude>
> red b(
> 1 1 1 0 0 0
> 1 1 1 0 0 0
> 0 0 0 0 0 0
> 0 0 1 1 1 1,
> 6
> ) .
result NzNat: 1
Maude>
> red b(
> 1 1 1 1 1
> 1 1 1 1 1
> 1 1 1 1 1
> 1 1 1 1 1,
> 5
> ) .
result NzNat: 1
Maude>
>
> --- Blockiness 2
>
> red b(
> 1 1
> 1 1,
> 2
> ) .
result NzNat: 2
Maude>
> red b(
> 0 0 0 0
> 0 0 0 0,
> 4
> ) .
result NzNat: 2
Maude>
> red b(
> 0 0 1 1 0 0 0 0
> 0 0 1 1 0 0 0 0,
> 8
> ) .
result NzNat: 2
Maude>
> red b(
> 0 0 1 1 0 0 0 0
> 0 0 1 1 0 0 0 0
> 1 1 0 0 0 0 0 0
> 1 1 0 0 0 0 0 0,
> 8
> ) .
result NzNat: 2
Maude>
>
> --- Blockiness 3
>
> red b(
> 0 0 0 0 0 0 1 1 1
> 0 0 0 0 0 0 1 1 1
> 0 0 0 0 0 0 1 1 1,
> 9
> ) .
result NzNat: 3
Maude>
> red b(
> 1 1 1 0 0 0 1 1 1
> 1 1 1 0 0 0 1 1 1
> 1 1 1 0 0 0 1 1 1
> 0 0 0 1 1 1 0 0 0
> 0 0 0 1 1 1 0 0 0
> 0 0 0 1 1 1 0 0 0,
> 9
> ) .
result NzNat: 3
Maude>
>
> --- Blockiness 4
>
> red b(
> 0 0 0 0 0 0 0 0
> 0 0 0 0 0 0 0 0
> 0 0 0 0 0 0 0 0
> 0 0 0 0 0 0 0 0,
> 8
> ) .
result NzNat: 4
Maude>
> red b(
> 0 0 0 0 0 0 0 0 1 1 1 1
> 0 0 0 0 0 0 0 0 1 1 1 1
> 0 0 0 0 0 0 0 0 1 1 1 1
> 0 0 0 0 0 0 0 0 1 1 1 1
> 0 0 0 0 0 0 0 0 1 1 1 1
> 0 0 0 0 0 0 0 0 1 1 1 1
> 0 0 0 0 0 0 0 0 1 1 1 1
> 0 0 0 0 0 0 0 0 1 1 1 1,
> 12
> ) .
result NzNat: 4
```
### Ungolfed
```
mod M is
pr LIST{Nat} * (op size to z) .
ops b n : Nat Nat ~> Nat .
var A B M N W X Y Z : [Nat] .
eq b(M, W) = n(M, W s W) .
ceq n(M, W s N) = n(M, W N)
if X A Y B Z := M
/\ W rem N + z(M) quo W rem N =/= 0
or A + B == 1
and z(X) quo W quo N (z(X) rem W quo N)
== z(X A Y) quo W quo N (z(X A Y) rem W quo N) .
eq n(M, W s N) = N [owise] .
endm
```
For a given `N`, we essentially test *every* partition of the input list into five sublists (including ones where `A` and `B` aren't single elements). Then we verify if that partition corresponds to an actual counter-example for `N`. This is very slow — the last case for blockiness 4 takes several minutes to run. But it terminates!
---
Saved 2 bytes by removing two pairs of parentheses. Parentheses don't often cost bytes in Maude because they can often replace a space due to tokenization weirdness, but in this case there were two pairs of parentheses next to each other.
]
|
[Question]
[
## Challenge
Given daily arrival and departure times of every train that reaches a railway station, find the minimum number of platforms required for the railway station so that no train waits.
In other words, find the maximal number of trains simultaneously present in the station.
## Input
* a pair of lists of times: arrivals and departures; the two lists have same length; arrival `i` corresponds to the same train as departure `i`.
* **alternatively**, a list of pairs of times, or any equivalent.
* times are numbers between `0`, included, and `24`, excluded.
* there are no dates, only times: input is the daily schedule and repeats every day.
* the departure time of a train **can** be lower than its arrival time; in that case, the train is understood to arrive on a day and depart on the next day; that train will require a platform before midnight and after midnight.
* if the arrival time is lower than the departure time, the train is understood to arrive and depart on the same day.
* input can be restricted to integers
## Output
* one integer, the minimum required number of platforms.
## Test cases
```
arrivals = [10, 13, 16]
departures = [12, 15, 18]
out = 1
arrivals = [10, 11]
departures = [12, 13]
out = 2
arrivals = [ 1, 3, 7, 9,10,10,19,23]
departures = [11, 4,11,10,11, 2, 2, 2]
out = 5
arrivals = [1, 2]
departures = [2, 3]
out = 2
arrivals = [1, 2]
departures = [3, 2]
out = 2
arrivals = [2, 22]
departures = [5, 6]
out = 2
```
## Rules
* This is code-golf, the shortest code in bytes wins!
## Related challenges
* [Count the timespans](https://codegolf.stackexchange.com/questions/166802/count-the-timespans)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
1ị>×24+)r/€%24ċþF§Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8/9/w4e5uu8PTjUy0NYv0HzWtUTUyOdJ9eJ/boeUPdzb8P9wOFDo66eHOGf//R3NxRkcbGugoGBrF6ihEGxoDWaZglhmQZREbq4OmwBDIMoYJA9mGIFGgLhMQbQ4TsAQyDMDqDWBCIBbECEsow8gYxIAbBRHTUYCZDmSCXWIEZgDFYgE "Jelly – Try It Online")
## How it works
If you expand the times out and lay them out as a visual aid you get something like this (3rd test case as an example):
```
1 2 3 4 5 6 7 8 9 10 11 1 2
3 4 7 8 9 10 11 19 20 21 22 23 0 1 2
9 10 23 0 1 2
10 11
10 11 12 13 14 15 16 17 18 19 20 21 22 23 0 1 2
```
(Note that the `1 2` in the top right is the continuation into the next day)
From this, it's clear that the number of platforms required is equal to the maximum of the number of repeated occurrences of each time. For example, 10 appears in the ranges 5 times in this example (the maximum), so the output is 5. The only problem is with times spanning multiple days, which we fix by adding 24 to those values.
The code works as follows (out of date):
```
1ị>×24+)r/€%24ċþF§Ṁ - Main link, takes a list of pairs of times
) - Over each pair, map:
1ị - Is the first element...
> - ...greater than each element?
- This yields [0, 0] for increasing pairs and [0, 1] for decreasing
×24 - Multiply each one by 24
+ - Add in to the original pair
- This replaces a pair [a, b] with [a, b+24] if b < a
€ - Over each pair, map:
r/ - Convert to a range
%24 - Modulo all values by 24
F - Flatten this list of pairs to get all times a train is at the station
þ - Pair each time up with each range, then, over the pairs:
ċ - Count how many times the time is in that range (either 1 or 0)
§ - Take the sum of all lists, giving the number of times a train is at the station for each time
Ṁ - Take the maximum of these sums
```
[Answer]
# [Python](https://docs.python.org/2/), 62 bytes
```
lambda l:max(sum(a-b^b-h^h-a<1for a,b in l)for h in range(24))
```
[Try it online!](https://tio.run/##dZDhbsIgFIX/8xQ3/oIEl9Gqm814ElcNtXRtRiuhdOpevruojZvtEiCXy3fOPcGefXloor6Q771RdZYrMEmtTrTtaqrm2Tabl9tyrt5EcXCgeAZVA4aFSxlKp5oPTaMFY32uC3Ba5ZQlTvvONaC/lKFOHXdVYztP2VNrTeXpTM7YRqSMkGNZGQ0iIeDdGU9QzlUoajnk2iqHLhprfbJ673UOEjbXCRAC7O4BYpYSxPba@gQyZD4JGMS/K0unPBkBgmHbznikCmqwYV3V@FtTymEmv3X6wQYgxBDPHESMe5WSu@3lJcLuEvdrSg5dsBdkQismdfGgiR40IDjguBcOa476sNY8ikcmiC04ngHAOrquwXX5mOTy9tcC@X9TTPHxL/9HPsweCfBvYDVWyDEtA3tFZfQD "Python 2 – Try It Online")
Golfing [Surculose Sputum's solution](https://codegolf.stackexchange.com/a/210846/20260). The new part is `a-b^b-h^h-a<1` to check whether the time `h` lies in the interval from `a` to `b` taken cyclically, that is, their sorted ordering is a cyclic permutation of `[a,h,b]`. To do this, we check whether an odd number of the differences `a-b`, `b-h`,`h-a` are negative. I first did this with multiplication `(a-b)^(b-h)^(h-a)<1`. But, xor (`^`) lets us do the same and cuts parens with better precedence.
[Answer]
# [R](https://www.r-project.org/), 111 bytes
Brute force - unfortunately TIO can't run it but R 4.0.2 on desktop doesn't have stack issues.
```
{f=pryr::f
`:`=f(a,b,`if`(a<b,a:b,c(a:24,0:b)))
f(a,d,max(sapply(0:24,f(x,sum(mapply(f(u,v,x%in%u:v),a,d))))))}
```
[Try it online!](https://tio.run/##dY7RCoMwDEXf/Yq@DFLIg22dm2X@S6ujINhN6hRl7NtdqrDBZCUJIffcpGHpWvtw9@D7cnm6sgtz0NolRpvSgcUKTeMM2EuFVldYg9Uyw1RXnPMkAlf0doLedl07QxpFBxP2gwe/zRwMOOJ0aG6HQY8cycLX9/qehhpEikwoypzTFSGpO1Ke6cwOEx9E/crIaMcJWYFExihQqhUnKUOqcUi93GLvl5EmSf2R1N4VF60a/ZjlnC9v "R – Try It Online")
Much shorter version with simpler logic:
# [R](https://www.r-project.org/), 72 bytes
```
function(a,d)max(sapply(0:24,function(x)sum(a<=x&x<=d|a>d&(x>=a|x<=d))))
```
[Try it online!](https://tio.run/##dY/RCoMwDEXf9xV9khTyoK1zc1j/JSjCwGqxCh347y514GCykoSk5@bSTpvrae7GyXqzdcvQzM9xAMJWWgrgybn@BelD5XjAIP1igSoTklCZdqW6TSDUhtY4Sj5fT2ggS1FkmrOQyJPi7sp5l/JykmWHRP9iFOxxQ1EiK2OUqPQuZ5Qj13jJvfrEeV9FNSP9B@nzVjTaGb9YFPyxNw "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 73 bytes
```
lambda l:max(sum([a<=h<=b,not b<h<a][a>b]for a,b in l)for h in range(24))
```
[Try it online!](https://tio.run/##dZDhboMgFIX/8xQ3/QUJWaa23WpkL@JMgxWnGSpBXNu9vLu0Nd2qS4BcLt859wRzdlXXhmMp3kctm7yQoONGnmg/NDSViagSkfO2c5AnVSKzVL7lWdlZkDyHugXN/KXypZXth6LhmrGxUCVYJQvKYqvcYFtQX1JTK4/7ujWDo@ypN7p2dCVWLA0yRsixqrWCICbg7BlPkNbWKOo5FMpIiy4Ka3Uy6uBUAQLS6wTwAfb3ABHLCGIHZVwMOTKfBDTi37WhS56MAMGw/aAdUiXV2DC2bt2tKcQ0k98642QD4GMEzxyCCPc2I3fby0uI3Q3u14x0g7cPyII2WNRFkyZ80EDAAce9cNhx1Pu142E0M0FszfH0ANbhdU2um8ckl7e/Fsj/m2KJj375P/J@9kyAfwPbuULMaeHZKyrCHw "Python 2 – Try It Online")
Input: A list of pairs of time.
For each hour in the day, check how many trains are in the station. Then find the max of those.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εD¬‹24*+Ÿ24%}˜D¢à
```
-2 bytes by taking inspiration from the [*@cairdCoinheringaahing*'s Jelly answer](https://codegolf.stackexchange.com/a/210818/52210) for the first part (`D¬‹24*+`), so make sure to upvote him as well.
Input as a list of pairs of times.
[Try it online](https://tio.run/##MzBNTDJM/f//3FaXQ2seNew0MtHSPrrDyES19vQcl0OLDi/4/z862lDH0DBWJ9pYxwRImkM4ljqGBkDK0ADCBdJGIMoSTBkZA6lYAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/c1tdDq151LDTyERL@@gOIxPV2tNzXA4tOrzgv87/6OhoQwMdQ6NYnWhDYx1DUxBtpmNoERuro4AkZahjaAwV0jE0BIoY65gASXMIx1LH0ACkygDCBdJgTZZgysgYSEG1gvk6cJOMwVyorJEOyHIjIx2z2NhYAA).
**Explanation:**
```
ε # Map each pair of the (implicit) input-list to:
D # Duplicate the current pair
¬ # Push the first value of the pair (without popping)
‹ # Check for both whether this value is larger (1 if truthy; 0 if falsey)
24* # Multiply both by 24
+ # Add it to the pair we duplicated (at the same positions)
Ÿ # Pop the pair and push a list of integers in that inclusive range
24% # Take modulo-24 on each value
}˜ # After the map: flatten the list of lists of integers
D # Duplicate the list
¢ # Count how many times each value occurs in the list
à # Pop and push the maximum
# (after which it is output implicitly as result)
```
Uses the legacy version of 05AB1E, where `[2,2]` with builtin `Ÿ` would result in `[2]` (as expected) instead of `[2,2]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
>/×24+Ṫr%24FĠẈṀ
```
A monadic Link accepting a list of lists, `[arrivals, departures]`, which yields the number of platforms.
**[Try it online!](https://tio.run/##y0rNyan8/99O//B0IxPthztXFakambgdWfBwV8fDnQ3/D7c/alrz/380l0J0tKGBjoKhMRCbxXIp6EQbGgGZpkBsERvLpQOVNkRIGUOEFQx1FICaFMyB2BIobADFQLaRMUQ1UIUJSC9UBkgrGMEw1GygYrBaoJgxmpCxDkwVUNIIIgZ0loIZUDAWAA "Jelly – Try It Online")**
### How?
```
>/×24+Ṫr%24FĠẈṀ - Link: [arrivals, departures] = X
/ - reduce by
> - greater than?
×24 - multiply by 24
Ṫ - tail (this actually removes the departures from X and yields them,
leaving [arivals] as our left argument for the rest of the chain.)
+ - add (adds 24 to the departures that should be on the next day)
r - inclusive range (vectorises)
%24 - modulo 24 (change to 24 hour times)
F - flatten (gets a list of all hours trains are demanding to be at the station)
Ġ - group indices by their values
Ẉ - length of each (number of trains at the station at each of the utilised hours)
Ṁ - maximum
```
---
Also 15 as a dyadic Link accepting `arrivals` on the left and `departures` on the right:
```
>×24+⁹r⁸%24FĠẈṀ
```
[Try it online!](https://tio.run/##y0rNyan8/9/u8HQjE@1HjTuLHjXuUDUycTuy4OGujoc7G/4fXq7/qGnN///RXArR0YYGOgqGxkBsFsuloBNtaARkmgKxRWwslw5U2hAhZQwRVjDUUQBqUjAHYkugsAEUA9lGxhDVQBUmIL1QGSCtYATDULOBisFqgWLGaELGOjBVQEkjiBjQWQpmQMFYAA "Jelly – Try It Online")
[Answer]
# x86-16 machine code, ~~40~~ 39 bytes
```
00000000: b217 32db 5156 32f6 ad3a c412 f63a e212 ..2.QV2..:...:..
00000010: f63a d012 f67a 0143 e2ec 3afb 7f02 8afb .:...z.C..:.....
00000020: 5e59 feca 79dc c3 ^Y..y..
```
**Listing:**
```
B2 17 MOV DL, 23 ; loop 23 to 0 hours (h)
HOUR_LOOP:
32 DB XOR BL, BL ; reset max hour
51 PUSH CX ; save array length
56 PUSH SI ; save array pointer
TRAIN_LOOP:
32 F6 XOR DH, DH ; clear negatives counter
AD LODSW ; AL = arrival (a), AH = departure (b)
3A C4 CMP AL, AH ; is a-b negative?
12 F6 ADC DH, DH ; if so, bit-shift 1 into DH
3A E2 CMP AH, DL ; is b-h negative?
12 F6 ADC DH, DH ; if so, bit-shift another 1
3A D0 CMP DL, AL ; is h-a negative?
12 F6 ADC DH, DH ; if so, bit-shift another 1
7A 01 JP NOT_AT_STATION ; was there an odd number of negatives?
43 INC BX ; if so, increment count of trains at station
NOT_AT_STATION:
E2 EC LOOP TRAIN_LOOP ; go to next train
3A FB CMP BH, BL ; BH = max( BL, BH )
7F 02 JG NOT_MORE ; if not highest number of trains, continue
8A FB MOV BH, BL ; BH set to new max
NOT_MORE:
5E POP SI ; restore array
59 POP CX ; restore array length
FE CA DEC DL ; decrement hour
79 DC JNS HOUR_LOOP ; if not past zero hour, keep looping
C3 RET ; return to caller
```
[Try it online!](https://tio.run/##pVZtb9s2EP4c/YpDg6EpwBiRnbcaGAYnzuoEThzE7lagCwJKoi1tMimQVOKs6G/P7kjJkpMV8DADsSzec889vBcy3BixjPLn/UUcv3QyaUX@YJ6l5SuQqtBinq2CjlhZoSUUGu3zoJNwy4OCG9MH6BiLqwt491MCt4Pp9A/5LpjzLH9l@nVwOSZTxyJX0FnkKsphyTMZ0Fc/APzkggNokzH4aoWx4f3OLuhSgk0F8Eg9ChDZIrVARuM8Yp7n7jXmRvwbR/d@O1xvS9zhlrijLXHHW@JOtsSd/ginhQ3qBZ/tldIAgq8YfVGmhREWvxeZwWIbiIR9EkI6GkdoWm4RuUWr1kpMK3F7JaGVxK/kKjFPsINheAo/AzUQcK35M5jsb8GA57gqVoWIrUhISplb51iUJgWNAtHVcGqBTRDMMVbOUbGDL9Uj7j5nFAY94vxtsCZBs7vB5c0U6s@uX52XMraZkm@T5BkF1/TydqONtdq0E5OgmMiJSUhMa2u@dAmVjgbm3mtIxJzTvqyC97T8HvwU@WyoAupsxOkPUhYvCx8Wk0phlTB1spbcolvt9IuD/ykF@Ml@8Cj0yeZgFMMQXC6Ek0LTviGlpZ5slXp/QlQ4qg1GDNrk/SYzrmt1slqnvxKJ4dDkCqtKW5S25UKVOGgq6MNRNvyvPfiKku6ZI/iwbvzquPH1fvEPL@R68hvAcMyg23PdGatSooJUq3KRQvcQUlVqE4wmn@8expPJrff6MrkDOEOvs7Hz8qOzxA4huIPcfp6O4PwLmuvG9R2YC7mwaQOZXr6BFIpOYR04na@jDkcM/7xW12xSLLjNHrHGTns1B@PJcPq7Zx6MsU@QOXvEftjjHxgMRjQVouDallrAXuQzdX59C4h2dnLMDPD9aB3Ad8tgeL4houqUKLMmzeYWQlASCzgctSgJPa4po/30P1JyqfAG0BA2lFSxwZoy3ef/i/IKGeFmMnsYzB6ms8HscnJDg/PEDV09mCEuQSUJyHIZoZOaN0n34S5vMNxZVewqFkcHTIRvKHSxGu85zKjF4eDufNmM2K/qNrmFpvBO/EIRkcR705M0aTgbrVvwjGqKHbjn@3JUdf/Vp2pr15O7izoVuHlI8Salg73ZkxeIQ48FzGQpmvnYDEOt7vQ8UbygJu/v@KZG0eumxrmwSld93ZjrsdgwtydjeEHlG3tUImItlgKzuB6uKzq11zPZ2haDv4Qo8LZRRX1O3V3M6mjY7dLVBI8OoV/8vzHBrr/h6KUP3/wZ9J3BN3dteFHr14JnGlPU6XS@B@46DfvQiZ6tgJBBj0F4wMIuPnosPMLHMQtPHaxbw9DYbWAhC3vO3ntlZ@7pbYevbT16dp3tqLZhtFOyhU7HIYMT9/Mjw1AuXOge5P/RkfcqhuNN9i5Dpm6XHTvjSWt3aET/0Fm7Xtnppi@aMRhCDoKXfwA "Assembly (gcc, x64, Linux) – Try It Online")
As a callable function. Input array as a list of pairs at `SI`, length in `CX` result in `BH`.
**Explanation:**
Loops through 24 hours and checks, for each hour, how many trains will be at the station.
Uses [@xnor's formula](https://codegolf.stackexchange.com/a/210863/84624) to check cyclical time interval -- that is if `a-b`, `b-h` and `h-a` are an odd number of negative results then `h` falls within the interval. Each of these are compared and if negative the carry flag (`CF`) is set and bit-shifted as a `1` or `0` into `DH` to record the number of negative results.
The parity flag (`PF`) is then checked, which is set if the number of `1` bits is even. If odd, a counter is incremented for that hour and then compared to the previous highest counter and the max is updated for the result.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 20 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set"))
Anonymous tacit infix function taking arrivals as left argument and departures as right argument.
```
{≢⍉⊢⌸∊⍵}24|⊣…¨⊢+24×>
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR56JHvZ2PuhY96tnxqKPrUe/WWiOTmkddix81LDu0AiiubWRyeLrd/7RHbRMe9fY96mp@1LvmUe@WQ@uNH7VNfNQ3NTjIGUiGeHgG/zc0UDA0VjA0U0hTMDRSMDRVMLRQwAEe9c5VMOQCaTCEqjZWwAtAGoy4DBWMFcwVLBVAGoHIUsHIGKTdUMEERECMMwJDsAZTLhA3DYgJmI5sA0iDMcgEojQAAA "APL (Dyalog Extended) – Try It Online")
`>` 1 if arrival is after departure
`24×` multiply 24 by that
`⊢+` add the right argument (the departure) to that
`⊢…¨` inclusive range for each arrival-departure pair
`24|` division remainder when divided by 24
`{`…`}` apply the following lambda (`⍵` is the argument, i.e. the list of ranges)
`∊⍵` **ϵ**nlist (flatten) the argument
`⊢⌸` table of indices for each unique hour
`⍉` transpose (so rows, representing how many of each hour there are, become columns)
`≢` count the number of rows (i.e. the maximum number of occurrences of any hour)
[Answer]
# JavaScript (ES6), 75 bytes
Expects a list of pairs of times.
```
a=>(t=24,g=m=>t--?g(a.map(([a,d])=>n+=(t<a)+(t>d)<=(a>d),n=0)|n<m?m:n):m)``
```
[Try it online!](https://tio.run/##fY3LDoIwEEX3fgXLaSikBXxAGPiQhoQGkGhoS6Rx5b9jAdmpqzm5c@bOXT7l1Dxuow20abv5irPEAixGCe1RYWGDoOxBhkqOAELStiJYaB/B5pL4YIuW5AjSDaqRkZfOVakyTTJF6npujJ7M0IWD6eEKQnBGPR5V1BM8dnRc6eToUlWEHP7o3FH8XXIbvjiuMVnmeQ9SB2y9Znu00FaYfiCKF/hRvBnUWz/Pbw "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 42 35 33 bytes
```
[:>./[:+/(([:~:/1#~[,:]+>*[)>:)"0
```
[Try it online!](https://tio.run/##ZYvLCsIwEEX3/YpLhD5MbTKJrw60iIIrceE2diUWceMHCP31mj4WxcLMMJx77rsVWVSjYERIocF@VxlOt8u5dVxmyrFUcey4YUWLxqVcyXLpkpITodskuB4zzD2hG7h0Yo6eVL0gzCKkHsWl8q@Qh2@V@vSeCEL1L8@kA8tQgwQFwfPx@mCDAgRYYAfkIN1PDmNRg3yy7m7H/G@GGZqma/bciwZkB0wjtqDtmGxA@0nH39qvDdof "J – Try It Online")
### High level idea:
1. Represent each range with a 0-1 list, one slot for each hour, a `1` meaning that hour is occupied.
2. Sum the rows.
3. Take the max.
### Example
Take `1 2 23 f 5 4 2`, that is, the ranges:
```
1 5
2 4
23 2
```
We apply `(([:~:/1#~[,:]+>*[)>:)"0` (mostly J mechanics) to create the 0-1 lists:
```
0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
```
Note how the `23 2` range extends as needed to go into the next day. This is accomplished by `]+>*[` which adds to the right arg `]+` the left arg `[` times `*` "1 if the right arg is less than the let" `>`.
Next we do the row-wise sum:
```
0 1 2 2 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
```
And take the max:
```
2
```
### Bonus, 34 byte version using Adam's APL approach
```
[:>./[:#/.~@;([<@-.~&i.1+]+24*>)"0
```
[Try it online!](https://tio.run/##TYvBDoIwEETv/YoJJiIihW1BpQohMeHkyWvjydioF/@AX69bysFkZrJ5s/PxiUwdOoMUO1Qw7ELicruO3ppeltasSjkNp409D4Wc1m9J@T1X9bbPkspnQjwfry8adCBAAwegBVWzWigNB@KmDhkY3yoqLlVYzpwfFUhHTAvWoP3SNKDj34bTsbXwPw "J – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
F⮌θF⊕﹪⁻⊟ηι²⁴⊞υ⁺ικI⌈Eυ№υι
```
[Try it online!](https://tio.run/##JYzLCoMwEEX3/YpZTmAK9QFFXLrqQgjdiougKYbGxCZG@vdpYoc7D@65zLQIN1mhY3xZB/iUh3Re4ocxOI2HmZxcpdnljL2dg7bYKxM8crvhwghU6rJmKc@DXzAQcJ2wIngz1l64U2bHTvgde/FVa1jT3nKssyGRkD/kamMcBigIKoI7QUPF7VRDZTXSUCRSU5rZS3f51zjG66F/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⮌θ
```
Loop through the arrival times in reverse order, as it's easier to process the departure times in reverse order.
```
F⊕﹪⁻⊟ηι²⁴
```
Calculate the time that this train spends at the station...
```
⊞υ⁺ικ
```
... and loop over that to push the start, intermediate and end times to the predefined empty list.
```
I⌈Eυ№υι
```
For each time in the list, count how many times it appears in the list, and output the maximum of those.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 117 bytes
```
\d+
$*11
(1+) (?!\1)
$&24$*
(1+) \1\b
$1
+%`^(1+) 1(1+\1)
$1 $2 1$2
1(1{24})
1
O`1+
(1+)(\s\1\b)*
$#2$*11
O^`\d+
\G\d
```
[Try it online!](https://tio.run/##JY29DsIwDIR3P4URBuVn6bmRUCdGxr6AVQVUBhYGyoZ49pCE5dPpk8/3ur8fz2sptkaSAJBD9OzOO4MnOWqS8FcGu5GA4iEvXaCyH4FFGaJUzUfT1xNozoi952xrTR9I9toH5iW3MbvYWgq4mpETnVqYGANhaLGyPpwqdGT9AQ "Retina 0.8.2 – Try It Online") Takes input as a list of pairs. Explanation:
```
\d+
$*11
```
Convert to unary, but increment all of the numbers as Retina has difficulty working with zero.
```
(1+) (?!\1)
$&24$*
```
Add 24 to all of the departure times that are less than the arrival times.
```
(1+) \1\b
$1
```
If the arrival and departure times are the same then delete one.
```
+%`^(1+) 1(1+\1)
$1 $2 1$2
```
Otherwise repeatedly fill in any times in between.
```
1(1{24})
1
```
Reduce all of the times "modulo 24" (allowing for the increment).
```
O`1+
```
Sort the times.
```
(1+)(\s\1\b)*
$#2$*11
```
Count (in unary) the number of occurrences of each times.
```
O^`\d+
```
Sort in descending order.
```
\G\d
```
Convert the first (i.e. maximum) to decimal.
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn) `-fs`, [~~36~~ ~~34~~ 30 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
ö·ògT£nžú#│ä♦PüâTPF™,åé@⁻BFÏc-
```
[Try it!](https://zippymagician.github.io/Arn?code=OjwoKHs+On0mJlstPjI0IDB+On1dOl98fD0+On19XCk6XzpA&input=W1sxMCAxMl0gWzEzIDE1XSBbMTYgMThdXQpbWzEwIDEyXSBbMTEgMTNdXQpbWzEgMTFdIFszIDRdIFs3IDExXSBbOSAxMF0gWzEwIDExXSBbMTAgMl0gWzE5IDJdIFsyMyAyXV0KW1sxIDNdIFsyIDJdXQ==&flags=ZWZz)
# Explained
Unpacked: `:<(({>:}&&[->24 0~:}]:_||=>:}}\):_:@`
```
:< Sorted in descending order
(
(
{ Block with key of _
_ Implied
> Is greater than
_
:} Last entry
&& Boolean AND
[ Begin array
_
-> Exclusive range
24 Literal twenty-four
0 Literal zero
~ 1-range
_
:}
] End sequence
:_ Flatten
|| Boolean OR
_
=> Inclusive range
_
:}
} End block
\ Map block over...
_ ...Variable initialized to STDIN; implied
) End expression
:_
:@ Group based on frequency
)
First entry
Length
```
[Answer]
# [Scala](https://www.scala-lang.org/), 113 105 bytes
Saved 8 bytes thanks to the comment of @ceilingcat
---
Golfed version. [Try it online!](https://tio.run/##jY89b8IwEIZ3fsVN6CxZKLEpbSMcibFDJ9QJMbiJg1KBE2JXchvy29NLiUAdQLV88n0873uyy/Re99X7h8k8vOrSQtvnpoACdbI2x82L9VueX1KmMAJfgZiz2UHXGEClqOG7rCFns6z6tL7NtDPouGEqdUsVpmGpzMmlZoohVe40lKwb5KEHGHYdaC3qZucSWDWN/tqsfVPa3ZYl8GZLDwraCdCpqev3Fgv8xTCOOMSSYsE4jC1B5QPFE2Pstij@K5A3YQ7k/8jhmahoDMqFvBoQMx8sxym94nzvmIqLnED5L1DecRy2XUn6/uJMdpOu/wE)
```
def f(a:Seq[Int],d:Seq[Int])=(0 to 24).map(x =>(a zip d).count{case(s,e)=>s<=x&x<=e|s>e&(x>=s|x<=e)}).max
```
Ungolfed version. [Try it online!](https://tio.run/##lVA9b4MwEN35FW@KbMmKwKRpGxWkjh06VZ2qDi6QiAoMMq5Em/Db6RlIaKakEod99z7uzk2iCtX31cdnllg8q1xj7wFptkVdKLutTNkwtcGjMer77Unbd4H0b8o3oAPRIAOYD1tBrviyVDVrEcVgCj95jZQvk@qLqHskqsnAGquMFch0ygfakOMhQovFgn50G7DD4YjFruBAMo4jjEWCT1yOzjVuaZTOm9YoaSemzK45Tv1iTa53bvBXnc@T11S1hWbz2gOdBb5AEFKsucBUkpTeUNxxzi@Lg3NheFEkQP1uBe6J7U9BdxnORsRZOesJpVOO3xXm8mRDgvBfgvCKDm6KWUHPtB4Vndd5ff8L)
```
object Main {
def platforms(a: Array[Int], d: Array[Int]): Int = {
(0 to 24).map(x => (a zip d).count { case (start, end) => (start <= x && x <= end) || (start > end && (x >= start || x <= end)) }).max
}
def main(args: Array[String]): Unit = {
println(platforms(Array(10, 13, 16), Array(12, 15, 18)))
println(platforms(Array(10, 11), Array(12, 13)))
println(platforms(Array(1, 3, 7, 9, 10, 10, 19, 23), Array(11, 4, 11, 10, 11, 2, 2, 2)))
println(platforms(Array(1, 2), Array(2, 3)))
println(platforms(Array(1, 2), Array(3, 2)))
println(platforms(Array(2, 22), Array(5, 6)))
}
}
```
]
|
[Question]
[
You're given a rectangular grid of the characters `.` and `#`, like this:
```
..........
..#.......
....#..#..
...#......
..........
```
Your task is to fill the entire axis-aligned bounding box of the `#` with further `#`:
```
..........
..######..
..######..
..######..
..........
```
The axis-aligned bounding box is the smallest rectangle which contains all the `#`.
**Want more? [Try Part II!](https://codegolf.stackexchange.com/q/91517/8478)**
## Rules
You may use any two *distinct* printable ASCII characters (0x20 to 0x7E, inclusive), in place of `#` and `.`. I'll continue referring to them as `#` and `.` for the remainder of the specification though.
Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.
You may assume that the input contains at least one `#` and all lines are the same length.
You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output.
You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins.
## Test Cases
Each test case has input and output next to each other.
```
# #
... ...
#.. #..
... ...
... ...
#.. ###
..# ###
.#. ###
#.. ###
..# ###
..... .....
.#.#. .###.
..... .....
... ...
.#. .#.
... .#.
.#. .#.
... ...
.......... ..........
.......... ..........
....#..... ....#.....
.......... ..........
.......... ..........
.......... ..........
....#..... ...##.....
...#...... ...##.....
.......... ..........
..#....... ..###.....
....#..... ..###.....
...#...... ..###.....
.......... ..........
..#....... ..######..
....#..#.. ..######..
...#...... ..######..
.........# ..########
..#....... ..########
....#..#.. ..########
...#...... ..########
```
[Answer]
# VBA Excel, ~~150 bytes~~ 146 bytes
**Instruction:**
Create a workbook with two blank worksheets: Sheet1 and Sheet2. Set the input in Sheet1 and then put the following code in the Sheet1 code module
```
Sub A:For Each C In UsedRange:If C.Value="#"Then Sheet2.Range(C.Address)="#"
Next:For Each C In Sheet2.UsedRange:Range(C.Address)="#":Next:End Sub
```
**Ungolfed the code:**
```
Sub A()
For Each C In UsedRange
If C.Value = "#" Then Sheet2.Range(C.Address) = "#"
Next
For Each C In Sheet2.UsedRange
Range(C.Address) = "#"
Next
End Sub
```
**Explanation:**
1. Loop through every cell in the used range Sheet1
2. Set the conditional statement to *copy* every cell contains character hashtag (#) in the used range Sheet1 and *paste* it to the cell in Sheet2 with the same address as Sheet1.
3. Loop through once again every cell in the used range Sheet2 to *copy* every cell address in it and then use it to assign character hashtag (#) to the cell in Sheet1 with the same address as the used range Sheet2.
**Example I/O:**
[](https://i.stack.imgur.com/i74m2.png)
[](https://i.stack.imgur.com/oFD5s.png)
**Caveat:** Make sure every cell in Sheet2 always blank every time you run the program.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/), ~~70~~ ~~68~~ ~~69~~ ~~61~~ ~~58~~ ~~60~~ 40 bytes
```
€S`¹gG~}Dg©L*0KŸ<U¹v¼y1åi®FXNå}ë0®×}J}¾ä
```
**Explanation**
```
€S` # split each string in input to a charlist and place separately on stack
¹gG~} # OR the char arrays to produce a single list with 1's in the columns that have 1's and 0 in the rest
Dg L* # multiply by indices (1-indexed)
© # store row length in register
0K # remove 0's (the indices which should not have 1's
Ÿ<U # store a list of the indices that should have 1's in X
¹v } # for each string in input
¼ # increase counter
y1åi ë } # if the row contains at least one 1
®FXNå} # push 1 for indices which should have 1 and else 0
0®× # else push a row of 0's
J # join into a string
¾ä # split the string in rows
```
[Try it online](http://05ab1e.tryitonline.net/#code=4oKsU2DCuWdHfn1EZ8KpTCowS8W4PFXCuXbCvHkxw6Vpwq5GWE7DpX3DqzDCrsOXfUp9wr7DpA&input=WycwMDAwMDAwMDAwJywnMDAxMDAwMDAwMCcsJzAwMTAxMDAxMDAnLCcwMDAxMDAwMDAwJywnMDAwMDAwMDAwMCdd)
[Answer]
# Mathematica, ~~91~~ 70 bytes
*21 bytes saved due to [@MartinEnder](http://ppcg.lol/users/8478).*
```
ReplacePart["."+0#,Tuples[Range@@@MinMax/@(#~Position~"#")]]->"#"]&
```
Anonymous function. Takes a character matrix as input an returns a character matrix as output. The Unicode character is U+F3C7 for `\[Transpose]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~19~~ ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
|/Tr/FṬ|
ỴµZÇZ&ÇY
```
This is a full program. Input and output are strings of **0**'s and **1**'s, delimited by linefeeds.
[Try it online!](http://jelly.tryitonline.net/#code=fC9Uci9G4bmsfArhu7TCtVrDh1omw4dZ&input=&args=MDAwMDAwMDAwMAowMDEwMDAwMDAwCjAwMDAxMDAxMDAKMDAwMTAwMDAwMA) or [verify all test cases](http://jelly.tryitonline.net/#code=fC9Uci9G4bmsfArhu7TCtVrDh1omw4dZCsWT4bmj4oCcwrbCtuKAncOH4oKsauKAnMK2wrbigJ0&input=&args=MQoKMDAwCjEwMAowMDAKCjAwMAoxMDAKMDAxCgowMTAKMTAwCjAwMQoKMDAwMDAKMDEwMTAKMDAwMDAKCjAwMAowMTAKMDAwCjAxMAowMDAKCjAwMDAwMDAwMDAKMDAwMDAwMDAwMAowMDAwMTAwMDAwCjAwMDAwMDAwMDAKCjAwMDAwMDAwMDAKMDAwMDAwMDAwMAowMDAwMTAwMDAwCjAwMDEwMDAwMDAKCjAwMDAwMDAwMDAKMDAxMDAwMDAwMAowMDAwMTAwMDAwCjAwMDEwMDAwMDAKCjAwMDAwMDAwMDAKMDAxMDAwMDAwMAowMDAwMTAwMTAwCjAwMDEwMDAwMDAKCjAwMDAwMDAwMDEKMDAxMDAwMDAwMAowMDAwMTAwMTAwCjAwMDEwMDAwMDA).
### How it works
```
ỴµZÇZ&ÇY Main link. Argument: s (string)
Ỵ Split s at linefeeds into the array A.
µ Begin a new, monadic chain. Argument: A
Z Zip/transpose A.
Ç Apply the helper link to the transpose.
Z Zip/transpose to restore the original order.
Ç Apply the helper link to A.
& Take the bitwise AND of both results.
Y Join, separating by linefeeds.
|/Tr/FṬ| Helper link. Argument: A (array of strings)
|/ Reduce A columnwise by bitwise OR. This casts to integer.
T Truth; yield the indices of 1's.
r/ Reduce by range. This yields an exponentially growing, nested, ragged
array that contains all integers between the lowest and highest index
in the previous result, at least once but possibly multiple times.
F Flatten the result.
Ṭ Untruth; yield an array with 1's at the specified indices.
Multiple occurrences of the same index are ignored.
| Take the bitwise OR of the result and each row of A.
```
[Answer]
## C#, ~~262~~ 251 bytes
```
s=>{int l,t,r,b,i,j,k;l=t=r=b=i=-1;for(;++i<s.Length;){j=s[i].IndexOf('#');if(j>-1){k=s[i].LastIndexOf('#');l=l==-1|j<l?j:l;t=t==-1?i:t;r=k>r?k:r;b=i;}}for(i=t;i<=b;++i)for(j=l;j<=r;){var c=s[i].ToCharArray();c[j++]='#';s[i]=new string(c);}return s;};
```
Will golf it further when I have more time.
It compiles into a `Func<string[], string[]>`.
Formatted version:
```
s =>
{
int l, t, r, b, i, j, k;
l = t = r = b = i = -1;
for (; ++i < s.Length;)
{
j = s[i].IndexOf('#');
if (j > -1)
{
k = s[i].LastIndexOf('#');
l = l == -1 | j < l ? j : l;
t = t == -1 ? i : t;
r = k > r ? k : r;
b = i;
}
}
for (i = t; i <= b; ++i)
for (j = l; j <= r;)
{
var c = s[i].ToCharArray();
c[j++] = '#';
s[i] = new string(c);
}
return s;
};
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 87 bytes
Byte count assumes ISO 8859-1 encoding.
```
Tm`A` `^\GA+¶|(¶A+)+\Z|^(A+?)(?<=(?=\D*^\2Z)\A\D*)|(A+)$(?=\D*\Z(?<!(?<!\3)$\D*))
T`p`L
```
Uses `A` for `.` and `Z` for `#`.
[Try it online!](http://retina.tryitonline.net/#code=VG1gQWAgYF5cR0ErwrZ8KMK2QSspK1xafF4oQSs_KSg_PD0oPz1cRCpeXDJaKVxBXEQqKXwoQSspJCg_PVxEKlxaKD88ISg_PCFcMykkXEQqKSkKVGBwYEw&input=QUFBQUFBQUFBQQpBQVpBQUFaQUFBCkFBQUFaQUFaQUEKQUFBWkFBQUFBQQpBQUFBQUFBQUFB)
[Answer]
# Scala, 317 characters
```
val a=input.split("\n");val e=a.map{s=>(s.indexOf("#"),s.lastIndexOf("#"))}.zipWithIndex.filter(_._1._1!= -1);val b=(e.map{s=>s._1._1}.min,e.map{s=>s._1._2}.max,e.head._2,e.last._2);print((0 to a.length-1).map{y=>(0 to a(y).length-1).map{x=>if(x>=b._1&&x<=b._2&&y>=b._3&&y<=b._4)"#" else "."}.mkString+"\n"}.mkString)
```
More readable version, could probably have golfed it more:
```
val a=input.split("\n")
val e=a.map{s=>
(s.indexOf("#"),s.lastIndexOf("#"))
}.zipWithIndex // Need the indexes for the Y values
.filter(_._1._1!= -1) // Ugly because of tupleception: (actual tuple, index)
val b=(
e.map{s=>s._1._1}.min,
e.map{s=>s._1._2}.max,
e.head._2,
e.last._2)
print(
(0 to a.length-1).map{y=>
(0 to a(y).length-1).map{x=>
if(x>=b._1&&x<=b._2&&y>=b._3&&y<=b._4)"#"
else "."
}.mkString+"\n"
}.mkString
)
```
[Answer]
## JavaScript (ES6), 168 bytes
```
s=>/^#/gm.test(s)?/#$/gm.test(s)?s.replace(/^.*#[^]*#.*$/m,s=>s.replace(/./g,'#'))?f(s.replace(/.$/gm,'')).replace(/$/gm,'.'):f(s.replace(/^./gm,'')).replace(/^/gm,'.')
```
Takes input as a multiline string. Works by recursively stripping leading and trailing `.`s from all lines until at least one line begins and one ends with a `#`, then selects as many lines as possible but starting and finishing on lines containing `#` and changes all the `.`s to `#`. Probably readily golfable.
[Answer]
# R, ~~158~~ 155 bytes
This program takes in input points `.` and hashtags `#`, line by line.
```
v=c();f=which((d=matrix(strsplit(paste0(a<-scan(,""),collapse=""),"")[[1]],nr=sum(a<0),b=T))=="#",a=T);d[min(f[,1]):max(f[,1]),min(f[,2]):max(f[,2])]="#";d
```
**Ungolfed :**
```
a<-scan(,"") #Input
v=c() #Empty vector
f=which((d=(matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=length(a),b=T)))=="#",a=T) #Main work is here !
d[min(f[,1]):max(f[,1]),min(f[,2]):max(f[,2])]="#" #Creates
#the new figure
d #Displays it
```
Here are the details of the third line :
```
paste0(a,collapse="")
#Collapses the input into a single string
strsplit(paste0(a,collapse=""),"")[[1]]
#Split this string character-wise
matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=sum(a<0),b=T)
#Creates and fills (by row) a matrix with number of row the number of line of the input
which((d=(matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=l,b=T)))=="#",a=T)
#Gives the index of the matrix's elements that are "#"
```
[Answer]
## PowerShell v3+, ~~215~~ ~~162~~ ~~148~~ ~~144~~ 139 bytes
```
param($n)$n|%{(((-join(0..($n[0].length-1)|%{$i=$_;+('1'-in(0..($n.length-1)|%{$n[$_][$i]}))}))-replace'(?<=1.*?).(?=.*?1)',1),$_)[0-ge$_]}
```
Takes input as an array of strings `$n`, with `0` instead of `.` and `1` instead of `#`. Then, we loop through `$n`, each iteration testing whether the current string is smaller than `0` (i.e., there's a `1` in it), and if so, output a string. Uses a [pseudo-ternary](https://codegolf.stackexchange.com/a/79895/42963) in place of an `if`/`else` operation.
The string is constructed from loops through the width of the input string. Each iteration, we tack on a `0` or a `1` depending upon if `1` is found somewhere in the corresponding vertical column. For the last test case, for example, this will result in a string like `0011001001`. Requires v3+ for the `-in` operator. That string is paired with a fancy-dancy regex replace to replace any "inner" `0`s with `1`s. Much thanks to [Business Cat](http://chat.stackexchange.com/transcript/message/31904068#31904068) in chat for the assist on that. Our string would be `0011111111` at this point.
Else, output the current (all-zeros) string `$_`.
The resulting strings are left on the pipeline, and output is implicit. The default `Write-Output` for an array of strings is with a newline between each element, so that's visually what happens.
### Examples
```
PS C:\Tools\Scripts\golfing> .\highlight-the-bounding-box-cartesian.ps1 '0000000001','0010000000','0000100100','0001000000'
0011111111
0011111111
0011111111
0011111111
PS C:\Tools\Scripts\golfing> .\highlight-the-bounding-box-cartesian.ps1 '0000000000','0000000000','0000100000','0001000000'
0000000000
0000000000
0001100000
0001100000
```
[Answer]
# Perl, 51 bytes
Includes +2 for `-0p`
Give input on STDIN, off character is `A`, on character is `a`, e.g.:
```
bounding.pl
AAAAAAAAAA
AAaAAAAAAA
AAAAaAAaAA
AAAaAAAAAA
AAAAAAAAAA
^D
```
`bounding.pl`:
```
#!/usr/bin/perl -0p
s%(?=\D*a).+%$a|=$&%eg;s%.*a.*%$a%g;s/a.*a/\L$&/g
```
Same length:
```
#!/usr/bin/perl -0p
s%.+%${a./a/g}|=$&%eg;s%.*a.*%$a1%g;s/a.*a/\L$&/g
```
[Answer]
# Python, ~~219~~ 212 bytes
```
def b(a):j=len(a[0]);g=range;z=g(len(a));h=[i for i in z if'#'in a[i]];w=[i for i,c in[(i,[r[i]for r in a])for i in g(j)]if'#'in c];return[[any((r<h[0],h[-1]<r,c<w[0],w[-1]<c))and'.'or'#'for c in g(j)]for r in z]
```
(Although I think another method may well be shorter)
Takes and returns a list of list of chars.
Test it on [**ideoone**](http://ideone.com/P7GhYV)
[Answer]
# [Perl 6](http://perl6.org/), 62 bytes
```
{.[.grep(/a/,:k).minmax;$_».grep('a',:k).flat.minmax]='a'xx*}
```
An anonymous routine that can be passed an array of arrays of characters (representing the matrix) as argument, and modifies it in-place so that the calling scope has the modified array afterwards.
Uses `a` instead of `#` as the "on" character. The "off" character can be anything, it doesn't care.
[Answer]
# Python 3, 153 bytes
```
r=lambda w:list(zip(*w[::-1]))
f=lambda w,n=4:list(map(''.join,n and(('#'in w[0])and r(r(r(f(r(w),n-1))))or[w[0]]+foo(w[1:],n))or['#'*len(w[0])]*len(w)))
```
Input and output are a list of strings.
## ungolfed
```
r=lambda w:list(zip(*w[::-1])) # rotate grid cw 90 degrees
def f(w,n=4):
if n:
if '#' in w[0]:
u = r(r(r(f(r(w), n-1))))
else:
u = [w[0]] + foo(w[1:], n)
else:
u = ['#'*len(w[0])]*len(w)
return list(map(''.join,u))
```
## theory of operation
The main idea is to remove rows and columns around the outside of the array if they don't have a '#'. Whatever is left should be filled in with '#'s.
It is implemented using a recursive function.
Case 1: row 0 doesn't contain a '#'. Result is row 0 + recursive call on remaining rows.
Case 2: row 0 does contain a '#'. No more rows can be removed. Rotate array cw so that column 0 is now row 0. Then recursively process the rotated array. The result is rotated ccw.
Base case: The array has been rotated 4 times, meaning that all outer rows/columns have been removed if possible. Whatever remains should be filled in with '#'s
[Answer]
# Python 2, 184 bytes
```
def c(i):
m=n=();e,z=enumerate,'for j,r in e(i):\n for k,c in e(r):%s'
exec z%'\n if"#"==c:m+=j,;n+=k,'
exec z%'\n if min(m)<=j<=max(m)<[]>min(n)<=k<=max(n):i[j][k]="#"'
return i
```
Input and output are a list of strings.
[Try it on Ideone](http://ideone.com/BpKCMq) (fork of Jonathan Allan's test page)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 50 bytes
```
L}hbebjuXGhHX@GhHeH\#*yhMJs.e,Lkfq\#@bTUb.zySeMJ.z
```
[Try it online!](http://pyth.herokuapp.com/?code=L%7DhbebjuXGhHX%40GhHeH%5C%23%2ayhMJs.e%2CLkfq%5C%23%40bTUb.zySeMJ.z&input=..........%0A..%23.......%0A....%23..%23..%0A...%23......%0A..........&debug=0)
]
|
[Question]
[
**TLDR:** Sort your input according to a new English alphabet somewhat based on Chinese stroke count methods.
**Background:** In a Chinese glossary/index, finding terms that are contained within the book is different from English because Chinese doesn't have an alphabet like English, instead they are sorted by stroke count. `(一畫 = 1 stroke,二畫 = 2 strokes,三畫 = 3 strokes,四畫 = 4 strokes,and so on)`
An English glossary, having an alphabet, is naturally sorted alphabetically. For this challenge, we flip that idea somewhat to follow the Chinese manner. And we'll follow some Chinese writing rules to help determine stroke order for the alphabet below.
**Counting Strokes:** Take 口 (kou) for example, a simple square. You'd think it is 4 strokes, but it is actually 3. The 1st being the left vertical line. The 2nd being the top horizontal and right vertical in one fluid stroke, forming the corner. And the 3rd being the lower horizontal line, completing the square. This pattern, among others, holds relatively true across Chinese characters. For sake of simplicity though, and for some added diversity in the English Stroke Count Alphabet, there is a somewhat *subjective* choice for stroke counts.
**Defining the NESCA** First, I need to define stroke count for each letter. For sake of simplicity, and somewhat *subjectively*, I'll use the characters as they appear below. If there are any arguments why a letter should have a different stroke count, please make your case, but again in order to promote diversity in stroke counts, I made some personal judgment calls. For example, `W` could arguably be done in 2 strokes, where each stroke makes a `v` shape, but if that was the case for every letter, this new alphabet would essentially resemble the original. Hence my *subjective* choice of stroke counts. (For those that also read/speak Mandarin, 不好意思!)
`A B C D E F G H I J K L M N O P Q R S T U V W X Y Z`
`3 3 1 2 4 3 2 3 3 1 3 2 4 3 1 2 2 3 1 2 1 2 4 2 3 3`
`a b c d e f g h i j k l m n o p q r s t u v w x y z`
`2 2 1 2 2 2 2 2 3 2 3 2 3 2 1 2 2 2 1 2 2 2 4 2 2 3`
Letters with equal stroke counts should retain the original alphabetic order as before. The only tie-breaker should be upper and lower case letters with the same stroke counts. `C and c, O and o, S and s, D and d, etc.` So the English Stroke Order Alphabet is as follows. (If I made an error, please say as much, there are a lot of examples that I might have to adjust)
**The NESCA**
`C J O S U D G L P Q T V X A B F H I K N R Y Z E M W`
`c o s a b d e f g h j l n p q r t u v x y i k m z w`
and more specifically...
`CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw`
`1111111122222222222222222222222222333333333333344444`
**Note 1:** Tiebreakers - If upper and lowercase for the same letter have the same stroke count, uppercase letters take precedence.
* "Cousin" precedes "cousin"
* "father" precedes "Father" (because lowercase f is 2 strokes, while the uppercase is 3)
* "Stop" precedes "soap" (while the o would precede t in stroke count, uppercase S precedes lowercase s)
* KO precedes kO (K precedes k)
* kO precedes ko (O precedes o)
* make precedes When (both have 4 strokes, but m precedes W in the original alphabet)
**Note 2:** Input will never include any numbers, punctuation, or special characters, nor will it be empty.
**Note 3:** I left this challenge in the Sandbox for 2 weeks as a precaution. I'm worried a lot of people will argue against my subjective decisions in defining this alphabet (especially the letter `g`). I merely tried to allow for a very new and very different alphabet, and to add more diversity to Challenges.
**The Challenge** Given a string input containing a sentence, series of words, or a list of words, organize those words according to the NESCA. Output can be either a string, or a list of properly words is a single string of properly organized words, including duplicates should they exist.
**EDIT** At the behest of users, I have changed my examples to be one consistent input/output format. My example formats can be found here, and exact examples can be obviously found in edit history.
* Example Format 1 `"INPUT HERE" / "OUTPUT HERE"`
* Example Format 2 `[INPUT HERE] / [OUTPUT HERE]`
* Example Format 3 `["INPUT", "HERE"] / ["OUTPUT", "HERE"]`
* Any suitable format for your language, as per community standards.
**Input / Output**
`"It was the best of times it was the worst of tImes" / "of of best the the tImes times It it worst was was"`
`"When life gives you lemons make Lemonade" / "gives Lemonade lemons life you make When"`
`"The journey of a thousand miles begins with one step" / "of one step a begins journey The thousand miles with"`
`"English Stroke Count Alphabet" / "Count Stroke Alphabet English"`
`"A man a plan a canal panama" / "canal a a panama plan A man"`
`"Carry on my wayward son" / "Carry on son my wayward"`
`"Close our store and begin destroying every flower green house just lose no people quietly rather than using vexing xrays yesterday it killed Zachs mini wombat" / Same as input` (If you can write a better sentence than above, I'd be much appreciated. I'd gift reputation, but I don't know how)
`"May the Force be with you" / "be the you Force May with"`
`"Im going to make him an offer hE cant refuse" / "cant offer an going him hE refuse to Im make"`
`"jello Jello JellO JEllo jellO JELlo JELlO jEllo JELLO JelLo JeLlo" / "JeLlo JelLo JellO Jello JELLO JELlO JELlo JEllo jellO jello jEllo"` (Annoyed? Me too!)
`"We suffer more often In imagination than IN reality" / "often suffer reality than In IN imagination more We"`
`"Code Golf and Coding Challenges" / "Code Coding Challenges and Golf"`
`"Do or DO not there is no try" / "or DO Do no not there try" is"`
`"Failure the best teacher is" / "best teacher the Failure is"`
`"Can you tell that I am a Star Wars fan" / "Can Star a am fan tell that you I Wars"`
`"enough examples no more words" / "enough examples no more words"`
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 53 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I/O as an array of words. I wasn't able to run *all* the test cases 'cause trying to format the input for them all on my phone got to be infuriating.
```
n`CcJOoSsUabD¸fGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cVM&code=bmBDY0pPb1NzVWFiRLhmR2doakxsblBwUXFyVHR1VnZYeHlBQkZISWlLa05SWVp6RU1tV3c&input=Ikl0IHdhcyB0aGUgYmVzdCBvZiB0aW1lcyBpdCB3YXMgdGhlIHdvcnN0IG9mIHRJbWVzIgotUw) (header splits input strings on spaces)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes
```
“EḂ 2JḶ]{⁵+cUBẋ÷ỌṫƇÆ⁷ɗ"CỵƊ¢Ṁċ’œ?ØẠ¤w)Þ
```
[Try it online!](https://tio.run/##y0rNyan8//9RwxzXhzuaFIy8Hu7YFlv9qHGrdnKo08Nd3Ye3P9zd83Dn6mPth9seNW4/OV3J@eHurce6Di16uLPhSPejhplHJ9sfnvFw14JDS8o1D8/7f7jd@///aKWQjFQlHQWlrPzSorzUShAzPw1EJoKIkoz80uLEvBQQOzczJ7UYxEhKTc/MA7PKM0sywDrywGYUl6QWKMUCAA "Jelly – Try It Online")
[Verify all test cases](https://tio.run/##bVTNbtNAEL7zFFHEBdETL4BKmiKXQA4FVVD1MInX9qbr3bBex7G4pD1QifbGAZAQQogbXEv/bg1U4jGcFwnrmbUdEBd7dzzzzTcz33jEhMiXy8XsY7c4P2zd2yrOf@y9Whyc3h0@e1BcHs/PiquT4uLbzdH89eLg7Pe7dqe4Or15c/2luJj9PF7MPvx6e3/@vrj8fP01uzP/tJwfPbq9OPz@fLncvdVq7bY9015rtTNIypeJWPkasAStKkAjjxl@5f9xzZT@y9crfffWEHonYrI0Ch6gb8gnBJSrFO0sVhINMeyjR6@0gM8qhKeUZKRSLVnepAFioNIEpI8AXBD0gIWcMDNuIoyQiJEYNq5guzIUPMGv20Yryt1RqcRK1sU4ggEzlfc6MZR14rFYuQxBgkCrPcRQBXVAayKMrnFOrcsz0Eg4sfbKVagEGdgqianSeHe1YUnlwbdj0SrnMixvbMIoQyBUxjAy1Iw6XnaGOpfSdKoUUiFVpsYC7y9TzoxAGA12pJoaS/WliUs1YVN3mmrIaYSWC9M@5I0w9rkQDBm/gGFEc@WSk0riAdQNfUxRTkGbSg@d6lbHVmrE@XsxFqccB6NWJRPxmHpF6giohKjrZoPMNAvKfji4kV0phNhaPfTx0HWWUWPpOR97QMuo8rGWXt@F9xxO6Vypn2SXVpRiN1UVGBqSh08egx0vGE5CqXrvPSHiILjJa6UoHyEeKhGsCMSaXWs6EdgZyLDZwQ0kppDBRp8kYFz3iQ9PGmEYXefaBC5S8vjnr2CYHS/VxJNG73Jls41tn6sGQzxkG9dLs20A43dAY/YA6m1gUqUhKoBNIR67tSZ6VQvtT8fHzHt/AA "Jelly – Try It Online")
A monadic link that accepts and returns a list of words.
## Explanation
```
“...’œ?ØẠ¤w)Þ Main monadic link
Þ Sort by
) Map [over each letter in a given word]
w Find index of subsequence in
¤ (
“...’ 3928442642485912187600397757783525135099072511850472479412437675483
œ? rd permutation of
ØẠ the string "ABC...XYZabc...xyz"
¤ )
```
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, ~~104~~ 100 bytes
*@NahuelFouilleul saved 4 bytes*
```
sub t{pop=~y/CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw/A-z/r}say for sort{t($a)cmp t$b}@F
```
[Try it online!](https://tio.run/##Fci3EoIwGADgV/kHBh0QHBi9Ews2sPctQChSEpOAIoePbtTtu49ilhpS8sIFUVNCe@9KG3rzFdnxA3JHPg4mYXSz03xNN3e2F8WxPD8rc2BNZ/EiWW4v19fYyU4PzVRfGms4qiAgDDhhohYtBbW9jIJQ3KZvSXmKcA5pHGAI4xJzqEgBKc5IziFDCQb7b@TjD6Ei/q1UHaOjd3Wpoi8 "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~107~~ ~~101~~ 99 bytes
Saved ~~6~~ 8 bytes (and got below 100!) thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
lambda s:s.sort(key=lambda k:[*map("CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw".find,k)])
```
[Try it online!](https://tio.run/##1ZVbb@M2EIXf8ysGerFduAHaLVAggAukuWydetfbbtq0e3mgrZFEmyK1JBVbG@xvT89QctZBX/raILEZkprLmfPZTRcrZ188FrMPj0bVq1xROAunwfk43nI3G/a2Z@@/qVUzzi7WN0v3NvyhVpc5Fy/LarMw9k3z2yd/G9s/7//ad@c/X/8y179uX//@97vPV6/qu112WmibT7eTj5PHyCEGmtE4m0faqUCxYlphk1xBUdccSH892Dk/nMxxkk2zu4otGV0wlfoedzvXkuHa2UC12jItZK1yzmia3SLAxrXecichFCK6NiibU60Nnl1xqfHcTseKnGUKkRukuLKl0aGit9E7RLxwrY10bppKrTji/ByZLKI1Jr2tlVWGGrzWCqcXynuks1R36KLbKZ9TcFZOjAtMqAeJnGeSQlIJlKN97zptS@J7xuOFcTv2VHpGt1I0GmkhRIpgHTXsGsP0qdUcTUdeQSuP9lBQGyTMPe/lbe9VB40Qnn2uOlF2q43hnN6pdQXJtNXQuF4paewVbojo186vZSa9MlAYZ/OaSicho@uFrnSNDqBrgczVlcgQyXOBWnF9w8Y4unl6XdLNlaw3w3oh@3hd0ibtY71Yys2F3MepjBoTaVP4WuRyRYQYc0u6VhBNRQ2RU8vz10isjI6dqOxyppfOFElf/CdFX1QKXdsyWejSkfN0uYSQUfpFbB1E1eglwLXSpsXeky8jQytUoUMar02ei2hEskeak4IScIvydKd8oELJtNm6tqyI96puxGyIn9qAo3MEOpmc8L7hdcQsBAb4E799vqpPniw/IAFWhIpEg7CBP@ToEThY/sBBokNqTHMSYHBV4g8WR7GD8w9w3KaMz9iQ0Sc1xfwDCQcGaCAE5735ldCQAOihSIQcsxCe8fB/YGHVz0Bk7HEQOAZRktV74yNJj4XgAAp6AAQSACP643ry85O3k//5yPOJggMRXxnpCUp0pPGJ@QccBrMP5k/@P2Yi2eyODyz8C4EkthAicRMIIMK6IxwAQu/2Z/5PHw0DHE8sJNsrQQC2P6JChJsnHv4TC0iw3iIHUBh9aL//8Yf1aEpp9d2L0eSkQJ1xirSWPutmnL5DpnQAaHJ2QvgxeDqehgbajCdppxibfiFfOCManW4wq8Ne47WN42KUPcQvGX37E2UPAYuHoZT3YTbjj19Gk8d/AA "Python 3 – Try It Online")
Inputs a list of strings and sorts them accordingly.
[Answer]
# [R](https://www.r-project.org/), ~~159~~ ~~134~~ 125 bytes
```
icuSetCollate(locale="ASCII");s=scan(,"");s[order(chartr("CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw","A-Za-z",s))]
```
[Try it online!](https://tio.run/##FcbLEoIgFADQX2FY4Yx@QePCLMvKXvYwmxaIt7BICjDTn6fprI6ytmJNCiaUQlADREhGBfg4SMM4xs5A@5rRmrj4/7NUJSjCOFVGERyy2Uqmek@LUQnXyY3fF6JevzZvtTPN4ZN9u2AYTeNq/lhuT3k/Tp7HFrs48HLq9djVjnOxCe2Q4YAiqRigAlBbGY462dgf "R – Try It Online")
Thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) for -7 bytes.
Similar to others, translate the characters in the string using `chartr` into an appropriate `order`, then sort the strings using that `order`.
The default collation order in the R install on TIO, `en_US.UTF8`, is very odd: while, for instance, `e` comes before `E`, `ekF` comes *after* `EgHTk` (those being the translations of "and" and "begin" in the unchanged test case). So I switch to an ASCII locale, which compares by byte value instead.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ΣžnS•f[?θ$Ÿ)*:™ûò0Æì+Ω£µ¥.—g"Ý»θä•.Isk
```
I/O as a list of list of characters.
Port of [*@xigoi*'s Jelly answer](https://codegolf.stackexchange.com/a/215282/52210), so make sure to upvote him/her as well!
[Try it online](https://tio.run/##yy9OTMpM/f//3OKj@/KCHzUsSou2P7dD5egOTS2rRy2LDu8@vMngcNvhNdrnVh5afGjroaV6jxqmpCsdnnto97kdh5cANeh5Fmf//x8dreSppKOgVKIUq6MQrVQOYieCiGKIQAmInQEiUiECSRA2WAVCXz6InYakJRNE5CKpBUtlkmQVWAXY5CKC9nli2BcLAA) or [verify all test cases](https://tio.run/##RZK/btRAEMZ7nmJkaIAook5zivIHOTq44pAiEVHsxWN7L@sds7u@OxdIKRBPQEuThAKJAiGBToqgOCvtPURe5PjWiUJj7@7MfDPfb1e8mmjezJLU1k3YIUoG7dajZNSEfovd@PFmfXnz145vzy/yk8F6@eRm@fTZzu3Hi@66@/mi@9R9f77@trpc/Vp93b49/1wk3ZfV9XrZXaFgO/Vnmw9H3Y/uz9bq92BzkqSB5spTKJkm7ANJTkFX7En/D8zF3UdSRJKt5LhkS0bnTIWeIbeVhgxXYj1V6oxpGNcqY6S@Qf1UGme5jQoKgtJ4ZTOqtEHphAuNsrkOJYll8oFrlB3Ywmhf0jg4geCeNDbQrqlLNeGA@C4aWajVpv@dKqsM1fhWCtE95RzaWapamGjnymXkxcaIEc@EedBIHFMcpB@BMrh30mpbEM8Y5bmROTsqHMNsHBpGGnDoFaxQzVIbpveN5mBacgqoHOxhoMZHmRkv4m/hVAtEkGeXqTaCPdPGcEZv1WkJYtpqIK4mKhp7hYzI/FDcabySOzIAjFhaUSFRMsgd51JXcACuOTqXBxFDIMc5ZkX6lI0ROnr4jujoIK6n9@thPMd3RNP@HOvhKGYOYz6i8aZxI00vX0VckgfASC3pSgGaChqQe8vpazRWRoc2UpaM6aWYvOeLXRx6r1RwbYv@Be0LiaP9EUCG6Bfa2keqwUWBQ6VNg7OHZxkYrDCF9v312v7JBRiJ3QOlpEACr0U5OlbOU67ibbOVpiiJF6qq42ODfm8DDzrzybt/).
**Explanation:**
```
Σ # Sort the (implicit) input-list by:
žn # Push the constant string "ABC...XYZabc...xyz"
S # Convert it to a list of characters
•f[?θ$Ÿ)*:™ûò0Æì+Ω£µ¥.—g"Ý»θä•
"# Push compressed integer 3928442642485912187600397757783525135099072511850472479412437675482
.I # Get the 392...482nd permutation of the character-list
s # Swap to get the current list of characters
k # And get the index of each character in the permutation
# (we sort on those lists of indices)
# (after which the sorted list is output implicitly as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•f[?θ$Ÿ)*:™ûò0Æì+Ω£µ¥.—g"Ý»θä•` is `3928442642485912187600397757783525135099072511850472479412437675482`. (Note that it's 1 lower than the number used in the Jelly answer, because 05AB1E uses 0-based indexing and Jelly uses 1-based indexing instead. [This number is generated with the `œ¿` Jelly builtin](https://tio.run/##DczVDYRAFADA2nB35w87YFlclzauIBIS6nowBQwqMCYAz/@@AIDJZKN3Zi9J2bz4CWWFVNyZgzVO7rL6W3gQiuZFqVYa3Y7ik9PaYAeKZliOF0RJVlRNN0zLdlzPD8IoTtLsa8qqRg1uu34Yp3lZt/0g5ws).)
[Answer]
# JavaScript (ES6), 119 bytes
```
a=>a.sort((a,b)=>(g=s=>[...s].map(c=>"CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw".search(c)+10))(a)>g(b)||-1)
```
[Try it online!](https://tio.run/##RZLBUtswEIbvPMVOLthT8JRzJ5lJQ6ChgbSFlhaGw8Ze2wqy1khyEnd493RlG3qRZe3q3/0/7Qa36FKran9qOKNDPj7geIKJY@ujCE/W8XgSFWM3njwmSeKekgrrKB1PRrP0asW37ieuzzPKL4tys9TmW/39xd755tf2976dfr74slBfn29@/Hn4O7@u7nejxBHatIzS@MPZxziOMJ4U0Tp@fT09iw@fHo8ARgsPO3TgS4I1OQ@cg1cVOVD/Azu2Q2QhkdFJuHdfkgGtcoJCbSW95QY0VWwcVPhMsAx7zKjPvhOVDTfWUBt0UGS5cWgyqJSW22sqlNzcKV8CGwLnqe5vzk2hlSvh1lsW2Rk3xsNU1yWuyfcpU6loRLPW3SdFgxpqWSvsE2ZordQ1ULXiqd2hzcCxGYKaHYH0JkXZEoSmunYgEx6WW2UKoC2JQq55RxYKS@I9GBBTjZDpFAxDTVxrgpdGkdctWBR4VqxKW40LMlvah8/eYivERJ5shm1A/ay0pgweMC0FoDJKoFdrHBxeS1J4iAu2aXinHpQg78OLCgoOwp57@KWqxIeQzqV@OQ9IPFjKpeP@xoa0Zrh6X1dwNQ/7zbBfhnNZV7DpzmW/XIXMZciX6DAE8lJNV6QK6Dj3AmZhQFUoANErYd7ZX9xIedTKtwN0mX24ZJ13uOUvdD8rUSCY4m3EzhnYwvlK0PpgXyooFzh7O8hcoNKNHL9PrycBKO0o9/bypptML75CJx4WgMJGxgkt3KN1kOMwCGS4KUqgPVZ1mEkp1LmS6c/c6OjpKMnZzkU/cjCeQCqjzpoSzUWURy5xtdiLjuE4jpONvEa/jQ//AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 141 bytes
```
T`CcJ\O\oSsUabD\defGg\hj\L\lnP\pQqrTtuVvXxyABF\HIiKkNRYZz\EMmW\w`Ll
O`\w+
T`Ll`CcJ\O\oSsUabD\defGg\hj\L\lnP\pQqrTtuVvXxyABF\HIiKkNRYZz\EMmW\w
```
[Try it online!](https://tio.run/##pVTbbtswDH3PVxAGBgyYf6LrbemyZVu7ZRcXKFPTtlJZyiS5qffzHUnbaYoN2MOARJLJc45E8diBknH4@OLl@c3j1c3x7UWxLPxl/Izrk6Kk6rwumk2xKKz7UGw//gxXqfty//WhP3p9VryZm7d37z99@/6rOH3XrordzcLOljfF7tXsipf/Kfb4mM0T7DBCagjWFBP4CpJpKYJ5Sux8GDNzzmSzjJf8U7zk9S@pkcqawlaWaPA/m81@ZKuGXJZDZk1FMtfmnuV40ftO49R6p4EW7xSxkAiWlF0zfQ/fR59xJtVRbJLQTa95@6uGctj4Ljjqcz5/Dpjz0X0X0ZU5tMZSzLmo2jiedyY1jHLMiYm2OR9AKE8BYU/gvaru8YemaPEJslNXWxMbuEzB3xEc@84lOLLbBteU@FqHwJid4jCy@AazI2jRAcLW6nSLDi1seWyR6cMjSl5DA0w5Qj7GEHouANqeO9LvMJQQvcsOMvFZVknWRwIuj4v2gYDLGqqGkrsffG9cDXRPzK@s31GAOhA5kCsg2HTsAFVwHrbkt5bgZ2co2R4Csm0CXxafsYsic08PMj0E7CP0LE@hxF6sdGespRK@420T@VKdYXO1a0zqqnfYS59ZTaYzH251sdZRrn4yhXhoiI7Y0Sl7yqikHHHMvM2h9nwm7qnnbrKjcmgMR9GJgyoK/HyaSyNSDoEqLpp3GR7HvEBHEaUKfkAOqrKJKItBNmSth4v9uISLU1lvxvVC4jwuYaNxXi@WglwInrPcTJ33MeXRAVbZk9KkPe2gqtL2FUHs5PzQStd9lbincwemRe49JsNG0c7N33MxaE3q9bMgsJE4hkeYIg/Zqrsi9ZgvCc69rdRd/CQuOG6Qe@5q/d4o4o/EnqM2OPHSOx9kPFnK6Hwamx20vSYOUQ2GXv1wiB8UnP8bV/CDhPTpDI3tAj19NROxNbloI6d9FhHIBJesvG0O2HmMsFZuJ8EcsOW39jJhgBWGCBUOr6UbYih5jh1QRGCuYCmenO/qBugBW37Forxter/8CS7j9b/yvwE "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Simply replaces all letters with other letters that are in the desired sort order, then replaces then back after sorting the words into order. Note that Transliterate has several shorthand letters (such as `L` and `l` of course) which need to be quoted in the master list.
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 61 bytes
```
{x@<"CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw"?x}
```
[Try it online!](https://tio.run/##RZJBc9MwEIX/yo4vtAeGO2UGSpoWl7QBWih0uGzita1E0rqSnNh0@tvDk@mUiyxLu2/3fdrta9/4w6F@@zh8eFfM1pdLvYnfeXVWSX3RtJuF9V@6rw/hNvU/dj@H8fTj@afSfN5ef/t1/2d@5e72xfvh6fB4NJwUVLypj7D@Ho6Pn14dFWWiPUdKrdBKYiKtKRknkcz/i72G55sSN8VJcdeKJ2tqocbsEDtqT1ac@kiOt0KLvOdKEHqL/I32wcuYFRiC2kf2FTljkbqSxiBtb1JL6oVikg5pc99YE1u6SUEhONPeJzq1XcsrScUJFaeo5CHX2emzZs@WOqyOkT7jEFDPkxvhYtxzqCiqzzdWoxAaQiUNQrmTqQeqYD/oaHxDshOk11b3EqgJAre5azjpAWJS8EqdaGeFHnojyY4UGKwC/KGhPmaZnQz5MwQewQjyEioeM9mtsVYquud1C2TGGzB2K4az4goRGfq5hnV@k39oQBh3paNGs2TSf6Bb4@AAYGtUbucZQ6IgNXpF@EasVbp8WZd0Oc/7zfN@kc@xLmkznWO/WObIRY7HbX5qPEk/ybuMS@sEGKUn4xjQOBlAniyX1yjM1qQxU9ZK6EJtPfHFX2561jJc@2YaoTMlDXS2BMiU/ULbxEw1hSxwzsb2OHuZyyRghS5MnJ7XTzOXYCRXT1QSgwTGhQPdcYhUc35t8do3LcnArsvTBv3JBia6isXx4S8 "K (ngn/k) – Try It Online")
Takes the input as a list of words; returns a list of words.
```
{ } a function with parameter x
"CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw"?x find the indeces of each character of the input words in the list of stroke counts
< grade down
x@ take the words at the graded down indeces
```
[Answer]
# [Red](http://www.red-lang.org), 162 bytes
```
func[b][forall b[b/1: collect[foreach c b/1[keep index?
find/case"CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw"c]keep
b/1]]sort b forall b[b/1: last b/1]]
```
[Try it online!](https://tio.run/##VZNBc9MwEIXv@RU7uTMdrhxgSpqWlLSBtlCoxwfZXttKZK0ryUnMnw9Prh2GHCRZu3ra/fTiuDg9cJGks/IDncrO5kmWJqU4ZQxlSXbx/gPlYgznIe6yymvKCdvJjrklbQs@fpqVmC9y5Xm@yG838uh/qOyq4PKmqrdrY7@131/dU@h@7n8d@8vP119W@uvu/uH3y5/lXfN8mOdpFJtBNU29uEAZ/V@BUT7QED5NRXhKZoTffBXooDyFmiljpElJQTfsSf8LHMSNkRUi87eDzzVbMrpkqvQe@b10ZLgR66lRO6Z1XKuCx/Qn6Gylc5b7qKQgLJ1XtqBGGxzPuNI4etChJrFMPnA7Hl3aymhf02NwAuGFdDbQpWlrlXEYcy5xqYVqa4YpV1YZajE2asxYKOdwtaWmR2P9QbmCvNgpasQzoT5cDEQUCxtKogJUnPTaVsR7hkRp5MCOKscAEJtAYx34DApWqGVpDdNrpzmYnpwCQod2UVjno8yej3E6OtUDG@TZFaqPwHcaVinoBS8EitpqoG8yNTV5h6z4Htfi8vhcb7QAfoyvGqokSgd5e4NaN@gEvEtUUC8jlkCOS9Q8HtmyMUK353FDt8u43o7rddzHuKHtsI/1ehMz1zEf0ckNeLFuuKaJ@KQMgLOypBsFiCpogB8QrO5RgDI69BN5KZhuxJQDc3zFBhY17Mu2OrvtSkgcXW0AOEQGuEP7SDu4SehaadNh/2zlEJ2OirQ/W8AONg1oLlYTaEUKhOAs5ehZOU@lmhzBVrqqJj6qpo0GxV1Da/gzFBBMKaHWafBMGjGwEs3ffZxTSb5Fc/GT5mk6O/0F "Red – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ẹ1ʋỴḂỤ$*Ɗż©zk’b4żØẠŒuÞFiⱮµÞ
```
A monadic Link accepting and yielding a list of words (each being a list of characters).
**[Try it online!](https://tio.run/##AWEAnv9qZWxsef//4oCc4bq5McqL4bu04biC4bukJCrGisW8wql6a@KAmWI0xbzDmOG6oMWSdcOeRmnisa7CtcOe/@G4ssOHS///Ik1heSB0aGUgRm9yY2UgYmUgd2l0aCB5b3Ui "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##RZLPahRBEMZfpVhyUXIRPHkL@SMbV/egEFA81GZqZnrT0z1292QznmIugt48KUjw4EUQQdEQk@Bhl3jwLXZfZP1qEvQy3dNV/VV9v66xWNsul4vD9/Ozn7f@vJ6ff5@fHs3PP67c/P3q8mL66fne4vDd6Pblxezt/OzD5ZtmdrxlFl@/TH/Mjpfz02@rs5cr9xZHn8eLF7/uTE9u6Do9mZ4sl096/UQTjpRKoZHERD6nZCqJZP4HJj5cR/qI9FZ7O6U4siYXKsw@clvfkJXKu0gV7wkNdM@ZIPUR7o99E5y0qsAQ9E1kl1FlLK6OpDC4NjGpJO@EYpIa1zZdYU0s6WEKHoLrvnGJ1mxd8kgS4mso5KBW227ZZceWanwrRnSdQ0A5R1ULE@2EQ0bRO41YH4XQDwr5IKSNdC1QBvfBt8YVJPuC67n1EwlUBIFZbRpGGnDoFJynWnxthZ41RpJtKTBQBdhDQ01UmX050OUgcAtEkJeQcatg94y1ktFj3i1BzDgDxNWI1dh9ZCjzLR929UmuyAAwYv2KCq@SyV9xLk0FB@Cao3K5qRgSBcnRK9LHmBtP2/@@Q9re1P34ej/Qc3yHNO7OsR8MNXOg@YjqS@NFmk6@Ulw@T4DRd2QqBjROBpA7y/0HKMzWpFYp@0zorrd5xxd/2vR6yXDtim6CNjz5QBtDgEzqF9omKtUUVGCLjW1w9m8sk4AVujCxe17XjVyCEa2eqE8MEpgWDrTDIVLO@trifFOUJAdc1Tps0O9sYKCz2Hv6Fw "Jelly – Try It Online").
### How?
```
“...’b4żØẠŒuÞFiⱮµÞ - Link: words
µÞ - sort (words) by this monadic chain, f(word):
“...’ - base 250 literal = 12827082404216683880457031718358
b4 - in base 4 -> 2201321220213201120101312211011111212121011101113112
ØẠ - alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
ż - zip -> [[2,'A'],[2,'B'],[0,'C'],...,[2,'z']]
Þ - sort by:
Œu - to upper-case -> [[0,'C'],[0,'c'],[0,'J'],...,[3,'w']]
F - flatten -> [0,'C',0,'c',0,'J',...,3,'w']
Ɱ - for each character, c, in word:
i - index (of c) in (that)
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~93~~ 92 bytes
```
l->sort(l,by=x->findlast.(i for i=x,"CcJOoSsUabDdefGghjLlnPpQqrTtuVvXxyABFHIiKkNRYZzEMmWw"))
```
[Try it online!](https://tio.run/##1ZXLbttGFIb3eooDZUOisgWjOwMy4PiSynXitHHrNkUXI/JQHHk4w8wMLTFF36Loqk/XF3H/M6QcG910W8PmbYbn8p//Mzed0epo9/haBT6stC2NCjErjo/PauVnFI6PP0Sv7TqnBT0tLxZZkWMxp8kr4p0OMZC25LlgG@mBfdDOBnIVXUl4yoK2BdPR4dc5XgjMVMfYhuP5vHRFONzIJqPs@tD59Zzt/OFovkI985BSh/mrF9Ud3Hat4d9OV1hWRUyF7m@GYn/PJ5MKBT@ag5PgfMzMbNUvdgcn@xCHmabKedKL3Wx6VlzduA/hB7U6L7l6s64318a@b7/75G9j9@PDT7v@9PXlN0v97f2773/@@PnibXO3neb5Y2Tpe0HZdBlpqwLFmmmFh9J41A1DlC8LW@fHlSVWprPpXc2WjK6Y1voBe3vXkeFGhGvUPdO1XKuSpzSb3iLAxnXeci8hFCK6LihbUqMN3l3xWuO9rY41OcsUIrdIcWHXRoeaoIpDxDPXYTynpq3ViiPWT5HJIlpr0qlQVhlqcWwUVs@U90hnqenRRb9VvqTgrKwYF5hQDxI5zySFpBKoRPve9ZgBMXzQU2Xclj2tPaNbKRqNdBAiRbCOWnYYJn3qNEfTk1fQyqM9FNQFCfMAf@G086qHRgjPvlS9KHuvjeGSPqqihmTaamjcrJQ09hY7RPRL5wuZyaAMFMbasqG1k5DRDULXukEH0LVC5vpCZIjwcoVasX3Dxji6ejre0NWFXG/G62t5juMNbdJzXF/fyM5r2Y9VGTUm0qXwjcjlqggxlpZ0oyCaiqBlaHn5DomV0bEXlV3J9MaZKumLOykabkfXdp0sdO4IJj6/gZBR@kVsHUTV6CXApdKmw7MnX0aGVqhChzRemzwX0Yhkj7QkBSXgFuXpTvlAlZJps3XdugbnqmnFbIif2oCjSwSa5BPetVxEzEJggD/xO@Srh@TJ8iMSYEWoSDQIG/hDjgGBveX3HCQ6pMY0JwEGWyX@aHEUOzp/D8dtyviCDRl9UlPMP5KwZ4BGQrA@mF8JDQmAAYpEyHMWwgse/g8srIYZiIwDDgLHKEqy@mB8JBmwEBxAwQCAQAJgRH9sT35@8nbyPz/zfKJgT8QXRgaCEh1pfGL@EYfR7KP5k/@fM5Fsdsd7Fv6FQBJbCJG4CQQQYd0zHADC4PYX/k//GkY4nlhItleCAGz/jAoRbpl4@E8sIEFxjxyCwt9//TmdEU5/TPOJfG@yOONcPpWfdZul78eM9vDkE8JPhxdDC1GyODxo5cObdcONfG42mFLWIixNxx345EVjszHzLxkvFiH/6ujXtGdGkRYnxKDUlo//AA "Julia 1.0 – Try It Online")
works with Julia > 1.3
uses as input and output a list of the words
based on [this](https://codegolf.stackexchange.com/a/215292/98541) answer by @Noodle9
edit: replace `collect(x)` with `i for i=x` (-1 byte)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~72~~ 63 bytes
```
≔⭆⁴⭆⌕A”)“∧·¹]↗¿¤≕τB}VC↘”Iι§⭆α⁺ν↧νληUMθEι⌕ηλW⁻θυF№θ⌊ι⊞υ⌊ιEυ⭆ι§ηλ
```
[Try it online!](https://tio.run/##VU9Na8MwDL3nV4icZPAgTnbLKRQKhQUCO5YevCSrBY69xfay/vrMTgrtDtLTx5P01Cs591bqdW2co6vBdz@TubbyC185PJIjmaHRGvNSlKIohKgiimhlWUSLebXXxb2fwqraGTmHg3QeiTEOjT@ZYfx9OiQ5dDo4NBze7DLOvXQjGpbIevOK1VkkHuw0STPgN4c0RhySKlQ7rc4WRXoEbMnEZZEUGINPOwMebDB@GyNDU5iSEAZdcArDv2KddVGUx7Q@PL9PD933c6xe1/M5b@Utfpd7NSY42rnfgo/NL@RVwpsN@eWyvvzoPw "Charcoal – Try It Online") Link is to verbose version of code. Partly inspired by @JonathanAllan's answer. Takes input as a list and outputs the sorted words on separate lines. Explanation:
```
≔⭆⁴⭆⌕A”)“∧·¹]↗¿¤≕τB}VC↘”Iι§⭆α⁺ν↧νλη
```
The compressed string `”)“∧·¹]↗¿¤≕τB}VC↘”` expands to `2121001131211121220122113321001111210011011133112122` which represents the decremented stroke counts of each letter in the order `AaBbC...Zz`. The NESCA is then calculated by extracting the relevant letters in order of stroke count.
```
UMθEι⌕ηλ
```
Replace each string with an array of integer offsets into the NESCA.
```
W⁻θυF№θ⌊ι⊞υ⌊ι
```
For each unique word in the list in ascending order, push each occurrence to the sorted list. (`Minus` filters out all matches, so we have to explicitly push the duplicates.)
```
Eυ⭆ι§ηλ
```
Restore each integer array to its original string and output each string on its own line.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 26 bytes
```
Σ啪¯æ·$ÎÐ+MAî+X•4Bžnø{Ssk
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3OJzWx81LDq06tD6w8sObVc53Hd4grav4@F12hFAYROno/vyDu@oDi7O/v8/WikrNScnX0lHQckLmeEPZrhCRbIQIj5QNUAGWCQLpgYo4uMP1e4DNQekOBYA "05AB1E – Try It Online") Beats all other answers.
```
Σε•...•4Bžnø{Ssk # trimmed program
# implicit input...
Σ # sorted by...
sk # index of...
# (implicit) current element in...
ε # map over letters of...
# (implicit) current element in sort...
sk # in...
# (implicit) flat...
S # list of characters in...
# (implicit) each element of...
{ # sorted list of...
# (implicit) all elements of...
•...• # 12827082404216683880457031718358...
B # in base...
4 # literal...
ø # with each element paired with corresponding element from...
žn # "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# implicit output
```
]
|
[Question]
[
# Task
Given an integer matrix `M` and a modulus `m`, find an inverse of `M` modulo `m`. If the matrix `M` is not invertible modulo `m`, the behaviour is left unspecified.
# Matrix inverse
If `M` is a square matrix, its inverse exists if and only if its determinant is not 0. Similarly, when we are talking about matrices modulo `m`, the inverse of `M` will exist if and only of the determinant of `M` is invertible modulo `m`, which happens when the determinant is coprime with `m`.
The inverse of `M` is a square matrix `inv(M)` such that `M*inv(M) = inv(M)*M = I`, where
$$I = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
\vdots & \ddots & \ddots & \ddots & \vdots \\
0 & 0 & \cdots & 0 & 1
\end{bmatrix}$$
has the same shape of `M` and is called the *identity matrix*. As an example, consider the first test case, where `[[22, 43], [29, 37]]` is the inverse of `[[26, 16], [38, 41]]` mod `45`:
$$\begin{bmatrix}
26&16\\38&41
\end{bmatrix} \cdot \begin{bmatrix}
22&43\\29&37
\end{bmatrix} = \begin{bmatrix}
1036&1710\\2025&3151
\end{bmatrix} \equiv \begin{bmatrix}
1 & 0 \\ 0&1
\end{bmatrix} \mod 45$$
# Input
A square matrix `M` with integer values between `0` and `m-1`, inclusive, and a positive integer `m > 1`. The matrix may be given in any sensible format, including
* a list of lists, where the inner lists encode the rows, like `M = [[1, 2], [3, 4]]`, or a flattened version, like `M = [1, 2, 3, 4]`
* a list of lists, where the inner lists encode the columns, like `M = [[1, 3], [2, 4]]`, or a flattened version, like `M = [1, 3, 2, 4]`
where these encode the matrix
\$\$\begin{bmatrix}
1 & 2 \\ 3 & 4
\end{bmatrix}\$\$
The integer `m` giving the modulus.
You may also accept the size of the matrix as input.
The inputs can be given in any order.
# Output
A matrix representing the inverse of `M` modulo `m`. You may assume such an inverse exists. Preferable format is for each matrix entry \$a\_{i,j}\$ to satisfy \$0 \leq a\_{i,j} < m\$ but this is just to make it easier to compare with the test cases.
# Test cases
```
45, [[26, 16], [38, 41]] -> [[22, 43], [29, 37]]
39, [[29, 50], [29, 1]] -> [[16, 19], [4, 35]]
35, [[24, 14], [48, 45]] -> [[5, 7], [4, 33]]
53, [[43, 20], [15, 8]] -> [[5, 14], [37, 7]]
49, [[15, 11, 30], [20, 12, 40], [33, 25, 2]] -> [[33, 28, 23], [25, 18, 0], [25, 48, 13]]
37, [[8, 9, 22, 17], [24, 30, 30, 19], [39, 8, 45, 23], [5, 30, 22, 33]] -> [[18, 17, 26, 20], [29, 36, 23, 1], [19, 0, 9, 3], [30, 23, 14, 21]]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!
---
This is the fourth challenge of the [RGS Golfing Showdown](https://codegolf.meta.stackexchange.com/q/18545/75323). If you want to participate in the competition, you have 96 hours to submit your eligible answers. Remember there is still 300 reputation in prizes! (See 6 of [the rules](https://codegolf.meta.stackexchange.com/q/18545/75323))
Also, as per section 4 of the rules in the [linked meta post](https://codegolf.meta.stackexchange.com/q/18545/75323), the "restricted languages" for this third challenge are *only* [Jelly](https://codegolf.stackexchange.com/a/200519/75323), [V (vim)](https://codegolf.stackexchange.com/a/200525/75323) and [05AB1E](https://codegolf.stackexchange.com/a/200491/75323) so submissions in these languages are not eligible for the final prize. But *they can still be posted!!*
Otherwise, this is still a regular [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so enjoy!
[Answer]
# [R](https://www.r-project.org/), 68 bytes
```
function(M,m,n,A=M){while(any(A%*%M%%m!=diag(n)))A[]=rpois(n^2,9)
A}
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0/DVydXJ0/H0dZXs7o8IzMnVSMxr1LDUVVL1VdVNVfRNiUzMV0jT1NT0zE61raoID@zWCMvzkjHUpPLsfZ/mkZuYklRZoVGsoaRmY6CIRAbW@gomBhq6hhpAmlTHQUjzf8A "R – Try It Online")
Strikingly slow. Will most likely time out for all test cases on TIO, but is guaranteed to give an answer eventually.
Works by rejection sampling: generates random matrices `A`, with each value taken from a \$Poisson(9)\$ distribution, until a solution is found.
Note that to get `A` of the correct dimensions, it is 6 bytes shorter to initialize it as `A=M` and then replace all the values with `A[]=rpois(n^2,9)` than to create it directly with `A=matrix(rpois(n^2,9),n)`.
[Answer]
# [J](http://jsoftware.com/), ~~18~~ 16 bytes
```
(]%1+.]^5 p:[)%.
```
[Try it online!](https://tio.run/##dVBNT8JAED3TXzEx9GOLLu62Fd0Es9HEk/HgtWmNgRLrRyCAZo2Vv44zS4GC6WGy2Tdv3nszr@uH6bIAfzYvvsrp5wKW87JY@E4MyjdVGY5DASVfmSoouWHheMhD3j8NxI/0jGLedTnkLv/2nbRyuc629LQquU6JnSrk68aAdnkrWViu/uWyUtooyzzrAw@RbCd23/xJ9BKYqRQZ400vQIG6y/btIHN7VjTLLcBQFLFUWbQJBmnNVDlLvJliK0K3YJBbzIICb@NyN/cCmv5gOrAchqv5Vkf0eFMjI6AWWNUBhIecZiICjkLSgE7zFU5nBG3@lH6H6cxhzgn3JzBU4MMpnIPCOuNw@3h/t95Y71XXzPl4XhJXguzKCwMCK7o0EAvjFKOXKcQJTABJnU7n4YbDvFh8vi93rYpa0KMz75nEG70Uo7cD8SsDybkBerfa0VWrNraa2jvmP@0Ioq5IUFNgcNLHEhIXwDeK8I89ud2l3S8@9Itb/WKIu3gf3EKiixjgG2@cqQTiERZdkIwxQFLnkjZPvd2gffHB4eKD4yDrPw "J – Try It Online")
Resolves `p/q mod n` element-wise (instead of using `det(M)` to resolve the modular inverse globally).
Abuses GCD of rational numbers to extract `1/q` from `p/q`.
### How it works
```
(]%1+.]^5 p:[)%. NB. left arg = modulo, right arg = matrix
( )%. NB. bind inv(matrix) as new right arg
5 p:[ NB. phi(modulo)
]^ NB. inv(matrix)^phi(modulo) element-wise
1+. NB. GCD with 1; GCD(1, p/q) = 1/q
]% NB. Divide inv(matrix) by the above element-wise
```
---
# [J](http://jsoftware.com/), 18 bytes
```
%.@]*-/ .*@]^5 p:[
```
[Try it online!](https://tio.run/##dZBbT8JAEIWf6a@YGKC0wMBeamUTTKOJT4YHXxs1BkpYL4FAMWus/PU6W2gBTR8mk93z7Tkz@5pPlmkC7mqdfOrldgPpWicb15GgXJNpf@Yz0LgzWUej8fzZGH0c9Drsm7eN8trXeowt/HKdOGth9FjicaYxii0dK@KjkwdRC2thVrDRD/JMRUYVZH8A6BNcvKiOT8@sG8BKxUTM9lqHDA6qd5Q95wLdOYwVuNCDISiqPsLtw/1dXjwrDQs89xzn4yW1OAfe5JcGGJW4MiCZcZLpYgkygDkQ1Gg0JjcI62SzfU8rKbMSdK3pkbTcdJFM387MRwaCoQHbS28xqvUm6dS7Iv95CxBNFpAno8GtPxXjtAB1IehMGi93qc@T53myNk@CbNL/0BacUlhIXe6TbTG6F1T2B20wDRAc5uLFPIftwvrFw/PFw7@D5L8 "J – Try It Online")
A dyadic tacit function that takes modulo (left arg) and the matrix (right arg), and gives possibly very large-valued modular inverse of the matrix. To reduce the range, prepend `[|` at the start of the function.
### How it works: the math
A simple mathematical way to calculate the modular inverse of a matrix is the following:
$$
\begin{align}
M^{-1} \text{ mod }n &= \text{cofactor}(M) \times \bigl((\det M)^{-1} \text{ mod }n \bigr) \\
&= M^{-1} \times \det M \times \bigl((\det M)^{-1} \text{ mod }n \bigr)
\end{align}
$$
If the matrix \$M\$ is invertible modulo \$n\$, we know that \$(\det M)^{-1} \text{ mod }n\$ exists, and it can be found using Euler's theorem:
$$
(\det M)^{-1} \equiv (\det M)^{\varphi(n)-1} \text{ mod }n
$$
Then we can simplify the original equation to
$$
\begin{align}
M^{-1} \text{ mod }n &= M^{-1} \times \det M \times \bigl((\det M)^{\varphi(n)-1} \text{ mod }n \bigr) \\
&\equiv M^{-1} \times (\det M)^{\varphi(n)} \mod{n}
\end{align}
$$
And now the fun fact: J has built-ins for matrix inverse, matrix determinant, and Euler's totient function. And it uses built-in rational numbers when calculating the matrix inverse!
### How it works: the code
```
%.@]*-/ .*@]^5 p:[ NB. left arg = modulo, right arg = matrix
5 p:[ NB. totient(modulo)
-/ .*@] NB. det(matrix)
^ NB. det(matrix) ^ totient(modulo)
%.@] NB. inv(matrix)
* NB. inv(matrix) * det(matrix) ^ totient(modulo)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
¯\\_(ツ)\_/¯ the answer was in the documentation of [Modulus](http://reference.wolfram.com/language/ref/Modulus.html)
```
Inverse[#2,Modulus->#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n26r8N8zryy1qDg1WtlIxzc/pTSntFjXTjlW7X9AUWZeiUN6tLG5TnW1hY6ljpGRjqF5rU61kYmOsQEIGVoCecaWOhY6JqY6RsZAjilIGKjO2Li2NvY/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript (ES6), ~~209~~ 206 bytes
Takes input as `(modulo)(matrix)`.
This transposes the matrix of cofactors (resulting in the adjugate) and multiply it by the inverse of the determinant of \$M\$ modulo \$m\$.
```
m=>M=>M.map((r,y)=>r.map((_,x)=>((g=k=>(++k*D(M)%m+m)%m-1?g(k):x+y&1?-k:k)``*D(h(M,x).map(r=>h(r,y)))%m+m)%m),h=(a,n)=>a.filter(_=>n--),D=M=>+M||M.reduce((s,[v],i)=>s+(i&1?-v:v)*D(h(M,i).map(r=>h(r,0))),0))
```
[Try it online!](https://tio.run/##pZNNc5swEIbv/hW6tKyKIAhBHLsDuaRHTjlSTcLY2CYY8MiUSWby391dyWSmp04bDxZarfQ@@yFeqqk6b0xzGoN@2NaXXXbpsrzAJ@yqE4ARbzzLjTOexCsaAPusxZfvt98eoOBfOr/DIZD3e2j5@tV/@yrvg3bd8udn3HCAAo9ZAZPlB6vI50NcHDKoRI@yVbhrjmNt4CnL@yDg4iHDMPzi/b0ITb39takBzqKctGhw99mHhjDTeuJXSPMHJEIIDZfv5YKVLEkFK8v4VjB5q3Gq7gRLpNYMjX/93dyQVIwCiqTilWBqqTVh1MpicEyj2fefFIeRFPGKpBKkpFeKSwZXZGJdlEz6iWRQbzkzlGOkihgJjrHNROKeu89kks7RqiXRLCSx5SJpKRHtShahRcW1lqIA0B//FW0hdjtWI3adIWG0otmgQslrghRGWeICxkDNlLYCVFQVub@rO7XU1ndWTZ2XzlCxmJ5bReIoSpcs/ui@IkvRLaAi4kJkiVbJypAPoTFek4VehLvB/Kg2B4CyE6zQnGU52wz9eTjW4XHYww46jh@du@rkdN/mRNMpHIfH0TT9Hnh4qraPY2VGiDnzmcc8Hr4MTQ@ex@fZz96zPnrzy28 "JavaScript (Node.js) – Try It Online")
## Commented
### Helper function \$h\$
The function \$h\$ removes the \$n\$-th entry from the array \$a[\:]\$.
```
h = (a, n) => // a[] = array, n = index
a.filter(_ => n--) // keep all but the n-th entry
```
### Helper function \$D\$
The function \$D\$ computes the determinant of the matrix \$M\$.
```
D = M => // M[] = input matrix
+M || // if M[] is 1x1, stop recursion and return its unique value
M.reduce((s, [v], i) => // otherwise, for each value v at (0, i):
s + // add to the sum
(i & 1 ? - v : v) * // either v or -v depending on the parity of i
D( // multiplied by the result of a recursive call with:
h(M, i) // M[] without the i-th row
.map(r => h(r, 0)) // and without the first column
), // end of recursive call
0 // start with s = 0
) // end of reduce()
```
### Main function
```
m => M => // m = modulo, M[] = matrix
M.map((r, y) => // for each position y:
r.map((_, x) => // for each position x:
( //
( g = k => // g is a recursive function taking a counter k
( ++k * // increment k and multiply it
D(M) // by the determinant of M
% m + m //
) % m - 1 ? // if it's not congruent to 1 modulo m:
g(k) // try again until it is
: // else:
x + y & 1 ? -k // return either k or -k
: k // depending on the parity of x+y
)`` * // initial call to g with a zero'ish value
D( // multiply by the determinant of:
h(M, x) // M[] without the x-th row
.map(r => h(r, y)) // and without the y-th column
) % m + m // return the result modulo m
) % m //
) // end of inner map()
) // end of outer map()
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes
```
ÆḊ×Ɱ⁹%ỊTḢ×ZÆḊ-Ƥ$-ƤNÐe⁺€Zʋ
```
[Try it online!](https://tio.run/##y0rNyan8//9w28MdXYenP9q47lHjTtWHu7tCHu5YdHh6FFhc99gSFSD2Ozwh9VHjrkdNa6JOdf8/vByk8v//6GhDUx0FQ0MdBWODWB2FaCMDIM9IR8EEzDM21lEwAsobxcb@N7EEAA "Jelly – Try It Online")
A dyadic link taking the matrix as its left argument and the modulus as its right. Returns a matrix. Append a `%` to get it within the range `0, m`
[Answer]
# [SageMath](https://doc.sagemath.org/html/en/developer/index.html), ~~48~~ 33 bytes
Saved 15 bytes thanks to ovs!!!
```
lambda m,M:~Matrix(Integers(m),M)
```
*Nothing on TIO for SageMath unfortunately.*
Modular inverse of a matrix `M` (input as a Python list of lists) mod `m`.
[Answer]
# [Sledgehammer](https://github.com/tkwa/Sledgehammer), 6 bytes
```
⠑⡿⡆⠱⣁⣭
```
Decompresses into this Wolfram Language function:
```
Inverse[#2, Modulus -> #1]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8N8zryy1qDg1WtlIR8E3P6U0p7RYQddOQdkwVu1/QFFmXolDWrSxuU51tYWOpY6RkY6hea1OtZGJjrEBCBlaAnnGljoWOiamOkbGQI4pSBiozti4tjb2PwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
FEXθ×ηη⪪E×ηη÷ιXθλη¿⬤ι⬤ζ⁼⁼λν﹪ΣEμ×ξ§§ιπλθIι
```
[Try it online!](https://tio.run/##TY09D4IwEIb/yo3X5BwwOjkZdXAgIcGNMDRQQpOD8lGQ@Odri2Kcnsvd@9xb1HIojGTnKjMAxrLDxDzVgD3BQzdqxJqgFoIg7VjbNfC3J7i39qpnXSrUBD@VRVC8J0BXgGfmcA54Edz6SfKIXzBB67OxKSc2mE7N2tFs9YvX7L0t1YIb/adOfDo8@gBIBt1avMjRohbi5Fx2JNgTZFnkmfvhQBDlee52M78B "Charcoal – Try It Online") Link is to verbose version of code. Takes input as \$ m, n, M \$ where \$ n \$ is the size of \$ M \$, and does not reduce its output modulo \$ m \$ (can be done at a cost of 2 bytes). Stupidly slow, so don't try this with realistic values. Explanation:
```
FEXθ×ηη⪪E×ηη÷ιXθλη
```
There are \$ m^{n^2} \$ possible square matrices of size \$ n \$ with coefficients between \$ 0 \$ and \$ m \$. Looping over this value, compute each matrix, but don't bother reducing the terms modulo \$ m \$. Then, loop over the list of matrixes.
```
¿⬤ι⬤ζ⁼⁼λν﹪ΣEμ×ξ§§ιπλθ
```
Perform the steps of matrix multiplication of this matrix by the input matrix, reduce it modulo \$ m \$, and compare the each result to the appropriate value of the identity matrix.
```
Iι
```
If this was the inverse then print the matrix.
[Answer]
# [MATL](https://github.com/lmendo/MATL), (25?) ~~31 29~~ 26 bytes
*My first MATL answer*
-5 bytes & a bug-fix (+2) thanks to Luis Mendo!
The trailing `.` may be unnecessary - it is if there is only ever a single inverse of `M` with elements modulo `m`.
```
:inZ^!"&G@[]eY*w\tZyXy=?@.
```
A full program which prints the elements in row major order separated by newlines.
**[Try it online!](https://tio.run/##y00syfn/3yozLypOUUnN3SE6NjVSqzymJKoyotLW3kHv/39TrmhDUwVDY2sFI0MgFQsA "MATL – Try It Online")** - Too slow for any of the given test cases.
Quite possibly not the best approach for MATL.
### How?
```
:inZ^!"&G@[]eY*w\tZyXy=?@. - expects inputs m and M
: - range (m) -> [1,2,...,m]
i - push input (M)
n - number of elements
Z^ - ([1,2,...,m]) Cartesian power (#elements(M))
! - transpose
" - for each column, C:
&G - push both inputs
@ - push C
[] - push an empty array (to make e work as below)
e - reshape (C) to square matrix of side ceil(#elements(C)^0.5)
Y* - (reshaped C) matrix multiplication (copy of M)
w - swap top two stack entries
\ - (multiplication result) modulo (copy of m)
t - duplicate top of stack
Zy - size
Xy - (size by size) identity matrix
= - equal -> logical matrix
? - if all are truthy:
@ - push C
. - break
- implicit print of stack (the valid C)
```
[Answer]
# [R](https://www.r-project.org/), 128 bytes
```
function(x,m,n)t(round(which((1:m*det(x))%%m<1.5)[1]*outer(1:n,1:n,Vectorize(function(a,b)det(x[-a,-b,drop=F])*(-1)^(a+b))))%%m)
```
[Try it online!](https://tio.run/##VY7NasMwDMfvewpfClKmjDq222Ys1z3CLqWD5qvNIUkxCS17@Uyyx2gOAlv6/T/8cimWdh6qqRsHeFBPA07gx3mo4X7tqiuAfu@TupnggbjZ9B/6zeFRn5JxnhrPx4FkvppqGn3308C/2ZlKDLpjeqa0pNqPt@LzhAmkGr/h/FoiBktc2uK5Al5iET/eJfSlBV923KeCbEdK75BUBeZAympEsm5F5KTcNhDyFMDkK8Dy1gbAioUTYmVhDaksWmhH6sCAM8@AbLUmZf5ytvzN2Cp@jciZyKTbKprjuFLGqN5HpRWTODqPaiZCLQZN2Lh4F5kxUnaPyy8 "R – Try It Online")
A function taking three arguments, `x` = the matrix, `m` = the modulus and `n` the number of rows of `x`. Returns a matrix. Uses the same method as my [Jelly answer](https://codegolf.stackexchange.com/a/200691/42248).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), (21?) 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
The trailing `Ṫ` may be unnecessary - it is if there is only ever a single inverse of `M` with elements modulo `m`.
```
Ḷṗ⁹L²¤ṁ€⁹æ×%³L⁼þ`$ƑɗƇṪ
```
A full program printing the result.
**[Try it online!](https://tio.run/##y0rNyan8///hjm0Pd05/1LjT59CmQ0se7mx81LQGyDu87PB01UObfR417jm8L0Hl2MST04@1P9y56v///6b/o6MNTXUUDI1jdRSijQzBrFgA "Jelly – Try It Online")** - Too slow for any of the given test cases (the 35 case took ~20 minutes locally).
---
**11 bytes** (but floating point output):
Using [Bubler's observation](https://codegolf.stackexchange.com/a/200834/53748) (go upvote!) that raising the determinant to Euler's totient is enough to remove the determinant's denominators:
```
æ*-ׯḊ*ÆṪ}ɗ
```
However, unlike in J, the inversion of \$M\$ in Jelly gives floats so we no longer get an integer matrix as output.
[Try it online!](https://tio.run/##y0rNyan8///wMi3dw9MPtz3c0aUFJHeuqj05/f///9HRhqY6CoaGOgrGBrE6CtFGBkCekY6CCZhnbKyjYASUN4qN/W9iCQA "Jelly – Try It Online")
[Answer]
# WIN+APL, 114 bytes
Prompts for matrix followed by modulus.
```
m←r←⎕⋄z←r[1;1]⋄⍎∊(¯1+1↑⍴r)⍴⊂'z←z×1 1↑r←(1 1↓r)-((1↓r[;1])∘.×1↓r[1;])÷r[1;1]⋄'⋄⌊.5+n|((1=n|z×⍳n)/⍳n←⎕)×(z←⌊.5+z)×⌹m
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##PU7BSsNAEL3vV8ytu5RUZ3fTNhT/oP2C0kOoRIQ0Snoy9CTShrQpikj9Cw8K4tX8yfxInElB2Bnee/vmzcT3aXD9EKd3N8Eyjdfr22VLx7fZlLbPTlG5S9oVw5yLZdo/FcLmOMEFE6qPVFb69wP7SNsXqr9yw42qx574iuaEIB8yrjv4mptA6w7MOcNQ@T5gV8dxsjDN9394TxYcqkHYzzY8cpVtOI/qz8xcSD9fZJqTllVnY8GUDj@rlg9vE2XB8jV2CDgENwaPyocqUR48y2OIwFrAEVgP7lIeRuAiYGMI1kEoEjucU270Bw "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Magma](http://magma.maths.usyd.edu.au/magma/), 34 bytes
```
func<m,M|Matrix(Integers(m),M)^-1>
```
No TIO for magma, though you can try it on <http://magma.maths.usyd.edu.au/calc/>
[Answer]
# Java 8, ~~270~~ 261 bytes
```
M->m->{int l=M.length,R[][]=new int[l][l],T[][]=new int[l][l],d=0,s=l,r,c,k;for(;d!=1|s!=0;){for(r=l*l;r-->0;R[r/l][r%l]=d*=Math.random())d=m;for(d=1,s=r=l;r-->0;d*=T[r][r]%m)for(c=l;c-->0;s-=T[r][c]%m)for(T[r][c]=k=0;k<l;)T[r][c]+=M[r][k]*R[k++][c];}return R;}
```
-9 bytes thanks to *@ceilingcat*.
Keeps trying random matrices (including duplicates) until it find the correct one, so times out for most test cases. I tried adding a cache so it tries random matrices without duplicates, but then it still times out for the same test cases.
[Try it online](https://tio.run/##hZJRa9swEMff8ynUQMGKZS1uExhVZdjLoA9mkObN@EGzndSxJBtJ7gieP3t2dtWGQdnA4PPd7//X6c4n8SqiU9lcCimsRamo9bBAyDrh6gKdoEp7V0t66HXh6lbT7z54rLXL8iwn/4SetKuOlSHI00mCDohf0ihRUTJAEkmeUlnpo3shu4nguvo10zKHh@w/yZV8TSyXxJCCNOzQmoCVNzz@bW/4muFhShguV5KZKErWbJeZLyA0tzLn5Yqnwr1QI3TZqgDjkqvZoeQxeILMiwDcZwZU@a3CE1BAqZhLNnorFe8l/8UbOL55lAz7RMjTKWjy1S5rwnBKsdFUrjca7dh4YQuYdNf/lDBpP/DXti6RgiUEz87U@pjlSOBpIQi5yrpgSxB6HwYMZhjiLYnvRzLcxdN7xOzK3gP8F3u3IfEG2M1Xstl6dlxctz0fPkunxaiPpaHUt/B8tq5StO0d7aA7J3WwfNJd7@wDUnwZqnDJUArB9Zf4Zow4W1pWVbdv3@4UpNi3@Znfj96B4QP6n8mBiq6TZzDzgcLY32i8/AE) (only contains the test cases `m=35; M=[[24,14],[48,45]]` and `m=5; M=[[15,13],[21,13]]`).
**Explanation:**
```
M->m->{ // Method with int-matrix & int parameters and int-matrix return
int l=M.length, // Dimension of the input-matrix
R[][]=new int[l][l], // Result-matrix of that same size
T[][]=new int[l][l], // Temp-matrix of that same size
d=0, // Flag for the diagonal
s=l, // Flag for the decreasing sum
r,c,k; // Index integers
for(;d!=1 // Continue looping as long as the diagonal flag isn't 1 yet
|s!=0;){ // nor the decreasing sum flag isn't 0 yet:
for(r=l*l;r-->0; // Loop over all cells:
R[r/l][r%l]= // Set the current cell in matrix `R`:
d*=Math.random())d=m;
// To a random value in the range [0,m)
for(d=1, // Reset the diagonal flag to 1
s=r=l; // Reset the decreasing sum flag to `l`
r-->0 // Loop over the rows:
; // After every iteration:
d*= // Multiply the diagonal flag by:
T[r][r] // The value in the `r,r`'th cell of matrix `T`
%m) // Modulo the input `m`
for(c=l;c-->0 // Inner loop over the columns:
; // After every iteration:
s-= // Decrease the decreasing sum flag by:
T[r][c] // The value in the `r,c`'th cell of matrix `T`
%m) // Modulo the input `m`
for(T[r][c]=k=0; // Reset the `r,c`'th cell of matrix `T` to 0
k<l;) // Inner loop `k` in the range [0, length):
T[r][c]+= // Increase the `r,c`'th cell of matrix `T` by:
M[r][k] // The `r,k`'th cell of matrix `M`
*R[k++][c];} // Multiplied by the `k,c`'th cell of matrix `R`
return R;} // And if the loops are done: return matrix `R` as result
```
[Answer]
# [R](https://www.r-project.org/), ~~97~~ 83 bytes
```
function(M,m,d){while(any(M%*%(x=matrix(T%/%m^(1:d^2-1),d))%%m-diag(d)))T=T+1;x%%m}
```
[Try it online!](https://tio.run/##TczRCsIwDAXQd79iIIVUb5Fu3RB1n7C3Pg/G5rRgJ4yJFfHbawYKgxDCzUnG2CcnlcT@MbSTuw9UwaOT7@fV3c7UDC@qxEZQKH0zjS6QFTvha9KHrk6VlkylEF51rrkQz9KWdquPgbNPXPf0u2pJI0MOI5FyFdxXyy0nukC2h@GXKWAlTD6jpTHQBoZN/jfZbOIX "R – Try It Online")
Pretty slow. Takes the `d`imension of the matrix as input. The previous version using a `for` loop is a bit faster.
Thanks to Robin Ryder for -14 bytes.
### Explanation:
We iterate over every number between \$1\$ and \$m^{d^2}\$, converting each to its base-\$m\$ digits (with leading zeros), reshaping those digits into a matrix of the appropriate size, and testing to see if it's the inverse of \$M\$ modulo \$m\$.
I wanted to attempt the whole series in SNOBOL but I'm not sure I will be able to implement matrix multiplication in SNOBOL in time for it to be a valid submission...
[Answer]
# [Python 3](https://docs.python.org/3/) + [SymPy](https://docs.sympy.org/latest/index.html), 33 bytes
```
from sympy import*
Matrix.inv_mod
```
[Try it online!](https://tio.run/##XVLLaoRAELz7FQ256DIJzrSzroHkD/IFMoRAkHjwgWtC/HrTNY2b1YNKd3VVT9U4LvPX0PO6NtPQ0XXpxoXabhym@ZS8fcxT@/vU9j/v3fC5Ni/7RpI0w0RtP37PV/lQnRClOpLWtTsbsudgqOaLocKGkMnHy@uBHl9JBpzUjAFXGeIyhD1fmj7fYKVz9U@30K@AFwL4I1uatogotnul3233hsqNzAdywYZcXG1l7BK5nndc1eYSKnsyKNaKqp49lwpGY8UQFtxpGHduIiIndRoINKTKtwIm7PGY0pNkEKONVuCZc300GRY82t@EvaLgwDUyKbNbolgijnBz7pY8o2LcAPKQRh7XRrmoBUw2O7miJDzTOLX9nDbpSX@MLFv/AA "Python 3 – Try It Online")
SymPy's Matrix class has a [method for modular inverse](https://docs.sympy.org/latest/modules/matrices/matrices.html?highlight=inv_mod#sympy.matrices.matrices.MatrixBase.inv_mod).
]
|
[Question]
[
## Introduction
Today we're gonna take care of the bane of first-year linear algebra students: matrix definiteness! Apparently this doesn't yet have a challenge so here we go:
## Input
* A \$n\times n\$ [symmetric](https://en.wikipedia.org/wiki/Symmetric_matrix) Matrix \$A\$ in any convenient format (you may also of course only take the upper or the lower part of the matrix)
* Optionally: the size of the matrix \$n\$
## What to do?
The challenge is simple: Given a real-valued matrix \$n\times n\$ Matrix decide whether it is positive definite by outputting a truthy value if so and a falsey value if not.
You may assume your built-ins to actually work precisely and thus don't have to account for numerical issues which could lead to the wrong behaviour if the strategy / code "provably" should yield the correct result.
## Who wins?
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes (per-language) wins!
---
## What is a positive-definite Matrix anyways?
There are apparently 6 equivalent formulations of when a symmetric matrix is positive-definite. I shall reproduce the three easier ones and reference you to [Wikipedia](https://en.wikipedia.org/wiki/Positive-definite_matrix#Characterizations) for the more complex ones.
* If \$\forall v\in\mathbb R^n\setminus \{0\}: v^T Av>0\$ then \$A\$ is positive-definite.
This can be re-formulated as:
If for every non-zero vector \$v\$ the (standard) dot product of \$v\$ and \$Av\$ is positive then \$A\$ is positive-definite.
* Let \$\lambda\_i\quad i\in\{1,\ldots,n\}\$ be the [eigenvalues](https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors) of \$A\$, if now \$\forall i\in\{1,\ldots,n\}:\lambda\_i>0\$ (that is all eigenvalues are positive) then \$A\$ is positive-definite.
If you don't know what eigenvalues are I suggest you use your favourite search engine to find out, because the explanation (and the needed computation strategies) is too long to be contained in this post.
* If the [Cholesky-Decomposition](https://en.wikipedia.org/wiki/Cholesky_decomposition) of \$A\$ exists, i.e. there exists a lower-triangular matrix \$L\$ such that \$LL^T=A\$ then \$A\$ is positive-definite. Note that this is equivalent to early-returning "false" if at any point the computation of the root during the algorithm fails due to a negative argument.
## Examples
### For truthy output
\begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}
\begin{pmatrix}1&0&0&0\\0&2&0&0\\0&0&3&0\\0&0&0&4\end{pmatrix}
\begin{pmatrix}5&2&-1\\2&1&-1\\-1&-1&3\end{pmatrix}
\begin{pmatrix}1&-2&2\\-2&5&0\\2&0&30\end{pmatrix}
\begin{pmatrix}7.15&2.45\\2.45&9.37\end{pmatrix}
### For falsey output
(at least one eigenvalue is 0 / positive semi-definite)
\begin{pmatrix}3&-2&2\\-2&4&0\\2&0&2\end{pmatrix}
(eigenvalues have different signs / indefinite)
\begin{pmatrix}1&0&0\\0&-1&0\\0&0&1\end{pmatrix}
(all eigenvalues smaller than 0 / negative definite)
\begin{pmatrix}-1&0&0\\0&-1&0\\0&0&-1\end{pmatrix}
(all eigenvalues smaller than 0 / negative definite)
\begin{pmatrix}-2&3&0\\3&-5&0\\0&0&-1\end{pmatrix}
(all eigenvalues smaller than 0 / negative definite)
\begin{pmatrix}-7.15&-2.45\\-2.45&-9.37\end{pmatrix}
(three positive, one negative eigenvalue / indefinite)
\begin{pmatrix}7.15&2.45&1.23&3.5\\2.45&9.37&2.71&3.14\\1.23&2.71&0&6.2\\3.5&3.14&6.2&0.56\end{pmatrix}
[Answer]
# C, 108 bytes
*-1 byte thanks to Logern*
*-3 bytes thanks to ceilingcat*
```
f(M,n,i)double**M;{for(i=n*n;i--;)M[i/n][i%n]-=M[n][i%n]*M[i/n][n]/M[n][n];return M[n][n]>0&(!n||f(M,n-1));}
```
[Try it online!](https://tio.run/##rVO7csIwEKytr7iQISMZKfgRKgF/4DqFowL8IDdjZMaYJuBfjyMZD014uKDQSLq9vb2TZhOxSZK2zWnENUeWlod1kbluJI95WVFcaFdLFEKyKMapVjGOtRKLKO6Pbh/WatrFtJJVVh8qDf116b3RF306dQLCZ0w27SvqpDikGcz3dYrl@/eSoK5hu0JNGRyJc@4CTBuxgoWNOLTvLFZdxiXQ3QF8DuDZBQ3/j1rEv4t2GdAYsMt4oDYz2QEH4V@tF5zVrqOiQ0xGOFjNMmzN4Go9i8xuzhacZwu9wWrhQ7WPR2qWO3y2@/8mnvhv4glqYriafY3wZj37zrOhasRpJHGMI4Fap6AxhSfNNoc9/mSlMReD6eUce4oZdDJhhrurDCOno3H6pUccLIyKQ2CcSJzeq54kDWl/k7xYbfat@NSlwO2uwARrYdh/ "C (gcc) – Try It Online")
Performs Gaussian elimination and checks whether all diagonal elements are positive (Sylvester's criterion). Argument `n` is the size of the matrix minus one.
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~19~~ ~~17~~ 12 bytes
```
@(A)eig(A)>0
```
[Try it online!](https://tio.run/##rZPPasMwDMbvfYrvUhofLPwnbihmY3uO0UNZnREY22i7vX4mC1PijR1qlsMnSzY/PiTl/fly@ErzeEdE80P3qNL0wnpv5mnsxu7JwsBEAyvKca9QfQrH6fzRbS6nz7RREen1nEppPPBZam9HYJ1frBZUIboSDXyJBv1eNVED07SNjs1y0Fnhl34bvWoHF1kCO8x@vama0EQdyLJd6kPMgh35oe7sjdSC9VezfTHrGrFYS76q10D/tQeNXP0LrG1bc39wnewTtyP8L1fmpmVwotD16Bq513WAJefhabEXXB94kcn2US4lNdiSi/xOLnICQ2F7y58j6fwN "Octave – Try It Online")
The function eig provides the eigenvalues in ascending order, so if the first eigenvalue is greater than zero, the other ones are too.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes
```
ṖṖ€$ƬÆḊṂ>0
```
Uses [Sylvester's criterion](https://en.wikipedia.org/wiki/Sylvester%27s_criterion "Sylvester's criterion - Wikipedia").
[Try it online!](https://tio.run/##jVBLDoIwEN1zilm4gKRDWgohbtx6CMLSjeECbllo4gE8BQeQNYn3wIvUmVJLQRNNpknfy3tvPsdD05yMGfsb1bPtNo9uOI/369i3O2mGC1FUe2PiOIoAqkoJkFS1IAQVfdUCMVETDLULQbYmqPSaoMp9ChQC2IbKaRhwW0@gBUTq2cQU67K3hgEnyTCFm0tvKlNFiizNC6fhr4BtqkurSYQ7Ak/8mZ5/SSdFOJKlvEa6sUPCvvmE@LcJAxM316GG5y1@mKbtMVgfp/1xPkDyAg "Jelly – Try It Online")
### How it works
```
ṖṖ€$ƬÆḊṂ>0 Main link. Argument: M (matrix)
$Ƭ Do the following until a fixed point is encountered.
Ṗ Pop; remove the last row of the matrix.
Ṗ€ Pop each; remove the last entry of each row.
ÆḊ Take the determinants of the resulting minors.
Ṃ Take the minimum.
>0 Test if the least determinant is positive, i.e., if all determinants are.
```
[Answer]
# [R](https://www.r-project.org/), 29 bytes
```
function(m)all(eigen(m)$va>0)
```
[Try it online!](https://tio.run/##lVFBCsIwELznFQsKJrCB1Nqb@hIvMTYaaFNIU0HEt9etorShHlxyyAwzwywbervrbedNdI3ntdBVxUt3Lof/8qr3SvS1jsGZsoWtBFa5NnLGFjQQQxcvNxaOzp@44RkqVAIZvMZwhVmCiRGC4dcBBcIaZTYSEYZsSskBI@RTK5EkXY91hClQJWkKc0XWd2Wrq7a8jXPy2ZzNXA6pkgoDOdGpV9WEGt50cfmHVSZWqpInOtqh@Gml1W0TeA3Ow@eU4k5KoyO3dGZcHfxKsAfrnw "R – Try It Online")
---
Alternative using cholesky :
# [R](https://www.r-project.org/), ~~34~~ 33 bytes
```
function(m)is.array(try(chol(m)))
```
[Try it online!](https://tio.run/##lVFBCsIwELznFQse3MBGUqs3/YmXGBsMtCmk8VDEt9dtRWmDHlz2MsPMMMvGwR0Hdws2@TZgI323MTGaHlPs0V7bmjkph8ak6G3VwUGBqH2XUIgVD6R4S9dexLMPF7RYkCYtScA0FjUVGWZGSkEfB@wJtqSKmYgxFEtKjZigXFqZZOl2rmPMgTpL01Rqtr4qO1N3VT/PKb/m7L7lsCqrMJILnZ6qZtS4y8PVH1aVWblKmen4hv1PK5/u2ogN@ADvV8o7K61J6PjFtD6FtRQPMTwB "R – Try It Online")
-1 byte thanks to @Giuseppe
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
f((x:y):z)=x>0&&f[zipWith(-)v$map(u/x*)y|u:v<-z]
f[]=1>0
```
[Try it online!](https://tio.run/##bVHLasMwEDxbX@FDCVJZuXrYhIg6f9BLLz0IUXSoiajjmMYOjum/u7IiRKA5zbCzO5pdHez5@6ttl6XBeFJXomZST3u22TR6dv2HGw6YksvT0fZ4fJmeyfV3VJdXOhvUaFPzPVtc14/DOVcq11q/28GdOtsaY1AU6lyjTGsODJgBzYBH9MwYSFqsisQYyMQYlLG38h2U@7LwRoHQFUEmLypArGUBVZhfHSWL8rbg3qEoq1XwALtCbqMm70bLNCruQ4Y49P8G9KFKkyziLv6J6oEcUtEYKyDQWzCUGYSO1nX@jv4T3j5x/@O6oWjI7bwoW/4A "Haskell – Try It Online")
Basically a port of [nwellnhof's answer](https://codegolf.stackexchange.com/a/172682/82619). Performs gaussian elimination and checks whether the elements on the main diagonal are positive.
~~Fails the first falsey output because of rounding errors, but it would theoretically work with infinite precision.~~ Thanks to [Curtis Bechtel's suggestion](https://codegolf.stackexchange.com/questions/172677/is-the-matrix-positive-definite#comment416654_172688), now the outputs are all correct.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
```
0<Min@Eigenvalues@#&
```
[Try it online!](https://tio.run/##dc7BCgIhEAbge08RBJ1GGMe8FXjpGPQKEm4JrYdyu4jPbrNJbS7s7cf/43d6G2@ut9FfbOkOBfcnH8zRX1142fvgnmazLeeHD9F0JiUJCJhhnRDkN3DMeTUZDQRCjh0xqkmMAVTj@ImAPi2BrmvEawobpv7ZbmI0G/sdJhYvEwtKzBiBqiX/rVtW3g "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
Yv0>
```
[Try it online!](https://tio.run/##y00syfmf8D@yzMDuv70CAqgqZKZxqZcUlZZkVKpz1aLIpOYUp3KppyUCKaBcLKpcXgqXS8j/aEMFAwUDayBhCKGAjFiuaFMFIwVdQ2sgaQimdUGUgjFQBsgwUjCyBpGmIB1GQB3GBkAJY4SECUzCCKwBaoEuig26WMR1wRJGCsYgAaB5pkgSAA "MATL – Try It Online")
I've noticed that for the `[3 -2 2; -2 4 0; 2 0 2]` test case, MATL calculates the `0` eigenvalue with a very small inaccuracy, computing something as low as about \$10^{-18}\$. This therefore fails the first falsy test case due to precision issues. Thanks to Luis Mendo for pointing out that a non-empty array is truthy iff all its entries differ from 0, saving 1 byte.
[Answer]
# Mathematica, ~~29~~ 28 bytes
```
AllTrue[Eigenvalues@#,#>0&]&
```
Definition 2.
[Answer]
# [Julia 1.0](http://julialang.org/), 28 bytes
```
using LinearAlgebra
isposdef
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v7Q4My9dwSczLzWxyDEnPTWpKJErs7ggvzglNe3/fwA "Julia 1.0 – Try It Online")
---
# [Julia 0.6](http://julialang.org/), 8 bytes
```
isposdef
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/s7ggvzglNe3/fwA "Julia 0.6 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
It is possible to do it using even less bytes, @Mr. Xcoder managed to find a [5 byte MATL answer](https://codegolf.stackexchange.com/a/172680/24877)!
```
YvX<0>
```
**Explanation**
```
Yv compute eigenvalues
X< take the minimum
0> check whether it is greather than zero
```
[Try it online!](https://tio.run/##ZY5BDkIhEEP3nqIXGDLMQH4MxnN8Y1y4153x@ljmo9G4acOjpdyvj1vvp@d60GPv5wyFNkUOpV92G4uzTVf4dEVhovJGcjPWaDIUHk0xWKNU5kfblXhJmY1UahuCffKF1D/hMsP2HueUfP9I/qgEtvgXH6o/OPYkBkMh2@QL "MATL – Try It Online")
[Answer]
## [Maple](https://www.maplesoft.com/support/help/maple/view.aspx?path=LinearAlgebra%2fIsDefinite), 33 bytes
(i.e. my 2 cents)
```
with(LinearAlgebra):
IsDefinite(A)
```
[Answer]
# JavaScript (ES6), ~~99 95~~ 88 bytes
Same method as [nwellnhof's answer](https://codegolf.stackexchange.com/a/172682/58563). Returns \$0\$ or \$1\$.
```
f=(m,n=0,R=m[n])=>R?f(m,n+1)&R[m.map((r,y)=>y<n&&R.map((v,x)=>r[x]-=v*r[n]/R[n])),n]>0:1
```
[Try it online!](https://tio.run/##lVLLboMwELzzFZx4tLZrGxzUB@mtH4B6QxxQGvoQmAhSFL6ernFDQaQkQT54xzvj8SxfaZPWm@pzt8eyfNt2XRY6BZIhRVFYxDJxw3X0nCnolrlWFBekSHeOU6EWTtonaVmRRhp0AKSKDwkOm5sKqHeR4rtIJmv6wLpNKesy35K8fHfs1@p7/9Ha7qMxhjMnNkz4YoZMCitBuoQ9m5YKSQxQXxaYkvgMgeXNEFj@krbolTA7snjv7q/GfQXKZwxiIPKBBIUYWdFePbqkERCmvBBfDCzYI/OeeMEvb0K0X9K8/j9074Qlf2aJXxD7KE985eDwRRJ4WYNPx6oeJq7V0OHicbpYx4tH@Z6ZCzyWcLjeI4LOZ6R6AvWjEOYfT3W/ximh4HNF@MBVQrpf46pHrLSX7gc "JavaScript (Node.js) – Try It Online")
]
|
[Question]
[
In my language [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), there is a slightly funny construct: the empty triangle:
```
^
-
```
When given no arguments, it returns `0`. To generate `1` using this construct, we could use this:
```
^
/!\
^---
-
```
This simply passes `0` to the negation function. We can continue negating this result:
```
^
/!\
---^
/!\
^---
-
```
To get 0. One more negation gives:
```
^
/!\
^---
/!\
---^
/!\
^---
-
```
## Challenge
Given an integer **n** ≥ 1, output the empty pyramid being negated **n** times in the described fashion.
## Test cases
```
input
output
1
^
/!\
^---
-
2
^
/!\
---^
/!\
^---
-
3
^
/!\
^---
/!\
---^
/!\
^---
-
6
^
/!\
---^
/!\
^---
/!\
---^
/!\
^---
/!\
---^
/!\
^---
-
```
[Answer]
# [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), ~~31655 bytes, non-competing (obviously...)~~ ~~16989~~ ~~12901~~ 8465 bytes, somewhat-competing
So, I thought this would be a funny thing to try.
## Edits:
* -14666 bytes by finally getting around to [adding some compiler optimisation to psll](https://github.com/MarcinKonowalczyk/psll-lang/commit/597f0de1b9718532319360259fa68fd07ce9d610)
* -4088 bytes by using different optimisation technique
* -4436 bytes by [implementing automatic variable name shortening into psll](https://github.com/MarcinKonowalczyk/psll-lang/commit/67c02355f27cbc3cdd238d4b20475cb6320190eb) (I really wanted the Explanation psll code to compile into the answer *without* any modifications)
```
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
^- / \ -^ / \ ^- / \ -^ / \ ^- / \ -^ / \ / \ ^- / \ / \ / \
^- /set\ -^ /set\ ^- /set\ -^ /set\ ^- /set\ -^ /set\ /set\ / \ /set\ / \ /out\
^- ^-----^ -^ ^-----^ ^- ^-----^ -^ ^-----^ -^ ^-----^ -^ ^-----^ ^-----^ ^---^ ^-----^ / \ ^-----^
^- /f\ / \ -^ /t\ /f\ ^- /r\ /+\ -^ /r\ /+\ -^ /r\ /+\ -^ /r\ /+\ /r\ /+\ ^- / \ /l\ /0\ / loop \ /s\ /d\
-^ --- /chr\ -^ --- --- ^- --- ^---^ -^ --- ^---^ -^ --- ^---^ -^ --- ^---^ --- ^---^ ^- / \--- --- ^---------^ --- ---
-^ ^----- / \ / \ /r\ /e\ -^ /r\ /f\ -^ /r\ /c\ -^ /r\ /d\ /r\ /e\ ^- / \ /!\ / \
-^ / \ ^---^ ^---^ --- --- / \ --- --- -^ --- --- / \ --- --- --- --- ^- / \ ^--- / \
-^ /47 \ / \ -^ / \ -^ / \ -^ / \ ^- / \ /!\ / \
-^ ----- /set\ -^ /set\ -^ / \ -^ / \ ^- / \ ^--- / \
-^ ^-----^ -^ ^-----^ -^ / \ -^ / \ ^- / ? \ / \ ^---------^
-^ /a\ / \ -^ /t\ /+\ -^ / \ -^ / \ ^- ^---------------^ /<=>\ / \ / \
-^ --- /chr\ -^ --- ^---^ -^ ^-----------^ ^- ^-----------^ ^- /!\ / \ ^-----^ / \ /set\
/ \ ^----- / \ /t\ /a\ -^ / \ / \ ^- / \ / \ ^- ^--- / \ /l\ /n\ / \ ^-----^
/ \ / \ / \ --- --- -^ /set\ /set\ ^- /set\ /set\ ^- /?\ / \--- ---/ \ /l\ /+\
/ \ /33 \ / \ -^ ^-----^ ^-----^ ^- ^-----^ ^-----^ ^- ^---^ / \ / \--- ^---^
/ \----- / \ -^ /r\ /+\ /r\ /+\ ^- /r\ /+\ /r\ /+\ ^- /m\ / \ ^---------^ / \ /l\ /1\
/ \ ^---------^ / \--- ^---^ --- ^---^ ^- --- ^---^ --- ^---^ ^- ---/ \ / \ / \ / \ --- ---
^-----------^ / \ / \ / \ /r\ /s\ /r\ /s\ ^- /r\ /d\ /r\ /d\ ^- / \ /out\ /out\ / \
/ \ ^- /set\ /set\ / \ --- --- --- ---/ \ --- --- --- --- ^- / \ ^-----^ ^-----/ \
/set\ ^- ^-----^ ^-----^ ^-------^ / \ ^- ^---------^ /s\ /c\ /e\ / \
^-----^ ^- /b\ / \ /d\ / \ ^- ^- / \ ^- / \ / \--- --- --- / \
/n\ /#\ ^- --- /chr\--- /chr\ ^- ^- / \ / \ /out\ /out\ / \
--- ^--- ^- ^----- ^----- ^- / \ / \ / \ ^-----^ ^----- / \
/l\ / \ / \ / \ ^- / \ ^-----------^ / \ /s\ /s\ /s\ / \
/ine\ / \ /92 \ /45 \ ^- / \ -^ / \ / \--- --- --- / \
-----/ \ ----- ----- ^- / \ -^ /set\ / \ / \
/ \ ^- / \ -^ ^-----^ ^-----------^ / \
/ \ ^- ^-----------^ -^ /r\ /+\ / \ / \ / \
^-----------^ ^- -^ / \ -^ --- ^---^ /set\ / \ ^-------------------------------------^
/ \ ^- / \ -^ /set\ -^ /r\ /s\ ^-----^ / \ / \ / \
/set\ ^- / \ -^ ^-----^ / \ --- --- /m\ /n\ / loop \ / \ / \
^-----^ ^- / \ -^ /r\ /c\ ^---^ --- --- ^---------^ / \ / \
/s\ / \ ^- / \ -^ --- --- / \ -^ / \ / \ / \ / ? \
--- /chr\ ^- / \ -^ /set\ -^ / \ /set\ / \ ^---------^
^-----/ \ ^-----------^ -^ ^-----^ -^ / <=> \ ^-----^ ^-----------^ /!\ ^-
/ \ / \ -^ / \ -^ /r\ /+\ -^ ^-------^ /m\ /-\ / \ / \ ^--- / \
/32 \ / \ -^ /set\ -^ --- ^---^ -^ / \ / \--- ^---^ /set\ / \ / \ /out\
-----/ \ -^ ^-----^ / \ /r\ /a\ -^ /<=>\ /-1 \ /m\ /2\ ^-----^ / \ / \ ^-----
^---------^ -^ /t\ /+\ / \ --- --- / \ ^-----^ ----- --- ---/k\ /l\ / loop \ / ? \ /t\
/ \ / \ -^ --- ^---^ / \ / \ /m\ /2\ --- --- ^---------^ ^-------^ ---
/set\ /set\ -^ /t\ /d\ / \ / \ --- --- / \ / \ /!\ ^-
^-----^ ^-----^ / \ --- ---/ \ / \ / \ /set\ ^--- / \
/e\ / \ /c\ / \ / \ ^-----------^ / \ / <=> \ ^-----^ / \ /out\
--- /chr\--- /chr\ / \ / \ / \ ^-----------^ ^-------^ /k\ /-\ /<=>\ ^-----
^----- ^----- / \ /set\ /set\ / \ / \ / \ / \--- ^---^ ^-----^ /r\
/ \ / \ / \ ^-----^ ^-----^ /set\ /set\ /<=>\ /-1 \ /k\ /2\ /+\ /1\---
/10 \ /94 \ ^-----------^ /t\ /+\ /t\ /+\ ^-----^ ^-----^ ^-----^ ----- --- --- ^---^ ---
----- ----- / \ / \--- ^---^ --- ^---^ /r\ /+\ /r\ /+\ /k\ /2\ /k\ /m\
/set\ /set\ /t\ /d\ /t\ /d\ --- ^---^ --- ^---^ --- --- --- ---
^-----^ ^-----^ --- --- --- --- /r\ /b\ /r\ /e\
/t\ /+\ /t\ /+\ --- --- --- ---
--- ^---^ --- ^---^
/t\ /b\ /t\ /e\
--- --- --- ---
```
[Try it online!](https://tio.run/##lVnbbhwpEH3vryDKo4XI2F5FkZL1jyCkZDxRIsdxNDP7kK/3dnM9VVTReB7a0EXDoS6nCvzn7/nr889Hezn@OD2fXl9N/IX8CKb@oMlk0qDQDxvMBi86AflqSX/s@nDGG1tlWw/GWXghDIoTDKags7UPegH7amnwLqdrmz31EB686AYVeNoUdDYA0QlWiSkA3ct/1wgwTh/s9gt5@tKr@OgLPoj2uynox/lFkAQRX0aYhUtR4HcPJnJxX@ldUuA5vrhBJeI72mdS/nFccVvK/YqCDx4A/np5@RMhuksUPm5KTGqw22fHH@e4QOzlZ5wwNgNVI3lH@6zHPk4IVxxkmaY3277angv4VRrAfbd2N2W4E3XG@O67p/2jx96jZx8XhKaPkXeehUiepxlecJa0ybbRNBreVRu03aG0NhswDi3U2aNql@ZJ9x@jxbcHYwjbM5Tr9wyjBCl1OyNgQ5WZhi07ia0EwtihAycapI6SzSVAw0FUaQiuTFzDnNEBQyfbpIxSpAzbAx3UfByiYiEzu68eTZmJ5YYrTzZLnUSTJnBtcQuM5z5/@dczmK4pL00NnML5AvCFbnJt@SCo7p0XUljj5uaw0auWjjIyoZT@psKoVfArb9TMPJBW9H10ZWb@7cFpA7NvAV7TYe43KiiWgDzZpeaBNIkfvBRilXqb42bMN1WFBbq7u8tAexfqEmWXmwfSKg6DOAPnbe61sLHVxEbGiCmUptOoI1WaxM@eWD7wSGHEsynSHbIaeewF2dcd7o4l41BTqCStYicyiwPTAZLsZIsUnk6YBv11S6IX37Lx2g41BiDbtnawPYPHAg9ajjFT1B9VOzo4cXXHtoX5GKYQpAyaYeSSWq7j9A0cIqB@Trw8yNS2l2yxjkefyWXdsRQyTvhuRUeDbh32rVBNMk4tZuhKu8l4dMhwWO6ReOTwNmJcpe898e6YRzCj7KNT8TnFy4yYNDm@GmC4dskjtaUfs4YpFw3PfWYGXqlgMl@rMU9c23fWU5Muof7kbZcW8TP4SvD@/H3ymJ8/3ZbW/T9GoQW5JvWq@ZnHzQLMECG8vSl901oSO4ilaXeU3fOACYRQqu6Ul/sloHSa3XOCKYgN5E6VubNgyjz8pDssv96AsaLcKTZ3Pa9Pv12FplicV9nyL1U2PO3JNzgj7yulCeRq4gEaubtRPjLs7ohnQC2z6R5Y1sP43cqtVDuT@4y3JE5Dj8k8GepJDr3w6I10zAcdW1KYWXF7ZgJpPTRnujVeA8qgdrcr@qlfSxJz6RRGPSSokKcVpEbwVDJOuQToTEzde4ZXhQN1qeT8LgEKgLQ7gQppPSuzfD7Lr3jADXahJbvfzYf9FcpZviEwvBrNYWb9NM3Sy5TEAHdbSu@9XKamjvPl6wJewtGj0RTZEkcvN8mklvd7GVKs6s787qAI8mWJs4dkvO3IeOunKBd3kcYvykETOeqKmVJUA1ThXnZmS4on9@ShqpR5Ny71kM@B15b5ZVLpkuWYDtkusoPeihvb4V1y7KoaVU6PkC6v6Xw0ZkO@C4GFZ2m3RX/As7j43weaKsc0OEfnU3zbor7E/KkeJY@e/0/JiPckVrmGfiNIjWfZcW9RD5S99ca8N0fgGsE@IcE2jpBinLaY@QY3fNPMPcWsTa8r0Y1im9pucMG3i17Gx9n0yWceyHd0B99i@vChHi/vjZfshlxJedPsoh/YuGdQvKBbjHSeFAymX@yZ4c2kqrwnhTaTGp/hhlwuyEi7MKJhbTOELf90nsTbyJG@me67yzyaqL95/I@hMvnYOdR9sJWXwY47JS0D410B93WEWwHy@no4/A8 "Pyramid Scheme – Try It Online")
## Explanation
```
(set n (# line)) // Set n to line input
(set space (chr 32))
(set newline (chr 10))
(set caret (chr 94))
(set fslash (chr 47))
(set bang (chr 33))
(set bslash (chr 92))
(set dash (chr 45))
// Left triangle
(set lt fslash)
(set lt (+ lt bang)) (set lt (+ lt bslash)) (set lt (+ lt newline))
(set lt (+ lt dash)) (set lt (+ lt dash)) (set lt (+ lt dash))
// Right triangle
(set rt caret) (set rt (+ rt newline))
(set rt (+ rt space)) (set rt (+ rt space))
(set rt (+ rt fslash)) (set rt (+ rt bang)) (set rt (+ rt bslash))
(set rt (+ rt newline))
(set rt (+ rt space)) (set rt (+ rt caret))
(set rt (+ rt dash)) (set rt (+ rt dash)) (set rt (+ rt dash))
(set rt (+ rt newline))
// n = mod(m,2)
((set m n) (loop (<=> (<=> m 2) -1) (set m (- m 2))))
// Print the top and the first triangle
(? (! (? m ( // If m
(out space space) (out space)
))) ( // Else
(out space caret) (out newline)
))
(set l 0)
(loop (! (! (<=> l n))) ( // While l < n
((set k l) (loop (<=> (<=> k 2) -1) (set k (- k 2)))) // k = mod(l,2)
(? (! (? (! (<=> (+ k m) 1)) ( // If xor(k,m)
(out rt)
))) ( // Else
(out lt)
))
(set l (+ l 1))
))
(out space dash) // Final triangle
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
FN«↙^→/!\¶³‖T»↓^-
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NToZqLM6AoM69Ew8olvzzPJzWtREdBKU5J0xouHpSZngES1FeMiYnJQ5IxBjGDUtNyUpNLQooS84qB5udqAAVruZCMBBmnC9T1/7/xf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FN«
```
Loop for the appropriate number of negations.
```
↙^→/!\¶³
```
Print a negation function. (The `³` expands to `---`.)
```
‖T
```
Reflect the canvas.
```
»↓^-
```
At the end of the loop, print the empty triangle.
[Answer]
# [Python 2](https://docs.python.org/2/), 94 bytes
```
i=input();print i%2*2*" "+" ^"
while i:print['/!\\\n---^',' /!\\\n ^---'][i%2];i-=1
print" -"
```
[Try it online!](https://tio.run/##JYtBCoAgEEX3nmIaCMsaItsVnURzFzQQJmFEp7ew5X/v/fDE7fA6JZ7ZhytW9RRO9hG41EorBGwQHIp7430FHrM0siustZ6InGwlwD/BfUAu5rsuE9Pci1wjEKY0vA "Python 2 – Try It Online")
Trying to golf this... 3 `print` statements seem awfully redundant.
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 101 bytes
```
a=>{k=" ^---"for i:0..a print([" ^",k,"---^"][i?~i%2+1:i]+"\n"+" "*(~i%2)*2+"/!\\")print(k+"\n -")}
```
[Try it online!](https://tio.run/##JYvdCoMgGIZv5dsLgWa2LdhJYF1IJnQifAga4tnYbt2KTp@fPaeSYvWmbmb6BgNyWmv4lInHV99vtGeORSwgIocudDi9w7rw/OdmUO@RVwUboUBoxcVkOyg8H9ZC3nO4AtKQv@rFR9YD "Proton – Try It Online")
also too long lol
[Answer]
# Perl 5, 77+1 (-p) bytes
```
$\=' ^
_';map$_%2?$\=~s,\^, ^
/!\\
^---,:$\=~s, \^,^
/!\\
---^,,1..$_}{
```
[try it online](https://tio.run/##K0gtyjH9/18lxlZdIY5LIV7dOjexQCVe1cgeKFRXrBMTp6MAklDQV4yJ4VKI09XV1bGCSCkoACXjuMASQOE4HR1DPT2V@Nrq//8NDf7lF5Rk5ucV/9ctAAA)
[Answer]
# [Funky](https://github.com/TehFlaminTaco/Funky), 95 bytes
```
n=>{print((n%2)?" ^":" ^")fori=n i>0i--print({" /!\\\n ^---","/!\\\n---^"}[i%2])print" -"}
```
[Try it online!](https://tio.run/##SyvNy678n2b7P8/WrrqgKDOvREMjT9VI015JIU7JSklBAUhppuUXZdrmKWTaGWTq6kIUVQOl9BVjYmLyFOJ0dXWVdJQgPCA7Tqk2OlPVKFYTrBJkhK5S7f80DUNjzf8A "Funky – Try It Online")
[Answer]
# JavaScript (ES6), ~~77~~ 74 bytes
```
n=>(s=`^
/!\\
^---`,n%2?` `+s:` ^`)+`
/!\\
---${s}`.repeat(n/2)+`
-`
```
### Try it:
```
f=
n=>(s=`^
/!\\
^---`,n%2?` `+s:` ^`)+`
/!\\
---${s}`.repeat(n/2)+`
-`
```
```
<input oninput=o.innerHTML=f(value)>
<pre id=o>
```
[Answer]
# Java 8, 104 bytes
```
n->{String r=n%2>0?" ^\n":" ^\n";for(;n-->0;r+=n%2<1?" /!\\\n ^---\n":"/!\\\n---^\n");return r+" -";}
```
**Explanation:**
[Try it here.](https://tio.run/##nVBNi8IwEL3vr5gNCAmS@rGwh43WX6CXPW4VsjFKtE5Lmgoi/e110vaoFyFDePPeY@bNSV@1LEqLp/25NbmuKlhrh/cPAIfB@oM2FjYRAvwG7/AIhhMDKBQ1Gyp6VdDBGdgAwhJalOl90PoljubpdMXIvsuQ/bDuU4fCc4VSplPlx1GzmEXN5DPLMoSdlLIT95hQNAnlbag9gh8zkEw1reqnl/V/TtOHJa6F28OFMvB@h78taDEEuFXBXpKiDklJVMiRY2L4THRZnvKvmeicv@38etv5LYbLN@0D)
```
n->{ // Method with integer parameter and String return-type
String r= // Result-String, starting at:
n%2>0? // If the input is odd:
" ^\n" // Start the result at " ^" + new-line
: // Else (the input is even):
" ^\n"; // Start the result at " ^" + new-line
for(;n-->0; // Loop the input amount of times
r+=n%2<1? // If the current row is even:
" /!\\\n ^---\n" // Append the result-String with " /!\" + new-line
// " ^---" + new-line
: // Else (the current row is odd):
"/!\\\n---^\n" // Append the result-String with "/!\" + new-line
// "---^" + new-line
); // End of loop
return r // Return the result-String
+" -"; // + " -"
} // End of method
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~70~~ ~~68~~ 60 bytes
*thanks to @MartinEnder for -8 bytes*
```
.+
$*
r`11
21
1
¶ /!\¶ ^---
2
¶/!\¶---^
^¶( *)
$1 ^$&
$
¶ -
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYurKMHQkMvIkMuQ69A2BQV9xRggFaerq8tlBBQAc4GcOK64Q9s0FLQ0uVQMFeJU1LhUQKp1//83AwA "Retina – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 73 bytes
```
lambda n:n%2*' '+' ^%s\n -'%(-~n/2*r"""
/!\
---^
/!\
^---""")[n%2*9:]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk/VSEtdQUFdW10hTrU4Jk9BV11VQ7cuT99Iq0hJSYlLXzGGS1dXN45LQQHEVIgDcoDimtEgjZZWsf8LijLzShTSNCw1/wMA "Python 2 – Try It Online")
Golfing [TFeld's solution](https://codegolf.stackexchange.com/a/148486/20260).
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 25 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
^¶ -”.∫2%«I"X¬ΒNN┘y7¹‘∆ž
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJTVFJUI2JTIwLSV1MjAxRC4ldTIyMkIyJTI1JUFCSSUyMlglQUMldTAzOTJOTiV1MjUxOHk3JUI5JXUyMDE4JXUyMjA2JXUwMTdF,inputs=Mw__)
[Answer]
# [Python 2](https://docs.python.org/2/), 100 bytes
```
lambda n:n%2*' '+' ^\n'+'\n'.join(['/!\\\n---^',' /!\\\n ^---'][i%2]for i in range(n,0,-1))+'\n -'
```
[Try it online!](https://tio.run/##JYxLCgIxEESv0i6GTjTxk40geJLpCUQ02qKVIczG08eImype8aj5szwKQstnaa/0vlwT4YQhrJmIN0xR0KvH9lkUZuTdSkTgvY/suvNHin3gadQhTLlUUlJQTbjfDNze@YO1vxPy3OaqWCibo21f "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 87 bytes
```
f(n){for(puts(n%2?" ^":" ^");n;)puts(n--%2?" /!\\\n ^---":"/!\\\n---^");puts(" -");}
```
[Try it online!](https://tio.run/##JY3BCgIxDETv@YpYEBLWIHoRrOKPlAUpVHIwiq6nZb@9ZtvLMGHeZLI8cq61kPFcXh96/6Yv2fZ4C4g4hnNw4WiReyDSo/0mpWQ4iogz/XK/sg0MKG6X@ryrEcMM/g3VJtTYbJN1T6@HqJdT1GHgQsq7XvcyLNDRCn8 "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 82 bytes
```
def f(n):x=n%2;print' '*x*2,'^'+(-~n/2*"\n/!\\\n---^\n /!\\\n ^---")[x*9:]+'\n -'
```
[Try it online!](https://tio.run/##JcixDkAwEADQXzkSubZcGt0QX@J0omE5IoZa/Ho1Mb53Pvd2iEtpWQMEJbqPo1RuOK9dbgQ00bgGPdaKXrHOlCy2YGYhIs8C8At8dqmnaLp@rjEHYQqq1ekD "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 167 bytes
```
def f(n):
g=[[" "]*5for _ in' '*-~n];a=["^","/!\\","---"]
for i in range(n):
for r,R in zip(a,g[i*2:]):R[(i-n)%2*2+(r>"]"):]=r
g[-2][1]="^";g[-1][1]="-";return g
```
[Try it online!](https://tio.run/##JU9BCsIwEDy3r4gLYhIbpZFeWuIjek2jFGxjBLch1IMe/HpM7V5mZxhmGP@e7xOeYrwNIxkpsjrPrNIaCBhejVMgV@JwR8iOiy@aplcaLlDAcdN1CYQQYPJs8bnkI6FHO6wpfzEU7SJ/nKd9YbXjsjasbjV1AtlWcrmn4QwGWG1USM1aSKNLo1JHk0i5EgFNGOZXQGKjDw5nCh3C4TE5pM/eU1j/Ig2oWLr4Aw "Python 3 – Try It Online")
-4 bytes thanks to Mr. Xcoder
-1 byte thanks to Jonathan Frech
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
É·>'^ú¶•2Ÿ§'vôÅ•"-
^\!/"ÅвJ12ôIL<Rè`„ -J
```
[Try it online](https://tio.run/##AUgAt/9vc2FiaWX//8OJwrc@J17DusK24oCiMsOCxbjCpyd2w7TDheKAoiItCiBeXCEvIsOF0LJKMTLDtElMPFLDqGDigJ4gLUr//zM) or [verify some more test cases](https://tio.run/##yy9OTMpM/W/qquSZV1BaYqWgZO9ny6XkX1oC4en8P9x5aLudetzhXYe2PWpYZHS46eiOQ8vVyw5vOdwK5CvpcinExSjqKx1uvbDJy9Do8BY/H5ugwysSHjXMU9D1@q9zaJv9fwA).
**Minor 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative:**
```
É·ðú„^
•e
QΣœKΔ•"- ^
\!/"ÅвJ8₂‚£ILRè»…
-J
```
[Try it online](https://tio.run/##AU0Asv9vc2FiaWX//8OJwrfDsMO64oCeXgrigKJlClHOo8WTS86U4oCiIi0gXgpcIS8iw4XQsko44oKC4oCawqNJTFLDqMK74oCmCiAtSv//Mw) or [verify some more test cases](https://tio.run/##yy9OTMpM/W/qquSZV1BaYqWgZO9ny6XkX1oC4en8P9x5aPvhDYd3PWqYF8f1qGFRKlfgucVHJ3ufmwLkKOkqxHHFKOorHW69sMnL4lFT06OGWYcW@/kEHV5xaPejhmVcCrpe/3UObbP/DwA).
**Explanation:**
```
É # Check if the (implicit) input-integer is odd (1 if odd; 0 if even)
· # Double that (2 if odd; 0 if even)
> # Increase it by 1 (3 if odd; 1 if even)
'^ '# Push string "^"
√∫ # Pad it with the input%2*2+1 amount of leading spaces
¶ # Push a newline character "\n"
•2Ÿ§'vôÅ• '# Push compressed integer 193455283599881836
"-\n ^\!/"√Ö–≤ # Convert it to custom base-"-\n ^\!/"
# (which converts it to base-length and indices it into the string)
J # Join this list of characters together to a single string:
# " /!\\n ^---\n/!\\n---^\n"
12ô # Split it into parts of size 12: [" /!\\n ^---\n","/!\\n---^\n"]
IL # Push a list in the range [1, input]
< # Decrease each by 1 to make the range [0, input)
R # Reverse it to range (input, 0]
è # Index each into the pair of strings (0-based and modulair)
` # Pop and push all strings separated to the stack
„ - # Push string " -"
J # Join all strings on the stack together
# (and output the result implicitly)
É· # Same as above
√∞√∫ # Pad a space character with that many spaces
„^\n # Push string "^\n"
•e\nQΣœKΔ• # Push integer 11080812880919929
"- ^\n\!/"√Ö–≤J # Same as above: "/!\\n---^ /!\\n ^---"
8₂‚ # Push 8 and 26 paired together: [8,26]
£ # Split the string into parts of that size: ["/!\\n---^"," /!\\n ^---"]
IL # Push a list in the range [1, input]
R # Reverse it to range [input, 1]
è # Index each into the pair of strings (0-based and modulair)
» # Join this list with newline delimiter
…\n - # Push string "\n -"
J # Join all strings on the stack together
# (and output the result implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•2Ÿ§'vôÅ•` is `193455283599881836` and `•e\nQΣœKΔ•` is `11080812880919929`.
[The compressed ASCII-string was generation with this 05AB1E tip.](https://codegolf.stackexchange.com/a/120966/52210)
[Answer]
# [Ruby](https://www.ruby-lang.org), 97 94 bytes
```
puts " "*(a%2)+" ^";f=->n{puts""+["/!\\\n---^"," /!\\\n ^---"][n%2];(n>1)?f[n-1]:puts(" -")}
```
[Try It Online!](https://tio.run/##JYtLCoQwEAWv0j4QktFG43JEPUg@EBdZNuKMCxHPHhWXr6reus17joNp87L9fwQifFQsO12BAvo08CjHo4DKoimcc8LMAfWdvpPCDeCtlJ3vlYxGT8kKG/99fgrE0GdONvp8AQ)
I was unable to find a way to fit the entire thing in one function, so `f` is set to the lambda.
Based on [TotallyHuman](https://codegolf.stackexchange.com/users/68615/totallyhuman)'s Python answer.
]
|
[Question]
[
# Background
## The 1-2-3-Tribonacci Sequence
Imagine for a second that you could make a fibonacci sequence by replacing the standard iteration formula with the following:

Basically, instead of summing the last two to get the next, you sum the last three. This is the basis for the 1-2-3-Tribonacci sequence.
## Brown's Criterion
Brown's Criterion state that you may represent any integer value as a sum of members of a sequence provided that:
1. 
2. For all `n` greater than 1, 
## What this means for the challenge
You may describe any positive integer as a sum of members of the 1-2-3-Tribonacci sequence formed by the following initial conditions:

This is known as, for every value in this sequence, the ratio between terms is never greater than 2 (the ratio averages out at about 1.839).
## How to write in this numerical representation system
Let's say that you use a little-endian representation. Line up members of the sequence like so:
```
1 2 3 6 11 20 37 68
```
Then, you take your number to be represented (for our tests, let's say it's `63`) and find the values of the given 1-2-3-Tribonacci which sum to 63 **(using the largest values first!)**. If the number is part of the sum, put a 1 under it, 0 if not.
```
1 2 3 6 11 20 37 68
0 0 0 1 0 1 1 0
```
You may do this for any given integer - just verify that you use the largest values below your given input first!
# Definition (finally)
Write a program or function that will do the following given some positive integer input `n` (written in any standard base) between 1 and your language's maximum value:
1. Convert the value into the defined 1-2-3-Tribonacci's numerical representation.
2. Using this binary-like representation, and read it as if it were binary. This means that the digits stay the same, but what they mean changes.
3. Take this binary number and convert it into the base of the original number.
4. Output or return this new number.
However, as long as the output is valid, you needn't follow these steps. If you magically find some formula that is shorter (and mathematically equivalent), feel free to use it.
# Examples
Let the function `f` be the function described by the definition, and let `[]` represent steps taken (as little-endian, though it shouldn't matter) (you do not need to follow this process, this is just the process described):
```
>>> f(1)
[1]
[1]
[1]
1
>>> f(5)
[5]
[0, 1, 1]
[6]
6
>>> f(63)
[63]
[0, 0, 0, 1, 0, 1, 1]
[104]
104
```
[Answer]
## Javascript ~~117~~ 111 bytes
Thanks to @theonlygusti for helping golf off 5 bytes
```
x=>{r=0;a=[1,2,3];i=1;while(a[++i]<x)a[i+1]=a[i]+a[i-1]+a[i-2];for(;x;i--)if(x>=a[i]){r+=1<<i;x-=a[i]}return r}
```
## How It Works
First, the function generates all tribonacci numbers until it finds one greater than the input
```
a=[1,2,3];i=1;for(;a[++i]<x;)a[i+1]=a[i]+a[i-1]+a[i-2];
```
Next, it reverse searches the list of numbers. If a number is less than the input, it adds 2^(index of that number) to the return value and reduces the input by that number.
```
for(;x;i--)if(x>=a[i]){r+=1<<i;x-=a[i]}
```
Finally it returns the result.
[Try it Online](https://tio.run/#L27ml)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~110~~ 102 bytes
-3 bytes thanks to Rod (neat trick for casting boolean `i` to an int with `+i` so the repr ``+i`` works)
```
n=input()
x=[3,2,1]
r=''
while x[0]<n:x=[sum(x[:3])]+x
for v in x:i=n>=v;n-=v*i;r+=`+i`
print int(r,2)
```
**[Try it online!](https://tio.run/nexus/python2#DcrBDsIgDADQe7@C20Aw0ZF4YHY/Qkh20dhE61IZ69/jzu91RuJ1q9aBYo5hDNcCgsMA@4veD6P5Uu6cDvttH6s5xeKKV3h@xTRDbDQR8oxt4jO2E03icfG0wCrE9QjVShhd77f4Bw)**
[Answer]
## JavaScript (ES6), ~~97~~ 93 bytes
Here, we are using `reduce()` on a recursive function. We assume that the output is 31-bit (which is the largest unsigned quantity that JS can easily work with for bitwise operations anyway).
```
n=>[...Array(x=31)].reduce(p=>(c=(F=k=>k<4?k:F(--k)+F(--k)+F(--k))(x--))>n?p:(n-=c,p|1<<x),0)
```
Performance wise, this is clearly not very efficient.
For the curious:
* The ratio between the number of calls to `F()` for N+1 `reduce()` iterations vs N iterations quickly converges towards the Tribonacci Constant (≈ 1.83929). Therefore, each additional bit in the output costs approximately twice as much time as the previous one.
* With 31 bits, the `F()` function is called a good 124 million times.
### Test
*NB:* This may take 1 or 2 seconds to complete.
```
let f =
n=>[...Array(x=31)].reduce(p=>(c=(F=k=>k<4?k:F(--k)+F(--k)+F(--k))(x--))>n?p:(n-=c,p|1<<x),0)
console.log(f(63))
```
[Answer]
# Mathematica, ~~78~~ 74 bytes
```
Fold[#+##&,#~NumberDecompose~Reverse@LinearRecurrence[{1,1,1},{1,2,3},#]]&
```
`LinearRecurrence[{1,1,1},{1,2,3},#]` generates a list, of length equal to the input, of the 1-2-3 tribonacci numbers. (The `{1,1,1}` represents the sum of the previous three terms, while `{1,2,3}` are the initial values.) Then `#~NumberDecompose~` finds the greediest way to write the input as a sum of elements of the list (this is the same function that would decompose a monetary amount into multiples of the available currencies, for example). Finally, `Fold[#+##&,...]` converts the resulting binary list into a (base-10) integer.
Previous submission:
```
Fold[#+##&,#~NumberDecompose~Reverse@Array[If[#<4,#,Tr[#0/@(#-Range@3)]]&,#]]&
```
As is often the case (though not above), this golfed version is super slow on inputs larger than 20 or so, because it generates (with non-optimized recursion) a list of tribs whose length is the input; replacing the final `#` by a more reasonable bound like `Round[2Log@#+1]` results in much better performance.
[Answer]
## Haskell, 95 bytes
```
(a!b)c=a:(b!c)(a+b+c)
e#(r,c)|c-e<0=(2*r,c)|1<2=(2*r+1,c-e)
f n=fst$foldr(#)(0,n)$take n$(1!2)3
```
Usage example: `f 63` -> `104`. [Try it online!](https://tio.run/nexus/haskell#HclBDsIgEEDRfU8xpCxmBJNCExemHGYYIWnU0SBL746mu//yB7LJJImvmI0QsstOaCozNi/0lXPZloTxdChs8WgX/H/QVEFT/XRbX49bw5lw8Uq2872AWgwm0jqevCskeLddO1iocFnHDw "Haskell – TIO Nexus").
How it works: `!` builds the 1-2-3-Tribonacci sequence. Given `1`, `2` and `3` as the start parameters, we take the first `n` elements of the sequence. Then we fold from the right function `#` which subtracts the next element `e` from `n` and sets the bit in the return value `r` if `e` is needed or lets the bit unset. Setting the bit is doubling `r` and adding `1`, letting it unset is just doubling.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wik/Code-page)
```
S=³
3RUµḣ3S;µ<³Ạµ¿µŒPÇÐfṀe@ЀµḄ
```
**[Try it online!](https://tio.run/nexus/jelly#ATsAxP//Uz3CswozUlXCteG4ozNTO8K1PMKz4bqgwrXCv8K1xZJQw4fDkGbhuYBlQMOQ4oKswrXhuIT///82Mw "Jelly – TIO Nexus")**
I'm almost certain there is a MUCH shorter way to achieve this in Jelly.
### How?
```
S=³ - Link 1, compare sum to input: list
S - sum
³ - 3rd command line argument which is 1st program argument.
= - equal?
3RUµḣ3S;µ<³Ạµ¿µŒPÇÐfṀe@ЀµḄ - Main link: n
3RU - range(3) upended -> [3,2,1]
µ µ µ¿ - while
<³ - less than input (vectorises)
Ạ - all?
ḣ3S; - head(3), sum, and concatenate
[3,2,1] -> [6,3,2,1] -> [11,6,3,2,1] -> ...
µ - monadic chain separation, call the result x
ŒP - power set of x - e.g. for [6,3,2,1] -> [[],[6],[3],[2],[1],[6,3],[6,2],[6,1],[3,2],[3,1],[2,1],[6,3,2],[6,3,1],[6,2,1],[3,2,1],[6,3,2,1]]
Ðf - filter keep
Ç - last link (1) as a monad (those that sum to the input)
Ṁ - maximum (e.g. an input of 63 would yield [[37,20,6],[37,20,3,2,1]], the maximum of which is [37,20,6], the one with the largest numbers used)
µ - monadic chain separation (to have x as the right argument below)
e@Ѐ - exists in with reversed arguments mapped over x (e.g. [37,20,6] with x = [68,37,20,11,6,3,2,1] yields [0,1,1,0,1,0,0,0])
Ḅ - convert from binary to integer.
```
[Answer]
# [Perl 6](http://perl6.org/), ~~93~~ 91 bytes
*-2 bytes thanks to b2gills*
```
{my@f=1,2,3,*+*+*...*>$^n;sum @f».&{$_~~any first *.sum==$n,@f.combinations}Z*(2 X**^∞)}
```
### How it works
* First, it generates the 1-2-3-Tribonacci sequence up to the first element larger than the input:
```
my @f = 1, 2, 3, *+*+* ... * > $^n;
```
* Based on that it finds the subset of the sequence which adds up to the input:
```
first *.sum==$n, @f.combinations
```
* Based on that it constructs a list of booleans specifying whether each element of the sequence is part of the sum:
```
@f».&{$_~~any ...}
```
* And finally it interprets that list of True=1, False=0 values as base 2 and returns it as a (base 10) number:
```
sum ... Z* (2 X** ^∞)
```
[Answer]
## JavaScript (ES6), ~~61~~ 60 bytes
```
n=>(g=(x,y,z)=>(n>x&&g(y,z,x+y+z)*2)+!(n<x||![n-=x]))(1,2,3)
```
Calculates the 1-2-3-Tribonacci numbers until it reaches the original number, then as the recursion unwinds, tries to subtract each one in turn, doubling the result as it goes.
Edit: Saved 1 byte thanks to @Arnauld.
[Answer]
## Batch, ~~151~~ ~~148~~ 145 bytes
```
@set/ar=0,n=%1
@call:c 3 2 1
@echo %r%
@exit/b
:c
@set/as=%1+%2+%3
@if %n% gtr %3 call:c %s% %*
@set/ar*=2
@if %n% geq %3 set/an-=%3,r+=1
```
Port of my JavaScript answer. Edit: Saved 3 bytes by passing my subroutine arguments in reverse order and another 3 bytes by using individual `@`s on each line instead of `@echo off`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ ~~18~~ 17 bytes
```
Ḣx3+
BÇL¡2ị
²Ç€»ċ
```
[Try it online!](https://tio.run/nexus/jelly#@/9wx6IKY20up8PtPocWGj3c3c11aNPh9kdNaw7tPtL9/@geMNv9/39DHQVTHQUzYwA "Jelly – TIO Nexus")
### Background
Instead of trying to convert an integer to 1,2,3-Tribonacci base, then from binary to integer, we'll do the opposite: convert integers to binary, then from 1,2,3-Trionacci base to integer, and return the highest one that matches the input. This is easily accomplished.
We'll exemplify the process for input **63**, in particular the step where **104** is tested. In binary, from most significant to least significant digit, **104** is equal to
```
1 1 0 1 0 0 0
37 20 11 6 3 2 1
```
where the second row represents the positional values of those digits.
We can extend the 1,2,3-Tribonacci sequence to the right, observing that the added digits comply with the same recursive formula. For three mre digits, this gives
```
1 1 0 1 0 0 0 0 0 0
37 20 11 6 3 2 1 0 1 0
```
Now, to compute the value of the base 1,2,3-Tribonacci number, we can make use of the recursive formula. Since each number is the sum of the three numbers to its right (in the table above), we can remove the first digit and add this to the first three digits of the remaining array. After **7** steps, which is equal to the number of binary digits of **104**, we rare left with only three digits.
```
1 1 0 1 0 0 0 0 0 0
37 20 11 6 3 2 1 0 1 0
2 1 2 0 0 0 0 0 0
20 11 6 3 2 1 0 1 0
3 4 2 0 0 0 0 0
11 6 3 2 1 0 1 0
7 5 3 0 0 0 0
6 3 2 1 0 1 0
12 10 7 0 0 0
3 2 1 0 1 0
22 19 12 0 0
2 1 0 1 0
41 34 22 0
1 0 1 0
75 63 41
0 1 0
```
Now, since the first and last remaining digit both have positional value **0**, the result is the middle digit, i.e, **63**.
### How it works
```
²Ç€»ċ Main link. Argument: n
² Yield n². Since 1.839² = 3.381921 > 2, the range [1, ..., n²] will contain
the answer. Better bounds, at the cost of additional bytes are possible.
Ç€ Map the the second helper link over [1, ..., n²].
» Take the maximum of n and each result.
ċ Count the occurrences of n.
BÇL¡2ị Second helper link. Left argument: k. Right argument: n
B Convert k to binary. Let's call the result A.
L Length; count the number of binary digits. Let's call the result l.
Ç ¡ Apply the first helper link l times to A.
2ị Retrieve the second element.
Ḣ×3+ First helper link. Argument: A (array)
Ḣ Head; pop and yield the first element of A.
x3 Repeat it thrice.
+ Add the result, component by component, to the beheaded A.
```
[Answer]
# Jelly ([fork](https://github.com/miles-cg/jelly/tree/frobenius)), ~~17~~ 16 bytes
```
ḣ3S;µ¡
3RṚdzæFṪḄ
```
Saved 1 byte thanks to @Dennis who golfed it without even running it.
This relies on a fork of Jelly where I am disappointingly still working on implementing an efficient Frobenius solve atom. For those who are interested, I would like to match Mathematica's speed in `FrobeniusSolve` and luckily there is an explanation of their [method](https://mathematica.stackexchange.com/questions/114308/frobeniussolve-how-does-it-work) in the paper "Making Change and Finding Repfigits: Balancing a Knapsack" by Daniel Lichtblau.
## Explanation
```
ḣ3S;µ¡ Helper link. Input: a list
µ Create monadic chain
ḣ3 Take the first 3 items
S Sum
; Prepend to the list
¡ Repeat it n (initial argument from main) times
3RṚdzæFṪḄ Main link. Input: integer n
3 The constant 3
R Range. Makes [1, 2, 3]
Ṛ Reverse. Makes [3, 2, 1]
Ç Call the helper link on that list.
Generates the first (n+3) 123-Tribonacci values in reverse
³ Get n
æF Frobenius solve for n using the first n 123-Tribonacci values in reverse
Ṫ Tail. Take the last value. The results of Frobenius solve are ordered
where the last result uses the least
Ḅ Unbinary. Convert digits from base 2 to base 10
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~110~~ 102 bytes
```
?se1sa2sb3sc_1sf[laddSdlbdsalcdsb++sclf1+sfle>y]dsyx0sk[lk2lf^+skler-se]sr[Lddle!<rlf1-dsf0!>z]dszxlkp
```
Well, seems like great minds *do* think alike. Apparently, the algorithm I came up with to get around the limitations of `dc` is coincidentally the exact same one used in @LliwTelrac's answer. Interesting.
[Try it online!](https://tio.run/nexus/dc#DcqxCsIwFAXQb@kcAk3FTeoPuDmGKsl7Lwi5qOQubf/bOfbMp19pgWliPlGegSUiqd4VWZkgyuwcBSU4Fti8LcptHVkj6oTycKyw5mkLW7ypwoZLO7ZXlnGY96PvK@q39/Pv/fGS5GV/ "dc – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), 93 bytes
```
n=input();y=k=n*n
while y>n:
x=y=z=0;k-=1
for t in bin(k):x+=t=='1';x,y,z=y+x,z+x,x
print k
```
This is a port of [my Jelly answer](https://codegolf.stackexchange.com/a/109540/12012).
[Try it online!](https://tio.run/nexus/python2#HY7NDoIwEAbP7FPsrSA1kRg9tPl8F35qbIoLITW2vDyChzlOZvppcFBKbQIv8yeWlc0IkJPQ9@VHx/khhjghY8XFhjMa4ue0cGQv3HkpQ2VSjQioRtmks16R66TXnUTz4iVy2PYC0aHJoTWab5rvV0PFP8rgsX13Q2tYqHDJ9dzvX9sP "Python 2 – TIO Nexus")
[Answer]
# bash + BSD utilities (OS X, etc.), 53 bytes
```
jot $[2#$1**4]|egrep -v '[2-9]|11(1|$)'|sed $[2#$1]!d
```
# bash + GNU utilities (works under BSD also), 59 bytes
```
seq -f2o%.fp $[2#$1**2]|dc|egrep -v '11(1|$)'|sed $[2#$1]!d
```
Input and output in both the above are in binary.
---
[Try out the GNU version at TIO.](https://tio.run/nexus/bash#@1@cWqigm2aUr6qXVqCgEm2krGKopWUUW5OSXJOaXpRaoKBbpqBuaKhhWKOiqV5TnJoCVRSrmPL//39DMPial6@bnJickQoA) (The example linked to demonstrates input of 111111, which is 63 in binary, and output of 1101000, which is 104 in binary.)
I don't think TIO offers a BSD option, but if you have a Mac available, you can try them both out there. (The 59-byte program is *much* faster than the 53-byte program.)
---
Unfortunately, `seq` can't simply be dropped into the BSD solution in place of `jot`, since the output format for `seq` is different for outputs above 999999. (This starts being a problem for inputs around 32, since 32^4 > 1000000.)
You can replace `jot` above with `seq -f%.f` to get this to work with GNU utilities, but for the same 59 bytes, you can use the GNU solution above, which is much faster.
]
|
[Question]
[
# Challenge
Create the shortest program that meets the requirements
## Requirements
1. The code must generate a 5x5 grid of 0s, like so:
```
00000
00000
00000
00000
00000
```
2. The code must accept an input (column, row, character). The grid must change accordingly:
Start:
```
00000
00000
00000
00000
00000
```
Input:
```
(2,5,*)
```
Output:
```
0*000
00000
00000
00000
00000
```
(Note: the bottom-left corner is position 1,1.)
3. The program must return an error message other than the grid if the row/column input is not 1,2,3,4, or 5. This can be any message of your choice (as long as it's not the grid), so `0` is an acceptable error-output.
4. The program must work with all printable ASCII characters (of a US keyboard).
## THE WINNER
The winner will be the person who has the shortest code and fulfills all requirements. If more than one answer works and has the same (shortest) length, the person who answered first will be the winner.
[Answer]
# [Dyalog APL](https://www.dyalog.com/), ~~17~~ ~~13~~ 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Prompts for an enclosed array containing (row, column) and then for a character. Gives INDEX ERROR on faulty input.
```
⊖⍞@⎕⊢5 5⍴0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdvSgz5f@jrmmPeuc5POqb@qhrkamC6aPeLQYgyf8KYABSw/Woq8lIwZRLCwA "APL (Dyalog Unicode) – Try It Online")
`⊖` flip upside-down the result of
`⍞` inputted-character
`@` replacing the content **at** position
`⎕` evaluated-input (enclosed row, column)
`⊢` of
`5 5⍴` 5×5 array of
`0` zeros
[Answer]
## Ruby, ~~157~~ 149 bytes
```
g=(1..5).map{[0]*5}
loop{puts g.map(&:join).join ?\n
x=gets.match /\((.),(.),(.)\)/
a,b=x[1].hex,x[2].hex
1/0 if a<1||a>5||b<1||b>5
g[5-b][a-1]=x[3]}
```
Error on malformed input or out of bound position
Thanks to ConorO'Brien (8 bytes) and afuous (2 bytes) for helping saving bytes
[Answer]
## Batch, 199 bytes
```
@echo off
if %1 gtr 0 if %1 lss 6 if %2 gtr 0 if %2 lss 6 goto g
if
:g
for /l %%j in (5,1,-1)do call:l %* %%j
exit/b
:l
set s=000000
if %2==%2 call set s=%%s:~0,%1%%%3%%s:~%1%%
echo %s:~1,5%
```
Errors out if the position is out of range.
[Answer]
# PHP, ~~111~~ ~~100~~ 97 bytes
```
$s=str_repeat("00000\n",5);$s[($x=($a=$argv)[1])+29-6*$y=$a[2]]=$a[3];echo$x&&$y&&$x<6&$y<6?$s:E;
```
prints `E` if row/column out of range.
Run with `php -r <code> <row> <column> <character>`
[Answer]
## Python, 66 bytes
```
lambda a,b,n,l='00000\n':6>b>0<a<6and(5-b)*l+l[:a-1]+n+l[a:]+~-b*l
```
[Answer]
# Dyalog APL, ~~24~~ ~~20~~ 18 bytes
Saved 4 bytes thanks to Zgarb! Saved 2 bytes thanks to Adam!
```
a←5 5⍴0⋄a[⊂⎕]←⍞⋄⊖a
```
Prompts for input. See below for an explanation.
---
## 20 bytes
```
{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}
```
Assign to a function and call it `y x f 'c'`. E.g.:
```
f←{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}
5 2 f '*'
0 * 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
6 6 f '*'
INDEX ERROR
←{a←5 5⍴0 ⋄ a[⊂⍺]←⍵ ⋄ ⊖a}
∧
0 0 f '*'
INDEX ERROR
←{a←5 5⍴0 ⋄ a[⊂⍺]←⍵ ⋄ ⊖a}
∧
```
## Explanation
```
{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}
```
`{...}` is a function with left argument `⍺` and right argument `⍵`. `⋄` separates statements, so there are three statements:
```
a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a
```
The first statement `a←5 5⍴0` sets `a` to a `5` by `5` grid of `0`s.
The second statement sets the member at coordinates dictated by `⍺` to `⍵` (that is, the character).
Finally, we perform `⊖` on `a` and return that, yielding the firsts of `a` reversed.
[Answer]
## JavaScript (ES6), ~~73~~ 76 bytes
Throws a `TypeError` if the column or the row is out of range.
```
(c,r,C,a=[...`00000
`.repeat(5)])=>(a[29+c-r*6]=C,c<1|r<1|c>5|r>5||a).join``
```
### Demo
```
let f =
(c,r,C,a=[...`00000
`.repeat(5)])=>(a[29+c-r*6]=C,c<1|r<1|c>5|r>5||a).join``
console.log(f(2,5,'*'));
```
[Answer]
# C#, 199 Bytes
Based on Pete Arden's answer
```
string g(int c, int r, char a){if(c<1|c>5|r<1|r>5)return "Index Error";var b="00000";var d=new[]{b,b,b,b,b};c--;d[r-1]=new string('0',c)+a+new string('0',4-c);return string.Join("\r\n",d.Reverse());}
```
Ungolfed:
```
public static string G(int c, int r, char a)
{
if (c < 1 || c > 5 || r < 1 || r > 5) return "Index Error"; // Check it's not out of range
var b = "00000";
var d = new [] { b, b, b, b, b }; // Generate display box, and fill with the default character
c--; // Convert the X to a 0 based index
d[r - 1] = new string('0',c) + a + new string('0',4-c); // Replace the array's entry in y coordinate with a new string containing the new character
return string.Join("\r\n", d.Reverse()); // Reverse the array (so it's the right way up), then convert to a single string
}
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~27~~ 22 bytes
Returns no grid when row/column > 5.
```
‚6‹Pi25L²<5*¹+Q5äR»1³‡
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCaNuKAuVBpMjVMwrI8NSrCuStRNcOkUsK7McKz4oCh&input=Mgo1Cio)
**Previous version**
```
‚6‹Pi26G¾5²<*¹+NQi\³}})5äR»
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
This feels way too long...
```
Ṫ0ẋ24¤;ṙÑs5UY
’ḅ5
Ṗḟ5R¤
-ÑÇ?
```
**[TryItOnline!](http://jelly.tryitonline.net/#code=4bmqMOG6izI0wqQ74bmZw5FzNVVZCuKAmeG4hTUK4bmW4bifNVLCpAotw5HDhz8&input=&args=WzUsMiwnKidd)**
### How?
```
Ṫ0ẋ24¤;ṙÑs5UY - Link 1, make grid: [row, column, character] e.g. [5,2,'*']
Ṫ - tail: character '*'
¤ - nilad followed by link(s) as a nilad
0 - zero
ẋ - repeated
24 - 24 times [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
; - concatenate: "000000000000000000000000*"
Ñ - call next link (2) as a monad 21
ṙ - rotate left by "000*000000000000000000000"
s5 - split into chunks of length 5 ["000*0","00000","00000","00000","00000"]
U - upend (reveres each) ["0*000","00000","00000","00000","00000"]
Y - join with line feeds 0*000
- implicit print 00000
00000
’ḅ5 - Link 2, position: [row, column] 00000
’ - decrement 00000
ḅ5 - convert from base 5
Ṗḟ5R¤ - Link 3, input error checking: [row, column, character]
Ṗ - pop: [row, column]
ḟ - filter out values in
5R¤ - range(5): [1,2,3,4,5] - any values not in this remain giving a truthy result
-ÑÇ? - Main link: [row, column, character]
? - ternary if:
Ç - last link (3) as a monad
- - -1 (if truthy - the error identification)
Ñ - next link (1) as a monad (if falsey - the grid)
```
[Answer]
# JavaScript (ES6), 89 bytes
```
f=(X,Y,Z,x=5,y=5)=>x+y>1?(x?X+x-6|Y-y?0:Z:`
`)+f(X,Y,Z,x?x-1:5,y-!x):X<1|X>5|Y<1|Y>5?e:""
```
Because I love recursion. Throws a `ReferenceError` on invalid coordinates.
[Answer]
**Mathematica, 38 bytes**
```
(x=Table[0,5,5];x[[-#2,#]]=#3;Grid@x)&
```
[Answer]
# Brain-Flak 415 Bytes
Includes +3 for `-c`
```
([][()()()]){{}}{}({}<(({}<(({})<>)<>>)<>)<>([((((()()()){}){}){}){}]{}<([((((()()()){}){}){}){}]{})>)(()()()()()){({}[()]<(({})){{}(<({}[()])>)}{}({}<(({})){{}(<({}[()])>)}{}>)>)}{}({}{}){<>{{}}<>{}}<>>)<>(()()()()()){({}[()]<(((((((((()()()){}){}){}){})))))((()()()()()){})>)}{}{}<>({}<()((((((()()()){}){}()){}){}()[{}])({})({})({})({}){}{}[((((()()()){}){}){}){}()]){({}[()]<<>({}<>)>)}{}<>{}>)<>{({}<>)<>}<>
```
[Try it Online!](http://brain-flak.tryitonline.net/#code=KFtdWygpKCkoKV0pe3t9fXt9KHt9PCgoe308KCh7fSk8Pik8Pj4pPD4pPD4oWygoKCgoKSgpKCkpe30pe30pe30pe31de308KFsoKCgoKCkoKSgpKXt9KXt9KXt9KXt9XXt9KT4pKCgpKCkoKSgpKCkpeyh7fVsoKV08KCh7fSkpe3t9KDwoe31bKCldKT4pfXt9KHt9PCgoe30pKXt7fSg8KHt9WygpXSk-KX17fT4pPil9e30oe317fSl7PD57e319PD57fX08Pj4pPD4oKCkoKSgpKCkoKSl7KHt9WygpXTwoKCgoKCgoKCgoKSgpKCkpe30pe30pe30pe30pKSkpKSgoKCkoKSgpKCkoKSl7fSk-KX17fXt9PD4oe308KCkoKCgoKCgoKSgpKCkpe30pe30oKSl7fSl7fSgpW3t9XSkoe30pKHt9KSh7fSkoe30pe317fVsoKCgoKCkoKSgpKXt9KXt9KXt9KXt9KCldKXsoe31bKCldPDw-KHt9PD4pPil9e308Pnt9Pik8Pnsoe308Pik8Pn08Pg&input=KjEz&args=LWM)
Takes the character to insert first, then the row then column without spaces.
Most of this is just error handling. Brain-Flak doesn't have a good way to check if values are in a range. For errors, it either outputs nothing, or just the character that was supposed to be inserted. Solving the actual problem only takes 211 bytes:
```
<>(()()()()()){({}[()]<(((((((((()()()){}){}){}){})))))((()()()()()){})>)}{}{}<>({}<()((((((()()()){}){}()){}){}()[{}])({})({})({})({}){}{}[((((()()()){}){}){}){}()]){({}[()]<<>({}<>)>)}{}<>{}>)<>{({}<>)<>}<>
```
[Answer]
# Excel VBA, 67 Bytes
Outputs to the range *A1:E5* on the activesheet of the vba project, exits with
>
> Run-time error '1004':
>
>
> Application-defined or object-defined error
>
>
>
when an invalid input is provided.
**Code:**
```
Sub a(c,r,x)
c=IIf(r<1Or c>5,-1,c)
[A1:E5]=0
Cells(6-r,c)=x
End Sub
```
**Usage:**
```
a 4,5,"#"
```
**Output** (from example above)**:**
```
A B C D E
1 0 0 0 # 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
```
[Answer]
# C#, 208 Bytes
Golfed:
```
string G(int c,int r,char a){if(c<1||c>5||r<1||r>5)return"Index Error";var b="00000";var d=new string[]{b,b,b,b,b};d[r-1]=d[r-1].Substring(0,c-1)+a+d[r-1].Substring(c);return string.Join("\r\n",d.Reverse());}
```
Ungolfed:
```
public string G(int c, int r, char a)
{
if (c < 1 || c > 5 || r < 1 || r > 5) return "Index Error";
var b = "00000";
var d = new string[] { b, b, b, b, b };
d[r - 1] = d[r - 1].Substring(0, c - 1) + a + d[r - 1].Substring(c);
return string.Join("\r\n", d.Reverse());
}
```
Testing:
```
Console.Write(G(6, 6, '*')); //Index Error
Console.Write(G(1, 4, '#'));
00000
#0000
00000
00000
00000
Console.Write(G(5, 5, '@'));
0000@
00000
00000
00000
00000
Console.Write(G(1, 1, '}'));
00000
00000
00000
00000
}0000
```
[Answer]
# WinDbg, 95 bytes
```
j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
```
Almost half of it just verifying the indexes are in range... Input is done by setting the psuedo-registers `$t0`, `$t1`, and `$t2` (where `$t2` holds the ascii value of the char to replace). For example, `(2,5,*)` like the example would be:
```
0:000> r$t0=2
0:000> r$t1=5
0:000> r$t2=2a
```
Prints `0` on error.
How it works:
```
j (0<(@$t0|@$t1)) & (6>@$t0) & (6>@$t1) * If $t0 and $t1 are both positive and less than 6
'
f 8<<16 L19 30; * Put 19 (0n25) '0's (ascii 30) at 2000000 (8<<16)
eb 2000018+@$t0-@$t1*5 @$t2; * Replace the specified cell with the new char
da /c5 8<<16 L19 * Print 19 (0n25) chars in rows of length 5
';
?0 * ...Else print 0
```
Sample Output:
```
0:000> r$t0=2
0:000> r$t1=5
0:000> r$t2=2a
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Filled 0x19 bytes
02000000 "0*000"
02000005 "00000"
0200000a "00000"
0200000f "00000"
02000014 "00000"
0:000> r$t0=-2
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Evaluate expression: 0 = 00000000
0:000> r$t0=4
0:000> r$t1=2
0:000> r$t2=23
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Filled 0x19 bytes
02000000 "00000"
02000005 "00000"
0200000a "00000"
0200000f "000#0"
02000014 "00000"
0:000> r$t1=f
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Evaluate expression: 0 = 00000000
```
[Answer]
## Haskell, 77 bytes
```
r=[1..5]
(x#y)c|x>0,x<6,y>0,y<6=unlines[[last$'0':[c|i==x,j==6-y]|i<-r]|j<-r]
```
Usage example:
```
*Main> putStr $ (2#5) '*'
0*000
00000
00000
00000
00000
```
If `x` and `y` are within range, outer and inner loop through `[1..5]` and take the char `c` if it hits the given `x` and `y` and a `0` otherwise. If `x` or `y` is not in range, a `Non-exhaustive patterns` exception is raised.
[Answer]
# Octave 49 bytes
```
@(c,r,s)char(accumarray([6-r c],s+0,[5 5],[],48))
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~53~~ 50 bytes
EDIT: Now that I know that I don't have to show the starting grid, I've swapped out the user inputs `_!_!_?` for command line parameters `::;`, saving 3 bytes.
```
[5|?@00000|]::;~(b>5)+(c>5)>1|_Xd\$LOCATE 6-c,b|?B
```
Original version: This halts between printing the 0-grid and taking the coordinates for the substitution, showing the 0-grid.
```
[5|?@00000|]_!_!_?~(b>5)+(c>5)>1|_Xd\$LOCATE 6-c,b|?B
```
Prints 5 strings of 5 `0`'s, asks user for 2 numerical inputs and 1 string input, checks if the numbers are < 5 and uses QBasic's `LOCATE` function to substitute the right character.
[Answer]
# Java, 99 bytes
```
(i,j,k)->{int[]b=new int[]{60,60,60,60,60};int[][]a=new int[][]{b,b,b,b,b};a[i-1][5-j]=k;return a;}
```
[Answer]
# Bash, 59 bytes
**Golfed**
```
printf '00000%0.s\n' {1..5}|sed "$1 s/./$3/$2"|grep -z "$3"
```
*$1*, *$2* - row, column, *$3* - replacement char, error is reported via exit code
**Test**
```
>./box 2 2 "*"
00000
0*000
00000
00000
00000
>echo $?
0
>./box 6 2 '*'
>echo $?
1
```
[Answer]
# Vim, ~~60~~ ~~47~~ ~~42~~ 76 keystrokes
Input is in the format (on the first line):
```
25*
```
With the cursor starting at the beginning
```
"ax"bxx:if<C-r>a<1||<C-r>a>5||<C-r>b<1||<C-r>b>5
^
endif
6i0<ESC>Y5pG:norm <C-r>al<C-r>bkr<C-r>-
Hqqxjq5@qdd
```
If the input is invalid, then throws: `E492: Not an editor command: ^`
The cide that produces the output is only `42` bytes, but in order to create an error, my bytecount is drastically increased.
[Answer]
# Java 8, ~~194~~ 192 bytes
```
interface M{static void main(String[]a){String r="";int i=0,j,z=new Byte(a[0]),y=new Byte(a[1]);for(;++i<6;r+="\n")for(j=0;++j<6;r+=6-i==y&j==z?a[2]:0);System.out.print(z>0&z<7&y>0&y<7?r:0);}}
```
[Try it here with correct input.](https://tio.run/##Vc2xDoIwGATgV2k6mFaEVBIZrI1P4MSIHf5AMa3SYikkhvDsFcPkdvkulzMwQep6ZU3zjFHboHwLtUK3eQgQdI0mpxvUgbakDF7bRyWBzltEXmDMW@fJukNasIPhSaIvBfeJwHeL6a8zgq1qNiVFqhOMaabeI7wGAtVR0h0x/8YkvUKVyzOjvPwMQXWZG0PWr6eBeMqXJcaYx1PcfwE)
[Try it here with incorrect input.](https://tio.run/##Tc29DoIwFAXgV2kYSCs/qQ6QWK4k7k6MyNBgMa2hkFIxxfDsFePidE@@nJOr@MyTYRRa3R7eS22F6Xgr0OU9WW5li@ZB3lDPpcaVNVLf64aT9y8iA0HAtg2SQGMVL6DFC52dFZjXtCGx@4d9Q1g3GMyiSBYZMxEEVx2QLymgm6qfZokEcKECWEpeH5ojJaxykxV9OjxtOm6fLV5ONFyKPHTbdUVemm9rXb331Od@9wE)
This would be **~~116~~ 114 bytes** instead as function instead of full program:
```
(a,b,c)->{String r="";for(int i=0,j;++i<6;r+="\n")for(j=0;++j<6;r+=b==6-i&a==j?c:0);return a>0&a<7&b>0&b<7?r:"0";}
```
[Try it here.](https://tio.run/##dY/BasMwEETv/opFB2PVshGFxhBZyRc0lx7bHlaKE6Q6spHlQAn@dldOTOmll1125rHMWLxi0fWNs8evWbc4DPCKxt0SAONC40@oGzgsJ8Bb8MadQWfRAWQLAIr9ylREakriGAIGo@EADiTMGTLFNC12t5X0khBx6vz9j5GcWZHnpt4In0vy4QhdPCt5VO1DVVJuCpOilHavt5wK34TRO8AdT7GuUhW3qqu93xJOxDSLJUU/qjamWMNcO3OES6yWPVK8fwLStdf3EJpL2Y2h7KMVWpe5UmfPDF4YkCdC783@5TiD6g83JdP8Aw)
**Explanation:**
```
interface M{ // Class
static void main(String[]a){// Mandatory main-method
String r=""; // Result-String, starting empty
int i=0,j, // Index-integers
z=new Byte(a[0]), // First input converted to integer
y=new Byte(a[1]); // Second input converted to integer
for(;++i<6; // Loop (1) from 1 to 6 (inclusive)
r+="\n") // After every iteration: Append a new-line to the result
for(j=0;++j<6; // Inner loop (2) from 1 to 6 (inclusive)
r+=6-i==y // If the second input equals `6-1`,
&j==z? // and the first input equals `j`:
a[2] // Append the third input to the result-String
: // Else:
0 // Append a zero to the result-String
); // End of inner loop (2)
// End of inner loop (1) (implicit / single-line body)
System.out.print( // Print:
z>0&z<7&y>0&y<7? // If the coordinates are valid (1-6):
r // Print the result `r`
: // Else:
0); // Print 0 as error instead
} // End of main-method
} // End of class
```
]
|
[Question]
[
A pristine program is a program that does not have any errors itself but will error if you modify it by removing any contiguous substring other than the entire program.
A crystalline program is sort of the opposite. It is a program which doesn't have any errors itself but will error if you modify it by adding any 1 character anywhere. We call these crystalline because adding an impurity will cause it to break.
Now a true crystalline program is quite hard to come by so in this challenge we will be just trying to get as close as possible.
You will write a program which does not error and count the number of 1 character insertions that also *don't* error. If your program were crystalline this number would be 0. Also count the number of total 1 character insertions possible.
Your score is then:
\$
\dfrac{\mathrm{number\,\,of\,\,nonbreaking\,\,insertions}+2}{\mathrm{number\,\,of\,\,total\,\,insertions}}
\$
And your goal is to minimize this measure.
## Specifics
* Since different languages use different codepages and different ranges of characters, for this challenge a character is just any byte. The number of characters in your program is just the number of bytes it occupies and insertions are just that, the insertion of a new byte between any existing bytes or at the beginning and end of the program. You may select which characters you want to consider relevant for this challenge. When we insert any byte it will be one of those selected. The selected bytes must include:
+ At least 96 distinct characters
+ All characters used in your program
* For counting, insertions are considered different if they produce different programs. For example if your program is `ABBA`, then inserting a `B` after the first `A`, after the first `B` and after the second `B` all produce `ABBBA`, this counts as 1 insertion.
* A program errors if any of the following happens:
+ The compiler exits with a non-zero return code when run on the program.
+ The program exits with a non-zero return code when run.
+ The compiler produces non-empty output to STDERR when run on the program.
+ The program produces non-empty output to STDERR when run.If your programming language of choice always triggers some of these options, ignore those specific options and treat them as non-errors. If your programming language of choice doesn't have a compiler just ignore options that mention a compiler.
[Answer]
# [Ellipsis](https://esolangs.org/wiki/Ellipsis), score ‚Üí 0
The program consists of \$144 \times 8^n + 23\$ ASCII periods `.` for \$n \geq 0\$, and gets a perfect score (i.e. every possible insertion causes an error, and any of the 256 possible octets can be inserted). As such, this is a true crystalline program, in addition to scoring arbitrarily close to 0 (even though being a true crystalline program isn't required for a perfect score). Because the scoring gives an advantage to longer programs, you can get a score arbitrarily close to 0 by increasing *n*.
[Try it online!](https://tio.run/##KypNqvyfo2CroOXiGOKol55aUqxRnFpgm5eZo6mXk5qXXpJhzaWRE20Qq2@sqVeSH1@sYaGpl5yRWFSsl5tYUF1TUaNQUJSZV6KgWq5hp2CjoK2gq6CnoKMQrRCrGV0B0pEZW8sVH@/q5xIf/19vFIyCUTAKBhf4/x8A "Ruby – Try It Online") for \$n=1\$
The Ellipsis implementation is a compiler to brainfuck, so for this answer to be valid, the resulting brainfuck program needs to be executed via using a brainfuck compiler that will notice a syntax error (but there are plenty of those to choose from).
## Explanation
Ellipsis is a Lenguage variant, caring only about the length of the program it's compiling. It divides the length of the program by 3 (using floor division), interprets it as an octal number, and maps each octal digit to a brainfuck command.
If the program has length \$144 \times 8^n + 23\$, then floor-dividing this by 3 gives us \$48 \times 8^n + 7\$. In octal, that's `6`, followed by \$n\$ `0`s, followed by `7`; the brainfuck program is therefore of the form `[>…>]` with \$n\$ `>` characters. This is a valid brainfuck program that does nothing (it's a zero-iteration loop).
Any insertion will cause the program to have length \$144 \times 8^n + 24\$. Floor-dividing that by 3 will give us \$48 \times 8^n + 8\$, i.e. slightly higher, which will corrupt the `]` at the end of the program. For \$n=0\$, the program is now `]>` which is a syntax error due to the unmatched brackets. For larger \$n\$, the program is now `[` followed by \$n-1\$ `>` followed by `<>`; again, a syntax error due to unmatched brackets.
## How does this program work in other comparable languages?
* I couldn't find a valid [Unary](https://esolangs.org/wiki/Unary) interpreter; the web interpreter seems to have fallen off the Internet. As such, I couldn't verify its error behaviour. Essentially the same program as the Ellipsis can be written in Unary according to the spec, though.
* [Lenguage](https://esolangs.org/wiki/Lenguage) does *not* work (unless you consider a very slow memory leak to be an error because it will eventually exhaust all of memory); the Lenguage interpreter, upon finding an unmatched `[` or `]`, will go into an infinite loop trying to find the other, because (probably by mistake) the search for matching brackets wraps around the program. Eventually its count of unmatched brackets will overflow, but it's a bignum that uses memory proportional to the logarithm of its value, so this will take a very, very long time.
* The [Ecstatic](https://esolangs.org/wiki/Ecstatic) and [MGIFOS](https://esolangs.org/wiki/MGIFOS) implementations ignore invalid characters, so wouldn't notice insertions of things other than exclamation marks and asterisks respectively, and thus wouldn't score very well.
* [Unary Except Every Zero Is Replaced with the Title of This Programming Language or, Alternately, Is Replaced with the Smallest Counter-Example to the Goldbach Conjecture. Compilers and Interpreters Only Have to Implement the Former Option](https://esolangs.org/wiki/Unary_Except_Every_Zero_Is_Replaced_with_the_Title_of_This_Programming_Language_or,_Alternately,_Is_Replaced_with_the_Smallest_Counter-Example_to_the_Goldbach_Conjecture._Compilers_and_Interpreters_Only_Have_to_Implement_the_Former_Option) almost works (with a character being placed inside the title of the language reducing the count, something that could break the bracket matching), but would not notice a character being inserted between two copies of the title of the programming language, and as such couldn't get a perfect score.
## ais523, this looks like a challenge that could be cheesed by checksums, why didn't you write an answer in [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree)
A Pear Tree prints its main error message `a partridge` to standard *output*. Although this is an error by any normal definition, it doesn't fit the definition of an error in the question.
Additionally, the scoring favours longer programs. In A Pear Tree, the size of the checksum doesn't scale with the length of the program, so very long programs tend to have checksum collisions that prevent the normal checksumming behaviour of the language working correctly.
[Answer]
# Java `-encoding utf-16`, \$2^{-37}\$
Try to insert a single byte to UTF-16 file would resulting invalid encoding. So `javac` reports invalid utf-16 and refuse to compile the source code. That doesn't really matter what your source code is doing as long as it is a valid Java source code. Java supports at most 1GB source code. So maybe there are 256G different insertions, and the score should be 1/128G here. I'm not sure if this is a valid submission through.
---
# Java, \$2^{-37}\$
After thinking this twice. I just found out that you doesn't really need the `-encoding utf-16` compile parameter. Since `javac` will fail to compile your source code if it is larger that 1GB. So you simply need to submit a valid 1GB-1B program in Java. Any insertion would simply cause `javac` refuse to compile due to source code too long.
[Answer]
# [R](https://www.r-project.org/), score=0.000000000202, 2000000021 bytes
*Edit: corrected score (increased by 1.04-fold) thanks to JDL*
```
t(1)[nchar("aaaaaaaaaa...2000 million and 1 letter 'a's...aaaaaaaaaaa")-2e9,]
```
[Try it online with a smaller version of the program!](https://tio.run/##K/r/v0TDUDM6LzkjsUhDKREbUNLUNUo11In9r6yQWpGYW5CTqpCZV5xaVJKZn6dQkpFYopCSn1qcp16ikFSUmpgNFEpVSC6qLC5JzLHiKtHQJtJ4Li6c5oPNLUY3GIu5FVjdDQA "R – Try It Online")
Score calculated by hand so may contain (hopefully small) errors.
The longest allowed string in [R](https://www.r-project.org/) is `2^31-1` ≈ 2e9 bytes.
**Nonbreaking insertions:**
'#' at the start, position 4, or end (3 insertions), '!', '.', '+' or '-' at position 3 (4 insertions), '.' or 'i' at position 4 (2 insertions), any digit at positions 3 or 4 (20 insertions), whitespace (space or tab) at positions 0,3,4,6 or at positions 0,2,3,6,7,8 from the end (20 insertions), for a total of 49 insertions.
**Total possible insertions:**
All ASCII except 'a' (126 possible characters) at 2000000021 positions, plus 'a' at 21 positions, for a total of 2.52e11 possible insertions.
**Score:** `(49+2)/(126*2000000021+21)` = 2.02381e-10
---
We could also improve the score by gaming the relevant character set to exclude most of the nonbreaking characters: that is, excluding any of '#!.+-01345678i \t'. This leaves 4 nonbreaking insertions (by inserting one of '2' or '9' at positions 3 or 4), giving a score of `(4+2)/(110*2000000021+21)` = 2.727273e-11
---
Of course, an even more extreme (but boring) extension of this approach would be just the string `"aaaaaaaaaa...2147483647 letter 'a's...aaaaaaaaaa"`. Any single character added within the string will trigger an `Error in "aaa...aaa" : R character strings are limited to 2^31-1 bytes` error. Once we exclude whitespace and the '#' character from our character set, this would give a score of `2/(124*2147483649)` = 7.510666e-12.
[Answer]
# [Zsh](https://www.zsh.org/), score \$ \frac {2+0} {497} \approx 0.00402 \$ (1 byte)
```
;
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhYLrSE0lAsTBgA)
For the purposes of this answer, the "character set" of Zsh shall be all bytes except tab, newline, space, `#`, `-`, `:`, `w`, making the total number of characters 249. Since the program is only 1 byte, there are \$ 2 \* 249 - 1 = 497 \$ unique possible insertions.
Every one of these 497 insertions breaks the program - Zsh is particularly good at producing errors :)
Validator / auto-scoring program: [Attempt This Online!](https://ato.pxeger.com/run?1=TVFdToNAGIyPcIqRYgNpaAuVpA0W44uXMD7QZWlJVhaXxarISXypabyDZ_E0fkCb-LJ_3-x8M_N9Ht-r3eHwXevMW35Fw_578VOqvNDwBOI0rxIh5J6nWMGfYxFgEeI6RLiE76_MTMhEo5BcKamgpU6EmdFp86Y5nGY-nQZh2LpoTCPP0GCreAnv_vUZdg_5x99SmclC50XN0ZoGW9uNM3I7GN06UiZTIrUiy2awGe09ryG4HjpPJnTrtWe4qgjS4eNupXdyOhDEs5S_zIpaCARxpVOSTmVS5ziwb7FeY47xGLazZ_AYbgaIOxTcoaXB2U6SbfS-L0-tPsAoDO-uA3SiTrH0sshCa7Zm_89-cM6JTRC4mMHp9cOD7z4CI1T1RquEaciCkzckjMmaRtKloHcUW12KnJpRbFYUWSiV3KrkaRjgeaB_)
This scoring program can be modified to test almost any language if you [run it on TIO](https://tio.run/##RZDNboMwEITP@ClGKo2MEJBS5dCqobe@RNUDMuZHcmxqTEmLeHZqG6LcRt7Z9TfzN7TruupR0ggzCRrGwFTFU4ZEeYXDAWnmFFkIMWpk7e4gdusmOWsV@KU3v@i1anR5Ab92hleYOtMifCek1500SARe8HTEc46i6oZSCDXxipBaqNJAKq610jDKlILUVrG21KDzMU3z02nxjF2NGY3mPZKP6zdCb7nfwmLHTEnTyZFjIYHgZjsYxyTwFDUeGcKZPkRud0GxpwjuiVBkFf/J5CgE8mIwlQXzX1Nq0@B8xtE1E9LJNsXwtjmibRB5zsCXIm0vLtPrBmqfHc8e1BEttlfvDD/pLX@MPEK2UX@t/w), where a Zsh program can access the interpreters of any other language (which is not the case on ATO).
[Answer]
# [Python 3](https://docs.python.org/3/), score \$\frac{2}{6841}\approx0.00029\$
```
ConnectionRefusedError.with_traceback.__subclasshook__.__subclasshook__
```
[Try it online!](https://tio.run/##ZZHBTsMwDIbveQpLHNLSsmnjACraCcEDADc2VW3qrtG6pHLSsanqs5ckG2iIUyP/9vfZaneyjVb3k9AVwgo459OzVgqFlVq9Yd0brF6INM2@pG1yS4XAshC7WZ6bvhRtYUyj9S7P/xUmx5oZS7KLYsYqrMGisZGIMwZg6eQ/AHhE4WrhTWh7UvBBPTKfCOxsdp28Fq1Bxm4gbFtpNKC0BfT7ZcyZkezF4hqcVTQFGXfWcLsvukg0lFKhthgtH9LF8jGOR7hzGb9Zr9Mn4CPrSCobtaiiMBmnwCtprFTCQnlyZO6gUgWkV3xmcpOIJDxltoFaE0iQCs6aAPKbJIs4ZMJnAT2yK5kjelWnjZFli67JX@J@gPcdnMz0@yjcdTxzjp7jpy6Qg5tWWpWExU6q7V/AuYW/C02Y8bTmwzI5jPPhxzyuhshV4vlvgcfTNw "Python 3 – Try It Online") Footer verifies and scores the program.
The 96 bytes are codepoints from 27 to 127, without , `#`,`\\`,`,` and `;`. In theory I could append `.__subclasshook__` arbitrarily many times to get a lower score.
[Answer]
# [Ruby](https://www.ruby-lang.org/), score \$ \to 0 \$
```
<<abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVG9TsNADBZj7ik8NYlIjzZpC0Vhol1hYEQIpRenCaS59HLpD-pLMLN0gIcqT4MviQQLg2XL_n7O549PVS_2x1NP4brOFIJdobaZkDHCDYShPb-b3d7P5jYXqVyVX7VO-lenyzCMFiLGZJlmL6_5qpDlWlW63mx3-zf2_6ilf5-9d6pMpJEiQ7JyBpxzfzxx-Soqnd61SJULfXgceDDyYOrBkKrhkMKnCDzwJx4EVAdUB2NCUR5RHhN2ajD-5OmPFiuVXFZk9ICaF7hlxtCsyXMsljp1OUYihVjCISti3B2Y1T3ud7DYa6S-1UqFITT8uC55VlSotNMwPTA4l1lYxMxEIVEpqci7IfIKcxS6UTQNo4ibKG-mVGtVI7MUVqJGmO8EljqTBQ2SKK-wUayEVOY-Tifd7QDn4NOvXXQ-bZOV0KE8aHhd4lo-Jx50S7aXOR7b_AM)
Add arbitrarily more letters to `abcdefghijklmnopqrstuvwxyz` in both places to achieve a lower and lower score, asymptotically approaching zero. (with \$ n \$ letters, the score is \$ \frac 1 {279+239n} \$). The example shown here has a score of \$ \frac 1 {6693} \approx 0.00015 \$. With 1 million letters, the score would be \$ \approx 0.0000000042 \$.
The charset is all bytes except `\x00`, `\x04`, tab, newline, `\x0b`, `\x0c`, `\x0d`, `\x1a`, space, `!`, `#`, `+`, `-`, `;`, `\`, and `~`.
Explanation:
`<<` starts a "here-doc", which takes a single word, and turns the rest of the source code upto the first occurrence of that word again as a literal string.
This was originally going to be an[(](https://codegolf.stackexchange.com/a/249286)other) answer in Zsh, which also has here-docs, but unlike Zsh, Ruby produces an error when a heredoc isn't closed. (compare lone `<<abcdefghijklmnopqrstuvwxyz` in [Ruby](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWe2xsEpOSU1LT0jMys7JzcvPyCwqLiktKy8orKqsgSqAqYToA) to [in Zsh](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhZ7bGwSk5JTUtPSMzKzsnNy8_ILCouKS0rLyisqqyBKoCphOgA)).
By having an error whenever the same word is not used twice, we can detect any single-character insertion to inside that word.
A few quirks of Ruby's syntax mean we can discard some ASCII characters, but they can be more than made up for by invalid UTF-8 bytes.
[Answer]
# [BitCycle](https://github.com/dloscutoff/esolangs/tree/master/BitCycle), score 0.0737
```
1...v
...^ ^
```
where `...` is an arbitrary number of spaces
[Try it online!](https://tio.run/##S8osSa5Mzkn9/99QT0@vjAtIxCnE/f8PAA "BitCycle – Try It Online")
Bitcycle has 70 operating bytes: `><^=+/\|-10!?~{}@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` (plus newline)
Per the challenge, I am considering 26 more, all of which are no-ops: `23456789#$%&*()_,.;:'"[]` (plus "`")
Note that any position other than the first will have a duplicate case in a previous insertion location, and thus will only be `95` insertions instead of `96`. Insertion space will be indicated by an asterisk `*`. For the examples, the region `...` will be indicated by quotation marks `""`.
```
*1""v any char except newline offsets 1 nonbreaking
""^ ^ "v", so "1" enters a loop 96 total
```
```
1"*"v like case 1, but chars "^vV^/\+{~!?@" 13 nonbreaking
""^ ^ will also redirect the "1" elsewhere 95 total
```
```
1""v* no chars 95 nonbreaking
""^ ^ will err 95 total
```
```
1""v identical 1 nonbreaking
"*"^ ^ to case 1 95 total
```
```
1""v no chars 95 nonbreaking
""^* ^ will err 95 total
```
```
1""v no chars 95 nonbreaking
""^ *^ will err 95 total
```
```
1""v no chars 95 nonbreaking
""^ ^* will err 95 total
```
The score can be expressed as a fraction: \$\frac{3+4c+14n}{1+5c+2cn}\$ where \$c\$ is the number of characters in the set minus 1, and \$n\$ is the length of `...`. To generate the score listed, \$c=95, n \to\infty\$, which evaluates to \$\frac{7}{95}\$.
*Previously, I had missed a nonbreaking insertion, but this didn't change my score because of the assumed infinitely large \$n\$*
[Answer]
# Python 3, score \$\frac2{239}\$ (0 bytes)
And our hero program is...
NOTHING!!!
Same approach as above. The "bad characters" are:
`\t` (tab), `\n` (newline), `\x0c` (something IDK), `\r` (newline sort of), `#` (comment), `\` (line continuation), (space) , and `0123456789` (numbers).
Thus we define the range of bytes that can be added to be all single byte characters that are not in the above list.
Python testing script:
```
characterset=[chr(x) for x in range(256)]
noerr=''
for char in characterset:
try: exec(char)
except: pass
else: noerr+=char; print(char)
noerr
len(noerr)
```
(Designed to be directly runned in the interactive console.)
However, sometimes `_` will work in REPL and the `\` somehow works, so be warned.
[Answer]
**C(gcc)**
```
m\
a\
i\
n(){}
```
score:
118/3840
-> 120/3840
**Explanation**
main must be a part of the program, so almost no characters are valid there.
To lower the score I expanded that part of the code with backslash-newline, which allows for very few characters(and thus more errors).
test code:
```
#include <stdio.h>
char prog[]="m\\\na\\\ni\\\nn(){}";
char tofile[0xff];
main(){
long long bad=0;
long long total=0;
for(int i=0; i<sizeof(prog);i++){
char c=0;
do{
FILE* tmpc=fopen("/tmp/tmp.c", "w");
int j;
for(j=0;j<i;j++) tofile[j]=prog[j];
tofile[i]=c;
for(j=i;prog[j];j++)tofile[j+1]=prog[j];
fwrite(tofile, sizeof(prog), 1, tmpc);
fclose(tmpc);
FILE* gcc=popen("gcc /tmp/tmp.c", "r");
char gccc=getc(gcc);
while(gccc!=EOF){}
int status=pclose(gcc);
printf("code: \"%s\" Exit Status: %d\n", tofile, status);
if(!status)
bad++;
total++;
}while(++c!=0);
}
printf("score:\n %lld\n----\n %lld\n", bad, total);
}
```
It could be possible to do better, but the above code takes too long to run.
[Answer]
# Forth, Score 0.001736111 4 bytes
```
: abcdefghijklmnopqrstuvwxyz01234 ;
```
When run from a terminal, this program will correctly return nothing and the interpreter will return OK to the terminal.
Any insertion into the 31 character name will result in the correct program name not compiling, so the program will not exist and will not run.
Any insertion that puts anything but a blank character beside the `:` or `;` will result in the program not compiling correctly.
Possible insertions are
* blank before `:`,
* blank after `:`,
* blank before `;`, and
* blank after `;`.
The language parses with blanks and does not recognize any difference between one blank and two blanks between nonblank words. So there is no program that lacks these 4 insertions.
35 character program. At 36 locations we can insert any of 96 characters. 36\*96 = 3456.
(4+2)/3456 = 0.001736111
Standard compilers must allow names up to 31 characters, and may allow larger names. So this program could be, say 259 characters long, but then it would not run on all Forth compilers.
By stuffing the program with more 31-character functions, in the limit we would have 1 valid insertion per 31-character name, and that's as low as it gets.
However, if we only consider an insertion valid if it changes the program, and `: test ;` compiles the same as
`: test ;` then maybe we should not consider those insertions.
In that case the program
```
: abcdefghijklmnopqrstuvwxyz01234 ;
: test
abcdefghijklmnopqrstuvwxyz01234
abcdefghijklmnopqrstuvwxyz01234
abcdefghijklmnopqrstuvwxyz01234
abcdefghijklmnopqrstuvwxyz01234 ;
```
is also entirely crystalline and we can add as many lines as we like to reduce the score toward zero.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score \$ \to 0 \$
```
abcdef-abcdef+Null
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8xKTklNU0XQmn7lebk/P8PAA "Wolfram Language (Mathematica) – Try It Online")
Similar to the Ruby answer, add arbitrarily more letters to `abcdef` in both places to achieve a lower and lower score, asymptotically approaching zero. (with \$ n \$ letters, the score is \$ \frac {16}{315+92n} \$). Thanks Mathematica for no limits to variable names! The example shown here has a score of \$ \frac 2 {95} \approx 0.0210526 \$. With 1 million letters, the score would be \$ \approx 0.000000173912 \$.
The charset is 0x20 to 0x7F, printable ASCII, though there is nothing stopping any characters being input.
The 16 exceptions, in no order, include multiplying by one, replacing subtraction with adding a negative, and calling the local namespace:
```
+abcdef-abcdef+Null
`abcdef-abcdef+Null
abcdef-abcdef+Null
1abcdef-abcdef+Null
abcdef+-abcdef+Null
abcdef -abcdef+Null
abcdef-+abcdef+Null
abcdef-`abcdef+Null
abcdef- abcdef+Null
abcdef-1abcdef+Null
abcdef-abcdef;+Null
abcdef-abcdef +Null
abcdef-abcdef+ Null
abcdef-abcdef+1Null
abcdef-abcdef+Null;
```
Other attempts included (0.0740741):
```
Quiet[0/0,{Power::infy,Infinity::indet}];
```
Which nicely throws an error if you mess with most of it, and (0.00126984)
```
If[#0==#1,,1,1]&[If[#0==#1,,1,1]&]
```
Which is a quine-like solution that tries to actively detect tampering.
]
|
[Question]
[
[Alienese](https://futurama.fandom.com/wiki/Alienese) refers to two "languages" in the show [*Futurama*](https://en.wikipedia.org/wiki/Futurama). In actuality, they are two ciphers of English text with a pictographic alphabet. The first is a simple substitution cipher, but the second is slightly more complex. The second is a type of [autokey cipher](https://en.wikipedia.org/wiki/Autokey_cipher) that follows these steps:
* Take a word to be encrypted, e.g. `FUTURAMA`
* Replace each letter with its 0-index in the alphabet: `[5, 20, 19, 20, 17, 0, 12, 0]`
+ Note that, due to the next step, zero indexing is important and 1 indexing cannot be used
* Take the cumulative sums of the array: `[5, 25, 44, 64, 81, 81, 93, 93]`
* Modulo each term by `26` to bring it within bounds: `[5, 25, 18, 12, 3, 3, 15, 15]`
* Index into the alphabet: `FZSMDDPP`
We can iterate this process until we reach our original word again. For example, for `FUTURAMA`, the full list, space separated, is
```
FUTURAMA FZSMDDPP FEWILODS FJFNYMPH FOTGEQFM FTMSWMRD FYKCYKBE FDNPNXYC FIVKXUSU FNISPJBV FSASHQRM FXXPWMDP FCZOKWZO FHGUEAZN FMSMQQPC FRJVLBQS FWFALMCU FBGGRDFZ FGMSJMRQ FLXPYKBR FQNCAKLC FVIKKUFH FAISCWBI FFNFHDEM FKXCJMQC FPMOXJZB FUGURAZA FZFZQQPP FEJIYODS FJSAYMPH FOGGEQFM FTZFJZEQ FYXCLKOE FDACNXLP FIIKXUFU FNVFCWBV FSNSUQRM FXKCWMDP FCMOKWZO FHTHRNMA FMFMDQCC FRWILBDF FWSALMPU FBTTEQFZ FGZSWMRQ FLKCYKBR FQACAKLC FVVXXHSU FAVSPWOI FFASHDRZ FKKCJMDC FPZBKWZB FUTUEAZA FZSMQQPP FEWIYODS FJFNLZCU FOTGRQSM FTMSJZRD FYKCLKBE FDNPAKLP FIVKKUFU FNISCWBV FSASUQRM FXXPJZQC FCZOXWMO FHGURNZN FMSMDQPC FRJVYODF FWFAYMPU FBGGEQFZ FGMSWMRQ FLXPLXOE FQNCNKYC FVIKXHFH FAISPWBI FFNFUQRZ FKXCWMDC FPMOKWZB FUGUEAZA FZFZDDCC FEJILOQS FJSALZPH FOGGRQFM FTZFWMRD FYXCYKBE FDACAKLP FIIKKUFU FNVFPJOI FSNSHQEM FXKCJZDP FCMOXWZO FHTHEAZN FMFMQQPC FRWIYODF FWSAYMPU FBTTRDSM FGZSJMEQ FLKCLXBR FQACNKLC FVVXKUFH FAVSCWBI FFASUQRZ FKKCWMDC FPZBXJMO
```
and takes 104 steps to return to `FUTURAMA`. I conjecture that, for any non-empty string of letters, this process always returns to the original string in a finite number of steps.
---
You are to "prove" this conjecture. That is, write a program that takes a non-empty string of letters (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`, or `abcdefghijklmnopqrstuvwxyz`, you may choose), and outputs the number of steps to return to the original input, by iterating this autokey cipher. Note that, by listing the terms, the list should *either* start or end with the input, which counts as either the first or last step.
You may take input in any convenient format, including taking the input as an array of characters. You may only take the input as an array of code points if you are unable to input as characters or as a string (e.g. brainfuck).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
J -> 1
NK -> 2
TQR -> 52
NAK -> 4
AAAQ -> 1
CGCC -> 13
CAIRD -> 26
NNNNX -> 8
FUTURAMA -> 104
ALIENESE -> 104
NANNANNAN -> 16
ZBDMBCWJQJPWF -> 208
MUJJEKIBPULKWRHW -> 2704
HWGYIBRBRBLADVYTXL -> 5408
```
---
Interestingly, it appears as almost all words result in a number of steps either equal to 1 (a fixed point) or divisible by 13. We say a word is "interestingly-aliense" if this *isn't* the case, i.e. it is neither a fixed point, nor has a cycle length divisible by 13. We can see, by brute forcing all combinations of words with 2 or 3 letters, that the full list of these words is
```
NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ ANA ANB ANC AND ANE ANF ANG ANH ANI ANJ ANK ANL ANM ANN ANO ANP ANQ ANR ANS ANT ANU ANV ANW ANX ANY ANZ NAA NAB NAC NAD NAE NAF NAG NAH NAI NAJ NAK NAL NAM NAN NAO NAP NAQ NAR NAS NAT NAU NAV NAW NAX NAY NAZ NNA NNB NNC NND NNE NNF NNG NNH NNI NNJ NNK NNL NNM NNN NNO NNP NNQ NNR NNS NNT NNU NNV NNW NNX NNY NNZ
```
All of which either result in 2 or 4. We can also see that all of these contain the letter `N`. Indeed, we can try out some guesses for longer "interestingly-alienese" words based on this. For example, `NNNNX` has a cycle of 8 (`NNNNX, NANAX, NNAAX, NAAAX, NNNNK, NANAK, NNAAK, NAAAK`), and `NANNANNAN` has a cycle of 16, as shown above. Can you find any more, potentially with longer cycles?
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~13~~ 12 bytes
```
#(26!+\)\65!
```
[Try it online!](https://ngn.bitbucket.io/k#eJxlj9tuwjAQRN/nK4z7QoVQQ0hMhNRKzgWIcxExSQ0Vz/z/J7B27KoX21JmJztrn8f+ZRmLxer+ehfpAtiwd/ZgXHHEs+objtTrcdAcifcl/fDdUsqBiu1cFceioLjwlax1yZH5FK0rtUZ+ymEaJy07+cOSbV311aUiS4Sr+vnQ1MgP+srLLi+MGtTZHMjfhXg3KVU1dX6e2sbok6HXJyF0MsdbnWvarSw/b+O15cAbFFt/sA36xn5jEKUVaQxitCqBBZybLJxTWzgyFxFwXFZnCEiuK6Ks5wn1N40zBH6RuHFRhr8UzidG/EdwbyXEJ0m1ZfQ=)
Git gud, Jelly. Only one byte ahead of an ASCII-only language? :P
Takes uppercase input and computes the length of the loop. -1 byte thanks to ZippyMagician's observation that subtract 65 == mod 65.
```
#(26!+\)\65! input: a string
65! modulo 65 ('A') from each letter (gives a numeric list)
( )\ repeat and collect until loop is found:
26!+\ cumulative sum mod 26
# length of the result
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes
```
If[#!=##2,1+Accumulate@#~Mod~26~#0~##,0]&[LetterNumber@#-1]&
```
[Try it online!](https://tio.run/##JUxNb4MwDL3zL0YmLqNS28NuTISP0kBAkMJohzhkWVAjDSrRcJim5a8zQm3Lz@892z2VV95TKRidO2dGXQOeHAD29u4FMjb10zeV3AUqvX2p/asCWwWAvW2tBnMp@ZhN/ScfXbDZtdb8TDibxru4DVj0Qjpo6MQg5I9RTIJLNx/FIBuweetc/0pHypb7uwtaS50YHdSvYcambZhZontZkJXAlUEIC42RH0UafYhIsPpLnPVwqMqKwBSu2xiFWXgKHw@yR2ny4QWp59dxEef1QQtpFcdhgry8wklNjrXWjnV0QR5ZEsPg/VKesWn8zf8 "Wolfram Language (Mathematica) – Try It Online")
Input a list of characters. Determines the period through recursion. Times out (or reaches the recursion limit) for larger test cases.
---
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~69~~ ~~65~~ 63 bytes
```
s1//.j_/;!Drop[LetterNumber@s-1,-j]~Mod~#1:>j#&//#@2#@13&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v/j9pIWG@vp6WfH61oouRfkF0T6pJSWpRX6luUmpRQ7FuoY6ulmxdb75KXXK7ydsM7Syy1JW09dXdjBSdjA0VvsfWJqZWuIQUJSZVxKtrGuX5uCckViUmAw0odhBOVatLjg5Ma@umkvJS0mHS8nPG0SGBAaBOY5gnqOjYyCIdnd2dwfRzo6eQS5geSCIADHcQkNCgxx9HcGqfTxd/VyDXSEG@EEQiBPl5OLr5BzuFegVEO4GEvAN9fJy9fZ0Cgj18Q4P8ggHiXmEu0d6OgUBoY@jS1hkSISPElftfwA "Wolfram Language (Mathematica) – Try It Online")
Input a list of characters. Computes the period. The private-use characters are `\[Function]` and `\[VectorLess]`.
```
& g: i =>
1//.j_/;! :>j# least power of i (=j) such that
Drop[LetterNumber@s-1,-j]~Mod~#1 no elements divisible by i outside the final j
//#@2#@13& g(2)*g(13)
```
### Explanation:
Denote the \$n\$th accumulation of the list \$A=(a\_1,a\_2,...,a\_l)\$ by \$A[n]=(a[n]\_1,a[n]\_2,...,a[n]\_l)\$, and the length of the cycle of \$A\$ modulo \$m\$ by \$c\_m(A)\$. Then, in general,
\$a[n]\_k=\displaystyle\sum\_{i=0}^{k-1}\frac{n^{(i)}}{1^{(i)}}a\_{k-i}=a\_k+\sum\_{i=1}^{k-1}\frac{n^{(i)}}{1^{(i)}}a\_{k-i}\$, where \$x^{(y)}\$ is the [rising factorial](https://en.wikipedia.org/wiki/Falling_and_rising_factorials). (These are the diagonals of Pascal's triangle).
By definition of a cycle, for any \$n\$ where \$A[n]\equiv A\pmod m\$, that is, \$a[n]\_k\equiv a\_k\pmod{m}\$ for all \$k\$, \$c\_m(A)\mid n\$.
Since 2 and 13 are relatively prime, \$c\_{26}(A)=\operatorname{LCM}(c\_2(A),c\_{13}(A))\$.
First consider cycles mod 2. Let \$2^x\$ be the least integer power of 2 such that \$2\mid a\_i\$ for all \$a\_i\le l-2^x\$, i.e. the final \$2^x\$ elements contain all those not divisible by 2. Consider the \$2^x\$th accumulation \$A[2^x]\$:
\$\begin{align\*}
a[2^x]\_k&=a\_k+\sum\_{i=1}^{k-1}\frac{(2^x)^{(i)}}{1^{(i)}}a\_{k-i}\\
&=a\_k+\sum\_{\substack{1\le &i<k\\&i<2^x}}\frac{(2^x)^{(i)}}{1^{(i)}}a\_{k-i}
\end{align\*}\$
It can be fairly easily be shown that \$2\mid\frac{(2^x)^{(i)}}{1^{(i)}}\$ for all \$0<i<2^x\$, so \$A[2^x]\equiv A\pmod2\$ and \$c\_2(A)\mid2^x\$.
Because of the way we defined \$2^x\$ there exists minimal \$p\$ such that \$a\_p\not\equiv0\pmod2\$ and \$2^{x-1}\le l-p<2^x\$. Then
\$\begin{align\*}
a[2^{x-1}]\_{p+2^{x-1}}&=a\_{p+2^{x-1}}&&+\sum\_{i=1}^{p+2^{x-1}-1}\frac{(2^{x-1})^{(i)}}{1^{(i)}}a\_{p+2^{x-1}-i}\\
&=a\_{p+2^{x-1}}&&+\sum\_{i=1}^{2^{x-1}-1}\underbrace{\frac{(2^{x-1})^{(i)}}{1^{(i)}}}\_{\equiv0\pmod2}a\_{p+2^{x-1}-i}\\
&&&+\underbrace{\frac{(2^{x-1})^{(2^{x-1})}}{1^{(2^{x-1})}}a\_p}\_{\text{both }\not\equiv0\pmod2}\\
&&&+\sum\_{i=1}^{p-1}\frac{(2^{x-1})^{(i+2^{x-1})}}{1^{(i+2^{x-1})}}\underbrace{a\_{p-i}}\_{\equiv0\pmod2}\\
&\not\equiv a\_{p+2^{x-1}}&&\pmod2,\\
\end{align\*}\$
using primality of 2 to show that the middle term must \$\not\equiv0\pmod2\$.
Therefore \$A[2^{x-1}]\not\equiv A\pmod2\$, so \$c\_2(A)\not\mid2^{x-1}\$. Since 2 is prime, \$c\_2(A)=2^x\$.
(\$p\$ does not exist if \$2^x=1\$, but in that case the only integer \$c\_2(A)\mid1\$ is \$c\_2(A)=1\$).
An analogous argument works mod 13, so we can let \$c\_{13}(A)=13^y\$, where \$13^y\$ is defined in a similar fashion to \$2^x\$, and \$c\_{26}(A)=2^x13^y\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes
```
ØAiⱮ’Ä%26ƊƬL
```
[Try it online!](https://tio.run/##y0rNyan8///wDMfMRxvXPWqYebhF1cjsWNexNT7///9X8gh3j/R0CgJCH0eXsMiQCB8lAA "Jelly – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~69~~ 64 bytes
```
->s{g=h=s.bytes;1.step.find{r=0;g==h=h.map{|b|(r+=b-13)%26+65}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664Ot02w7ZYL6myJLXY2lCvuCS1QC8tMy@lusjWwDrdFiiZoZebWFBdk1SjUaRtm6RraKypamSmbWZaW1v7v0AhLVrJLTQkNMjR11Ep9j8A "Ruby – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 83 bytes
```
lambda s:(g:=lambda r,i=1:all(ord(c)%r==~r%2for c in s[:-i])or g(r,i*r)*r)(2)*g(13)
```
[Try it online!](https://tio.run/##NU5rb4IwFP3eX9EvxNbgwktHSFhSEJWHRJgM3SOLk6lNGJDCsuzL/jordeu9yT3n3HNu2nx3l7rSzYb1J/u5Lw8fb8UBthY6W/YfYTK1VetQlqhmBTpiidn2D5O0U83gEdIKtk/WhL5gTs@Im8cM80YaHp@RquP@60LLd6haAFL5Va6hzTPNZ4fwTduUlE8AG0arDo0kTWnh5A5KRgGR1OKRhKh8QhTLNcZ9MKxUEIfD1MA2SQcw1UBMhGQAQkhyNblL1xVIBy7x07mIzEDM327AJlhk2ywlayJcCs9Gvhd7994/j0l8bSHMwKMzXztuHiTBJl@Ic4oJ1lkQeKHvbLIozNNVLvRbnl7ly73vpLwiMn/Yb3eR@KuhmL8 "Python 3.8 (pre-release) – Try It Online")
Port of my second [Mathematica solution](https://codegolf.stackexchange.com/a/237131/81203), and probably a bit easier to understand. Python plays nicer with out-of-bounds slices.
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 119 bytes
```
INPUT w$
n$=w$
1s=0
FOR i=1TO LEN(n$)
s=s+ASC(MID$(n$,i))-65
MID$(n$,i)=CHR$(s MOD 26+65)
NEXT
r=r+1
IF n$<>w$GOTO 1
?r
```
[Try it at Archive.org!](https://archive.org/details/msdos_qbasic_megapack)
### Explanation
```
INPUT w$
n$ = w$
```
Input `w$` (the original word) and set `n$` (the next encrypted form) to `w$`.
```
1 s = 0
```
Label `1` is the start of our main loop. Initialize `s` (the cumulative sum) as 0.
```
FOR i = 1 TO LEN(n$)
```
Loop over the indices of the characters in `n$`.
```
s = s + ASC(MID$(n$, i)) - 65
```
Get the ASCII code of the `i`th character of `n$`, subtract 65, and add to the cumulative sum.
```
MID$(n$, i) = CHR$(s MOD 26 + 65)
```
Take `s` mod 26, add 65, convert from ASCII code, and set the `i`th character of `n$` to that character.
```
NEXT
r = r + 1
```
End of `FOR` loop. Increment `r` (the number of repetitions we've gone through).
```
IF n$ <> w$ THEN GOTO 1
```
If the next encrypted form is different from the original word, loop.
```
PRINT r
```
Otherwise, print the number of repetitions.
---
In [QB64](https://www.qb64.org), we can get down to **106 bytes** using the extended forms of `ASC` instead of `MID$`:
```
INPUT w$
n$=w$
1s=0
FOR i=1TO LEN(n$)
s=s+ASC(n$,i)-65
ASC(n$,i)=s MOD 26+65
NEXT
r=r+1
IF n$<>w$GOTO 1
?r
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~62~~ 61 bytes
Expects the input in lowercase, as suggested by @UnrelatedString (-1 byte).
```
f=(s,q)=>s!=q&&1+f(Buffer(s).map(c=>(t+=c+7)%26+97,t=0),q||s)
```
[Try it online!](https://tio.run/##jdHdboIwFMDx@z2FM5lpA1N0TtxFvdibHEqrlFLoB6KL787otmQZxWTn9PJ38T@pgDNYaorGPas6Z33PCbKxxuRgH4leLNYRR@8t58wgi5cVNIiSA3IRoVGKnza76C2NHUlwrG83i3taK1tLtpT1EXE0F3OMZ@GsVrP1w4iqctIOdDOmTpspO9DXwCoo79jtmAKAnrBTsfRI6R36ElgoTB5if9guqB3mMmn3Y8pb1xqoYKR9QhKeJgummGX/wgrU9/urPQ6CP7K8ymgntGg6/uv9cUmQXLVCsLLImlaWnTl1P97jNMw4dcdrkZlhJeTnq7vIL@9/eZvs@08 "JavaScript (Node.js) – Try It Online")
Or [56 bytes](https://tio.run/##ldLRbsIgFAbg@z2FM5lC6rQ6Z90FXuxNKIVaSmkL1Oriu3clZsniOCY7cPsl5/9zJD1Ry0zRuFddZ3wYBEF20WJysM@knc3WkUB2WdEGMXJALiIsSvDLZhd9JAtHYrxor1cbzed4YLW2teJLVedIoM9OCG7QVE4xxpO/s1pN1k9hosuwGckGIK41QTOSd8hoWkJmCxBKaRsyD8KwnDGIvEGGFiYLIF/ADkozzjls9gARnesMrei98qvFYAWq4Jpb/i@kqb79O@URFOgrzaqU9bKVTS9@OV9CDEWqOil5WaRNp8reHPsf51ECrnfs80uRmvEpmp0u7qxuzl/PNt4P3w) by taking a Buffer as input.
### Commented
```
f = (s, // s = input string
q) => // q = reference string, initially undefined
s != q && // stop as soon as s == q
1 + // otherwise: increment the final result
f( // do a recursive call:
Buffer(s) // turn s into a Buffer
.map(c => // for each ASCII code c in the Buffer:
(t += c + 7) // add c + 7 to t
// (where 7 is -(97 mod 26) + 26)
% 26 // reduce t modulo 26
+ 97, // add the ASCII code of 'a'
t = 0 // start with t = 0
), // end of map()
q // pass the reference string q,
|| s // or s if q is still undefined (1st iteration)
) // end of recursive call
```
[Answer]
# [Joy](http://joy-lang.org/), 166 bytes
```
DEFINE i == rotate 1 + rotate [0]swap[[dup dup size 1 - at]dip +[]cons concat]step rest[26 rem]map.
DEFINE a == 0 swap[ord 65 -]map dup i[equal not][i]while pop pop.
```
Crashes on the longer inputs, but as far as I can tell that's because of the implementation.
Explanation:
```
DEFINE sumScan == [0]swap[[dup dup size 1 - at]dip +[]cons concat]step rest.
DEFINE iter == rotate 1 + rotate (* increment counter *)
sumScan[26 rem]map. (* sum scan, then mod 26 *)
DEFINE alienese == 0 swap[ord 65 -]map (* convert to numbers and set counter *)
dup iter[equal not][iter]while pop pop. (* iterate until it's equal again, then pop off values that aren't counter *)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 136 bytes
```
s=k=input();n=1
while 1:
l=[ord(x)-65for x in s];s=''.join(chr(sum(l[:x+1])%26+65)for x in range(len(l)))
if s==k:break
n+=1
print(n)
```
[Try it online!](https://tio.run/##PY6xDoIwFEX3fsVbDO@FaIIGBkgHFjcXIxNhQC22Ul9JCxG/Hll0vMk5OXf4jNrxYQkyOlaX6lyeymgdvTQ8TCNSwTIRb22sgiQXYGXt/B1n2mZp5zzMYBhCU6x6tHs6w3jTHsP0Qlvnc5w0tNlncZbSH/YtPxRaxWiJSIDpIEjZ51ev2l4Ax2tv8IZHZFqW36cv "Python 3 – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 79 bytes
```
s->d=Mod(1-x,x^#s);p=Mod(Polrev(Vecsmall(s))-65/d,26);i=1;while(p*d^i!=p,i++);i
```
[Try it online!](https://tio.run/##JYxtS8MwEMe/SszepC5BJrg3pYP0YVvTB9raLtvEQbGdBqILjej89LXJ7o773@9/x6l2EORdjWfgjZqsOi@7dGhBrvh6mmnHVZaLixz6H7Tr3/RnKyXSjkOWTw8dflw6rvAW7u@HkD1S991J3HkKi/l88sdWKfmHNCAroAbx9T2N0AAEZ/MCgxfIIAYwT0yvy8oCtUQpLY0GmyCwSuMqtPsp9mZYN3VT0Yza6zSO8ug5uj3Ib2Xg6IeZH3BWsoKvjZE1jEVJ7BdNmvBqy4235ZtD7FdTpjTcHep9Cl@d8R8 "Pari/GP – Try It Online")
Convert the string to an element \$P\$ in the ring \$\mathbb{Z}[X]/(26,X^n)\$, where \$n\$ is the length of the string, and find the smallest \$i>0\$ such that \$P\*(1-X)^i=P\$.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
LU¡₁m(-65D
m%26∫
```
[Try it online!](https://tio.run/##yygtzv7/3yf00MJHTY25Grpmpi5cuapGZo86Vv///98tNCQ0yNHXEQA "Husk – Try It Online")
#### Explanation:
```
m(-65D # map codepoint - 65
LU¡₁ # length of longest unique prefix of iteration of function on next line
m%26∫ # map %26 on cumsum
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 23 bytes
```
l.usmC+65%sd26._m-Cd65N
```
[Try it online!](https://tio.run/##K6gsyfj/P0evtDjXWdvMVLU4xchMLz5X1znFzNTv/38lt9CQ0CBHX0clAA "Pyth – Try It Online")
```
l.usmC+65%sd26._m-Cd65N # Full program
.u # Collect until input found
m N # Map over current value (variable d)
Cd # Code point of d
- 65 # Minus 65 (Index of alphabet)
._ # Prefixes
m # Map over (on prefixes with d)
sd # Sum current prefix
% 26 # Modulo 26
+65 # Add 65 (Code point)
C # ASCII char
s # Join list
l # Length of whole scan-fixedpoint
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1µAskηOAsèDIQ}N
```
-2 bytes thanks to *@Neil*.
Input as a lowercase list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f/f8NBWx@Lsc9v9HYsPr3DxDKz1@/8/WilNSUepFIhLoHQRECcCcS6YjgUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8ND211LM4@t93fsfjwCpdD6wJr/f7r6B3a@j86WilLKVYnWilPSUcpG8wqAbIKgbgILp4Il0uE8hLBakAiyUBWOhAngzFMBCSfCTZDRykFbg4yrgCLpgFZpUBcAqWLoHpzwTTMxhyoaalQvSC6GEwjuxBmMiYbpKoKyEoCuwZiehLUzeVAnAX1MYgugIqlKcXGAgA) (except for the last two, which time out).
Slightly faster minor alternative (thanks to *@Neil*):
```
Ask©1µηO₂%D®Q}N
```
[Try it online](https://tio.run/##yy9OTMpM/f/fsTj70ErDQ1vPbfd/1NSk6nJoXWCt3///0UppSjpKpUBcAqWLgDgRiHPBdCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/x@LsQysND209t93/UVOTqsuhdYG1fv919A5t/R8drZSlFKsTrZSnpKOUDWaVAFmFQFwEF0@EyyVCeYlgNSCRZCArHYiTwRgmApLPBJuho5QCNwcZV4BF04CsUiAugdJFUL25YBpmYw7UtFSoXhBdDKaRXQgzGZMNUlUFZCWBXQMxPQnq5nIgzoL6GEQXQMXSlGJjAQ) (except for the last two, which still time out).
**Explanation:**
```
1µ # Loop until the counter is 1:
k # Get the indices
s # of the current list of characters (this will be the implicit
# input in the first iteration)
A # in the lowercase alphabet
η # Get the prefixes of this list
O # And sum each inner prefix-list
Asè # Modular index this list into the lowercase alphabet
D # Duplicate it
IQ # Pop the copy, and check if it's equal to the input
# (if this is truthy, implicitly increase the counter by 1)
}N # After the loop: output the last 0-based index of the loop
# (after which it is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org), 108 bytes
```
i=s=[ord(c)-65for c in input()];a=0
while a<1or s!=i:s=[sum(s[:j+1])%26for j in range(len(i))];a+=1
print(a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3czJti22j84tSNJI1dc1M0_KLFJIVMvOAqKC0REMz1jrR1oCrPCMzJ1Uh0cYQKFusaJtpBdRSXJqrURxtlaVtGKupamQG0pgF0liUmJeeqpGTmqeRqQnSrm1ryFVQlJlXopGoCbFzAYzyA4IICAcA)
This isn't a very interesting answer.
If only Python wasn't *bad*, we could have this for 105 bytes:
```
lambda s:1+len([*iter(lambda:(t:=([sum(t[:j+1])%26for j in range(len(s))])),(t:=[ord(c)-65for c in s]))])
```
Explanation:
```
lambda s: # xxx
[ord(c)-65for c in s] # convert input string to list of alphabet indeces
(t:=) # assign to `t` initially
iter(lambda: ,) # repeat until t recurs:
[sum(t[:j+1])%26 # cumulative sums of `t`
for j in range(len(s))]
(t:=) # reassign to `t`
1+len([*]) # length of repeating segment
```
But in the inner lambda, the list comprehension binds `t` as a free variable to the inner lambda, rather than a free variable to the *outer* lambda. If there was a way to do `nonlocal` in a `lambda`, we could avoid this.
Here's a bit of a hack that does actually work: [Attempt This Online!](https://ato.pxeger.com/run?1=JU1LDoIwEN17im5MZlRMMJGYGq7A2gRZILRaAi3ph-BZ3LDBE3gZbmMbZjNv5v0-3_5tX0pOC9aMkxGGNFOSIR2PQzoQpYkHV82s0zLADU_vs7M8uiyiLbtHXRJD433LJOQ7YZmG9UthhNy4zi_MabOPC9yeEu7zGiIk0aV8Mggug1ggHoJc6RoqjJJzkFVBZjzl6bXw12shLfBQJHtnIRhXapozP7f1-AM)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v1.4.5, 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
;@=mnB å+ £BgXu26Ã eNg}a
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.5&code=O0A9bW5CIOUrIKNCZ1h1MjbDIGVOZ31h&input=WyJGIiwiVSIsIlQiLCJVIiwiUiIsIkEiLCJNIiwiQSJd) Switched to array of characters to save 1
```
; - 2nd set of predef. Vars
@...}a - repeat until true
return number of times
= - reassign U(input) by
mnB * index each in ALPHA
å+ * cumulative sum
£Bg * each: get[ABCD..]
Xu26Ã at X%26
eNg - compare to orignal input
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ ~~28~~ 25 bytes
```
IΠE⟦²¦¹³⟧XιL↨⌈E⮌θ∧﹪⌕αλιμι
```
[Try it online!](https://tio.run/##JYzLCsIwFER/JctbiAt16apVfEAKoYhaxMUlDTaQh6Zp9e/jpc4wcBiGUT1GFdDmLKPxCbY4JJAxdKNKUOML7ivOlusHZzJ8dATDmdD@mXqocNC0@Bo3unnZ6ElH6t4FZ6XvoKYTG2BviJEzS7WhuKKY6a9NzsfroT1VDVmUu0t7vom8mOwP "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @Nitrodon/@att's closed form formula: for each of the prime factors of 26, the offset from the end of the word of the first letter whose alphabet index is not divisible by that prime is rounded up to the next power of the prime and the two values are multiplied together.
```
⟦²¦¹³⟧ Literal list `2,13`
E Map over the two primes
ι Current prime
X Raised to power
θ Input word
⮌ Reversed
E Map over letters
λ Current letter
⌕α Index in alphabet
﹪ Modulo
ι Current prime
∧ Logical And
μ Current index
⌈ Take the maximum
↨ Converted to base
ι Current prime
L Take the length
Π Take the product
I Cast to string
Implicitly print
```
Conveniently base conversion of zero is the empty list with length zero so that the prime power is simply `1` for a single letter or a word only containing the letter `A`.
Previous 28-byte brute-force version:
```
W¬№υθ«⊞υθ≔⭆θ§αΣE…θ⊕λ⌕αμθ»ILυ
```
[Try it online!](https://tio.run/##JU1LDoIwFFzDKbp8TeoJWCFGJUFDxKgsm9LQJqUV2vqJ8ey1yMxqPplhgk7MUBXCU0jFERyNg8J47cATNGKM0SdNam/ForM0ya2VvYbGTVL3B3qHkaDclbrjL6AENX6A2S3eTPFCmH9eajbxgWvHO1AYE7SVupvbA56xLH/TOk7Ge2odVFz3Lp7GNAthf9215foUWeWbS3u@VWH1UD8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W¬№υθ«
```
Repeat until a cycle is detected. (Since cumulative sum is invertible, this will always be the original word.)
```
⊞υθ
```
Save the previous value.
```
≔⭆θ§αΣE…θ⊕λ⌕αμθ
```
For each letter, take the prefix so far, convert each letter to its alphabet index, take the sum, and take the letter at that index.
```
»ILυ
```
Output the cycle length.
Much faster ~~36~~ 32-byte version:
```
≔ES⌕αιθW¬№υθ«⊞υθ≔﹪EθΣ…θ⊕λ²⁶θ»ILυ
```
[Try it online!](https://tio.run/##NY49C8IwFEXn5ldkfIG6OLh0qhW1UKVY8WMMbWgCadI2iSLib4@xKm@6l8s5r@Z0rDWV3qfGiFbBjvaQq97Zyo5CtUBivBaqARpjQUIYSILuXEiGYa8tZNopC@7TE4KfKCqd4d@coOjP1I2TekIPMa5cB9mjlizjeipyVY@sY8qyBmTABMt88VO9UBneCB5qLBRMtTbQwyTxfnveXPPlIVyRrk7X46Xws5t8Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔ES⌕αιθ
```
Map the input letters to their alphabet index.
```
W¬№υθ«
```
Repeat until a cycle is detected. (Since cumulative sum is invertible, this will always be the original word.)
```
⊞υθ
```
Save the previous value.
```
≔﹪EθΣ…θ⊕λ²⁶θ
```
Calculate the cumulative sum modulo 26.
```
»ILυ
```
Output the cycle length.
The intermediate values for a string of `n+1` `N`s can be read from the columns below, with `N` represented by `1` and `A` by `0`:
```
0 1(1...)
1 10(10...)
2 1100(1100...)
3 1000(1000...)
4 11110000(11110000...)
5 10100000(10100000...)
6 11000000(11000000...)
7 10000000(10000000...)
8 1111111100000000(...)
(...)
11 1000100000000000(...)
12 1111000000000000(...)
(...)
15 1000000000000000(...)
(...)
```
The `2ᵏ`ᵗʰ row consists of a cycle of twice its length given by `2ᵏ` `1`s and `2ᵏ` `0`s. Over the next `2ᵏ-1` rows the `1`s decay into a single `1` as they did for the first `2ᵏ` rows, and then the next row doubles in cycle length.
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), 14 bytes
Unfortunately can't beat [Bubbler's K answer](https://codegolf.stackexchange.com/a/237127/90265), but it comes close. This is practically a direct translation, except for the fact that `65|` is the same as `_65+` in this specific case. Takes capital input.
```
:#(26|+\)$:65|
```
# Explanation
```
: A non J-style train
65| Input mod 65
( ... )$: Fixpoint
+\ Cumulative sum
26| Mod 26
# Size
```
[Answer]
# [Haskell](https://haskell.org), 89 bytes
```
import Data.Char
s!o|t==o=1|True=1+t!o where t=scanl1(\x y->chr$(ord x+ord y)`mod`26+65)s
```
[Try it online](https://tio.run/##TcdNC4IwGADg@37FO/GgjAKDPAgLpAg6RBB66@DQwaR9yLtFCv73RXTp8sCjhH9KrWMczeQwwEkEsT0qgcRTtwbOHS/WBl@SFyxQB28lUULgvhdWF9ljhmVz6BWmmcMBZvZ1yTvjhm5XsnKfe0KMGC1UFVxukOW/cZhwtAFSSM5t097ra50A/UuMHw)
(65 \* 2 mod 26 conveniently equals 0.)
[Answer]
# TI-Basic, ~~129~~ 131 bytes
```
Input Str1
"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2
Str1
Repeat Ans=Str1
cumSum(seq(inString(Str2,sub(Ans,I,1))-1,I,1,length(Ans
1+remainder(Ans,26→R
J+1→J
sub(Str2,ʟR(1),1
For(I,2,dim(ʟR
Ans+sub(Str2,ʟR(I),1
End
End
J
```
+1 byte if not run on a TI-84+/SE with the 2.53 MP OS by replacing `remainder(Ans,26` with `26fPart(Ans/26`.
Output is stored in `Ans` and displayed.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes
```
m{**65.%}J1{{++26.%}pa}C~[-jFi+.
```
[Try it online!](https://tio.run/##JYq9DoIwFEZf5S4uEEk0kf22FGgLDVRqQSaNDBpJ/AlxaPDVsYnfOcMZvvP0ug/v5zQsn4tbRhcE8S5azWLjXBhuY5@P00y//fqWXsNomcd@EaAkNLUGhRIQsQaaUQoUuU5A@bWQmsZoLBGw4EyxPfNf9ReOJCkJtaIWlU2hNEIwyUllCml1biG3WceJ9hSYHLqmLX4 "Burlesque – Try It Online")
```
m{ # Map each char
** # Ord(a)
65.% # Mod 65
} # <-- converted to alphabet index
J # Duplicate
1 # Prefix Arg to infinite loop
{ #
{ #
++ # Sum
26.% # Mod 26
} #
pa # Partial (applied to each init)
} #
C~ # Infinite list of function evaluated successively on arg
[- # Drop first element (original converted string)
j # Swap in duplicated original
Fi # Find index of original in list
+. # Increment by 1 (0 indexed)
```
[Answer]
# Python3, 101 bytes:
```
import itertools as i
s,c=(n:=[ord(j)-65for j in n]),1
while(s:=[j%26for j in i.accumulate(s)])!=n:c+=1
```
If anything, a cleaner and more efficient way to produce the cumulative sums.
]
|
[Question]
[
[Cubically](//git.io/Cubically) is too tedious to manually write any code in. Your challenge is to translate ASCII text into Cubically source code.
# Cubically
This is just a quick run-down of Cubically; the [repository](//git.io/Cubically) has a more complete guide and details.
Cubically is an esolang I wrote a while ago, designed to be painful to use. It contains two pieces of memory, a 3x3x3 Rubik's Cube and a register called the "notepad".
### Memory
The internal Rubik's Cube is initialized like this:
```
000
000 top face
000
111222333444 left, front, right, and back faces, respectively
111222333444
111222333444
555
555 down face
555
```
After performing a clockwise 90° turn on the right face, the memory cube would look like this:
```
002
002
002
111225333044
111225333044
111225333044
554
554
554
```
### Commands
A non-integer character sets the default command. For each integer before the default command is set once again, the command is performed with that integer. For example, `x524y312` would perform command `x` with 5, then with 2, then with 4, then perform command `y` with 3, then with 1, then with 2.
The integers that commands use represent face indexes. So `x0` would perform `x` on the UP (0-indexed) face. `x1` would perform `x` on the LEFT (1-indexed) face, and so on.
Performing any command with `6` will perform that command on the notepad value. Performing any command with any integer over 6 will result in an error.
Here are some example commands:
* `R1` - turn the RIGHT face clockwise 90° so the internal cube will look like the second example above
* `R11` - turn the RIGHT face clockwise 90° twice, identical to `R2`
* `+0` - add all values of the UP face to the notepad
* `+000` - add all values of the UP face to the notepad three times
* `@6` - print the nonexistent 6th-indexed face (memory) as a character
* `%4` - print the sum of all values on the BACK face as an integer
A complete list of commands and syntax is available at the [repository](//git.io/Cubically).
# Challenge
You will take ASCII text as input and print a Cubically program as output.
Examples (stolen from [here](https://codegolf.stackexchange.com/a/126522/61563) and [here](https://codegolf.stackexchange.com/a/126679/61563)):
```
Input -> Output
Hello, World! -> +53@6+1F2L2+0@6L2F2U3R3F1L1+2@66L3F3R1U1B3+0@6:4U1R1+00@6-000@6*0-4+000@6-00@6+2-000000@6-5+4000@6-00@6/0+00@6:0+0/0+00@6
1$2$3$4$5$6$7$8$9$10$ -> B1+2/2%6@4+00/0%6@4+00/1%6@4+21/1%6@4+30/0%6@4+22/1%6@4+22/1%6@4+40/1%6@4+52/1%6@4+42/1%6@4
```
# Rules
* Your program may not contain a dictionary containing the translations for the 100 testcases.
* Your program must finish in less than 180 seconds (no brute-force programs that take weeks).
* Your program must output valid Cubically code that finishes in less than 180 seconds.
* Your program will take input via standard input, unless you want to mess with the test driver.
* Your program must output Cubically code that produces nothing but your program's input when run. [ಠ\_ಠ](https://chat.stackexchange.com/transcript/message/38913238#38913238)
# Scoring
You will test your program with 100 pseudorandom strings of pseudorandom length. (A bash script is provided that will do this for you.) Here is how you will score:
* Let the length of the output program be **o**.
* Let the length of the input string be **l**.
* Let a variable **r** be the result of **o/l**.
* Find the average of all **r**: **(r1 + r2 + r... + r100) / 100**.
[Test with this script.](https://tio.run/##lVXtf9o2EP7uv@IKZNiFGNI2ewkhG2tplo0mWZruLUkzYR@2NlvyJDkvTdm/np1sA6bNfr9WH0DcPbp77rmTmDId3983H/WmXPSm9MNxmp@xnCbcylxBpmSkWAqRRA1cgIkRZlxpA0xFeYrC@GDBn7ws2MRK5lEsc1PE04HimelaMyJkMhchaB4JXYC5CHnADJKbGUsK0pzSpzLks1vQMkUTcxEVND6nQMdIw5Jh36HgsAeKidAPnCgIqi1symJX6AYvj05gNJnAZHS4/2a0P369U5gB@KwUKpBpxhNUPS4MqkwhfYJADDUwCFAZRurNCAF4Y1BoLkUXWBgCJxEktK3QbZhiIq99x8EgltBobTWImfWsSDw/enV8MBm/@JiJDUYsUuKsbUg6F@YBlvTwBoPcsCnlj1EhpWgC@qQa2IptirLiMtlMKtBG2Ya3XL9nZfCcUDqLJpLvUvN3OGzdNWk/XzoK3psCobWAQPvctNf91kd10advbsyqtIPD0/HJ8cn49KHqFGYJo2raNX0rveCam7gss@b0q9bQScFSDCuJuxDETERodS9PGyn9T5D3IQJQ61qNRU1sSyBCgYomOARkKuFEzVkKQndg2HI/DAm7C3W8NehSdNo/JPoCsi66Qk05ypHSAUtw@GRQw/ZWzWrAe5gG3gftovNLS3lpPo5W2KFTgBdRQilwMcqjK5IgsnddKtxpwP9F6MFWv18FoOeLiyDJQ4RdbUIu/XjPWTMlfLpuMzxFa3GuJA@t8Jd2dmXqUtMVPNbUfSno9SDBIUHhwZ1TzjMzPKh8BZQlGY1Jnp5dwHBZfKO/9eTps@0vv/r6m8bK@O@j75qtjbdfPHa9y86fm8Ozi/PzQbvr9@7m73fOG7t739bAo@@fvxi/3P/h4MefJq8Oj45/Pnl9@uaXX3/7/Y8aiE2DEGdRzP/6O0mFzP6h9za/ur65fdcYlPNgL6idGuAwhP6AvnZtPQPodPiqffqME/1VLVYL14MNcG2z5cxdeDzYhC3vogquzyjURRHYmTuOTZPS6@VaTT2nVKzIPSi2lbSET1mSyMB91vcGNZYrhtRa2nQ6C9ntqvVId92S4cbTba@zXQWxK8uNdnVlmDvz@7W/Jfug/Qc) You'll have to modify it as instructed. Note that the program does not check whether the output is valid Cubically code.
If you can't get the script working, I can help. Ping me in the [Cubically chat room](https://chat.stackexchange.com/rooms/62883/cubically).
[Answer]
# Lua, [Score](https://tio.run/##lVZZQ9tGEH7Xr5jaUCR8G0gCxjQ0ISQtOUpIL0PTtbS2N5W0rrTiCKF/PZ3Z1YkNSfRgr3Znv5n55tKYxbPPn@vfdcYi7IzxxbLq3/BYdbiSSQTzSE4jFsBU8hhECGrGYSKiWAGLpknAQ9UGEv7qh4TVLJLJdCYTpfFiNxJz1aRtzmEuk9CDWEzDWAuL0BMuUxyPmSKjIEhQfSA9MbmCWAZczUQ41WZ8i4OWkor5w66F4LAHEQu9tmtNXTddQkvqleYNnr0@hv2jIzjaf3X4bv/w4O2O3gYQE0OUK4O58HnUEaHi0Tzi@Ash514MDFweKYbsTVAC@KXiYSxk2ATmeSCQBAlrRPQajLkvL9qWxd2ZhNpKr4aW0UlhxJPXL9@8ODp4umgJgaEVAdocEyTe8xKXG/P4JXcTxcaof8YjjirqwNvIGpDHpMJ4bJRNZASxiijgK3a7QzQ4lietLIh49j4WH/lw5bqO65v8QNvdCjmsZCKwdqrWqud0hn7hb1tdqsK1F69ODo7fHB@cLPMu4nOfoTdrJX5TvuBCqJlxs3TYTkODN0MWcC@luAnujIVTTryb20rK9lfQu8wAKEWtZEWJbDJgykMeYQZ7wFnkCzTNygnBGhiu2H7CNBTsZqw4FZGcbFwvIzsTqZId8RixTSrFLvP5sD8oyXaKINXgE4xd51aY8H6@Y4plEU3vQ0MLZyieDHmWwvvn6PqUalxGfKcGdyF0oNftpgDYtkTo@onHYTdWnpDt2Z5V2fLFuLqnRMBpxzqXwiPC31POysDGYEewHmPUZYhdA2MHPg8duLZMHjMl3PRMizJ/jumRBKMzGObO17q9/sbm1oOHj7ZrxeZ/3z2ur6z@9f267bxv/N0ajs5OTwdrzXbn@ubTzmltd@@HkvD@j0@eHjw7fP7ip5@PXr56/eaX47cn73797fc//iwJsbHr8cl0Jj784wehnP@LfTY5v7i8@lgbmHygwrTJCQFD6A7wb5f8GUCjIYrwxSOB5he@EBe2A6tgU7DlxM5OHGhBzzlLweMRQp1pYOvGskhNgF3LJk4dyzCmdQ/0MqUW5QPm@9K1N7vOoGRlYSGGFheNRkY7PaUYxU3bWLi6seU0tlIQeuaJiu043bixbj63WnDIKYx4YqFOzBxcoyZMkogzz66tsxrWjjmiATOEWi19nWD5krnXMNoiNze3mjDapNXGA1xt0Kr/EFd9WvUe4apHq21UbRB8Fqsn5PYQQuFbFprzUnpcT7FsUgqak3TSJympIEaDbTMJdpwm9HD7A02w0n4D97taPEIuU2UBIaMdA92Oic5ek7zdwShhNHU7RjVkD3OpGZ0zP@GA08xNImx6CkdpLBQOGhQ0kC6CYM3TuBxfKY6ZNEdIShxLTzI8HxZOolehZh61HPM5Z6ZGtDIr7UwISL/tNtQeUyZzP@YaaBVpQ7AuYGTxdZfoLhBRpK5vk0S@uxQRMXEILxzaLvaMbSdVqc9TH4l317ikTX@OFmAnRpX4xTDB4RdiF59EMig8xZh54lzEglr2@Aq2MyNzCfICVbbyHafwsGS/MaGkB00pXUqlqqbsVSFuk9DIGkTu56JMq2giFd2ll3Vo9TKglM@UIlOv@JnFL/EK1gSmWasHpXFflA8K6CoaafGzXOJiRl82ZaeMYBnlbttaWrYkWPFOqypGU258saK07lZS5VbsWXilPxJ1PS6JtHEQP8wipiO2WmSA2bwVI0Q@ia7oI0vOcfTQNEUsAvZIC@E26TIWoNZUxL2SUAFTs/bElzKy831Kakoro/eevOj0iqBnraJgKXWluyx3TLAKxyoxMlSEMMwFtrStWyAjs2XleZP6ZLRj76yau2jyTq1yuGB13j4yxN6XEBtLEbtlxDxLFm6XgTPCzH@rdFYG@OoILJSYm3YCWyeXkyfrXYm6JEnvr9Iv1agJurusMO8L4T0BXEy6LwTvntAtBK7MesZdpUnc2SKymzm7S2dKaZK7fSu7ZeWW9C3ameOoVDZedf4H): ~~85.91~~ ~~13.50~~ ~~13.20~~ ~~12.70~~ ~~9.41~~ ~~9.32~~ ~~9.83~~ ~~9.66~~ ~~9.12~~ ~~9.06~~ 8.03 (Average)
```
-- Get input
local inp = io.read("*a")
local out = ""
local faces = { [5] = 45, [4] = 36, [3] = 27, [2] = 18, [1] = 9 }
local lastChar = nil
-- Mode the program is in
-- 2 = not set (needs :), 1 = just set (needs +), 0 = normal
local mode = 1;
for i = 1, inp:len() do
-- Character value at current position
local c = string.byte(inp, i)
if c == lastChar then
-- Repeat character
out = out .. "6"
elseif c % 9 == 0 and c <= 45 then
if #out == 0 then
out = out .. "@"
end
out = out .. (c / 9)
else
local c2 = c
-- Handle if difference from lastChar is divisible by 9
if lastChar and (c - lastChar) % 9 == 0 then
local difference = c - lastChar
if difference > 0 then
out = out .. "+"
else
out = out .. "-"
difference = difference * -1
end
for index = 5, 1, -1 do
local face = faces[index]
while difference >= face do
difference = difference - face
out = out .. index
end
end
c = 0
end
-- Handle anything not divisible by 9
local extra = c % 9
if extra > 0 then
-- Try to optimize by dividing by 9, if possible
if lastChar and math.floor(lastChar / 9) == extra then
out = out .. "/1"
mode = 1
extra = 0
else
while extra > 0 do
local n = extra > 5 and 5 or extra
if mode == 2 then
out = out .. ":"
mode = 1
elseif mode == 1 then
out = out .. "+"
mode = 0
end
out = out .. n
extra = extra - n
end
out = out .. "/1"
mode = 1
end
c = c - (c % 9)
end
-- Handle anything divisible by 9
for index = 5, 1, -1 do
local face = faces[index]
while c >= face do
if mode == 2 then
out = out .. ":"
mode = 1
elseif mode == 1 then
out = out .. "+"
mode = 0
end
c = c - face
out = out .. index
end
end
out = out .. "@6"
lastChar = c2
end
mode = 2
end
print(out)
```
[Try it online!](https://tio.run/##jVVNb9swDL37V3AeCthtnMZps63dOgzYYb3sMuxW9KDaSqNBsQJZaZsN@@0ZKdmyXLvpgCCmSerx61GWW7bfZxl84wZEtdmaSKqCSZLhCoSaas7KJD5mcRo1JrU1aIrj5nXJCl6j4g/cLG7xeb6YwM05SWfvUDojaf4epTlJ@QeUcpIu4G@DIFltvq6YRmUlZBRhOt9VycGsOGy0utdsDaLGlMgyJy9loMaEk4rzsobLdAI5qn9t657@BPUz667XTDbB1oSMeXyMlkqDIHFC1V5KXiUplCoCwDCUDysM1/DA5JYDM1BsteaVgY2qhRGqQkcHWSBIbbSo7qd3O8MTREPIFO34E0uyX3VFYlV01Eb5wTeckNtgVu/6S//TKcRfYlRyWXMLdIRtQ7AZsKrE10/U7g4RXd7a0@ThtaOIiFmVw3BJAadwkTYhrb2pkfpeuJJs6teYgeQUshTLJcfOFByWWq27SnFmpXgQtbhDx7sdXLRJeg@qAkNmXpN2FQb5uxSCOJhKcKjx6qfyuQ/xvAkncWPwdQ59stgberGDl2PI8hao6WfTIgDLr6rkT3gEdwJpluWOX2FVtD7oYLfoxrrfeo/HlcDOhUU5xxDl5dwy6xs49qqzobyxS76TiNazHlWezZ5VO7NC1tt9HJm0K5A/Gc3sxI46Bjjlsxkh8k@9A6NAbYxYi98Wi4BLikK4EzqMC2gjdXPvEWrNzGq6lErpxOuJ1EQrF/cAL07zbujtVdF1qSllNsYdN6yusN6MXCsquPIOC5vrApAkVhV53jQ1ueh4d/bTHaZ8GfeMg6z99dEi5q8hnowizkJEz5LB6RC4bZh7ZoEtBPjvCQxWrGhugsSSK/VkfYmoIyQ9vKWv7agbejG2mIdGeGCAQ9K9MrwDoxsMLux627veJfHiFdGe9N0d/aYEX/JiHrWnIp/JPCLNBj@VJsGj6X5/zaVUE3hUWpZv/gE)
Okay, I don't think I can optimize this anymore.
This version iterates through each character, adding c % 9 (where c is the character's decimal value) by doing `:5+2/1`, then adds the parts divisible by 9 by adding that face's value. For example: `:2/1+551@` to print "e", where `:2/1` adds 2, `+551` adds 99 (9 \* (5 + 5 + 1), or 9 \* 11), and `@` prints the output. Input is read with `io.read()`.
Optimizations include directly adding/subtracting after printing if the difference between characters is a multiple of 9, dividing the current value if possible rather than setting c % 9 from scratch, and repeating characters by printing the current value again rather than recalculating it. Additionally, I've implemented Kamil's method of instantly printing any face that already contains the target value, and MD XF's suggestion to not use `:` at the beginning, but instead just start with a `+`.
[Answer]
# [Cubically](//git.io/cubically), [Score](https://tio.run/##lVRbW9tGEH3Xr5j4UkuRb4rBaW1McYIhpA5QB3oDSmVpLW0j7aq7Ky4hzl@ns5IvckO/L9GDPJ6ZnTlzzqymrgwfH8vPWlPKWlP8Yxjlb3iMMtzzVEAieCDcGAJOJFAGKiQwo0IqcEWQxoSpJujkr350sgoFT4OQpyqrJz1BE1XXbkIg4SnzQdKAySyZMp96riIYdpUGBXGK7WPu09k9SB4TFVIWZDC@ZUBDceVGg7aBxWEXhMv8pmcEnrcwocEzK@MNDk4mMByPYTw8PjwfHo7e9zI3AJ3lRHk8TmhERIsyRUQiCL6BEeJLcMEjQrnI3gwzgNwpwiTlrA6u7wNFEjjUNNE1mJKI3zYNg3ghh1LFKSEyHVmDeH3y7vRoPNr/EokuhihixCx1STznpx7J4ZE74qXKnWL/kAiCLcpAmsga6Il1i3zivNmMC5BKaMErZrOlabAMnxtLETF2LelHMqg8lNGerwIZ7gYjUFmmQO1S1TbjOoZz4bup7tR6tKPjs9HkdDI6e2o6QZLIxWlqBX4XfMEtVWE@ZiHYXEiDJ5kbE39BcR280GUB0bznpxXnza@g9ykAUFCtgKJAtgYQEEYEbrAPxBURRWjGihC8A4OK2eKJannpFBc9iu5bAq0PsqForgfsLLmyNg6uJED7KQmWKZsSCCKxY75gEvuRwYt@Ibe1lq4En2DqWf8RD8@vPPkV@rJa5gc7S15W8Tkjy8Ue3iAhgb75XJBeCf6vQgucdntRAD9mlHlR6hPYkcqnvBnuGhuuiE43fYrGRHuMG059LcO13mQem7gCAp5L3AXO8FuCikJEmAUPRr7drqLeIpalulGCS5PGF1cwWA1fajsvOlvb3Zff/1BaOz8/2ytXqn9@99y0ru2/GoOLq8vLfq3ebD3MP/UuSzu7PxaSh69e748ODt8cvf1p/O745PTnyfuz819@/e33PwpJ7tTzySwI6d8fopjx5B/8@qY3t3f3H0v9fB/0dTX1EBQG0O7jz46epw@2TdfyyQuK8NezaC5MC6pgarH5zFxGLGiAY10tissLLHWVFTbmhqHbxPgtMzWnlpEzlvXuZ@aCWsyPcZe5Z261rX4B5RohSouGbS9p109BI1k3c4TVzrZlby@K6CdJlTTlwjE35o/nnX1n0hk7B51Xzrmz3/nce2k7ZsPZ6@Cr6ljdnmN3HMfZ61adhjYcu93e2tNu/cepamtrWzswv5sdt7r/Ag): 86.98
```
U3D1R3L1F3B1U1D3~:7+1(-1@3(-1%1)6:1+3111@6%1-31111+004@6:1+11111%6:1+45@6:1-1%6~:7+1)6
```
[Try it online!](https://tio.run/##Sy5NykxOzMmp/P8/1NjFMMjYx9DN2Mkw1NDFuM7KXNtQQ9fQwRhIqBpqmlkZahsbGho6mKka6oIYhtoGBiYOIGEQx1AVxDIxBQkA1ZuBtWuaKfz/75Gak5OvoxCeX5SToggA "Cubically – Try It Online")
Turns out, all you need is conditional loops, a face equal to 1, and consistent End-Of-Input behavior.
```
U3D1R3L1F3B1U1D3 set LEFT face sum to 1
~:7 read input, set notepad to input
+1 add 1 to notepad
( open loop that can always be jumped to
-1 subtract 1 from notepad
@3 print RIGHT face (ASCII 43 '+')
## the following mechanism gets the output program's ##
## notepad to the current inputted ASCII value: ##
( open loop that can always be jumped to
-1 subtract 1 from notepad
%1 print '1'
)6 jump back to loop while notepad is nonzero
## the following mechanism prints "/1@6:1" ##
:1+3111@6 set notepad to 47, print (ASCII 47 '/')
%1 print LEFT face print (integer '1')
-31111+004@6 set notepad to 64, print (ASCII 64 '@')
:1+11111%6 set notepad to 6, print (integer 6)
:1+45@6 set notepad to 58, print (ASCII 58 ':')
:1-1%6 set notepad to 0, print (integer 1)
~ read input
:7+1 set notepad to input plus 1, so EOF changes to zero
)6 loop if notepad is truthy
```
The adding/subtracting of the LEFT face is to get the loop to end when EOF is read.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), Score: ~~129.98~~ ~~11.73~~ ~~10.82~~ ~~9.62~~ ~~10.33~~ ~~10.32~~ 10.20
-1.2 point from MD XF's suggestion to use `@6666...` instead of `@6@6@6@6...` for repeating character, and superior initialization sequence
```
static void Main()
{
List<byte> input = new List<byte>();
int inChar = Console.Read();
while (inChar != -1)
{
input.Add((byte)inChar);
inChar = Console.Read();
}
Console.Write("U3D1R3L1F3B1U1D3");
byte[] sides = new byte[] { 20, 1, 14, 43, 24, 33 };
byte currentChar = 0;
if(currentChar == input[0] || sides.Contains(input[0])) Console.Write("@");
foreach (byte character in input)
{
if (currentChar == character)
{
Console.Write("6");
continue;
}
if (sides.Contains(character))
{
Console.Write(Array.IndexOf(sides, character));
continue;
}
if (currentChar < character)
{
Console.Write("+");
while (currentChar < character)
{
byte nextAdd = sides.Where(s => s + currentChar <= character).Max();
currentChar = (byte)(currentChar + nextAdd);
Console.Write(Array.IndexOf(sides, nextAdd));
}
}
if (currentChar > character)
{
Console.Write("-");
while (currentChar > character)
{
byte nextSub = sides.Where(v => currentChar - v >= character).Max();
currentChar = (byte)(currentChar - nextSub);
Console.Write(Array.IndexOf(sides, nextSub));
}
}
Console.Write("@6");
}
}
```
[Try it online!](https://tio.run/##rVRdb9owFH3Gv@KWJ0dARJqqL3xoHdU@JKpJrSoeqj4Y5zIspU5nOxRE@e3MmaFNDGxMNIoVXfv6nOOck3Dd4pnCda6F/Al3C23wqUPKVTgU8pc3NcjSFLkRmdThV5SoBO8QItkT6mfGEQb5WEwWZEl4yrR2pUBFlmttmBEcZplI4IYJSQPbVRsKbbrjhcE@CPmcG@iBxBd4n6ZBh0DpEtLYMZgyZVsHVkaWYniLLPEbX6YiRaCb3rMetKKg0rCsVA7bKgivkoTSgjtwez1c13iEgBUhlXrbO1LCIK3fx9fRbTyMvsSfo/voOq572wsFD4@gRYJ681Y2U0s4bzchsvdFEy7iJpzbZxzDqkN2EIDnSqE0G71t11L7c4gJrSz23Pkf2o/w@up4rd3SWK803S4FgX@OT4XwCu/ExorxKVAnwIIzblBZeMfg21CriQn4Wt62BXa96Kl5vJcFr53mVqKQORbFyo4NnKf/He4A3pVSbBF@lwnOf0zc7mZJxD6unVR4p@iWD@E376ZvT0Ya9T3hK4X7aLbDjG9BkTg3Nvo2JO7VjaaokNro9UFDo5Kjbtme8IbN6QGZxVUNoPuwKsIbW@q/gBzh1RbkAMquXSvyTwf7JzvY@g8H@x/g4F0@9hycFQ6WaVowg/6HOtjaUp/uYAFyioP@z@myvvNXXq2L8Q3TNGsCGWUqTc5@Aw "C# (.NET Core) – Try It Online")
My newest version actually does some manipulation of the cube! Yay!
That first `Console.Write` up there is a fixed manipulation MD XF worked out that creates this cube:
```
242
202
242
000131555313
010121535343
000131555313
424
454
424
```
The significance of this cube is that one of its sides has a sum of 1, allowing manipulations of the Notepad on a smaller scale than multiples of nine, and in particular it simplifies relative movement rather than needing to start from zero each character; in this algorithm both addition and subtraction are used to take the shortest path between characters.
MD XF's version of the initialization causes side 2 to have a sum of 14, which saves many bytes of output for ASCII distances between 14 and 20.
Now can handle inputs with internal newlines, Console.Read() gets individual characters until End of File; see the TIO link which should have the input
```
Hello,
World!
```
Shaved a couple fractions of a point by immediately outputting a character if its ASCII value just happens to already exist on a side.
[Test Script](https://tio.run/##rVZ9X9s2EP4bfYproMNuEichtNsakjUFythC6aCs24AyxVZibbaUWjIvDdlX7062kzgObPTXGpLY0unuuec5ndynyv/0afVRrc9FrY8PhKx@xkVW4UbGEYwiOYxoCEPJFHAB2mcw4JHSQKNhHDKhHTDGD76MsfYjGQ99GevEn3IjPtIVM8wYjGQsPFB8KFRizIXHXaoZTlNtQEEYY/hQenxwA0qGTPtcDBMYn5Mg0VLToF0n6Bw6EFHhOS4Zum52C1WZ3CW8wavDI@j2etDrvt476e7tHj9PhgH4ICXKleGIByyqcaFZNIoYfoNgzFNAwWWRpsjeAC2AXWsmFJeiAtTzgCMJEtYN0evQZ4G8cghhri@htNYoITIz47hqjmP78ODNfm93ZxmM8YdAQoStjFdc6sUuSxGya@bGmvYRgs8ihlFCV829D2QESkdG5DXLqZnUbeJJMhUO5y4U/8jaa@NVvJ/MJhKsVcFgbWoC62d6fXHezGEu@O3oaz3PZf/1292jN0e7b@9KJ2KjgCL89RynGUdwxbWf5pWbdDI5cKWgIfMyWivg@lQMmeE6Xa2ldB7A510AIKdUDkWOXQNgyASLsGo9YDQKOEIjM0Kw7ttrViiFTNnHpbA1pcZesJsxjvd3MT41WWQ8YgoDpDWkXBqw9kYrZ1ubK1WCW@i7dkErXD8bSXfJsrdkHMqJ8dSLJwWb1m73EvMfms0tI/a8BPd5qEGjXs8cYL/iwg1iD/lQ2uPS8TtkYSjg/cUxzUNmRsil5J5h/cIUrgwtVDyCJwqllwLbBQoIARM2jElazFRzN5tLTGkwwhqJw9NzaM@SL9UbG83Np8@@/e770nzwn0cvVtcev//miWVflP@stk/Pz85a6xWnNp7cPj8rbXV@yBl3X27v7L7a@3H/p597B68P3/xydPz25Nd3v/3@R86I9l2PDYY@/@vvIBRy9AEbbHx5dX3zsdRK68HsTsskwaEN9Rb@bJl8WlAu87l86pQj/HkuhgvLhsdgGbHlwJrO2FCFhn2eOVen6Oo8cUwmhJgwIbYry3Bqk5SxJHYruc2oRfuQBoF0rc263cqhnCNEafGmXJ7Sbq6cRqpipQgfN5/a5aeZE3ONYq0slQ1MyORTrLDHw/GN0ixskfyT0@PiQ2FoWwYBczX2WOXsmZ3I3RYxHUGNzHbejvt4doyJG1CFHXBMsnJIaujAZG6yXulxpbf6N5p1MHtEhHkJdgXzYSuHeMaR2Db0tGEbg8uAOUeMekXDK98cBFZm@6gN1Ya9YDAmxXMzQeB0Pc@yTGw7XVvwmxo@AACqvPA8tX0Xcc2s0klzp3HU7DVeNV82Tho7zVJhuUGAG0Vxj6mMlWxoDBv1CjTwf7MCm80KbOBvswmTFlnyAG4cYaPWGd56arKSJDGwFibbaf6n9XO4vU3josjCHKrKmk7ZdjGPFwb4QlysUEZdH6wUADqnrmnqeOolbooyrKzgiVLEMltm47yxWSnEfWbi4jD2F81FzMzDBD@ZuwL@ubt7/HWjiN44@8Jj14eDdHUlB@KuWEtVUchiK59E0Xi5@u6okXLpjuLLFfeDo90fcVYoAt@ZsPSxSFLq3pkXGAtLD98o8AxaCJWXxzmg19Y9MJNOtlCA6cZaAF6ehv4PJw/QaurkHi/Lck3I/yrY@WIFq5@hYOcrKHgc9wsKXhoF82GqcAmdr6pgdRr6yxU0Tr5EwWJzelZa6sr4N/kX) courtesy of MDXF
---
[Previous submission here](https://tio.run/##Zc7BasMwDAbgs/0Ubk8OXcd2GYwSGOSyQ3vpDj2rjroIXLtYykYoefbMSRiD7OCDrF@f5HjrYsKhZQqf5qNjwetO6wBX5Bs4NFV7pkun79p5YJ5LwqTvAwsIOfMVqTYHoGCLnFIsaZQo3Foxpali4Ojx8YhQ7ymgLXZanTtBE1vJkaqBBE4w5exTbl3yMeAaO0Um5C9BYf4ptMqL1C99SiRo15v1SKvvhjzaJb4qF1g2JmSpPM@KWgKb0ryOjf7/4reXaabX/TC@d/Q@PphTTL5e/QA "C# (.NET Core) – Try It Online") and explanation:
This is kinda boring, but as far as I can tell it works. Admittedly I only tried `Hello, World!` but I ran the output in the TIO Cubically interpreter and it output "Hello, World!" so I assumed it works.
Rather than actually manipulating the cube at all, the notepad is simply incremented by the sum of the 1 face (9) repeatedly until it has the right value for each character, then prints it.
[Answer]
# C++11, [Score](https://tio.run/##lVdpe9NGEP6uXzE4AcuRz4QEsC2XFAKlDYEG0isxqSytrW0kraojB8H963Rmda0Sh0PPg7zZud95d1bMrNj9/HntXm/Gg94M/9C0te94tDW4EmkEYSQWkeXDQrAYeACJy2DOozgBK1qkPguSLpDyNz@knLiRSBeuSBPpL7YjHiZt2mYMQpEGDsR8EcRSmQcOt62EodhKKCnwUwzvC4fPryAWPktcHixkGt9ToJaIxPLMvobOYQKRFThdW1vYdr6EjpAriRu8eHMIu/v7sL978PJo9@Xeu6HcBuDzDChb@CH3WNTjQcKiMGL4hoAxJwYLbBYlFqI3Rw1glwkLYi6CNliOAxxBENAkoJswY5646Goas10BjfVBAzMjSdcOwyqRZ29ev321v/f8djbkEDPxMe@Y3KKtk9osS5FdMjtNrBnm4LKIYZiFYUAnThzTNozBoIxEpdNa0@YigjiJqPPrerdHeLQ0R2hFN1F2GvOPzFy/XsP1shTIAjoBg/VCBZonSbMuJxkWiO9ucplU9b06eL93@PZw7/2qEiMWehaW1FSAzoGDC564Wa2KsJv3CC0Dy2dOjnUbbNcKFowakFknQnS/AeNVCYDSPiULBXFKYMECFiGVHWBW5HFMTSsBwcNgEsTkCMYFJq2aQgk1rldBXajUoY5YjJ4zRsW25TFzc6To9qoWNeATzOzWjSahfbmTnZnb3uQ@GFK58OKIgBVM3j3Hwhd01EXEhg24y0MPBv1@7gCnFw9sL3UYjJGjXHTdiVbb8visvpdwn9GOdi64Q3CfEmOFr2OrI9iIseciwOGBnQOPBS241jIWWwm3c5lUtbwQyZH6x1Mwy@Ib/cHm1sPtnUePnzSqzf/uPV1bv//hwYbeOjX@7pjH05OTUbPd7V0vPw1PGuPJD4ry7o/Pnu@9ePnTq59/2X998Obtr4fv3h/99vsff/6lKFkz22Hzhcv/OfP8QIT/4rhNzy8urz42Rhkf6FjqVAQHE/oj/BlTPSMwDF61Lz7mmH5VC2Ght@A@6NRsMdcLSQs6MGhNc@fxMbqaSsfaUtMojI/DSydMW1qGmIw9ksscWtT3Lc8Ttv6w3xopWVYZYmtxYRgF7PQoPYrbepbh/a3tlrGdO6EnTJNYj/ONpbZUiMEFkpdZvsqCc2YnIlJ3rCiyrtQNj/s8iWsq3kJEeHDRk1aRhAdzzB@pNhwiTizi9mlmOkbpZDj0rUu91dbw5zmfk@pg83Ebghc0H0zYGWnSVIYnizbkmsYA57qXxueWl7J2dqzyNW0nETrIt@X6tiMZY4IJIjijnPBhJJUlM6S3AukLly4evbaXER@d2nQPj8dV4GOpN63wl39Dx8yiHd9UnJaNKfNgl2GUEbQIJ2lyKaKLJGMWZHenTsToqzkVOk2jCR@g2WlWeRCXOryIVniowCO@30Pv8OAB3NrFVt5ZupwPLZ1CYvgsBZV/Oa5VP9CnIi@zKGQynhrtzoid1RHvjIonlSt6ywr58pxWU02J1zg8auSgUw8RyOudNgy227D5CP/R@kkbHm4uR4ot3vqTSc5@EZ/x8CIuZgTt4deMp5cs7s7YgqK3K2J3GR3ntoQ@81uKjvs0YQYj6PWo03dONUnzbK7BNSmfBVYYW/ZZG@9Q282piVcyk/cqnVe6BKobKz8LUJCXT@t9kzKTKIinPuFByip5mVCYJRTC2CxOMDYCTSmz8GajyW1VaFiwj1ipbONtiaspTKCma@AkvuGvDlxpaN4yHK00y6ijmPG63vIWm75We161csTCm@mowyuXZlEVo/60GgVluDidZcSgRT0k7qjQ1GFG4ZQaKY/5d7cSrb@llYaMUrWzjkCtk5mqAfUMcxIXtw4yP77Vsy/AutrpaLULFXsy/FrXNUwMH3wfiIQNFe5cStaMzexeq0k6xamSBMyzLaxyj54IFtkrTv2s5ZlgxYGvNVyO0ExVDh20Nsz6ZB@pcnXgcXrRdzD91i@DXKCaFjdW605/zZOgtFjib76sD9nTLz8nwUlQfAmb0CATqqkHesFExLDbqsJRkMMj2Oo@eTzYGmjVRWq7o/I7zMb/aJTnKL/p1fltu7VTgxZO9q2C47ND1upFJ2EguXLJ1Gt8utOoRBQbW@LIhmGyWS62W11LvQ1NqWCjp/0P): 6.37
```
#include <iostream>
#include <vector>
#include <array>
#include <limits>
#include <algorithm>
const int inf = std::numeric_limits<int>::max(),
maxDiff = 128, nFace = 6;
std::array<int, maxDiff+1> plusvalue, totalvalue, plustrace, totaltrace;
std::array<int, nFace> input;
void prtrace(int value) {
while (value) {
std::cout << plustrace[value];
value -= input[plustrace[value]];
}
}
void prexpr(int i) {
char xorwt = 0;
if (i < 0) {
xorwt = '+' ^ '-';
i = -i;
}
if (totalvalue[i] != 0 && totalvalue[i] != inf) {
std::cout << (char)('+' xor xorwt);
prtrace(totaltrace[i]);
if (totaltrace[i] != i) {
std::cout << (char)('-' xor xorwt);
prtrace(totaltrace[i] - i);
}
}
}
int main() {
std::cout << "RU";
input = {6, 15, 27, 26, 19, 42};
std::cin >> std::noskipws;
std::fill(plusvalue.begin(), plusvalue.end(), inf);
plusvalue[0] = 1; // '+'
for (int i = 0; i < nFace; ++i) { // knapsack, each value repeated inf times
int val = input[i];
if (val == 0) continue;
for (int p = 0; p <= maxDiff - val; ++p) {
if (plusvalue[p] != inf && plusvalue[p + val] > plusvalue[p] + 1) {
plusvalue[p + val] = plusvalue[p] + 1;
plustrace[p + val] = i;
}
}
}
for (int p = 0; p <= maxDiff; ++p) totalvalue[p] = plusvalue[p], totaltrace[p] = p;
totalvalue[0] = 0;
for (int sub = 1; sub <= maxDiff; ++sub) {
if (plusvalue[sub] == inf) continue;
for (int p = 0; p <= maxDiff - sub; ++p) {
if (plusvalue[p+sub] != inf && totalvalue[p] > plusvalue[p+sub] + plusvalue[sub]) { // include '+'s
totalvalue[p] = plusvalue[p+sub] + plusvalue[sub];
totaltrace[p] = p+sub;
}
}
}
// // Note: plustrace[x] = i<=nFace : plustrace[x-input[i]] + 1 = plustrace[x]
// long long sum = 0;
// for (int i = 0; i <= maxDiff; ++i) {
// sum += totalvalue[i];
// std::cout << i << '\t' << totalvalue[i] << '\t';
// prexpr(i);
// std::cout << '\n';
// }
//
// std::cout << "_______________________________\n\nAverage = " << sum / (maxDiff + 1.) << '\n';
// RU 3.98131
char ch;
int cur = 0;
while (std::cin >> ch) {
int diff = ch - cur;
prexpr(diff);
std::cout << "@6";
cur += diff; // cur = ch
}
}
/*
RU 3.98131
*/
```
Try it online! [(generate Cubically code from ASCII)](https://tio.run/##lVZZb9s4EH7Xr5hNu7Ec@U6bwxdatN3HfSi2T45bMDRtEZElQaJyoPBfrztD6iBjp90KsCRzjm848w1HPE27G873@1cy5lGxEjCVSa4ywbZzr1m7F1wlmb3Csow92QuR3EqVOyrRJsmkCtGTx5M4VyBj@q1hBrlajcdxsRWZ5N@M6RSl8/F4yx79dsfDx0e5JtXh6KoD8T@MC/xzMfG0qYYniw6UmsFwDmlU5PcsKkQHVKJYVL7TssrQQbms3w8daYw5BpgWauJ594lcQZppZZ8i197a8N0DvB5CGQnwnTW6tFOeFAqm0wZ4ofWWk1pN/4fuzKAtniuWmjtvV8chHtNMhyErOB6yDB6T7EFhYgbGQq7BlzCFgR1TpdMKWvAVWt1WE4fE5a6s0CoPTfIWcgl/oXc4PYWDVSzli1v3Kbq2T5AIb0JoN7hVXpt6oE9LXkdRyTSejfYiYvc44ouo0EXHjd6uyTxle8tk7Fe4Dt7J5y8nZdKphpjI7xcdGL7twOgSf/R@3YE3o93EspUxzOcl@5P8TqYPOVKtlq9lFPk1i3u3YkPonYbYPRGvaIFSb/zWosVgSd0ygX6fKq2Fa0yEIY2mCBA1NM0nEASUTlK@i1maM37XAcF4WFIzE6lgSqx0vyq5FXlTG9MLUJFXLt26admMKIhdr2RciEZeB5SagFKYzqoOxkKgKUWWPi80uW02mlbsI1ZayxCQgyXMwdENYPjcn5u42nB2YDg5amaoY5lJV293wKbf7b3ctdVi6fNw7MOrlBpUy0hToDwKari8uDXEoBcXElfs1LhpRuGSCqnb/I9Lidb/p5SBRmnK6WbAqaRRDcCNsCRxNXWQ@flBzX6R1uNOJ8dd2Lknw99V3cPA8ML7v4kSY4s7j5o105mZa46kW3WVJmAZbWVVeoySeGNuebE1JTeCIw3vFFwfoUZVHzpoHczck31iy@0DT9KtdaNa9HSHQSmwTauJ1X7RX@smri12@Cxf3UP226@vm/gmfn8vMrahr4MTMqE99cGvmIg57LUbOAL5/AXOe9dXw/Oh1wxSHlaHuQJeZE0flZPePr956HQNWqzMtwoen12ytgedTgPJrSHj7vHdxUkjImwsyUoXDIM1sfCwGUv9M8/awVnf2@//CwWgNxpDyRo@FLeSsyh6QvRkk7Et5GFSRCu4FUAqochED97HT3rnjCuR4SYgYzFmcTEa9HqXn5Ygc2CcixSHQA/evXr999fTM789HJ2/eXtxeXU98H7wdcQ2@b6Lu5nxIBgOfwI) and [(run Cubically code)](https://tio.run/##jVK7DsIwDPwgq5IdO537DUh8AHRC6srA15f4nBewsDjq5c6@c7o/74/9dhyv87xcKedtJV14Wxch9iMnR9SrfybSUo0EPBlQKJ3nSueYskPi3cgM3QyyUmMEUwClm3MAZhXoko8UBrl6SYO@KMNDdFWMKkq/qN6sOhbq0tK7gCm5iIqvkQ/DfvNYy8PdnkU4AVXjJuFau7cWQactaXjn2Xyka6D0GUWIj9mVqkbLSV/ZiBa7bHGAy4DjiNTxwozlxQqsDzNuAfBm4wkmt9VotVzX5eq2DkXTeNu0aK8Z1mWSf3K@@X/U/q9t63m@AQ)
Explanation:
* First the program prints "RU", which make the face sum from `{0,9,18,27,36,45}` to `{6, 15, 27, 26, 19, 42}`. What makes that face sum set useful is that the gcd is 1, so by Bézout's identity there exist a way to construct any number `d` from a sum (or difference) of those numbers.
* Therefore, if the next char is `ch` and the current notepad value is `n`, then let `d = ch - n`, we can execute Cubically commands in the form `+{digits from 0 to 5}-{digits from 0 to 5}` such that the notepad value becomes `ch`. Then just execute `%6` to print notepad value.
* To find the most efficient way to express `d` as a sum/difference of numbers in the face sum set, I use Knapsack algorithm for all numbers from 0 to 128. E.g., for `d=1`, the program gets `27 - 26 = 1`, so it prints `+2-3`, which is `27 - 26 = 1`. Which can be seen when run the program with input `abc`, the program output
>
> RU+4333@6**+2-3**@6**+2-3**@6
>
>
>
[Answer]
# C++, score: ~~4.026~~ 3.998
improvement: added M, E and S rotations; now eats even more RAM
Fortunately, there is no memory limit here! This program can use over 10 GB of RAM, if you are unlucky enough.
Uses a heavily modified A\*-like algorithm that doesn't find even nearly optimal solutions.
It takes at least 2 bytes to cause any change to the notepad, and another byte to print it, so getting a score below 3 is almost certainly impossible.
Uses a shamelessly stolen large part of the <https://codegolf.stackexchange.com/a/104881> answer to "Simulate a Rubik's cube" (by user "cmaster - reinstate monica") (for some reason I remember golfing that answer, but I can't find any related comments).
```
//#define _GLIBCXX_DEBUG
#include <x86intrin.h>
#include <cstring>
#include <iostream>
#include <streambuf>
#include <bitset>
#include <cstdio>
#include <atomic>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>
#include <random>
#include <set>
#include <list>
#include <map>
#include <unordered_map>
#include <deque>
#include <stack>
#include <queue>
#include <string>
#include <iomanip>
#include <unordered_set>
#include <thread>
#define faceMove(offset) {offset,offset+1,offset+2,offset+15,offset+28,offset+27,offset+26,offset+13}
int faceMoves[9][8] = {
faceMove(3), //Up
faceMove(39), //Left
faceMove(42), //Front
faceMove(45), //Right
faceMove(48), //Back
faceMove(81), //Down
{0,0,0,0, 0,0,0,0}, //M
{0,0,0,0, 0,0,0,0}, //E
{0,0,0,0, 0,0,0,0}, //S (these 3 move the centers in Cubically)
}, lineMoves[9][12] = {
{50,49,48,47,46,45,44,43,42,41,40,39}, //Up
{3,16,29,42,55,68,81,94,107,76,63,50}, //Left
{29,30,31,45,58,71,83,82,81,67,54,41}, //Front
{109,96,83,70,57,44,31,18,5,48,61,74}, //Right
{39,52,65,107,108,109,73,60,47,5,4,3}, //Back
{65,66,67,68,69,70,71,72,73,74,75,76}, //Down
{0*13 + 4, 1*13 + 4, 2*13 + 4, 3*13 + 4, 4*13 + 4, 5*13 + 4, 6*13 + 4, 7*13 + 4, 8*13 + 4, 5*13 + 10, 4*13 + 10, 3*13 + 10}, //M
{4*13 + 0, 4*13 + 1, 4*13 + 2, 4*13 + 3, 4*13 + 4, 4*13 + 5, 4*13 + 6, 4*13 + 7, 4*13 + 8, 4*13 + 9, 4*13 + 10, 4*13 + 11}, //E
{1*13 + 3, 1*13 + 4, 1*13 + 5, 3*13 + 7, 4*13 + 7, 5*13 + 7, 7*13 + 5, 7*13 + 4, 7*13 + 3, 5*13 + 1, 4*13 + 1, 3*13 + 1} //S
};
#undef faceMove
void cubeRotate(std::string& cube, int* move, int rotation)
{
int sign = rotation < 0 ? -1 : 1;
for(int* submove = move; submove != move + rotation; submove += sign)
{
char takeout = cube[submove[3*rotation]];
for(int j = 3; j --> 0;) cube[submove[j * rotation + rotation]] = cube[submove[j*rotation]];
cube[*submove] = takeout;
}
}
std::string cubeMove(std::string cube, int move, int inverted)
{
cubeRotate(cube, faceMoves[move + inverted] - inverted, inverted ? -2 : 2);
cubeRotate(cube, lineMoves[move + inverted] - inverted, inverted ? -3 : 3);
return cube;
}
std::string cubeStart = 1+R"(
000
000
000
111222333444
111222333444
111222333444
555
555
555 )";
std::array<char, 6> faceVals(const std::string& s)
{
std::array<char, 6> fvs {};
int xs[6] { 3, 0, 3, 6, 9, 3};
int ys[6] { 0, 3, 3, 3, 3, 6};
for(int i = 0; i < 6; i++)
{
char ts = 0;
for(int y = ys[i]; y < ys[i] + 3; y++)
for(int x = xs[i]; x < xs[i] + 3; x++)
ts += s[y * 13 + x] - '0';
fvs[i] = ts;
}
return fvs;
}
std::string target;
struct sstate
{
int i;
std::string cube;
int notepad;
char prevCmd;
int movesSincePrint = 0;
bool operator < (const sstate& rhs) const
{
return std::tie(i, notepad, cube, prevCmd) < std::tie(rhs.i, rhs.notepad, rhs.cube, rhs.prevCmd);
}
int heur() const
{
return 3 * (target.size() - i);
}
};
std::vector<std::pair<sstate, char>> neighbours(sstate of)
{
std::array<char, 6> fvs = faceVals(of.cube);
std::vector<std::pair<sstate, char>> ans;
if(target[of.i] == of.notepad) return {{{of.i+1, of.cube, of.notepad, '@', 0}, '@'}};
for(char c : "+-*/X&|:_")
ans.push_back({{of.i, of.cube, of.notepad, c}, c});
if(of.prevCmd == '+' && of.notepad < 512)
for(int i = 0; i < 6; i++)
{
if(of.notepad + fvs[i] > 512) continue;
auto next = of; next.notepad += fvs[i]; ans.push_back({next, i+'0'});
}
if(of.prevCmd == '-' && of.notepad < 512)
for(int i = 0; i < 6; i++)
{
if(of.notepad - fvs[i] > 512) continue;
auto next = of; next.notepad -= fvs[i]; ans.push_back({next, i+'0'});
}
if(of.prevCmd == '*' && of.notepad < 512)
for(int i = 0; i < 6; i++)
{
if(fvs[i] * of.notepad > 65536) continue;
auto next = of; next.notepad *= fvs[i]; ans.push_back({next, i+'0'});
}
if(of.prevCmd == '/')
for(int i = 0; i < 6; i++)
{
if(fvs[i] == 0) continue;
auto next = of; next.notepad /= fvs[i]; ans.push_back({next, i+'0'});
}
if(of.prevCmd == 'X' && of.notepad < 512)
for(int i = 0; i < 6; i++)
{
if((of.notepad ^ fvs[i]) > 512) continue;
auto next = of; next.notepad ^= fvs[i]; ans.push_back({next, i+'0'});
}
if(of.prevCmd == '&')
for(int i = 0; i < 6; i++)
{
auto next = of; next.notepad &= fvs[i]; ans.push_back({next, i+'0'});
}
if(of.prevCmd == '|' && of.notepad < 512)
for(int i = 0; i < 6; i++)
{
if((of.notepad | fvs[i]) > 512) continue;
if(fvs[i] == 0) continue;
auto next = of; next.notepad |= fvs[i]; ans.push_back({next, i+'0'});
}
if(of.prevCmd == '_')
for(int i = 0; i < 6; i++)
{
if(fvs[i] == 0) continue;
auto next = of; next.notepad %= fvs[i]; ans.push_back({next, i+'0'});
}
if(of.prevCmd == ':')
for(int i = 0; i < 6; i++)
{
auto next = of; next.notepad = fvs[i]; ans.push_back({next, i+'0'});
}
if(of.cube != cubeStart) { auto next = of; next.prevCmd = '~'; next.cube = cubeStart; ans.push_back({next, '#'}); }
std::string moves = "ULFRBDMES";
for(int i = 0; i < 9; i++)
if(of.prevCmd == moves[i])
{
auto next = of;
next.cube = cubeMove(next.cube, i, false);
next.cube = cubeMove(next.cube, i, false);
next.prevCmd = '~';
ans.push_back({next, '\''});
}
if(of.movesSincePrint < 1 || (of.movesSincePrint == 1 && 'A' <= of.prevCmd && of.prevCmd <= 'Z'))
for(int i = 0; i < 9; i++)
{
auto next = of;
next.cube = cubeMove(next.cube, i, false);
next.prevCmd = moves[i];
next.movesSincePrint++;
ans.push_back({next, moves[i]});
}
return ans;
}
struct astate
{
sstate ss;
int f;
bool operator < (const astate& rhs) const
{
if(f != rhs.f) return f < rhs.f;
if(ss.heur() != rhs.ss.heur()) return ss.heur() < rhs.ss.heur();
return ss < rhs.ss;
}
};
std::string metagolf(std::string target)
{
::target = target;
std::map<sstate, std::pair<sstate, std::string>> prev;
astate start = {{0, cubeStart, 0, '~'}, 0};
std::map<sstate, int> dists; dists[start.ss] = 0;
std::set<astate> openset; openset.insert(start);
int nodes = 0;
std::vector<int> ics(target.size() + 3);
sstate best; int bestdist = INT_MAX; bool done = false;
std::vector<std::set<std::string>> cubes(target.size() + 1);
int itsleft = 10000;
int curI = 0;
int lastChange = 0;
while(!openset.empty() && (!done || itsleft --> 0))
{
auto it = openset.begin();
auto[cs, cf] = *it; openset.erase(it);
int cd = dists[cs];
if(cs.i == target.size()) { if(cd < bestdist) bestdist = cd, best = cs; done = true; continue; }
if(cs.i < curI) continue;
if(cs.i > curI) cubes[cs.i].insert(cs.cube);
if((cubes[cs.i].size() > 1000 && cs.i > curI) || (cubes[cs.i].size() > 0 && cs.i > curI && nodes - lastChange > 5e4)) curI = cs.i, lastChange = nodes;
if(nodes % 128 == 0) printf("n=%d, cf=%d, i=%d, notepad=%d, tc=%d\r", nodes, cf, cs.i, cs.notepad, target[cs.i]);
nodes++;
for(auto[next, cmd] : neighbours(cs))
{
if(dists.count(next) && dists[next] <= cd + 1) continue;
dists[next] = cd + 1;
prev[next] = {cs, std::string(1, cmd)};
openset.insert((astate){next, cd + 1 + next.heur()});
}
}
std::string ans = "";
while(prev.count(best))
{
auto[pr, cmd] = prev[best];
best = pr;
ans += cmd;
}
std::reverse(ans.begin(), ans.end());
return ans;
}
std::string gen_random(int len)
{
static const char alphanum[] = "0123456789"
"~!@#$%^&*()_+`-=[]\\;',./{}|:\"<>?" //this is obviously not alphanumeric
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
std::string s;
while(len --> 0) s += alphanum[rand() % (sizeof(alphanum) - 1)];
return s;
}
int main()
{
//auto cube = cubeStart;
//for(int i = 0; i < 9; i++) cube = cubeMove(cube, i, 0);
//for(int i = 0; i < 9; i++) cube = cubeMove(cube, i, 1);
//printf("%s\n", cube.data());
double ans = 0;
for(int i = 0; i < 100; i++)
{
std::string s = gen_random(rand() % 35 + 5);
std::string code = metagolf(s);
printf("%s: %s\n", s.data(), code.data());
ans += code.size() * 1.0 / s.size();
}
printf("%lf\n", ans * 1.0 / 100);
//std::string ts = "Hello, World!";
//int n = ts.size();
//printf("%s\n", metagolf(ts).data());
}
```
To avoid Unicode handling, this program performs certain character substitutions: `X` corresponds to `⊕`, `&` to `·`, and `#` to `▦`.
I used this to create an answer to "Hello, World!": <https://codegolf.stackexchange.com/a/206322>
]
|
[Question]
[
In mathematics, matrix multiplication or the matrix product is a binary operation that produces a matrix from two matrices. The definition is motivated by linear equations and linear transformations on vectors, which have numerous applications in applied mathematics, physics, and engineering. In more detail, if A is an n × m matrix and B is an m × p matrix, their matrix product AB is an n × p matrix, in which the m entries across a row of A are multiplied with the m entries down a columns of B and summed to produce an entry of AB. When two linear transformations are represented by matrices, then the matrix product represents the composition of the two transformations.
Source: [Wikipedia](https://en.wikipedia.org/wiki/Matrix_multiplication)
In other words, to multiply two matrices, for example:
```
1 2 3 1 4
2 3 4 × 3 1 =
3 4 5 4 6
```
First, take row number 1 in the first matrix, column number 1 in the second matrix, and multiply `1` by `1`, `2` by `3`, and `3` by `4`.
```
1 × 1 = 1
2 × 3 = 6
3 × 4 = 12
```
Now add them together to get your first item:
```
1 2 3 1 4 19
2 3 4 × 3 1 =
3 4 5 4 6
```
For the second number in the first column of the result, you will need to take row number 2 instead of row number 1 and do the same thing.
```
1 × 2 = 2
3 × 3 = 9
4 × 4 = 16
= 27
```
After you do the entire first column, the result looks like this:
```
1 2 3 1 4 19
2 3 4 × 3 1 = 27
3 4 5 4 6 35
```
Now, do the same exact thing again, but take the second column instead of the first column, resulting in:
```
1 2 3 1 4 19 24
2 3 4 × 3 1 = 27 35
3 4 5 4 6 35 46
```
## Your task
Given two matrices (max dimensions 200x200), containing numbers in the range -10000 to 10000, where the number of columns on the first one equals the number of rows on the second, multiply the first one by the second one. (Matrix multiplication is non-commutative.)
You may take input and give output as an array of arrays (or equivalent), a matrix (if your language has that format) or a multiline string.
You may not use any built-ins for matrix multiplication.
## Test cases
```
1 2 1 2 3 4 5 13 16 19 22 25
3 4 × 6 7 8 9 10 = 27 34 41 48 55
5 6 41 52 63 74 85
2 3 3 5 15 13
3 4 × 3 1 = 21 19
5 3 11 27
1 3 1 3 7 15
9 3 × 2 4 = 15 39
1 -1000 -1999 -3997
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Z×þḅ1
```
Takes **B** and **A** as arguments and returns **A × B**.
[Try it online!](http://jelly.tryitonline.net/#code=WsOXw77huIUx&input=&args=WzEsIDIsIDMsIDQsIDVdLCBbNiwgNywgOCwgOSwgMTBd+WzEsIDJdLCBbMywgNF0sIFs1LCA2XQ)
### How it works
```
Z×þḅ1 Main link. Left argument: B. Right argument: A
Z Zip; transpose B's rows and columns.
×þ Table multiplication; multiply all columns of B (rows of B's transpose) by
all rows of A, element by element. Results are grouped by the rows of A.
ḅ1 Unbase 1; compute the sum of all flat arrays in the result.
```
[Answer]
# Python 2, ~~69~~ 66 Bytes
This just follows the standard formula, but lambda-d for conciseness :) The ungolfed code is extremely straightforward!
```
lambda x,y:[[sum(map(int.__mul__,r,c))for c in zip(*y)]for r in x]
```
*Thanks to Alexi Torhamo for saving 3 bytes! :)*
Ungolfed code:
```
x = [[1,2],[3,4],[5,6]]
y = [[1,2,3,4,5],[6,7,8,9,10]]
output = []
for row in x:
nrow = []
for col in zip(*y): # zip(*[]) transposes a matrix
nrow += [sum(a*b for a,b in zip(row,col))] # multiplication for each pair summed
output += [nrow]
print output
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes
```
vyU²øvyX*O})ˆ
```
[Try it online!](http://05ab1e.tryitonline.net/#code=dnlVwrLDuHZ5WCpPfSnLhg&input=W1s1LDNdLFsxLDNdLFs5LDNdLFsxLC0xMDAwXV0KW1sxLDNdLFsyLDRdXQ)
**Explanation**
```
v # for each row in the first matrix
yU # save the row in X
²øv # for each row in the transposition of the second matrix
yX* # multiply the rows
O # sum the elements of the resulting row
} # end inner loop
) # wrap elements of the new row in a list
ˆ # push to global list
# implicitly output global list
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~57 56~~ 54 bytes
```
e=[]:e
z=zipWith
a!b=[sum.z(*)r<$>foldr(z(:))e b|r<-a]
```
[Try it online!](https://tio.run/##JcjBCoIwGADgu0/xCx62@JOstBLXS3ToMP7DpMVGmrIpwejd16DLd/iM8i89DDFqIanVWRDBzne7mEzlvZB@HcvANtx1xfU5DQ/HAms519B/XbdVFEdl3yBgXpfb4qAEb6YPFCBlhXtCecBjssaGCPL/Yjqs0zZ4wjNesNoRxR8 "Haskell – Try It Online")
Usage:
```
Prelude> [[1,2],[3,4],[5,6]] ! [[1,2,3,4,5],[6,7,8,9,10]]
[[13,16,19,22,25],[27,34,41,48,55],[41,52,63,74,85]]
```
`foldr(zipWith(:))e` with `e=[]:e` is a shorter form of [`transpose`](https://codegolf.stackexchange.com/a/111362/56433).
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
map.(foldr1(z(+)).).flip(z$map.(*))
z=zipWith
```
[Try it online!](https://tio.run/##NcoxEsIgEIXhnlNskQJ0ZURN1IJzWCAFiZIwkriTpOLwIuOMzSu@/w1ueT1jzF7f8@hIcv@Oj1nxxLdCSCF9DMRT9UsbIVjSKdAtrEN2oMEYhQeL5oinsjU21rL271gU6@INnvGCV1T7ktnowlQuNIdphQo8tODyp/PR9UvedURf "Haskell – Try It Online")
Takes arguments in reversed order.
[Answer]
# Mathematica, 20 bytes
```
Inner[1##&,##,Plus]&
```
Anonymous function. Takes two rank-2 lists of numbers as input, and returns a rank-2 list of numbers as output. For those curious, `Inner` is a function that does a matrix-multiplication-like application of two functions to two tensors.
[Answer]
# J, ~~13~~ 9 bytes
Saved 4 bytes thanks to miles!
```
[:+/*"#:~
```
This is a capped fork:
```
[: +/ *"#:~
```
Which is equivalent to:
```
[: +/ (*"#:)~
[: +/ (*"_ 1 0)~
```
Which performs the desired multiplication; these are then summed.
With a dot product built in, 5 bytes: `+/ .*`
## Test cases
```
f =: [: +/ *"#:~
(3 3$1 2 3 2 3 4 3 4 5)f(3 2$1 4 3 1 4 6)
19 24
27 35
35 46
(3 3$1 2 3 2 3 4 3 4 5);(3 2$1 4 3 1 4 6)
+-----+---+
|1 2 3|1 4|
|2 3 4|3 1|
|3 4 5|4 6|
+-----+---+
(2 2$2 3 3 4)f(2 2$3 5 3 1)
15 13
21 19
(2 2$2 3 3 4);(2 2$3 5 3 1)
+---+---+
|2 3|3 5|
|3 4|3 1|
+---+---+
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~7~~ 6 bytes
```
mMδṁ*T
```
Please note the argument order, [try it online!](https://tio.run/##yygtzv7/P9f33JaHOxu1Qv7//x8dbahjHKsTbaRjEhsL5JmCeRAxSyhb19DAwCA2FgA "Husk – Try It Online")
-1 byte thanks to @Zgarb!
### Explanation
Basically just doing what the definition of matrix-multiplication sais:
```
mMδṁ*T -- takes arguments in reverse order, eg: [[1],[0],[-1]] [[1,2,3],[4,5,6]]
T -- transpose the first argument: [[1,0,-1]] [[1,2,3],[4,5,6]]
m -- map the following function (example element [1,0,-1])
M -- map the following function applied to [1,0,-1] (example element [1,2,3])
δṁ -- accumulate a sum of element-wise..
* -- ..multiplication: -2
-- [[-2],[-2]]
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 6 bytes
```
+/'*\:
```
[Try it online!](https://ngn.bitbucket.io/k#eJxdjkEOwjAMBO9+xd6goIpsTBrciJcA197yHh7Ex3AaChKR7Fir2bWX+XjaHe6zSOW8J2JRnEvCNEiNqwAXkMqEjAsMDIMst8pS46ObnGimblBHFfxnkjP0svUfGULYFmiJzfzjT9J2wit5ZwJV2g2vp0vEFZGgiaSV+j6y9ZiFm96H3Ock1nWP8YUewxYPNfkctAWNNDOMapbfLmI1Rw==)
Because arraylang FTW.
### How it works
```
+/'*\: Dyadic train; x: m×n matrix; y: n×p matrix
*\: Multiply eachleft; multiply each row of x to whole of y
each row of x (xr) = length-n vector
each element of xr is multiplied to each row of y
the result is m×n×p cube
+/' Sum each; sum across the 2nd axis to get the m×p matrix
```
Jelly port is `×"€S€` which only ties with [the existing solution](https://codegolf.stackexchange.com/a/100211/78410).
[Answer]
# [J](http://jsoftware.com/), 7 bytes
```
+/@:*"$
```
[Try it online!](https://tio.run/##TY5JCsJAEEX3OcUjNCRxiOnqIYMIouBKXHgFMYgb77@KlQFxUU1Vw3/vv4e0JOs5dGRsqOh0tiXn@/UyrHfHbpWaoUiej9eH3CHGIjg8gVj0uRD@f6hpaLFVkdxOJdZhI7ZFBAl7pMZ5vMU3BL11C0J01J4m/CRuQc7YCa2qWT7e4xsXg7L9DFaeC/i4YNRoRoDGp55inDbU8BIM2k6DVhHDFw "J – Try It Online")
Port of the more well-known K idiom `(+/*)\:` (for each row of x1 and entirety of x2, first-axis multiply and sum). `"$` is the shorthand for `"1 _`, which satisfies the "for each row of x1 and entirety of x2" part.
[Answer]
## R, 66 bytes
```
function(A,B)apply(B,2,function(i)apply(A,1,function(j)sum(j*i)))
```
Unnamed function taking two R-matrices as input and returns the product. It makes use of `apply` which is used to apply functions across margins of arrays. It works just as a double `for` loop in this case: for each column of `B` and for each row of `A`, return the sum of the (vectorized) products.
Compare to the pure for loop approach (`101` bytes):
```
function(A,B){M=matrix(NA,m<-nrow(A),n<-ncol(B));for(i in 1:n)for(j in 1:m)M[j,i]=sum(A[j,]*B[,i]);M}
```
[Answer]
# C#, ~~168~~ 167 bytes
```
(A,B)=>{int n=A.Length,p=B[0].Length,i=0,j=0,k=0,s;var R=new int[n,p];while(i++<n)for(j=0;j<p;){s=0;for(k=0;k<A[0].Length;)s+=A[i][k]*B[k++][j];R[i,j++]=s;}return R;};
```
Thank you @Mukul Kumar for saving 1 byte, the while loop was actually shorter this time :P
Full program with test cases:
```
using System;
class Matrix
{
static void Main()
{
Func<int[][], int[][], int[,]> a = null;
a = (A,B)=>
{
int n=A.Length,p=B[0].Length,i=0,j=0,k=0,s;
var R=new int[n,p];
while(i++<n)
for(j=0;j<p;)
{
s=0;
for(k=0;k<A[0].Length;)
s+=A[i][k]*B[k++][j];
R[i,j++]=s;
}
return R;
};
int[,] t1 = a(new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } },
new int[][] { new int[] { 1, 2, 3, 4, 5 }, new int[] { 6, 7, 8, 9, 10 } } );
int[,] t2 = a(new int[][] { new int[] { 2, 3 }, new int[] { 3, 4 } },
new int[][] { new int[] { 3, 5 }, new int[] { 3, 1 } });
int[,] t3 = a(new int[][] { new int[] { 5, 3 }, new int[] { 1, 3 }, new int[] { 9, 3 }, new int[] { 1, -1000 } },
new int[][] { new int[] { 1, 3 }, new int[] { 2, 4 } });
Console.WriteLine(IsCorrect(t1, new int[,] { { 13, 16, 19, 22, 25 }, { 27, 34, 41, 48, 55 }, { 41, 52, 63, 74, 85 } } ));
Console.WriteLine(IsCorrect(t2, new int[,] { { 15, 13 }, { 21, 19 } } ));
Console.WriteLine(IsCorrect(t3, new int[,] { { 11, 27 }, { 7, 15 }, { 15, 39 }, { -1999, -3997 } } ));
Console.Read();
}
static bool IsCorrect(int[,] answer, int[,] valid)
{
if (answer.Length != valid.Length)
return false;
for (int i = 0; i < answer.GetLength(0); i++)
for (int j = 0; j < answer.GetLength(1); j++)
if (answer[i, j] != valid[i, j])
return false;
return true;
}
}
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~12~~ 11 bytes
```
7L&!*Xs6Be!
```
Matrices are input using `;` as row separator.
[**Try it online!**](https://tio.run/##y00syfn/39xHTVErotjMKVXx//9oQwUjawVjBRNrBVMFs1guEB/EVTC1VjBTMFewULBUMDSIBQA)
Matrix multiplication without the builtin was part of [my answer to *Showcase of languages*](https://codegolf.stackexchange.com/a/76535/36398). However, when trying to reuse the original code for this answer I realized it had a bug (row vector output was incorrectly converted to a column vector). This is now corrected, both here and there. For an explanation of how the code works, see the referred post (length-11 snippet).
[Answer]
# C++14, ~~173~~ ~~168~~ ~~156~~ 146 bytes
* -5 bytes for returning via reference parameter
* -12 bytes for using foreach and `C.back()` instead counting on `i`
* -10 bytes for dropping `C.clear()` and requiring `C` to be empty at start
As unnamed lambda:
```
[](auto A,auto B,auto&C){int j,k,s=B[0].size();for(auto a:A){C.emplace_back(s);for(j=-1;++j<s;)for(k=-1;++k<B.size();C.back()[j]+=a[k]*B[k][j]);}}
```
Requires input and output as `vector<vector<int>>` and output must be empty beforehand.
Ungolfed:
```
auto f=
[](auto A, auto B, auto&C){
int j,k,s=B[0].size();
for (auto a:A){
C.emplace_back(s);
for (j=-1;++j<s;)
for (k=-1;++k<B.size();
C.back()[j]+=a[k]*B[k][j]
);
}
}
;
```
Sample:
```
int main() {
using M=std::vector<std::vector<int>>;
M a = {
{1,2,3},
{2,3,4},
{3,4,5},
};
M b = {
{1,4},
{3,1},
{4,6},
};
M c;
f(a,b,c);
for (auto&r:c){
for (auto&i:r) std::cout << i << ", ";
std::cout << "\n";
}
}
```
[Answer]
## JavaScript (ES6), 66 bytes
```
(a,b)=>a.map(c=>b[0].map((_,i)=>b.reduce((s,d,j)=>s+d[i]*c[j],0)))
```
[Answer]
## C#, 131 bytes
```
(A,B)=>new List<List<int>>(A.Select(x=>new List<int>
(B[0].Select((f,i)=>B.Select(r=>r[i])).Select(y=>x.Zip(y,(p,q)=>p*q).Sum()))));
```
I stole [Yodle's solution](https://codegolf.stackexchange.com/a/100216/62428) with the assumption that I could write this more efficiently using LINQ (as opposed to for loops). Took a few attempts but crunched it down somewhat.
Here it is broken down somewhat:
```
a = (A, B) => new List<List<int>>(
from x in A
select new List<int>(
from y in B.First().Select((f, i) => B.Select(r => r.ElementAt(i)))
select x.Zip(y, (p, q) => p * q).Sum()));
```
The only real 'trick' here is the matrix transpose, `B.First().Select((f, i) => B.Select(r => r.ElementAt(i)))`. Once we transpose the second matrix, we have two arrays `A[i,x]` and `B[j,x]`. Take the cartesian product (`i*j`) and Zip each of those `x` length arrays together.
Test code:
```
using System;
class Matrix
{
static void Main()
{
Func<int[][], int[][], List<List<int>>> a = null;
a = (A, B) => new List<List<int>>(A.Select(x => new List<int>(B[0].Select((f, i) => B.Select(r => r[i])).Select(y => x.Zip(y, (p, q) => p * q).Sum()))));
List<List<int>> t1 = a(new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 5, 6 } },
new int[][] { new int[] { 1, 2, 3, 4, 5 }, new int[] { 6, 7, 8, 9, 10 } });
List<List<int>> t2 = a(new int[][] { new int[] { 2, 3 }, new int[] { 3, 4 } },
new int[][] { new int[] { 3, 5 }, new int[] { 3, 1 } });
List<List<int>> t3 = a(new int[][] { new int[] { 5, 3 }, new int[] { 1, 3 }, new int[] { 9, 3 }, new int[] { 1, -1000 } },
new int[][] { new int[] { 1, 3 }, new int[] { 2, 4 } });
Console.WriteLine(IsCorrect(t1, new int[,] { { 13, 16, 19, 22, 25 }, { 27, 34, 41, 48, 55 }, { 41, 52, 63, 74, 85 } }));
Console.WriteLine(IsCorrect(t2, new int[,] { { 15, 13 }, { 21, 19 } }));
Console.WriteLine(IsCorrect(t3, new int[,] { { 11, 27 }, { 7, 15 }, { 15, 39 }, { -1999, -3997 } }));
Console.Read();
}
static bool IsCorrect(List<List<int>> answer, int[,] valid)
{
if (answer.Count*answer[0].Count != valid.Length)
return false;
for (int i = 0; i < answer.Count; i++)
for (int j = 0; j < answer[0].Count; j++)
if (answer[i][j] != valid[i, j])
return false;
return true;
}
}
```
[Answer]
# [Haskell](https://www.haskell.org/), 49 bytes
```
z=zipWith
m a=map(\x->foldr1(z(+))$z(map.(*))x a)
```
[Try it online!](https://tio.run/##XY1BDoIwEEX3nGIWLFodTEsBZYHXcIFNaIKGRgoEWZBevpYmGjWT/MXL@3869Xzc@t45W1k9XfTSRQZUZdRErmtyvo99O3NiyZ7S2BKPD2RH6QqKOqP0ABW0YwQwzXpYIIa65igwl1inmGEhJTSmCbQI7OhT4MlnhqXPHDmT8mcgRRGk7FMWgXj1z/QES083e7uEM8a@XqbvHfcC "Haskell – Try It Online")
Input and output are lists of columns. Maps each column of the second matrix to that row, zipped with the columns of the first matrix and scaling each, summed as a vector.
I feel that there's gotta be a nice way to make this pointfree and save a handful of bytes, but I'm not seeing it yet.
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), 9 bytes
An array lang I'm currently working on. It's not complete, but it can solve this just fine.
```
+/&*\@;:=
```
# Explanation
```
A = left matrix, B = right matrix
= Transpose B
\ Table of A and =B
+/&* Reduction via sum after multiplying
@;: After squishing (rank-2 matrix to rank-1 vector) both args
```
I'm probably going to add inner product eventually, so this solution will eventually be `+ .*` or `+/ .*`, haven't decided which yet. I can't make use of the k idiom, as multiplication between a vector and matrix is currently unsupported, resulting in a rank error.
[Answer]
# [Uiua](https://www.uiua.org/), 5 bytes
```
∺'/+×
```
[Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oi6Jy8rw5cKCk14IOKGkCBbWzEgMl1bMyA0XVs1IDZdXQpNeSDihpAgW1sxIDIgMyA0IDVdWzYgNyA4IDkgMTBdXQpmIE15IE14)
Takes two matrices in reverse order, because `∺ distribute` evaluates on the entirety of the first arg and each row of the second, and there is no mirror version of it. Other than that, this also works like the K idiom.
```
∺'/+× input: matrix A(m*k), matrix B(n*m)
∺ map over the entirety of A(m*k) and each row of B(m):
' × multiply each row of A and each element of B and
/+ sum each column
```
[Answer]
# Javascript, 128 bytes
```
m=(a,b)=>{$=[];q=0;for(x in b){c=[];j=0;for(y in a[0]){_=i=0;for(z in b[0]){_+=a[i][j]*b[q][i];i++}c.push(_);j++}$.push(c);q++}}
```
You get the result by just checking $ - it's kinda cheating, but hey, it saved a few bytes.
[Answer]
# PHP, 110 bytes
```
function f($a,$b){foreach($a as$n=>$x)foreach($b as$m=>$y)foreach($y as$p=>$v)$z[$n][$p]+=$v*$x[$m];return$z;}
```
Three loops for the elven arrays. This is so straight forward ... but there´s not much to golf.
[Answer]
# [Actually](http://github.com/Mego/Seriously), 14 bytes
Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=4pSsQDtsKeKImWBp4pmAKs6jYE3ilaE&input=W1sxLCAyXSwgWzMsIDRdLCBbNSwgNl1dCltbMSwgMiwgMywgNCwgNV0sIFs2LCA3LCA4LCA5LCAxMF1d)
```
┬@;l)∙`i♀*Σ`M╡
```
**Ungolfing**
```
Implicit input A, then B.
┬ Transpose B's rows and columns. Call it B_T.
@ Swap A to TOS.
;l) Get len(A) and move to BOS for later.
∙ Push the Cartesian product of A and B_T. Call it cart_prod.
`...`M Map the following function over cart_prod. Variable xs.
i Flatten xs onto the stack, getting a row of A and column of B.
♀* Multiply each element of A_row by each element of B_column.
Σ Sum the resulting list to get an element of A*B.
The result of the map returns every element of A*B, but in one flat list.
╡ Push a list containing len(A) non-overlapping sublists of A*B.
This separates A*B into rows.
Implicit return.
```
[Answer]
# C, 618 bytes
```
M(char*a,char*b){char*P[2];P[0]=malloc(strlen(a));P[1]=malloc(strlen(b));for(int A=0;A<strlen(a);A++){P[0][A]=a[A];};for(int B=0;B<strlen(b);B++){P[1][B]=b[B];};int H[200][200],B[200][200];int O,N,m,J;for(int Y=0;Y<2;Y++){int y=0,z=0,r=0;char j[7];int p=strlen(P[Y]);for(int i=0;i<=p;i++){if(P[Y][i]==' '||P[Y][i]==','||i==p){(Y<1)?H[y][z]=atoi(j):(B[y][z]=atoi(j));memset(j,'\0',4);(P[Y][i]==' ')?z++:y++;z=(P[Y][i]==',')?0:z;r=0;}else{j[r]=P[Y][i];r++;};};(Y<1)?O=z+1,N=y:(m=y,J=z+1);};for(int U=0;U<N;U++){for(int F=0;F<J;F++){int T=0;for(int d=0;d<O;d++){T+=H[U][d]*B[d][F];};printf("%d ",T);T=0;};printf("\n");};}
```
A named function and by *far* the longest submission here, partly due to the fact that converting the character array inputs into C 2-dimensional integer arrays is taking up the most bytes, and also because I have not golfed in C in the longest time. I am still working on shortening this as much as I can, and any tips in doing so are much appreciated.
Now, with that out of the way, this takes input through the command line with the two matrices represented by two strings, with each one containing the rows separated by commas and each row represented by space separated integers. For example, the matrices:
```
1 2 3 44 52
A= 4 5 6 B= 67 -79
7 8 9 83 90
```
would be input as:
`./a.out "1 2 3,4 5 6,7 8 9" "44 52,67 -79,83 90"`
The resulting matrix is output to STDOUT as a multiline string. For example, the output for the above input would be:
```
427 164
1009 353
1591 542
```
[Answer]
## Clojure, 60 bytes
```
#(for[a %](for[b(apply map vector %2)](apply +(map * a b))))
```
Many bytes spent on transposing the 2nd argument.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
```
->m,n{m.map{|r|n.transpose.map{|c|r.zip(c).sum{|i,j|i*j}}}}
```
[Try it online!](https://tio.run/##PY3BDoIwEETvfMXGmKBmaUQE9YA/QohBLVpCS0OLoNRvxxLUOewm82Z26@b8HPJ48I4cRc8Jz2RvaiOIrjOhZKXoZF1MTV5MLi5LohreG4aFYavibTW0d1ZSuFGtHACOICCG@YkoWTK9cDt3OZ1gBugjK4HB2@ZkoxXkyRhPv1@r1oAdRFcn9Y/MvK9mDhXXIYHEx02KkAS4HVeIUQopdDARtDaGI4hwh3s8oL@23LHUsl/vVwimaIC@tT4 "Ruby – Try It Online")
[Answer]
# [Raku](http://raku.org/), 55 bytes
```
{cross(with=>{sum @^x Z*@^y},@^a,[Z] @^b).rotor(@b[0])}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Orkov7hYozyzJMPWrrq4NFfBIa5CIUrLIa6yVschLlEnOioWKJSkqVeUX5JfpOGQFG0Qq1n7X684sVIhLb9IIU0j2sZUwdhOx8YQTFpC2bqGBgYGdrE6CtFQCSMFE7tYzf8A "Perl 6 – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 49 bytes
```
% =axes
a\b=[sum(a[i,:].*b[:,j]) for i=a%1,j=b%2]
```
[Try it online!](https://tio.run/##hY5BCoMwEEX3nuJvBC22ZEy11ZCTxCwibSHBWtEK9vRplFK662L4fwbeY9zcWUOL9zGkWa5TZJpWqmm@J0bZrNaHXavqzOkUt8cIK01MmZNtnGt/sdPQmVeiCLkAx1EUKDUarId1RyFQ4oQzKhDTaTSMtn92ffLbvpaAbJbNwFeWg/5BRYAoTLXlnhhjnw@4yIMr9W8 "Julia 1.0 – Try It Online")
~~[1 byte](https://tio.run/##yyrNyUw0rPj/X@t/SmZxQU5ipUa0oYKRtYKxgom1qYJZrIKWAkgAxFcwtVYwUzBXsFCwVDA0iNXkKijKzCvJydNAZsFNAWoBmwI2wRik11jBkJAmU6AmQyC2BNO6hgYGBlAXGFsbAc3S/A8A "Julia 1.0 – Try It Online")~~
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5.5 bytes (11 nibbles)
```
.$.`'_+!$_*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq_VU9BLU47UVVeK1ICJQiZvG0UrR0YY6RjrGsTrRQFLHBEgDSR3T2FglHbAcRMQQSJromAFFY6F6AQ)
```
.$ # map over the rows of matrix 1
. # map over the rows of
`' # transpose of
_ # matrix 2
+ # sum of
! # zip together
$_ # both rows
* # by multiplication
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
ᵐ*ᵐ∑
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fqsebp2gBcSPOiYuKU5KLoYKL7hZFh1tqGMUqxNtrGMCJE11zGJjFcBiOkARHVOgmJmOuY6FjqWOoUFsLFd0NFACqhyk0BisxFjHECxnCpYzBJOWULauoYGBAdRQkIgRSCfEegA)
```
ᵐ*ᵐ∑
ᵐ Map
* Multiply
ᵐ Map
∑ Sum
```
If a built-in for dot product is allowed, then it can be 2 bytes:
```
ᵐ∙
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fssebp3wqGPmkuKk5GKo0IKbZdHRhjpGsTrRxjomQNJUxyw2VgEspgMU0TEFipnpmOtY6FjqGBrExnJFRwMloMpBCo3BSox1DMFypmA5QzBpCWXrGhoYGEANBYkYgXRCrAcA)
]
|
[Question]
[
# Task
Write a program/function that when given 3 positive integers \$a, b\$ and \$m\$ as input outputs a positive integer \$x\$ such that \$a^x\equiv b\ (\text{mod}\ m)\$ or that no such \$x\$ exists.
A reference implementation can be found [here](https://tio.run/##bZDRboQgEEXf@Yp5ExNqFHBXm9hP6Bc0adyKuyQKBGjqfr1lsE33oRMlmXvPzA24e7xZI/Z9UjNMOnx4FdX7Yq90ZHBhsNqpfCaQarYeNtAG/GiuijaPHpaewdkvHNsOC4YBLn8@Vlr@6Q1s5KF5tUbtenXWRwj3QAgGLdoozEpCFeKkTd6jjWMwmgBDBiofoteOFm@mKKvgFh1pAU8vUJRI/1wgwevoqDaR4YJfjiWqJJkLQWF29PS/ByjzRVLq3tQM8G9rDGnI0aeD11nhh5I@fsZeciLahEuUpOhQ6wRpuuaUZk68ZyDqc0Y5F0SIOumy4TLNiLbPIT0aEvVsihyET/YN "Python 3 – Try It Online").
# Constraints
You can expect \$a\$ and \$b\$ to be less than \$m\$.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins.
# Sample Testcases
```
# a, b, m -> x
10, 10, 50 -> 1
10, 100, 200 -> 2
10, 1, 127 -> 42
35, 541, 1438 -> 83
35, 541, 1438 -> 1519
1816, 2629, 3077 -> 223
3306, 4124, 5359 -> 1923
346, 406, 430 -> None
749430, 2427332, 2500918 -> 8025683
3442727916, 3990620294, 6638635157 -> 5731137125
```
**Note:** in the third testcase the solution cannot be 0 since the solution has to be a positive number
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~59~~ ~~53~~ 51 bytes
Saved 6 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Saved 2 bytes thanks [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!!
```
p;x;f(a,b,m){for(p=a,x=1;p-b&&++x<m;)p=p*a%m;x%=m;}
```
[Try it online!](https://tio.run/##bZHbboMwDIbv@xQWEhWUVAsJ9KCU3Ux7irWaAoWNi9AIuIhW8ezMHKJ2XZH8x/D7s5GTrb@yrO@1MKLwJEmJ8q/FpfZ0IolJQqHX6XIZBOaghK8TvZKuEsZNlOh6JcvK8@G6AHyyb1mvoP44QQJX52je2dHs3zBih8D9O3c6MRJl1UKbN@2nnKCQErDBYzx34QYzTgeNNo9Uek8NQiCOUNiG7QlEIYtQ6T9MTVhMCRsptkWJ@A5n0C3mMY8HnNM7MDc6N21@HlEciUOwBGPHMWUo4X5Qy@D@wBvAsjrnBhkq5vQATfmTXwrPtvRf5g9Y7gsIgrHOLtX@gMQe86pG/yT@2Km106e2srZ6ajdo26u/ObpGr/Ac90xgCli/Duo2xwqvVBJICSgCDcFbxx7JbU3TlNPcrVt0/S8 "C (gcc) – Try It Online")
Inputs positive integers \$a,b,m\$ with \$a,b<m\$.
Outputs a positive integer \$x\$ such that \$a^x\equiv b\ (\text{mod}\ m)\$ or \$0\$ if no such \$x\$ exists.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~55~~ 51 bytes
```
def f(a,b,m,x=1):a**x%m==b<exit(x);x<m<f(a,b,m,x+1)
```
[Try it online!](https://tio.run/##TZBNboMwEIX3PsUoVaVAnQhs8tuQXbe9gwNDagkbZDstnD4dkzSNhJH95nszz@7H8NVZcdWm71wAP3pGa@kxOKwuzuvOttroMM@zNF0n1xobaOaKn7jhQ5kne5Wmw6spy9MBB8KG5H04mMMDecuT597sBbT1AVUNXQOqChfVtiNEa9D2zMETTIJT2iMoC@hc58jlO/hBqEgJ6AOYSxt030bFo2cx1X38nt3NH0OFfaD8JDLWdA5abZHGw3TBUGtLLOWEEweTcGrQYxWwhhKM6uf4rVo@eZa@b6n3bHGcJQl75h5b6p4xCG6kln/vQyg49JSUyCz6YqD/XKA84P4ZwqVB79UZGfRO23Cv8AfxP/GaZxziWmWwOELObmf6iWxSxE2hT2ziuRBMrggvolTIbdS2kuXbfE2etdhxkNlmQoWQTMqM9CIXBXnkajcN2cVCEfWpKKdBn53FXw "Python 2 – Try It Online")
A recursive function that simply tests all exponents from \$1\$ to \$m\$. Returns through exit code: a positive exponent \$x\$, or \$0\$ if no such \$x\$ exists.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~38~~ 33 bytes
Expects `(a,m)(b)` as 3 BigInts. Throws *RangeError* if there's no solution.
```
(a,m,x=m)=>g=b=>a**--x%m-b?g(b):x
```
[Try it online!](https://tio.run/##Xc5Na4NAEAbgu79iLoWdsJr9MtGWtVDooZdeegweVqvWEt1ilmIp@e12TRVCLi/LPPMu82m@zakc2i8X9va9mmo9EUM7OuoOddboQmdmswnD8a4Li8eGFHg/Tg@HAOAAwBmFNWMGOYXtFviVcTanYKuJ6x7weUPsF1MLytiPY@WRK5ksmMgZecJ3FMROpBQk269NIS4qJfOquFAUYhmn6z3pP4NUnkGxS0p/Esz8avsqyIOotsOzKT8IORgKBYUuR9AZ/IIbfnyWtj/ZYxUdbUNq8tQ2L70jBikszw5xnRaICGcojfPfVXhTriJn39zQ9g2Z1844/QE "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
Expects `(a,m)(b)` as 3 BigInts. Returns *false* if there's no solution.
NB: This version always returns the smallest solution.
```
(a,m,x=0n)=>g=b=>a**++x%m-b?x<m&&g(b):x
```
[Try it online!](https://tio.run/##Tc7NbsIwDAfwe5/Cl6EEAuQT2m3ppEk77LIXqHpIuraASDIBmvr2XcoaCR/@svyzJZ/Mr7k2l@PPbe3Ddzt2ekSGODJo6rEue211aZbL1Wp4cmv7Nry6xaJHFj8P40uVAVQAjBJIqSjUBLZbYA/G6JScJuOPd8CmDb6fTc4oVBwrGZFJkc@YiwlZznYE@I4XBATdp0vO7yoEjSoZlwSUUEX6p/hnEDIySHpPEV@Cib@Cb7M623Th8mGaA0KVIWAJuBqDLqEJ/hrO7eYcetSh92P/6W/IYAJz6zBOU4tjjX8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Lm¹%³k>
```
Inputs in the order \$m,a,b\$; outputs `0` if no \$x\$ is found.
[Try it online](https://tio.run/##yy9OTMpM/f/fJ/fQTtVDm7Pt/v83NDG24DI25TI1MQQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaHHEf5/cCNXibLv/Ov@jow0NdIDI1CBWB8I00DEygHF0DI3MgUxjUx1TEyDHxNgCJGFhaKZjZGZkqWNsYA6WNjYw0zExNDLRMTU2tQQJmAD5IDFjg9hYAA).
**Explanation:**
```
L # Push a list of values `x` in the range [1, (implicit) input `m`]
m # Take the (implicit) input `a` to the power of each of these `x`
¹% # Take each modulo the first input `m`
³k # Get the 0-based index of the first occurrence of the third input `b`
# (-1 if there are none)
> # And increase it by 1 to make it a 1-based index
# (after which it is output implicitly as result)
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 23 bytes
```
{⍺(∊×⍳⍨)(⍺⍺|⍵×⊢)⌂traj⍵}
```
[Try it online!](https://tio.run/##dc89CsJAEAXg3lNMmRTC7s5uTGobbdULrCQK4h9ioaiNgkhwRQuxsrGysxAbS73JXCSuphAkwmNgho8Ho/vtfDjW7V4zH42GUTeMwiSZkLk7tIqfBzJXMmfXsQebKZmbvcUnl9bz4UC37D5LGrTcktlQvHhckJY72uyrlaKdtVK5mmioQwcsAc7eUQzIHIHn6uB0oOGCzv0QBoKlSPxFwEXhQ2S2QQVKWiXR/zAfs6t87oHwRADICmmhENkUkXkguZCgUAXpD8E/Ky19c0z/YF/1Ag "APL (Dyalog Extended) – Try It Online")
Dyalog APL can't handle large integers, so a modulo should be performed after each iteration.
### How it works
```
{⍺(∊×⍳⍨)(⍺⍺|⍵×⊢)⌂traj⍵} ⍝ dop; ⍵ ⍺ ⍺⍺ ← a b m
( )⌂traj ⍝ Collect all iterations until duplicate is found
⍵ ⍝ starting from a:
⍵×⊢ ⍝ Multiply a
⍺⍺| ⍝ Modulo m
⍺( ⍳⍨) ⍝ Find the 1-based index of b in the result,
∊× ⍝ changing to 0 if not found
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
_╒k▬\%=)
```
Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/206700/52210), so also:
Inputs in the order \$m,a,b\$; outputs `0` if no \$x\$ is found.
[Try it online.](https://tio.run/##LYg7DkBAFAD7d4rXKHTvuyjcRCIaJIjGSSScwqlcZC2RTDEzS7eNwzr3Mbb3sU/3eTVZncfohPwCQr8RsBSfApuWqI5uDEpFuiUHlCAVuHqFqhTQWAxMCdVSUHgA)
**Explanation:**
```
_ # Duplicate the first (implicit) input `m`
╒ # Pop one and push a list in the range [1, `m`]
k # Push the second input `a`
▬ # For each value `x` in the list, take `a` to the power `x`
\ # Swap so the originally duplicated `m` is at the top of the stack
% # Take modulo-`m` on each value in the list
= # Get the first 0-based index of the value that equals the third (implicit)
# input `b` (-1 if there are none)
) # And increase it by 1 to make it a 1-based index
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [R](https://www.r-project.org/)+gmp, ~~47~~ 46 bytes
Or only [37 bytes](https://tio.run/##fc7LCsIwEIXhfd@jkIFBJrdehL6FayWptQaaVtK60JePcadCXJ9vfibEydlgwoON/gbF2a19GLbhNC1jFy/3ud/cMjODFj14s/VXdkBzZHzvoSx911mInzfMrDvrxifjBMgJNX03f3ZCQX8FclFndqkBtUpCySaXaHgFKCrRoqQ6G5KUlOJCoZa6zSn1RlShkunjoogv) by requiring input in the form of `bigz` big integer.
```
function(a,b,m)match(T,as.bigz(a)^(1:m)%%m==b)
```
[Try it online!](https://tio.run/##bY7LCsIwFET3@Y/CDVwk77ZC/8K1ktRaA01b0rrQn48RN1qFWc3hDBPT4F208Q59mCk5@6WN3dqdhqlv0uU2tqufRrDoMNBg1/YKB7TLzvn@AZYege8DLYrQNI6mTxk4wxzNvjffNUPB/gHkotzUUqNWGShZbYWKGxRG1ChZ@aNJZlBxoVBLXW@hyuzFZT5BSHoC "R – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
->a,b,m,x=0{(a**x+=1)%m==b&&x||x<m&&redo}
```
[Try it online!](https://tio.run/##TY5Ba4MwGIbv/RUf7WbUpjYmsdWydIeywy4dlN2cDF2VFbSKWnCov93GINsgyeF53vf7Ut6inyERw2of4ghnuBGk1UPTbJbCNh4zISJNa7queco0rYzPeT/4MwBkEwzjdQis9mAj/AflQ4nC9B@Wh25HyCfKHNnmI@fMHYXLprhrb@SIDfUwMLJVJUonyRiRktuUyzZzPLXd@7V8lCrB1A@O@TVGs8CKw69vaKGrOyhudQXzRVuCgMQ3a6sq0kutI4wMKwsLXdvV@efFCHpYtOj1iOB2TeOqApkXUPtIjQzgGZIwrWLYSbb@OC8f1oE1FvvD2@n0cnifQz/cAQ "Ruby – Try It Online")
The logic is straightforward: increment the exponent \$x\$ and return it if it satisfies the required equation, otherwise repeat while \$x\$ is less than \$m\$. Outputs the smallest solution for \$x\$, or `false` if no solution exists.
[Answer]
# Java 8, 97 bytes
```
(a,b,m)->{for(int x=0;x++<m;)if(a.modPow(b.valueOf(x),b.valueOf(m)).equals(b))return x;return-1;}
```
\$a\$ and \$b\$ are both `java.math.BigInteger`; \$m\$ and the output \$x\$ are both `int`.
Outputs `-1` if no \$x\$ is found.
[Try it online.](https://tio.run/##fVHLTsMwELz3K6ycbMWNnFcfCuXAjQMFqUfEYZ06JSVOSuKUoKpXPoBP5EfKJi3QqhWS5fXOzno94yWsob@cv@ziDKqK3EGab3qEpLlRZQKxItM27QAS0yWyHQ3m2blJF7fIWaiSAL8IS972aBZh/7aHW2XApDGZkpxMyI4Cl1yz/vUmKUraUpuJiBrbvtIRSxOKFxbzh@KNSmcNWa3uE9ow/pdoxhz1WkNWUclYqUxd5qSJ9oe@G213UTt0VcsMhx5mr4t0TjRqpDNTpvni8YkA2ws0qjLUFRxXKLpHH2OCe@IM5a43PMb8kIcBooE/OqGO3AH3Bt6Y@2J42uCLAQ9cL@ChH45PKgEW2qIvzgzsRHSs1jXobP4xe69l9l4ZpZ2iNs4KZZospxZMLBtsi0uMEqPGqG2LfH18ovOWnTuXv/fXcGD837pk@J2Hx2533w)
**Explanation:**
```
(a,b,m)->{ // Method with 2 BigInteger & integer parameters and integer return
for(int x=0;x++<m;) // Loop `x` in the range (0,m]:
if(a.modPow(b.valueOf(x),b.valueOf(m))
// If `a` to the power `x`, modulo `m`
.equals(b)) // equals `b`:
return x; // Return `x` as result
return-1;} // If the loop has ended without result, return -1 instead
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes
Takes in a list of `[A,M,B]`, output is either `X` or `false`. The `[3306, 5359, 4124]` test case times out on TIO, but returns the correct result locally. First Brachylog answer, so probably not the best solution. :-)
```
bhM>.>0&h;.^;M%~t?∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/PynD107PzkAtw1ovztpXta7E/lHH8v@qCtGGBjoKpkBsaBDLBeUaGYD5CAFDI3MgAeYamwJZJsYWQE0muEQMLQzNdBSMDcyBuozMjCwhyowNgIKmxqaWOgomhkYmEEEToJiJMdAKEwOz2P@YOv9HAQA "Brachylog – Try It Online")
### How it works
```
bhM>.>0&h;.^;M%~t?∧
bhM set the second item to M
>.>0 output must be between M and 0
&h input's first item (A)
;.^ A^output
;M% A^output mod M
~t? must unify with the tail from the input (B)
∧ return the output
```
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
(a#m)b=last$0:[x|x<-[1..m],mod(a^x-b)m==0]
```
[Try it online!](https://tio.run/##TZFbb5tAEIXf@RVTkgdQCMXGzq3ltVKl9CK1Uh8cW1rMBFbeC9ldbCL5v7uz4EskY7Fnzpz5dmiY3aAQh0PErmRcFoJZd509Lfp9//V2MUlTuUykriK26m/LWBZFtjw4tM5CAYsAIJpkCfhnnsXJ5Ux/0@yjQr/p/XjO5@SeeWWWPxwtD5M76ribPiaQZ/cnY56ROptMZ9SQzx@P6syLQyXP4mUQeByIWAJlAjImrkqTT6CDng4Rgysvl6S1nfvjDFxDZBu9AxbDzQ2EL24FoX@L@Cu1fC4gA9eggsHUAwqLEP7UCsNTQ1EcOwZLeZIj2tTHghwL8YsLaTql@zoBraCPQQKleKGk1/3ew54nj6DPCsLfzNpwRLiI3xgXn8IgkIyr030v1X/MKK7qJx8F47eqNCjtYK1lS3tB8Q5bNPz1fbAYfOu4QQLBhm25NhBhWqfAHbQ0HS3siAmpg/C4Jb/rjMIqgR13je7cMYxm@jyD3sRVhRSpNFgtOse1@uIDK01xHuU8n7kjxBgKWya6IYFBqy13fEsn5bBGEyfAVAWWqzUOTUzZHVHxMbJT/K3DBNYNrjcehtW0Hzvm15Sjhm3Amvk7nUkaFG0Kz8zUPkrRHmk2XUJL7hwBOQ0bxNbTd3QpM8T9/f4LHJcIgpMt9Z9XsvbHOGDYeXD4Dw "Haskell – Try It Online")
The function `(a # m) b` returns a positive integer `x` such that `a ^ x == b (mod m)`. If no such `x` exists, it returns `0`. This is done by the brute force method.
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 58 50 bytes
```
define f(a,b,m){for(;x<m;)if(a^++x%m==b)return(x)}
```
[Try it online!](https://tio.run/##RYxLCsMgEED3PYWbghIXo6P5kOQqhdoqZGEK0oJQenYzWkrBEd6bx7hbKXcftt2zwK/SySje4ZH4nJc4i43cpevyOa6rE8k/X2nnWXxKCVyBZHUsiNOP6NPwZ3p6qISWOlPZ4NjWo@qp7fUkGcLwjRDIGaUNxWin5kxVzSPdPQA "bc – Try It Online")
This just tries the integers from 1 to `m`, and outputs the first one
which satisfies being a discrete log. Otherwise, the function returns
`0` (default return value).
[Answer]
# [R](https://www.r-project.org/), 61 bytes
```
function(a,b,m){for(i in c(1:m,0))if((T=(a*T)%%m)==b)break;i}
```
[Try it online!](https://tio.run/##bc67DoJAEAXQnq@gIZkxU8y@eGj2L@gNIJiNAsmKlfHb17V0MZnqntyb8eHiHoMft/F8X682TM9l2Ny6QEc9zfiaVg8ud0s@gDjOxIhuAmgtdIcWi2JGa3vs/djdTu79swWCKZ5hzPYxk@R/QEJWSawMGR1Bqzot1KIkWcqGFFe7muKStJCajDJNijra11V8IsvCBw "R – Try It Online")
The base form of R doesn't support arbitrary-precision arithmetic (see [my other 'R+gmp' answer](https://codegolf.stackexchange.com/questions/206694/find-the-discrete-logarithm/206703#206703) for a solution using the 'gmp' library that allows this).
But, pleasingly, the step-by-step calculation of `(a^x)mod m` comes-out at only 14 bytes longer than the brute-force approach, and it's *much* faster.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
NθI⊕⌕﹪XN…·¹θθN
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMzL7koNTc1ryQ1RcMtMy9Fwzc/pTQnXyMgvxyoGFmjpo4CUHFOaXFmWWpQYl56qoahjkKhpiaIAEkhqQQB6///DY3MFQwNFAz/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `m, a, b` and outputs `0` if there is no solution. Explanation:
```
Nθ Store `m`
…·¹θ Range from 1 to `m` inclusive
XN Take powers of `a`
﹪ θ Reduce modulo `m`
⌕ N Find index of `b`
⊕ Convert to 1-indexing
I Cast to string
Implicitly print
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 84 bytes
```
\d+
*
"$+"{`,(?=(_+))((_+),)+
,$.1*$3$&
)`^(_+),\1+
$1,
L$`.*(,_+)(,_+)+$(?<=\1)
$#2
```
[Try it online!](https://tio.run/##HcgrDoAwDABQ32OMhrRrs1AQGAgX4AgLjAQEBkFwHH58zBPv3K79WCznuAp4cCjuTkpDT7Mw06eygGIwjw2WwGn6M5oAmsKIKXjSt34Eaej6aAxY1Dlb3apVag8 "Retina – Try It Online") Sadly no test suite as this uses `"$+"`, and I can't figure out how to emulate that with multiple sets of inputs (Retina just crashes when I try). Takes input in the order `m, a, b` and produces no output if there is no solution. Explanation:
```
\d+
*
```
Convert to unary.
```
"$+"{`
)`
```
Repeat `m` times...
```
,(?=(_+))((_+),)+
,$.1*$3$&
```
... multiply the second number by the second last number and insert it between the first two numbers...
```
^(_+),\1+
$1,
```
... and reduce it modulo `m`.
```
L$`.*(,_+)(,_+)+$(?<=\1)
$#2
```
Count the position of the power matching `b` starting from the end.
[Answer]
# [Io](http://iolanguage.org/), 57 bytes
```
method(a,b,m,x :=1;for(i,1,m,if((x=x*a%m)==b,return i))0)
```
[Try it online!](https://tio.run/##jY7PCsIwDIfvPkUvQis9pEn/rMrexMuGKxbcJmPC3n5mgmjxIrQl/T7yS/K4JnGsxXntu/k6XmSjW93rhZk5pXGSWRv@5yTlUi@HZt@rum711M2PaRBZKVBrkga02K4DJe5THubbsHtTfhB@OR8M35Qc99uNW6r@EqYynsM9Ri0IQplGwM4atNxMLhbOburlqVgs2MiEIy0GIuTCAURTbmNZYojbaIoRPAJGHuI9VZ6ccZ811ic "Io – Try It Online")
]
|
[Question]
[
## Challenge:
Given a matrix input, determine the amount of diagonals and anti-diagonals with duplicated numbers.
So if we have a matrix like this:
```
[[aa,ab,ac,ad,ae,af],
[ba,bb,bc,bd,be,bf],
[ca,cb,cc,cd,ce,cf],
[da,db,dc,dd,de,df]]
```
All diagonals and anti-diagonals would be:
```
[[aa],[ab,ba],[ac,bb,ca],[ad,bc,cb,da],[ae,bd,cc,db],[af,be,cd,dc],[bf,ce,dd],[cf,de],[df],
[af],[ae,bf],[ad,be,cf],[ac,bd,ce,df],[ab,bc,cd,de],[aa,bb,cc,dd],[ba,cb,dc],[ca,db],[da]]
```
**Example:**
```
[[1,2,1,2,1,2],
[1,2,3,4,5,6],
[6,5,4,3,2,1],
[2,1,2,1,2,1]]
```
All diagonals and anti-diagonals would be:
```
[[1],[2,1],[1,2,6],[2,3,5,2],[1,4,4,1],[2,5,3,2],[6,2,1],[1,2],[1],
[2],[1,6],[2,5,1],[1,4,2,1],[2,3,3,2],[1,2,4,1],[1,5,2],[6,1],[2]]
```
Removing all diagonals and anti-diagonals only containing unique numbers:
```
[[2,3,5,2],[1,4,4,1],[2,5,3,2],[1,4,2,1],[2,3,3,2],[1,2,4,1]]
```
So the output is the amount of diagonals and anti-diagonals containing duplicated numbers:
```
6
```
## Challenge rules:
* If the input matrix is empty, contains only 1 number, or contains only unique numbers across the entire matrix, the output is always `0`.
* Input is guaranteed to only contain positive digits `[1,9]` (unless it's completely empty).
* The matrix will always be rectangular (i.e. all the rows are the same length).
* I/O is flexible. Input can be taken as a list of lists of integers, or 2D array of integers, or a Matrix-object, as a string, etc. etc. You are also allowed to take one or both of the dimensions of the matrix as additional input if it would save bytes in your language of choice.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
```
Input: Output:
[[1,2,1,2,1,2], 6
[1,2,3,4,5,6],
[6,5,4,3,2,1],
[2,1,2,1,2,1]]
[[]] 0
[[1,2], 0
[3,4]]
[[1,1], 2
[1,1]]
[[9,9,9], 6
[9,9,9],
[9,9,9]]
[[7,7,7,7], 8
[7,7,7,7],
[7,7,7,7]]
[[1,1,1], 1
[2,3,4],
[2,5,1]]
[[1,8,4,2,9,4,4,4], 12
[5,1,2,7,7,4,2,3],
[1,4,5,2,4,2,3,8],
[8,5,4,2,3,4,1,5]]
[[1,2,3,4], 4
[5,6,6,7],
[8,6,6,9],
[8,7,6,5]]
```
[Answer]
# [R](https://www.r-project.org/), ~~92~~ ~~86~~ ~~82~~ 78 bytes
```
function(m,x=row(m),y=col(m),`|`=split,`^`=Map)sum(max^table^c(m|x-y,m|x+y)>1)
```
[Try it online!](https://tio.run/##rZLNioMwEMfvPkUhl4Sdgonxa9n0DXrrWbSygmBqsZYq9N3tJJRqZSlla4Ykk0z4zST5N0Pxsx6K8yFvy/pANXSqqS9UM@hVXlfGSa@pOh2rsoU0SdU2O7LTWVOddUmb7avfJKf62q17wPGrZxvOhgKjbVN2NKccBEy7BxJ8CNB89LxZlDPcDGDfYw1qx9hq3kjgPODggvvHkf834o5w/i2xHvGilE/gy6IRLkZ4jK/qLQqfvHloP3BJeOQ8qYU/VCJQIaiHTy5D@DM8stgYR2llaFKFaNKm5HZP3FcRmn/3JcZ8I81oUgrhwpkJfRR3iEfNHOMcGrEzm/L9ixA53AA "R – Try It Online")
### Explanation
First, we declare additional variables \$x\$ and \$y\$ that stand for row and column indices, respectively. Then we can delineate the diagonals and anti-diagonals by taking their difference and sum. E.g., for a 4x4 matrix:
\$x-y\$ gives:
`0 -1 -2 -3
1 0 -1 -2
2 1 0 -1
3 2 1 0`
\$x+y\$ gives:
`2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8`
Now `split(m, x-y)` and `split(m, x+y)` produce the actual lists of diagonals and anti-diagonals, which we join together.
Finally, we count the entries of the resulting list where duplicates are present.
Thanks for bytes saved:
-4 by CriminallyVulgar
-4 by digEmAll
[Answer]
# [J](http://jsoftware.com/), ~~21~~ 20 bytes
-1 byte thanks to Jonah!
```
1#.|.,&((~:&#~.)/.)]
```
[Try it online!](https://tio.run/##VVBNC8IwDL37K4Irc4NZ1y5bP2AnwZMn7x5EHOLFPyD76zVtKm482jTvJY@kr7CVuwlGDztooAVPZy/heDmfgirkRzZlVc2@LGZZH2R9DfXmcX@@YYARJkCKAhTo1emI70kZ6EbK1qpigzYZ3Pwy0wTxs2BBr4SE5QAdQYAD4Zi1mcVYHnsM82pRzTY8pqYRs6HSeSWbamxSHd2Y1okdhoCpUyVO58wS@vxG0np2xGyI/6XyvxhqiNFRNPGfwhc "J – Try It Online")
## Explanation:
```
1#. find the sum of the
, concatenation of
( ) the result of the verb in the parentheses applied to
] the input
& and
|. the reversed input
( )/. for each diagonal
~:&#~. check if all elements are unique and negate the result
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 31 bytes
```
ËcUî
ËéEÃÕc¡XéYnÃÕ mf fÊk_eZâÃl
```
[Try all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=y2NV7grL6UXD1WOhWOlZbsPVIG1mIGbKa19lWuLDbA==&input=W1tbMSwyLDEsMiwxLDJdLAogWzEsMiwzLDQsNSw2XSwKIFs2LDUsNCwzLDIsMV0sCiBbMiwxLDIsMSwyLDFdXQpbW11dCltbMSwyXSwgICAgICAgICAgICAgICAgICAgIAogWzMsNF1dCltbMSwxXSwgICAgICAgICAgICAgICAgICAgIAogWzEsMV1dCltbOSw5LDldLCAgICAgICAgICAgICAgICAgIAogWzksOSw5XSwKIFs5LDksOV1dCltbNyw3LDcsN10sICAgICAgICAgICAgICAgIAogWzcsNyw3LDddLAogWzcsNyw3LDddXQpbWzEsMSwxXSwgICAgICAgICAgICAgICAgICAKIFsyLDMsNF0sCiBbMiw1LDFdXQpbWzEsOCw0LDIsOSw0LDQsNF0sICAgICAgICAKIFs1LDEsMiw3LDcsNCwyLDNdLAogWzEsNCw1LDIsNCwyLDMsOF0sCiBbOCw1LDQsMiwzLDQsMSw1XV0KW1sxLDIsMyw0XSwgICAgICAgICAgICAgICAgCiBbNSw2LDYsN10sCiBbOCw2LDYsOV0sCiBbOCw3LDYsNV1dCl0KLVFt)
Explanation:
```
Ëc #Pad each row...
Uî #With a number of 0s equal to the number of rows
ËéEÃÕ #Get the anti-diagonals:
ËéEÃ # Rotate each row right a number of times equal to the row's index
Õ # Get the resulting columns
c #Add to that...
¡XéYnÃÕ #The diagonals:
¡XéYnà # Rotate each row left a number of times equal to the row's index
Õ # Get the resulting columns
mf #Remove the 0s from each diagonal
fÊ #Remove the all-0 diagonals
k_ Ã #Remove the ones where:
eZâ # The list contains no duplicates
l #Return the number of remaining diagonals
```
I also tried [a version](https://ethproductions.github.io/japt/?v=1.4.6&code=y6NbWVhFXX3DcmMK/F/OLVrMw2NV/F/OK1rMwyCubWcxw2tfZVriw2w=&input=W1sxLDIsMSwyLDEsMl0sICAgICAgICAgICAgCiBbMSwyLDMsNCw1LDZdLAogWzYsNSw0LDMsMiwxXSwKIFsyLDEsMiwxLDIsMV1dCi1R) based on Kirill L.'s Haskell answer, but couldn't find a good way to "group by a function of the X and Y indices" and the alternative I found wasn't good enough.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
ŒD;ŒdQƑÐḟL
```
[Try it online!](https://tio.run/##y0rNyan8///oJBfro5NSAo9NPDzh4Y75Pv///4@ONtQx0oHiWB0uBTDfWMdEx1THDMw3A7JMgCJAFWA@XDWQHwsA "Jelly – Try It Online") or **[Check out the test suite!](https://tio.run/##bVE7DsIwDN17ih7AS9qmH7EisbAwR9lgQb0AKwsr9AJcgAN0r8o94CLhxQmmoq1V6cV@79lxjoe2PTk3duvV2O13z9twffX3rRsu7/Nj45wxRlFG8beUypekXMmpIE2lJZxLoAIZcPksOpyRSIyxU4efVcJdlmpwQYeoVt53kaOkQ0OIOQucWBEU@BVx/CvAksoEyxxLk/CN/bTh7lpmUlRjLxm6Fj6@SrA0b8d7@3rOSsUbzUKGas7VvNmwbUVafGO/2Rx4EUQVtR43EVfA0NsP)**
Alternatives:
```
ŒD;ŒdQƑ€¬S
ŒD;ŒdQƑ€ċ0
```
### How it works?
```
ŒD;ŒdQƑÐḟL – Monadic link / Full program.
; – Join:
ŒD – The diagonals
with
Œd – The anti-diagonals.
Ðḟ – Discard the lists that are not:
QƑ – Invariant under deduplication.
L – Length (count them).
```
[Answer]
# JavaScript (ES6), ~~107 105 101~~ 98 bytes
```
f=(m,d=s=1)=>(m+0)[s-=~d/2]?m.some(o=(r,y)=>!r.every((v,x)=>x+d*y+m.length-s?1:o[v]^=1))+f(m,-d):0
```
[Try it online!](https://tio.run/##fVHbboMwDH3vV7C3ZJhLKLdWyvohiElVCe0mIBOpUHnZrzOHkG7SSmVFio@PfXz5PA5Hdeo/vq5eJysxTTUnLVRccUb5G2ndkBbK499VEJWH1leyFURy0sOI4ZfeF4PoR0IGuKF/c6vX0W39RnTn68VTB7aXxVC@Yy3q1ljXq@g@nE6yU7IRfiPPpCaFEwROunGcgkEEyyvBAluIIYHUACl@Y4SQY4B7AgKbktLNg9qhJj6P3hVRbZUZGSazva0rztPsAM1w/33XEnNNyWA2w3/orKWzpbHf7eh5lm/ypGG2zJbjdiPsMNZmEpN5u1pXh7Z2eH2UyECQGzCfj2MuxiBZFYv/nNZqpGiZLaOdnXUydEyt6Qc "JavaScript (Node.js) – Try It Online")
### Note
The way this code is golfed, the anti-diagonal consisting of the sole bottom-left cell is never tested. That's OK because it can't possibly contain duplicated values.
### Commented
```
f = ( // f = recursive function taking:
m, // m[] = input matrix
d = // d = direction (1 for anti-diagonal or -1 for diagonal)
s = 1 // s = expected diagonal ID, which is defined as either the sum
) => // or the difference of x and y + the length of a row
(m + 0)[ //
s -= ~d / 2 // increment s if d = -1 or leave it unchanged otherwise
] ? // if s is less than twice the total number of cells:
m.some(o = // o = object used to store encountered values in this diagonal
(r, y) => // for each row r[] at position y in m[]:
!r.every((v, x) => // for each cell of value v at position x in r[]:
x + d * y + // x + d * y + m.length is the ID of the diagonal
m.length - s ? // if it's not equal to the one we're looking for:
1 // yield 1
: // else:
o[v] ^= 1 // toggle o[v]; if it's equal to 0, v is a duplicate and
// every() fails which -- in turn -- makes some() succeed
) // end of every()
) // end of some()
+ f(m, -d) // add the result of a recursive call in the opposite direction
: // else:
0 // stop recursion
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
```
í‚εεygÅ0«NFÁ]€ø`«ʒ0KDÙÊ}g
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8NpHDbPObT23tTL9cKvBodV@bocbYx81rTm8I@HQ6lOTDLxdDs883FWb/v9/dLShjpEOFMfqKIC5xjomOqY6ZiCuGZBhAhQAyoO4cKVAbiwA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##yy9OTMpM/W/p5vL/8NpHDbPObT23tTL9cKvBodV@bocba2trHzWtObwj4dDqU5MMvF0OzzzcVZv@X@d/dLShjpEOFMfqKIC5xjomOqY6ZiCuGZBhAhQAyoO4cKVAbixXdDSYgOoE6oJyDSEGQZRY6gAhSACNAZIz1wFDkCAWJtQwmM0g88EMU6jJhjoWQLcZAU0zAUGQpCnYbSDtIAljiDtAnjGCCOhYgIQswJ6C@NNQxxTmCZgNQK8DoTlEJYhpCWGaA5lAxQA)
**Explanation**
```
í # reverse each row in input
‚ # and pair with the input
ε # for each matrix
ε # for each row in the matrix
ygÅ0« # append len(row) zeroes
NFÁ # and rotate it index(row) elements to the right
] # end loops
€ø # transpose each matrix
`« # append them together
ʒ } # filter, keep only rows that
0K # when zeroes are removed
DÙÊ # are not equal to themselves without duplicate values
g # push length of the result
```
I feel like I've missed something here.
Need to try and golf this more later.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~144~~ 136 bytes
```
lambda m:sum(l(set(d))<l(d)for d in[[r[i*x+o]for i,r in enumerate(m)if-1<i*x+o<l(r)]for o in range(-l(`m`),l(`m`))for x in[-1,1]])
l=len
```
[Try it online!](https://tio.run/##ZZDRboMwDEXf@Yo8JpuRlhQKndovYUhlImxISahSKnVfzxyHAt2wAOfm@Mbx5Wf8HpyautPHZBr72TbMvl9vlht@1SNvhTga/HaDZy3rXVX5qn@5vw51UHrA1zHtblb7ZtTcir5L5ZEIrPOCsCFAvnFfmqeGn@1ZQPyR7T3YphJkXYvEnIx208X3bmQdryoJCua3BrY@CaOtHWSQw74GXO8xy1BBmNZLITkz2CfJ6hsUxuBtq81nYCnaRuA/Itc2qAf5AAOrtuwBMB40svN6yWLdc1vot3QfmohZvp4C8hkv8coK7bIQhOd05QIj7OxIkzQmFRUoSStpXHGEEvJ5IEyqPyOJfWzujPPGKGaTkB/mvMCcjCCbfgE "Python 2 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 98 bytes
```
@(A)nnz([(q=@(Q)arrayfun(@(n)nnz(z=diag(Q,n))-nnz(unique(z)),-([m,n]=size(Q)):n))(A),q(rot90(A))])
```
[Try it online!](https://tio.run/##bVFNb4MwDL3zK7hMciQXEcrnJCT2E3pGHNBGJw5NBSuTxp9ntpPRbGsspBf7vWfHXF9v/eewnesoirYGXpQxK7Qw1Q2cVD/P/dd5MdCAkcJav439O5zQKHXgxGLGaRlgVQoP0F7QdPXHuA6kVc/EIT@cYL7eqpig6tR2hrbVmKD7OgyfQu/kQSjlI6aYYd4h3XNCKWVIIPddTPdOBQFbEvht5J3YUmy3R6yYTKnhbqa50UNmIuPd21ZIwdzwL50f4qo7@lEVKOF0vrIk7l71sDeZne1@nFjLYvgVdkWZN6XGkhaY0Awph9WLTvODMtklN2LSUQy07D@xGSwlV8p/sP9GY@bZu8b/xkrFPaconAPjyuGCMLts3w "Octave – Try It Online")
[Answer]
## Haskell, ~~118~~ 112 bytes
```
import Data.List
r#(a:b)=sum[1|(/=)=<<nub$[h|h:_<-a:r]]+[t|_:t<-a:r]#b
[]#_=0
a#_=a#[[]]
h x=[]#x+[]#(reverse x)
```
[Try it online!](https://tio.run/##dVHLboMwELz7K1aiB1CcNCa8guDWY/sFloUcCQnUQBGQKof8O10/eKhNvbLlHc3OrNeVHD7L63Wa6qb76kd4k6M8vNfDSHrHlenFy4dbw9nDfc29PMva2@WFV48qLbK9THshdnx8FOloMudCuHCK/EgkntLhXAhSwT1H9L7Dw@3L77IfSrh7UyPrFnJoZPdRgNv1dTvCASoPOAHOGfWp3YLCvPZ7dUYEQBNONKAhjQRVQITXACGsMcAigAAiSlVstDZLyx6J9X3GsQxURc9ZjSmnf7i@6XFxPlOMv2zN1e@xhPVqC2Oq43epLkwUeyFsk7XDZz3qYmZmpN5jxxWu7TKa4DB9bCRQMUuoQqafFurBKjNFOxkJpv/DNxBNDJjofzGfxWi4OljvJ60FxiHCiGcRlZznJMYElcT0Aw "Haskell – Try It Online")
```
r#(a:b) -- function '#' calculates the ant-diagonals of a matrix
-- where 'a' is the first row and 'b' all the others
-- as we recursively walk down the rows of the matrix,
-- 'r' holds the rows from before with the respective
-- head dropped
--
[h|h:_<-a:r] -- if the heads of the the current row and the rows
-- before
(/=)=<<nub$ -- contain duplicates
[1| ] -- make a singleton list [1] (else the empty list)
sum -- and take the sum thereof
+ -- and add
# -- a recursive call with
[t|_:t<-a:r] -- the tails of the current row and the rows before
b -- and the rows below
--
[]#_=0 -- base case if there aren't any tails anymore, return 0
a#_=a#[[]] -- if there are tails, but no further rows below,
-- continue with tails
h x=[]#x+[]#(reverse x) -- main function, call '#' with input matrix 'x'
-- and the reverse of it to get the number of diagonals
-- and anti-diagonals. Recursion starts with no
-- rows before the 1st row.
-- example trace of function '#'
-- input matrix:
-- [[1,2,3,4],
-- [5,6,7,8],
-- [9,9,9,9]]
--
-- | r a b a:r heads tails (r of next call)
-- -+----------------------------------------------------------------------------------
-- 1| [] [1,2,3,4] [[5,6,7,8], [[1,2,3,4]] [1] [[2,3,4]]
-- | [9,9,9,9]]
-- |
-- 2| [[2,3,4]] [5,6,7,8] [[9,9,9,9]] [[5,6,7,8], [5,2] [[6,7,8],
-- | [2,3,4 ]] [3,4 ]]
-- |
-- 3| [[6,7,8], [9,9,9,9] [] [[9,9,9,9], [9,6,3] [[9,9,9],
-- | [3,4 ]] [6,7,8 ], [7,8 ]
-- | [3,4 ], [4 ]
-- |
-- | ....
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
#S≠uṁ∂Se↔
```
[Try it online!](https://tio.run/##yygtzv7/Xzn4UeeC0oc7Gx91NAWnPmqb8v///@hoQx0jHSiO1QHzjHVMdEx1zIA8MyBtAuQDZYE8uDogLxYA "Husk – Try It Online")
## Explanation
```
#S≠uṁ∂Se↔
S hook: S f g x = f x (g x)
e pair the matrix
↔ with its reverse
ṁ∂ get the antidiagonals of each, in a single list
# count all diagonals which satisfy the following:
S hook: S f g x = f x (g x)
≠ diagonal does not equal
u itself uniquified?
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~61~~ ~~56~~ 53 bytes
```
F²FLθFL§θ⁰F⟦⁻κ×⊖⊗ιλ⟧⊞υ⊞O⎇∧λ﹪⁺μιLθ⊟υ⟦⟧§§θμλILΦυ⊙ι‹⌕ιλμ
```
[Try it online!](https://tio.run/##VU9NS8QwEL3vr8hxAiPYdYuVPRUXQXCxh72FHGIbbTBNdvMh7q@v05aiZmAe7w1v5qXtVWi9suP47gODLWczvmj3kXq48P@8Ts@u099wQXbL15k4GpcjfCI7mUFHOOg26EG7pDs4@PxmCQ3nyCyXnDU59pBxxtezDir5ACcdnApXqF0HFtnRd9l6aCytHZAZ8v4GItL4M2RCIamtmf5kG@ZjnO83TTAuwaOKaf3Ck7FJhylB7a5gps0xkkqXzeSa3PPbj6MQosAKd7jFB@pUEjeMiRILku6pptHdIhZESqKzhNUiViQtwo48pZRyvPmyPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²
```
Loop over forward and reverse diagonals; `i=0` represents forward diagonals while `i=1` represents reverse diagonals.
```
FLθ
```
Loop over each row index. This represents the index of the start of the diagonal.
```
FL§θ⁰«
```
Loop over each column index.
```
F⟦⁻κ×⊖⊗ιλ⟧
```
Calculate the row index of the diagonal at this column index. I use a `for` loop over a single-element array instead of an assignment as this avoids having to wrap the assignment into a block with the following statement, thus saving a byte.
```
⎇∧λ﹪⁺μιLθ
```
Check whether this is the first column or the diagonal is about to wrap around between bottom and top.
```
⊟υ
```
If it isn't then pop the last list from the list of lists.
```
⟦⟧
```
if it is then start a new empty list.
```
⊞O...§§θμλ
```
Add the current diagonal entry to that list.
```
⊞υ
```
And push that list (back) to the list of lists.
```
ILΦυ⊙ι‹⌕ιλμ
```
Count the number of lists that contain duplicates.
Let's take an example when `i=0` and `k=1`. This means that we've already collected two diagonals, `[[1,1,5,2],[9,4,3,5]]`. Here's our input:
```
1 8 4 2 9 4 4 4
[5]1 2 7 7 4 2 3
1 4 5 2 4 2 3 8
8 5 4 2 3 4 1 5
```
We then loop `l` from `0` to `7`. This advances both the row and column by 1 each time:
```
1 8 4 2 9 4 4 4
[5]1 2 7 7 4 2 3
1[4]5 2 4 2 3 8
8 5[4]2 3 4 1 5
```
The list is now `[[1,1,5,2],[9,4,3,5],[5,4,4]]`. However when `l` is `3`, we have `k+l=4`, a multiple of the height of the array. This means that we need to start a new list: `[[1,1,5,2],[9,4,3,5],[5,4,4],[]]`. We then continue to collect diagonal elements:
```
1 8 4[2]9 4 4 4
[5]1 2 7[7]4 2 3
1[4]5 2 4[2]3 8
8 5[4]2 3 4[1]5
```
The list is now `[[1,1,5,2],[9,4,3,5],[5,4,4],[2,7,2,1]]`. Now when `l` is `7`, we have `k+l=8`, another multiple of the height of the array. This means that we need to start a new list, which ends up with the last element of that diagonal: `[[1,1,5,2],[9,4,3,5],[5,4,4],[2,7,2,1],[4]]`.
```
1 8 4[2]9 4 4[4]
[5]1 2 7[7]4 2 3
1[4]5 2 4[2]3 8
8 5[4]2 3 4[1]5
```
By collecting wrapping diagonals starting at the first element of each row we eventually accumulate all of the diagonals of the array.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~99 98 96 94~~ 83 bytes
```
Count[DuplicateFreeQ@Diagonal[#,i]~Table~{i,-t,t=#~Total~2}&/@{#,Reverse@#},1<0,2]&
```
[Try it online!](https://tio.run/##bVJRS8MwEH7Pr4gUisKNrt26dWgw4NiDT7rNp1IkjmwGtlRq5ktp/3q9pF1EMUfpd99dvrtLchLmXZ6EUTvRCUEZrQmp6xgSGL4GCHX@BKaQwsz5M0RTZDDD@T4bfSRQYfhdBHCzZ@JB8pK6ADTH/UV9fA7OHP8f9rq@GVutR6mvEkOGLSeoO7Xm4qlr2arYyGToy46Z9AxkjsvcuP0RxJD@zOYr4cGgzYdsixcDniPGHc0tIRTXQ3nWJneQ0sdSaco5XZ31zqhS5wKoaJdKHEotjm0Q0ojTtdAHmRs2CtptaZBOgI5MUdhYHcBafsnqU/LA1nPr9f56U1aGB1fsRaMqD8IbFypCQvas61tYnj@OeOlGriopn/mlaB6AKtqteDvKtlYwMmCYL9yEEf9dMr4bQ1KE3T7i9vUwZt/GGC3BsTN7JXiSDY0i@lQpbbpv "Wolfram Language (Mathematica) – Try It Online")
* `Function[a,a~Diagonal~#&/@Range[t=-#~Total~2,-t]]` gets all diagonals of `a`-- which works because `#~Total~2` is larger than any dimension of `a`.
[Answer]
# APL+WIN, 69 bytes
Prompts for a 2d matrix of the form 4 6⍴1 2 1 2 1 2 1 2 3 4 5 6 6 5 4 3 2 1 2 1 2 1 2 1
This yields:
```
1 2 1 2 1 2
1 2 3 4 5 6
6 5 4 3 2 1
2 1 2 1 2 1
+/~(v⍳¨v)≡¨⍳¨⍴¨v←(v←⊂[1](⌽0,⍳1↓n)⌽(n⍴0),m,((n←0 ¯1+↑⍴m)⍴0),⌽m←⎕)~¨0
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5r69dplD3q3XxoRZnmo86Fh1aA2Y96twAFgKo0QMSjrqZow1iNRz17DXSA0oaP2ibnaQJ5GnlAdQaaOrk6GkBm2wQDhUPrDbUftU0ECudqQuSAynJBRvRN1aw7tMLgP9DS/2lcJgpmQGlDBSMFZGysYKJgqmAGhKZAljGarCEA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
(⌽0,⍳1↓n)⌽(n⍴0),m pad m with zeros to isolate diagonals
((n←0 ¯1+↑⍴m)⍴0),⌽m pad rotated m with zeros to isolate anti-diagonals
```
Yields:
```
1 2 1 2 1 2 0 0 0 2 1 2 1 2 1 0 0 0
0 1 2 3 4 5 6 0 0 0 6 5 4 3 2 1 0 0
0 0 6 5 4 3 2 1 0 0 0 1 2 3 4 5 6 0
0 0 0 2 1 2 1 2 1 0 0 0 1 2 1 2 1 2
v←(v←⊂[1](.....)~¨0 enclose the diagonals as a nested vector with padded zeros removed
+/~(v⍳¨v)≡¨⍳¨⍴¨v identify diagnols with duplicate entries and sum
```
[Answer]
# Perl 5, ~~89~~ 82 bytes
```
map{$i=0;map{$a[$x+$i].=$_;$b[@F-$x+$i++].=$_}/\d/g;$x++}@F;$_=grep/(.).*\1/,@a,@b
```
[TIO](https://tio.run/##K0gtyjH9/z83saBaJdPWwBrMSIxWqdBWyYzVs1WJt1ZJinZw0wULaGuDhWr1Y1L0062BQtq1Dm7WKvG26UWpBfoaepp6WjGG@joOiToOSf//WyoAIRcS@S@/oCQzP6/4v25iToGBgZt@TJ7@f11fUz0DQwA)
[Answer]
# TSQL, ~~140~~ 128 bytes
Found a way to golf 12 characters. This is no longer the longest solution.
Golfed:
```
SELECT sum(iif(y+x=j+i,1,0)+iif(y-x=j-i,1,0))FROM
@,(SELECT x i,y j,max(y)over()m,v w
FROM @)d WHERE(x*y=0or m=y)and v=w and x<i
```
Ungolfed:
```
DECLARE @ table(v int,x int,y int)
-- v = value
-- x = row
-- y = column
INSERT @ values
(1,0,0),(2,0,1),(1,0,2),(2,0,3),(1,0,4),(2,0,5),
(1,1,0),(2,1,1),(3,1,2),(4,1,3),(5,1,4),(6,1,5),
(6,2,0),(5,2,1),(4,2,2),(3,2,3),(2,2,4),(1,2,5),
(2,3,0),(1,3,1),(2,3,2),(1,3,3),(2,3,4),(1,3,5)
SELECT sum(iif(y+x=j+i,1,0)+iif(y-x=j-i,1,0))
FROM @,(SELECT x i,y j,max(y)over()m,v w FROM @)d
WHERE
(x*y=0or m=y)
and v=w
and x<i
```
**[Try it out](https://data.stackexchange.com/stackoverflow/query/973009/spot-all-antidiagonals-with-duplicated-values)**
]
|
[Question]
[
A *pandigital number* is an integer which contains every digit from 0 to 9 at least once. 1234567890, 1902837465000000, and 9023289761326634265 are all pandigital. For the purposes of this challenge, numbers such as 123456789 are not pandigital, since they do not contain a 0, even though 123456789 = 0123456789.
A *diverse* pair of integers is a pair of integers \$(a, b)\$ such that \$a^b\$ is pandigital. \$b\$ is called the *diversifying exponent*.
**Challenge:** Given an integer \$a\$, find the **smallest** corresponding diversifying exponent \$b\$. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins.
(You may assume that there exists such an exponent, that is, your program will not be given invalid input, such as a power of 10.)
Your solution must be able to handle at the minimum the given test cases, but it should theoretically handle all valid inputs.
This is [A090493](http://oeis.org/A090493) on OEIS.
## Test cases
```
2 -> 68
3 -> 39
4 -> 34
5 -> 19
6 -> 20
7 -> 18
8 -> 28
9 -> 24
11 -> 23
12 -> 22
13 -> 22
14 -> 21
15 -> 12
16 -> 17
17 -> 14
18 -> 21
19 -> 17
20 -> 51
21 -> 17
22 -> 18
23 -> 14
24 -> 19
25 -> 11
26 -> 18
27 -> 13
28 -> 11
29 -> 12
30 -> 39
31 -> 11
32 -> 14
33 -> 16
34 -> 14
35 -> 19
36 -> 10
1234567890 -> 1
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 9 bytes
```
;.≜^dl10∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/31rvUeecuJQcQ4NHHcv//zf9HwUA "Brachylog – Try It Online")
This is a function submission. The TIO link contains a wrapper that makes a function into a full program.
## Explanation
```
;.≜^dl10∧
.≜ Brute-force all integers, outputting the closest to 0
; ^ for which {the input} to the power of the number
d has a list of unique digits
l10 of length 10
∧ (turn off an unwanted implicit constraint)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
f=lambda n,k=1:11>len(set(`k`))and-~f(n,n*k)
```
Input has to be a long, as ``k`` behaves differently for longs and ints.
[Try it online!](https://tio.run/##DcxBDoIwFEXRMa7iOWjoV0hoUVGSshFjQg0UCfhLEAZO3HpleJOTO32Xl2cdgjOjfT8bC04Go0qlqrFl@WkXWQ81keUm/TnJCR8GCs7PYPSM2XLXSp0gLwhH3JXOT@dLcb1lj3IX9W5TewOVbRFNc88LYqGyFWkFodcYAtsSTo6eO8lEFP4 "Python 2 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 25 bytes
```
>:@]^:(10>#@~.@":@^)^:_&1
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7awcYuOsNAwN7JQd6vQclKwc4jTjrOLVDP9rcnGlJmfkK5hZKNgqpCkYVUC4RgZgrhmUa2oIkTWA8o0twXxjGN8QotzYrOI/AA "J – Try It Online")
Single monadic verb. The input should be an extended-precision integer (e.g. `2x`).
### How it works
```
>:@]^:(10>#@~.@":@^)^:_&1 Monadic verb. Input: base a
^: ^:_ Good old do-while loop.
&1 Given 1 as the starting point for b,
>:@] increment it each step
( ) and continue while the condition is true:
":@^ Digits of a^b
~.@ Unique digits
#@ Count of unique digits
10> is less than 10
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 32 bytes
```
{first ($_** *).comb.Set>9,1..*}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzots6i4REFDJV5LS0FLUy85PzdJLzi1xM5Sx1BPT6v2vzVXcWKlgoaRnp6epaadnZ5aGkQkTcPQyNjE1MzcwtJA8z8A "Perl 6 – Try It Online")
Pretty self-explanatory.
### Explanation
```
{ } # Anonymous code block
first ,1..* # First positive number that
($_** *) # When the input is raised to that power
.comb.Set # The set of digits
>9 # Is longer than 9
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~51 46~~ 43 bytes
Takes input as a BigInt literal. Returns [**true** instead of **1**](https://codegolf.meta.stackexchange.com/a/9067/58563).
```
f=(n,k=n)=>new Set(n+'').size>9||1+f(n*k,k)
```
[Try it online!](https://tio.run/##NYxBDoIwEADvvGJNCHQtEuBmtHzCD9Bga7BkayjRxNK31xrjbWYOc5dP6cZleqwHslcVoxaMKiMIRU/qBRe1MuJlibWb3qo/blvLNaO9qQxGbRdGIKCjExCcoW2a5oucI/gMUtuJFAmK4s8/GS05O6t6tjc2SJZ7Cpg@uU9rDANmIX4A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 41 bytes
```
->n{i=0;i+=1until(n**i).digits.uniq[9];i}
```
[Try it online!](https://tio.run/##BcFJCoAgFADQq7Qsq482R9hFxEVzH0IadBHp2e2924yvX7lPe/Uhpx3GnBml8QgVIRjBjBvqB4zCS7SyQ@dDQTKAvEpYnhVlVTctlalgVEawDNP@WW3PYBVaOv8D "Ruby – Try It Online")
[Answer]
## Haskell, 50 bytes
```
f a=until(\b->all(`elem`show(a^b))['0'..'9'])(+1)1
```
[Try it online!](https://tio.run/##BcFLCoAgEADQq8wiUMki3bmwi1jRCErSaNGHjm/vbXjvgajWCGjf8iTik@9GJOJroJDXezs@josXwrGB9T0zbBa8VULVjKmAhfNK5YEGMp4QwWlppB6kVnP9AQ "Haskell – Try It Online")
Same byte count:
```
f a=[b|b<-[1..],all(`elem`show(a^b))['0'..'9']]!!0
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~10~~ 9 bytes
Saved 1 byte thanks to *Mr. Xcoder*
```
XµINmÙgTQ
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/4tBWT7/cwzPTQwL//zc2BQA "05AB1E (legacy) – Try It Online")
**Explanation**
```
Xµ # find the first positive integer N that
INm # when the input is raised to N
Ù # and duplicate digits are removed
g # has a length
TQ # equal to 10
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
WΦχ¬№IXIθLυIκ⊞υωILυ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDLTOnJLVIw9BAR8Evv0TDOb80D0gmFpdoBOSXAyXAzEJNHQWf1Lz0kgyNUk1NIAcsmq0JAgoBpcVAYR2Fck1rroCiTJh2JPXW//8b/dctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WΦχ¬№IXIθLυIκ⊞υω
```
Repeatedly push the empty string to the empty list until there are no digits that the power of the input to the length of the list does not contain.
```
ILυ
```
Print the length of the list.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 76 bytes
```
{#{10>#?(+/|\0<|x)#x}{{+/2 99#,/|0 10\x,0}/+/99 99#,/a*\:x,0}\a::|(99#10)\x}
```
[Try it online!](https://tio.run/##NVDBboMwDL3vK5DYAUYnYjsEEk/bhxSk9kI1deqkqodUwH6dBZOc3svz87Od6/vtclvX0U35BOoz/yqqeu7Vx@zL3C/TVNWYWZsf6llloHp/UEtd1dbu4vmtd5vUn52biyCBKnu/rA83vR6ff3c3Zp5Pv1cuTuP5@4c9P/leDsvL44hsuiEgMdkNNZPesGGQt2FUG7YM4usYBS2j@AAYSQgyohBKRDOCkBC2K4ahFRLi9vYueWwsoeJGFISkYJyNFLtQx@0wJO9mkzwhWfbBLpVsnE4q3kgQS4QxkEKyEaKTkj6AQrLaDyTdmLazimFY/wE "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`|(99#10)\x` we represent numbers as reversed lists of 99 decimal digits - do that to the argument
`a::` assign to global variable `a` (k has no closures. we need `a` to be global so we can use it in subfunctions)
`{` `}{` `}\` while the first function returns falsey, keep applying the second function (aka while loop), preserving intermediate results
`a*\:x` each of `a`'s digits multiplied by each of `x`'s digits ("outer product")
`99 99#a*\:x,0` add an extra column of 0s and reshape again to 99x99, this shifts the i-th row by i items to the right, inserting 0s on the left (this works for the tests, for larger inputs 99x99 might lead to overflows)
`+/` sum
`{+/2 99#,/|0 10\x,0}/` propagate carry:
* `{` `}/` keep applying until convergence
* `0 10\x` divmod by 10 (a pair of lists)
* `|0 10\x` moddiv by 10
* `2 99#,/|0 10\x,0` moddiv by 10, with the "div" part shifted 1 digit to the right
* `+/` sum
`{10>#?(+/|\0<|x)#x}` - check for (not) pandigital:
* `|x` reverse `x`
* `0<` which digits are non-zero
* `|\` partial maxima
* `+/` sum - this counts the number of leading 0s in `x`
* `10>` are they fewer than 10?
`#` length of the sequence of powers - this is the result
[Answer]
# Pyth, ~~10~~ 8 bytes
```
fq;l{`^Q
```
Try it online [here](https://pyth.herokuapp.com/?code=fq%3Bl%7B%60%5EQ&input=36&debug=0).
```
fq;l{`^QT Implicit: Q=eval(input())
Trailing T inferred
f Return (and print) the first positive integer where the following is true:
^QT Raise input to the current number-th power
` Convert to string
{ Deduplicate
l Take the length
q Is the above equal to...
; 10
```
*Saved 2 bytes thanks to FryAmTheEggman, previous code `fq;l{j^QT;`*
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 11 bytes
```
λ?neSUL₀=;ṅ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BB%3FneSUL%E2%82%80%3D%3B%E1%B9%85&inputs=2&header=&footer=)
```
λ ;ṅ # First truthy integer n where
?ne # When raised to input^n
SUL₀= # Length of unique digits is 10
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
1*@ṾØDfƑʋ1#
```
[Try it online!](https://tio.run/##AUEAvv9qZWxsef//MSpA4bm@w5hEZsaRyosxI/8yIHIgMzYg4bifIDEwIDsgMTIzNDU2Nzg5MCDCtSA7IiDDh@KCrCBH/w "Jelly – Try It Online")
### How it works
```
1*@ṾØDfƑʋ1# Main link. Argument: n
1 Set the return value to 1.
1# Call the link to the left for k = 1, 2, ... and with right argument n,
until it returns a truthy value.
ʋ Combine the four links to the left into a dyadic chain.
*@ Compute n**k.
Ṿ Convert it to its string representation.
ØD Yield "0123456789".
fƑ Filter and return 1 is the result is equal to the left argument.
```
[Answer]
# [Tcl](http://tcl.tk/), 82 bytes
```
proc X d {while {[llength [lsort -u [split [expr $d**[incr i]] ""]]]-10} {}
set i}
```
[Try it online!](https://tio.run/##hcxBCoMwFIThfU4xBFeCoLa11pMIaVYa6oNUQ/KkBcnZ04LYbdfzzc@DTcn5ZUCPEdtrImuwKWvN/OAJyobFM4oVKjhLDGXeziMb81zRPHiQ1pBSa11UZcQWRTAMimkfBdPzm3MrB8jj0EH1yEjLiFbsHlX5j9bNz9an86W5trdS7Dqj7n7A9AE "Tcl – Try It Online")
[Answer]
# [Racket](https://racket-lang.org/), 110 96 bytes
-14 bytes thanks to UltimateHawk!
```
(define(f n[b 1])(if(= 10(length(remove-duplicates(string->list(~v(expt n b))))))b(f n(+ b 1))))
```
[Try it online!](https://tio.run/##dY67DsIwDEV3vsIqiyNUqQ8oMMCPAENanBKRmigJFSz8OqQUIRY8@VjyudfJ5kzhOTWSW3Aj4JGUZkIFvKshPwjUCjeQZ2iI23BCR92lp/R4tUY3MpBHH5zmNt0a7QM@eqSbDcBQi/fUgwpnEGUDxgDtrZF3iPdCiMmXkz0nP4idtKDgkxcLxDX2JCigrEbX/18FeVHOF9Vytc5i5gs "Racket – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~52~~ 47 bytes
thanks to @BMO
```
f=lambda n,i=1:len({*str(n**i)})>9or 1+f(n,i+1)
```
[Try it online!](https://tio.run/##JclBDsIgEEDRPacYdzOURSlqWxK8C8aik9Rpg2yM8exI4t@9/P1dHpu4WlNY4/N6iyCGg/XrIvjRr5JRtGb60mXeMtguYfudpZoaGVggR7kvOBhwI3kFLU7tHALYHjzsmaUgG0jIREr9ndAO7ng6j9PcE9Uf "Python 3 – Try It Online")
[Answer]
# Java, 108 bytes
```
a->{int b=0;while(new java.math.BigDecimal(a).pow(++b).toString().chars().distinct().count()<10);return b;};
```
[Try it online!](https://tio.run/##fZRNb4MgGMfP66fgiGlqBJzVOHdYdt1pOzRZdkDLWjqLBrFt0vSrz6GQLV0KHiB5fjxv/0fY0QNd7NZfw9D2Zc0rUNW068AL5QKcZ0B/XCgmP2nFwMparBUIOK40yCfrZTZtnaJKh1mBEygAXTyexzNlEeXHLa8ZFOwIdjpnuKdqGz7xzTOr@J7WkAZh2xzhfF4GoWpeleRiA4Ow2lLZ6X3NO8VFpUZT0wu9P6AoyCVTvRSgzC@5SW@7sFUcGr4Ge90LNAHfPwCVmy7QjdyxE6t6xd5Yp3SCqx5ayQ9Usaso18enY39qaMmYVPAUCogDUBQgSW3Ef5RMlGS3aWxofJveTxQ5fJOJ4ug2XRpfR1Wp8XXQzFBHVQgZTBzY6IGxAxM/Nopg5MBWEpe30QQtHdiK4mos9efOvMH1IEZ87/DGyO@NvfPCxFs5jr1/CraquUpL/Lmtao5549QfPPNOjETe@0GQNzjBXlmIVS1x4Njv7b9@xKoW/b4kl2EYvptW8UZ0w4LRYXxTfwA "Java (JDK) – Try It Online")
**Explanation**
Brute force, looping a^b until it finds a string with 10 (or more, but that's impossible as there will only be 0 through 9) unique characters.
`BigDecimal` is required both because `Math.pow` is not accurate enough (fails on case `11`), and also because converting a `Double` to a String by default shows scientific notation, which breaks this method of finding a pandigital number.
[Answer]
## [W](https://github.com/A-ee/w) `d`, ~~8~~ 5 bytes
This answer was made to fullfill lirtosiast's bounty.
```
Ö↕,╣⌡
```
Uncompressed:
```
xUT=iX
```
## Explanation
```
iX % For every item in the range from 1 to infinity:
x % Exponentiate b with a
U % Uniquify the value (Numbers are cast to a string)
T= % Is the length equal to 10?
% (Due to the unique mechanism in W, this finds the length
% of the string before the operation is done.)
% If that's true, output the number and halt.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 107 bytes
```
param([bigint]$a)for([bigint]$b=1;-join("$([bigint]::pow($a,$b))"|% t*y|sort -u)-ne-join(0..9);$b=$b+1){}$b
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXIzopMz0zryRWJVEzLb8IwU2yNbTWzcrPzNNQUoGLWlkV5JdrqCTqqCRpairVqCqUaFXWFOcXlSjolmrq5qVCNBjo6VlqWgNNUEnSNtSsrlVJ@v//vzkA "PowerShell – Try It Online")
Pretty straightforward, just a shame we need to use `[bigint]` everywhere. We take input `$a`, then setup a `for` loop with initializer `$b=1`.
Each iteration we increment `$b` after checking whether `$a ^ $b` (via `pow`) sent `t`oCharArra`y`, `sort`ed with the `-u`nique flag, then `-join`ed together into a string is `-n`ot`e`qual to the range `0..9` also `-join`ed into a string.
That's a mouthful. For example, this would compare `7 ^ 5 = 16807 --> "01678"` against `"0123456789"`, determine they're not equal, and continue the loop.
Once we're out of the loop, we've determined which `$b` suits our input, and so leave that on the pipeline. Output is implicit.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~107~~ 101 bytes
```
import StdEnv,Data.Integer
$a=hd[b\\b<-[1..]|length(removeDup[c\\c<-:toString(prod(repeatn b a))])>9]
```
[Try it online!](https://tio.run/##Lc27CsIwFIDh3ac4g0ODNnhBoaJOdRAchI5phtM0toXciEdB8NmNBR1//uFTRqNL1rcPo8Hi4NJgg48EFbUn95yXSMjPjnSn42SKh74VTV03@1wsOZdvo11HfRa19U9dPoJQda32@Y58RXFwXRaib8cdNJKDBpAxyY6FTBXhiBxGMkA2BQ/k/wqDTKw4LyTMZiCWI7PeSpY@6mawu6f8fEnly6Ed1C@uBunmo015nzaLhf0C "Clean – Try It Online")
Takes input as `Integer`, returns `Int`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
(For[n=1,!AllTrue[DigitCount[#^n],#>0&],n++];n)&
```
[Try it online!](https://tio.run/##DcnBCsIgGADgZwlBiv3QbLWKWCwWHTpFdBMDCbcE/Q1xJ9le3bx@n5Xhq6wM@iNT36TlzXmODYPFxZiXHxW/6kGHzo0YOHmjAHIuqQAsCnHCFU0Pr/NEAn1LJrpuO2d/RlmV8SlxULyqBUQGrJzEfHca58g21XZX7w/HTOkP "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 27 bytes
```
${Generate{#Unique[x^_]>9}}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@1@l2j01L7UosSS1Wjk0L7OwNDW6Ii4@1s6ytva/X2pqSnG0SkFBcnosV0BRZl5JSGpxiXNicWpxdJqOgpGVsZm6oZGxiamZuYWlQVycoUHsfwA "Attache – Try It Online")
## Explanation
```
${Generate{#Unique[x^_]>9}}
${ } lambda, input: x
Generate{ } first natural number _ satisfying...
x^_ the input to that number
Unique[ ] unique digits of ^
# length of ^
>9 is greater than 9
i.e.: has 10 distinct digits
```
## Alternatives
**28 bytes:** `${Generate{Unique@S[x^_]@9}}`
**29 bytes:** `${Generate{Unique[S[x^_]]@9}}`
**30 bytes:** `${Generate{#Unique[S[x^_]]>9}}`
**31 bytes:** `Generate@${{#Unique[S[x^_]]>9}}`
**32 bytes:** `${Generate[{#Unique[S[x^_]]>9}]}`
**33 bytes:** `${If[#Unique[x^y]>9,y,x&$!-~y]}&0`
**34 bytes:** `${If[#Unique[x^y]>9,y,$[x,y+1]]}&0`
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 20 bytes
```
:i;0{).i\?`.|,10<}do
```
My first stab at it, pretty happy with my solution.
TLDR; Takes i as the base, and makes a 0. Open block. Incrememnt that 0 by 1, then put it as an exponent of i. Turn it into a string, then check how many characters there are. If 10, stop. If not, repeat block.
Successful exponent printed on program termination.
[Try it online!](https://tio.run/##S8/PSStOLsosKPlv/N8q09qgWlMvM8Y@Qa9Gx9DApjYl//9/AA "GolfScript – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 18 bytes
```
rir0?^{NBL[10==}fi
```
[Try it online!](https://tio.run/##Dcw7CsJAFIbR/lvN3P/OswiCtbiBgIUQIRAFI6lC1j5mAec8t3WZft9t6stn7@u8hstjv19vo4VhOF5zP95jF04kkSlUGmaYMMcilrCMFaxiDQVkSMhRRAllVFBFDQ@44efneMQTflp5TLnUFv4 "Burlesque – Try It Online")
```
ri # Read input as int
r0 # Range [0,inf]
?^ # Raise to power
{
NB # Unique digits
L[10== # Length == 10
}fi # Find index of first which
```
[Answer]
# [Perl 5](https://www.perl.org/) `-Mbigint -n`, ~~61~~ 43 bytes
```
$t=$_**($p+=1)while grep$t!~/$_/,0..9;say$p
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lxFYlXktLQ6VA29ZQszwjMydVIb0otUClRLFOXyVeX8dAT8/SujixUqXg/3@jf/kFJZn5ecX/dX1N9QwMDYB0UmZ6Zl7Jf908AA "Perl 5 – Try It Online")
]
|
[Question]
[
Let `A` be an `m` by `n` rectangular matrix of **positive** integers, where `m` and `n` are also **positive** integers.
We are interested in RoD ('Right-or-Down') paths from the upper-left cell of `A` to the lower right cell; in an RoD path, each successive cell of the path is either one cell to the Right of or one cell Down from the previous cell.
Given any such RoD path, we can take the sum of the cells in `A` in that path.
For example, consider the 4 by 3 matrix:
```
[ [1, 2, 3, 4],
[5, 1, 6, 7],
[8, 2, 1, 1] ]
```
Then we can consider the RoD path:
```
1 > 2 3 4
v
5 1 6 7
v
8 2 > 1 > 1
```
which has a sum of `1+2+1+2+1+1=8`. It's worth noting that this path has the smallest sum of all possible RoD paths from upper left to lower right in that matrix.
So, the proposed challenge is to provide the shortest function/program in your language of choice that outputs the minimum sum an RoD path from upper left to lower right can have in a given matrix `A`.
The usual forbidden loopholes are in effect. Your input can be in any reasonable format; your output must be an integer.
This is code-golf; answers are scored by number of bytes.
## Test Cases
```
[ [5] ] -> 5
[ [5, 2] ] -> 7
[ [5],
[2] ] -> 7
[ [ 9 , 1 , 12, 3 ],
[ 12, 11, 6 , 11],
[ 12, 9 , 2 , 11] ] -> 40
[ [ 6 , 8 , 11, 2 ],
[ 3 , 6 , 7 , 6 ],
[ 6 , 2 , 8 , 12] ] -> 37
[ [ 4 , 5 , 8 , 4 ],
[ 6 , 5 , 9 , 4 ],
[ 2 , 5 , 6 , 8 ] ] -> 31
[ [ 4 , 5 , 15, 18, 30],
[ 26, 26, 3 , 4 , 5 ],
[ 7 , 9 , 29, 25, 14],
[ 16, 1 , 27, 13, 27],
[ 23, 11, 25, 24, 12],
[ 17, 23, 7 , 14, 5 ] ] -> 94
[ [ 10, 15, 7 , 2 , 9 ],
[ 24, 5 , 2 , 1 , 25],
[ 2 , 12, 14, 30, 18],
[ 28, 4 , 12, 22, 14],
[ 15, 21, 21, 11, 4 ],
[ 21, 15, 21, 29, 9 ] ] -> 103
```
[Answer]
# [J](http://jsoftware.com/), 42 bytes
```
v(+}.<.}:)&.>/@{.[:</.(2#v=._1+1#.$){.!._]
```
[Try it online!](https://tio.run/##ZVDLagJBELz7FZUYoouTcbtn9jGDK4GAp5xyDUEkREIuuXkRv31T7ehBAr09/ajq6t6f8d7P9hgyZnCokfk9eby8vW7Gw3xx8it/ytWjXy@fj/49r5Z@rtPD4LeykKl/qI7@zm8/xmqysxkJAlEEZ14ELZ3LjBMsn3x9fv9iV579NYg1BqwtLUNa9MZVh8C4Q@usplbVwgjdLSOiYTc6whpKRRKUEQdd8PIfL7QeoXbQ1ixY1VGOq9LY5TzhAdAOEuiJDOfFGmjkLlSRzmrsk1ukUryVktqUCENyRmvsR3CEs1eNGIjomfIAq6gWZQLFjILne@RaSkhFSupw0Rr/AA "J – Try It Online")
### How it works
```
v(+}.<.}:)&.>/@{.[:</.(2#v=._1+1#.$){.!._]
v=._1+1#.$ Sum of two dimensions - 1; assign to v
(v is a verb)
(2# ){.!._] Extend the given array in both dimensions
[:</. Extract the antidiagonals as boxed arrays
v @{. Take the first `v` antidiagonals
( )&.>/ Reduce over unboxed items:
}.<.}: Given the right item R, take the minimum of R[1:] and R[:-1]
+ Add to the left item
```
### Illustration
```
1 2 3 4 Input array, dimensions = 3,4
5 1 6 7
8 2 1 1
1 2 3 4 _ _ Extended to 6,6 with filler _ (infinity)
5 1 6 7 _ _
8 2 1 1 _ _
_ _ _ _ _ _
_ _ _ _ _ _
_ _ _ _ _ _
1 Diagonalize and take first 6 rows
5 2
8 1 3
_ 2 6 4
_ _ 1 7 _
_ _ _ 1 _ _
Reduction: left+min(right[1:], right[:-1])
1 1 => 8
5 2 5 2 => 10 7
8 1 3 8 1 3 => 12 5 11
_ 2 6 4 _ 2 6 4 => _ 4 8 12
_ _ 1 7 _ => _ _ 2 8 _
_ _ _ 1 _ _
```
[Answer]
# JavaScript (ES6), ~~78~~ ~~77~~ 76 bytes
```
m=>(M=g=s=>(v=(m[y]||0)[x])?g(s+=v,y++)|g(s,x++,y--)*x--|M<s?M:M=s:0)(x=y=0)
```
[Try it online!](https://tio.run/##hVLLboMwELzzFT7iYhq/gDiqmy/gCxCHKE1QqiRUpYpA4t@p14/AIWkPqzW7s@PZwZ@7267bf5@@ftJr@3GYjnq66Pe41I3uTL7p@FIN9ThSXPU13jZxl@gbGZIEj@ZM@iQhQ5rilz5Nx/Kt25abUncbiuNeD5riad9eu/Z8eD23TXyMqwihCmWojmqM0WqFsih6jCCIz6jiGaom9vA/VBlCBsEJEmEMPhgjKIcGWxSVvd4WA6@kj4lhdo0cDw/EAjnSwmZfzD2pRfM7sXiiWBpY5uFyyQFFtSxyX3RSZmL2NzHLTKyNHTTw5MSGsORktrfwN3JlAqZk8Cp3rvLCZAE5UAnviEFzaff1EwYJTaBkkiyfgpKP9TLqtBbeP3XfWxL/ULyKbGGI/bcStoMtQ2PtNoMm58tFQCdzAbpnbxmZm8peHvQyKqZf "JavaScript (Node.js) – Try It Online")
### Commented
```
m => ( // m[] = input matrix
M = // initialize the minimum M to a non-numeric value
g = s => // g = recursive function taking the current sum s
(v = (m[y] || 0)[x]) ? // if the current cell v is defined:
g(s += v, y++) | // do a recursive call at (x, y + 1)
g(s, x++, y--) * x-- // do a recursive call at (x + 1, y)
| // if at least one call did not return 0 (which means
// that we haven't reached the bottom-right corner)
M < s ? // or M is less than s (false if M is still non-numeric):
M // return M unchanged
: // else:
M = s // update M to s, and return this new value
: // else (we're outside the bounds of the matrix):
0 // return 0
)(x = y = 0) // initial call to g with s = x = y = 0
```
[Answer]
## Haskell, ~~63~~ 57 bytes
```
f x@((a:_:_):c:d)=a+min(f$c:d)(f$tail<$>x)
f x=sum$id=<<x
```
[Try it online!](https://tio.run/##fVHLboMwELznK/bAAVQf4sU8BVX/o0IRKkW1CjRKUom/p/twwyFVhVYLs7PjGfPRXz/fp2nbRlhf4rivT/Upqd/qIWn7p9kv8RjxB7Vb76cmel6TA1Hb6/cc@aFtmnWbe79AC8PXAeB88csNIhjhlZ4KDFguNJBCZwjiV2sN5AzbO8RMVAi6Bx0ml6CLqDopqEYhXaA8aAgTSQcehByNskBx@xZD1Q5hgPTYf4VsRlVSuqNu5kYqFTGmCFwEfayoeMNp8FyvBwvqKXcVSUNSYqKTLMImFo9YzDrR/suZPaqrItxGFTI5NYzhl2B2jyq/xHEGzqJwqf55hLgbZkdWix3@3pc1@6iSI6HbfgA "Haskell – Try It Online")
```
f x@((a:_:_):c:d)= -- if it's at least a 2x2 matrix
a+min -- add the top left element to the minimum of the
-- path costs of
f$c:d -- the matrix with the first row dropped and
f$tail<$>x -- the matrix with the first column dropped
f x= -- else, i.e. a 1xm or nx1 matrix, i.e. a vector
sum$id=<<x -- return the sum of this vector
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~38~~ ~~36~~ ~~30~~ 29 bytes
*Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for pointing out a mistake, now corrected.*
```
lyZyqsG&nghZ^Yc!tsGz=Z)Ys)sX<
```
[Try it online!](https://tio.run/##y00syfn/P6cyqrKw2F0tLz0jKi4yWbGk2L3KNkozslizOMLm//9oQx0FIx0FYx0FE2sFUx0FINdMR8HcWsECLA7kGsYCAA) Or [verify all test cases](https://tio.run/##RVBBDoIwELz7inoxMemBbluQoDcTPuBBIRiNBz2oicGD@Hmc2RpNWJadmc5OuR2f1/EwXodmePT17H6@NPvdafrs6/eqme/6eb9djtt189qMbewmbbRG2CptpTUOj1jjK20OY86WRvAKQgp0kXipjFdVgXfFD0kcHYM1UadglIpqwkF0oM1P5ljQ@gw0fVCwJokDRdrPoi4gUq55BYzz7Djmv6F4scAQkIEnThm9sM9laVuhYUvGSREkOUbNp38gMA9zAVpoGMIi3wg841Jxr97M2T@OuGX3AQ).
### Explanation
```
l % Push 1
y % Input, implicit. Duplicate from below. Pushes the input below
% the current 1, and a copy of the input on top
Zy % Size of input. Gives [m, n]
qs % Subtract 1 element-wise, sum. Gives m+n-2
G % Push input again
&n % Push size as two separate numbers. Gives m, n
gh % Transform n into 1 and concatenate horizontally. Gives [m, 1]
Z^ % Cartesian power of [m, 1] raised to m+n-2. This produces the
% Cartesian tuples as row of a matrix. A typical tuple may be
% [1, m, 1, m, m]. This will define a path along the matrix in
% linear, column-wise indexing (down, then across). So 1 means
% move 1 step down, and m means move m steps "down", which is
% actually 1 step to the right
Yc % Concatenate strcat-like. This prepends the 1 that is at the
% bottom of the stack to each row
! % Transpose. Each tuple (extended with initial 1) is now a column
!ts % Duplicate, sum of each column
Gz % Number of nonzeros of input. Gives m*n-1
=Z) % Keep only columns that sum m*n. That means that, starting from
Ys % Cumulative sum of each column. This defines the path
) % Index: pick entries specified by the path
s % Sum of each column
X< % Minimum
% Display, implicit
```
[Answer]
# [R](https://www.r-project.org/), 90 bytes
```
function(m){l=sum(m|1)
if(l>1)for(i in 2:l)m[i]=m[i]+min(m[i-1],m[max(0,i-nrow(m))])
m[l]}
```
[Try it online!](https://tio.run/##fY1NCsJADIX3PUWXE0zB6c/YivUU7koXtTAQmExhbLGinr1mdoLgIi8v4X1J2Gx6ytLNLn6cafKK4ena28KKXxoSssqdNdgpKErJp/nRAXfUt1F2TJLvKNM9csfDqvZImQ/TXa5ADwl3rn9vVvEwB1rVqBrUqHMsomiNJorYBuMIGNG2wOsj9gtA8oUarGM6wgYPUka8rPL/WImVpEpJV/KmFKYSX/9C2wc "R – Try It Online")
The naive solution: iterate through the array (down the columns), replacing each entry by the sum of itself and the minimum of its above and to-the-left neighbors, if they exist, then return the last entry.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~57~~ 54 bytes
```
my&f={|.flat&&.[0;0]+min (f(.[1..*]),f $_>>[1..*])||0}
```
[Try it online!](https://tio.run/##VVFda8MwDHzvrxCshHTzgiU7H2YsfySE0ocZCu02ur2UZb89sywn8R6E8el0urM/326XZp6v98K//kyVv5y@i6Ia9Isen67ndyh9WQ1YVY/jQXnYH/s@3aZJ/85fpzv4cn88gP@47XYDDOBAAXKRAgOj2kEA@YKooOEGZiCzScDAhQd47sFqUWJyBzJIi5IBUWnjmcAmqUQ2bUqmFSUb8Dr1bT7EoMtBSqDszpTwvxLWobqQUC@DjYplohqTUqNNK8iF4im7xG/koagNp@FzkTIpc2CTjYnSRGBykyXRxh2rQWfFIGox16YncWsyK84p/Q/VWeT4P5bjcKyl0UkUbhLlztkYSrHR7fVQbU0Xl68GUZv5Dw "Perl 6 – Try It Online")
### Explanation
```
my&f={ } # Function f
|.flat&& # Return empty slip if matrix is empty
.[0;0]+ # Value at (0,0) plus
min # Minimum of
f(.[1..*]) # Rows 1..*
f $_>>[1..*] # Columns 1..*
( , )||0 # Or 0 if empty
```
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~100~~ 89 bytes
```
f A{g={|x,y|{g(x-1,y)if[x>0];g(x,y-1)if[y>0];[0]if[x+y=0]}|min|[A[x][y]+_]}g#A-1,#A[0]-1}
```
[Try it online!](https://tio.run/##bVLbisIwEH33KwZ9UYyQm61lcaHfEYLIaqUPtov1oaXtt3dnkuBibMoQknPmTOZ0HvXlPE0F5P3t2A8t64b@tm53gnWbsjDtN7dfeGbdTtC5o7PhlqBtd@R2HO5lNZjctNZ0dnuy422VY/YqR9ZOjNP9XFbQLwDX89o8Tz/n5trAEYy7omXwy4CBoJAMFFj2AgmmSyEYJEQQMyBlSw9iLmjO3sQp7wBeQ8biCrxw6vYITIKwy5ZOXKXv4hqhfaDouXwCszlQBtA/z4uLeXGxxzggzmONhLlQrgCRI0IaqssMg1R07F/inZcp7or2uIQKzmG21M6HSAEziUSlhHZvoF4y/d6L4L6PNHiaffihfbMyzILczxjmZkGTE@RITDh4F4gk5Vyz1IPwQT19/hPB/kmZeyT1IrhyNBvP8QBF/YCcQQOX@qX0@yirJxTrfMNgibO@RNyBl7q6LsbpDw "Röda – Try It Online")
*-9 bytes thanks to [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack)*
[Answer]
# [Python 3](https://docs.python.org/3/), 108 bytes
```
def f(A,m,n,i=0,j=0):r=i+1<m and f(A,m,n,i+1,j);d=j+1<n and f(A,m,n,i,j+1);return A[i][j]+min(r or d,d or r)
```
[Try it online!](https://tio.run/##VVDbboMwDH3vV/itRPUqEqDXMYnvQGhCgqpBkKLAJvXrme2wG8I49jn2OWF8zveHSxY7jA8/w/ScEOppXpr2BreowAEd2jzGLo/Vxed2p18HqF3zC@40dura5B1B7j@E1FNX384f3kFR2qrsqt1gXeTh4aHBhpNXy41SAdbBUI8Rqe97O7e@7t/bz7pHNrWf5sY6ddkAPaO3biYN2L68bVHkoG9dVKg1l3GllFrKMquqDX0RTDhUCGU4nhE0vQYh4SYfNDUOnL4bxJG2DBByChzDeCLcI325OgiT8bA9RcikTlc0k21SGal43R@q5iB@EguF91GQCMPcOgY7HEyVTfoglzCE6YSzzCarS751Ko6YShxGmCorWVrHQfgo7s8yHeyYsDhb/crfSdkdu5TmSawxYMyPH57UIdhCuK4OIgKcWab6Ag "Python 3 – Try It Online")
## Ungolfed
```
def f(A, m, n, i=0, j=0):
right = i + 1 < m and f(A, m, n, i + 1, j)
down = j + 1 < n and f(A, m, n, i, j + 1)
return A[i][j] + min(right or down, down or right)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ZI_.ỊȦ
ŒJŒPÇƇLÐṀœị⁸§Ṃ
```
**[Try it online!](https://tio.run/##y0rNyan8/z/KM17v4e6uE8u4jk7yOjop4HD7sXafwxMe7mw4Ovnh7u5HjTsOLX@4s@n////R0QqWOgoKhjoKhkZA2jiWSycaxDIEiiiYgWiYCFgdWCY2FgA "Jelly – Try It Online")**
### How?
```
ZI_.ỊȦ - Link 1: isDownRight?: List of 2d indices (limited to having no repetitions)
Z - transpose
I - deltas (vectorises)
_. - subtract 1/2 (vectorises)
Ị - insignificant? (effectively _.Ị here is like "v in {0,1}? 1 : 0")
Ȧ - any & all (0 if a 0 is present when flattened, else 1)
ŒJŒPÇƇLÐṀœị⁸§Ṃ - Main Link: list of lists of integers, A
ŒJ - multi-dimensional indices of A
ŒP - power-set
Ƈ - filter keep only those truthy by:
Ç - last link as a monad
ÐṀ - filter keep only those maximal by:
L - length
⁸ - chain's left argument, A
œị - multi-dimensional index into (vectorises)
§ - sum each
Ṃ - minimum
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~37~~ 32 bytes
```
{⊃⌽,9e9(⊢⌊⍵+(2⊣⌿⍪)⌊2⊣/,)⍣≡+⍀+\⍵}
```
[Try it online!](https://tio.run/##RU/LSgNBELznK/q2MyTB7Zl9ZPwWL0s0sriQkOQiEhCUQNas6MEP0Ny85yKI/9I/slbvBoWhqa6uruopFtX48rao5tfjaVWsVuW0lee3ci7bl7idod5J/SD771G4CkbqD9nX0hyHxkl9kP2PNJ8WlHZnIyvNQXbvQ2nuhxdQbdp23Tk0R9BLwJk0X@fR/CaSp8doVpRVBALj5WZgYJXaNaWKdtqQQ5v3gz@8fTWBmNiRtwaVmTKUDgfS3kKZxL00o4kqnDUespwyC8op6VTmT44JpeASHaZwAXAAWO5E/C9ivAn5GAL4ZOQJrDW5RuNhil3GQeRyYo8Kpe9OwBcSjTWcEyiMdRX@Ien9OVZ7DClgSdOc@qR6jH40QS7S0eJUZZzr4yBkfUjRy5lOTIAR/Dn2g/Ev "APL (Dyalog Classic) – Try It Online")
`+⍀+\` partial sums horizontally and vertically - this provides an initial overestimate for the paths to each square
`9e9(`...`)⍣≡` apply "..." until convergence, at each step passing some very large number (9×109) as left argument
`,` add `9e9`-s to the left of the current estimate
`2⊣/` take the first from each pair of consecutive cells, effectively dropping the last column
`2⊣⌿⍪` same thing vertically - put `9e9` on top and drop last row
`(2⊣⌿⍪) ⌊ 2⊣/,` minima
`⍵+` add the original matrix
`⊢⌊` try to improve the current estimates with that
`⊃⌽,` bottom-right cell
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
≔E§θ⁰∧κΣ§θ⁰ηFθ«≔§η⁰ζFLι«≔⁺⌊⟦§ηκζ⟧§ικζ§≔ηκζ»»Iζ
```
[Try it online!](https://tio.run/##VY7NCsIwEITP5in2uIEVTLSoeCqeBAXBY@ih@NdgjdpWEcVnj0lNUANLYOab2V0XebU@5aW1aV3rvcFFfsa0mZnN9o4Xgh4nSM0GDwSr6/HfcY@g4BO2O1WAFw5P1gktkSs@DQ8HdVpqvjX7pkDNWzriy/Ja40IbfXQ71E/44MOZvyFo2muxMcR/@eC82IstK20anOZ1gw/OJ9YqpUD0CERCMAQC6WYMGTEABXJAkARR@D@JhhekGwf0fXoUjRHBIJiyBYLh@6X4jBAeiglBX3PcLs8y272Vbw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: This would probably be shorter if there was a three-argument `reduce` in Charcoal.
```
≔E§θ⁰∧κΣ§θ⁰η
```
Prefill the working array with large values except for the first which is zero.
```
Fθ«
```
Loop over the rows of the input.
```
≔§η⁰ζ
```
Initialise the current total with the first element of the working array.
```
FLι«
```
Loop over the columns of the input.
```
≔⁺⌊⟦§ηκζ⟧§ικζ
```
Take the minimum of the current total and the current element of the working array and add the current element of the input to give the new current total.
```
§≔ηκζ
```
And store that back in the working array ready for the next row.
```
»»Iζ
```
Print the total once the input has been completely processed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
XL,1ẋLḊŒ!1;ⱮÄịẎ§Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8/z/CR8fw4a5un4c7uo5OUjS0frRx3eGWh7u7H@7qO7T84c6m////RytEK1gq6CgYgrCRjoKxQqwOlwJQEMQxNNRRMANJGCIJglQbQQQVYgE "Jelly – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~26~~ 25 bytes
```
∧≜.&{~g~g|hhX&{b|bᵐ}↰+↙X}
```
[Try it online!](https://tio.run/##RU8xasNAEPyKcOEm6@C9k05S43zDcFwRpZCKQCBNMLJcuDB2lzaQPq0bh5Df@D6izMgHgWNvd2Z2Z7d5fXzqNs8vrRn76@/penmPx6/ZYrHKZm8P8XCO@z3hn2/EAewIOp4@7@f9rt21265bz/tm24AZoL6Lh4/1MI4@874IQfiJSUkQn9JaVNSIBYJPVRzCraiFwE3mpCJpwFhISnHIHASA06RcClT5hBdoZmaQofVfoHiV2CU5tDuxAhhVSTs88GxUrCGmFLWIFNvJHhfkNISgFGAQsB211yWHA5WaepoZzphu5YlQWmgq1tiTkDHJDVrlg8e0tkqCakwLWfgD "Brachylog – Try It Online")
-1 byte because the cut isn't necessary--you can't take the head of an empty list
There's probably a lot of room to golf this but I need sleep.
The approach boils down to trying every value for the output, smallest first, (`∧≜.`) until a path can be found (`b|bᵐ`) to the bottom right corner (`~g~g`) which produces that sum (`hhX&...↰+↙X`).
[Answer]
# Java 8, ~~197~~ ~~193~~ ~~190~~ 188 bytes
```
m->{int r=m.length-1,c=m[0].length-1,i=r;for(;i-->0;)m[i][c]+=m[i+1][c];for(i=c;i-->0;)m[r][i]+=m[r][i+1];for(i=r*c;i-->0;)m[i/c][r=i%c]+=Math.min(m[i/c+1][r],m[i/c][r+1]);return m[0][0];}
```
-9 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##jVRNb9swDL33VxABBtgLk1mWP2Ok9x3aDejR8MFz3VZd7ASKkqEo8tsz0nFqpWsHA4pgPT2Sj6TC53Jfzp7vfx@rVbndwk2p2tcrANWaWj@UVQ23fOwAqBza8yIvGjcj8HBF29aURlVwCy0sj83s@pWJetnMV3X7aJ5mAqtlk3vFcFZLnT2stZOp2ezay9wmV0VeFVOiqangz@5aLauBoQsiMYM/iNQz9FeLo75VRa6X6gv7uinN07xRrdPh7FYXeObQ0c10bXa6BdZGKzscM05ns/u1onT6rPZrdQ8NlcS5M1q1j3kBpXuqh6m3xmnrP9CX5IQCvAr0UWJwwDMQosAI4wFIiCFQHLrzoSvlf/yFY3noj/b4JmWsCaQIJNlHkIMxHYVAiGi/AJnMV2N9RwhJ58kf3IBkxxDTboERO2byWN0BhpjYzYgISG3AJyDCZKzWAIH6SStB6VleIqTFoplgKY65Gj4tMrGiiojr6ccoJO2WH8mFILIfcJIDP0a6Im@i8z9OrPBYKUvgnlhBQk6CQQ5lifW5wxRBkmFi8RNOi658/zIJkil4ce/skgrsr1KOO1KspH9JTNWQFMqjXC8UeBQhjVAGPqYRN8CqfURyE7KIgwgDlmg/x1DGGKXU8ZRqR5LS0HpPiRdiLOkFULWBiFJevFl7vnWToBP/NgJP0u9etqZu5uudmW9oRJhV60y@t5udWcCkz3lDo8a8/ORbp@mxj8x@7MzJbtrOK2J@Tv1Ynh3nnUoel/tSQ7k4IwO2X5RuD/0bzJnAZK7rTV0aR86c/XQycftR7rjulM54TvNzpayVf4fjXw)
**General explanation:**
I actually already did this challenge about a year ago with [Project Euler #81](https://projecteuler.net/problem=81), except that was limited to a square-matrix instead of an `N` by `M` matrix. So I slightly modified my code from back then to account for that.
I first sum the bottom row and rightmost column from the very last cell backwards. So let's use the example matrix of the challenge:
```
1, 2, 3, 4
5, 1, 6, 7
8, 2, 1, 1
```
The last cell remains the same. The second last cell of the bottom row becomes the sum: `1+1 = 2`, and the same for the second last cell of the rightmost column: `1+7 = 8`. We continue doing this, so now the matrix looks like this:
```
1, 2, 3, 12
5, 1, 6, 8
12, 4, 2, 1
```
After doing that, we look at all the remaining rows one by one from bottom to top and right to left (except for the last column/row), and we look for each cell at both the cell below it and right of it to see which one is smaller.
So the cell containing the number `6` becomes `8`, because the `2` below it is smaller than the `8` right of it. Then we look at the `1` next of it (to the left), and do the same. That `1` becomes `5`, because the `4` below it is smaller than the `8` right of it.
So after we're done with the second to last row, the matrix looks like this:
```
1, 2, 3, 12
10, 5, 8, 8
12, 4, 2, 1
```
And we continue doing this for the entire matrix:
```
8, 7, 11, 12
10, 5, 8, 8
12, 4, 2, 1
```
Now the very first cell will contain our result, which is `8` in this case.
**Code explanation:**
```
m->{ // Method with integer-matrix input and integer return-type
int r=m.length-1, // Amount of rows minus 1
c=m[0].length-1, // Amount of columns minus 1
i=r; // Index integer
for(;i-->0;)m[i][c]+=m[i+1][c];
// Calculate the suffix-sums for the rightmost column
for(i=c;i-->0;)m[r][i]+=m[r][i+1];
// Calculate the suffix-sums for the bottom row
for(i=r*c;i-->0;) // Loop over the cells in reversed order:
m[i/c][r=i%c]+= // Add to the value of the current cell:
Math.min( // The minimum of:
m[i/c+1][r], // The value in the cell below it
m[i/c][r+1]); // And the value in the cell left of it
return m[0][0];} // Return the value in the cell at index {0,0} as result
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 223 bytes
Takes input as a 2D List of ints.
Additional 19 bytes for `import java.util.*;` included.
```
import java.util.*;m->{var l=m.get(0);int s=m.size(),c=l.size(),x=-1>>>1,a=l.get(0);return s*c<2?a:Math.min(s>1?n.n(new Vector(m.subList(1,s))):x,c>1?n.n(new Vector<>(m){{replaceAll(l->new Vector(l.subList(1,c)));}}):x)+a;}
```
[Try it online!](https://tio.run/##lVVNb6MwED2HXzHiBE2CYvJdEqoe9rDSppdKvVQ9uISmdI1B2GnTjfjt2bEhlABdaS1k8MybN8/jD97oOx2@bX@fojhNMglvOHb2MmLOlWcY6f6ZRQEEjAoBGxpxOBoGYCsdQlKJr4jLMHuhQQh3CICylRh0Ard@RUKudPcTwbsw832IbU@Dc6On3yXbHXBYQzz0R55Rtx@Br09oPr7TDNg6dnahtEa2pxIIHIroT2jZg2DNzp@H9ZD4vk8GFG0lOgvlPuMgroKVe0OvN1S@OnHELeGTG@5wi4cf8BAGMskspNw/K80WGQjbtq8Pg6CFWvlWbB@PWZgyLMAtYxYb@jUSViMJkMTLcySy@9TLT17udZXzPYm2EGO1rXuZRXz3@AQ02wkb5GuWfAj4cQjCVEYJ/6q1DDGBOTXLitZM4HYYzQGYlb3hXAIQfFwYm4PKpZuJRkJghl7S5cNIV/u6iTFuodyoqBk8BsU6x77lmmlSFXgxkQb3BGCqUZMuAnQtu1yudildXdR1ZjIFsoDxqEFhujPAB@VrWNM713ndJbgY3kxvkpkqtDsHMsa@xTzWpcL1m6ipN2PngADkJxOYfi@ejJTyuS7hsiUPmafFkmE/bXn1JkD@MZIsWt6FmjICXLdraiibqAenMGnnJVAClkpVdQt8dxT0XIqj4DhOxNO9tL@2fufNQhF9wFskpZkIN3pkFYGe0bv/FDKMnWQvnRRJJcPzjGe6CLL/JacrVz1FdV7/S6S6LW6zjH5qgG/VlvMFbxB1v@G5R@DI0x@rgt5hId/JV23r9228eXu93kWlKzmIeKBMIIWOfMTxkyNSFuEegX59/1RizzpVrDJ067zMd1YbJKxQqz5W5@yVXrQWeqHRylQO3W6tMr@jy4sDq2R5xOgnu6E4vxgVhdUsJWMN/gUt/wQF@rzo@ekv "Java (JDK) – Try It Online")
---
**How it works**
```
import java.util.*; // Import needed for Vector class
m->{ // Lambda that takes a 2D list of integers
var r=m.get(0); // Store first row in variable
int h=m.size(), // Store number of rows
w=r.size(), // Store number of columns
x=-1>>>1, // Store int max
a=r.get(0); // Store the current cell value
return h*w<2?a: // If matrix is single cell return value
Math.min( // Otherwise return the minimum of...
h>1? // If height is more than 1
n.n( // Recursively call this function with
new Vector(m.subList(1,h))): // a new matrix, without the top row
x, // Otherwise use int max as there is no row below this
w>1? // If width is more than 1
n.n(new Vector<>(m){{ // Recursively call this function with a new matrix
replaceAll( // where all columns have been replaced with
l->new Vector(l.subList(1,w)) // cloned lists without the leftmost column
);
}}): // Otherwise use int max as there is
x // no column to the right of this
)+a; // Add the current cell value to the result before returning
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 86 bytes
```
f=lambda A:len(A)>1<len(A[0])and A[0][0]+min(f(zip(*A)[1:]),f(A[1:]))or sum(sum(A,()))
```
[Try it online!](https://tio.run/##ZY5BDoJADEX3nqLLVrugIygaNeEcxgVGiSQwEtSFXh7bEQPRzPxM8/5vp83zfrl613XFtsrr4ymHbF2dPWa0k00o9tGBcn8CK/TO6tJjga@ywWlGe1kfiAtNWUHXFm6PGk0ZIxF1TVv6OxQIehImBgKa/EJ0rHjgqNQRKxkQoBjDOcchO3YgBoZElapiIJ6AwkUPV2PoergI6f9JEjFIwrBU34Xmb2P8aTQo9iajieJUGphbd/o1Ug6LmelCoDdsvpOPRMbLCQ/mKnweFuze "Python 2 – Try It Online")
If `B` is the transpose of `A`, then the problem definition implies that `f(A)==f(B)`.
`A[1:]` is the array `A` missing its top row. `zip(*A[1:])` is the array `A` missing its leftmost column and transposed. `sum(sum(A,()))` is the sum of all elements in `A`.
If `A` has only a single column or single row, there is only one path, so `f` returns the sum of all elements in `A`; otherwise we recurse and return the sum of `A[0][0]` + the smaller of `f` of `A` missing the top row and `f` of `A` missing the leftmost column.
]
|
[Question]
[
In mathematics, a *cyclic quadrilateral* is one whose vertices all lie on the same circle. In other words, every vertex is on the circumcircle of the other three. For more information, see the [MathWorld article](http://mathworld.wolfram.com/CyclicQuadrilateral.html).
### Examples
These quadrilaterals are cyclic:
[](https://i.stack.imgur.com/1t0IX.png)
This trapezoid is not cyclic.
[](https://i.stack.imgur.com/K3hYA.png)
(Images from Wikipedia)
### Objective
Given the coordinates of four vertices in counterclockwise order which form a convex quadrilateral, determine if the quadrilateral is cyclic.
Coordinates will be integers (note, however, that the circumcenter coordinates and circumradius are not necessarily integers.) As implied by the previous paragraph, no three points will be co-linear and no two coincident.
### I/O
You may take input using any reasonable format. In particular, `[[x1,x2,x3,x4],[y1,y2,y3,y4]]`, `[[x1,y1],[x2,y2],[x3,y3],[x4,y4]]` and complex numbers are all fine.
Output using any different consistent values for true and false.
### Test cases
True:
```
[0,0], [314,0], [314,1], [0,1]
[-5,5], [5,-5], [1337,42], [42,1337]
[104, -233], [109, -232], [112, -231], [123, -224]
```
False:
```
[0,0], [314,0], [314,100], [0,99]
[31,41],[59,26],[53,58],[0,314]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes
```
#∈Circumsphere@{##2}&
```
[Try it online!](https://tio.run/##dY4xCsMwDEX3nMIQ6OSAJdltsxl6ge6lQwiBZEgpqTsZ7zlnL@LKwkOXTnrfPH1rHcI8rUNYxiFft@URbrn97Ptl2cb3@nrO0zb52LaYDtl7r2ITo9HKJK0igf0lKGTKZGCtc1q58sazEwCik1YWC1tkk3OVwXBDh0TimV6CiAAoQeoBqQS0de3fKcbUY/q@mgT8s3Q4LsejEJe5czV5MaUm3fMX "Wolfram Language (Mathematica) – Try It Online")
Takes four inputs: the lists `{x1,y1}`, `{x2,y2}`, `{x3,y3}`, and `{x4,y4}`. Checks if the first point lies on the circumcircle of the other three. Also works for checking if \$n+1\$ points in \$\mathbb R^n\$ are concyclic, provided the last \$n\$ of them are affinely independent (because `Circumsphere` is sad if you give it a degenerate input).
Alternatively, here is a mathematical approach:
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~29~~ ~~28~~ ~~25~~ 24 bytes
```
Det@{#^2+#2^2,##,1^#}^0&
```
[Try it online!](https://tio.run/##dY0xCwIxDIX3@xWFgos9aJJW7dbBH@AuFooceMM5SLfS316Ts6vweJCX7yVbLq9ly2V95n77rO9y79elxKoTHjUmNFobSLole@gxRlWnWq1RBG6YbUZJwgJW45GR2RvFAqKzUQ6F4VFSh794gGD5BtjABrJBEnZGIsaRcHcQRzcqf99bthAGJSXPZz0NyHGAJw4ue7W1qT36Fw "Wolfram Language (Mathematica) – Try It Online")
Takes two lists as input: `{x1,x2,x3,x4}` and `{y1,y2,y3,y4}`. Returns `Indeterminate` when the four points are on a common circle, and `1` otherwise.
From the four points \$(x\_1, y\_1), (x\_2,y\_2), (x\_3, y\_3), (x\_4, y\_4)\$, this solution constructs the matrix below:
\$\begin{bmatrix}x\_1^2 + y\_1^2 & x\_2^2 + y\_2^2 & x\_3^2 + y\_3^2 & x\_4^2 + y\_4^2 \\ x\_1 & x\_2 & x\_3 & x\_4 \\ y\_1 & y\_2 & y\_3 & y\_4 \\ 1 & 1 & 1 & 1 \end{bmatrix}\$
The determinant of this matrix is 0 if and only if the four rows are linearly dependent, and a linear dependency between the rows is the same thing as the equation of a circle that's satisfied at all four points.
The shortest way I could think of to check if the determinant is 0 is to raise it to the 0-th power: `0^0` is `Indeterminate` while anything else gives `1`.
[Answer]
# [Python 3](https://docs.python.org/3/), 70 bytes
```
lambda b,c,d,e,a=abs:a(a(b-d)*a(c-e)-a(b-c)*a(d-e)-a(c-d)*a(b-e))<1e-8
```
[Try it online!](https://tio.run/##nY/LDoIwEEX3fEWXrWmTTgsKRv7ETVsgmvCKstCvxynEZDCsXJ7T5s6943u6Db2dm/I6t67zlWNeBlnJWrrS@efZcce9qsTB8aBqoSKFSNVKYX3zSOICtcrn8XHvJ97wMHRjW7@4lkwLyb5oId0RQISOKETyG6QyyTLyD1FRBmtPkqWGqNRgFuq9ONB4VxlraYQuFkczAMziaEUwNjqTxuAk@W@y1tvRRbFX0wJuorczrGiOVGCXLN9m4YWl2vwB "Python 3 – Try It Online")
I use the [Ptolemy's theorem](https://en.wikipedia.org/wiki/Ptolemy%27s_theorem).
>
> In a quadrilateral, if the sum of the products of its two pairs of
> opposite sides is equal to the product of its diagonals, then the
> quadrilateral can be inscribed in a circle.
>
>
>
`b`, `c`, `d`, `e` are complex numbers.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes
```
{!im ($^b-$^a)*($^d-$^c)/(($d-$a)*($b-$c)):}
```
[Try it online!](https://tio.run/##bY3BCsIwDIbve4oKRVq7YpO00wq@ymROBwOHMk9Dffaa9uDJS/4v@f8kj@t8a9K0iPUgjum1GiehZHu2su30hunC1OutUpKpjNjrtT580rNbxKDe8qTFcJ8r5Ywba0HgfwqsjquuK2WDCdwGmysQ7YxHJo8mNyUCzlskyr6LTNkHQKZ8CJAsoi/JP6@cK89iLAEC4/NSiAabrGTCvgQ4POr0BQ "Perl 6 – Try It Online")
Takes vertices as complex numbers. Uses the fact that the sum of opposite angles is 180° in a cyclic quadrilateral. The order of operations should guarantee that floating-point operations yield an exact result for (small enough) integers.
### Port of Misha Lavrov's TI-Basic solution, 33 bytes
```
{).im}
```
[Try it online!](https://tio.run/##bY3NCsIwEITvfYoIIvlpanaTVHPwPUQR6cFCwNJSeynis8dNDp68zMzCtzPTY362aVjZrmen9N5c5Y0P3cTkXtZ8e2cX3czj0i0PIZo4fNKrW1nPG8IE68e54kaZWDML7udAbkhFXXHtlafT66xg7UE5pORQ5SOys6QXHzIKxmm0NnMmUMocAFLKhYBWI7pS@mfSmDIaQgEsKJeffFDYZrfKHwtAcBTpCw "Perl 6 – Try It Online")
[Answer]
# JavaScript (ES6)
## Testing the angles, 114 bytes
Takes input as the array \$[x1,y1,x2,y2,x3,y3,x4,y4]\$. Returns a Boolean value.
```
a=>(F=i=>(A=Math.atan2)(a[i+3&7]-(y=a[i+1]),a[i+2&7]-a[i])-A(a[i+5&7]-y,a[i+4&7]-a[i]))(0)+F(2)+F(4)+F(6)==Math.PI
```
[Try it online!](https://tio.run/##jU49C8IwEN37KzpJQhtJLqnaIYKL4CC4lw5BW61II1oEf329S1FBOgj38XL37r2c3cPd97fm2onWH6q@tr2zS7a2DdaV3bruNHWda4EzVzSJnsxLwZ6WsCp5Sh1ohqDkYhVIGQ2eYWc@O84kT9YMqBgqM24H@d2m3/v27i/V9OKPrGaFTGMMrcy3qwDRkkc/ZJGl8RCElNbzNDYwJL1GTpRERQFaI0PmARJZQYBopUATBEPH0R@/k8Mwz0fcSNBgZugEM@yonS3ex3jQvwA "JavaScript (Node.js) – Try It Online")
---
## Computing a determinant, 130 bytes
Takes input as \$[x1,x2,x3,x4]\$ and \$[y1,y2,y3,y4]\$ in currying syntax. Returns a Boolean value.
This one is equivalent to [MishaLavrov's 2nd answer](https://codegolf.stackexchange.com/questions/176162/is-this-quadrilateral-cyclic/176174#176174), with a rotated matrix.
```
x=>y=>!(g=a=>a+a?a.reduce((v,[r],i)=>v+(i&1?-r:r)*g(a.map(r=>r.slice(1)).filter(_=>i--)),0):1)(x.map((X,i)=>[1,Y=y[i],X,X*X+Y*Y]))
```
[Try it online!](https://tio.run/##dZDdaoQwFITv@xT2puRoIvnRti4k@xqKSAmuSopdl7iV3ae3J3avioVhIMM3k5BPu9i59e5yZefp1K29Xm/a3LV5JoO22tjEHm3qu9N32xGy0No31IE2S0Lcizgyf/AQD8SmX/ZCvDY@nUeHqABIezdeO08@tHGMAVAOBwHktqGk3GZqQSt9r11DS1rGZVLFVQOwttN5nsYuHaeB9KTmNFIiexhvYEtQAoX40x@c5TRCCaXeaJTJwOMxpJn8jXdKguO24AWaCJRUocekUliVSm4ugstsp/7vEzlaUew0wliO1@XqUcgwkK8YvG8z4R9@AA "JavaScript (Node.js) – Try It Online")
[Answer]
# TI-Basic (83 series), 21 bytes
```
e^(ΔList(ln(ΔList(augment(Ans,Ans
not(imag(Ans(1)Ans(3
```
Takes input as a list of four complex numbers in `Ans`. Returns `1` if the quadrilateral is cyclic and `0` otherwise.
This is [nwellnhof's cross-ratio computation](https://codegolf.stackexchange.com/a/176171), in heavy disguise. If we start with values \$z\_1, z\_2, z\_3, z\_4\$, then:
* `ΔList(augment(Ans,Ans` computes the differences \$z\_2-z\_1, z\_3-z\_2, z\_4-z\_3, z\_1-z\_4\$ (and a few more redundant terms),
* `e^(ΔList(ln(` of that computes the ratios \$\frac{z\_3-z\_2}{z\_2-z\_1}, \frac{z\_4-z\_3}{z\_3-z\_2}, \frac{z\_1-z\_4}{z\_4-z\_3}, \dots\$.
* We check if the product of the first and third terms, which is \$\frac{z\_3-z\_2}{z\_2-z\_1} \cdot \frac{z\_1-z\_4}{z\_4-z\_3}\$, has no imaginary part. Note that this is the same as the [cross-ratio](https://en.wikipedia.org/wiki/Cross-ratio) \$(z\_3,z\_1;z\_2,z\_4) = \frac{z\_2-z\_3}{z\_2-z\_1} : \frac{z\_4-z\_3}{z\_4-z\_1}\$.
I did my best to check if numerical error is a problem, and it doesn't seem to be, but if anyone has good test cases for that, please let me know.
[Answer]
### JavaScript (ES6) (101 bytes)
```
p=>(h=(a,b)=>Math.hypot(p[a]-p[b],p[a+1]-p[b+1]))&&((h(2,4)*h(0,6)+h(0,2)*h(4,6)-h(0,4)*h(2,6))<1e-8)
```
Takes input as `[x1,y1,x2,y2,x3,y3,x4,y4]`, outputs a Boolean.
Checked based on $$ef=ac+bd$$ where \$e,f\$ are the diagonals and \$a,b,c,d\$ are the sides in order.
[Try it online!](https://tio.run/##jU7BqsIwELz7FT3JRhNJNqlasP6BX1A8RF/78kRM0CL49XU3RQTx8GCXmUl2dvbk7/52vP6lXl3iTzt09ZDqLYQavDyIervzfViER4o9pMbvVWoOe0lsbjInEGI6BQiA0olZAC2XYs6ArBwpxSr/ISmxMa1ai@EYL7d4bhfn@AsdNFoWVNa4N5pMOWDyMaxKWYzFzFi7koXDsVl9sRhNGxVaSxO6ypSHDWZKUQYtU3RsnvzjOj0@VtWXNF7oqEtKwiUh7S7XLzMZhic "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
²Sṭ;L€€ṖÆḊ¬
```
[Try it online!](https://tio.run/##bU4xDsIwDNz7CnY3ku0k0IgvsLFRdWSg4gOsDEXiAbyiLEx0bV9SPhLsqq2EihTdOXeXc8rj@XyJsX3t@@a53X2utZy@eXRV/763deyq00GU7iYQY54jYJmuLLmZSRgFizTJ/@mKOLu/6tSk7lKdetQ1HrwI3iiStRtwLJNj0MsQIXSGrVUfg0zqE7FMWkxsDbMbVy2WIA7LQxh/Ck4f@QC8VrbgsyEg4bJIikjZFw "Jelly – Try It Online")
Uses the determinant approach from [Misha Lavrov's Mathematica solution](https://codegolf.stackexchange.com/a/176174/78410). Outputs 1 for true, 0 for false.
### How it works
```
²Sṭ;L€€ṖÆḊ¬ Main link (monad). Input: [[x1,x2,x3,x4], [y1,y2,y3,y4]]
²S Square each scalar and add row-wise; [x1*x1+y1*y1, ...]
ṭ Append to the input
;L€€ Add two rows of [1,1,1,1]'s
Ṗ Remove an extra row
ÆḊ¬ Is the determinant zero?
```
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Iµ÷×ƭ/÷SµḞ=A
```
[Try it online!](https://tio.run/##bU4xDsIwDNz7CnY3wnYSaAYGRmbGqiNL1Q@wsvAENl4AY1XmRuIf8JFgV20lBMudc2ffpT40zTGlXd/GLl6e92Xs9n37elw32xTP79MtpbJEwDpfWHIzkzAKVnlW/tMVcXa/1SlJ3V91ylHXePAieKNI1q7BsUyOQR/DCqEzbK36GGRSn4hl0mBia5jdWPVTgjiUhzD@FJwe@QC8Urbgi2FBlusqqxIVHw "Jelly – Try It Online")
Uses the convoluted cross-ratio approach from [Misha Lavrov's TI-Basic solution](https://codegolf.stackexchange.com/a/176192/78410). Outputs 1 for true, 0 for false.
### How it works
```
Iµ÷×ƭ/÷SµḞ=A Main link (monad). Input: list of four complex numbers [z1,z2,z3,z4]
I Increments; [z2-z1, z3-z2, z4-z3]
µ Refocus on above for sum function
÷×ƭ/÷S (z2-z1)÷(z3-z2)×(z4-z3)÷(z4-z1)
µ Refocus again
Ḟ=A (real part) == (norm) within error margin
i.e. imag part is negligible?
```
I believe both are golfable...
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 25 bytes
```
{0=-/|⍵}(-⌿2 3⍴2/⌽)×⊃-1↓⊢
```
[Try it online!](https://tio.run/##XY29agJREEb7fYrpVouL83NvzAZ8mMWwwZsFRW1CYhURNC4EUlgnL5BGG0EC@ibzIpvZxcpiZg5zPvjySekeX/Jy/OSGZT6bjYZ1Xejq8xUHrvem1WHRcbr9YxCt9tzT7al72enm3ZGuvnTzU9fzJm1BXX9PDQutjg/p@DnVj2Va5KMytYfp6SLBiCDkr5sAbeZAyfk3xAAh2gUS6UfP4Dk22HpCb45FgDBriYGIWyIglobYt9mbDkRryTJTmAhFTxCyyHcQJIZ7UxZq3D8 "APL (Dyalog Classic) – Try It Online")
Ptolemy's theorem, credit: [Кирилл Малышев's answer](https://codegolf.stackexchange.com/a/176167/24908)
]
|
[Question]
[
My boss\* does not understand why her programmers react negatively to users changing program requirements. Help her understand! On every answer, create a new requirement. Then, write a program/function that solves that requirement and all prior requirements, while in a new programming language.
# Examples
User 1 posts the first answer. He specifies that the program must output "Hello, World." He creates a program in Java that outputs "Hello, World."
User 2 posts the second answer. She specifies that the program must accept input *n* and output the *n*th prime, up to the language's number max. She creates a program in C++ that accepts input *n* and outputs the *n*th prime and outputs "Hello, World." She could not have created a program in Java.
User 3 posts the third answer. He specifies that the program source cannot contain the text "Hello". He creates a function in Python that accept input *n* and outputs the *n*th prime and "Hello, World." while not using the text "Hello" in his source. He could not have created a program in Java or C++.
# Answer Format
```
#Answer # - <language name> [version, if pertinent]
Requirement: <rule>.
<code>
[explanations, encoding, TIO link, etc.]
```
# Answer Rules
* The answer must follow the above format, or similar.
* The answer can be a program or a function.
* The answer must fulfill all requirements up to and including the current answer.
* The same user may not post two answers in a row.
* If two answers are posted with the same number, the one posted later
should be deleted.
* Do not edit your requirement unless you messed up badly **and** no
other answers have been posted.
* If your answer does not comply with your rule and all other rules, it
is invalid. Try to fix this before someone else posts the next
answer.
* Different versions of the same language only count as different
languages **if** the program or function created in either version
will behave differently in the other version.
* The answer may not accept any input not required, and may not output anything not required except for necessary whitespace. However, while behind the scenes the program must fulfill all "hidden" (from the user) requirements, it may do whatever else you want it to, especially if you must fulfill an execution time requirement.
# Requirement Rules
* The requirement must only specify one requirement. This requirement
can be conditional, and if this requirement requires an input and/or
an output, this may be included.
* The requirement may not remove or modify prior requirements, or
conflict with them, but may extend one (specify which).
* If the requirement restricts the source ([restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'")), or requires text in the source, it may only remove a single string (e.g. `0`, `Hello`), or require a single character.
* The requirement cannot require the source to be under 100 bytes,
require a specific encoding, or,
in and of itself, rule out a majority of common languages.
* The requirement may not force the source to conform to a certain pattern (for example, starting each line with a certain character, or (@Conor) hashing to a certain value) other than that specified in restricted source.
This is [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'"), so all answers build on previous answers. I and maybe others will try to keep a list of all requirements. To see answers in order, you can sort by oldest. To see the newest answer, sort by oldest, then navigate to the end of the list.
# How to Win (changed for hold vote):
When no answer is posted for two weeks, the challenge is over, and scores will be calculated. The scores will be calculated by summing the totals number of answers by each user, but weighting posts based on how far into the chain they are (since the later posts have more requirements, they are harder).
Pseudocode:
```
for each answer in user.Answers {
score += 1 + (answer.number / 100)
}
```
Example:
Sally has three answers. She posted answer 5, answer 7, and answer 20.
Her score will be `1.05 + 1.07 + 1.2 = 3.32`. If it was a straight sum of answers, her score would be 3, but the weighting of chain depth rewards harder answers.
# To start:
Here is the first requirement, given by my boss\*:
Requirement 0: The program must output 0 before anything else.
\*fictional
# List of Requirements and Languages
Note that this may be out of date - please look at the last posted answer immediately prior to posting your answer to ensure you are fulfilling every requirement. I am very sorry if you create an exquisite program, only for someone to snipe it - if you really really want to post it anyway, specify non-competing.
>
> Full (but maybe not current) Requirement: Cannot contain `0`, `*` or `]` in the source code, and cannot use a join-on-newline builtin. Outputs `0`, then takes a non-negative integer input `n` and outputs a newline followed by the 0-indexed `n`th Fibonacci number (may be `1` indexed), followed by a newline, followed by the same input n squared, followed by a newline, followed by `n` multiplied by a new input `m`, followed by a newline, followed by `10^B`, where `B` is the number of bytes in the source code, followed by a newline, followed by the `n`th `0`-indexed (may also be `1`-indexed) prime number, followed by a newline, followed by the Greatest Common Divisor of n and m.
>
>
> 0: The program must output `0` before anything else. **Language: N/A**
>
> 1: The program source cannot contain `0`. **Language: 05AB1E**
>
> 2: The program takes a non-negative integer input `n` and outputs a newline followed by the `0`-indexed n'th Fibonacci number (may be `1` indexed). **Language: dc**
>
> 3: The program outputs a newline, followed by the same input `n` squared. **Language: J**
>
> 4: The program outputs a newline, followed by `n` multiplied by a new input `m`. **Language: Ohm**
>
> 5: The program cannot contain `*` (ASCII code `0x2A`). **Language: Python 3**
>
> 6: The program outputs a newline, followed by `10^B`, where `B` is the number of bytes in the source code. **Language: Mathematica**
>
> 7: The program outputs a newline, followed by the `n`th `0`-indexed (may also be `1`-indexed) prime number. **Language: JavaScript (ES6)**
>
> 8: The program does not use a join-on-newlines builtin, but can use any other join builtin. **Language: Jelly**
>
> 9: The program outputs a newline followed by the Greatest Common Divisor of n and m. **Language: Scala**
>
> 10: The program cannot contain `]`. **Language: Pyth**
>
>
>
>
# Current Scores (ordered by first post)
>
> **Okx**: 1.01
>
> **R. Kap**: 2.09
>
> **Conor O'Brien**: 1.03
>
> **Nick Clifford**: 1.04
>
> **Eric Rose**: 1.05
>
> **Greg Martin**: 1.06
>
> **Erik the Outgolfer**: **2.18**
>
> **math\_junkie**: 1.09
>
>
>
>
[Answer]
# Answer 1 - 05AB1E
Requirement: Prints `0`... without a `0` in the source code
```
¾
```
[Answer]
# Answer 5 - Python 3
**Requirements:** Outputs 0 without 0 in the source code, then takes a non-negative integer input n and outputs a newline followed by the 0-indexed nth Fibonacci number (may be 1 indexed), followed by a newline, followed by the same input n squared, followed by a newline, followed by n multiplied by a new input m. Do not use the character `*`, ASCII code `0x2A`.
```
def f(n, m):
print(1-1)
a = 1-1
b = 1
for i in range(n):
c = a+b
a = b
b = c
print(b)
print(n.__mul__(n))
print(n.__mul__(m))
```
[Answer]
# Answer 3 - [J](http://jsoftware.com/)
```
echo"+(1-1),(*:,~[:+/@:!&i.-)@".1!:1(3)
```
Requirement: Outputs `0` without `0` in the source code, then takes a non-negative integer input `n` and outputs a newline followed by the `0`-indexed `n`'th Fibonacci number (may be `1` indexed), followed by a newline, followed by the same input `n` squared.
[Try it online!](https://tio.run/nexus/j#@5@anJGvpK1hqGuoqaOhZaVTF22lre9gpaiWqaer6aCkZ6hoZahhrPn/vykA "J – TIO Nexus")
[Answer]
# Answer 4 — [Ohm](https://github.com/MiningPotatoes/Ohm)
Requirement: Outputs `0` without `0` in the source code, then takes a non-negative integer input `n` and outputs a newline followed by the 0-indexed `n`th Fibonacci number (may be 1 indexed), followed by a newline, followed by the same input n squared, followed by a newline, followed by `n` multiplied by a new input `m`.
```
¼,≡ƒ,²,*,
```
[Answer]
# Answer 2 - dc
```
12298P?sa1 1-sb1sc[lblcdsb+scla1-dsa1 1-<y]dsyxlcp
```
**Requirement:** Outputs `0` without `0` in the source code, then takes a non-negative integer input `n` and outputs a newline followed by the `0`-indexed `n`'th Fibonacci number (may be `1` indexed).
[Try it online!](https://tio.run/nexus/dc#@29oZGRpEWBfnGioYKhbnGRYnBydk5STnFKcpF2cnJNoqJsClIo31LapjE0prqzISS74/9/4a16@bnJickYqAA "dc – TIO Nexus")
[Answer]
# Answer 6 — Mathematica
Requirement: Outputs 0 without 0 or \* in the source code, then takes a non-negative integer input n and outputs a newline followed by the 0-indexed nth Fibonacci number (may be 1 indexed), followed by a newline, followed by the same input n squared, followed by a newline, followed by n multiplied by a new input m, followed by a newline, followed by 10^B where B is the number of bytes in the source code.
```
((e=Echo)[1-1];e@Fibonacci@#;e[#^2];e[1##];2^# 5^#&@59)&
```
[Answer]
# Answer 10 - Pyth
Requirement: Takes two inputs, `n` (>=0) and `m`. *Outputs* `0` without the use of `0`, `*` or `]` anywhere in the source code, and without builtins for joining on newlines. Then outputs a newline followed by the `1`-indexed nth Fibonacci number (may be `0` indexed), followed by a newline, followed by `n` squared, followed by a newline, followed by `n` multiplied by `m`, followed by a newline, followed by `10^B` where `B` is the number of bytes in the source code, followed by a newline and the `n`th `1`-indexed (may also be `0`-indexed) prime number, and finally followed by a newline and the Greatest Common Divisor of n and m.
```
JU2KE=H2VQ=+Js>2J=+YK=hHW!P_H=hH;jb[ZeJ^Q2sY^T51HiK
```
[Online interpreter](//pyth.herokuapp.com?code=JU2KE%3DH2VQ%3D%2BJs%3E2J%3D%2BYK%3DhHW%21P_H%3DhH%3Bjb%5BZeJ%5EQ2sY%5ET51HiK&test_suite=1&test_suite_input=5%0A1%0A8%0A-2&input_size=2)
[Answer]
# Answer 7 - JavaScript (ES6)
```
(a,b)=>String.fromCharCode(48)+'\n'+(m=(a)=>a>1?m(a-1)+m(a-2):1)(a)+'\n'+Math.pow(a,2)+'\n'+Math.exp(Math.log(a)+Math.log(b))+'\n'+1E257+'\n'+(T=(u,i=2,l=1-1,m=2)=>l<=u?(p=(o,z=2,s=1-1)=>z<o?p(o,z+1,s+(o%z<1&&z!=o)):s)(i)<1?T(u,i+1,l+1,i):T(u,i+1,l,m):m)(a)
```
**Requirement:** A function that takes two inputs, a non-negative integer `n` and any number `m` and *returns* a string containing `0` without the use of `0` anywhere in the source code, then a newline followed by the `0`-indexed `n`th Fibonacci number (may be `1` indexed), followed by a newline, followed by `n` squared, followed by a newline, followed by `n` multiplied by `m` without the use of `*` anywhere in the source code, followed by a newline, followed by `10^B` where `B` is the number of bytes in the source code, and finally followed by a newline and the `n`th `0`-indexed (may also be `1`-indexed) prime number.
## Test Snippet
```
S=(a,b)=>String.fromCharCode(48)+'\n'+(m=(a)=>a>1?m(a-1)+m(a-2):1)(a)+'\n'+Math.pow(a,2)+'\n'+Math.exp(Math.log(a)+Math.log(b))+'\n'+1E257+'\n'+(T=(u,i=2,l=1-1,m=2)=>l<=u?(p=(o,z=2,s=1-1)=>z<o?p(o,z+1,s+(o%z<1&&z!=o)):s)(i)<1?T(u,i+1,l+1,i):T(u,i+1,l,m):m)(a)
```
```
m: <input type="number" min=0 id="i1"></input>
<br>
n: <input type="number" step="0.01" id="i2"></input>
<br>
<input type="button" value="Submit" onclick="console.log(S(document.getElementById('i1').value, document.getElementById('i2').value))"></input>
```
[Answer]
# Answer 8 - [Jelly](https://github.com/DennisMitchell/jelly)
Requirement: A function that takes two inputs, a non-negative integer `n` and any number `m` and *returns* a string containing `0` without the use of `0` anywhere in the source code, then a newline followed by the `0`-indexed `n`th Fibonacci number (may be `1` indexed), followed by a newline, followed by `n` squared, followed by a newline, followed by `n` multiplied by `m` without the use of `*` anywhere in the source code, followed by a newline, followed by `10^B` where `B` is the number of bytes in the source code, and finally followed by a newline and the `n`th `0`-indexed (may also be `1`-indexed) prime number. No builtins for joining on newlines allowed, but joining builtins still allowed.
```
ÆḞṭØDW⁺¤;⁸²¤;×;ȷ25;⁸ÆN¤j⁷
```
[Try it online!](https://tio.run/nexus/jelly#@3@47eGOeQ93rj08wyX8UeOuQ0usHzXuOLQJSB@ebn1iu5EZiH@4ze/QkqxHDXMObfv//7/pf0MA "Jelly – TIO Nexus")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), submission #11, 432 bytes
```
n,m,z,c,q,a,s,t;A(a,b){return b?A(b,a%b):a;}B(n){if(n<=1)return 1-1;for(int i=2;i<n;i++)if(n%i==1-1)return 1-1;return 1;}C(n,c,z){while(c<n){if(B(z++))c++;}return z-1;}D(n){return(!n||n==1)?n:(D(n-1)+D(n-2));}main(){putchar(48);scanf("%d",&n);t=s=n;while(--t)s+=n;printf("\n%d\n%d\n",D(n),s);scanf("%d",&m);q=A(n, m);a=n;while(--m-1)n+=n;printf("%d\n",n);putchar(49);for(z=0;z<432;z++)putchar(48);printf("\n%d\n%d",C(a,1-1,1-1),q);}
```
I hereby ban line endings appearing anywhere in the source code :v).
[Try it online!](https://tio.run/##XVHBboMwDL3vKzokJlsYaWUctpqoarvP2CWk7RppeC1QTYLy7cyMbmI9WHHi5/eeHRe/O9f3QgU15OhEliqqeQWWcmzLXX0uZZYvV5CTDXNcWO7WINj6PUhm5nhFzOM57z9L8FLPvEnYZ8I@inCAhd4YrU@hvyl3GxCVbbD9OviPHbhs5F5Do93oooi7K7jRvu510B4f4F4uF1FqXMoCtKAS0XAkiNwV1gtgezzX7mBLSJ@RK2dlD0G4DehBkGtTGeFRNo5rrCK9HkudQEFvEm7HCGjQpOp/f4F8Miv1PtPMTngKdSFTppFD9f6svODPqhrzyE2WPiU8jDo1emsioI1@h@5tCKSTjtf36V36DQ "C (gcc) – Try It Online")
[Answer]
# Answer 9 - Scala
**Requirements**: Takes two inputs, `n` (>=0) and `m`. Outputs `0` without the use of `0` or `*` anywhere in the source code, and without builtins for joining on newlines. Then outputs a newline followed by the `1`-indexed nth Fibonacci number (may be `0` indexed), followed by a newline, followed by `n` squared, followed by a newline, followed by `n` multiplied by `m`, followed by a newline, followed by `10^B` where `B` is the number of bytes in the source code, followed by a newline and the `n`th `1`-indexed (may also be `0`-indexed) prime number, and finally followed by a newline and the Greatest Common Divisor of n and m.
```
(n:Int,m:Int)=>{
val z=1-1;val o=println _;var i=1;var j=z
o(z)
o((1 to n).foldLeft(z,1)((a,b)=>(a._2,a._1+a._2))._1)
o(math.pow(n,2))
o(List.fill(n)(m).sum)
o(math.pow(9+1,299))
while(j!=n){i+=1;if((2 to i-1)forall(i%_!=z))j+=1};o(i)
o((1 to math.min(n,m)).filter(c=>n%c==z&&m%c==z).last)
}
```
[Try it out here](https://scalafiddle.io/sf/rF2IpSY/0)
]
|
[Question]
[
Over on <http://meta.stackoverflow.com>, we have a few memes of our own. One of them is Freehand Red Circles.
See [this post](https://meta.stackexchange.com/a/19775/180276):
[](https://meta.stackexchange.com/a/19775/180276)
So, the challenge is,
## can you draw freehand red circles... with code?
Additional restrictions:
* You will take an **image** as input, and you must output the image with freehand red circle added.
* Must be predictable, i.e. same image input must result in same output. You can use randomness, but results have to be consistent for same input.
* Output must be exactly the same image as input, except with circle (no other alterations).
* The freehand red circle must look freehand (no perfect circles!), be red (obviously), and look generally like a circle (no random squiggly lines).
---
This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most upvotes at the beginning of March 2014 will win. There is no specific goal, other than "freehand red circles," so be as creative as possible so you get the most upvotes! (To be as unbiased as possible, I will upvote any answer that follows the rules.)
[Answer]
# C + GD library
Instead of just drawing circles any old where, I thought it would be fun to find something red in the picture and draw a circle around that.
Here are some examples of the results obtained [with](http://commons.wikimedia.org/wiki/File:V-Pick_Group.JPG) [a](http://commons.wikimedia.org/wiki/File:Botones.jpg) [few](http://commons.wikimedia.org/wiki/File:A_line_of_colored_pushpins.jpg) [photos](http://commons.wikimedia.org/wiki/File:Grey_and_red_Mini%27s_-_Flickr_-_foshie.jpg) [from](http://commons.wikimedia.org/wiki/File:Post_box_-_geograph.org.uk_-_168995.jpg) [Wikimedia](http://commons.wikimedia.org/wiki/File:SEAT_600_cars.jpg) [Commons](http://commons.wikimedia.org/wiki/File:Redbutton.jpg):

And here's the code. It's a bit messy, but not too difficult to follow, I hope:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gd.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
/* Used for image segmentation */
int floodfill(int *tmp, int i, int w, int id) {
int np=1;
tmp[i]=id;
if (tmp[i-w-1]<0) np+=floodfill(tmp,i-w-1,w,id);
if (tmp[i-w]<0) np+=floodfill(tmp,i-w,w,id);
if (tmp[i-w+1]<0) np+=floodfill(tmp,i-w+1,w,id);
if (tmp[i-1]<0) np+=floodfill(tmp,i-1,w,id);
if (tmp[i+1]<0) np+=floodfill(tmp,i+1,w,id);
if (tmp[i+w-1]<0) np+=floodfill(tmp,i+w-1,w,id);
if (tmp[i+w]<0) np+=floodfill(tmp,i+w,w,id);
if (tmp[i+w+1]<0) np+=floodfill(tmp,i+w+1,w,id);
return np;
}
int main(int argv, char *argc[]) {
FILE *infile,*outfile;
gdImagePtr img;
int *t, *tmp;
int w,h,x,y,r,g,b;
int c,redness,rgb;
int i,np,max,min,thresh;
int xt,yt,n;
int areaID,size,maxID;
double xmin,ymin,xmax,ymax,rad,r0,th;
gdPoint v[33];
/* Check command line and open source JPEG file */
if (argv!=3) return printf("Usage: %s <in.jpg> <out.jpg>\n",argc[0]);
if (!(infile=fopen(argc[1],"r"))) return printf("Can't open <%s>\n",argc[1]);
if (!(img=gdImageCreateFromJpeg(infile))) return printf("Bad JPEG: <%s>\n",argc[1]);
fclose(infile);
/* Extract red pixels and auto-threshold */
w=img->sx;
h=img->sy;
np=w*h;
t=tmp=calloc(np,sizeof(int));
for (max=0,min=255,y=1;y<h-1;y++) {
for (x=1;x<w-1;x++) {
rgb=gdImageGetTrueColorPixel(img,x,y);
r = (rgb&0xff0000)>>16;
g = (rgb&0xff00)>>8;
b = rgb&0xff;
redness = max(0,r-(max(g,b)+abs(g-b)));
if (redness>max) max=redness;
if (redness<min) min=redness;
*t++ = redness;
}
t += 2;
}
thresh = (max+min)/2;
for (t=tmp,i=0;i<np;i++,t++) *t=((*t>thresh)?-1:0);
/* Label each area detected */
areaID=1;
maxID=0;
max=-1;
for (t=tmp,i=0;i<np;i++,t++) {
if (*t<0) {
size=floodfill(tmp,i,w,areaID);
if (size>max) {
max = size;
maxID = areaID;
}
areaID++;
}
}
/* Calculate centre coordinates and area */
if (max>0) {
xt=yt=n=xmax=ymax=0;
xmin=w; ymin=h;
for (t=tmp,y=0;y<h;y++) {
for (x=0;x<w;x++) {
if (*t++==maxID) {
xt+=x;
yt+=y;
n++;
if (x<xmin) xmin=x;
if (y<ymin) ymin=y;
if (x>xmax) xmax=x;
if (y>ymax) ymax=y;
}
}
}
x = xt/(2*n) + (xmax+xmin)/4;
y = yt/(2*n) + (ymax+ymin)/4;
r0 = max(20,min(min(w,h),max(xmax-xmin,ymax-ymin))/2);
}
/* Default circle if nothing found */
else {
x=w/2; y=h/2; r0=min(w,h)/3;
}
/* Draw a red circle */
for (th=4.0,i=0;i<33;i++) {
rad = r0 * (1.2 + (" ,<MYZVSB>@EJIOSWZfgb^bbfgeZTOI@2"[i]-87)/160.0);
v[i].x = x + rad * sin(th);
v[i].y = y + rad * cos(th);
th += 0.22;
}
gdImageSetThickness(img,7);
c = gdImageColorAllocate(img,255,0,0);
gdImageOpenPolygon(img,v,33,c);
/* Output results to file */
printf("Saving...\n");
if (!(outfile=fopen(argc[2],"w"))) {
return printf("Can't open <%s> for writing\n",argc[2]);
}
gdImageJpeg(img,outfile,85);
fclose(outfile);
gdImageDestroy(img);
printf("Finished\n");
return 0;
}
```
---
**Note:** Markdown messed up my link in the comments, so I'll just point out that the code uses [segmentation](http://en.wikipedia.org/wiki/Image_segmentation) to identify *all* the areas of red in the picture, and then draws a circle around the largest of these. For example, [this image](http://commons.wikimedia.org/wiki/File:Buket_and_spade_on_Killahoey_Strand_-_geograph.org.uk_-_1426946.jpg):

produces the following output:

[Answer]
# C — about ~~750~~ 720 bytes if squeezed\*
I think I came up with something that looks freehand-y enough.
* starts at a random angle
* draws a full circle plus or minus a bit
* uses a thick squiggly line (maybe *too* squiggly!)
* is customizable by changing a `MAGIC` number
Compile:
```
gcc -o freehand freehand.c -lm
```
Run:
```
./freehand [X center in % W] [Y center in % H] [radius in % diagonal] < [PPM file input] > [PPM file output]
```
Example:
```
./freehand 28.2 74.5 3.5 < screenshot.ppm > freehand.ppm
```
Before:

After:

Code:
```
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define MAGIC 42
#define UNIFORM(x) ((x) * (double)rand() / (double)RAND_MAX)
typedef struct {unsigned char r, g, b;} RGB;
int main(int argc, char **argv)
{
int W, H, i, f, g, x, y;
double X, Y, R, a, r;
RGB *p;
srand(MAGIC);
if (argc != 4 || scanf("P6 %d %d 255\n", &W, &H) != 2)
return 1;
p = malloc(sizeof(RGB) * W * H);
fread(p, sizeof(RGB), W * H, stdin);
X = W * atof(argv[1]) / 100.0;
Y = H * atof(argv[2]) / 100.0;
R = hypot(W, H) * atof(argv[3]) / 100.0;
for (a = UNIFORM(M_PI), i = 2.0 * M_PI * R + UNIFORM(R / 4.0), r = R; i > 0; i--, a += 1.0 / R)
{
r += UNIFORM(2.0) - 1.0;
f = sin(a) * r + X;
g = cos(a) * r + Y;
for (x = f - 2; x <= f + 2; x++)
{
for (y = g - 2; y <= g + 2; y++)
{
if (x >= 0 && x < W && y >= 0 && y < H)
{
RGB *s = p + y * W + x;
s->r = 255;
s->g = 0;
s->b = 0;
}
}
}
}
printf("P6 %d %d 255\n", W, H);
fwrite(p, sizeof(RGB), W * H, stdout);
free(p);
return 0;
}
```
\* and using `U` for `UNIFORM` and `M` for `MAGIC`
[Answer]
# Mathematica
```
ClearAll[f]
f[image_,rad_, xPos_:.5,yPos_:.5,color_:Darker[Red,0.3],thick_:.01,axes_:False]:=
Module[{i=ImageDimensions[image],rr,y=SeedRandom[2]},
rr:=RandomReal[{-.1,.1}];
Show[image,Graphics[{color,JoinForm["Round"],CapForm["Round"],Thickness[thick],
Line[t=Table[{rad i[[2]] (Cos[z]+rr)+i[[1]]xPos,rad i[[2]] (Sin[z]+rr)+i[[2]] yPos},
{z,0, 2 Pi+2Pi/12,Pi/12}]]}],Axes-> axes]]
```
`f` takes the following parameters:
* image: the image that will be marked up with a circle
* rad: the radius of the circle, in fraction of image width
* xPos: the position of the center of the circle along x, from 0 to 1 (default=.5)
* yPos: the position of the center of the circle along y, from 0 to 1 (default=.5)
* color: ink color (default= dark red)
* thickness: stroke thickness (default = .01)
* axes: whether to display axes (default = False)
---
**Examples**
```
text = Import["text.png"]
f[text,.13,.58,.23]
```
## pic1
A different radius, location, blue color, thicker stroke, displaying axes.
```
f[text,.22,.7,.5,Blue,.015,True]
```

]
|
[Question]
[
## Background
For the purpose of this challenge, all numbers and their string representations are assumed to be in *decimal* (base 10). I tried to find proper terminology for this challenge, but I do not think there is any, so I made it up.
A self-replicating number is a number that appears as a substring in any of its multiples up to and including its square, excluding itself. An \$n\$-order self-replicating number appears as a substring in ***exactly \$n\$*** multiples of itself up to its square, including itself. All numbers are *at least* 1st-order self-replicating numbers, because they appear as a substring in their first multiple (1 times the number).
For example: 5 is a 3rd-order self-replicating number, because it appears 3 times in the multiples of itself up to its square: **5**, 10, 1**5**, 20, 2**5**. On the other hand, 4 is a 1st-order self-replicating number, because it appears only once: **4**, 8, 12, 16.
There are only 6 1st-order replicators, because numbers will always have a self-replicator order \$\geq\lfloor\log\_{10}(x)\rfloor+1\$, where \$x\$ is the number, as multiples of the number and any power of ten are guaranteed to have the number as a substring. Because of this property of self-replicating numbers, the series of \$n\$-order self-replicating numbers cannot ever be an infinite series. The last possible \$n\$-order self-replicating number is \$10^n-1\$.
## The Challenge
Your task is to write a program which takes two integers, \$m\$ and \$n\$, and does one of the following:
* return the first \$m\$ \$n\$-order self-replicating numbers **\$or\$**
* return the \$m^{th}\$ \$n\$-order self-replicating number (0 or 1-indexed, your choice) **\$or\$**
* output the series of numbers that are either \$m\$-order or \$n\$-order self-replicating numbers. You may treat this series as if it were infinite; in other words, your code is not required to halt - it'd be very cool if it did, though. **\$or\$**
* By popular demand, and because the previous option was a source of valid misinterpretation, you may now instead take a single integer, \$n\$, and output the series of \$n\$-order self-replicating numbers. As with the last option, you may treat the series as if it were infinite.
## Rules
* You are allowed undefined behavior for values of \$m\leq0\$ or \$n\leq0\$.
* Your code is not required to halt if the next number in the sequence does not exist. For example: if you chose either of the first two output options and your code receives \$m=7, n=1\$ as input, a 7th 1st-order self-replicating number will never be found because no 1st-order self-replicating numbers higher than 9 exist.
* Standard loopholes forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program in bytes for each language wins.
## Test Cases
| \$m\$ | \$n\$ | Output |
| --- | --- | --- |
| 5 | 0 | undefined |
| 6 | 1 | 1,2,3,4,7,9 |
| 7 | 1 | 1,2,3,4,7,9 **\$or\$** undefined |
| 20 | 2 | 6,8,10,11,12,13,14,15,16,17,18,19,21,22,23,24,26,27,29,31 |
| 30 | 4 | 30,45,48,52,55,59,68,69,82,94,110,115,122,128,130,136,137,139,144,145,152,168,170,171,176,177,184,187,190,192 |
| 10 | 38 | 650,3520,3680,3920,6050,6350,6840,7640,7880,7960 |
| 3 | 101 | 7125,8900,9920 |
| 1 | 2778 | 5000 |
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
1ẇⱮ×R$SƊ=¥#
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//MeG6h@KxrsOXUiRTxoo9wqUj////Mv8yMA "Jelly – Try It Online")
Takes \$n\$ then \$m\$ on the command line and outputs the first \$m\$ \$n\$-order self-replicating numbers
## How it works
```
1ẇⱮ×R$SƊ=¥# - Main link. Takes n on the left
¥ - Group the previous 2 links into a dyad f(k, n):
Ɗ - Group the previous 3 links into a monad on k:
$ - Group the previous 2 links into a monad on k:
R - Yield the range [1, 2, ..., k]
× - Multiply each element by k
Ɱ - For each element i in [k, 2k, ..., k²]:
ẇ - Is k a substring of i?
S - Sum; Count the 1s
= - Does this equal n?
1 # - Count up k = 1, 2, 3, ... until m such k return true under f(k, n)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~76 67~~ 66 bytes
*Saved 1 byte thanks to @user81655*
A function expecting \$n\$ and printing the \$n\$-order self-replicating numbers forever.
```
n=>{for(m=0;k=++m;s||print(m))for(s=n;k;)s-=!!(k--*m+'').match(m)}
```
[Try it online!](https://tio.run/##FcpBCoAgEADAt3jSTYwOHQLZ/iKCZLImKl6yt1udZ07TTLHZp6raNhyOiPvtriwIFx1QStKl95R9rIIAfikYddBQFDImglITSc5hJlPt8Z1nOLHCeAE "JavaScript (V8) – Try It Online")
### Commented
```
n => { // n = input
for( // infinite outer loop:
m = 0; // start with m = 0
k = ++m; // before each iteration, increment m and copy it in k
// (always truthy, so we never exit the loop)
s || print(m) // after each iteration, print m if s = 0
) //
for( // inner loop:
s = n; // start with s = n
k; // stop when k = 0
) //
s -= // decrement s if ...
!!(k-- * m + '') // ... k * m coerced to a string
.match(m) // contains m (decrement k afterwards)
} // end
```
[Answer]
# [R](https://www.r-project.org/), ~~58~~ 55 bytes
-3 bytes thanks to Dominic van Essen
```
n=scan();repeat if(sum(grepl(F,(F=F+1)*1:F))==n)show(F)
```
[Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTuii1IDWxRCEzTaO4NFcjHcjN0XDT0XCzddM21NQytHLT1LS1zdMszsgv13DT/G/yHwA "R – Try It Online")
Prints all the \$n\$-order self-replicating numbers.
[Answer]
# [J](http://jsoftware.com/), 47 bytes
```
(>:@][echo@]^:(e.~1#.1*@#.]E.&":"0]+]*i.))^:_&1
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NeysHGKjU5Mz8h1i46w0UvXqDJX1DLUclPViXfXUlKyUDGK1Y7Uy9TQ146zMTA3VDP9rcqUpmCgYW/wHAA "J – Try It Online")
Third option for output.
TIO has +2 since I changed infinity `_` to 651 to make it clear that it works.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
Generates the sequence for a given \$n\$.
```
≤≜.{≥.;?×s?∧≜}ᶜ?∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfblvw/1Hnkkedc/SqH3Uu1bO2Pzy92P5Rx3KgCFByDoj5/78JAA "Brachylog – Try It Online")
```
≤≜.{≥.;?×s?∧≜}ᶜ?∧
≤≜ a number k greater-equal than n
. is the output
{ }ᶜ count the outputs of the predicate,
? unify with n
∧ return the output
≥ a number less-equal than k
. is the output
;?× multiplied by k
s? has k as substring
∧≜ return the output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
IΦXχ⌈θ№θLΦι№I×ι⊕λIι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zpyS1SCMgvxxIGhroKPgmVmTmluZqFGpq6ig455cCFRbqKPik5qWXZMBUZ8JkwEaEZOamFoPEPPOSi1JzU/NKUlM0cjTB@kHymZpQYP3/f3S0oY6CUWzsf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes a pair (actually any list) of integers `[n, m]` as input and outputs all self-replicating numbers of those order(s), but somewhat slow so avoid using it at all really. Explanation:
```
χ Predefined variable 10
X Raised to power
θ Input integers
⌈ Maximum
Φ Filter implicit range where
θ Input integers
№ Contains
L Length of
ι Current value
Φ Filter implicit range where
ι Outer value
× Multiplied by
λ Inner index
⊕ Incremented
I Cast to string
№ Contains
ι Outer value
I Cast to string
I Cast to string
Implicitly print
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 81 bytes
outputs the series of n-order self-replicating numbers forever
```
Do[Tr@Boole@StringContainsQ[(T=ToString)/@Array[m#&,m],T@m]==#&&Print@m,{m,∞}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yU/OqTIwSk/PyfVIbikKDMv3Tk/ryQxM684MFojxDYkHyKoqe/gWFSUWBmdq6ymkxurE@KQG2trq6ymFgCULXHI1anO1XnUMa82Vu0/WETBIT3a2CL2/38A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
def f(n,i=1):
if sum(`i`in`i*~k`for k in range(i))==n:print i
f(n,i+1)
```
[Try it online!](https://tio.run/##JcsxDoAgDAXQnVN0pOqCIwl3qYlUf4zFoA4uXh0H3/6O51qLja3NWUm9DUiBoyMonffuBQITdO8mWiptBKM62ZI9mFOyeFTYRXD/7QM39SO3Dw "Python 2 – Try It Online")
Trivial answer that loops through the numbers in order and checks if they are self-replicating.
-8 bytes thanks to *dingledooper*
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 99 bytes
```
param($n)for($x=1;;++$x){$o=0;for($i=$x;$i-le($x*$x);$i+=$x){$o+=("$i"-match"$x")};if($o-eq$n){$x}}
```
[Try it online!](https://tio.run/##JYzRCsMgEAT/RfZBI0JKH4/7GCmGCKYmttCD4LdfJH3cmWH3@kvts6ZSVPfY4mbxdkttFsIPIu8h7kTlmW6YGULIoaQRTMON4fnfeLYG2YQtfl@rgRjXKS8WNaRjnJ6Q3lX1eQE "PowerShell – Try It Online")
A script expecting \$n\$ and printing the first \$n\$-order self-replicating numbers forever.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 77 bytes
```
param($m,$n)for(;$n*($m-=$z)){,++$i*($z=(1..$i|?{$i*$_-match$i}).Count-eq$n)}
```
[Try it online!](https://tio.run/##bVLJjtNAEL37K0rBoJgpR@5ub60oMCgCaQ7JIDI3hEaepMMYecOLQMn428Ozk8CFQ1fX@l5Vqaryl6mbZ5NlJ3tPCzqeqqRO8qmds104@7Kezu3iLUx3YR8c58g3N3YK@7CYitnMTl/eH2Hbj26etNtnO@2d2bLsitY1P1Hfn3rLup1aFhFPAybynFENoQo8CMmKfY5YO9YrRKL/RKisqSt2Zp8WZueQ@47uCuhpaygry2pElB6THOpCjll4LAQLyUKx8FkELEIWEQuENEtAS5aKpc8yZBmx1KzEuTMFHH/AgeIH7MccSA4CDjSHMYeaY8kakCMFcIEkJGCRLhRIFFiUBityUC9QLVAoIsQj9BQNjQydIB7j1/BrOczeliXGKb4Tlk4Pd/fjOkBDKkY/YeCxCjClCmMIDS304AvVIGLf4ygcRIxopEPvvE01bNPDPiMhA46157FG6Tk4rFlGESb0PLgsh17oNR2xBiI7LaoVj98an/ldmW1rdjgQ@/GcYLKkakbPyiRNVxt3WeZ5UuwuCGNSbZoua5HzBsc1Yp4hx4x@lF8/b5Zd05b5/dMPcHy7PdLHv9BXljmtBmsAmNP6oq7ntOm2W9M0cEwuXBPC5cG6djyZ05drE/9yeqvHsJ/KGlfrPiRPmSH3Q9eWm/RgTn8A "PowerShell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞ʒL¤*¬δåOQ
```
Uses the last option: given an integer \$n\$, outputs the infinite (non-halting) sequence of \$n\$-order self-replicating numbers.
[Try it online](https://tio.run/##yy9OTMpM/f//Uce8U5N8KrUqz205vNQ/8P9/EwA) or [verify for the first `n=[0,20]` inputs all output-values below 1000](https://tio.run/##yy9OTMpM/W9kcGyS36GVnkr@pSUFpSXFCkmpOfnlCof3K6TlFylk5gHFFPJsD@@3UlDS@e9zapJPpVbluS2Hl/ofWhf4v1bn0Db7/4YGBgYA).
**Explanation:**
```
∞ # Push an infinite list of positive integers: [1,2,3,...]
ʒ # Filter each integer `y` by:
L # Push a list in the range [1,y]
y* # Multiply each by `y`
δ # Map over each value in this list:
y å # Check if it contains `y` as substring
O # Sum this list together to get the amount of truthy values
Q # And check if this is equal to the (implicit) input-integer `n`
# (after which the filtered infinite list is output implicitly as result)
```
[Answer]
# Scala, 67 bytes
```
n=>Stream.from(1)filter(x=>x.to(x*x,x).count(_+""contains ""+x)==n)
```
[Try it in Scastie!](https://scastie.scala-lang.org/TdeAc7aBRCu8PflS4j3sPQ) (ignore the deprecation warnings)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èõ*X è_s øXÃ¥V}jU1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yPUqWCDoX3Mg%2bFjDpVZ9alUx&input=MzAKMg)
* we could save a byte by returning nth term 0 indexed just by using `iU` instead of `jU1` but this way is more easy to validate output.
```
È ...}jU1 - first n terms
õ*X - multiples to X^2
è .. ¥V - number of multiples returning true to _ 'function (Z)'== second input?
_s øXÃ - convert to string and check if contains X
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 27 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍸⍵=(1⊥⊢(1∊⍷⍥⍕)¨⊢×⍳)¨⍳10*⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu@NR71ZbDcNHXUsfdS0C0h1dj3q3P@pd@qh3quahFUCxw9Mf9W4GMXs3GxpoAVXXAgA&f=S1MwAgA&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f)
A dfn submission which takes \$n\$ and prints all self-replicating numbers of order \$n\$ and terminates.
**Commented:**
```
{⍸⍵=(...)¨⍳10*⍵} ⍝ dfn which takes n as a right argument and returns all nth-order self-replicating numbers
⍳10*⍵ ⍝ the indices from 1 to 10^n
(...)¨ ⍝ for each number, calculate the order of self-replication
⍵= ⍝ is this order equal to n?
⍸ ⍝ the indices of all 1's
(1⊥⊢(1∊⍷⍥⍕)¨⊢×⍳) ⍝ train that takes a number k as a right argument and returns the order
⊢×⍳ ⍝ k × (1 2 ... k) = (k×1 k×2 ... k×k)
⊢( ... )¨ ⍝ for each value as a right argument and k as a left argument:
1∊⍷ ⍝ is the left argument is a substring of the right after ...
⍥⍕ ⍝ ... both are formatted as a string
1⊥ ⍝ sum all results
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~160~~ 154 bytes
```
def am(m,n):
k=lambda n:[i*n for i in range(1,n+1)if str(n)in str(i*n)];l=[];i=1
while len(l)<m:
q=k(i)
if len(q)==n:l.append(q[0])
i+=1
return l
```
[Try it online!](https://tio.run/##PU5LDoIwEN1zill2pDEUExdgT0JY1FBkQjuUWmM8fS0u3L1/XvikZeNLzpOdwXjhJWNXwaqd8ffJAHcDnRjmLQIBMUTDDyuU5FohzfBMUTAW/QAliGPv9DD2pFUF74WcBWdZOLz5sgq7XgVhAaV66DtqzZ07mxAsT2IfmvHn1kc92vSKDC6HSJxEOXeVCrH607aRLWL@Ag "Python 3 – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 96 bytes
```
fun f(n:Int)=generateSequence(1){it+1}.filter{x->(x..x*x step x).count{"$it".contains("$x")}==n}
```
[Try it online!](https://tio.run/##hc7NCsIwDAfwu09Rxg6tYtmHOBHm3fN8gTGyUTfTuWVQKH32WWR60MNyCsmP5N9q6hTOcz0hqzmer0gibwBhKAkKeE6AFfBYWEW72MladQSDNfsLN1KarWEjQc@MkJWekGwQKgp8j1QqHHkQmkC4PEf3fvDwQy6Y3TBf/aCQOuS1vy6pbIEfhbxrhTddkN81XIgfmCwwidbkYZHpqkxPC41XaRx9kqarSbPse/ffuvkF)
Returns the sequence of all \$n\$-order self-replicating numbers
]
|
[Question]
[
# The 21 Hairstyles of the Apocalypse
Given a a list of numbers between 1 and 21 (or 0 and 20) output a "stitched together" drawing of the following faces (***see rules for stitching information***):
```
___ ,,, ooo === +++ ### -*~*-
(o o) (o o) (o o) (o o) (o o) (o o) (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
*** ||| _/7 ))) ((( xxx @__
(o o) (o o) (o o) (o o) (o o) (o o) (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
((_ >X< '*` ^^^ )|( \|/ &&&
(o o) (o o) (o o) (o o) (o o) (o o) (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
```
Each, unique face listed on a new-line (the # is the integer ID for the face):
```
___
(o o)
ooO--(_)--Ooo #1
,,,
(o o)
ooO--(_)--Ooo #2
ooo
(o o)
ooO--(_)--Ooo #3
===
(o o)
ooO--(_)--Ooo #4
+++
(o o)
ooO--(_)--Ooo #5
###
(o o)
ooO--(_)--Ooo #6
-*~*-
(o o)
ooO--(_)--Ooo #7
***
(o o)
ooO--(_)--Ooo #8
|||
(o o)
ooO--(_)--Ooo #9
_/7
(o o)
ooO--(_)--Ooo #10
)))
(o o)
ooO--(_)--Ooo #11
(((
(o o)
ooO--(_)--Ooo #12
xxx
(o o)
ooO--(_)--Ooo #13
@__
(o o)
ooO--(_)--Ooo #14
((_
(o o)
ooO--(_)--Ooo #15
>X<
(o o)
ooO--(_)--Ooo #16
'*`
(o o)
ooO--(_)--Ooo #17
^^^
(o o)
ooO--(_)--Ooo #18
)|(
(o o)
ooO--(_)--Ooo #19
\|/
(o o)
ooO--(_)--Ooo #20
&&&
(o o)
ooO--(_)--Ooo #21
```
The face is as follows:
```
hhhhh
(o o)
ooO--(_)--OooS
```
Where `h` is the dynamic apocalyptic hairstyle and `S` is the potential stitching hyphen.
---
# Examples
**Input:** `[1,2,3,4,5]`
**Output:**
```
___ ,,, ooo === +++
(o o) (o o) (o o) (o o) (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
```
---
**Input:** `[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]`
**Output:**
```
___ ,,, ooo === +++ ### -*~*- *** ||| _/7 ))) ((( xxx @__ ((_ >X< '*` ^^^ )|( \|/ &&&
(o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o) (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
```
---
**Input:** `["Fraggle Rock"]` / `[22]` / `[-21041024]` / `[22,23,24,25,26]`
**Output:** `Nobody cares.`
---
**Input:** `[1,1,1,1]`
**Output:**
```
___ ___ ___ ___
(o o) (o o) (o o) (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
```
---
# Rules
* Preceeding and trailing newlines/spaces/hyphen are fine.
* Faces can occur more than once in the input.
* If there is an invalid number in the input you may have undefined behavior.
* The stitching:
+ The stitched faces will be concatenated by a single hyphen on the bottom (3rd) line.
+ The faces will all be on a single line (unlike the first drawing).
* Input can be 0 or 1 indexed, with 20 being the max for 0, 21 for 1.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~122~~ ~~117~~ ~~113~~ ~~110~~ ~~109~~ ~~107~~ ~~105~~ ~~104~~ ~~103~~ ~~102~~ ~~100~~ 99 bytes
1-indexed, with index wrapping. I've followed the spec here, which requires a hyphen *between* the last line of each face, rather than the test cases, which include a hyphen *after* the last line of each face.
```
[Umg"@__((_>X<'*`^^^)|(\\|/"i"&_,o=+#*|)(x"m³ ò3 i7"-*~"ê)iA"_/7")¡"(o o)"á"O--(_)--O"ûoDÃq-]ûD m¸
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=W1VtZyJAX18oKF8%2bWDwnKmBeXl4pfChcXHwvImkiJl8sbz0rIyp8KSh4Im2zIPIzIGk3Ii0qfiLqKWlBIl8vNyIpoSIobyBvKSLDoSJPLS0oXyktLU8i%2b29Ew3EtXftEIG24&input=WzEsNyw4LDEwLDIwLDIxXQ)
```
[ :Construct an array of 3 elements
Umg"@.../"i"&...x"m³ ò3 i7"-*~"ê)iA"_/7") :FIRST ELEMENT (F)
U : Input array
m : Map
g : Index into
"@.../" : Literal string
i : Prepend
"&...x" : Literal string
m : Map
³ : Repeat 3 times
ò3 : Split into chunks of 3
i7 : Insert at 0-based index 7
"-*~"ê : "-*~" palindromised
) : End insert
iA"_/7" : Insert "_/7" at index 10
) : End map
¡"(o o)"Ã :SECOND ELEMENT (S)
¡ : Map input array
"(o o)" : Literal string
à : End map
¡"O...O"ûoDÃq- :THIRD ELEMENT (T)
¡ : Map input array
"O...O" : Literal string
ûo : Centre pad with "o"
D : To length 13
à : End map
q- : Join with "-"
] :End array
ûD :Centre pad each to length 13 with spaces (T will always be at least 13 characters long)
m :Map
¸ : Join F & S with spaces. Split T on spaces, creating a singleton array which gets cast back to a string on output
:Implicit output, joined with newlines
```
[Answer]
# [Python 2](https://docs.python.org/2/), 209 bytes
```
def f(a):s=t=u='\n';i=0;exec"s+=(\"_,o=+#-*|_)(x@(>'^)\\&_,o=+#**|/)(x_(X*^||&_,o=+#~*|7)(x__<`^(/&\"[a[i]::21]+'*-'*(a[i]==6)).center(14);t+=' (o o) ';u+='ooO--(_)--Ooo-';i+=1;"*len(a);print s+t+u[:-1]
```
[Try it online!](https://tio.run/##Lc7RSsMwGAXga32KUGH5/6RxazcUEiO@wW6Fpq1lpjMgyWhTmBB89doyz9U539W5/MSv4Mt5/rQ96aFDOeqoJ02Np8rpnbJXe8pGrsFkbR40fxAstQjXN3ilDRqzuSljabtoC@@sSekff1l6XrF9@WhguzFZ1VWulrIsak6ZoAzWrfUT4uPJ@mgHKA6oIteULIFAAq6FUDUtFsJRCGhRiGMIYrnHdaEy9m398ltdBucjGXnkUyVFUc99GIgjzpOh82cLe5T3dz3chsvLIt8jzn8 "Python 2 – Try It Online")
0-based indexing; nothing especially clever here, just data accessed via slicing and using exec instead of a loop.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~103~~ 102 bytes
```
E²⪫Eθ⎇ι(o o)⪫ײ§ -⁼λ⁶§⪪”|″:αuxkτT↷K[ï�↔ς↨?◧BZ@C←↑⊞A⧴M✂↶ºKf÷H#S⦃J&≔⁰∧5À³≕r‹▷”³λ× ⁹M⁴←⪫EθooO--(_)--Ooo¦-
```
[Try it online!](https://tio.run/##TU9NS8NAEL37K5YNxNlkltoq9TOiBw@KpYI9CG2zLnXFhTXTprFECP71dWwFndPMe/PezFu82XpBNsT4UPuqgZFdwgDFHflq269QTFxd2foTPAoJJEjJX37i3936Z/u6ua1eXAtSaOZuVh82rCGgGCql/tjHZfANSGMMIhJRURR5nidJkn1lXF3Xmd4xKwCgbdsrYwDM5dPFfvZclqXqYDbremma8oVDdg1qa777QQpGTxk43xvRxsERirN799rwvIv1P48kGmsNRmk9JpJsIrVkaYzT6QEOsT/A/sl8HvUmfAM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
E²⪫Eθ
```
Loop over the input twice. Each result is then implicitly printed on its own line.
```
⎇ι(o o)
```
On the second loop, just generate the eyes.
```
⪫ײ§ -⁼λ⁶
```
Wrap hairstyle 6 in `-`s, other hairstyles in spaces.
```
§⪪”|″:αuxkτT↷K[ï�↔ς↨?◧BZ@C←↑⊞A⧴M✂↶ºKf÷H#S⦃J&≔⁰∧5À³≕r‹▷”³λ
```
Extract the three hairstyle characters from a compressed string.
```
× ⁹
```
Insert nine spaces between each hair or eyes.
```
M⁴←
```
Move 4 spaces left.
```
⪫EθooO--(_)--Ooo¦-
```
Print the rest of the faces, joined with a `-`.
[Answer]
# [R](https://www.r-project.org/), ~~413~~ 391 bytes
Thanks Giuseppe for 22 less bytes and getting this under 400 bytes.
```
function(s,n=length(s)){I=intToUtf8
U=utf8ToInt
R=rep
K=cat
a=U("_,o=+#^*|&)(x")
b=c("@__","((_",">X<","'*`","",")|(","\\|/","","-*~*-","_/7")
s[s==7]=22;s[s==10]=23;s[s==18]=7;s[s==21]=10
for(i in s)K(I(c(rep(32,4+(i!=22)),"if"(i<14,R(a[i],3),U(b[i-13])),R(32,5+(i!=22)))))
K("
",I(R(c(R(32,3),40,111,32,111,41,R(32,6)),n)),"
")
K(I(40+R(c(x<-c(71,71,39,5,5),0,55,1,rev(x),5),n)[-(14*n)]))}
```
[Try it online!](https://tio.run/##VVBhS8MwEP2eXzEj6KW7YtOmdm6N@LXsW1lB6GrdyqoBSaXtZOD0r9frJoLhePcud@/lSDvUsTvUe1v1prHQodVvO/vSv0InxGeije1XTdbXM5bpPaVVk9iepbrdvbOlrjY92@gMeImNnl4@OccrAQcu2FZXwB/KkiMHGPH@MSa8dp4JKcQRCNfr4825dp1vx6Vc3kSk7vJO66jQvr84UekRD375rNDRmfqyoBarmxbMxNhJJ5aQQAW0GwQ@qimYC/IQArmpOZhYKkxhk5sCA4EZbHPjyqCgfjrOh3/zdNgSOOOYQEqGpzZJlIdSSqRiTEqedbdkYMdHGB9lCShvOqoOsVtBJJEiuMMQQ4EehiFKbHcfcBDjhRW5C1I5VtAaX0MNch6JBX0r8LUluxpmc6n@38hw7ksx/AA "R – Try It Online")
[Answer]
# JavaScript (ES6), ~~200~~ 199 bytes
Expects 1-indexed input.
```
a=>[1,0,2].map(y=>a.map(n=>s=y&2?'ooO--(_)--Ooo':` ${p='( -'[y*n-7?y:2]}${"o o___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&".substr(y*n*3,3)}${y?p:')'} `).join(s[3])).join`
`
```
[Try it online!](https://tio.run/##bZDRboJAEEXf/Qqjhp2FWXRBRUkX@we@NgFdqNVGYxkitpGI/jpdbZ9aZ15ucm/Ozcwu@8rK1WFbHEVOb@tmo5pMRbHEAXoL9yMroFJRdhe5ikpVWd6MEc2FAM2FmBOxMG2b6Z0LxaAtWFzZuQhmVegtLr1zh9qktUZEIlJKOY7T7Xbtq22mrmvdDzjnAHA6nZ61BtDRyxOz0@VyyWtIkrpvWVbHLT9fy@MBDNn20eeGW82KkHF2uVWn3N3RNocy9hf8R6ettFlRXtJ@7e7pHTZgTvLQxyGOTKb1z7vvX4clOXuQ/eXgGIMHrAlOUQ5QGp6H0kc5fFQ4QjlGGaCcoJyiZ759a2@@AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // given the input array a[]
[1, 0, 2].map(y => // for each row y:
a.map(n => // for each integer n in a[]:
s = // let s be the content of this row
y & 2 ? // if this is the 3rd row:
'ooO--(_)--Ooo' // use a hardcoded string
: // else:
` ${ // append 4 spaces
p = '( -'[ // append and save in p:
y * n - 7 ? y : 2 // '(' if y = 0 (2nd row)
] // ' ' if y = 1 and n != 7
}${ // '-' if y = 1 and n = 7
"o o___,,,ooo(...)" // append the middle pattern (NB: truncated string)
.substr(y * n * 3, 3) // which is always the eyes if y = 0
}${ //
y ? p : ')' // append p for the 1st row or ')' for the 2nd row
} ` // append 4 spaces
).join(s[3]) // join with the 4th character of s (space or hyphen)
).join`\n` // join with line-feeds
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 164 bytes
```
->a{puts a.map{|i|j="_,o=+# *| )(x ^ &"[i];(j<?!?%w{@__ ((_ >X< '*` -*~*- )|( \|/ _/7}[i%11-2]:j*3).center(14)}*""," (o o) "*k=a.size,"ooO--(_)--Ooo-"*k}
```
Zero indexed. [Try it online!](https://tio.run/##FYzbDsFAFADffcWxUnZXz2EREtryB14lVaukTVphBY1Lt369dJ4mmWRuxeFdp36NQVxei8cdYjrH19JmNveZdo3f74C0IPgL/uwAuizMogXPvWV76TzLldbAuYZg40FP7gHlVyIIy2FrB6AHsyrMHKVwFM1zORZ0TC6P5MbVRFSSMZc1V27AiEaAyZMf0z37JC4zZo3ItUBcG4P/UtVpOCSaRq00nBGpcSNqQjQaRvUP "Ruby – Try It Online")
All the difficult stuff happens on the top line.
`"_,o=+# *| )(x ^ &"` contains all the hairstyles with 3 identical characters, from which we select the `i`th character, `j`.
if `j` is not a space, the following expression returns 3 copies of the character. If it is a space, we select the correct hairstyle from between the `%w{}`. The "odd" hairstyles are numbers 6,9,13,14,15,16,18,19 and `i%11-2` gives a perfect hash to `0..7`
```
j<?!?%w{@__ ((_ >X< '*` -*~*- )|( \|/ _/7}[i%11-2]:j*3
```
All that remains is to pad to 14 spaces (centred) and print an appropriate number of middles/bottoms.
[Answer]
# Java 8, ~~273~~ ~~263~~ ~~254~~ 247 bytes
```
a->{String p="",q=p,r=p,s=" ",t="ooO--(_)--Ooo",u="(o o)",z;for(int i:a){z=i==7?"-":" ";p+=s+z+"___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&".split("(?<=\\G...)")[i]+z+s+" ";q+=s+u+s+" ";r+=t+"-";}return t.join("\n",p,q,r);}
```
-16 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##lZDLUtswFIb3PMWZk5kgRccGhUsAI2DXVWHRTWcwcVVjGIUgObZM08Tuq6dy8Asg6SzO7f8130J/6Gjx/LbLl7qu4bs2dnsAYKwvqhedF3DfpwA/fGXsK@QsdB6fQPMklLsQ4dVee5PDPVhQsNPRzXaYLhUirVRJVYhaYS@E5BU69xBFLONR9OAcUqOQOXAcaZO8uKr3AHOl@XajjFKzW4zwCgGTUqhabARmWUZEzjmllBBiNBpN/k3Cads2O5pxzhlj6/X6LssYy25@Xh9Ofs3nc96yNG2PxuMxxnW5NJ4hu71WafotjmOO/NE8BfFa9E6r3qkZkkooL8Ifkq4qfFNZ8PHCGcswtUglrajiSbdLPmGUze9lgDEw@XDmGd4DVPaJZI9uIPq39sV77Bofl6Hll5bZOGe2@AN7xttjkjSlEzrt@J72V1bojM5pRhd0STIUJckpyROSpyTPSJ6TnJG8IHlJ0@OvqO/vsNAddLv/)
**Explanation:**
```
a->{ // Method with integer-array parameter and String return-type
String p="",q=p,r=p, // The three rows, starting all as empty Strings
s=" ", // Temp-String of four spaces for the first and second rows
t="ooO--(_)--Ooo",// Temp-String for the third row
u="(o o)", // Temp-String for the second row
z; // Temp-String, uninitialized
for(int i:a){ // Loop over the input-array
z=i==7? // If the number is 7 (edge-case):
"-" // Set temp-String `z` to "-"
: // Else:
" "; // Set temp-String `z` to a space " "
p+= // Append to the first row:
s // Four spaces
+z // Append the temp-String `z`
+"___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&"
.split("(?<=\\G...)")[i]
// Append the correct hat based on `i`
+z // Append temp-String `z` again
+s+" "; // And append five spaces
q+= // Append to the second row:
s // Four spaces
+u // The head
+s+" "; // Five spaces
r+= // Append to the third row:
t // The hands and bodies
+"-";} // And the stitch "-"
return t.join("\n", // Return a newline-joined String, of
p,q,r);} // the three rows
```
[Answer]
# [Python 2](https://docs.python.org/2/), 204 bytes
```
i=input();l=len(i)
for l in[' '*4+' -'[x==6]+"_,o=+#**|_)(x@(>'^)\\&_,o=+#~*|/)(x_(X*^||&_,o=+#**|7)(x__<`^(/&"[x::21]+' -'[x==6]+' '*5for x in i],[' (o o) ']*l,['ooO--(_)--Ooo-']*l:print''.join(l)
```
[Try it online!](https://tio.run/##Tc3NasMwDMDx@57CpBDLjrwu6Rdkddkb5DpIHO@yUhdjhZJCBqGvntoMxnQSP4T@w894oVAti9MuDPcRxLvX/juAEy9nujHPXGg543JbcKZ4O2m9N0VmkXSxknK2AqYPOPFedF3@qw85r6Na@JT9POd/p4eE9vjVwzrP2qmuq9L8f5oqu9ScYpM5g7EbB4iRSAvjRvqIRI1SYIVSDZFKWA83F0bOX6/kAnixLO0blljhBre4wz0ezBM "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~247~~ 242 bytes
```
function(a,n=length(a)){for(i in a)cat(format(h[i],,,,"c",14+!20-i))
cat("
"," (o o) "*n,"
")
cat("ooO--(_)--Ooo"*n,sep="-")}
"*"=rep
h=readLines(,21)
___
,,,
ooo
===
+++
###
-*~*-
***
|||
_/7
)))
(((
xxx
@__
((_
>X<
'*`
^^^
)|(
\|/
&&&
```
[Try it online!](https://tio.run/##VY5RS8MwFIXfz6@IKdSbNGF2bEyKEX@AsFfBrbHUdg1oMroKBat/vaawF8/Dvdxz7uV@/dyauf3y9eCCp0p589H409BRJcR3G3pyzHlWiboaKI6fsXWv7qiieM1Vvslu1nfaCYFlg4MrzhijwIJgi7j0KrrXOIS91mSF1vsQlujSnA3XXPyAS2765owu1ur92fnmQmqdC1hrEb8hhABjDLIsQ5Ik0PJXakgpMU0T7GoHESmICOM44ileEVk8vjzgVr6hLEuIiXCYVkjTdG4pL3ZXqoOPfC3dF/nmv5Nvi0gw/wE "R – Try It Online")
Now, trying to bring R to a more manageable byte count...
Since doing character manipulations in R is so hopelessly verbose, I settled on listing all face and hairstyle patterns completely as is.
For pretty-printing the hairstyles I use `format` function with `justify="centre"`. Unfortunately, we need to use an extra padding character for `i==20` because `format` calculates padding as if the backslash was escaped, like `\\|/`.
The current version does *not* use trailing hyphen.
Edit: Credit to JayCe for -2 and Giuseppe for -3 bytes.
[Answer]
# [Red](http://www.red-lang.org), 333 319 bytes
```
func[x][h: copy[]i: 0
foreach[k l m]{___,,,ooo===+++### ***|||_/7)))(((xxx@__((_>X<'*`^^^^^^)|(\|/&&&}[alter h
pad pad/left either 7 = i: i + 1["-*~*-"][rejoin[" "k l m" "]]9
14]foreach y x[prin h/(y)]print append/dup copy"^/"{ (o o) }l: length? x
print take/part append/dup copy""{ooO--(_)--Ooo-}l 14 * l - 1]
```
[Try it online!](https://tio.run/##ZU/RaoNAEHz3K4YLpKfmuJimhEht@weBPhUul6vEs9pY7xADhpj@ur3YvJTusuww7OzONjobXnUmpJfHQ36s96KTooixN/YkZBlj7uWm0em@EAdU@JJnpdRsNjPGJEkShuFkMgEQBEHf94qvfN@nlHZd96IUperp7fEueN@N4fd02/PpdHoRadXqBoVn0wyueKXzFrpsC8eukMDdLREiEoQF3wEjUjT605S1ICCjDdelXHvRUt7c4YRO2KasUXB68uUVtkit1XXGs6MdHyI7Ts7OLaiB8a8AlypGpeuPtnhG5/2q2vSguU2b/3pyNmbDGFU@Yxtj2KVCtETgHDFEcsghIowpb6sI8UZygXss8fCXXiNyowtEayzmWMnhBw "Red – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 163 bytes
```
->a{puts a.map{|i|(i==6?"-*~*-":i<9?"_,o=+#~*|"[i]*3:"_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&"[3*i-27,3]).center 14}*""," (o o) "*k=a.size,"ooO--(_)--Ooo-"*k}
```
[Try it online!](https://tio.run/##PY7NDsFAFEb3nmJyJXVn9F6qoiEGb2ArqXaUtMlEGPGTFMOrFxvf6pyczXe@be9NpRuaFc/T7XoRBR@K09Nbj1br0RxIvRXBxE7HczCh0932W3lIbabiCZheIqVExLquF8Ygmtlq2lGbPM@lx/Xa94IggDRWlgZJGGeSd@XxWp5FNHwpgBDEd@iEkz8QoPa64It9lCE4tyRCI4mWztG3vJoq7TOPstbvZ6tKE@Yo/ls0ZB70s@YD "Ruby – Try It Online")
0-indexed. I fiddled with Level River St's [answer](https://codegolf.stackexchange.com/a/164572/78274) and found another approach to encode the hairstyles, apparently of similar golfiness. Here, we treat the "longest" 5-char haircut as a special case, trivial patterns in the first part of the list are encoded by 1 char each, and in the second part all 3-char patterns are listed literally, no matter - are those chars distinct or not. Finally comes the monkey-face boilerplate.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~210~~ 212 bytes
-4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). (It grew again when I fixed a bug that the original code had.)
Pretty straight-forward.
```
#define r(s)for(i=!puts("");i<n;printf(s,c,"___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*`^^^)|(\\|/&&&"+x*3,c=x^6?32:45,x=l[i++]));
x,c,i;f(l,n)int*l;{r("%5c%.3s%-6c")r(" (o o) ")r("ooO--(_)--Ooo-")}
```
[Try it online!](https://tio.run/##bZDdboJAEIWv5Sm2EO0sHKoLAlqk7Rt420Rl21BpSCxrgCYkYl@drib971zNmS9z5idzn7Os762nbV6UW1ZRzXNVUZFc7F@bmkyTx8WijPdVUTY51chgSikBKKWSJHEcx7Is@83W0XWdHEeccyJq2/ZOSiJ5c7@4tB/SNOUdrdfdeDQamU5r@8iSNg1vfe96GqBNdqvCcTacx0arRxRxTjuUXM@0d/GhInMYZMMrvx66YWZyrZkOUkzxU8LOJaWWrkuSu@5SKdfkx163s5fHoiRuHIzBSTXbuhGrDUvYYQIBDz6mx/iLeb8YAoSIMMMcQhcFhAfhQ0whAogQIoKYQczhTb7b@H9tghM3BjmdVwAL9KmDzxd/AA/ME/8SHyz6CY79Ow "C (gcc) – Try It Online")
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 313 bytes
```
B6?>8b2*B0il2)?\B" "9a2*
{" ___ "D
{" ,,, "D
{" ooo "D
{" === "D
{" +++ "D
{" ### "D
{"-*~*-"D
{" *** "D
{" ||| "D
{" _/7 "D
{" ))) "D
{" ((( "D
{" xxx "D
{" @__ "D
{" ((_ "D
{" >X< "D
{" '*` "D
{" ^^^ "D
{" )|( "D
{" \|/ "D\
{" &&& "D{
{" " LLRB͍!{
"-(_)--Ooo-"{*@\~4-:l͍e,:{$ak$" (o o) "{*$ak$"ooO-"
```
[Try it online!](https://tio.run/##Pc7NasJAEAfwu08xbiTuTrJoYmtVjErwKAiePIRsbelBlA4IQmAX38BH85liEifO6cd8/JnL9f/4W5bpeLmY/MSYDo/nWC2zVICYHmLsWAHGGBDrWmEYsoiIlSQJKwgClud5L2m8oX71EJGnzjmWGXyxlFIsKSWrKArW6v2BlK0W@zmrj9@sPM/bPNemZG5QKavp@35FW7MqAZvNLn3cu7YjtDRK6y2RFhZX2e1Dz86P@184s73DqdesSwJS0BxabLpEWy3KMoogimEE0ecT "Runic Enchantments – Try It Online")
Reasonably compact in terms of compressing the strings and re-using segments where possible as well as using the input values as direct jump offsets when `B`ranching.
If excess trailing space is allowed, this can be shortened by 2 bytes by omitting the `4-` on the last line. +2 bytes for a `1-` if the final `-` is intended to not be there (matching spec, violating examples).
The chunk, `" (o o) "` is annoying impossible to compress, as constructing it using things like `" "4*` ends up being exactly the same number of bytes.
Passing inputs >21 do fun things. E.g. [a single 22 gives a close shave](https://tio.run/##Pc5LCsIwEAbgvaeIqdRk2qAE8VGsSnEpCK5clMYHLsTigCAUEryBR/NMta1TZ/Uxj595PO/Xc1km4@VietKQDK@5lss04YzPjho6ljNjDOPrWmEYkhCRFMcxKQgCkud5Pyl4gfr1AICmzjmSGUxIUkqSEIJUFAVp9f9AiFaL/ZzUhwMpy7I2z7UpqRtUSmv6vl/R1qyKs81ml3zeXdvhShip1BZRcQur9DVSUf55X8LI9o63XrMukKFkzaGFpou4Vbwstf4C).
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~187~~ 171 bytes
-16 bytes thanks to mazzy
```
''+($args|%{($x=' '*4)+($y=' -'[$_-eq6])+("___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*``^^^)|(\|/&&&"|% s*g($_*3)3)+$y+$x;$z++})
"$x(o o)$x "*$z
"ooO--(_)--Ooo-"*$z
```
[Try it online!](https://tio.run/##PclBTsMwEIXhfU4xcqbx2I7VTpImrSCIG3SLBMRlkZZFJUOzwG1drh4CCOZtRt//5j/64/DaHw4j7trLKKUhfDnuhzi7EIZWgtSVmuw0vVY@orP9e/08iXDO5XnuvW/b1hiTpqn@1NPFGN28UUoRUQjh3jkid/dwK/V223WdivQU51mWiTiDQe8JnS5VqQyeDIYbPBtzVYnAQB68wgBC4zkR3m@sJaes3Xhvv228JhnuYAEMBZRQwRLqRIgfbGAFa@CpMXABXP4FroCXwDVwA7wCXkOx@G@/G78A "PowerShell – Try It Online")
0-indexed, has a trailing hyphen.
Unrolled:
```
''+($args|%{
($x=' '*4) + ($y=' -'[$_-eq6]) +
("___,,,ooo===+++###*~****|||_/7)))(((xxx@__((_>X<'*``^^^)|(\|/&&&"|% substring ($_*3) 3) +
"$y$x ";
$z++
})
"$x(o o) $x"*$z
"ooO--(_)--Ooo-"*$z
```
Nothing too fancy. Only the first line has some decent logic in it. It indexes into the hair string by using the `$current_entry_value*3` and scoops out that chunk by using `s`ubstrin`g`, before joining all the chunks into one big line. Ran into the issue of ` escaping the next caret, leaving me wondering why I was getting an IndexOutOfBounds error but that's fixed. Now using a much better way to combine the first line.
[195 Bytes to follow the spec of no leading/trailing hyphens](https://tio.run/##TY7dTsJAFITv@xTNcmjP2Z4Vti0tJNb4BtySqF2IKf4EuwgaF1h89drghc7cTOZLJrO1X81u/9xsNh2sq1O3Xe1WbwgtqVf70vbBD08IrorDWOaUIBz6qOI7MKp5Lx76RhhjmNlaW1VVkiSDwUB@y17eezMqiQgRnXO3xiCam8V1LJfLuq7J470fRVEk/DDcyycEIzPKKBFwABeKMwUCHNrQUghOSIRjBe3Vo/1sPyhgYe1cKTSk1NxaIeF4eRyruDsHEaxDHLPmlDPOecJFPyZ@65KnPGPdU806ZZ39IZ2znrAuWJesp6xnnI7/Ub6Yuh8 "PowerShell – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 240 bytes
```
h=[x*3for x in"_,o=+#*|)(x^&"]
for i,*l in(6,"-*~*-"),(9,"_/7"),(13,"@__","((_",">X<","'*`"),(18,")|(","\|/"):h[:i]+=l
*x,=map(int,input().split())
l=len(x)
p=print
p(*(h[i].center(13)for i in x))
p(" (o o) "*l)
p("ooO--(_)--Ooo-"*l)
```
[Try it online!](https://tio.run/##HY7dSsQwEIXv8xTDCDrJJrvWrvuHEd9gb4VujbJUGohJqBUiFF@9Jp2LmcN3ZpgTf8c@@Hqee90kUX@GARJYj0YGvboRE6f0dostK4aVwmWPdhKV@BMKuaSjRLPZF1XVEl@MQYlEpT@/PuV@J94X8yCRT5TBZdogP/XNybYr7ZhIUn99RLJ@lNbHn5H4@js6mydnTrvOU@Is6jjkDRZJUN/Ydn3t/NgN@SdfguVUkPJBJIRcFCDwIgCFW2gIZ6XIcKXOIahC5/keKniAGrbwCDvYwwGOUGVYwT8 "Python 3 – Try It Online")
]
|
[Question]
[
Piet is an interesting programming language for a number of reasons. Today we will focus on one reason: the [roll](https://twoguysarguing.wordpress.com/2010/03/15/piet-roll-command/) command. The roll command was originally from PostScript and is a powerful way to manipulate the stack.
The roll command pops the top two elements of the stack and uses them as parameters. We'll call the first value popped `turns` and the second `depth`. A turn to depth n will take the topmost element of the stack, make it the nth element in the stack, and move each of the elements above it up one. If `turns` is negative this is done in the opposite direction. That is, the nth element is moved to the top and the other elements are moved down. This is repeated `abs(turns)` times.
## Challenge
Write a program or function that takes in a stack and returns that stack after executing a roll.
### Rules
* Input and output may be in a list, array, string with a delimiter, passed in one element at a time, or any other reasonable format. Output must be in the same format as the input.
* `depth` will never be negative and will never be greater than the length of the stack.
* The input stack will always contain at least two elements.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in each language wins. As such, I will not be accepting an answer.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
### Test Cases
```
in: out:
2
4
1 3
2 4
3 1
4 2
5 5
6 6
in: out:
-2
3
1 2
2 3
3 1
in: out:
-42
0
1 1
2 2
3 3
4 4
5 5
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~64~~ 62 bytes
Edit: -2 bytes: @xnor saw something I'd thought wrong about.
`r` takes and returns a list of `Int`s.
```
r(t:d:l)|d<1=l|(x,y)<-d%l,(z,w)<-mod t d%x=w++z++y
(%)=splitAt
```
[Try it online!](https://tio.run/nexus/haskell#RYq9CoMwFEb3PIVDhYRcQ021g5ihzyEOoVdoIEZJUvzBd7fq0uk75/D12jhlXOy8fsfb11njuiB6PdLwGSbhhe80MnHl3dNYYWXZhnWu7EZnWFidYWqBrjAd2A@YxATTWU2cr5wvhKZMhdGa@Ir73kgoIAcJj2NLeLakyU650imFhPv/0JIf "Haskell – TIO Nexus")
`splitAt n l` splits a list `l` at index `n`, `mod` calculates remainder of division, `++` concatenates lists.
[Answer]
## JavaScript (ES6), ~~49~~ 47 bytes
```
(t,d,...a)=>a.splice(t=(t%d+d)%d,d-t).concat(a)
```
Edit: Saved 2 bytes thanks to @Shaggy by taking the stack elements as separate parameters. Explanation:
* When the turn is a multiple of the depth, nothing happens. The first step is therefore to calculate turn modulo depth. As JavaScript only knows how to calculate the remainder, I have to do this in two steps.
* A turn of `1` moves the top element to the `depth` element. A turn of `2` moves the top two elements, etc. However, you can also achieve this by moving the elements between turn and depth to the front. `splice` removes those elements and `concat` prepends them to the remaining elements. (I could have used an array comprehension instead as it is the same length.)
* Unlike `slice`, the second parameter to `splice` is the number of elements to remove.
[Answer]
## CJam, 31 bytes
```
)\):N@\,0a|={NW*1$1$>)\+@@<\+}*
```
Input and output are arrays on the stack, with the last element representing the top of the stack.
Stack trace:
```
e# Stack: [6 5 4 3 2 1 4 2]
) e# Take out first value: [6 5 4 3 2 1 4] 2
\ e# Swap: 2 [6 5 4 3 2 1 4]
) e# Take out first value: 2 [6 5 4 3 2 1] 4
:N e# Store in N: 2 [6 5 4 3 2 1] 4; N=4
@ e# Rotate: [6 5 4 3 2 1] 4 2
\ e# Swap: [6 5 4 3 2 1] 2 4
, e# Range: [6 5 4 3 2 1] 2 [0 1 2 3]
0 e# Push 0: [6 5 4 3 2 1] 2 [0 1 2 3] 0
a e# Wrap in array: [6 5 4 3 2 1] 2 [0 1 2 3] [0]
| e# Logical or: [6 5 4 3 2 1] 2 [0 1 2 3]
e# (This will replace an empty array with [0] to handle a special case of n=0)
= e# Get array value: [6 5 4 3 2 1] 2
{NW*1$1$>)\+@@<\+} e# Push block: [6 5 4 3 2 1] 2 {NW*1$1$>)\+@@<\+}
* e# Preform n times: [6 5 4 3 2 1]
N e# Push N: [6 5 4 3 2 1] 4
W* e# Negate: [6 5 4 3 2 1] -4
1$ e# Copy element 1 back: [6 5 4 3 2 1] -4 [6 5 4 3 2 1]
1$ e# Copy element 1 back: [6 5 4 3 2 1] -4 [6 5 4 3 2 1] -4
> e# Slice a[-4:] [6 5 4 3 2 1] -4 [4 3 2 1]
) e# Take first value: [6 5 4 3 2 1] -4 [4 3 2] 1
\ e# Swap: [6 5 4 3 2 1] -4 1 [4 3 2]
+ e# Append: [6 5 4 3 2 1] -4 [1 4 3 2]
@@ e# Rotate twice: [1 4 3 2] [6 5 4 3 2 1] -4
< e# Slice a[:-4]: [1 4 3 2] [6 5]
\ e# Swap: [6 5] [1 4 3 2]
+ e# Append: [6 5 1 4 3 2]
e# Preform the block again: [6 5 2 1 4 3]
```
[Answer]
## Mathematica, 58 50 bytes
*Edit: Thanks to Martin Ender for saving 8 bytes.*
```
Take[x={##3},#2]~RotateLeft~#~Join~Drop[x,#2]&@@#&
```
## Explanation:
Pure function which expects a list where the beginning of the list represents the top of the stack. We pass the elements of the list into the pure function `Take[x={##3},#2]~RotateLeft~#~Join~Drop[x,#2]&`. `x` is set to the sequence of elements starting with the third argument., then we rotate the first `#2` (second argument) elements of `x` to the left `#` (first argument) times, then `Join` the remaining elements of `x`.
It would save `3` bytes if we just passed the stack elements in as arguments to the function directly rather than being in a list initially, but then the input and output formats wouldn't match.
## Original solution:
```
#/.{t_,d_,x___}:>{x}~Take~d~RotateLeft~t~Join~Drop[{x},d]&
```
There's something really satisfying about this chain of infix functions. Replaces a list with first element `t`, second element `d`, and remaining elements `x` with the result of rotating the first `d` elements of `{x}` to the left `t` times and joining the remaining elements of `{x}`.
[Answer]
# Ruby, 40 bytes
```
x=->s{n,d,*s=s;s[0,d]=s[0,d].rotate n;s}
```
[Try it online!](https://tio.run/nexus/ruby#@19hq2tXXJ2nk6KjVWxbbF0cbaCTEmsLofSK8ksSS1IV8qyLa/8XKFRERxvpmOgY6hjpGANpUx2z2FgusLAuSAQsDhcxMdIxQCiNjf3/HwA "Ruby – TIO Nexus")
Takes the input as a list, returns a list. The fact that a built-in `rotate` exists which can handle both positive and negative rotations makes this trivial.
[Answer]
# Python, ~~141~~ ~~98~~ ~~87~~ 74 bytes
*11 bytes saved thanks to @Cole*
```
def f(s):*s,d,t=s;n=len(s)-d;return s*0**d or s[:n]+s[-t%d-d:]+s[n:-t%d-d]
```
Receives input as a list, where the last element is the top of the stack.
Uses the 0ⁿ trick to filter zero-depth and python's sign-adjusting modulo operator to determine the part of the list to-be-chopped.
[Answer]
# JavaScript ES6, ~~109~~ 92 bytes
```
x=>{for(i=x.shift(),i=i>0?i:-i,j=x.shift();i-->0&&j>0;)x=x.splice(j,1).concat(x);return x}
```
[Try it online!](https://tio.run/nexus/javascript-node#bYzBCgIhFEX3fUWrQeEpOk0tEu1DokWI1htkDMdAiL7dnDYD0erCOYfrdS3avHxMBHXh8x19JhRQoxEnPDKEccVMKmTMiK4bjVC0LOYR0DoygqTcxsleMylUJZefadqWd21sjsHxEG/Ek3MPA0joYdd2D4cLpZufgi3ym/yTQw9iPWhF/QA)
Receives input in the form of an array of integers.
Also has the count to arrow :P
## Explanation:
The code uses the shift function to extract the first two elements of the list.
It then gets the absolute value of the first element, which is the number of turns.
Since Javascript is zero indexed, the depth index needs to be decreased by 1.
If the depth index was 0 or 1, nothing should change, but due to the decrease, index of 0 would cause changes. Therefore exit the loop if depth index is not <=0.
The splice(a,b) function returns the sub-array of length b with starting index a from the array and leaves the original array without those elements.
When concatenated with the remainder of the original array, this is a single rotation of the array at the depth index.
By performing this operation n times, where n is the number of turns, the resulting array is the result of the roll operator.
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
lambda r:r[2:r[1]+2][r[0]:]+r[2:r[0]]+r[r[1]+2:]
```
[Try it online!](https://tio.run/nexus/python2#y7GN@Z@TmJuUkqhQZFUUbQTEhrHaRrHRRdEGsVax2hAhg1gQCyJlFfu/oCgzr0QhRyMzr6C0RENTk4ugwP9oIx0THUMdIx1jIG2qYxbLFa0L4oCFQBwTIx0DhIJYrq95@brJickZqQA "Python 2 – TIO Nexus")
[Answer]
# TI-Basic, ~~141~~ 150 bytes (noncompeting)
```
Prompt L1
L1(1→T
L1(2→D
seq(L1(C),C,3,dim(L1→L1
If TD>0
Then
For(A,1,T
L1(1→B
For(C,2,D
L1(C→L1(C–1
End
B→L1(D
End
End
If TD<0
Then
For(A,1,-T
L1(D→B
For(C,D,2,-1
L1(C–1→L1(C
End
B→L1(1
End
End
L1
```
Edit: fixed case where depth is zero (+9 bytes)
TI-Basic doesn't support 0-length lists, so this approach won't work for a two-length input.
Explanation:
```
Prompt L1 # 4 bytes, input list
L1(1→T # 7 bytes, turns
L1(2→D # 7 bytes, depth
seq(L1(C),C,3,dim(L1→L1 # 18 bytes, remove turns and depth from list
If TD>0 # 6 bytes, if turns is positive and depth is nonzero (can't be negative)
Then # 2 bytes
For(A,1,T # 7 bytes, do this 'turns' times
L1(1→B # 7 bytes, backup the first item
For(C,2,D # 7 bytes, shuffle the rest along
L1(C→L1(C–1 # 12 bytes
End # 2 bytes
B→L1(D # 7 bytes, restore the backup to where it should be
End # 2 bytes
End # 2 bytes
If TD<0 # 6 bytes, if T is negative and D is nonzero
Then # 2 bytes
For(A,1,-T # 8 bytes, do this -'turns' times
L1(D→B # 7 bytes, backup the Dth item
For(C,D,2,-1 # 10 bytes, shuffle the items the other way
L1(C–1→L1(C # 12 bytes
End # 2 bytes
B→L1(1 # 7 bytes, restore backup to where it belongs
End # 2 bytes
End # 2 bytes
L1 # 2 bytes, implicitly return
```
[Answer]
## Batch, 163 bytes
```
@set s=
@set r=
@set/ad=%2,t=(%1%%d+d)%%d
:l
@shift
@set/af=t-=1,f^^=d-=1
@if %f% lss 0 (set r=%r% %2)else set s=%s% %2
@if not "%3"=="" goto l
@echo%r%%s%
```
Takes input as command-line parameters and outputs a space-separated list. The parameters between `t` and `d` are extracted into the `r` variable so that they can be prepended to the `s` variable, which receives all of the other parameters.
]
|
[Question]
[
Create a program that computes the [hamming weight](http://en.wikipedia.org/wiki/Hamming_weight) of a string. Winner is the program with the lowest hamming weight.
Rules:
* Hamming weight for an ASCII character is defined as the total number of bits set to `1` in its binary representation.
* Assume input encoding is 7-bit ASCII, passed through whatever input mechanism is normal for your language (e.g. stdin, args, etc.)
* Output the result, as a number, to stdout or whatever default/normal output mechanism your language uses.
* It should go without saying, but you have to be able to *actually run the program, in real life,* for it to be a valid solution.
* Winner is the solution whose code has the lowest hamming weight.
* Sorry, no solutions in [whitespace](http://en.wikipedia.org/wiki/Whitespace_%28programming_language%29) for this one! Ok, you can code in whitespace now I've sorted out the rules :)
Per-character examples:
```
char | binary | weight
-----+----------+-------
a | 01100001 | 3
x | 01111000 | 4
? | 00111111 | 6
\x00 | 00000000 | 0
\x7F | 01111111 | 7
```
[Answer]
## J, weight 34
```
+/,#:a.i.
```
Usage - place the string to be measured in quotes at the end:
```
+/,#:a.i.'+/,#:a.i.'
34
```
Alternatively, taking input from the keyboard (weight 54):
```
+/,#:a.i.1!:1[1
hello
21
```
[Answer]
# J (33)
One lower than 34!
```
+/,#:3 u:
```
Heavily *inspired* by [this answer](https://codegolf.stackexchange.com/a/6243/18638), but a hamming weight of one lower.
```
+/,#:3 u:'+/,#:3 u:'
33
```
[Answer]
## [J](http://jsoftware.com), 39
```
+/,#:a.i:]
```
This is a function taking one argument. (Or replace `]` with the string directly; as Gareth notes, that brings the cost down to 34.)
```
+/,#:a.i:] 'hello world'
45
+/,#:a.i:] '+/,#:a.i:]'
39
```
[Answer]
## Python, 189
```
print sum(bin(ord(A)).count("1")for A in raw_input())
```
[Answer]
## QBasic, ~~322~~ ~~311~~ ~~286~~ 264
```
H$=COMMAND$
FOR A=1 TO LEN(H$)
B=ASC(MID$(H$,A,1))
WHILE B>0
D=D+B MOD 2
B=B\2
WEND
NEXT
?D
```
*Kind of* the right tool for the job, still sucks of course.
[Answer]
## Unary 0
You all knew it was coming. First the BrainFuck program:
```
,[[>++[>>+>+<<<-]>>>
[<<<+>>>-]>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>
[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-]
[-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>
[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<
[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<<<
[>>+<[>>+>+<<<-]>>>[<<<+>>>-]>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>
[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>
[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<
[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<<<]>>>
[>+>+<<-]>>[<<+>>-][-]+<[>[-]<<[<<->>-]<<[>>+<<-]>>>[-]]>[<<<+<[-]>>>>
[-]]<<[->>>>+<<<<]<[-<<+>>]<<],]>>>>>>>.
```
I added newlines to make it "readable" but it has a Hamming weight of 4066. It works by repeatedly getting the quotient/remainders of an input string and adding up all the remainders. Of course should you run it on itself you get: 226 (4066 % 256) (technically \xe2) so clearly it rules itself the winner.
Now we convert it to Unary and get
```
000 ... 9*google^5.9 0's ... 000
```
We use a unary implementation with NULL characters \x00 for '0' and boom, hamming weight of 0.
**Bonus question**:
For what ASCII characters `c` can you run this program on a string consisting on `N` repitions and have it output that character. (E.G. a string of 32 spaces gives a space). What values of `N` work (either an infinite number of them will work, or none will).
[Answer]
## C, weight 322 263 256
Does the hamming weight of the hamming weight count?
```
main(D,H,A)char*A,**H;{for(A=*++H;*A;A+=!(*A/=2))D+=*A%2;printf("%d",D-2);}
```
Used mostly standard golfing techniques.
A single loop calculates weight (shifting right and adding until zero) and scans the string (advances pointer when zero reached).
Assuming `D` is initialized to 2 (single parameter).
Hamming weight specific optimizations:
1. `ABDH`, with weight 2 each, used for names.
2. `*++H` preferred over `H[1]`.
[Answer]
### Golfscript ~~84~~ ~~72~~ 58
```
{2base~}%{+}*
```
*(thanks to Howard and Peter Taylor for their help)*
*Input:* the input string has to be on the stack (passed as command line argument, or simply placed on the stack).
In case you run it from the command line, make sure you use `echo -n`, otherwise the trailing newline will also be counted.
*Output:* prints the hamming weight value to the console
The program can be tested [here](http://golfscript.apphb.com/?c=OydoZWxsbyB3b3JsZCcKCnsyYmFzZX59JXsrfSo=).
[Answer]
## Perl, 80 (22 chars)
Done and done:
```
perl -0777nE 'say unpack"%32B*"'
```
Or here's an alternate version with a weight of 77 (21 chars):
```
perl -0777pE '$_=unpack"%32B*"'
```
I don't like that version as much, though, because its output omits the final newline.
To calculate the weight, I'm assuming that I'm counting characters in the usual way (excluding the `perl -e`/`-E`, but including other option characters). If for some reason people complain about this, then the best I can do without options is 90 (26 chars):
```
$/=$,,say unpack"%32B*",<>
```
Sample usage:
```
$ perl -0777nE 'say unpack"%32b*"' rickroll.txt
7071
```
Boom.
[Answer]
# Pyth - 15
**Disclaimer: This answer isn't eligible to win since Pyth is younger than this challenge.**
Uses `.B` for binary representation and counts the number of `"1"`'s.
```
/.BQ\1
```
Takes input in a string to save on `z` versus `Q`.
[Try it online here](http://pyth.herokuapp.com/?code=%2F.BQ%5C1&input=%22%2F.BQ%5C1%22&debug=1).
[Answer]
### Scala 231
```
readLine().map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum
```
Selftesting code:
```
"""readLine().map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum""".map(_.toInt.toBinaryString).flatten.map(_.toInt-48)sum
```
with selftesting modification.
[Answer]
# Java, weight ~~931~~ ~~774~~ ~~499~~ 454
I think this is the only answer at the moment with a weight over about 300.
```
class H{public static void main(String[]A){System.out.print(new java.math.BigInteger(A[0].getBytes()).bitCount());}}
```
Expects input as a command line argument.
[Answer]
# GNU `sed -r`, 467 + 1
(+1 for use of `-r` - or should that be +4?)
Outputs as a unary value per source line; to convert to a decimal total, redirect output into `| tr -d "\n" | wc -c`. Counts all printable ASCII characters (32-126), plus linefeed (10).
```
s@[a-z]@\U& @g
s@[?{}~]@ @g
s@[][/7;=>OW|^]@ @g
s@[-'+.3569:<GKMNSUVYZ\\]@ @g
s@[#%&)*,CEFIJL1248ORTX]@ @g
s@$|[!"$(ABDH0P`]@ @g
y! @!11!
```
It's hard to avoid listing all characters, but we can reduce this observing that lowercase letters have a Hamming weight of one more than the corresponding uppercase letters. We prefer newline (score 2) over semicolon (score 5) as a statement separator; we prefer `@` (score 1) or `!` (score 2) over `/` (score 5) as pattern delimiter.
Note - to get the right sets of characters, I created this table from the one in `man ascii`, sorted by weight. Just add the scores right and below to get the overall weight of each character:
```
2 4 3 5 6 7
--- ------ -
0: @ 0 P ` p |0
1: ! A 1 Q a q |
2: " B 2 R b r |1
4: $ D 4 T d t |
8: ( H 8 X h x |
3: # C 3 S c s |
5: % E 5 U e u |
6: & F 6 V f v |2
9: ) I 9 Y i y |
A: * J : Z j z |
C: , L < \ l | |
7: ´ G 7 W g w |
B: + K ; [ k { |3
D: - M = ] m } |
E: . N > ^ n ~ |
F: / O ? _ o |4
--- ------ -
1 2 3
```
This might prove useful to others.
[Answer]
# Julia 262 268
Modified version uses handy 'count\_ones' function for a saving of 6 (262)
```
show(mapreduce(x->count_ones(x),+,map(x->int(x),collect(ARGS[1]))))
```
Old version using no built in one-counting function (268)
```
show(mapreduce(x->int(x)-48,+,mapreduce(x->bits(x),*,collect(ARGS[1]))))
```
Uses command line argument for input.
[Answer]
# CJam 52 or 48
If input is not already on the stack (52)
```
q:i2fbs:s:i:+
```
If input is on stack (48)
```
:i2fbs:s:i:+
```
For example
```
"Hello World":i2fbs:s:i:+
```
[Answer]
# Julia, HW 199
```
H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))
```
With
```
A="H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))"
```
or by directly inserting the string:
```
julia> H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect("H=mapreduce;H(B->B=='1',+,H(P->bits(P),*,collect(A[:])))")))
199
```
The ungolfed version (HW 411) looks like this:
```
bitstring=mapreduce(x->bits(x),*,collect(teststring[:]))
mapreduce(checkbit->checkbit=='1',+,bitstring)
```
And for the fun of it, here is an optimized version (Hamming Weight **231**) of bakerg’s take on the problem:
```
A=mapreduce;show(A(B->int(B)-48,+,A(B->bits(B),*,collect(H[:]))))
```
with
```
H="A=mapreduce;show(A(B->int(B)-48,+,A(B->bits(B),*,collect(H[:]))))"
```
[Answer]
# HPPPL (HP Prime Programming Language), 74
```
sum(hamdist(ASC(a),0))
```
The HP Prime graphing calculator has a built-in hamdist() function. The hamming weight of each character is the same as the hamming distance from 0.
ASC(string) creates an array of the ASCII values of each character in a string.
hamdist(value,0) computes the hamming distance from 0 for each ASCII value
sum() sums up all values.
Calculating the hamming weight of its own source code:
[](https://i.stack.imgur.com/4aSY2.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), weight 17 (4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
ÇbSO
```
[Try it online](https://tio.run/##yy9OTMpM/f//cHtSsP///yGpxSUA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8PtScH@/3X@J3JVcNlzlaQWl3CFuAaHcIWAWAZc@XVcYBUA).
**Explanation:**
```
Ç # Convert the characters in the (implicit) input to their ASCII decimal values
# i.e. "Test" → [84,101,115,116]
b # Convert those values to binary
# i.e. [84,101,115,116] → ["1010100","1100101","1110011","1110100"]
S # Split it into a list of 0s and 1s (implicitly flattens)
# i.e. ["1010100","1100101","1110011","1110100"]
# → [1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,0,1,0,0]
O # Sum those (and output implicitly)
# i.e. [1,0,1,0,1,0,0,1,1,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,0,1,0,0] → 16
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 102
```
+*.ords>>.base(2).comb(~1)
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX1tLL78opdjOTi8psThVw0hTLzk/N0mjzlDzvzVXcWKlQpqGOm416prWXFxp@UUK6onqOuoVQGyvrmOgl5xRpKNgUGHuBmIpVHMpKOippekBTeOq/Q8A "Perl 6 – Try It Online")
While this isn't code golf, the shortest solution also seems to have the smallest hamming weight...
]
|
[Question]
[
[Robber's challenge](https://codegolf.stackexchange.com/q/248189/66833)
This [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge challenges the Cop to write a non-empty program that, when run, produces some non-empty output in language A, and, when reversed, produces some non-empty output in language B. The program may produce any output to STDERR when run in either language, but may not take input in any way.
The cop should provide the following information:
* The forwards program
* The output when run in language A
* The output when run backwards in language B
Robbers should attempt to find the two languages used
### Rules
* The criteria for a valid programming language are the same as those of [The Programming Language Quiz, Mark II - Cops](https://codegolf.stackexchange.com/questions/155018/the-programming-language-quiz-mark-ii-):
>
>
> + It has [an English Wikipedia article](https://en.wikipedia.org/wiki/Lists_of_programming_languages), [an esolangs article](http://esolangs.org/wiki/Language_list) or [a Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted, or is on [Try It Online!](https://tio.run/#) [or [ATO](https://ato.pxeger.com)]. Having an interpreter linked in any of these pages makes that interpreter completely legal.
> + It must satisfy our rules on [what constitutes a programming language](http://meta.codegolf.stackexchange.com/a/2073/8478).
> + It must have a free interpreter (as in beer). Free here means that anyone can use the program without having to pay to do so.
>
* Each answer must run in less than a minute on a reasonable PC.
* Different versions of a language count as the same language.
* Languages with different flags are valid. However, flags must be revealed to avoid obscure combinations.
* Cracking a submission consists of finding *any* pair of programming languages that work, not just the intended ones.
An answer is safe if it is not cracked until two months after the question is posted.
An answer can not compete one month after this challenge has been posted.
The shortest safe answer by byte count wins.
## Example cop post
```
# ??? and ???, 128 bytes
```
print(1)#.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
```
Language A expected output: `1`
Language B expected output: `v`
```
and, when cracked,
```
# Python 3 and brainfuck, 128 bytes, cracked by [<user>](<link to robbers post>)
```
print(1)#.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
```
Language A expected output: `1`
Language B expected output: `v`
<explanation>
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) and [Seriously](https://github.com/Mego/Seriously/tree/v1), 5 Bytes - [Cracked](https://codegolf.stackexchange.com/a/248298/65425) by [math junkie](https://codegolf.stackexchange.com/users/65425/math-junkie).
```
STINK
```
Language A expected output: the current date and time on the machine, in its locale formatted like so `Sun Jun 05 2022 18:41:48 GMT+0100 (British Summer Time)`.
>
> this is just the trailing K getting a JavaScript `date()`
>
>
>
Language B expected output of `KNITS`:
```
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,......................................................................................................................................................................................................000000000000000000000000000111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222333333333333333333333333333333333333333333333333333333333333444444444444444444444444444444444444444444444444444444444444555555555555555555555555555555555555555555555555555555555555666666666666666666666666666666666666666666666666666666666666777777777777777777777777777777777777777777777777777777777777888888888888888888888888888888888888888888888888888888888888999999999999999999999999999999999999999999999999999999999999GTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiikkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooopppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppprrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssstttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwy
```
..that is, in order:
\$298\$ newline characters
\$2278\$ space characters
\$198\$ `,`s
\$198\$ `.`s
\$27\$ `0`s
\$60\$ `1`s
\$60\$ `2`s
\$60\$ `3`s
\$60\$ `4`s
\$60\$ `5`s
\$60\$ `6`s
\$60\$ `7`s
\$60\$ `8`s
\$60\$ `9`s
\$1\$ `G`
\$98\$ `T`s
\$591\$ `a`s
\$595\$ `b`s
\$295\$ `d`s
\$1289\$ `e`s
\$297\$ `f`s
\$199\$ `h`s
\$98\$ `i`s
\$98\$ `k`s
\$693\$ `l`s
\$2\$ `m`s
\$591\$ `n`s
\$1091\$ `o`s
\$98\$ `p`s
\$397\$ `r`s
\$492\$ `s`s
\$893\$ `t`s
\$99\$ `u`s
\$296\$ `w`s
\$1\$ `y`
\$1\$ newline character.
>
> The `N` gets us the text of "99 Bottles of Beer", `S` then sorts the characters.
>
>
>
[Answer]
# Gol><> and ;#+, 12 bytes, cracked by [MathJunkie](https://codegolf.stackexchange.com/a/248467/65425)
```
push 72;ll-l
```
Language A expected output: `16`
Language B expected output: `-1`
You got half the intended language pair right. But not the other half.
[Answer]
# 05AB1E and Noether, 5 bytes, cracked by [Jonathan Allan](https://codegolf.stackexchange.com/a/248242/110013)
```
PLACO
```
Language A (forwards): `2483027905`
Language B (backwards): `26`
[Answer]
## Befunge-96 and befunge-97, 8 bytes, [Cracked by steffan](https://codegolf.stackexchange.com/questions/248189/two-in-one-guess-that-language-robbers/248191#248191)
```
_2h2,@#>
```
Outputs `4` going forwards and `0x00 0x02` bytes going backwards.
Well, that lasted all of five minutes :P
[Answer]
# Burlesque and Marbelous, 11 bytes, Safe
```
23 45 67 ++
```
Forward:
```
4567
23
```
Note: It outputs exactly this in the official online interpreter. But it also outputs a few more trailing characters in other interpreters, presumably because of different command line arguments for the different ways handling standard input, which is not supported in the official online interpreter. But I think I don't need to reveal the flags, because this is the only way running the official online interpreter, which is linked from the official website linked from the Esolangs page.
Backward:
```
vT2
```
Should be easy because it's obvious how it works in both languages.
[Answer]
# Pyth and Pip, 6 bytes, cracked by [whqwert](https://codegolf.stackexchange.com/a/248197/65425)
```
h+hTCG
```
Language A expected output: `156490583352162063278528710879425690470022892627113539022649734`
Language B expected output: `98.29704308057353`
[Answer]
# StupidStackLanguage and Deadfish~, 12 bytes, cracked by [math junkie](https://codegolf.stackexchange.com/a/248229/110013)
```
ioaddrsirmix
```
Language A (forwards): `-1`
Language B (backwards): `2`
[Answer]
# BRASCA and Foo (or others), 2 bytes, cracked by [jimmy23013](https://codegolf.stackexchange.com/a/248240/112857)
```
`"
```
Language A expected output: `"`
Language B expected output: ```
They both start a string with the first character and implicitly end it (no ending string character), and therefore the other character is printed.
[Answer]
# Perl 6 and x86-16 (MS-DOS COM), 41 bytes, Safe
```
say q@if-X ~h $hL~hCF)o,AF)XD`hBZQ]P ,XQ@
```
The forward program prints:
```
if-X ~h $hL~hCF)o,AF)XD`hBZQ]P ,XQ
```
Note the trailing newline.
The reverse program prints:
```
@QX, P]QZBh`DX)FA,o)FCh~Lh@QX, P]QZBh`DX)FA,o)FCh~Lh
```
One of these languages should be much easier than the other.
The forward program is fairly straightforward. `say` prints a string followed by a newline, and `q` is an operator that treats the next character as though it were a quote mark.
The reverse program is an x86-16 MS-DOS COM executable. MS-DOS programs are always loaded at 0x100, and if you disassemble it assuming that, you get the following:
```
0x100: 40 inc ax
0x101: 51 push cx
0x102: 58 pop ax
0x103: 2C 20 sub al, 0x20
0x105: 50 push ax
0x106: 5D pop bp
0x107: 51 push cx
0x108: 5A pop dx
0x109: 42 inc dx
0x10a: 68 60 44 push 0x4460
0x10d: 58 pop ax
0x10e: 29 46 41 sub word ptr [bp + 0x41], ax
0x111: 2C 6F sub al, 0x6f
0x113: 29 46 43 sub word ptr [bp + 0x43], ax
0x116: 68 7E 4C push 0x4c7e
0x119: 68 24 09 push 0x924
0x11c: 68 7E 09 push 0x97e
0x11f: 58 pop ax
0x120: 2D 66 69 sub ax, 0x6966
0x123: 40 inc ax
0x124: 71 20 jno 0x146
0x126: 79 61 jns 0x189
```
This looks like nonsense! How could it possibly output anything? I wrote the program using only printable characters, which leaves only a handful of instructions available, many of them not useful. In particular, it leaves no instructions that actually output anything. Loops aren't possible either, because loops are just jumps with negative offsets, and no negative numbers can be made from printable characters.
To get around this, the program is self-modifying: the instructions at 0x10e and 0x113 modify the instructions at 0x120 and 0x122 by subtracting off a constant. After these instructions, the modified program disassembles to:
```
0x100: 40 inc ax
0x101: 51 push cx
0x102: 58 pop ax
0x103: 2C 20 sub al, 0x20
0x105: 50 push ax
0x106: 5D pop bp
0x107: 51 push cx
0x108: 5A pop dx
0x109: 42 inc dx
0x10a: 68 60 44 push 0x4460
0x10d: 58 pop ax
0x10e: 29 46 41 sub word ptr [bp + 0x41], ax
0x111: 2C 6F sub al, 0x6f
0x113: 29 46 43 sub word ptr [bp + 0x43], ax
0x116: 68 7E 4C push 0x4c7e
0x119: 68 24 09 push 0x924
0x11c: 68 7E 09 push 0x97e
0x11f: 58 pop ax
0x120: CD 21 int 0x21
0x122: 78 FB js 0x11f
0x124: 71 20 jno 0x146
0x126: 79 61 jns 0x189
```
The first ten bytes are setting up the registers to their needed values. `cx` is initially `0x00ff` on most versions of MS DOS (including DOSBox, the free interpreter I tested it on), which is used to set `bp` to `0x00df` for addressing purporses. `dx` is set to `0x100`, the start of the string to be output later.
The next twelve bytes modify the loop as described above, using the `sub r/m16,r16` form of subtraction. The value of `bp` is critical to address the memory in the program without using unprintable characters.
The next nine bytes set up the three interrupts to be called (in reverse order). The upper byte sets the command to be run (output to stdout for 0x09 and exit for 0x4c), the lower byte is not important.
The key here is the loop `pop ax, int 0x21, js 0x11f`, which pops a value of the stack and then makes a `0x21` interrupt. Specifically, it makes the `ah=0x09` interrupt (print a `$`-terminated string starting at `dx` to stdout) twice and then the `ah=0x4c` interrupt (exit program).
Finally, the last 5 bytes `q yas` are never reached and only matter for the forward version of the program.
I tested this program with DOSBox: simply copy the program as an executable (`.COM`) file into a DOSBox folder and run it. Be careful to preserve the horizontal tab.
[Answer]
# ??? and ???, 209 bytes
```
+++++++++++++++++.++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++++++
:+++++++++++++++++++
```
Forward: 9
Backward: [
[Answer]
# MarioLANG and brainfuck, 520 bytes, cracked by [jimmy23013](https://codegolf.stackexchange.com/a/248263/65425)
```
...:+
>.>.-
-.---
-.---
-<.--
-->.+
+++-+
<<<.+
->.>+
->.-+
-----
-<.++
+++<+
-.->+
->.++
+++++
+++<-
+.++-
+>.<-
+.---
>.+++
->.<+
-<<<+
-<.>+
->..+
-.+>+
-.>.-
-.---
-.---
-<.--
-->.+
+++<+
-<<.+
->.>+
->.--
----+
-<.++
+++<+
-.->+
->.++
+++++
+++<+
-.+++
->.<+
-.---
>.+++
->.<+
-<<<+
-<.++
>>..+
-.+>+
-.>.-
-.---
-.---
-<.--
-->.+
+++<+
-<<.+
>.>>+
-.---
---<+
-.+++
++<.+
->>.+
+++++
+++++
-<.++
>.<.+
+>.-+
->.--
>]-<+
-<<<+
-<<++
->+++
+++++
>++++
>++++
+++++
+++>+
+++++
+++++
+++>+
+++++
+++++
->[++
+++++
:-++
```
Forwards: `-25`
Backwards:
```
Nobody is Awesome!!!
Nobody is Awesome!!!
Nobody is Awesome!!!
```
[Answer]
# Javascript and Bash, 193 bytes, cracked by [Komali](https://codegolf.stackexchange.com/questions/248189/two-in-one-guess-that-language-robbers/250828#250828)
```
(![]+[/“¡Ḟọ@⁼ị»/])[!+[...([])]+!+[]]+(!!!!!!![/“¡Ḟọ@⁼ị»/]+[])[+!+[]]+(![]+[])[!+[/“¡Ḟọ@⁼ị»*/]+!+[]]+(![]+[])[+!![]]//# i /''»ị⁼@ọḞ¡“{/ h {"}"/}{/ c ..]][[+][-_;};5$""3$ o3$''1$e {)(..]][[+][-_
```
Language A expected output: `lala`
Langauge B expected output: `hi`
[Answer]
Forwards:
```
"""+!|>1bab@|!+"""1110111p exit;"1" tuO
```
Backwards:
```
Out "1";tixe p1110111"""+!|@bab1>|!+"""
```
Forwards output:
```
1110111
```
Backwards output:
```
1
```
Shouldn't be too bad.
[Answer]
# TrumpScript and A Pear Tree, 4 bytes, cracked by [whqwert](https://codegolf.stackexchange.com/a/248235/65425)
Forwards:
```
+:
:+
0O
```
Backwards:
```
O0
+:
:+
```
Forwards:
```
Parsing error:
What are you doing on line 3?
```
Backwards:
```
a partridge
```
Should be quite easy...
[Answer]
# ??? and ???, 9 bytes
```
ps"x9O@"(
```
Forwards output: `9`
Backwards output: `@O9x`
]
|
[Question]
[
My PIN number is [1077](https://www.youtube.com/watch?v=Bq2F4aFOoYc), but that's too difficult to remember. I know from muscle memory that it's a digit, followed by a different digit, then followed by two of the same digit, which is different to the other two digits before it. As a pattern, we can say it is `ABCC` (where each letter represents a digit, and the same letter represents the same digit).
There are 15 possible PIN patterns. They are, along with some examples:
```
AAAA -> 5555 AAAB -> 7773 AABA -> 4484 AABB -> 3377 AABC -> 2265
ABAA -> 0300 ABAB -> 5252 ABAC -> 2325 ABBA -> 7667 ABBB -> 4888
ABBC -> 4880 ABCA -> 1041 ABCB -> 7080 ABCC -> 2600 ABCD -> 0857
```
You are to take 4 values as input representing the pattern of my PIN number. These values can be any reasonable value, such as the integers `1`, `2`, `3`, `4`, the letters `A`, `B`, `C`, `D` as strings, etc. You may choose what these values are, but please be mindful of [this](https://codegolf.meta.stackexchange.com/a/14110/66833) standard loophole when choosing values that aren't as simple as digits or characters.
You should then output all possible 4 digit combinations that fit the input pattern. You may output in any order, and in any format that clearly shows the 4 digits of each (so as integers doesn't work as you'll exclude leading zeros), and that clearly shows each combination together. One example could be outputting each digit separated by newlines and each combination separated by 3 newlines, or outputting a list of lists.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
There is a fixed set of inputs, so we can have a comprehensive set of test cases. However, the output for `ABCD` has 5040 numbers, which is rather long. [This](https://tio.run/##bVHbboQgFHyGr@ANSF1TcZ@a2KSXvzA@0Iq7tCwSxCa26bdbLko3TdWQkzMzZ0aOWdx51PW69mJAir8IRbi1fKF3EHxwNQvUoAqC13HWbvL11zcEw2iRUOIitENSo8j3dCCH3NZjhJKsfBfLRMJEsA1qN17nJ0aXACW7m@AHgRVuthq1f/n/eXcQGu6csDokbNuqiG9XbBXbKpZ77KpXx4plBcuKUO0oyyjL6K@2zmid0foKPXY@Y4i@5QzR98j@WsbZmdmF7F26XRkIluuTINWtf@Ld9fIk4w6UnBy5cEOkdgWanCWSlp@DVIocKaVpE2mXSUNR0@x@cQvJsOTGCN0TjMu3Ueo40k8r0KbyoyAw1rtkCn54fHrGrTxUaRXy6k9ogfDhHvvTf4mefChd1x8) program generates the complete I/O set. Below are just the first 25 (all 10 for `AAAA`), in lexicographic order:
```
AAAA -> 0000, 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999
AAAB -> 0001, 0002, 0003, 0004, 0005, 0006, 0007, 0008, 0009, 1110, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 2220, 2221, 2223, 2224, 2225, 2226, 2227
AABA -> 0010, 0020, 0030, 0040, 0050, 0060, 0070, 0080, 0090, 1101, 1121, 1131, 1141, 1151, 1161, 1171, 1181, 1191, 2202, 2212, 2232, 2242, 2252, 2262, 2272
AABB -> 0011, 0022, 0033, 0044, 0055, 0066, 0077, 0088, 0099, 1100, 1122, 1133, 1144, 1155, 1166, 1177, 1188, 1199, 2200, 2211, 2233, 2244, 2255, 2266, 2277
AABC -> 0012, 0013, 0014, 0015, 0016, 0017, 0018, 0019, 0021, 0023, 0024, 0025, 0026, 0027, 0028, 0029, 0031, 0032, 0034, 0035, 0036, 0037, 0038, 0039, 0041
ABAA -> 0100, 0200, 0300, 0400, 0500, 0600, 0700, 0800, 0900, 1011, 1211, 1311, 1411, 1511, 1611, 1711, 1811, 1911, 2022, 2122, 2322, 2422, 2522, 2622, 2722
ABAB -> 0101, 0202, 0303, 0404, 0505, 0606, 0707, 0808, 0909, 1010, 1212, 1313, 1414, 1515, 1616, 1717, 1818, 1919, 2020, 2121, 2323, 2424, 2525, 2626, 2727
ABAC -> 0102, 0103, 0104, 0105, 0106, 0107, 0108, 0109, 0201, 0203, 0204, 0205, 0206, 0207, 0208, 0209, 0301, 0302, 0304, 0305, 0306, 0307, 0308, 0309, 0401
ABBA -> 0110, 0220, 0330, 0440, 0550, 0660, 0770, 0880, 0990, 1001, 1221, 1331, 1441, 1551, 1661, 1771, 1881, 1991, 2002, 2112, 2332, 2442, 2552, 2662, 2772
ABBB -> 0111, 0222, 0333, 0444, 0555, 0666, 0777, 0888, 0999, 1000, 1222, 1333, 1444, 1555, 1666, 1777, 1888, 1999, 2000, 2111, 2333, 2444, 2555, 2666, 2777
ABBC -> 0112, 0113, 0114, 0115, 0116, 0117, 0118, 0119, 0221, 0223, 0224, 0225, 0226, 0227, 0228, 0229, 0331, 0332, 0334, 0335, 0336, 0337, 0338, 0339, 0441
ABCA -> 0120, 0130, 0140, 0150, 0160, 0170, 0180, 0190, 0210, 0230, 0240, 0250, 0260, 0270, 0280, 0290, 0310, 0320, 0340, 0350, 0360, 0370, 0380, 0390, 0410
ABCB -> 0121, 0131, 0141, 0151, 0161, 0171, 0181, 0191, 0212, 0232, 0242, 0252, 0262, 0272, 0282, 0292, 0313, 0323, 0343, 0353, 0363, 0373, 0383, 0393, 0414
ABCC -> 0122, 0133, 0144, 0155, 0166, 0177, 0188, 0199, 0211, 0233, 0244, 0255, 0266, 0277, 0288, 0299, 0311, 0322, 0344, 0355, 0366, 0377, 0388, 0399, 0411
ABCD -> 0123, 0124, 0125, 0126, 0127, 0128, 0129, 0132, 0134, 0135, 0136, 0137, 0138, 0139, 0142, 0143, 0145, 0146, 0147, 0148, 0149, 0152, 0153, 0154, 0156
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
⁵Œ!’³ịⱮQ
```
Times out on TIO, takes about two minutes on my machine:
```
% time python3 -m jelly eu '⁵Œ!’³ịⱮQ' "[1,2,3,1]"
[[0, 1, 2, 0], [0, 1, 3, 0], [0, 1, 4, 0], [0, 1, 5, 0], [0, 1, 6, 0], [0, 1, 7, 0], [0, 1, 8, 0], [0, 1, 9, 0], [0, 2, 1, 0], [0, 2, 3, 0], [0, 2, 4, 0], [0, 2, 5, 0], [0, 2, 6, 0], [0, 2, 7, 0], [0, 2, 8, 0], [0, 2, 9, 0], [0, 3, 1, 0], [0, 3, 2, 0], [0, 3, 4, 0], [0, 3, 5, 0], [0, 3, 6, 0], [0, 3, 7, 0], [0, 3, 8, 0], [0, 3, 9, 0], [0, 4, 1, 0], [0, 4, 2, 0], [0, 4, 3, 0], [0, 4, 5, 0], [0, 4, 6, 0], [0, 4, 7, 0], [0, 4, 8, 0], [0, 4, 9, 0], [0, 5, 1, 0], [0, 5, 2, 0], [0, 5, 3, 0], [0, 5, 4, 0], [0, 5, 6, 0], [0, 5, 7, 0], [0, 5, 8, 0], [0, 5, 9, 0], [0, 6, 1, 0], [0, 6, 2, 0], [0, 6, 3, 0], [0, 6, 4, 0], [0, 6, 5, 0], [0, 6, 7, 0], [0, 6, 8, 0], [0, 6, 9, 0], [0, 7, 1, 0], [0, 7, 2, 0], [0, 7, 3, 0], [0, 7, 4, 0], [0, 7, 5, 0], [0, 7, 6, 0], [0, 7, 8, 0], [0, 7, 9, 0], [0, 8, 1, 0], [0, 8, 2, 0], [0, 8, 3, 0], [0, 8, 4, 0], [0, 8, 5, 0], [0, 8, 6, 0], [0, 8, 7, 0], [0, 8, 9, 0], [0, 9, 1, 0], [0, 9, 2, 0], [0, 9, 3, 0], [0, 9, 4, 0], [0, 9, 5, 0], [0, 9, 6, 0], [0, 9, 7, 0], [0, 9, 8, 0], [1, 0, 2, 1], [1, 0, 3, 1], [1, 0, 4, 1], [1, 0, 5, 1], [1, 0, 6, 1], [1, 0, 7, 1], [1, 0, 8, 1], [1, 0, 9, 1], [1, 2, 0, 1], [1, 2, 3, 1], [1, 2, 4, 1], [1, 2, 5, 1], [1, 2, 6, 1], [1, 2, 7, 1], [1, 2, 8, 1], [1, 2, 9, 1], [1, 3, 0, 1], [1, 3, 2, 1], [1, 3, 4, 1], [1, 3, 5, 1], [1, 3, 6, 1], [1, 3, 7, 1], [1, 3, 8, 1], [1, 3, 9, 1], [1, 4, 0, 1], [1, 4, 2, 1], [1, 4, 3, 1], [1, 4, 5, 1], [1, 4, 6, 1], [1, 4, 7, 1], [1, 4, 8, 1], [1, 4, 9, 1], [1, 5, 0, 1], [1, 5, 2, 1], [1, 5, 3, 1], [1, 5, 4, 1], [1, 5, 6, 1], [1, 5, 7, 1], [1, 5, 8, 1], [1, 5, 9, 1], [1, 6, 0, 1], [1, 6, 2, 1], [1, 6, 3, 1], [1, 6, 4, 1], [1, 6, 5, 1], [1, 6, 7, 1], [1, 6, 8, 1], [1, 6, 9, 1], [1, 7, 0, 1], [1, 7, 2, 1], [1, 7, 3, 1], [1, 7, 4, 1], [1, 7, 5, 1], [1, 7, 6, 1], [1, 7, 8, 1], [1, 7, 9, 1], [1, 8, 0, 1], [1, 8, 2, 1], [1, 8, 3, 1], [1, 8, 4, 1], [1, 8, 5, 1], [1, 8, 6, 1], [1, 8, 7, 1], [1, 8, 9, 1], [1, 9, 0, 1], [1, 9, 2, 1], [1, 9, 3, 1], [1, 9, 4, 1], [1, 9, 5, 1], [1, 9, 6, 1], [1, 9, 7, 1], [1, 9, 8, 1], [2, 0, 1, 2], [2, 0, 3, 2], [2, 0, 4, 2], [2, 0, 5, 2], [2, 0, 6, 2], [2, 0, 7, 2], [2, 0, 8, 2], [2, 0, 9, 2], [2, 1, 0, 2], [2, 1, 3, 2], [2, 1, 4, 2], [2, 1, 5, 2], [2, 1, 6, 2], [2, 1, 7, 2], [2, 1, 8, 2], [2, 1, 9, 2], [2, 3, 0, 2], [2, 3, 1, 2], [2, 3, 4, 2], [2, 3, 5, 2], [2, 3, 6, 2], [2, 3, 7, 2], [2, 3, 8, 2], [2, 3, 9, 2], [2, 4, 0, 2], [2, 4, 1, 2], [2, 4, 3, 2], [2, 4, 5, 2], [2, 4, 6, 2], [2, 4, 7, 2], [2, 4, 8, 2], [2, 4, 9, 2], [2, 5, 0, 2], [2, 5, 1, 2], [2, 5, 3, 2], [2, 5, 4, 2], [2, 5, 6, 2], [2, 5, 7, 2], [2, 5, 8, 2], [2, 5, 9, 2], [2, 6, 0, 2], [2, 6, 1, 2], [2, 6, 3, 2], [2, 6, 4, 2], [2, 6, 5, 2], [2, 6, 7, 2], [2, 6, 8, 2], [2, 6, 9, 2], [2, 7, 0, 2], [2, 7, 1, 2], [2, 7, 3, 2], [2, 7, 4, 2], [2, 7, 5, 2], [2, 7, 6, 2], [2, 7, 8, 2], [2, 7, 9, 2], [2, 8, 0, 2], [2, 8, 1, 2], [2, 8, 3, 2], [2, 8, 4, 2], [2, 8, 5, 2], [2, 8, 6, 2], [2, 8, 7, 2], [2, 8, 9, 2], [2, 9, 0, 2], [2, 9, 1, 2], [2, 9, 3, 2], [2, 9, 4, 2], [2, 9, 5, 2], [2, 9, 6, 2], [2, 9, 7, 2], [2, 9, 8, 2], [3, 0, 1, 3], [3, 0, 2, 3], [3, 0, 4, 3], [3, 0, 5, 3], [3, 0, 6, 3], [3, 0, 7, 3], [3, 0, 8, 3], [3, 0, 9, 3], [3, 1, 0, 3], [3, 1, 2, 3], [3, 1, 4, 3], [3, 1, 5, 3], [3, 1, 6, 3], [3, 1, 7, 3], [3, 1, 8, 3], [3, 1, 9, 3], [3, 2, 0, 3], [3, 2, 1, 3], [3, 2, 4, 3], [3, 2, 5, 3], [3, 2, 6, 3], [3, 2, 7, 3], [3, 2, 8, 3], [3, 2, 9, 3], [3, 4, 0, 3], [3, 4, 1, 3], [3, 4, 2, 3], [3, 4, 5, 3], [3, 4, 6, 3], [3, 4, 7, 3], [3, 4, 8, 3], [3, 4, 9, 3], [3, 5, 0, 3], [3, 5, 1, 3], [3, 5, 2, 3], [3, 5, 4, 3], [3, 5, 6, 3], [3, 5, 7, 3], [3, 5, 8, 3], [3, 5, 9, 3], [3, 6, 0, 3], [3, 6, 1, 3], [3, 6, 2, 3], [3, 6, 4, 3], [3, 6, 5, 3], [3, 6, 7, 3], [3, 6, 8, 3], [3, 6, 9, 3], [3, 7, 0, 3], [3, 7, 1, 3], [3, 7, 2, 3], [3, 7, 4, 3], [3, 7, 5, 3], [3, 7, 6, 3], [3, 7, 8, 3], [3, 7, 9, 3], [3, 8, 0, 3], [3, 8, 1, 3], [3, 8, 2, 3], [3, 8, 4, 3], [3, 8, 5, 3], [3, 8, 6, 3], [3, 8, 7, 3], [3, 8, 9, 3], [3, 9, 0, 3], [3, 9, 1, 3], [3, 9, 2, 3], [3, 9, 4, 3], [3, 9, 5, 3], [3, 9, 6, 3], [3, 9, 7, 3], [3, 9, 8, 3], [4, 0, 1, 4], [4, 0, 2, 4], [4, 0, 3, 4], [4, 0, 5, 4], [4, 0, 6, 4], [4, 0, 7, 4], [4, 0, 8, 4], [4, 0, 9, 4], [4, 1, 0, 4], [4, 1, 2, 4], [4, 1, 3, 4], [4, 1, 5, 4], [4, 1, 6, 4], [4, 1, 7, 4], [4, 1, 8, 4], [4, 1, 9, 4], [4, 2, 0, 4], [4, 2, 1, 4], [4, 2, 3, 4], [4, 2, 5, 4], [4, 2, 6, 4], [4, 2, 7, 4], [4, 2, 8, 4], [4, 2, 9, 4], [4, 3, 0, 4], [4, 3, 1, 4], [4, 3, 2, 4], [4, 3, 5, 4], [4, 3, 6, 4], [4, 3, 7, 4], [4, 3, 8, 4], [4, 3, 9, 4], [4, 5, 0, 4], [4, 5, 1, 4], [4, 5, 2, 4], [4, 5, 3, 4], [4, 5, 6, 4], [4, 5, 7, 4], [4, 5, 8, 4], [4, 5, 9, 4], [4, 6, 0, 4], [4, 6, 1, 4], [4, 6, 2, 4], [4, 6, 3, 4], [4, 6, 5, 4], [4, 6, 7, 4], [4, 6, 8, 4], [4, 6, 9, 4], [4, 7, 0, 4], [4, 7, 1, 4], [4, 7, 2, 4], [4, 7, 3, 4], [4, 7, 5, 4], [4, 7, 6, 4], [4, 7, 8, 4], [4, 7, 9, 4], [4, 8, 0, 4], [4, 8, 1, 4], [4, 8, 2, 4], [4, 8, 3, 4], [4, 8, 5, 4], [4, 8, 6, 4], [4, 8, 7, 4], [4, 8, 9, 4], [4, 9, 0, 4], [4, 9, 1, 4], [4, 9, 2, 4], [4, 9, 3, 4], [4, 9, 5, 4], [4, 9, 6, 4], [4, 9, 7, 4], [4, 9, 8, 4], [5, 0, 1, 5], [5, 0, 2, 5], [5, 0, 3, 5], [5, 0, 4, 5], [5, 0, 6, 5], [5, 0, 7, 5], [5, 0, 8, 5], [5, 0, 9, 5], [5, 1, 0, 5], [5, 1, 2, 5], [5, 1, 3, 5], [5, 1, 4, 5], [5, 1, 6, 5], [5, 1, 7, 5], [5, 1, 8, 5], [5, 1, 9, 5], [5, 2, 0, 5], [5, 2, 1, 5], [5, 2, 3, 5], [5, 2, 4, 5], [5, 2, 6, 5], [5, 2, 7, 5], [5, 2, 8, 5], [5, 2, 9, 5], [5, 3, 0, 5], [5, 3, 1, 5], [5, 3, 2, 5], [5, 3, 4, 5], [5, 3, 6, 5], [5, 3, 7, 5], [5, 3, 8, 5], [5, 3, 9, 5], [5, 4, 0, 5], [5, 4, 1, 5], [5, 4, 2, 5], [5, 4, 3, 5], [5, 4, 6, 5], [5, 4, 7, 5], [5, 4, 8, 5], [5, 4, 9, 5], [5, 6, 0, 5], [5, 6, 1, 5], [5, 6, 2, 5], [5, 6, 3, 5], [5, 6, 4, 5], [5, 6, 7, 5], [5, 6, 8, 5], [5, 6, 9, 5], [5, 7, 0, 5], [5, 7, 1, 5], [5, 7, 2, 5], [5, 7, 3, 5], [5, 7, 4, 5], [5, 7, 6, 5], [5, 7, 8, 5], [5, 7, 9, 5], [5, 8, 0, 5], [5, 8, 1, 5], [5, 8, 2, 5], [5, 8, 3, 5], [5, 8, 4, 5], [5, 8, 6, 5], [5, 8, 7, 5], [5, 8, 9, 5], [5, 9, 0, 5], [5, 9, 1, 5], [5, 9, 2, 5], [5, 9, 3, 5], [5, 9, 4, 5], [5, 9, 6, 5], [5, 9, 7, 5], [5, 9, 8, 5], [6, 0, 1, 6], [6, 0, 2, 6], [6, 0, 3, 6], [6, 0, 4, 6], [6, 0, 5, 6], [6, 0, 7, 6], [6, 0, 8, 6], [6, 0, 9, 6], [6, 1, 0, 6], [6, 1, 2, 6], [6, 1, 3, 6], [6, 1, 4, 6], [6, 1, 5, 6], [6, 1, 7, 6], [6, 1, 8, 6], [6, 1, 9, 6], [6, 2, 0, 6], [6, 2, 1, 6], [6, 2, 3, 6], [6, 2, 4, 6], [6, 2, 5, 6], [6, 2, 7, 6], [6, 2, 8, 6], [6, 2, 9, 6], [6, 3, 0, 6], [6, 3, 1, 6], [6, 3, 2, 6], [6, 3, 4, 6], [6, 3, 5, 6], [6, 3, 7, 6], [6, 3, 8, 6], [6, 3, 9, 6], [6, 4, 0, 6], [6, 4, 1, 6], [6, 4, 2, 6], [6, 4, 3, 6], [6, 4, 5, 6], [6, 4, 7, 6], [6, 4, 8, 6], [6, 4, 9, 6], [6, 5, 0, 6], [6, 5, 1, 6], [6, 5, 2, 6], [6, 5, 3, 6], [6, 5, 4, 6], [6, 5, 7, 6], [6, 5, 8, 6], [6, 5, 9, 6], [6, 7, 0, 6], [6, 7, 1, 6], [6, 7, 2, 6], [6, 7, 3, 6], [6, 7, 4, 6], [6, 7, 5, 6], [6, 7, 8, 6], [6, 7, 9, 6], [6, 8, 0, 6], [6, 8, 1, 6], [6, 8, 2, 6], [6, 8, 3, 6], [6, 8, 4, 6], [6, 8, 5, 6], [6, 8, 7, 6], [6, 8, 9, 6], [6, 9, 0, 6], [6, 9, 1, 6], [6, 9, 2, 6], [6, 9, 3, 6], [6, 9, 4, 6], [6, 9, 5, 6], [6, 9, 7, 6], [6, 9, 8, 6], [7, 0, 1, 7], [7, 0, 2, 7], [7, 0, 3, 7], [7, 0, 4, 7], [7, 0, 5, 7], [7, 0, 6, 7], [7, 0, 8, 7], [7, 0, 9, 7], [7, 1, 0, 7], [7, 1, 2, 7], [7, 1, 3, 7], [7, 1, 4, 7], [7, 1, 5, 7], [7, 1, 6, 7], [7, 1, 8, 7], [7, 1, 9, 7], [7, 2, 0, 7], [7, 2, 1, 7], [7, 2, 3, 7], [7, 2, 4, 7], [7, 2, 5, 7], [7, 2, 6, 7], [7, 2, 8, 7], [7, 2, 9, 7], [7, 3, 0, 7], [7, 3, 1, 7], [7, 3, 2, 7], [7, 3, 4, 7], [7, 3, 5, 7], [7, 3, 6, 7], [7, 3, 8, 7], [7, 3, 9, 7], [7, 4, 0, 7], [7, 4, 1, 7], [7, 4, 2, 7], [7, 4, 3, 7], [7, 4, 5, 7], [7, 4, 6, 7], [7, 4, 8, 7], [7, 4, 9, 7], [7, 5, 0, 7], [7, 5, 1, 7], [7, 5, 2, 7], [7, 5, 3, 7], [7, 5, 4, 7], [7, 5, 6, 7], [7, 5, 8, 7], [7, 5, 9, 7], [7, 6, 0, 7], [7, 6, 1, 7], [7, 6, 2, 7], [7, 6, 3, 7], [7, 6, 4, 7], [7, 6, 5, 7], [7, 6, 8, 7], [7, 6, 9, 7], [7, 8, 0, 7], [7, 8, 1, 7], [7, 8, 2, 7], [7, 8, 3, 7], [7, 8, 4, 7], [7, 8, 5, 7], [7, 8, 6, 7], [7, 8, 9, 7], [7, 9, 0, 7], [7, 9, 1, 7], [7, 9, 2, 7], [7, 9, 3, 7], [7, 9, 4, 7], [7, 9, 5, 7], [7, 9, 6, 7], [7, 9, 8, 7], [8, 0, 1, 8], [8, 0, 2, 8], [8, 0, 3, 8], [8, 0, 4, 8], [8, 0, 5, 8], [8, 0, 6, 8], [8, 0, 7, 8], [8, 0, 9, 8], [8, 1, 0, 8], [8, 1, 2, 8], [8, 1, 3, 8], [8, 1, 4, 8], [8, 1, 5, 8], [8, 1, 6, 8], [8, 1, 7, 8], [8, 1, 9, 8], [8, 2, 0, 8], [8, 2, 1, 8], [8, 2, 3, 8], [8, 2, 4, 8], [8, 2, 5, 8], [8, 2, 6, 8], [8, 2, 7, 8], [8, 2, 9, 8], [8, 3, 0, 8], [8, 3, 1, 8], [8, 3, 2, 8], [8, 3, 4, 8], [8, 3, 5, 8], [8, 3, 6, 8], [8, 3, 7, 8], [8, 3, 9, 8], [8, 4, 0, 8], [8, 4, 1, 8], [8, 4, 2, 8], [8, 4, 3, 8], [8, 4, 5, 8], [8, 4, 6, 8], [8, 4, 7, 8], [8, 4, 9, 8], [8, 5, 0, 8], [8, 5, 1, 8], [8, 5, 2, 8], [8, 5, 3, 8], [8, 5, 4, 8], [8, 5, 6, 8], [8, 5, 7, 8], [8, 5, 9, 8], [8, 6, 0, 8], [8, 6, 1, 8], [8, 6, 2, 8], [8, 6, 3, 8], [8, 6, 4, 8], [8, 6, 5, 8], [8, 6, 7, 8], [8, 6, 9, 8], [8, 7, 0, 8], [8, 7, 1, 8], [8, 7, 2, 8], [8, 7, 3, 8], [8, 7, 4, 8], [8, 7, 5, 8], [8, 7, 6, 8], [8, 7, 9, 8], [8, 9, 0, 8], [8, 9, 1, 8], [8, 9, 2, 8], [8, 9, 3, 8], [8, 9, 4, 8], [8, 9, 5, 8], [8, 9, 6, 8], [8, 9, 7, 8], [9, 0, 1, 9], [9, 0, 2, 9], [9, 0, 3, 9], [9, 0, 4, 9], [9, 0, 5, 9], [9, 0, 6, 9], [9, 0, 7, 9], [9, 0, 8, 9], [9, 1, 0, 9], [9, 1, 2, 9], [9, 1, 3, 9], [9, 1, 4, 9], [9, 1, 5, 9], [9, 1, 6, 9], [9, 1, 7, 9], [9, 1, 8, 9], [9, 2, 0, 9], [9, 2, 1, 9], [9, 2, 3, 9], [9, 2, 4, 9], [9, 2, 5, 9], [9, 2, 6, 9], [9, 2, 7, 9], [9, 2, 8, 9], [9, 3, 0, 9], [9, 3, 1, 9], [9, 3, 2, 9], [9, 3, 4, 9], [9, 3, 5, 9], [9, 3, 6, 9], [9, 3, 7, 9], [9, 3, 8, 9], [9, 4, 0, 9], [9, 4, 1, 9], [9, 4, 2, 9], [9, 4, 3, 9], [9, 4, 5, 9], [9, 4, 6, 9], [9, 4, 7, 9], [9, 4, 8, 9], [9, 5, 0, 9], [9, 5, 1, 9], [9, 5, 2, 9], [9, 5, 3, 9], [9, 5, 4, 9], [9, 5, 6, 9], [9, 5, 7, 9], [9, 5, 8, 9], [9, 6, 0, 9], [9, 6, 1, 9], [9, 6, 2, 9], [9, 6, 3, 9], [9, 6, 4, 9], [9, 6, 5, 9], [9, 6, 7, 9], [9, 6, 8, 9], [9, 7, 0, 9], [9, 7, 1, 9], [9, 7, 2, 9], [9, 7, 3, 9], [9, 7, 4, 9], [9, 7, 5, 9], [9, 7, 6, 9], [9, 7, 8, 9], [9, 8, 0, 9], [9, 8, 1, 9], [9, 8, 2, 9], [9, 8, 3, 9], [9, 8, 4, 9], [9, 8, 5, 9], [9, 8, 6, 9], [9, 8, 7, 9]]
108.00s user 0.90s system 99% cpu 1:49.73 total
```
Accepts a pattern in the format `[1,2,2,3]`.
```
⁵Œ!’ All permutations of [0..9].
³ịⱮ For each such permutation, use the input as index vector:
e.g. for input [1,2,2,3], turn 3862149075 into 3886.
Q Eliminate duplicates.
```
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 50 bytes
```
[ 10 iota [ nths ] with map-permutations members ]
```
[Try it online!](https://tio.run/##DYwxDsIwEAT7vGI/QOS08ABEQ4OoIgrHOuQT8dn4LooQ4u3GxVQzmqcPlmu73y7X8xFK740kkOJFVWhF8hbHkNPC4nvHQXtjilLJ7FMqi@E0DF84TB2HX5sxOXA2jxliUfHAzhb7qhwK1bSZN86iSJQWqt234NcVY/sD "Factor – Try It Online")
Port of @Lynn's [Jelly answer](https://codegolf.stackexchange.com/a/233057/97916).
* `10 iota` The digits from 0 to 9.
* `[ ... ] with` Include the input in a quotation.
* `[ nths ] map-permutations` Map the permutations of 0-9 to the indices given by the input.
* `members` Remove duplicates.
[Answer]
# [Python 3](https://docs.python.org/3/), 86 bytes
```
lambda*r:{eval('x[%d],'*4%r)for x in permutations(range(10),5)}
from itertools import*
```
[Try it online!](https://tio.run/##HYxBCoMwEADvfUUQxCTkUGt7EXyJekgxaQNmN2zWYil9eyqdOc1l0pufCF3xw1RWG@@L1dR/3MuustnHeplNo681KY8kdhFAJEdxY8sBIUuy8HCyPStzU9@TJ4wisCNGXLMIMSGxLokCsNT5CLdIL/X/HiBtLNWByS4N1QSVKmNrLofd/AM "Python 3 – Try It Online")
Fix and -3 thanks to @dingledooper
-2 thanks to @tsh
(`f()` outputs unsorted list, so footer code is added to display sorted and joined by newlines)
Very fast. Fixed time complexity of \$O(120960) = O(10P5×4)\$, it could be \$6×\$ faster if we could take input numbers decremented by 1.
[Answer]
# [J](http://jsoftware.com/), 27 24 23 bytes
```
(-:&="1#])&(>,{4$<i.10)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXSt1GyVDJVjNdU07HSqTVRsMvUMDTT/a3KlJmfkK6QpqDsCgTqEp66rq6uOJOHkhEPC0Un9PwA "J – Try It Online")
* `(>,{4$<i.10)` Generates all 10K pins.
* `-:&="1#]` Filter those by equality to the input after transforming both by ["Self Classify"](https://code.jsoftware.com/wiki/Vocabulary/eq#monadic) `=`. Self classify gives a boolean signature for each unique member of a list, thereby encoding the "mask" that we're trying to match. Eg, `= 'AABC'` returns:
```
1 1 0 0
0 0 1 0
0 0 0 1
```
### bonus
`[:~.]{"1(i.@!A.i.)@10` for [21 bytes](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63q9GKrlQw1MvUcFB31MvU0HQwN/mtypSZn5CukARWCIYSrrqurq44sY6hgiEMGKPcfAA) using [Lynn's clever approach](https://codegolf.stackexchange.com/a/233057/15469). Executes decently fast.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
9ʀṖƛ?İ;U
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=9%CA%80%E1%B9%96%C6%9B%3F%C4%B0%3BU&inputs=%5B1%2C2%2C2%2C3%5D&header=&footer=)
Will time out. (But work in theory, because taking 0..n (n<9) permutations finish properly in time)
```
9ʀṖ # 0..9 permutations
ƛ # For each
?İ # Index with input
;U # Close and remove duplicates
```
[Answer]
# [R](https://www.r-project.org/) >= 4.1 plus gtools, 41 bytes
```
\(x)gtools::permutations(10,max(x))[,x]-1
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjO9JD8/p9jKqiC1KLe0JBEkWqxhaKCTm1gBlNWM1qmI1TX8n6aRrGGoY6RjrGOsqfkfAA "R – Try It Online")
A function that takes a vector of integers and returns a matrix with the PINs in rows and the digits in columns. It would be nice to have a base R equivalent of `combn` for permutations.
Thanks to @Mark for pointing out the flaw in my previous answer which did permutations with replacement rather than without.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
Ġ⁵ṗ4¤ĠṢ⁼ɗƇ’
```
[Try it online!](https://tio.run/##y0rNyan8///IgkeNWx/unG5yaMmRBQ93LnrUuOfk9GPtjxpm/v//P9pQxwgIDWMB "Jelly – Try It Online")
Works equally well when given a list of digits (`[1, 2, 3, 4]`) or a string (`"ABCD"`).
### How it works
```
Ġ⁵ṗ4¤ĠṢ⁼ɗƇ’ Monadic link. Left arg: PIN pattern
Ġ Group indices by identical values
(which gives the pattern to filter the combinations for)
⁵ṗ4¤ĠṢ⁼ɗƇ Monad-dyad pair:
⁵ṗ4¤ Create a list of 4-digit combinations using 1-10
Ƈ Filter from the above list by:
ĠṢ⁼ɗ Is the list of sorted groups identical to the input's?
’ Decrement to get a list of 0-9 combinations
```
[Answer]
# [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 8 bytes
```
9Żṗ4Qi$Ƙ
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//OcW74bmXNFFp4rGuJOKBvMKlxof///9bMSwyLDMsMV0 "Jelly – Try It Online") (my original Jelly answer)
Didn't take long for [Lynn to outgolf](https://codegolf.stackexchange.com/a/233057/66833) my [original Jelly answer](https://tio.run/##AScA2P9qZWxsef//OcW74bmXNFFp4rGuJOKBvMKlxof///9bMSwyLDMsMV0 "Jelly – Try It Online"), so I thought I'd show my approach, using my fork because `⁼¥Ƈ` annoys me.
## How it works
```
9Żṗ4Qi$Ƙ - Main link. Takes [a,b,c,d] on the left
9Ż - Zero-range of 9; Yield [0,1,2,3,4,5,6,7,8,9]
ṗ4 - Fourth cartesian power; All length-4 lists with elements from that range
$Ƙ - Keep those elements [x,y,z,w] for which the following equals [a,b,c,d]:
Q - Unique elements
i - Their indices in [x,y,z,w]
```
In this case, `i` in my fork has been modified so that using it on flat lists is equivalent to `iⱮ`, as otherwise it outputs `0` (not found): [Try it online!](https://tio.run/##y0rNyan8/z/z////0YY6RjrGOoaxYFYsAA "Jelly – Try It Online") Additionally, `Ƙ` has been added to supplant `⁼¥Ƈ` as it gets used [a lot](https://github.com/DennisMitchell/jellylanguage/issues/91).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
9Ýœε¹è}Ù
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f8vDco5PPbT208/CK2sMz//@PNtQxAkLjWAA "05AB1E – Try It Online")
-2 Thanks to @ovs
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Input is an array of integers `1-4`. Output is an array of integer arrays. Careful running this one; even with all 4 input integers the same, it takes about 10.5 seconds to complete.
```
Ao á mgU â
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QW8g4TQgbWdVIOI&input=WzEgMSAyIDJdCi1S) (Limits the lengths of the permutations to 4)
```
Ao á mgU â :Implicit input of array U
A :10
o :Range [0,A)
á :Permutations
m :Map
gU : Get elements at 0-based indices in U
â :Deduplicate
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Ṁ⁵œ!’ị@€
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//4bmA4oG1xZMh4oCZ4buLQOKCrP///zEsMiwzLDM "Jelly – Try It Online")
Another Jelly 8-byter. This works similarly to my R answer, and completes quickly on TIO.
```
Ṁ | Max
⁵œ! | Permutations of (10, max(x))
’ | Decrease by 1
ị@€ | Index original argument into each permutation
```
[Answer]
# Google Sheets, ~~366 354 352 301 203~~ 189
Ending parens discounted.
## Setup
* Input: A1, (any format)
* A2: Cache every relevant character comparison result
```
=ArrayFormula(MID(A1,{1;2;3},1)=MID(A1,{2,3,4},1))
```
* E1:
```
=SEQUENCE(1e4,1,)
```
* Set Column E to format all 4 digits. (Custom format `0000`. We'll add +4 for this)
* F1: Split digits into columns
```
=ArrayFormula(MID(E:E,{1,2,3,4},1))
```
* J1 (result):
```
=FILTER(E:E,(F:F=G:G=A2)*(F:F=H:H=B2)*(F:F=I:I=C2)*(G:G=H:H=B3)*(G:G=I:I=C3)*(H:H=I:I=C4))
```
## Notes
* At a high level, it enumerates all possible PINs with `SEQUENCE`, then applies several filter conditions to remove unwanted result.
* Each filter condition checks PINs that either both match or both don't match in the corresponding places (`=` is like `XNOR` in that regard)
* `*` acts like and `AND`
[Answer]
# [JavaScript (V8)](https://v8.dev/), 87 bytes
Expects a pattern made of non-digit characters. Prints the results.
```
f=(s,m=/\D/.exec(s),g=n=>n--&&g(n,s.match(n)||f(s.split(m).join(n))))=>m?g(10):print(s)
```
[Try it online!](https://tio.run/##TY/RCoMgFIbv9xRejFIo2@7GwkbWnqIFRZQrSqMTMaievUkz2Lnw5//8OGiTTzkUQ92P7nTbtophcDrmvWKPlp@ywEAcwSQLpOtalsDSAdrlY/HGkixLhYFC39Yj7ghtVC011cOC7iHw9ULu/VDLUe/Y/ATZoR7b2ZP/kpvOjx7tyY3HjcdDw43Pjc8PPzI8Mjw6eGyj9EQrNTxz/WRALEAzKpQE1Za0VQJnyXmGNc2Ij/Rn9Pl/qetKti8 "JavaScript (V8) – Try It Online")
---
# JavaScript (ES10), 100 bytes
Expects a pattern made of `1`, `2`, `3`, `4`. Returns an array of strings.
```
s=>[...Array(x=1e4)].flatMap(_=>(S=`${x++}`.slice(-4)).replace(o=/./g,c=>o[c]=o[c]||++n,n=0)^s?[]:S)
```
[Try it online!](https://tio.run/##NYoxT8MwEEZ3foWHSLaV9EqcTKALYmBk6pgaYrlOSWXZkV2hojS/PZTi3HCf3tM7qW8VdRjG88b5g1l6XCI2LQC8hqB@2AVLU3MJvVXndzWyT2zYDrtsuuT53EG0gzZsU3MOwYxW3cDjFrbHQmPjWy3x712vee4Kh4/8I7608mnHl@eW0PJ2tLiv@F@RWKxc3VekTqROlMmnXqRerH2VfJV8tfqaEvkAvQ9vSn@xSLAh2rvorQHrj6xrsynOcu@yqWeRw8kPjlFC@bx3HefLLw "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript (browser), 83 bytes
```
p=>{for(i=1e5;i++<2e5;)/.(.).*\1/.test(i+=n='')?0:p[p.map(v=>n+=i[v])]??=+alert(n)}
```
```
f =
p=>{for(i=1e5;i++<2e5;)/.(.).*\1/.test(i+=n='')?0:p[p.map(v=>n+=i[v])]??=+alert(n)}
alert = s => output.textContent += s + '\n'
f([1,1,1,1])
alert('----')
f([1,1,1,2])
```
```
<output id=output style=white-space:pre></output>
```
Input an array of 4 numbers, each number in range 1 to 4, `f([1, 2, 3, 4])` for example.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
EΦEXχ⊕⌈θ⭆◧Iι⊕⌈θΣλ⬤ι⁼¹№ιλ⭆θ§ιλ
```
[Try it online!](https://tio.run/##fY49C8IwEIb/SsYLRLCuTlIUCgoFx9LhaKMGrkmTXrX/Pp4dBBfhhod7P3i7B6YuIOVcJ@cZLjjCyRHbtGIdXkLF1qjKd8kO1rPtRVncMA8QtdZGXVmS99WN/dneGEqcGJz@GxKilQ5E4Iw6xhlpgsKoMswyRF4f/ac/ipsr39vlK@9zbhqZJ7mdXNvmzZPe "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of 0-indexed digits. Explanation:
```
χ Predefined variable 10
X Raised to power
θ Input array
⌈ Maximum
⊕ Incremented
E Map over implicit range
ι Current value
I Cast to string
◧ Left padded to length
θ Input array
⌈ Maximum
⊕ Incremented
⭆ Map over characters and join
λ Current character
Σ Numeric value or 0 for space
Φ Filtered where
ι Current string
⬤ All digits satisfy
№ Count of
λ Current digit
ι In current string
⁼ Is equal to
¹ Literal `1`
E Map over strings
θ Input array
⭆ Map over values and join
ι Current string
§ Indexed by
λ Current value
Implicitly print
```
[Answer]
# [PHP](https://www.php.net/), 128 bytes
```
for(;$n<1e4;){$s=sprintf('%04d',$n++);$m='';$l=A;$v=[];for($d=0;$d<4;)$m.=$v[$g=$s[$d++]]??$v[$g]=$l++;$m==$argn&&print($s.~_);}
```
[Try it online!](https://tio.run/##HYxBCoMwFAUv82oiacWCu@9HdNFLSCiFVCtoDIm4Ke3Rm6qbWQzMuJeLZeU2drOXBFtenwWlbwQOzg926aQ45YURZ1ilUsLEQhBGrgkrt5r2DIZzgim3EFPGWFv0jNDCKKV1VR1CM0al9gHj4XubJMdfImTfe0qfGOu6aX6zW4bZhni5/QE)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
Two solutions:
```
{@LRQ.pT
{[[email protected]](/cdn-cgi/l/email-protection)
```
[Try it online!](https://tio.run/##K6gsyfj/v9rBJyhQryDk//9oAx0FQzAyiAUA "Pyth – Try It Online")
Standard method - index into permutations of `[0, 1, ..., 9]`.
[Try it online!](https://tio.run/##K6gsyfj/v9rZIShIryDk//9oAx0FQzAyiAUA "Pyth – Try It Online")
Reverse the order of indexing - generate separate lists of all 0th, 1st, etc. elements of the permutations, then transpose.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~87~~ 85 bytes
-2 thanks to @ovs
```
lambda s:[c for i in range(10000)if len({*s})==len({*zip(s,c:='%04i'%i)})==len({*c})]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaHYKjpZIS2/SCFTITNPoSgxLz1Vw9AACDQz0xRyUvM0qrWKazVtbSHMqswCjWKdZCtbdVUDk0x11UxNhFxyrWbs/4KizLwSjTQNdUcnJ2d1Tc3/0YY6RkBoHAsA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 107 bytes
```
sub{my%s;my$r;$r.=$s{$_}++?"\\$_":'((?!'.join('|',map"\\$_",1..keys%s).')\d)'for@_;grep/$r/,'0000'..'9999'}
```
[Try it online!](https://tio.run/##XZbdTiNHEIXveYpeZ8jYMDFV/TczWF4Im7tI2ZvcxRFKhNk4C7bXZrVBhNs8QB4xL0LqG8gwSiMdCc2Znq@ruo68Xe5u0lNxPX/af/714fb@cD@7vS92s2I3nRf7h@Ly8fj4bLRYFJej03I8PntTTn/frNbj8s@yuv1l@/yk0un04/J@f7ifTMvJ4mpSXm9255ezD7vl9qTYnVSl2Cqn07K1VT4@zey5u713xd1yf@fGBz@V39oq3fyt@/RljNmpLedtuWDLRVsu2XLZlqttucaWY8fJz9XzFheDLdSZeCQgEUlIRmqkQVo@1X3PIwGJSEIyUiMN0oIkSAcXkIgkJCP1fzQXgwPZBwwGCUhEEpKRGmmQFhBDNxgkIBFJSEZqpEFaGOyIBoMEJCIJyUjte5pBbZTaeGoTqE2kNonaZGpTU5uG2rTUpuuFpzaB2kRqk6hNpjY1tWmoTUtthNp0jQvUJlKbRG0ytalfa/NuQAOIAqKAKCAKiAKigFjdDbijxufxeXwen8fn8Xl8AV/oTocv4Av4Ar6AL@CL@kJzMbh6HFc4hjXKJCIJyUiNNEhLWSikclxrlElEEpKRGmmQlopQcE8hrVEmEUlIRmrve5qLAY1C46EJ0ERoEjQZmhqaBpoWGoHGQxOgidAkaDI0NTQNNC00Ao1CE6CJ0CRoMjR1T/NuQGMgCogCooAoIAqIAqIGYlt31AGJSEIyUiMN0nImRbrTRSQhGamRBmk5dt@pwUwxtMIw2iWmU8xUYqYyM1UzUw0z1TJTxIEytHaJ6RQzlZipzEzVzFTDTLXMFLHhiQO7xHSKmUrMVGam6n6mLgYzRVoJaSWklZBWQloJaSWklZBWRkOnuDyYFbNiVsyKWTErZsXsMfsuDDF7zB6zx2w0facGMwW8kGVClglZJmSZkGVClglZJlREiDEhxoQYE2LMhE4xU56ZomhCMUzoFDMVmKnATAVmKjBT8XWm3g06RZOUJilNUpqkNElpktIkbWlm11F8Hp/H5/F5fB6fxxfwha7z@AK@gC/gC/gCvqjS0ww6xZlJViFZhWQVklVIViFZhWQVJkkIVSFUhVAVQtVokAZpqQhlZoiMBklIRmqkQVquhMaeZtAprgzJKiSrkKxCsgrJKiSrkKziu/uFj1AVQlUIVaOhU/g8PoJIQncP8QV8AV/AF/AFfJZVPc13AxpAuArKVVCugnIVlKugXAUNHTAWboFyC5RboNwC5RYo9dLYnQlLxBKxRCwRC9VUSqWpO3aGZvJw4Gzd3o@L1XpbnS//2E7m592PhNnLE3duT@b2y8N9k@PxZndVuf32ZnV3clLxzgzXV45hcP/89bfTyttf6F/@sLmbf11cj9ll8rzndrda3127Ea@fusN41b04quQY94tns@Uf9@W31c2y2@UtcD1UYf/Mn38XVeUz9@szvvn6zP4bPNt8nPOuW37qfAMinrkzNzLtHo2m4@67KmdlNbWfUqdlOXGnrjw6Ovrh/Y/u/ffl8O3RYg0Tmy/WELDHYj1yq2v3xrb@n3c0O3h8@hc "Perl 5 – Try It Online")
]
|
[Question]
[
CGCC hasn't always had MathJax. Back in the dark ages, it would have been necessary to write \$x^2\$ as `x²` (the horror!). In this challenge, you will be given some math which may include superscripts, and you should convert it to MathJax.
**Input:**
Input will consist of one or more letters `a` to `z`, some with superscripts. Answers may choose to handle only upper or lower case, or both.
Examples of inputs would be `x`, `x²`, `xy²`, `x²y²`, or `x²yz`. There will never be duplicates of a letter (so `xx` or `x²zx` won't be given), but you cannot assume the superscripts or letters are in any particular order. The first character in the input will never be a superscript.
Superscripts consist of the characters `¹`, `²`, `³`, `⁴`, `⁵`, `⁶`, `⁷`, `⁸`, `⁹`, and `⁰`. These can be joined into multi-digit superscripts, like x²¹ (\$x^{21}\$). You can assume `⁰` or `¹` are never given as superscripts, and there will not be leading `⁰`s.
**Output:**
Output should consist of a MathJax representation of the input. This must start and finish with `\$`.
Characters without superscripts can be written as themselves; `xyz` would simply become `\$xyz\$`. Characters with superscripts should be followed by `^`, then the superscript written with normal digits and wrapped in `{}`. For example, `x²¹z⁴⁸⁸` would become `\$x^{21}z^{488}\$`. Optionally, single digit superscripts can be written without the `{}`. For example, `x²` could be either `\$x^{2}\$` or `\$x^2\$`.
**Test cases:**
```
x \$x\$
xyz \$xyz\$
x² \$x^{2}\$ OR \$x^2\$
x²¹ \$x^{21}\$
x²yz² \$x^{2}yz^{2}\$ OR \$x^2yz^2\$
xy¹¹z \$xy^{11}z\$
x⁴ \$x^{4}\$ OR \$x^4\$
x⁶⁰ \$x^{60}\$
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer (in bytes) per language wins!
[Answer]
# JavaScript, 55 bytes
```
e=>`\\$${e.normalize`NFKD`.replace(/\d+/g,`^{$&}`)}\\$`
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/V1i4hJkZFpTpVLy@/KDcxJ7MqNcHPzdslQa8otSAnMTlVQz8mRVs/XSchrlpFrTZBsxaoPOF/cn5ecX5Oql5OfrpGmkZCRYKmJhe6WGUVNtFDm7CLHtqJXbyyCruOykM7D@3EasOjxi3Yhbc9atwAlPkPAA)
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~43 41~~ 40 bytes
```
`JD;"¦$"ṁ?Iȯ:'^`J"{}"ṁos€"¹²³⁴⁵⁶⁷⁸⁹"Λ√ġ√
```
[Try it online!](https://tio.run/##yygtzv7/P8HLxVrp0DIVpYc7G@09T6y3Uo9L8FKqrgXx84sfNa1ROrTz0KZDmx81bnnUuPVR47ZHjdsfNe541LhT6dzsRx2zjiwEEv///684tKmy6tAmAA "Husk – Try It Online")
The superscripts are 1 byte each since they're in Husk's codepage.
I wanted to replace `+₁+₁` with `S+`+"¦$"` but it didn't work for some reason.. :(
-2 bytes borrowing the indexing idea from hyper-neutrino.
-1 byte from Leo.
## Explanation
```
`JD;"¦$"ṁ?Iȯ`:'}+"^{"ṁos€"¹..⁹"Λ√ġ√
ġ√ group on alphabets
ṁ map and concatenate with:
? if:
Λ√ the group is alphabetical
I leave as is
ȯ`:'}+"^{"ṁos€"¹..⁹" otherwise:
ṁȯ map and concat each char to:
€"¹..⁹" index in ¹..⁹(0 if not present)
s cast to string
+"^{" prepend "^{"
`:'} append '{'
`JD;"¦$" surround the final string with "\$"
```
[Answer]
# [Factor](https://factorcode.org/), ~~148~~ ~~92~~ ~~77~~ 70 bytes
```
[ nfkd R/ \d+/ [ "^{""}"surround ] re-replace-with "\\$%s\\$"sprintf ]
```
It doesn't work on TIO because TIO is missing `nfkd` which is perfectly extant in a proper copy of 0.98. So have a screenshot of running the quotation in the listener.
[](https://i.stack.imgur.com/aiEEJ.png)
## Explanation:
It's a quotation (anonymous function) that takes a string from the data stack as input and leaves a string on the data stack as output.
* `nfkd` Convert a string to normalization form KD. (Turn `"²"` into `"2"`, for example.)
* `R/ \d+/` A regular expression that matches numbers.
* `[ "^{""}"surround ] re-replace-with` Replace numbers with themselves surrounded by `^{...}`.
* `"\\$%s\\$"sprintf` Surround the result with `\\$`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~65~~ 59 bytes
```
~c{{∧"⁰¹²³⁴⁵⁶⁷⁸⁹"},?XdX&|{~h.↰₂i}ᵐtᵐcṫ,"}^{"↻↻}ᵐ{,"\$"↔}ⁱ²c
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wvy65uvpRx3KlR40bDu08tOnQ5keNWx41bn3UuO1R4/ZHjTseNe5UqtWxj0iJUKuprsvQA@tuyQTpLQHi5Ic7V@so1cZVKz1q2w1EIPFqHaUYFSB/Su2jxo2HNiX//x@tVKGko1RRWQUiD22CkId2QujKKohIJdD@nWAVQCdAKKAbNijFAgA "Brachylog – Try It Online")
:/
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~92~~ 89 bytes given that no constant(\$2x^3\$)
```
x=>`\\$${[...x].map(c=>c=='¹'?1:escape(c).slice(-1)).join``.replace(/\d+/g,'^{$&}')}\\$`
```
[Try it online!](https://tio.run/##XZBBasMwEEX3OYUXopZoI1chdJGi9AiFbqMYCUVJHBzLxKbINl7kRqWUgrc6Si7iKnZpHc9u/rz5M/yDeBeZPEVpPk30RrVb2hq65IwBUK0wxmaNjyKFki4lpb5t/BeyUJkUqYIS4SyOpIJTghA@6CjhHJ9UGgunBWxzH@we/LACd7WPamfI22c@Md5/MWAYmJiiHCpFedXs5w0WVrOaAe/1rWtmPWGbEULqflCUf@u/u0U5cnBC51LYxjbl4HpYEVJ3L1zOX6Mf5gOHeY98X84ft9DTo6O4Cy2XexiEq9BjydpFcURdkLkLUieZjhWO9Q5uYY4Qan8A "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), ~~99~~ 94 bytes
```
x=>`\\$${x.replace(/[~-⁹]+/g,s=>`^{${[...s].map(c=>c=='¹'?1:escape(c+c)[5]).join``}}`)}\\$`
```
[Try it online!](https://tio.run/##XZDRaoMwFIbv@xReBJrQNc7S7WLD7hEGuzVKQpp2LdZIlaGGDHyjMcbA2zyKL@JSHZv13J3/fOc/h//I3ljGz4c0XyZyK7qd3xX@hhICgCrwWaQx4wK6wfuyrZtw4e5vMjuOFFABxjgL8YmlkPsb7vtz08yfvAeRcZYKyBccBXchwkd5SCjVmiJtXWn3SGeF818EFATMirIaK2V10cznFRaplSbAeX7pm9VAmGaCeHoYlNXf@u9uWU0crNC7lKYxTTW6HinP0/0Lbf01@WE9clgPyHdbf1xD97eWojabnL9CNwoihySX8E6ozyu3eckkk7HAsdzDHcwRQt0P "JavaScript (Node.js) – Try It Online")
# ~~76~~ 71 bytes if allowed
```
x=>`\\$${x.replace(/[~-⁹]/g,c=>`{}^${c=='¹'?1:escape(c+c)[5]}`)}\\$`
```
[Try it online!](https://tio.run/##XY7RToMwFIbv9xRcNFmbbSDL3IWG@Qgm3lIamtqhhgEZxLQlNeGNjDEmveVReBGsYJRx7s7/f/9/zgt9pSU7PxfVJssfeX8MehEcYowBqIV75kVKGYde@LbpGhN5yZpZt9YE1CwIlq1Z3vk3vGS04JCtGAqvIx0jbeNxfxsvhPM/GAgMFkKqqSLVj9Z@XGCk3moMnPuHYdmORGtmiK9HQ6q/@G9WqlmDFYYW2ZrWqMl1Uvu@Hl7oms/ZD7tJw25Evrrm/RLaX1kqdk@0Yk/QIyFxcBatvOSErFbAKjiwPCvzlLtpnsAjrBBC/Tc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~67~~ 61 bytes
```
->s{'\$'+s.unicode\_normalize(:nfkd).gsub(/\d+/,'^{\0}')+'\$'}
```
[Try it online!](https://tio.run/##KypNqvyfpmCrEPNf1664Wj1GRV27WK80LzM5PyU1Pi@/KDcxJ7MqVcMqLy07RVMvvbg0SUM/JkVbX0c9rjrGoFZdUxukp/Z/QWlJsUJatEp8rEJ5RmZOqkJ6aknx/4rKQ5sObT6081HjhqpHjVseNW5NedS47VHj9keNOx417gQA "Ruby – Try It Online")
`unicode_normalize(:nfkd)` seems quite long, but turns out to be 4 bytes shorter than `tr('⁰¹²³⁴-⁹','0-9')`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes
```
ØJiⱮ_81»48Ọ⁾^{;;”}
O>Ø⁷Œgṁ@µ¹Çƭ€⁾\$,ṁ3
```
[Try it online!](https://tio.run/##AWsAlP9qZWxsef//w5hKaeKxrl84McK7NDjhu4zigb5eezs74oCdfQpPPsOY4oG3xZJn4bmBQMK1wrnDh8at4oKs4oG@XCQs4bmBM////2F6wrnCssKz4oG04oG14oG24oG34oG44oG54oGwYsKyYw "Jelly – Try It Online")
-4 bytes thanks to Jonathan Allan ("subtract 81, max with 48" is shorter than "logical OR 129, subtract 81") (prepend `\$` and mold like 3 is shorter than prepend `\$` + append `\$`) (2-byte built-in for 128 saves a byte)
Unfortunately I can't generate a test suite for this because `tie` will keep cycling, which causes various issues.
Might add explanation later after golfing (if I do either). TL;DR, groups by superscripts and non-superscripts, the applies the last link to every other element using tie-each, and the last link indexes into jelly's codepage, which contains ^1 through ^9, uses `or` to fix the lack of ^0 (absent items have index 0 since jelly is 1-indexed), subtract the offset, turn back to `chr`, and then apply formatting
[Answer]
# [Raku](http://raku.org/), 35 bytes
```
{'\$'~S:g/\d+/^\{$/}/~'\$'}o~*.NFKD
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wj1GRb0u2CpdPyZFWz8uplpFv1a/DiRYm1@npefn5u3y31qhOLFSQUklXsHWTqE6TUElvlZJIS2/SMGmQqGiskqh4tAmED60E0RWVoF4lYd2HtoJlHnUuAVEbHvUuMHuPwA "Perl 6 – Try It Online")
This expression is the composition of two functions with the `o` operator. The right-hand function (the first to be applied) is `~*.NFKD`, which calls the `NFKD` method on its argument, then stringifies it, which turns superscript numbers into regular numbers. The left-hand function (between the brackets) constructs the final string by prepending and appending `\$` and using a regex to replace sequences of consecutive digits with `^{digits}`.
[Answer]
# [Python 3](https://docs.python.org/3/), 169 bytes
```
def k(s):
g="¹²³⁴⁵⁶⁷⁸⁹⁰";h="\$"
for y,x in enumerate(s):
if s[y]in g:h+='^{'+x;continue
if(x not in g)and(s[y-1]in g):h+='}'
h+=x
return h+'\$'
```
[Try it online!](https://tio.run/##JYxLCsIwFEXnXcUjCEmoDsSZ0pX4gappG8SXElNIFAfZkfh32qVkIzXW2b3cc27tTKVw0mFGrDsGf8/XG9JtRQE7duDTBMqMtJ/22t7iFvwj@Gfwr@DfwX@Cv5BZlZHFgCRQKA1uaEEiCGz2QudG/B9AFnCYu2VcymmVZnR1oqmdbRQaiY3oAWYBlfnJJc9xyyI/GvcG75UzjVgMNgEtTKMxFroY0K7WEg3bMeS8@wI "Python 3 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 170 bytes
```
func[a][s: charset extract t:"⁰0¹1²2³3⁴4⁵5⁶6⁷7⁸8⁹9"2
parse a[any[any[not s skip]ahead s insert"^^{"any[change
set c s(t/:c)]insert"}"]]rejoin["\$"a"\$"]]
```
[Try it online!](https://tio.run/##RY9LTsMwEIb3PsVoxKKsKC2PkmN0a1zJchwSHo5lG6lp1YVvhAoUvPVRfJHglEJG8vgbzYz@f4ws@6UsKSNVAX31qgTljNoCRM2NlQ7k2hkuHLgCk3@bxnAZ97P4Pk/@4yr5z@vkDzfJf90m/71IPtzhjOhhEzjlqjs@1TqwYJ8azXgteZmLRllpHK5WWxwmsph6kGTQE2An7qIQ5@w0s0PGjHxsG0Xx/gz5kBjrq9ZILursTxugBHLgGk9/t/mjuB8phpG7zdjpYojhfyMfNuIh34yEUW0a5ajO3l/a5/JXdAHVEbKZHw "Red – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~245~~ 241 bytes
```
def m(a):
b='⁰¹²³⁴⁵⁶⁷⁸⁹';r=c=0;o='\\$'
for l in a:
if l in b:
n=str(b.index(l))
if not r:o+='^{'+n;r=1
elif r:o+=n
if c==len(a)-1:o+='}'
elif l not in b and r:o+='}'+l;r=0
else:o+=l
c+=1
return o+'\\$'
```
[Try it online!](https://tio.run/##LY9LagMxDIbXk1N4UZCNSUnoLsE3CYV5eOiAIwePA0lDFr5RaV6d7RzFF5nKTnbWr8@fpN3Rf1n8mKZGt2zLS7GaFZWCGH7GYfwdLzFcY7jFcI/hEcNfDAOsnarVYm0VbDZvMCta65hhHbKS/hZd@yyqVBSoeu949d5how/cCJFCQtB65lZWKvg8gURSLlNHG@rlHF9grZTRSHvNlxk/08AnZrIkTWIlNi/bGaQh2SJDvU6ZoXctk99pv3fIrMyLTzvXoedbDofx0h/p3OGbri0rEGL6Bw "Python 3 – Try It Online")
-4 bytes thanks to pxeger.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes
```
T`⁰¹²³⁴-⁹`d
\d+
{$&}
^|$
\$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyThUeOGQzsPbTq0@VHjFt1HjTsTUrhiUrS5qlXUarnialS4YlT@/6/gqqis4qo4tAmED@0EkZVVIF4lUOtOoAxQL4jYBjQMAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`⁰¹²³⁴-⁹`d
```
Convert the superscripts to digits. (The `¹²³` cost 2 bytes each and the `⁰⁴⁹` cost three bytes each.)
```
\d+
{$&}
```
Wrap the superscripts in `{}`s.
```
^|$
\$
```
Wrap the entire string in MathJax tags.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
\$F⁺S\$¿›ιz⊞υVι«∧υ⪫{}⪫υωι≔⟦⟧υ
```
[Try it online!](https://tio.run/##LYy9DoIwFIVneYqbxuE2wSdwYjBGpyaO4tBggSZNMf1BhfBSbK68WG0D2znf@XKqlpuq4yoEZqR2SMpyT@gxqzsDyJS3eNEv724urg3SHFaBgqwBz0ZwJwzKiIcEmbct@hxOPVcoafwRygoYs936Xuhnmq@d1EjGiWwxojelSd88mWJhrWw03h85@NinED7f5bfMwzKHQ6/@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
\$
```
Print the leading MathJax tag.
```
F⁺S\$
```
Append the trailing MathJax tag to the input string. This ensures that a subscript is not the last character in the loop.
```
¿›ιz
```
If the current character is greater than a `z`, then...
```
⊞υVι
```
... evaluate it as a Charcoal digit and push the result to the predefined empty list.
```
«
```
Otherwise,
```
∧υ⪫{}⪫υω
```
If there is a superscript to print, then join the digits together and wrap them in `{}`s.
```
ι
```
Output the next character.
```
≔⟦⟧υ
```
Clear any superscript.
[Answer]
# [PHP](https://php.net/), ~~75~~ 73 bytes
```
fn($a)=>preg_replace('/\d+/','^{$0}',normalizer_normalize("\\$$a\\$",8));
```
<https://3v4l.org/mJZKd>
Works with PHP 7.4+ with the intl extension, doesn't work on TIO.
8 is the value of the `Normalizer::FORM_KD` constant, so this converts superscript characters to digits using NFKD.
[Answer]
# [Zsh](https://www.zsh.org/) `--extendedglob`, ~~121 116~~ 67 bytes
*Saved **a lot** by enabling extendedglob for the `(#m)` and `##` glob specs.*
```
<<<${1//(#m)[^a-z]##/^\{${MATCH//(#m)?/$[c=#MATCH,c-185?c&15:1]}\}}
```
~~[Try it online (has old comments)](https://tio.run/##jVPLbtNAFN37K45kq7abNsJAoOQBYoPUNWJDSCp7MsEDjsfyOLSN5YX/qGrpI9t8in8k3HFelUKhlq5n5s7cc899zVS4HDuusxzLFAyOlTuq3Xa9wmW@4rAY8r5/PBu4Qd8yVcMbNHoW63QOXUXnQJ/6Jjv2TlofTHbgtdreoFMYqkc4qjHMraEqCtfodrv2N8sm7B@EHbSHpNaKpWsYY1ws5ovrxU1V/q7K26q8q8r7qnyoynlVXulrLZez@uE1Vstivll3P4I6Y3Iy4XHGRxSRYZj4REFxn4VgoZ/6LOOpsRcncgMw8VWFtoIKZZqdRVImCjLJhIzhR5E8V8hRYMQjMRGEolDDUIbIdpso2gOrbNVbDfsxSXg8QhbyHQdkslZEQmWQYwQEoLYWXwitfj5NU4oFEY@/Z6F@p7VqmpB7lookW9k7VBZXI444QU9EvLIW8YhfrDEfl26t6nTqzeHfiUryzDLE00mwz/YRg@eS1gFu2Qb/YftkY2k/WjmAUGueI55IEWcbP2ORko9dnkm9jfgfn4nFHNRbixtQE5LcktyR3JM8kMxJrtB7D5PhAF5Lb9/Bw0u8wmu08AZvcUKaF8/x9VniXDcDZz8hNEEdDhFwRJM323AcctLrgSJ3XV2ewiiok0/H2ir0f3H48SUVIViX4AgpTyKf8VWjWzziegQ2Kamzfi6oFvYwtze3dmHvDSklN5@JhIZT26jiiBzV/RCjHltKtD5Nmk@Os2G4yz8 "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQWlGSmpeSmpKek5/ElaahqfHfxsZGpdpQX19DOVczOi5RtypWWVk/LqZapdrXMcTZAyJhr68SnWyrDBbRSdY1tDC1T1YzNLUyjK2Nqa39r8nFlaZQcWjnoU2HNj9q3PKoceujxm2PGrc/atzxqHHno8YNIGkQrqwCK9ykAKEO7YTRCOI/AA "Zsh – Try It Online")
```
${1//$find/$repl} # replace all instances of $find with $repl
[^a-z]## # The glob [^a-z]## is equivalent to the regex [^a-z]+
(#m)[^a-z]## # Set $MATCH to the value matched by [^a-z]]##
(#m)? # "?" matches any single character
$[$e1,...,$en] # $[arithmetic substitution], substitutes the result of $en
c=#MATCH # Set c to the codepoint of the first character of $MATCH
c&15 # ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ⁰ => #c & 15 => 9 1 2 3 4 5 6 7 8 9 0
c-185?c&15:1 # If $MATCH is ¹ (codepoint 185), output 1, else codepoint & 15
<<<$str # prints $str to stdout
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
```
s=>`\\$${s.replace(/\W+/g,n=>`^{${n.normalize`NFKD`}}`)}\\$`
```
[Try it online!](https://tio.run/##XY6xTsMwFEX3fIUHD7EKDqkqliqdgAUJJBhYrMiW64SixK7iCCW2PPSPEEJIWfMp/ZGQJgjSvO3dd@599429M82L3b68lGoruiTqdLShhEBoNS7EPmNc@AF5WQTphewvsYVWYqmKnGU7I@jD3f0NdY4i13toVwpdcqaFBhGgXgX@h8CKQK@qzVSpzUlrP8@w2C4dgeDxaViWI9E2MyR046E2f/Zfb21mCb0wpNRt0zZm8j22YeiGCsfD16zDapKwGpHv4@HjHLq@OrWgOGclf/WDmDwvgjxFOFHFLesVCaINsB4AXEmtMoEzlfqJLxFaew6tux8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 34 bytes
```
"⁰¹²³⁴⁵⁶⁷⁸⁹"S9Ý€"^{ÿ}":„\$.ø…}^{õ:
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f6VHjhkM7D206tPlR45ZHjVsfNW571Lj9UeOOR407lYItD8991LRGKa768P5aJatHDfNiVPQO73jUsKwWKLTV6v//CrD6DQA "05AB1E – Try It Online")
## Explained:
```
"..."S # Push [⁰...⁹]
9Ý # Push [0...9]
€"^{ÿ}" # Surround each element of [0...9] with ^{ }
: # Replace each element of [⁰...⁹] with its counterpart in [^{0}...^{9}]
.ø # Surround input with...
„\$ # \$ \$
: # Replace...
…}^{ # instances of "}^{"
õ # with an empty string
```
]
|
[Question]
[
Well, everyone loves **[Polyglots](https://codegolf.stackexchange.com/tags/polyglot/info)**. You will be given two integers, in any standard form of input (no hardcoding). Your task is to write a **polyglot** which finds the minimum value in a language and the maximum value between the two numbers in the other language, and performs the following operations:
* The code which finds the maximum value must also compute their sum.
* The program which finds the minimum value must also compute the result of their subtraction (`max - min`)
* *Here is the "tricky part"*: If the two numbers are equal, both the programs must not output/ return anything (both to `STDOUT` and `STDERR` or any other `return` method)
* See the *Output specs* section for more details about formatting
---
## Input
As stated above, two integers taken as input in any **[standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)**, common to both languages.
## Output specs
* For the program which finds the `max`, the format should be: `max_value, addition result`
* For the program which finds the `min`, the format should be `min_value, subtraction result (max - min)`
* The results can be printed, with any clear delimiter (,`\n`,`,` or whatever else you want), returned from the function as a string containing the two expected values with a delimiter or as a list of numbers (e.g: `[max_value,sum]`)
---
## Examples:
```
Input || Max Language Output || Min Language Output
100, 40 || 100, 140 || 40, 60
63, 67 || 67, 130 || 63, 4
-45, -5 || -5, -50 || -45, 40
21, 21 || ||
-1, 1 || 1, 0 || -1, 2
```
---
## Scoring:
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to write the shortest code to get the desired results, while taking note that **[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** are strictly disallowed. You must use two different languages, not other versions of the same language (e.g: `Python 2`-`Python 3` pairs are not valid)
[Answer]
# C and C++ (gcc), ~~117~~ 107 bytes
*-10 bytes thanks to @Steadybox!*
```
#include<stdio.h>
int f(int a,int b){auto c=.5;a-b&&printf("%d %d",c?b<a?b:a:a>b?a:b,c?a-b>0?a-b:b-a:a+b);}
```
**Explanation:** In C, `auto c=.5` declares an integer variable with the auto storage class (which is the default), which is then initialized to 0, whereas in C++11 it declares a double, which is initialized to 0.5. So the variable's value will be truthy in C++ and falsy in C.
**C - max language:** [Try it online!](https://tio.run/nexus/c-gcc#VcxBDoMgEIXhvacgNBpIwaDRDVg9y4zUlKRFU2FlPLuFZTd/Jl9e5ro5P7@jfQ57sG6tX2PhfCALywWRi/yAGFYyP@regMSq2r7JF0ZLS0pLxTzhABNq0DDiBBqTpN2ocjXK5Hfk5rzytw84z/hRLKxRSnSKmy2GnVHKTbK2EW3zT7LrhezTeV4/ "C (gcc) – TIO Nexus")
**C++ - min language:** [Try it online!](https://tio.run/nexus/cpp-gcc#VcxBDoMgEIXhvacgNBpIwaDRDVg9y4zUlKRFU2FlPLuFZTd/Jl9e5ro5P7@jfQ57sG6tX2PhfCALywWRi/yAGFYyP@regMSq2r7JF0ZLS0pLxTzhABNq0DDiBBqTpN2ocjXK5Hfk5rzytw84z/hRLKxRSnSKmy2GnVHKTbK2EW3zT7LrhezTeV4/ "C++ (gcc) – TIO Nexus")
[Answer]
# [Python 3](https://docs.python.org/3/) / [Jelly](https://github.com/DennisMitchell/jelly), 42 bytes
Using Jelly's [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page) to encode the file.
Raw bytes:
```
6c 61 6d 62 64 61 20 78 2c 79 3a 5b 6d 61 78 28 lambda x,y:[max(
78 2c 79 29 2c 78 2b 79 5d 2a 28 78 21 3d 79 29 x,y),x+y]*(x!=y)
0a 23 7f fa 2c d3 f7 d3 cd 04 .#.ú,Ó÷ÓÍ.
```
Both define an unnamed dyadic function.
Python (the max language) sees:
```
lambda x,y:[max(x,y),x+y]*(x!=y)
#\x7fú,Ó÷ÓÍ\x04
```
[Tests as Python](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQoVNpFZ2bWKEBZGjqVGhXxmppVCjaVmpyKcdUmKcd3qVzePLh7UDcG1NhYPI/Lb9IoSS1uEQhM08hOtrQwEDHxCBWJ9rMWMfMHEjrmpjq6JoCGUaGOkaGIAFDHcPYWCsuzoKizLwSDZBWHQX1mBJ1HYU0DS0QV1PzPwA).
Jelly (the min language) sees:
```
lambda x,y:[max(x,y),x+y]*(x!=y)½#
«,ạẋạṠ¥
```
[Tests as Jelly](https://tio.run/nexus/jelly#@5@TmJuUkqhQoVNpFZ2bWKEBZGjqVGhXxmppVCjaVmoe2qvMdWi1zsNdCx/u6gaROxccWvo/OtrQwEDHxCBWJ9rMWMfMHEjrmpjq6JoCGUaGOkaGIAFDHcPY2KN7Di/Xf9S0xhuI3f8DAA).
### How?
Jelly interprets 0x0a as `½`, the square root atom while Python interprets it as a newline. In Jelly 0x7f is interpreted as a separation between links (functions) and is represented by either a newline or a pilcrow in it's codepage. For Jelly the last link is the main function - here it does not call the link above (which the interpreter does still need to parse correctly). In Python 0x23, `#` instructs that anything after it and before 0x0a, a newline, is a comment.
The Python code that gets executed:
```
lambda x,y:[max(x,y),x+y]*(x!=y)
lambda x,y: - A function taking two inputs, x and y
[ , ] - A list with two items
max(x,y) - take the maximum of x and y
x+y - x plus y
x!=y - x not equal to y?
*( ) - multiply - True is treated as if it were 1, False as if it were 0
```
The Jelly code that gets executed:
```
«,ạẋạṠ¥ - A dyadic link (function of two variables): x, y
« - minimum(x, y)
ạ - absolute difference(x, y)
, - pair left with right (creating a list)
¥ - last two links as a dyad:
ạ - absolute difference(x, y)
Ṡ - sign(result) (i.e. {0:0, +x:1, -x:-1} but -x never happens)
ẋ - repeat the list to the left right times (either the same list or an empty list)
- return the result
```
[Answer]
# Ruby / Python 3, 102 bytes
Ruby returns max/sum, Python returns min/difference. Input is an array object read from STDIN.
```
a=eval((0and gets or input()))
b=a.sort()
x,y=(b or a)
z=0 or 1
x==y or print([[y,x][z],[x+y,y-x][z]])
```
[Try it online: Ruby](https://tio.run/nexus/ruby#HcnBCsIwDIDhe58i3lKMMhHmKU8SeuhwSkG60VVJ9vLVevs//hZ5/sQX4hDzHZ5z3WApkPL6rui9dxPH87aUH5ySMU59R@92HnpdnDJbr7WkXFHESIPsgUSPRnb6I/j0AD2wtSbjlWC8hS8)
[Try it online: Python](https://tio.run/nexus/python3#HcnBCoMwDIDhe5@ixwSz4RD0lCcJPUQmQxhVah2NL9@tu/0ff1VePvoG6DU@/WvJh9@SX@N@ZkBEN7Pejy394AoZw9y2oru4b/Vwhdla7WmNGUSMSpArkJTOyG5/BKxVxoH8OIUv)
The main quirk used here is the use of the truthy `0` in Ruby, which is falsy in Python. The other thing worth mentioning is that Python's `sort` function modifies the list in-place and returns `None`, while Ruby's doesn't and returns the sorted array, hence the need to use `b or a` to get the min/max.
Python 3 is required because Python 2 complains if you try to call `print` after the `or` statement in the last line.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) / [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 bytes
-1 byte after asking for some help - thanks Emigna! (``` will `push(uwrapped(pop()))`)
Raw bytes (the dump to the right shows what my Windows machine displays):
```
60 ca 69 b9 5a 73 4f 29 71 93 18 fa 2c d3 f7 d3 `Êi¹ZsO)q..ú,Ó÷Ó
cd 04 18 2f Í../
```
Both take input from STDIN and output to STDOUT as a list representation `[x, y]`.
The max language is 05AB1E:
```
`Êi¹ZsO)q“.ú,Ó÷ÓÍ../
```
Where the `.` represent unprintable bytes in it's codepage ([cp1252](https://en.wikipedia.org/wiki/Windows-1252)), and probably here in whatever you are using (0x18=`CAN` and 0x04=`EOT`).
Try the [05AB1E version](https://tio.run/nexus/05ab1e#@59wuCvz0M6oYn/NwkcNcyQO79I5PPnwdiDuZZHQ//8/WtfEVEdB1zSWCwA)
The min language is Jelly:
```
İ__iỤZs0)qƓð«,ạẋạṠ¥ð/
```
Try the [Jelly version](https://tio.run/nexus/jelly#@59wYl3mw91LoooNNAuPTT684dBqnYe7Fj7c1Q0idy44tPTwBv3//6N1TUx1FHRNY7kA).
### How?
05AB1E:
```
`Êi¹ZsO)q“.ú,Ó÷ÓÍ../ - parsed left to right, executed as parsed
- implicit input taken
i - If:
` - push(unwrapped(pop()))
Ê - push(pop()!=pop())
- ...Then:
¹ - push(1st item from input history)
Z - push(max(top of stack))
s - push(reverse(pop(),pop()))
O - push(sum(pop()))
) - wrap(pop())
q - quit - implicit print of top of stack
“.ú,Ó÷ÓÍ../ - unexecuted and unparsed string
```
Jelly:
```
`ȮiỤZs0)qƓð«,ạẋạṠ¥ð/ - parsed left to right, not executed until parsed
`ȮiỤZs0 - a dyadic chain which would error if executed (monad from dyad, index of, grade up, transpose, split into chunks of length 0)
)q - currently unassigned code points each currently creates a new link
Ɠ - read and evaluate a line of input
ð ð - dyadic chain separations
/ - reduce by:
« - minimum(left, right)
ạ - absolute difference(left, right)
, - pair(result)
¥ - last two links as a dyad:
ạ - absolute difference(left, right)
Ṡ - sign(result) (i.e. {0:0, +x:1, -x:-1} but -x never happens)
ẋ - repeat list left right times
- implicit print
```
[Answer]
# Java/[AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~219~~ ~~217~~ ~~212~~ 196 bytes
```
/*#\/* /
{$0=((x=$1)<y=$2)?x" "y-x:y" "x-y}x!=y
#*/interface B{static void main(String[]A){Integer x=Integer.parseInt(A[0]);int y=x.parseInt(A[1]);System.out.print(x==y?"":(x<y?y:x)+" "+(x+y));}}
```
[Try it online!](https://tio.run/nexus/awk#TU67jsIwEOz9FXshhZ3IiR0eJwWsCLqrKYEiAh9yQUCJ77SrKN@e2@IKmnlpNJq5zBbnMoNSjKlxUqJLrdqRSyvVYAIJaayJGTVN@OFILLIydNH33@3Vw2EcYhvDFX6f4QaPNnTyGPvQ3U@XvRq/uHf3PaD7V8Wr7QfPRu5P5qK2PATk8D22HB9piP5RPH9i8eKxyKccNUlSS9xRQzWqnB/lEnNSajtNYp6tMbAyYrOEzafQqzXotagsVFZoRi78AQ "AWK – TIO Nexus")
Java outputs the max and sum, AWK outputs min and difference. No output for either if the inputs are identical.
This is my first polyglot and first TIO :)
[Answer]
# JavaScript (ES6)/ QBasic, ~~172~~ 171 bytes
```
'';f=x=>{m=Math.max(...x);s=Math.min(...x);if(x[0]!=x[1])alert([m,m-s])}/*
INPUT c
LET m=c
LET s=c
INPUT n
IF n>c THEN m=n
IF n<c THEN s=n
IF n<>c THEN PRINT m,m+s
END
'*/
```
Based on [this solution of mine](https://codegolf.stackexchange.com/questions/116890/plus-or-minus-polyglots/117069#117069) of a similar [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'") question.
This solution too use the comment approach!
JavaScript is the min-language. It takes in an array containing numbers as input. Outputs two numbers separated by `,` (1st number is the smallest value of the input-array and 2nd number is the difference of the greatest and the smallest values of the input-array) by `alert()`ing. Does not `alert()` anything if the numbers are equal. You can call the function like `f([100,40])`.
QBasic is the max-language. Repeatedly asks for input, twice. Prints the largest number of the input-numbers as well as the sum of largest and smallest numbers of the input. Does not `PRINT` anything if the numbers are equal.
---
## How does it work?
In QBasic (a language of structured BASIC family; it does not require line numbers), `'` marks the beginning of a comment which goes till the end of the line. Whereas in JavaScript, it marks the start of a string. So, the whole first line is marked as a comment in QBasic but in JavaScript, the line is executed (and this line contains the JavaScript part that computes the smallest number and the difference of greatest and smallest numbers, as well as a `/*` at the end which starts a comment in order to hide the rest of the QBasic code from JavaScript interpreter.)
The code from second line to second-last line contains the QBasic code to compute the greatest number and the sum of greatest and smallest number (the code is very self-explanatory).
The last line contains `'*/`. `'` causes the QBasic interpreter to interpret the following code as a comment, whereas in JavaScript, it does not have any effect as it is a part of a comment (which was started at the end of the first line). The following code (`*/`) causes JavaScript to end the comment which was started in the first line, but it is not executed in QBasic because QBasic thinks it's a part of a comment.
---
## Test Cases
**JavaScript (min-language):**
```
'';f=x=>{m=Math.max(...x);s=Math.min(...x);if(x[0]!=x[1])alert([m,m-s])}/*
INPUT c
LET m=c
LET s=c
INPUT n
IF n>c THEN m=n
IF n<c THEN s=n
IF n<>c THEN PRINT m,m+s
END
'*/
f([100,40]);
```
**QBasic (max-language):**
Go to [this website](http://yohan.es/swbasic/). Copy paste the following code in their text-editor :
```
1 '';f=x=>{m=Math.max(...x);s=Math.min(...x);if(x[0]!=x[1])alert([m,m-s])}/*
2 INPUT c
3 LET m=c
4 LET s=c
5 INPUT n
6 IF n>c THEN m=n
7 IF n<c THEN s=n
8 IF n<>c THEN PRINT m,m+s
9 END
10 '*/
```
The reason why line numbers are required is that the website I mentioned only supports unstructured BASIC languages. And that website is the only decent online BASIC interpreter I could find. However, running the code present in the top of the post (the code without line numbers) should work fine in any good QBasic interpreter that supports structured BASIC and `'` as a comment-starter (few do not, most do, though)
]
|
[Question]
[
Let's use augmented reality to hunt small creatures hidden in source-code. Write a quine program that outputs its own code source, except for 5 consecutive characters that will be modified and that will display a *PCG-mon* : `(^_^)`
The 5 consecutive characters can be positioned anywhere in the source code (from position `0` to `n-5`, `n` being the source code length). The source code must have a minimum length of 5 characters. The string `(^_^)` or any of its substring of length >=2 must not appear in initial source code, only in output.
Example of valid submission:
* source code `my source code`, output `my (^_^)e code`
Invalid:
* source code `(^_^) copy;`, output `(^_^) (^_^)`
## Winning criteria
The shortest code in bytes wins.
[Answer]
# Javascript ES6, 44 bytes
```
$=_=>`$=(\^\_\^\)${($+'').slice(5)};$()`;$()
```
Output:
```
$=(^_^)=(\^\_\^\)${($+'').slice(5)};$()`;$()
```
Still working on golfing, but it works for now.
[Answer]
# Vim, ~~33~~, 27 keystrokes
```
qqqqqS(<C-v>94_<C-v>94)q@q<esc>hh"qPq@q
```
Note that `<C-v>` means ctrl+v, and is byte `0x16` and `<esc>` is the escape character, and is byte `0x1B`.
This just uses a slightly modified version of my [Golf you a quine for great good!](https://codegolf.stackexchange.com/a/92774/31716) answer.
Outputs:
```
(^_^)S(^V94_^V94)q@q^[hh"qPq@q
```
This is valid since `^V` is the way vim represents `<C-v>` and `^[` is the way vim represents `<esc>`.
The basic idea, is just to input the text `(^_^)` by its code points so we can avoid putting those characters in the source code. In insert mode, `<C-v>number` will insert the ASCII character of "number". However, since the challenge says:
>
> The string `(^_^)` or any of its substring of length >=2 must not appear in initial source code, only in output.
>
>
>
This answer abuses the "substring" rule by only entering the codepoints of the `^` characters, and entering `(`, `_`, and `)` directly.
Here's a gif that lets you see this solution in action, and puts the source code and output side by side for comparison:
[](https://i.stack.imgur.com/CUmKB.gif)
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), ~~13~~ 11 bytes
```
"(_)"
_p'^*
```
[Online interpreter](http://cjam.aditsu.net/#code=%22(_)%22%0A_p'%5E*) *(-2 bytes thanks to @MartinEnder)*.
```
"(_)" Push string
_p Duplicate and print repr with newline
'^* Join string with '^'
```
[Answer]
# Python, ~~115~~ ~~111~~ 107 bytes
```
def f():s='def f():s=%r;print s%%s.replace(s[:5],"^".join("(_)"))';print s%s.replace(s[:5],"^".join("(_)"))
```
Call `f()` and the output is:
```
def f():s='(^_^)():s=%r;print s%%s.replace(s[:5],"^".join("(_)"))';print s%s.replace(s[:5],"^".join("(_)"))
```
Inspired in part by [this answer to a similar question](https://codegolf.stackexchange.com/a/44925).
[Answer]
## CJAM, 16 15 bytes
Try it [here](http://cjam.aditsu.net/#code=%7B%22%5E(_)%22(*%7D_~sss).
```
{"^(_)"(*}_~sss
```
[Answer]
# Go (golang), 131 bytes
This challenge must have an answer in Go!
```
package main;import"fmt";func main(){a:="package main;import\"fmt\";func(%c_%[1]c)(){a:=%q;fmt.Printf(a,94,a)}";fmt.Printf(a,94,a)}
```
[Try it online!](https://play.golang.org/p/5900Og5Etr)
[Answer]
# JavaScript (ES6), 91 bytes
There's already a JavaScript answer, but there's not a non-source-reading JS answer:
```
a="a=%s;co%s.log(a,uneval(a),`(${'^'}_${'^'})`)";console.log(a,uneval(a),`(${'^'}_${'^'})`)
```
This is based on my non-source-reading answer to [Golf you a quine for great good!](https://codegolf.stackexchange.com/a/92449/42545). Outputs
```
a="a=%s;co%s.log(a,uneval(a),`(${'^'}_${'^'})`)";co(^_^).log(a,uneval(a),`(${'^'}_${'^'})`)
```
This can easily be modified by moving around the second `%s` in the string. For example,
```
a="a=%s;console.log(a,uneval(a),`($%s_${'^'})`)";console.log(a,uneval(a),`(${'^'}_${'^'})`)
```
outputs
```
a="a=%s;console.log(a,uneval(a),`($%s_${'^'})`)";console.log(a,uneval(a),`($(^_^)_${'^'})`)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“4094959441b³ỌØV”ṘVabc
```
Available at **[TryItOnline](http://jelly.tryitonline.net/#code=4oCcNDA5NDk1OTQ0MWLCs-G7jMOYVuKAneG5mFZhYmM&input=)**
Uses the built-in [payload capable](http://meta.codegolf.stackexchange.com/a/4924/53748) quine `“ØV”ṘV`
The `abc` on the end is just filler to be replaced
`b³` converts the integer into base 100, resulting in `[40,94,95,94,41]`
`Ọ` casts to characters, resulting in `(^_^)`
So the whole result is `“4094959441b³ỌØV”(^_^)`
[Answer]
# C# 5.0, 715 bytes
I know, this is huge. Just wanted to add a C# solution.
```
/*^()_*/using System.CodeDom;namespace System{class P{static void Main(){var b="/*^()_*/using System.CodeDom;namespace System{{class P{{static void Main(){{var b={0};var f=new string(new[]{{b[3],b[2],b[5],b[2],b[4]}});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider(\"CSharp\").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace(\"[4]}}}}}}}}\",f),w);Console.ReadKey();}}}}}}";var f=new string(new[]{b[3],b[2],b[5],b[2],b[4]});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace("[4]}}}}",f),w);Console.ReadKey();}}}
```
The output is:
```
/*^()_*/using System.CodeDom;namespace System{class P{static void Main(){var b="/*^()_*/using System.CodeDom;namespace System{{class P{{static void Main(){{var b={0};var f=new string(new[]{{b[3],b[2],b[5],b[2],b[4]}});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider(\"CSharp\").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace(\"[4]}}}}}}}}\",f),w);Console.ReadKey();}}}}}}";var f=new string(new[]{b[3],b[2],b[5],b[2],b[4]});var w=new IO.StringWriter();CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp").GenerateCodeFromExpression(new CodePrimitiveExpression(b),w,null);Console.WriteLine(b.Replace("(^_^)}}",f),w);Console.ReadKey();}}}
```
Available [at Ideone.com](http://ideone.com/nj0xwb)
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
')_`_*i't&Dwqh
```
Produces the output `')_`_*i'(^_^)h`.
[Try it online!](http://matl.tryitonline.net/#code=JylfYF8qaSd0JkR3cWg&input=)
### Explanation
```
')_`_*i' % Push this string
t&D % Duplicate and get string representation (i.e. enclose with quotes)
w % Swap
q % Subtract 1. Transforms ')_`_*i' into the code points of '(^_^)h'
h % Concatenate. Automatically casts code points to chars. Implicitly display
```
[Answer]
# Bash, 178 bytes
```
Q='#(8_8)
printf "Q=\47"
echo -n "$Q"|sed -r "s~(_|\()8~\1^~g"
echo -e "\x27"
tail<<<"$Q" -n4'
printf "Q=\47"
echo -n "$Q"|sed -r "s~(_|\()8~\1^~g"
echo -e "\x27"
tail<<<"$Q" -n4
```
Pfff, I am not good at quines :/ Any suggestion to golf it more is more than welcome! :-)
]
|
[Question]
[
**Background**:
>
> You have been given an assignment to convert base 10 numbers to base 2 without using any premade base conversion functions. You can't use any imported libraries either.
>
>
>
**Problem**:
Convert an input string from base 10 (decimal) to base 2 (binary). You may not use any premade base conversion code/functions/methods, or imported libraries. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes will win.
Input will be anything from -32768 to 32767 (include sign byte handling in your code)
[Answer]
# JavaScript, 46
```
for(x=prompt(o='');x;x>>>=1)o=(x&1)+o;alert(o)
```
[Answer]
# Brainf\*ck, 98 77
Obviously this isn't for the purpose of winning but what would a competition be if it didnt have a brainfk solution
```
++++[>++++<-]>>,<[->>++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]++++++[->++++++++<]>.[-]>[-<<<+>>>]<<<<]
```
Since brainfk can only handle 8bit integers and no negatives I guess it doesn't fully abide by the rules but hey I was never in it to win it.
This actually does work for 16-bit input if your interpreter supports
I even got it to output in ascii values
Here is the annotated code:
```
++[>++++<-] preload 8 onto cell 1
>>,< input into cell 2
[- iterate over cell 1
>>++< put 2 in cell 3
[->-[>+>>]>[+[-<+>]>+>>]<<<<<] division algorithm: converts {n d} into {0 d_minus_n%d n%d n/d}
>[-]++++++[->++++++++<]> clears cell 4 and puts 48(ascii of 0) into cell 5
.[-] output n%2 and clear it (the bit)
>[-<<<+>>>] bring n/2 into cell 2 (to be used for division in next iteration)
<<<<] end iterate
```
Shorter algorithm (77):
```
+>,>-<[>>[->]++[-<+]-<-]++++++++[->++++++<]>+[->+>+>+>+>+>+>+>+<<<<<<<<]>[.>]
```
This one can only handle 8bit integers.
The algorithm works by using a binary counter which is actually very short (one increment is `>[->]++[-<+]-<-` which then lays out the bits. The issue is that it is difficult to print out all of the bits
That last algorithm can be adapted to fit any number of bits at the expense of bytes. To be able to deal with N bit integers, it requires 53+3\*N bytes to encode.
examples:
```
(1 bit) +>,>-<[>>[->]++[-<+]-<-]++++++++[->++++++<]>+[->+<]>[.>]
(2 bit) +>,>-<[>>[->]++[-<+]-<-]++++++++[->++++++<]>+[->+>+<<]>[.>]
(3 bit) +>,>-<[>>[->]++[-<+]-<-]++++++++[->++++++<]>+[->+>+>+<<<]>[.>]
etc
```
[Answer]
## GolfScript - 17 bytes
```
~{.1&\2/}16*;]-1%
```
Not too much more verbose than the built-in `~2base`.
[Answer]
## Mandatory APL answer - 21 ~~22~~
```
"01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
```
Examples:
```
"01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: 0
0000000000000000
"01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: 13
0000000000001101
"01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: 9999
0010011100001111
"01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: -3
1111111111111101
"01"[1+2|⌊⎕÷2⋆⊖0,⍳15]
⎕: 32767
0111111111111111
```
[Answer]
# Turing Machine Code, 272 bytes
As usual, I'm using the rule table syntax defined [here.](http://morphett.info/turing/turing.html) You can test it on that site or, alternatively, using [this java implementation.](https://github.com/SuperJedi224/Turing-Machine)
A lot of the code is copied from my decimal-to-hex converter [here.](https://codegolf.stackexchange.com/a/68250/39022)
```
0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 9 l 1
1 1 0 l 2
1 2 1 l 2
1 3 2 l 2
1 4 3 l 2
1 5 4 l 2
1 6 5 l 2
1 7 6 l 2
1 8 7 l 2
1 9 8 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 0 l 3
4 * * r 4
4 _ _ r A
```
Counts down from the input in base 10 while counting up from 0 in base 2. On decrementing zero, it erases the input block and terminates.
[Answer]
# [Dyalog APL](http://dyalog.com/download-zone.htm), 11 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
2|⌊⎕÷2*⌽⍳16
```
`2|` The division remainder when halved of
`⌊` the rounded down value of
`⎕` the input
`÷` divided by each of
`2*` two to the power of each of
`⍳16` {0, 1, 2, ..., 15}
Requires `⎕IO←0` which is default on many systems.
[TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%27Input%3A%20%20%27%2C%u2206%u2190%28%3F2*16%29-2*15%20%u22C4%20%27Output%3A%20%27%2C2%7C%u230A%u2206%F72*%u2296%u237316&run)
[Answer]
## Javascript 59
```
o='';i=parseInt(prompt());do{o=(i&1)+o}while(i>>=1)alert(o)
```
[Answer]
## Perl, 44
This is my first Perl program ever, so please forgive me if this can be easily golfed down further. Edit: Thank you @primo for taking 7 chars away from my answer.
```
$x=<>;do{@s=($x&1,@s)}while($x>>=1);print@s
```
```
$x=<>;do{push@s,$x&1}while($x>>=1);print reverse@s
```
The logic is essentially the same as my previous C solution.
Also, uses 64 bits.
[Answer]
# Javascript - ~~56~~ 48 and ~~36~~ 28 characters
* Does not works with negative numbers.
Thanks to @Blender for shaving 8 characters.
This form takes input and shows output, 48 characters:
```
x=prompt();for(a="";x;x=~~(x/2))a=x%2+a;alert(a)
```
If just an instruction that puts in a variable `a` the binary form of a variable `x` is needed (and you don't bother in destroying the `x` value as a side-effect), here it is with 28 characters:
```
for(a="";x;x=~~(x/2))a=x%2+a
```
[Answer]
# Python - ~~61~~ 60 characters
```
x=input();print"".join("01"[x>>i&1]for i in range(15,-1,-1))
```
[Answer]
## C, 55 chars
Prints an extra leading zero (for the sake of 2 bytes).
Recursion within `printf` reverses the print order, so the algorithm extracts bits right-to-left but prints left-to-right.
*EDIT*: Saved a char by using `putchar` instead of `printf`.
```
f(x){(x*=x<0?-printf("-"):1)&&f(x/2);putchar(48+x%2);}
```
[Answer]
# Excel, ~~91 90 81~~ 74
Trailing parens already discounted.
Compatibility note: `CONCAT()` was available only after later versions of 2016. It replaced `CONCATENATE()`. Tested in Excel online.
## Formulae
* `A1` - Input
* `B1` - `=A1+4^8*(A1<0)` (13) - Convert to 16-bit unsigned equivalent.
* `B2` - `=1+INT(LOG(B1,2))` (15) - Number of binary digits + 1
## Code (46):
Convert `B1` to binary.
```
=IF(A1=0,0,CONCAT(--ISODD(B1/2^(B2-SEQUENCE(B2)))))
```
Works in the full 16-bit range.
[Answer]
## C, 81
```
char b[17];i=15;main(x){scanf("%d",&x);while(i+1)b[i--]=(x&1)+48,x>>=1;puts(b);}
```
The output has strictly 16 bits (including padding zeros)
[Answer]
# Bash, 44
```
f=b+=n/2**e%2*10**e,2**e++/n?f=b:f;echo $[f]
```
Pass an input value to the script through the environment variable `n`. The decimal representation of the binary result cannot exceed `LONG_MAX`.
This should also be compatible with `ksh93` and `zsh` if `b` and `e` are initialized to `0` and proper arithmetic expansion is used.
[Answer]
# Apps Script + Google Sheets, ~~147~~ ~~144~~ 121 bytes
### Script
```
function j(decNumb){var str='';do{str=String(decNumb%2)+str;decNumb=decNumb/2|0;}while(decNumb>=1);return parseInt(str);}
```
### Sheet
```
=j(b1)
```
Modified version of [this script](https://stackoverflow.com/a/30966383) by ZygD.
[Answer]
# Haskell, 66 bytes
```
c 0=0
c n=c(div n 2)*10+mod n 2
b('-':r)='-':b r
b r=show.c.read$r
```
Call with `b "-1023"`, add `main=interact b` for a complete program or
[try it on Ideon.](http://ideone.com/JXYWnk)
`c` performs the conversion for positive integers.
`b r=show.c.read$r` converts a string to a number, applies `c` and converts back to string.
`b('-':r)='-':b r` strips a possible leading `-` and re-appends it to the result.
[Answer]
# PowerShell, ~~59~~ ~~87~~ ~~82~~ 70 bytes
+28 bytes for supporting negative numbers.
-12 bytes thanks to @ASCII-only
```
param($d)$m=$d-lt0;while($d){$n="01"[$d%2]+$n;$d=($d-$d%2)/2}'-'*$m+$n
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVFUyXXViVFN6fEwLo8IzMnFSRUrZJnq2RgqBStkqJqFKutkmetkmILlNAF8TX1jWrVddW1VHKBEv///9c1NAAA "PowerShell – Try It Online")
Adapted from [this code](https://ss64.com/ps/syntax-base36.html). Takes input through a commandline parameter `-d`.
[Answer]
# APL(NARS), 17 chars, 34 bytes
```
{2∣⌊⍵÷2*(⍺-1)..0}
```
It is a copy and modify of Adam answer <https://codegolf.stackexchange.com/a/90107>
in the way one can add the parameter for the bits lenght,
and ⎕IO for this function (here is ⎕IO=1) should have no importance...
```
f←{2∣⌊⍵÷2*(⍺-1)..0}
16 f 2
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
32 f 2
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
32 f ¯1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
16 f ¯1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
64 f ¯12345678
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 1 1 0 1 0 1 1 0 0 1 0
```
it seeme easy handle the number of bits in this way (I cheked that last result should be right)
[Answer]
# Smalltalk (Smalltalk/X), 63/78
the first version creates an intermediate string (78):
```
t:=Number readFrom:Stdin.
((15to:1by:-1)collect:[:i|$0+(t>>i&1)]as:String)print
```
actually, there is no need to create the string; just output the chars (63):
```
t:=Number readFrom:Stdin.
15to:1by:-1 do:[:i|($0+(t>>i&1))print]
```
mhmh - is there a shorter way to read to a number?
[Answer]
# Python 3.x: 65 characters
```
b=lambda n:n<2 and'01'[n]or b(n//2)+b(n%2);print(b(int(input())))
```
[Answer]
# C# - 104
```
string p(int d){var r="";long i=1;while(r.Length<=64){var g=d&i;r=(g!=0)? "1"+r:"0"+r;i=i<<1;}return r;}
```
This method will convert decimal to binary up to `64` bits.
When executed the above method in Linqpad -
rr = p(-32768);
rr.Dump();
Output: `01111111111111111111111111111111111111111111111111000000000000000`
[Answer]
# [Kotlin](https://kotlinlang.org), 82 bytes
```
{s:String->{var i=s.toInt()
var r=""
(0..15).map{r="${i and 1}$r"
i=i shr 1}
r}()}
```
[Try it online!](https://tio.run/##hVVfj9M4EH/3pxiilUhQm2z3BBzVFQkQD0grgcS@3KOTTBMLx87Zzi6l6mdfZuw0u8txuqpKrRnPzO@PnX6zQStzX72ADw5lwBb21kHolYfGtgid1Xtoeqk1mg63og9h9Nuq4iTnSh9k8w2/0xbKl40dqn8m9EFZ46uryzdvXooP1tyiC7B3doBaeoTNJQSblldwp0JvpwD1pHRYK5PiTSzy3EaI9zSic3Yy7VYIoM/fdoJe3iLUiAY6dUtPSV/vVWcGNIH7N/Pc80gzDTW1/M3oySvTUYMDjA4HSbR/wQD7yTSRUxlnN9I85zKMRWoYrWPptKqddAo9IHVGVwrxxdla40C4zzIQTmVGmuqD47FPZMlbbNQgdfEIZV4rI92hSKMHeQBjH4b/F2I2qFpgVwMS1davgNz9N94SvirTYPJ9tn7N9q4ohOB73u8Zu79DakAmHShAAmpND0NEP0VOMVBHZNTrzG79x9XrV38yJV68hpyG6YlAs12xFblpWs0F1PtgJxchFOJFJURVwcfvI@UJ8eIH0VhOZSmIJwlhG/Q@T7Ju4Wv8LWAHRz401OXsQKSUxCdI0Y@AHboVLVRQUqsfmCp4p0M/6bCa7wW59ApqFUhJ5suBZnKOjlyqoBTIFK@xU8bwFLt/PJOYkKJqHx5mzACgtXd0irlJSclb6ZbMbq4ug/1kQl7M6QSOsllGkfyyLDcvi3KQI5Hmi/KQvzieW/H8zekipbK47WHKeeV7BxvKnRgi9RPnXuKUFxyb5Y723PDZaB1dQ/c7ZwapTC5d57fwzjl5@CtZ87ZYnLmWQ93K5Zb92oS5ahhhd3/021S8fnuM8uz8okjUY0dCPJLhSAFivnDOhNqpRO4kHFE53UcAN@5A/GQbz8QjQ7huZgrJlEA7k7aMKd6KXSy9Vgbz4tmzmBsJY9Amzy7iDrpSF8cx53VxyoqZ9WcD9OLEkSmvoBmHUZNST2a2uJckui@jFY0MTQ85OmfdFm56Z@8kvV2KGdAy9L1s0ztmNb/aljZZ8QS6J@ySLfm8z7N0S7MVZPGW8mK94eflXMWu5ImPSeUp/r9052NE0on5PNFfzk8 "Kotlin – Try It Online")
[Answer]
# [Small Basic](http://www.smallbasic.com "Microsoft Small Basic"), 133 bytes
A script that inputs from and outputs to the `TextWindow` console.
```
n=TextWindow.Read()
While n>0
c=c+1
x[c]=Math.Remainder(n,2)
n=Math.Floor(n/2)
EndWhile
For i=0To c-1
TextWindow.Write(x[c-i])
EndFor
```
[Try it at SmallBasic.com](http://smallbasic.com/program/?DCZ401 "SmallBasic.com") *Requires Silverlight and thus must be run in IE.*
I/O is taken/given from the black console.
-22 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~50~~ 43 bytes
-7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
f(n){printf("-%d"+(~n?n&&f(n/2),1:0),n&1);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zuqAoM68kTUNJVzVFSVujLs8@T00NKKFvpKljaGWgqZOnZqhpXfsfqEghNzEzT0OTq5qLM01D11TTWqGgtKRYQ0lJ0xokYm6BLmKAIlD7HwA "C (gcc) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 43 bytes
```
param($n)15..0|%{$r+='01'[($n-shr$_)%2]}
$r
```
[Try it online!](https://tio.run/##dZDRCoJAFETf9ysucW1dUtk1ygiE/iNCpDZ8MLPVKFC/3a5mYkHDPs2ZGbibXx/aFIlO0xbPEELV5rGJLzZmQq08T9ZWhWYRcqn4nky3SAxGwvIPDUPTNoztbAYkxwbpAHD5Iy4G7CriXE0k6Y0YejxtEp@0l36w3nQD//ahSwTdhvoWJQTUYEHVJzFzUD9zfSz1ie7F6O0aXdzTkow5fQNmvTlDe/BdfRtLYvtJz1jTvgA "PowerShell – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~34~~ 33 bytes
```
|!/?=0:,2-}:%2:+***" @"(0:
n{\~{
```
[Try it online!](https://tio.run/##S8sszvj/v0ZR397WwErHSLfWStXISltLS0tJQcFBScPAiiuvOqau@v///7plCrqGBgA "><> – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 124 bytes
```
/~/\/\///9/8*~8/7*~7/6*~6/5*~5/4*~4/3*~3/2*~2/1*~1/0*~*0/9*~0~/*/>Oⅼ~ⅼ>/ⅼ~ⅼO/Oⅼ~Oⅼⅼ/ⅼ\O~Oⅼ/_ⅼ~_~/>O/>~>~
```
[Try it online!](https://tio.run/##LYu7DcMwEEP3YfMk@d9oBS9gwHARIEU69eyyVabJIopkBOQRvAewvK7yfJRaMUcTbKzyyiIvzPLMJE@M8sggDyQ5EeVIkBXY5GBE3r/vj9tl/mXnRj2aOz32@@Ps/HTbkJ1dYxrqDw "/// – Try It Online")
Could be considered cheating, Outputs `ⅼ` and `O` instead of `1` and `0`, due to the mechanics of `///`.
Uses examples from the [wiki](https://esolangs.org/wiki////).
[Answer]
# [Perl 5](https://www.perl.org/), 26 bytes
Produces an additional leading `0` which can be avoided with two additional bytes (appending `}{`)
```
$\=($_&1).$\;redo if$_>>=1
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxlZDJV7NUFNPJca6KDUlXyEzTSXezs7W8P9/w3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# Clojure 129 bytes#
Golfed version:
```
(defn p[n](loop[m 32768](if(> m 0)(do(if(= 0(bit-and m n))(print"0")(print"1"))(recur(unsigned-bit-shift-right m 1)))(println))))
```
Ungolfed:
```
(defn print-as-binary [n]
(loop [mask 32768]
(if (> mask 0)
(do
(if (= 0 (bit-and mask n))
(print "0")
(print "1"))
(recur (unsigned-bit-shift-right mask 1)))
(println))))
```
[Answer]
# PostgreSQL, 184 bytes
```
WITH RECURSIVE t(a,b,c)AS(SELECT abs($1),0,0 UNION ALL SELECT a/2,a%2,1from t where a>0)select case when $1<0then '-'else ''end||string_agg(b::text,''order by a)from t where c>0OR $1=0
```
137 bytes if only handling positive numbers
```
WITH RECURSIVE t(a,b,c)AS(SELECT $1,0,0 UNION ALL SELECT a/2,a%2,1from t where a>0)select string_agg(b::text,''order by a)from t where c>0
```
Input is given as an integer query parameter (using the extended query protocol or by wrapping in a function) and output is given as a string.
]
|
[Question]
[
# Task
Haskell's and Scala's standard libraries have an `unfold` function that builds a list from an initial state `s` and a function `f`. This is done with the following steps (explained in an imperative way to be simpler):
1. Apply `f` to `s`.
2. If the result
* is empty, we're done building the list!
* Otherwise, the result should contain the next state `t` and the next element `e` of the list.
1. Add `e` to the list
2. Set `s` to `t` and go back to step 1
Here, we will only be considering lists made of integers. `s` will be an integer, `f` will take an integer as input, and the result of your `unfold` function will be a list of integers. The output of `f` will either be
* A fixed value representing that the list has ended
* A class of values (distinct from the fixed value above) that hold an integer representing the next state and an integer representing the next element.
## Example
Let's take the example of converting a number to base 5. The initial state would be the number to convert. The output would be a list of the digits in base 5, but reversed. The function would look something like this:
```
function f(s)
if s equals 0
return null
else
digit = s mod 5
nextState = s ÷ 5 (÷ is integer division here)
return [nextState, digit]
```
Using this function and an example initial state of 137, we go through the following steps:
* `s = 137` and the result is `[]`
* `digit = 2`, `nextState = 27`. The result is now the list `[2]` and `s` is `27`.
* `digit = 2`, `nextState = 5`. The result is now the list `[2, 2]` and `s` is `5`.
* `digit = 0`, `nextState = 1`. The result is now the list `[2, 2, 0]` and `s` is `1`.
* `digit = 1`, `nextState = 0`. The result is now the list `[2, 2, 0, 1]` and `s` is `0`.
* Since `s` is 0, we return the list `[2, 2, 0, 1]`
Reversed, that's `[1, 0, 2, 2]` or `1022`, which, in base 5, equals 137. Note that this algorithm does not work with 0 or negative integers.
[Here](https://scastie.scala-lang.org/IcF0yY6qSYCuFh5nER4x4g) is an implementation in Scala.
As a test case, your `unfold` function should be able to convert positive integers from a base 10 to another base (as a reversed list of digits).
[Answer]
# [Factor](https://factorcode.org/), ~~37~~ 36 bytes
```
[ collector [ follow ] dip 1 head* ]
```
[Try it online!](https://tio.run/##FYwxCgIxEEV7T/FrQWUREfQAYmMjVssWIZmwwdlMnI2IXj7O8or/isePzlfR9rhfb5cTnqSZGJOrI2Z6vSl7mlGUav0WTbnivOr2R/RGNAbbA3aTBNMUNz9SwdB6eGGm5XkJzeVjQUgFHUZyYW2Rd8zYwjM5bX8 "Factor – Try It Online")
*-1 byte thanks to @chunes*
Takes `initial-value` and `quotation` on the stack, and returns a vector. The input quotation should return `next-state next-value` on the stack, or `f f` to terminate.
`some-quot collector [ high-order-func ] dip` is a pattern to snatch the top of the stack of every call of `some-quot` into a vector. Unfortunately, it collects the top of the stack before `follow` can detect that the loop has ended, so the resulting vector has a dummy element at the end. `1 head*` removes it.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~32~~ 29 bytes
Full program, prompting for `s` and then for `f`.
```
¯1↓r⊣⎕{1↓r,∘⊃←⍺⍺⍵}⍣{⍬≡⍺}⎕⊣r←⍬
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@f9qhtQjWXAhAY2D7q3Wr1qHcNmJeSmZ5ZApQzrQGKgkXyUitKgksSS1KBoo96uoDCh7ebItTqwOW5arkedbSX5qXl56T8P7Te8FHb5KJHXYsf9U2tBrN1HnXMeNTVDDKmdxcYba191Lu4Gmj1o86FQIFaoFKghiKwijX/gYb9VwADiJlchsbmXGkA "APL (Dyalog Unicode) – Try It Online")
`r←⍬` initialise the **r**esult variable to the empty list
`⎕⊣` dismiss that in favour of `s` from stdin
`⎕{`…`}⍣{⍬≡⍺}` get `f` from std and use it as follows until the result is the empty list:
`⍺⍺⍵` apply `f` to the current `s` (returning `[e,t]` or `[]`)
`r,∘⊃←` extend `r` with the first value from that (`e` or `0`)
`1↓` drop the first value from that (leaving `[t]` or `[]`)
`r⊣` discard that (i.e. the last computed value, i.e. `[]`) in favour of `r`
`¯1↓` drop the last value (`0`)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{-1_1_*'|'{x}(y@*:)\x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6rWNYw3jNdSr1GvrqjVqHTQstKMqajl4kqLNjQ2t65Wia6wNbA2sNaIr1A11dQxVayIrY0FAK++D28=)
call with `f[n,s]`.
`s` should return an array `(nextState;digit)` and return a falsy value when it's supposed to end.
I can remove `{x}` but that would make the function stop on a repeated state. Although that is unlikely, it doesn't seem right to reject that.
# Explanation
```
{-1_1_*'|'{x}(y@*:)\x}
\x
iterate on first arg, producing array
(y@*:) apply second arg(function) to the first elem of the iteration
{x} stop if the iteration is falsy
|' reverse each array
*' take first element of each
-1_1_ remove first and last element
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
f=#@#2/.{a_,b_}:>b<>#~f~a&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2YLRMoOykb6etWJ8TpJ8bVWdkk2dsp1aXWJav8DijLzSqKVde3SHByUY9XqgpMT8@qquao906KVbW0NdKprdQJL80syU/NKgoAmZualpBZFK@uYxsaq6SgYGpvXctX@BwA "Wolfram Language (Mathematica) – Try It Online")
Input `[f, s]`. Returns a `StringJoin` of elements. Expects an empty list to indicate the list has ended.
To output a list, **+6 bytes**:
```
f=#@#2/.{a_,b_}:>{b,##&@@#~f~a}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2YLRMoOykb6etWJ8TpJ8bVWdtVJOsrKag4OynVpdYm1av8DijLzSqKVde3SgGKxanXByYl5ddVc1Z5p0cq2tgY61bU6gaX5JZmpeSVBQHMz81JSi6KVdUxjY9V0FAyNzWu5av8DAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
1 :'[:(#~2|i.@#)(,u@{:)^:_'
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRWs1KOtNJTrjGoy9RyUNTV0Sh2qrTTjrOLV/2typSZn5CtomKrVaOgo1xnYaGva6DmoqplqKqQpGBqb/wcA "J – Try It Online")
This is J adverb, which modifies a verb returning `(new element, new state)` to create the required unfold verb.
* `(,u@{:)^:_` Keep appending unfold's results until a fixed point, re-applying the verb to the last element on every iteration.
* `[:(#~2|i.@#)` Keep only odd indexed elements, ie, the elements only, and discard the states and the starting value.
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 46 bytes
```
(d U(q((S F)(i(F S)(c(h(t(F S)))(U(h(F S))F))(
```
[Try it online!](https://tio.run/##LYwxCsMwEAR7v2LLvSKEEEx@oNKN0QPkyCYHsp1Yavx6@RDpZgZ2i25n0vytlRGeP3KEEyodRuGbH5aGIvQmDZ1JZdpDRNLpCMcpHeO8YAp5vvVgCusUAzgIqAsGK5oLeDfsra17bCTYNNl1R4/H8/XfS70A "tinylisp – Try It Online")
### Ungolfed
Implements the spec directly:
```
(load library)
(def unfold
(lambda (val func)
(if (func val)
(cons
(head (tail (func val)))
(unfold (head (func val)) func))
nil)))
```
This approach is pretty inelegant: it's not tail-recursive, and it calls the function three times at each step. If I were going to implement `unfold` for the standard library, it would look more like this (using a helper function `_unfold`):
```
(def _unfold
(lambda (func return-val accum)
(if return-val
(_unfold func
(func (head return-val))
(cons (head (tail return-val)) accum))
(reverse accum))))
(def unfold
(lambda (func val)
(_unfold func (func val) nil)))
```
[Answer]
# JavaScript, 37 bytes
```
f=>g=s=>(a=f(s))?[a[1],...g(a[0])]:[]
```
[Try it online!](https://tio.run/##JcvBCsIwDADQv5EEZrG6XQbJPqTkELa1KCURu/n79eC7v5d@ta2f5/u4mm97Py173ahn4kKNGJQyNMQlaYoyhBAKaLoJypykr27N6x6qF/hPMGJbkjGPg13iJLOdtSLE@2OcEPsP "JavaScript (Node.js) – Try It Online")
`((state: T) => [next_state: T, val: S]?) => (state: T) => S[]`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ṫv@¥ƬFḊ
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//4bmqdkDCpcasRuG4iv///zE1OTc4/yJk4oG1VSTigJzigJ3CuT8i "Jelly – Try It Online")
A dyadic link taking the start value as its left argument and the Jelly code for the relevant function to unfold as its right. It expects the return value of this link to be an empty list if we’re done, otherwise a list of `[next value for result, next value for function]`. Returns a list of integers.
[Answer]
# [Haskell](https://www.haskell.org/), 22 bytes
```
f#x=do(s,v)<-f x;v:f#s
```
[Try it online!](https://tio.run/##VY1BDoIwFET3PcUkuGgTIBpDTFA8gAleAFkUaKGxAqFA8PLWEhbG5Z95b37DzVNobanHEMegHMEVGeU@Cpaz9diSIrfSW5Kqo8af2SWQWM5zLD1jp5@X8nchsMl/LpmQYH0RgspOVwONWZaHjJCCGxG5csIOj2XFlZtGkmCPsREt7t3YqLaG0EbgNpnRgZWa065yWETIi6vW@f2g2rXa9g7Hk/2UUvPa2KDs@y8 "Haskell – Try It Online")
Function is expected to return a list `[(state, value)]` or an empty list. (Footer converts from the conventional/expected use of `Maybe`.)
```
f#x= Define a function (#) on arguments f and x, returning
do <-f x; the concatenation for each element of f called on x
(s,v) providing the new state and value
v: of the value prepended to
f#s (f#) called on the new state.
```
Was this before I remembered `MonadFail` is a thing (never mind I'm not even using it anymore):
# [Haskell](https://www.haskell.org/), 26 bytes
```
f#x|s:v<-f x=v++f#s|1>0=[]
```
[Try it online!](https://tio.run/##XY3RCoJAEEXf9ysu2INSghERSPYBgf2A@bDVri2Ziau2gd/eNmtE1LzMXOaee89cX0RZWt8LEMfwOcINMp4Hbn@ElZ4ZdNyvQwmT9NOp9PQw30RJltvui6X8cRB0z8CDH551kEjgOgoGmvtZNAIFzKg@M2Db6Ra@nqEPsA4JMoRlTud/zltLEXelhTPkjB24Fku6O0ywN65XjXSCCGStsCNCVQVESczYM8FJ9entRLYlY1euKuLrRlXu9c6bL1b2eZQlL7QNj3X9Ag "Haskell – Try It Online")
Function is expected to return a list `[state, value]` or an empty list.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 36 bytes
```
for($k,$a=$args;$a){$a,$u=&$k $a;$u}
```
[Try it online!](https://tio.run/##TY7BCoMwEETP5iv2sJUISiml9BDyJaWHpUYraiKroYfgt6dbKLS34c0wM0t4OV6fbpqaR2CXMfouTK1NuQuscayRLBL3q0GqElKN0ZY4ApLBuOddKextUgALMc36NvjtLkkBQ6dFQFIFsptp8K1jsCAQDnCpVMFui@xBf0gDv1AFR/HrP2KkbleyVX7vAfZwOl/zGw "PowerShell Core – Try It Online")
Takes two parameters, a function `$k` and the initial value `$a`
-1 byte thanks to *mazzy*!
[Answer]
# [Perl 5](https://www.perl.org/), 45 bytes
```
sub u{@f=$_[1]->(@_);@f?(pop@f,u(@f,pop)):()}
```
[Try it online!](https://tio.run/##HY1RCoJAFEX/W8VFLN/YZJQNRWK6jwwhcMiocRibIMLfFtAS24iN8uDcA/fC05W5ib5v7Rn2ncvUL4@r0@JAecmSXGakG51LbsnBKWN7Yt24lgJv3F/wlb2n7aWWj2R0ZKBaPWjwpWB8yKlg2IMYuok2roTnl/h9vvAQ4drUioKAw1TPyrQVLMEvOYqZe8HcRfAK5UE2Bqt4yx12Dut4IzjiUIThDnOIpP8D "Perl 5 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 42 bytes
```
u=lambda f,x:(r:=f(x))and[r[1],*u(f,r[0])]
```
[Try it online!](https://tio.run/##TY3BCgIhFEXX@hWPWWm4mGGIYsAvMReGSoKj8tKwr7eJNu0u58C55V0fOa3XgqMln6MFCbfRZDT73Rrwom8MN@lZ59wkq1AtWpwa8wLVrLke1nn42o2S4KGDlDAfm6CrDRNMEyUuPt0fsuG1Z8u6gDOntGBIlf2@jyos64Xz8QE "Python 3.8 (pre-release) – Try It Online")
-1 byte thanks to Noodle9
-4 bytes thanks to Shaggy
Assumes falsy output for the end case and a pair otherwise (any subscriptable value with at least two elements). Since a list of falsy values is still truthy, this works perfectly fine.
[Answer]
# [Racket](https://racket-lang.org/), `#lang racket`, 57 bytes
```
(define(u s f)(match(f s)[`(,z,x)(cons x(u z f))][_'()]))
```
[Try it online!](https://tio.run/##TYxBCsIwFET3nmKgC@dDF4qIGz1JKRrbRINpQpsUSi9foyL07d7wmEE1L52Wwin/wPATttpYrzkiwgg7lZonDaJUN5ZzOQmb4COmHMw5kLq6bim1yJKX/eEEOtXdWwVG2eAPrQHPl/y5W61AYdZGZ2MC@zEkq33K9VHALrSjC1/5sLwB "Racket – Try It Online")
The function `f` can return anything other than a list of two values to indicate stop.
---
Not the most interesting racket solution: no tail-call recursion, so is bounded by memory usage. It would be more fun (and not difficult) to write a `#lang` that supplies `unfold` as part of its runtime—then there would be a 0-byte solution :)
We (unexpectedly?) save a few bytes by eliminating spaces between `,z,x` and `_'()` in `match` clauses. I expected each to coalesce into a single identifier, but (un)quoting took precedence. The remaining whitespace (6 spaces, by my count) is required.
[Answer]
# [R](https://www.r-project.org/), ~~43~~ 42 bytes
```
u=function(s,l=f(s))if(1/l)c(l[2],u(l[1]))
```
[Try it online!](https://tio.run/##TY1BCoAgEADvvWIvwi4IYhGdfEBvCE/mgrAoZL7fjC6dZg4Dc/WWucjpenPccrhTyVi1OMZKlBitEQoox@x1G7CeqPMvJUhvCgErKKNg1TBkkCBKjbBnnr4F2mWj/gA "R – Try It Online")
Recursive function using helper function `f` to to the unfolding.
`f` must output the fixed non-integer value `Inf` to represent that the list has ended (a more natural value in [R](https://www.r-project.org/) would be `NULL` or `NA`, but the functions `is.null()` and `is.na()` are each much less golfy than the simple test `1/x` [truthy for all integers, falsy only for `Inf`])
]
|
[Question]
[
The [gravitational binding energy](https://en.m.wikipedia.org/wiki/Gravitational_binding_energy) of a planet is the amount of energy required to separate every tiny piece of it so that no piece will orbit or collide with another piece. For a uniform sphere, Wikipedia gives this formula:
$$E = \frac{3GM^2}{5R}$$
Where G is the gravitational constant (6.672e-11 m3•kg-1•s-2), M is mass, and R is the radius.
I *could* make this challenge about merely calculating this in Joules (kg•m2•s-2), but… that would be *boring*. And besides, not everyone understands Joules.
So instead, let's convert it into the following units:
* Kilotons of TNT (4.184 trillion Joules, shorthand `kilotons`)
* Hiroshima nuclear weapons (62.76 trillion Joules, shorthand `nukes`)
* Hostess™ Twinkies (560,000 Joules, shorthand `twinkies`)
* Kilowatt-hours (exactly 3.6 million Joules, shorthand `kWh`)
* Kilograms of mass-energy (1 kg mass-energy = 299,792,4582 Joules, shorthand `kg`)
So, take in the following input:
* mass in kilograms
* radius in meters
* one of six distinct inputs representing the unit to use
And output the binding energy in the specified units. Append the shorthand unit to the end of the output.
# Rules
* The shorthand for Joules is `J`.
* Arbitrary whitespace is allowed, as long as it doesn't split the shorthand unit or the number.
* Scientific notation is allowed, in whatever format your language uses.
* You only need 4 significant figures. Floating points are *highly* recommended.
* Blah blah shortest answer in bytes.
# Test Cases
Generated with [this spreadsheet](https://docs.google.com/spreadsheets/d/1-EqcIhiNm9kXbXmsQzstkAhGFf_KQJJZay8Al6Zft9c).
```
Mass (kg) Radius (m) J kilotons nukes twinkies kWh kg
3.302E+23 2440000 1.789E+30 4.275E+17 2.850E+16 3.194E+24 4.969E+23 1.990E+13
4.869E+24 6052000 1.568E+32 3.748E+19 2.499E+18 2.800E+26 4.356E+25 1.745E+15
5.974E+24 6371000 2.242E+32 5.360E+19 3.573E+18 4.004E+26 6.229E+25 2.495E+15
6.419E+23 3390000 4.866E+30 1.163E+18 7.753E+16 8.689E+24 1.352E+24 5.414E+13
1.899E+27 69911000 2.065E+36 4.935E+23 3.290E+22 3.687E+30 5.736E+29 2.298E+19
5.685E+26 58232000 2.222E+35 5.310E+22 3.540E+21 3.968E+29 6.172E+28 2.472E+18
8.683E+25 25360000 1.190E+34 2.845E+21 1.896E+20 2.125E+28 3.306E+27 1.324E+17
1.024E+26 24620000 1.705E+34 4.075E+21 2.717E+20 3.045E+28 4.736E+27 1.897E+17
1.311E+22 1186000 5.801E+27 1.387E+15 9.244E+13 1.036E+22 1.611E+21 6.455E+10
1.989E+30 696300000 2.274E+41 5.436E+28 3.624E+27 4.062E+35 6.318E+34 2.531E+24
7.350E+22 1737000 1.245E+29 2.976E+16 1.984E+15 2.223E+23 3.458E+22 1.385E+12
```
---
Inspired by [Powering the Death Star with Twinkies](https://www.youtube.com/watch?v=i8LIDFGawDU) by Scott Manley.
[Answer]
# JavaScript (ES6), 78 bytes
Takes input as 3 distinct variables `(mass, radius, unit)`.
```
(m,r,u)=>m*m/r/[8987e9,56,6276e6,,4184e5,1e-4,360][parseInt(u,30)%7]/2498e11+u
```
### Test cases
The following snippet runs all test cases in the provided spreadsheet.
```
let f=
(m,r,u)=>m*m/r/[8987e9,56,6276e6,,4184e5,1e-4,360][parseInt(u,30)%7]/2498e11+u
console.log(
[
'3.302e+23 2440000 1.789e+30 4.275e+17 2.850e+16 3.194e+24 4.969e+23 1.990e+13',
'4.869e+24 6052000 1.568e+32 3.748e+19 2.499e+18 2.800e+26 4.356e+25 1.745e+15',
'5.974e+24 6371000 2.242e+32 5.360e+19 3.573e+18 4.004e+26 6.229e+25 2.495e+15',
'6.419e+23 3390000 4.866e+30 1.163e+18 7.753e+16 8.689e+24 1.352e+24 5.414e+13',
'1.899e+27 69911000 2.065e+36 4.935e+23 3.290e+22 3.687e+30 5.736e+29 2.298e+19',
'5.685e+26 58232000 2.222e+35 5.310e+22 3.540e+21 3.968e+29 6.172e+28 2.472e+18',
'8.683e+25 25360000 1.190e+34 2.845e+21 1.896e+20 2.125e+28 3.306e+27 1.324e+17',
'1.024e+26 24620000 1.705e+34 4.075e+21 2.717e+20 3.045e+28 4.736e+27 1.897e+17',
'1.311e+22 1186000 5.801e+27 1.387e+15 9.244e+13 1.036e+22 1.611e+21 6.455e+10',
'1.989e+30 696300000 2.274e+41 5.436e+28 3.624e+27 4.062e+35 6.318e+34 2.531e+24',
'7.350e+22 1737000 1.245e+29 2.976e+16 1.984e+15 2.223e+23 3.458e+22 1.385e+12'
]
.map((l, n) => {
[m, r, ...res] = l.match(/\S+/g).map(Number);
return 'Test case #' + -~n + ' -> ' + (
['J', 'kilotons', 'nukes', 'twinkies', 'kWh', 'kg']
.every((u, i) => +(+f(m, r, u).split(u).join``).toExponential(3) === +res[i])
? 'OK' : 'FAIL'
)
})
)
```
### How?
This is quite similar to [@ColeraSu's C answer](https://codegolf.stackexchange.com/a/149186/58563), with a JS-friendly hash function that works on the whole unit string.
```
Unit | Parsed as (*) | Base-30 -> Dec. | mod 7
-----------+---------------+-----------------+------
"J" | "j" | 19 | 5 (*):
"kilotons" | "kilotons" | 451052545318 | 4 Because we're parsing as Base-30,
"nukes" | "n" | 23 | 2 characters [u-z] (and anything
"twinkies" | "t" | 29 | 1 after them) are simply ignored.
"kWh" | "k" | 20 | 6
"kg" | "kg" | 616 | 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 78 bytes
```
²×⁽LÐ÷ȷ14÷⁴÷5÷⁵ị“¤Fðẏẏż“?A⁺ẏẏż“¬ŀż“8Ƙż“¡uþ³⁾ẉṿÆ“¡’¤;⁵ị“ÞṠlT“¡ṁæ-“;ØḲ“ȧ¹“ṫD“}»¤
```
[Try it online!](https://tio.run/##y0rNyan8///QpsPTHzXu9Tk84fD2E9sNTQ5vf9S45fB2UxC99eHu7kcNcw4tcTu84eGufiA6ugfIt3d81LgLiX9ozdEGMMPi2AyIwMLSw/sObX7UuO/hrs6HO/cfbgMLPmqYeWiJNdzYw/Me7lyQEwKWeriz8fAyXSDT@vCMhzs2ARknlh/aCaQe7lztAqRqD@0@tOT////GesapRsb/jfRMTFLN/hsCAA "Jelly – Try It Online")
Stuff to do with strings isn't really Jelly's type of challenge...
-7 bytes thanks to user202729 (thanks for helping me not get beaten by JavaScript :D)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~56~~ 54 bytes
Takes input as `unit, radius, mass`
```
6n56•G*•x619+•Oć•4°z)•1¡‡•S°*"Wwigu"I1èkè*2498T>°P/*¹J
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fLM/U7FHDInctIFFhZmipDaT9j7QDSZNDG6o0gbThoYWPGoBoUfChDVpK4eWZ6aVKnoaHV2QfXqFlZGJpEWJ3aEOAvtahnV7//@eVZqcWcxmZmBgAAZexnrGBUaqRMQA "05AB1E – Try It Online")
Saved 2 bytes thanks to *Erik the outgolfer* (base 255 encode `4184` and `6276`).
[Answer]
# C, 113 bytes
Hash the second character, using the trailing `'\0'` of `"J"`. Inline array in C is used.
Note we need to multiply the second `M` last, or it will overflow to `inf`.
```
f(m,r,c)float m,r;char*c;{printf("%e%s",m/r/(float[]){1e-4,360,6276e6,8987e9,56,4184e5}[c[1]%36%7]/2498e11*m,c);}
```
[Try it online!](https://tio.run/##jc27CoMwGIbh3auQgBDb30MORsW5S2@ggzhIiAfUKBrpIF67lW4dCn7TOzzwSa@W8jgqPMAM0q36sTT22Zlsyvkms22aW20qjBzlLAiGYA7wF@WFuxHlcWAiBEFjoQQkaRKrFCIBnCRcRXsuc1I4TDhxEVCeJoqQ23DeZPsxlK3GrrVZdoWZz0L6uFMGlPPwnA/oidxsWs2C0Rn/UNf2oxn1csXqtVOXoHm3uuuv2e7VXGL1j9qPDw "C (gcc) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~153 71~~ 69 bytes
```
op←{⍺,⍨40032E¯15÷÷/8987E13 36E5 6276E10 56E4 4184E9 1['gWuw '⍳⊃1↓⍺]⍵⍺⍺⍵}
```
[Try it online!](https://tio.run/##dZNPSsNAHIX3niK7KGic/5k5wGxm1Z0LcSEotaQ0BVuKiCvBhVARxDu4cyFScGlvkovUNJk00/gChcDvK48vL7zL6fjk6u5ynA83xcv7YFA8vYpNPi0f98Xy57hYfghCOLO/n1SuV@vVqTY6tZRHXFkZKZYqS0kklRWRoFpYE9HzeHg2X0Rxsfwqnh9p8fRWJl0Uy@/yUf2@HzabOBvGh0yU4YRE@fSIJ9wyfhA7eM1G43yWT24hnMyza0xmi9EkG/XA7OwG3Q8qM0Uk83eRaGUsE6EFxN4DstYEJ29dIHH47i15Sj2RiUlF1xLhxhKxwBImV5aIOHyvLTk3TccqEdR0vijE3hKy1hInby0hcfjuuzSGNi9AE21KlO6VCXnTJoRBnTi86hMi1wNqV6kZZ7uylZaWqdAVc@@KYevaE751xcj1gNqVSa6aynWJypHJvUFD3mwawmDWOLxaNkSuB/x3pQlhotMr5sC1hdg1CO@6tsj1gNqVUq12hFNqGQtVIfamkLWiOHnrCYnD92ZVipP2DYw2lpP9WcE/7HYFaTgsnF8vCzLXR3yvKU89SRMuSbdXhJteEQt6hclVr4g4eP8D "APL (Dyalog Unicode) – Try It Online")
Thanks to @Adám for absolutely crushing my old answer into this one.
Thanks to @ngn for 2 bytes.
This 'function' is actually an operator called `op`.
All the values for the measurement units were transformed to scientific notation.
### How it works:
```
{⍺,⍨40032E¯15÷÷/8987E13 36E5 6276E10 56E4 4184E9 1['gWuw '⍳⊃1↓⍺]⍵⍺⍺⍵}
1↓⍺ ⍝ take the measurement unit without the first letter (because it is ambiguous)
⊃ ⍝ picks the first element returned by
⍳ ⍝ Dyadic ⍳ota, which finds the index of
'gWuw ' ⍝ each of these characters
[ ] ⍝ square brackets indicate the index
8987E13 36E5 6276E10 56E4 4184E9 1 ⍝ of the element of this vector (1-indexed) which will be used as the divisor for
÷/ ⍵⍺⍺⍵ ⍝ dividing by the left operand (⍺⍺) and the right argument squared.
40032E¯15÷ ⍝ then divide this number by the result
⍺,⍨ ⍝ and append the measurement unit
```
[Answer]
# Python 3, ~~112~~ ~~106~~ ~~108~~ 101 Bytes
```
lambda m,r,u:str(40032e-19*m*m/r/{'':1e-4,'i':4184e5,'u':6276e6,'w':56,'W':360,'g':8987e9}[u[1:2]])+u
```
Pretty straight forward. Uses Python's `e` notation. Uses a dict that distinguishes unit based on the second letter and divides by the corrosponding value. `u[1:2]` is basically `u[1]`, expect it returns `''` instead of an error (which I only learned now). Then applies the formula with a few simplifications.
edit: down to 106 thanks to totallyhuman, back to 108 because of new nukes value and down to 101 thanks to Colera Su.
[Try it online!](https://tio.run/##dc1NDoIwEEDhvacwbAZwlP5RYBIv4AVcIAuNRYkWSWlDjPHsyAVcvy95w9vfX72c2/1pfp7t5XpeW3QYaPQuVoxJYbY8T21qM5d9AIgjdECKl8pUCAFIi0IbzhAmoFwbhXAEktrkCDcgUVVFJVRepqn41qHmJJom2YR5cF3v4zaWO2mERKGWGWMYHaIkWf2Lfur6R2fGxcw/ "Python 3 – Try It Online")
[Answer]
# Excel (Office 365), ~~106~~ ~~101~~ 97 bytes
Assuming cell `A1` is the mass, `A2` is the radius, and `B1` is the unit, written as the shorthand for the output.
```
=40032E-19*A1^2/(A2*SWITCH(MID(B1,2,1),"u",6276E6,"w",56,"W",360,"g",89876E8,"i",4184E5,1E-4))&B1
```
# Excel, 130 bytes
Old-fashioned Excel doesn't have the `SWITCH` function, so you have
```
=40032E-15*A1^2/(A2*IF(B1="J",1,IF(B1="nukes",6276E10,IF(B1="twinkies",56E4,IF(B1="kWh",36E5,IF(B1="kg",299792E3^2,4184E9))))))&B1
```
[Answer]
# Ruby , ~~83~~ 82 bytes
```
->m,r,u{"#{40032E-18*m*m/r/[36E2,56,8987E9,1E-3,4184E6,6276E7][u.sum*3%71%6]} "+u}
```
Uses a custom hash to index a LUT for the units (`i * k mod m` formula). The numbers were found using brute-force.
[Answer]
# Excel, 94 bytes
Takes Mass from `A1`, Radius from `B1`, Unit in `C1`.
Look up on `2*Code(Unit) + Length(Unit) modulo 11`.
```
=4.0032E-15*A1^2/B1/CHOOSE(MOD(2*CODE(C1)+LEN(C1),11),,4184E5,,,6276E6,1E-4,89876E8,360,56)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~59~~ 54 bytes
*Saved 5 bytes thanks to [@ChartZBelatedly](https://codegolf.stackexchange.com/users/66833/chartz-belatedly)*
I just wanted to try another weird method to convert the units. But the rest of the code is probably badly golfed.
```
⁵OẒḄ%9ị56,4184ȷ5,8987ȷ9,360,0,6276ȷ6,ȷ-4
²÷÷2498ȷ11÷¢⁵
```
[Try it online!](https://tio.run/##AW0Akv9qZWxsef//4oG1T@G6kuG4hCU54buLNTYsNDE4NMi3NSw4OTg3yLc5LDM2MCwwLDYyNzbItzYsyLctNArCssO3w7cyNDk4yLcxMcO3wqLigbX///8zLjNlMjP/MjQ0MDAwMP8ia2lsb3RvbnMi "Jelly – Try It Online")
### How?
We build a 'signature' of a unit string out of the primality of its ASCII codes. We interpret it as a binary value and apply a modulo to get the final index in the lookup table.
```
⁵OẒḄ%9ị[...] - helper link to convert the unit to a hardcoded constant
⁵ - the 3rd input e.g. "kilotons"
O - to ASCII codes --> [107, 105, 108, 111, 116, 111, 110, 115]
Ẓ - is prime? --> [1, 0, 0, 0, 0, 0, 0, 0]
Ḅ - binary -> decimal --> 128
%9 - modulo 9 --> 2
ị[...] - get value from table --> 418400000
²÷÷2498ȷ11÷¢⁵ - main link taking the mass, the radius and the unit
² - square the mass
÷ - divide by the radius
÷2498ȷ11 - divide by 2498e11
÷¢ - divide by the unit constant, invoking the helper link as a nilad
⁵ - append the unit
```
The helper link gives the following indices for each unit:
```
unit | ASCII codes | is prime? | bin -> dec | mod 9
---------+---------------------------------+-----------------+------------+------
J | 74 | 0 | 0 | 0
kilotons | 107,105,108,111,116,111,110,115 | 1,0,0,0,0,0,0,0 | 128 | 2
nukes | 110,117,107,101,115 | 0,0,1,1,0 | 6 | 6
twinkies | 116,119,105,110,107,105,101,115 | 0,0,0,0,1,0,1,0 | 10 | 1
kWh | 107,87,104 | 1,0,0 | 4 | 4
kg | 107,103 | 1,1 | 3 | 3
```
]
|
[Question]
[
Your task is to create a program that, when run, returns itself as output (this is known as a quine). However, this quine must, when it is copied `n` times, returns the quine, but with each of its characters duplicated in place `n` times, where `n` is a positive integer.
If your original program is `Derp`:
```
Derp -> Derp (must return itself as output to be a quine)
DerpDerp -> DDeerrpp
(the "Derp" is copied twice, so each character in the output has to be copied twice)
DerpDerpDerp -> DDDeeerrrppp
etc. etc.
```
Keep in mind you're allowed to have whitespace in your "base" program, but they are counted when "interweaving". Say your program is
```
Derp
{newline}
```
(The newline signifies a trailing newline, and there's an extra space after the `Derp`). When duplicated to become
```
Derp
Derp
{newline}
```
You must output
```
DDeerrpp
{newline}
{newline}
```
Keep in mind that there's `2` extra spaces after the `DDeerrpp`.
## Rules and Specs:
* Your program must contain at least two distinct characters (which implies that your code must be at least 2 bytes long).
* [Standard quine rules](http://meta.codegolf.stackexchange.com/a/4924/49561) apply.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
## [Fission](https://github.com/C0deH4cker/Fission), 6 bytes
```
'!+OR"
```
[Try it online!](https://tio.run/nexus/fission2#@6@uqO0fpPT/PwA "Fission 2 – TIO Nexus") [Try two copies!](https://tio.run/nexus/fission2#@6@uqO0fpAQh//8HAA) [Try three!](https://tio.run/nexus/fission2#@6@uqO0fpIRM/v8PAA)
### Explanation
This is just [the Fission standard quine](https://codegolf.stackexchange.com/a/50968/8478). It happens to work for this challenge, because Fission has explicit entry points into the program. In particular, by duplicating the program, we add another `R` which adds another atom (instruction pointer). Since the source code is toroidal, the effective code being executed doesn't change otherwise — to each atom, the code still looks the same locally. However, the atoms are executed in lock step, so that the things they print are interleaved and we get an additional copy of each character in the output.
For completeness' sake I'll just shortly reiterate how the program itself works. Regardless of whether we repeat the program or not (e.g. `'!+OR"'!+OR"'!+OR"`), each atom sees the following code:
```
R"'!+OR"'!+O
```
The `"` toggles string printing mode, so that the program starts by printing `'!+OR` directly to STDOUT, which is all of the quine except the quote. Then `'!` sets the atom's mass to the character code of `!`, `+` increments it, which gives `"`, and `O` prints it while simultaneously destroying the atom. The program then terminates, because there are no atoms left.
[Answer]
# Python 2.7, 377 310 304 194 191 bytes!
This is my first golf, so I didn't expect it to be too good. But I thought the concept in the solution I came up with was somewhat funny, so I'm posting it anyway.
```
def f():
import threading as T,inspect as i;global t,a,i
try:t.cancel()
except:a=0
a+=1;t=T.Timer(1,d);t.start()
def d():print''.join(c*a for c in i.getsource(f)+i.getsource(d)+"f()")
f()
```
Indeed, this is a quine; you can [try it here](https://tio.run/nexus/python2#TY5BCoMwEEX3OcXgxqSGULeKt/AC02Rip2gicQrt6W3cdfPhwYf3zkARojaDAt72XATkWQgDpwXwgNlyOnbycgGPy5ofuIJYtKxAyncQ5zF5WrVRQB9Puww43RVgN/WjTLObeaOiexvMKO4QLFKvlzRU6V44Sdu6V@ak/Q0h5gIeOAG7heTI7@JJR9P9YzBdU4sbo@qe5w8). It abuses the inspect module pretty hard.
If we try running it with the same source code x2, we get the right output as well; you can [try that here](https://tio.run/nexus/python2#1Y5BCoMwEEX3OcXgxqSGULeKt/AC02Rip2gicQrt6a1CF71Clw8@/709UISoTaeAlzUXAbkXwsBpAtxgtJy2lbycwP005xvOIBYtK5Dy7sR5TJ5mbRTQy9MqHQ5XBdgMbS/D6EZeqOjWBtOL2wSLHNNTGg7pWjhJXbtH5qT9BSHmAh44AbuJZMvP4klH0/xiME11FFdGxe/VH/fv@wc). x3, x4, etc. all work as expected.
Ungolfed with explanation:
```
def f(): # Defines a central function f
import threading as T,inspect as i # Imports threading and inspect
global t,a,i # Global vars
try:
t.cancel() # Tries to cancel Timer from previous code
except:
a = 0 # Reached when code is 1st copy; initializes a.
a += 1 # a++; this is the number of copies thus far.
t = T.Timer(1,d) # Creates, then starts a timer to call function
t.start() # d in 1 second.
def d(): # Prints out the source code; the quine part.
print''.join(c*a for c in i.getsource(f)+i.getsource(d)+"f()")
f() # Calls f()!
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 19 bytes
```
{]W=s"_~"+T):Te*}_~
```
[Try it online!](https://tio.run/nexus/cjam#@18dG25brBRfp6QdomkVkqpVG1/3/z8A "CJam – TIO Nexus")
### How it works
```
{ }_~ Define an anonymous code block (function).
_~ Push a copy, and execute the copy.
]W= Wrap the entire stack in an array and select its last element.
This discards whatever was on the stack before the original
code block, which is needed for subsequent iterations.
s"_~"+ Cast the code block to string, push "_~", and concatenate.
This pushes the stringified source code on the stack.
T):T Push T (initially 0), increment it, and save the result in T.
e* Repeat each character in the stringified source code T times.
```
[Answer]
# [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 66 bytes
*Significant Whitespace be the death of me*
```
[ "[ %q ] F 0 1 + `0 = `. { 0 m } R " ] F 0 1 + `0 = `. { 0 m } R
```
## Explained
```
[ "[ %q ] F 0 1 + `0 = `. { 0 m } R " ] F 0 1 + `0 = `. { 0 m } R #
[ # Pop whatever is already on the stack, if anything.
"[ %q ] F 0 1 + `0 = `. { 0 m } R " # This string contains basically the entire function.
] F # ] F duplicates the string, and then F formats it, which in this case puts the first string into the second at %q, surrounded by qoutes.
0 1 + `0 = # I needed an Incrementer, so I chose 0. 0, is conveniently, pre initilized at 0. And because RProgN is horrifying, you can remap the number functions as they're just more variables. So this increments 0 every time the group is called.
`. { 0 m } R # Replace each character with itself repeated '0' times. Because '0' is an incrementer, each time the script is called, the amount of times the characters are repeated increase.
```
*Good lord I'm a monster...*
[Try it online!](https://tio.run/nexus/rprogn#@x@toBStoFqoEKvgpmCgYKigrZBgoGCrkKCnUA3k5yrUKgQpKOGV/f8fAA "RProgN – TIO Nexus")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~122~~ ~~121~~ 112 bytes
```
s='try:from atexit import*;n+=1\nexcept:n=1;register(lambda:[print(end=c*n)for c in"s=%r;exec(s);"%s])';exec(s);
```
**Try It Online:** [one copy](https://tio.run/nexus/python3#PccxDsMgDADAr6BIUSCdsoL8krYDJU5lqRhke6Cvp1tvu6mwmXzjJa26bDjIHNXexPbENzgejKNgt8hwJME3qaH4T66vM8d7F2LzyCeUncPVxBVHvCisknBg8RrSsuozbP/O@QM "Python 3 – TIO Nexus") **|** [two copies](https://tio.run/nexus/python3#vc0xDsMgDADAr6BIUSCdsoJ4SduBEieyVAyyPZDXk61P6HjTDYmL8uUPrsUkhY5qsLTKugZ6xO1F0DM09RS3wHCiKLD9pvLZk382RlILtMe8kjsqm2yQJokzB@iQrbgwzfJ2y4///sa4AQ "Python 3 – TIO Nexus") **|** [three copies](https://tio.run/nexus/python3#3c0xDsMgDADAr6BIUSCdsoJ4SduBEieyVAyyPZDXk62P6HjTDYmL8uUPrsUkhY5qsLTKugZ6xO1F0DM09RS3wHCiKLD9pvLZk382RlILtMe8kjsqm2yQJokzB@iQrbgwzfJ2y4///o1xAw "Python 3 – TIO Nexus") **|** [four copies, with automatic verification](https://tio.run/nexus/bash#bZFBj9owEIXPza94CqBNFrJqFk6k4VL10FvVHHf3YJwJWEps1za7IMRvp@OAtpcqh2g8nvfefL5O0ATjCGFPME7tlBY9pGkJSkOgUz1Bi4FaNE9JIkXABk2STPCbLHEV58brnTk4BDWQh9Atnw1bpQmij3JW8fEo@OsU9kbDS6dsuCs292/DVwK5DxLvSu@KPwcWeLKn6PbjSPIQbjFvs3a08WN4FTzMIdhDuJm8C6fEtifWN3U6zexouvy/fJ5Gg@8n2SvJaU9wJFoYzi73wgnJIwgGwlpiQxViEWOMaMoFnhdYLpgdVmzX8T/LFGp8raDwDdPzxFwq5HlyTr6Q3BsUGun0bNZTtS4vKTYbTF/UfI4ZVpijfEsuMc/P7vYk9608Q3SOZFigWfxzjQhW@FAMecsYWtIhLsFBWtV1KApH1rhQfHaKmNpzo3NmGIu6QYlnLLG6Xn39ENxpHXsQgY68rBqiwGOl53X5qukoyYa1rsvK0U55ZpP1Yti2Yv1iHePNmFEtH3UeQUgGnvp65iri58t8XqUz/5Y/fJZ/AQ "Bash – TIO Nexus")
### How it works
This uses the standard Python quine: Store the code you want to execute in a variable (as a string); include some logic in that string to print itself, everything before it, and everything after it; then execute that string.
The code that is executed via the string **s** is the following.
```
try:from atexit import*;n+=1
except:n=1;register(lambda:[print(end=c*n)for c in"s=%r;exec(s);"%s])
```
The first line unconditionally imports the [*atexit* module](https://docs.python.org/3/library/atexit.html), which will allow us to register an exit handler. Trying to import the same module multiple times doesn't affect the script in any way. Then it *tries to* increment the variable **n**, to keep track of how many copies of the source code were executed.
The second line is executed only if the first one contains an error. This will be the case in the first iteration, since **n** is still undefined. In this case, we initialize **n** as **1** and register a lambda that performs the actual magic.
The registered exit handler
```
lambda:[print(end=c*n)for c in"s=%r;exec(s);"%s]
```
will be called right before the program finishes. The lambda itself creates the string `"s=%r;exec(s);"%s` – `%r` creates a string representation of the right argument (**s**), which includes everything between the single quotes and the quotes themselves – then iterates over its characters. For each character **c**, we simply print **n** copies of **c**. Passing `c*n` as the named argument `end` to `print` means that no linefeed will be appended.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 68 bytes
```
for c in(s:='for c in(s:=%r)%%s:\n print(end=c)#')%s:
print(end=c)#
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfnJ@SalukpKT0Py2/SCFZITNPo9jKVh2Zo1qkqapabBWTp1BQlJlXopGal2KbrKmsrgkU5EIV@w80KNrQStcwlosLZEQm0AiFaEMdIx3jWKDa1IrUZA2QjVqZOtW1mjDNSjF5StpKukpaRgZAsf8A "Python 3.8 (pre-release) – Try It Online")
## How it works:
* Based on the quine `print((s:='print((s:=%r)%%s)')%s)`
* when repeated multiple time, the code become something like:
```
for c in "string for the quine":
print(end=c)#comment
print(end=c)#comment
print(end=c)#
```
[Answer]
# Perl 5, 107 bytes
```
$_=q[$_=q[S];s/S/$_/;$a++;END{s/./$&x$a/eg;print if$a;$a=0}];s/S/$_/;$a++;END{s/./$&x$a/eg;print if$a;$a=0}
```
Ungolfed:
```
$_ = '...INSERT_SOURCE_HERE...'; # Standard quine
s/INSERT_SOURCE_HERE/$_;
$a++; # Count the number of repetitions
END {
s/./$&x$a/eg; # Interweave
print if $a; # Print...
$a=0; # ...but only once
}
```
[Try it online!](https://tio.run/nexus/perl#@68Sb1sYDSaCY62L9YP1VeL1rVUStbWtXf1cqov19fRV1CpUEvVT060LijLzShQy01QSgQpsDWpJVf//PwA "Perl – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 14 bytes
```
{s"_~"+]:.+}_~
```
[Try it online!](https://tio.run/nexus/cjam#@19drBRfp6Qda6WnXRtf9/8/AA "CJam – TIO Nexus")
### Explanations
```
{s"_~"+]:.+}_~
{s"_~"+ }_~ Basic quine operator.
]:.+ Append each character to corresponding element of the previous result if existed.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 18 bytes
```
`£_›:¥q\`:Ė\`+•`:Ė
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60%C2%A3_%E2%80%BA%3A%C2%A5q%5C%60%3A%C4%96%5C%60%2B%E2%80%A2%60%3A%C4%96&inputs=&header=&footer=) | [Try it Double!](https://lyxal.pythonanywhere.com?flags=D&code=%60%C2%A3_%E2%80%BA%3A%C2%A5q%5C%60%3A%C4%96%5C%60%2B%E2%80%A2%60%3A%C4%96%60%C2%A3_%E2%80%BA%3A%C2%A5q%5C%60%3A%C4%96%5C%60%2B%E2%80%A2%60%3A%C4%96&inputs=&header=&footer=) | [Try it x5!](https://lyxal.pythonanywhere.com?flags=D&code=%60%C2%A3_%E2%80%BA%3A%C2%A5q%5C%60%3A%C4%96%5C%60%2B%E2%80%A2%60%3A%C4%96%60%C2%A3_%E2%80%BA%3A%C2%A5q%5C%60%3A%C4%96%5C%60%2B%E2%80%A2%60%3A%C4%96%60%C2%A3_%E2%80%BA%3A%C2%A5q%5C%60%3A%C4%96%5C%60%2B%E2%80%A2%60%3A%C4%96%60%C2%A3_%E2%80%BA%3A%C2%A5q%5C%60%3A%C4%96%5C%60%2B%E2%80%A2%60%3A%C4%96%60%C2%A3_%E2%80%BA%3A%C2%A5q%5C%60%3A%C4%96%5C%60%2B%E2%80%A2%60%3A%C4%96&inputs=&header=&footer=)
```
` `:Ė # Evaluate the following piece of code on itself:
£ # Store (itself) to the register
_ # Pop
# The previous copy (if there is one) will've left its code on top of the stack; we don't want that, so we pop it
# This exposes the counter to the top of stack
›: # Increment the counter
¥ # Push the code
q # Unevaluate (stringify) it
\`:Ė\`+ # Append an eval (this is the quine bit)
• # Repeat each character (counter) times
# Now [counter, output] is left on the stack
```
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 25 bytes
```
`q\`:Ė\`+$:["21/÷Y∑|_]`:Ė
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60q%5C%60%3A%C4%96%5C%60%2B%24%3A%5B%2221%2F%C3%B7Y%E2%88%91%7C_%5D%60%3A%C4%96&inputs=&header=&footer=)
A quite neat solution that interleaves its code with the previous iteration
```
` `:Ė # Evaluate on itself...
q\`:Ė\`+ # Quine part - uneval, append code to eval
$ # Get the previous code
:[ # If it exists (There's a copy of the code before it)
"21/ # Divide each into 21 pieces
÷Y # Interleave them
∑ # Summate
|_] # Else (If this is the first copy) pop (the 0 on top) leaving the source
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 8 bytes
```
`I!•`I!•
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYEkh4oCiYEkh4oCiIiwiIiwiIl0=) |
[Try it Online!Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYEkh4oCiYEkh4oCiYEkh4oCiYEkh4oCiIiwiIiwiIl0=) |
[Try it Online!Try it Online!Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYEkh4oCiYEkh4oCiYEkh4oCiYEkh4oCiYEkh4oCiYEkh4oCiIiwiIiwiIl0=)
## Explanation
```
`I!•` # push `I!•` to the stack => [ I!• ]
I # quote and prepend => [ `I!•`I!• ]
! # push the len of the stack => [ `I!•`I!• , 1 ]
• # duplicate each char of the string by => [ `I!•`I!• ]
# implicit output
# each time the program repeat, the length of the stack increment and the end become :
! # push the len of the stack => [ `I!•`I!• , `I!•`I!• , 2 ]
• # duplicate each char of the string by => [ `I!•`I!• , ``II!!••``II!!•• ]
# implicit output the top element of the stack
```
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 11 bytes
```
`q‛:Ė+!•`:Ė
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYHHigJs6xJYrIeKAomA6xJYiLCIiLCIiXQ==) |
[Try it Online!Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYHHigJs6xJYrIeKAomA6xJZgceKAmzrElish4oCiYDrEliIsIiIsIiJd) |
[Try it Online!Try it Online!Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYHHigJs6xJYrIeKAomA6xJZgceKAmzrElish4oCiYDrElmBx4oCbOsSWKyHigKJgOsSWIiwiIiwiIl0=)
## Explanation :
```
`q‛:Ė+!•` # push `q‛:Ė+!•` to the stack => [ q‛:Ė+!• ]
: # duplicate the element on top of the stack => [ q‛:Ė+!• , q‛:Ė+!• ]
Ė # pop and execute the element on top of the stack => [ q‛:Ė+!• ]
q # quote => [ `q‛:Ė+!•` ]
‛:Ė+ # add `:Ė` to the top of the stack => [ `q‛:Ė+!•`:Ė ]
! # push the len of the stack => [ `q‛:Ė+!•`:Ė , 1 ]
• # multiply each char by => [ `q‛:Ė+!•`:Ė ]
# implicit output
# each time the program repeat, the length of the stack increment and the end become :
! # push the len of the stack => [ `q‛:Ė+!•`:Ė , `q‛:Ė+!•`:Ė , 2 ]
• # multiply each char by => [ `q‛:Ė+!•`:Ė , ``qq‛‛::ĖĖ++!!••``::ĖĖ ]
# implicit output
```
]
|
[Question]
[
*The shortest code to generate the correct times on the clocks wins.*
You are a seasoned time traveler and have been known to stop at many planets during your journies. Each planet rotates at a different rate and because of this, the length of a day is different than our usual 24-hour day. As a result, the planets use clocks with different numbers of hours. The hours on a clock with *x* hours are arranged similar to ours (1, 2, 3, ... , *x*) with the number rotating clockwise and *x* being at the top.
Additionally, each planet has a different amount of minutes in an hour, and a different number of seconds in a minute. You will be given a starting time and a number of elapsed seconds from which you must determine the ending time.
Input can be taken directly from a file passed as an argument, or as standard input. The first line of input will be the number of clocks you need to process. After that, each clock has three lines of input that contains integers in the following format:
```
x y z
h m s
t
```
The meaning of each letter is below.
>
> x = The number of hours in a day (2 <= x <= 99)
>
> y = The number of minutes in an hour (2 <= y <= 100)
>
> z = The number of seconds in a minute (2 <= z <= 100)
>
> h = The hour of the starting time (1 <= h <= x)
>
> m = The minute of the starting time (0 <= m < y)
>
> s = The second of the starting time (0 <= s < z)
>
> t = The number of seconds that have elapsed
>
>
>
The output must be the ending time for each clock after *t* seconds have passed since the starting time. Your output must be formatted as standard clock time (HH:MM:SS). Numbers should be padded, when necessary, to ensure that all numbers are two-digits.
## Test Cases
---
**Input**
```
2
5 20 10
1 10 5
2633
6 25 5
6 0 3
290
```
**Output**
```
04:13:08
02:08:03
```
---
**Input**
```
1
14 17 11
12 16 10
1530
```
**Output**
```
07:03:00
```
---
**Input**
```
2
8 40 25
3 1 15
10620
14 15 20
1 14 0
-580
```
**Output**
```
05:26:10
14:00:00
```
[Answer]
## Python, 142 characters
```
R=raw_input
for i in' '*input():x,y,z,h,m,s=map(int,(R()+i+R()).split());t=input()+h*y*z+m*z+s;print'%02d:%02d:%02d'%((t/y/z-1)%x+1,t/z%y,t%z)
```
[Answer]
## GolfScript - 50 chars
```
~](;7/{{~+.4$/\4$%])\}3*3<)@\or\+{100+`(;}%':'*n}%
```
The values (H/M/S) are collected by moving them to the front of the stack (`])\`). The hour 'underflow' at 0 is handled with `or`. Zero padding is handled with `100+`(;`, although I suppose `0`\+-2>` is the same length.
[Answer]
# GolfScript 62 60 characters
Edit: I managed to get the array formerly stored in a to reside on the stack, it takes a little extra switching that way though so no major improvement.
```
~](\7/\{(~+[]\{.5$/@@5$%\+@@+}3*;\;(@or\+{'0'\+-2>}%':'*n@}*
```
62 version:
```
~](\7/\{[]:a;(~{+.4$/\4$%a+:a;}3*;;;a(@or\+{'0'\+-2>}%':'*n@}*
1______a2____3_b4_5___6__7____8__9__10_____11_________12____13
```
I'm sure it can be done a lot better, I just couldn't think of anything better.
1: Make an array of all input, pick off the first element, group the rest into blocks of 7.
a/13: Consume the first number from the input to run the loop that number of times.
2: Store an empty array in a.
3: Pick a block of 7 and expand it to 7 individual numbers.
b/8: Run a loop 3 times, once for each of seconds, minutes and hours.
4: Add the last two numbers together, for the first iteration that is seconds and time to shift, for the following it is minutes and hour with the overflow from the previous cycle. Make a second copy of the result.
5: Divide the copy by it's limit to produce the overflow and shift the result back one space.
[Answer]
## J (172/35) 137 99 107
**Now passes all given test cases.**
```
4(1!:2)~LF,~"1([,':',])/"2,"2":"0(10 10#:1 0 0+{.#:{.&{:+{.#.1 0 0-~1&{)"2&(,&}.$~,&3 3&{.&{.)".;._2(1!:1)3
```
172 is the whole thing; 35 is the number of characters I would give if I was really snooty and refused to do the IO as indicated. (I still modified it a little bit; clocks is a function taking a filename meant to be used interactively within J.)
I sure hope this is a lot easier in J than I make it look.
Edit: Figured out how to do better input parsing in J, eliminated charsub, switched to command line invocation & output.
Edit 2: Changed input of central function to 3x3 matrix, eliminated many pesky parentheses, eliminated names
Edit 3: 0-o'clock handled.
Explanation:
My J still isn't great, and IO is a pain as always. So bits of this are loony.
* The verb `1 0 0+{.#:{.&{:+{.#.1 0 0-~1&{` takes a three by three matrix (consisting of the input lines, the last two elements are garbage)
* The h/m/s is gotten with {. (head), the actual time with 1&{ (second element), and the second count with {.&{: (head of tail).
* The verb uses [#.](http://www.jsoftware.com/help/dictionary/d401.htm) to transform the clock time to seconds. (See documenation.)
* It adds the second count and then uses [#:](http://www.jsoftware.com/help/dictionary/d402.htm) to get the 3 element answer.
* The 0 o'clock case is handled by subtracting 1 from the hour before the base change and adding 1 back after. (the two bits with `1 0 0`)
* The rest is input and output, which is really grubby (as always).
* `".;._2(1!:1)3` gets a 3 'column' matrix of the input with 0s in unfilled positions.
* `,&}.$~,&3 3&{.&{.` cuts the first row off the input and shapes the remaining rows into Nx3x3.
* The `"2` modifies the central verb to take the 3x3 cases.
* `10 10&#:` gives 2 decimal digits for each number giving an Nx3x2 matrix. (Getting 0s for padding was a *pain*.)
* `,"2":"0` converts the digits to ASCII (Nx3x2x1) and ravels the last column, giving Nx3x2 again as ASCII.
* `LF,~"1([,':',])/"2` inserts : between each element and appends them (Nx7) and adds a line feed per for (Nx8).
* `4(1!:2)~` prints each row.
[Answer]
## Haskell, 159 characters
```
v(_:x:y:z:h:m:s:t:r)=(w%x+1)&":"$z%y&":"$1%z&"\n"$v$t:r where w=y*z;(%)=mod.div(t+h*w-w+m*z+s)
v _=""
d&c=tail.(shows(d+100)c++)
main=interact$v.map read.words
```
---
* Edit: (207 -> 200) sometimes `divMod` isn't worth it!
* Edit: (200 -> 178) succumbed to not using the elegant `foldr` approach (which works for time systems with any number of components!)
* Edit: (178 -> 164) inlined `f`
* Edit: (164 -> 158) removed unnecessary parentheses
* Edit: (158 -> 160) fixed a bit introduced three edits ago: hours are now correct again
* Edit: (160 -> 159) dropped a call to `tail`
[Answer]
## Ruby, 128 chars
Shamelessly copies from the python one:
```
d=$<.read.split.map(&:to_i);d[0].times{|o|x,y,z,h,m,s,t=d[o*7+1,7];t+=z*(y*h+m)+s;puts ["%02d"]*3*':'%[(t/y/z-1)%x+1,t/z%y,t%z]}
```
[Answer]
## Haskell - 219 necessary characters
```
import Text.Printf
(#)=div
(%)=mod
n?d=(n-1)%d+1
e a n=mapM(\_->a)[1..n]
main=readLn>>=(e$do{
a<-e getLine 3;
let[x,y,z,h,m,s,t]=map read.words=<<a;
w=y*z;e=h*w+m*z+s+t::Int
in printf"%02d:%02d:%02d\n"(e#w?x)(e#z%y)(e%z)})
```
[Answer]
## PHP (241 chars)
Takes input from a file passed as an argument.
```
foreach(array_chunk(array_slice(file($argv[1]),1),3)as$v){list($x,$y,$z)=split(" ",$v[0]);list($h,$m,$s)=split(" ",$v[1]);$e=($v[2]+$s+$z*($m+$h*$y))%($x*$y*$z);$s=$e%$z;$e/=$z;$m=$e%$y;$h=($e/$y)%$x;printf("%02d:%02d:%02d\n",$h?:$x,$m,$s);}
```
And ungolfed:
```
$input = array_chunk(array_slice(file($argv[1]),1),3);
foreach($input as $v){
list($x,$y,$z)=split(" ",$v[0]);
list($h,$m,$s)=split(" ",$v[1]);
$t = $v[2];
$seconds_in_day = $x * $y * $z;
$total_elapsed = $t + $s + $m*$z + $h*$y*$z;
$elapsed = $total_elapsed % $seconds_in_day;
$sec = $elapsed % $z;
$elapsed /= $z;
$min = $elapsed % $y;
$elapsed /= $y;
$hours = $elapsed % $x;
if ($hours == 0) $hours = $x;
printf("%02d:%02d:%02d\n",$hours,$min,$sec);
}
```
And just to note, without sigils (the dollar sign), this comes out to 205 characters.
[Answer]
## Java, ~~486~~ 371 characters
Ungolfed version: <http://pastebin.com/6LiTdGyi>
This gives the same output as in the provided examples.
But I disagree on that behavior: a clock does not have as many numbers as there are hours in a day: it has half of them.
Meaning that if you add 3600 seconds to 12:50:12, it should print 01:50:12, not 13:50:12 (in our standard 24/60/60 system).
I handled that in my code but commented it out in my solution for it to match the examples.
Of course if you consider this, then the input times could be considered ambiguous unless you add some AM/PM marker.
But in any case, the puzzle has an inconsistency: if 00 hours should be replaced by x, then hours > (x/2) should be replaced by hours - (x/2).
Edit:
Golfed version:
```
import java.io.File;import java.util.Scanner;public class U{static int i(Scanner s){return
s.nextInt();}public static void main(String[]g)throws Exception{Scanner s=new Scanner(new File(g[0
]));int n=i(s);while(0!=n--){int J=i(s),K=i(s),L=i(s),P=(i(s)*K*L+i(s)*L+i(s)+i(s))%(J*K*L);System.
out.println(String.format("%02d:%02d:%02d",(0==P/L/K%J)?J:P/L/K%J,P/L%K,P%L));}}}
```
[Answer]
## Bash - 189 characters:
```
read n
for((i=0;i<n;i++));do
read x y z
read h m s
read t
R=$(((s+m*z+h*y*z+t)%(x*y*z)))
H=$((R/y/z))
R=$((R-H*y*z))
M=$((R/z))
printf"%02d:%02d:%02d\n"$((((H-1)%x+x)%x+1))$M$((R-M*z))
done
```
[Answer]
## PHP, ~~229~~ 228 characters
```
<?$v=file($argv[1]);while(++$i<$v[0]*3){list($x,$y,$z)=split(" ",$v[$i++]);list($h,$m,$s)=split(" ",$v[$i++]);$s=($e=($v[$i]+$s+$m*$z+$h*$y*$z)%($x*$y*$z))%$z;$m=($e/=$z)%$y;printf("%02d:%02d:%02d\n",($e/$y)%$x?$e%$x:$x,$m,$s);}
```
File must be passed into the script as an argument
**Ungolfed:**
```
<?php
$v = file($argv[1]); // Automatically break the file into an array by line
while(++$i < $v[0]*3){ // Loop for every three lines
list($x, $y, $z) = explode(" ", $v[$i++]); // Break apart the first line by space
list($h, $m, $s) = explode(" ", $v[$i++]); // Break apart the second line
/*
Add the starting time to the total number of seconds that have passed
Divide by total amount of seconds in a day
*/
$time = ($v[$i] + $s + $m * $z + $h * $y * $z) % ($x * $y * $z);
$seconds = $time % $z; // Get the number of seconds
$minutes = ($time /= $z) % $y; // Remove the end amount of seconds, then get the minutes
/*
Remove the end amount of hours
Determine how many hours there would be
If the number is zero, then output the max hours
If the number is not zero, output the amount of hours left
*/
$hours = ($time / $y) % $x? $e % $x : $x;
// Display the time in the correct format
printf("%02d:%02d:%02d\n", $hours, $minutes, $seconds);
}
```
**Changelog:**
229 -> 228: No need to set time remaining while performing division on the hours
[Answer]
## Bash, 139 characters
```
read n
while((n--));do
read x y z;read h m s;read t
((t+=z*(y*h+m)+s,a=(t/y/z-1)%x+1,b=t/z%y,c=t%z))
printf %02d:%02d:%02d\\n $a $b $c
done
```
[Answer]
## Scala 184 chars:
```
object C extends App{val r=new java.util.Scanner(System.in)
def n=r.nextInt
for(j<-1 to n;h=n;m=n;s=n;x=n;y=n;z=n;t=n;d=(x*m+y)*s+z+t){printf("%02d:%02d:%02d\n",d/(m*s)%h,d/s%m,d%s)}
}
```
In conflict to the rules, I claim, that for
```
14 15 20
1 14 0
-580
```
The output shouldn't be
```
14:00:00
```
but
```
00:00:00
```
and that's what my code produces. Please show me a clock which displays 24:00:00 on earth instead of 00:00:00 - maybe 24:59:59. Or do you expect the sequence:
```
23:59:59
24:00:00
00:00:01
```
instead of
```
23:59:59
00:00:00
00:00:01
```
[Answer]
# [Python 2](https://docs.python.org/2/), 137 bytes
```
lambda T:["%02d:%02d:%02d"%((s/z/y%x,x)[s%x<1],s/z%y,s%z)for x,y,z,h,m,s,t in[T[i:i+7]for i in range(1,len(T),7)]for s in[s+m*z+h*y*z+t]]
```
[Try it online!](https://tio.run/##dVHbboMwDH0eX2ExIZHWVZNwa6PxF31jPHQqrEgtrQiTgJ9nNtBKm1QUJ8e3c0xy79vzrdZjmX6Ol@P163SEg8lcT@qTeW6u5/t2O2x7r8NOZNbrPlSOFPF6tN4gylsDHfY44BmvaLGFqs4OWWWqdZJzsqIANMf6u/AVXoraPwhMxJSyXGvX19WwPq962ts8H9vCthZS8B2gz4dMI0QIWiIotvngSBwECDGBaPIJUYJCei9zhMyVoVGBkTsXwZWagJGBm4PABzNzhWQJGWNSUvEiEwULSUJdRso/jVS4QwjlrB3MU0XcGU9zhrOrl3nDabJNtFsoI6NjoyTPpULi/k/P/0A9sZztuTbqRUK@iKtJTwcm2tNiPf3Q4zuRE1ZuLhzhOPwifPkITWF/LvyQk2@N83ZvqrqF0mdfvOMDpelcOv4C "Python 2 – Try It Online")
Only slightly shorter than the [other Python answer](https://codegolf.stackexchange.com/a/1703/73368), but takes a different route to get there.
**Ungolfed Explanation:**
```
def f(T):
# ignore first list element, split list into even chunks of length 7
for i in range(1, len(T), 7):
# get variables for sublist
for x, y, z, h, m, s, t in [T[i:i + 7]]:
# get total time in seconds, inside a list so that we can use list comprehension
for s in [s + m*z + h*y*z + t]:
# split total time into parts
# seconds: convert seconds to minute, take remainder
sec = s % z
# minutes: convert seconds to minutes (discard remainder), convert minutes to hours, take remainder
min = s / z % y
# hours: convert seconds to minutes (discard remainder),
# convert minutes to hours (discard remainder),
# convert hours to days, take remainder
# if seconds are evenly divisible by total hours, use number of hours in day instead ("midnight")
hr = (s / z / y % x, x)[s % x < 1]
print "%02d:%02d:%02d"%(hr, min, sec)
```
[Answer]
## Haskell (~~815~~ 624 chars non-golfed, blank lines excluded)
~~Mine prints 00:00:00 instead of 12:00:00 or similar for "midnight"-like times.~~ Edit: changed that.
```
main = readFile "in.txt" >> mapM_ print . times . map (map read . words) . tail . lines
times [] = []
times ([x,y,z]:[h,m,s]:[t]:xs) = Time x y z h m s +++ t : times xs
data Time = Time {x,y,z,h,m,s :: Int}
hr t | h t == 0 = x t | otherwise = h t
instance Show Time where show t = pad2 (hr t) ++ ':':pad2 (m t) ++ ':':pad2 (s t)
pad2 x | x < 10 = '0':show x | otherwise = show x
t +++ ss | ss < 0 = t +++ (ss + x'*y'*z') | otherwise = Time x' y' z' h' m' s'
where (x',y',z') = (x t, y t, z t)
(ms, s') = (s t + ss) `quotRem` z'
(hs, m') = (m t + ms) `quotRem` y'
(_, h') = (h t + hs) `quotRem` x'
```
Could've abstracted a few things more, but w/e. It completely ignores the first line of the input file, and generally screams at you for improperly-formatted files.
]
|
[Question]
[
*While implementing polynomial multiplication in [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md) I found the following interesting operation on strings*
To compute the convolution of two strings (for instance `Hello` and `World`) first combine all pairs of letters with indices that add up to the same number
(ordered by the index of the first element)
```
0 -> "HW"
1 -> "Ho" "eW"
2 -> "Hr" "eo" "lW"
3 -> "Hl" "er" "lo" "lW"
4 -> "Hd" "el" "lr" "lo" "oW"
5 -> "ed" "ll" "lr" "oo"
6 -> "ld" "ll" "or"
7 -> "ld" "ol"
8 -> "od"
```
and then concatenate all these letter pairs into a single string.
Which in this example gives `HWHoeWHreolWHlerlolWHdellrlooWedlllrooldllorldolod`.
Your task is to implement this operation:
Write a program of function that takes two strings as input and outputs their convolution.
## Examples:
```
"" "Empty" -> "" // empty string
"Hello" "World" -> "HWHoeWHreolWHlerlolWHdellrlooWedlllrooldllorldolod"
"Code" "Golf" -> "CGCooGCloodGCfoldoeGofdleodfelef"
"123" "ABC" -> "1A1B2A1C2B3A2C3B3C"
"split" " " -> "s p l i t " // note the trailing whitespace
"+-" "12345" -> "+1+2-1+3-2+4-3+5-4-5"
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution (per language) wins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 62 bytes
```
a=>b=>a.map((c,i)=>b.map(d=>L[i]=[L[i++]]+c+d),L=[])&&L.join``
```
[Try it online!](https://tio.run/##JcexCsMgEADQf8kQPEzvB8o5d3DvIAexaorBeiEp/X0j6fLgrf7nj7Dn7XurElNbqHkyLzIeP35TKkwZ@q9EMtZlJtfVmlkHHWGy5BjG0eIquc5zC1IPKQmLvNWiHCIOj1SKDAz/PWUvsQ/u7QQ "JavaScript (Node.js) – Try It Online")
[Answer]
# APL (NARS2000), 7 glyphs
```
,/⍞,⍡,⍞
```
* `,/` Concatenate
* `,⍡,` the convolution by concatenation and concatenation
* `⍞` of a string input
* `⍞` and another string input
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 10 bytes
```
+þŒdṙL{UFṚ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCIrw77FkmThuZlMe1VG4bmaIiwiIiwiIixbIistIiwiXCIxMjM0NVwiIl1d)
This can almost certainly be about half the length; I'll get back to this when I can.
## Explanation
```
+þŒdṙL{UFṚ Main Link
+þ Outer product table with sum
Œd Matrix antidiagonals
ṙL{ Rotate left by the length of the left string
U Reverse (vectorizing)
F Flatten
Ṛ Reverse the whole list
```
The reason I use `+þ` instead of just cartesian product is that cartesian product in Jelly returns a flat list of pairs.
## Step-by-step
Let's start with `"+-` and `"12345"`. First, we take the outer product table with sum which gives us `[['+1', '-1'], ['+2', '-2'], ['+3', '-3'], ['+4', '-4'], ['+5', '-5']]`. Normally, in Jelly, strings are arrays of their characters, but using `+` breaks that. This usually causes problems but in this case actually helps as getting the matrix antidiagonals would not work correctly if this had depth 3.
Then, we take the matrix antidiagonals which start at the main anti-diagonal and go left, which gives `[[['-', '1'], ['+', '2']], [['+', '1']], [['-', '5']], [['-', '4'], ['+', '5']], [['-', '3'], ['+', '4']], [['-', '2'], ['+', '3']]]`. For some reason, this operation turns the strings back into normal Jelly strings.
We then rotate to the left by the length of the left string, which puts the pair containing the first character in each string at the end, giving us `[[['-', '5']], [['-', '4'], ['+', '5']], [['-', '3'], ['+', '4']], [['-', '2'], ['+', '3']], [['-', '1'], ['+', '2']], [['+', '1']]]`.
Now, all of our pairs are in inverse order, so we want to reverse the whole thing. However, because the pairs are at depth 2, we would also need to reverse each sublist. There are thus two ways to do this:
1. We can reverse each pair and then flatten the whole thing and reverse it, removing the need to worry about depth. This is the solution Jonathan Allen came up with in his golf. We do this with `UFṚ` (`UFU` would do the same thing).
2. We can reverse each sublist and then reverse the whole list, and the depth does not matter because Jelly will smashprint all of the characters onto one line at the end. We do this with any of `Ṛ€Ṛ`, `ṚṚ€`, or `Ṛ⁺€`.
## Credits
* -1 byte thanks to Jonathan Allan using `+þ` instead of `+€Ɱ`
* -2 bytes thanks to Jonathan Allan by changing the way the ordering is done.
[Answer]
# [J](http://jsoftware.com/), 17 14 12 10 bytes
```
[:;]/.@{@;
```
[Try it online!](https://tio.run/##dY29CsIwEIB3n@JwiZIm/V@iQlGQDOLgkkGcTETl4KTt5sPHa6ujHPfDx3d3zzjX4gYbAwISyMBwKg2702Efz2Z1SXXzblZxOTtuNTA4m3WzSNJlqpN5ls7C9U4gbEAkATcQjlr04osFKDNU5j9knaXgbBsIncXQ4tA9r/NELnjkiQi5D4cIyU9H/nzo4AUID@hh0roXPvpR4/g6MpeFymWpClmpUtaqUvVkSzWqeVFWTOIH "J – Try It Online")
J's `/.` builtin is tailor made for this...
* `{@;` Create a table of all pairs
* `]/.@` Get each diagonal
* `[:;` Flatten and unbox
[Answer]
# APL (dzaima\APL), 7 glyphs
```
∊⊂⍁⍤∘.,
```
* `∊` flatten into a list
* `⊂⍁` every diagonal
* `∘.,` of the table of all pairs of the input
[Answer]
# [Scala](http://www.scala-lang.org/), 118 bytes
Golfed verson. [Try it online!](https://tio.run/##TZBRT4MwFIXf@RUnhCxtBoub@rKNJXMx@qBPxvhgfEAoW7GjjNYlG@G3Y6FgaNL09jvn9t5bFUciauR3xmKN14jnqBwgYSmO5kKicq@W2JZldPl80yXP9190ifeca4SdEzhHApoprQx54UqTjgLEdRFs4D4eC31xqf@Pn5kQ0mofshTJWNvJhFnpSYp0rMwXt1bYPuzGXBWCa6tgzKeBhSbv7t6lHadOd3TdzlJZsig@9FMAcaQYiJr7UAuKcNNjoDBja5ET5Zrlqbmp46mFfd2rYpmfpTizIbNuXbZc7bTbaT9ocC0Jsd/o24OGmz5A2JDCPxlQEdNadV0HN/jNNRcoZoLle32YnvpgxVtRS1xXWXgN@Iqn4OvBNplk68FZXzgTCZRptCCc1l51Ipnpkc6OP7Zw3dTNHw)
```
(p,q)=>{(for{z<-0 until p.length+q.length;i<-0 to z;j=z-i;if i<p.length&&j<q.length}yield s"${p(i)}${q(j)}").mkString}
```
Ungolfed version. [Try it online!](https://tio.run/##XVDRasIwFH33Kw5FJGFW1m57ERWcjO1hexpjD2MPWZtqXNpIbxRE@u1d2rRSVii5Oefck3suJUKLujY/e5lYvAlV4DICUpkhdxcmyi3NsS5Lcf56t6Uqtt98jo9CWSxbJXASGlaSJYe8KrKsRQEWBAhXCJ7ygz0HfHqFX6TWxnOfptTpkNuYVHrq2ehsyETxnSfWj5shTgetrGcwxG9CD7q@@4eAtzgftUc77SwzpRTJrksBJIIkGEVTUMyxXHUwcHCxrS4YBe4bU@TeGVPs3ceXxBQno0@y76walX@uGjV/t86Bbg6/ykbf17wvrntlbsDrcHTMsQhxi2NhlQZFMy2Lrd3hxnl0dSdVXmhN09Rhe@faWIRQvSprhAOjycSpFv/cKpyV1CnIBaWIKV65M2Z7l5LP8l8/cZuyGtX1Hw)
```
object Main {
def main(args: Array[String]): Unit = {
val tests = List(
("" -> "Empty"),
("Hello" -> "World"),
("Code" -> "Golf"),
("123" -> "ABC"),
("split" -> " "),
("+-" -> "12345")
)
tests.foreach {
case (s1, s2) =>
println(s""""$s1" "$s2" -> "${convolve(s1, s2)}"""")
}
}
def convolve(s1: String, s2: String): String = {
(for {
sum <- 0 until s1.length + s2.length
i <- 0 to sum
j = sum - i
if i < s1.length && j < s2.length
} yield s"${s1(i)}${s2(j)}").mkString
}
}
```
[Answer]
# [Haskell](https://www.haskell.org), ~~72~~ 66 bytes
*-6 bytes thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)*
```
import Data.List
f=(map snd=<<).sortOn(sum.map fst).mapM(zip[0..])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY4xDsIwDEX3nsKKGFoJIkaGZkEMGUCMGaoOkZKICDeuknTpVVi6IM7EbUgFTP_J3_7fj9dNp7tFXJbnlN3u8D76YaSY4aSz5mefcuVEPegRUjCibRueinsNdZoGvo5dys0Kl3r2Y7fnvG9-SXoGAQ46Jks-sS0wRREN66tB-1C8MfqQYQNlTwCTSpJVMlpCJdFGXNWU00KkrMFCRFh0TSEkw75F_9c_)
[Attempt This Online!](https://ato.pxeger.com/run?1=NY6xCsIwEIb3PsURHFrQ4OjQgINDBsUxQ-kQSILBa64k6dJXcekiPpNvY4o6_R_33_3_PV43ne4WcVmeU3a7w_voh5FihpPOmp99ypUTgx4hBSPalqfiXUOdpoGvU5dys8Klnv3Y7Tnvm1-OnkGAg47Jkk5sC0xRRMP6atA-FG-MPmTYQNkTwKSSZJWMllBJtBFXNeW0EClrsBARFl1TCMmwb9H_8Q8)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 30 bytes
```
{,/+l@'d\<,/+\:/!'d:#'l:(x;y)}
```
[Try it online!](https://ngn.codeberg.page/k#eJw1j1FrgzAQx9/zKWKERUmdi7YvdmzVMLSvfXEDYStLbIVbT1S2lbF+9l2RBcL9L/x+F67Nfhaxgo20zT2FJos9aTNfQhZ8r8/hL2MxE4KLp49+OgsePXDq/k8cc3d95+M0dKcDE5UDQKJrHMDOdFVX6OpqcAh1BW6Aa7XEUcLaWaCECFSvDgJawYRB62hMidDOU0xpEEtDii1NSzi6ElsLDm3rwLXk6CQlJS/MbOhcF0muTVKkeWLSIjXEjD10E1F8Zkbec+Adn6inXU44OT4d6Q77Dmgh/nXsJjf2+3fHhIpIo0+Wq1lWWiWRVmmUqGWUqlW0jFaCNSx4Xr+sd2EWJJ7nZ6GvRCNEI7cb/XpzCbaPCylF3DQilJ6/ze6yt/1w+OSa7S7trVRXO2R/xZ5tVA==)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ẉp/SÞị"€
```
A full program that accepts a pair of lists of characters and prints the result.
**[Try it online!](https://tio.run/##y0rNyan8///hro4C/eDD8x7u7lZ61LTm////Stq6SjoKSoZGxiamSgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hro4C/eDD8x7u7lZ61LTm/@F2IBn5/390tJKSjoKSa25BSaVSrA6XQrSSB1BHPkgwPL8oJwUq6JyfkgoSc8/PSYMKGRoZg0QcnZyhAsUFOZklICEFqIC2LogHVGdiChKJBQA "Jelly – Try It Online").
### How?
Make a list of all of the pairs of indices of the strings in row-major order, sort these by their sums and then use each of these pairs to index back into the two strings respectively. The result is implicitly smashed together and printed.
```
Ẉp/SÞị"€ - Main Link: pair of lists of characters = [A, B]
Ẉ - length of each -> [len(A), len(B)]
/ - reduce by:
p - Cartesian product
-> [[1, 1], [1, 2], ..., [1, len(B)], [2, 1], ..., [len(A), len(B)]]
Þ - sort by:
S - sum
€ - for each:
" - zip-wise:
ị - index into {[A, B]}
- implicit, smashing print
```
[Answer]
# [Python](https://www.python.org), 78 bytes
```
f=lambda a,b,i=0:a and''.join(sum(zip(a,b[i::-1]),()))+f(a[b==b[:i+1]:],b,i+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3_dJscxJzk1ISFRJ1knQybQ2sgKy8FHV1vaz8zDyN4tJcjarMAg2gZHSmlZWuYaymjoampqZ2mkZidJKtbVK0Vaa2YaxVLEiztqEm1NTegqLMvBKNNA2ljNScnHwlHaXy_KKcFCVNTS64jLYuUNjQyNjEFEW4uCAnswQoo4Ai6pyfkgoUdM_PSUMRB4ql5haUVKIIOjo5u7i6QU0HykActWABhAYA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
⭆⁺θη⭆θ⭆Φη⁼κ⁺μξ⁺λν
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaATklBZrFOooZGjqKCBEC5E5bpk5JalFGhk6Cq6FpYk5xRrZOgpgbbk6ChWamppQXo6OQp4mCFj//@@cn5LK5Z6fk/ZftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ First input
⁺ Concatenated with
η Second input
⭆ Map over characters and join
θ First input
⭆ Map over characters and join
η Second input
Φ Filtered where
μ Inner index
⁺ Plus
ξ Innermost index
⁼ Equals
κ Outer index
⭆ Map over characters and join
λ Inner character
⁺ Plus
ν Innermost character
Implicitly print
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 47 bytes
```
Lw$`(.).*¶.*(.)
$.`*¶$.>`*¶$1$2
O$`(¶+).+
$1
¶
```
[Try it online!](https://tio.run/##K0otycxLNPyvqhGcwPnfp1wlQUNPU0/r0DY9LSCDS0UvAchW0bMDU4YqRlz@QBWHtmlr6mlzqRhyHdrG9f8/p2tuQUkll0dqTk4@Z3h@UU4Kl3N@Siqne35OGpehkTGno5MzV3FBTmYJpwKXti4nUMjEFAA "Retina – Try It Online") Takes input on separate lines but link is to test suite that splits on tabs for convenience. Explanation:
```
Lw$`(.).*¶.*(.)
$.`*¶$.>`*¶$1$2
```
List the Cartesian product of the two strings, but prefix each result with a number of newlines corresponding to the sum of the indices. (Results after the first gain an extra newline but this doesn't affect the overall sort order.) If I didn't have to handle empty strings then the `L$` could be removed to save two bytes.
```
O$`(¶+).+
$1
```
Sort each pair of characters by the sum of their original indices.
```
¶
```
Join everything together.
[Answer]
# Python3, 121 bytes:
```
E=enumerate
def f(x,y):
d={}
for i,a in E(x):
for j,k in E(y):d[i+j]=d.get(i+j,'')+a+k
return''.join(d[i]for i in d)
```
[Try it online!](https://tio.run/##VcxLCsIwEIDhfU4xdNOExoIvEKELLUVv4EK6KCTR1JiEmEKLePaaVBC6G75/Zuzg70avd9aNY1Vw3T25azxHjAsQuKcD2SNgxfuDQBgHkjYgNVS4jz5RSx8/CqvsKrO2Llh@4x6HkaYpyZrsgcBx3zmdpnlrpMZhr57exUtGRuuk9ljgJKGQVE/rh4QQ9NczV8rEdDFOsVkqDeOxnIwSs7BcraMfjuWMX1ZJHwPMOFtECzebbfDxCw)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 74 bytes
```
->a,b,*r{a.size.times{|i|b.size.times{r[k=i+_1]=[*r[k],a[i],b[_1]]}}
r*''}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY1NCsIwGET33ymyEITaFvzFTQUtongBFzFIYlMbTE1II6JtT-KmoB7K29iigrt5D2bm9jAndqnucbB5nmzsjV8rb0Jd5jomp34mrty3IuVZXoiC_bPBh0B0tl0SYKfOxKVYEJfh2pCyBOO02-V3cXROhORoz20GiKIAtbb-LlGpBsRqavyPNYpx_U6AH6NPu3oNYZ5qe4Ell1LBWhkZQagiDgslY-j2-jCdhZBpKSwg6HiNGgw_7Tc)
[Answer]
# C, ~~123~~ 121 bytes
Very naive approach: 3 nested loops.
```
k,n;main(int c,char**v){char*a,*b;do for(c=n++,a=v[1];*a;a++)for(k=c--,b=v[2];*b;b++)k--||printf("%c%c",*a,*b);while(k);}
```
Compile, then run the executable with the two strings as parameters.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
€.ā`âΣ€θO}€€н˜
```
Input as a pair of strings; output as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//UdMavSONCYcXnVsMZJ7b4V8LpIDowt7Tc/7/j1bySM3JyVfSUQrPL8pJUYoFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R01r9I40JhxedG4xkHluh38tkAKiC3tPz/nv9ahhmdLh/Uo6/6OjlZR0lFxzC0oqlWJ1opU8UnNy8oEi4flFOSlgEef8lFSggHt@ThqYb2hkDOQ6OjmDecUFOZklQL4CmKetC2QCFZiYKsXGAgA).
**Explanation:**
```
€ # Map over both strings in the (implicit) input-pair:
.ā # Enumerate the string, pairing each character with its (0-based) index
` # Pop and push both lists separated to the stack
â # Cartesian product the two together, creating pairs
Σ # Sort this list of pairs of pairs by:
€θ # Map over both pairs:
# Keep the last item of the inner-most pair (the indices)
O # Sum them together
}€€ # After the sort-by: nested map over each inner-most pairs:
н # Keep the first item (the characters)
˜ # Flatten the list of pairs of characters
# (after which it is output implicitly as result)
```
[Answer]
# [**T-SQL**](https://learn.microsoft.com/en-us/sql/t-sql/language-reference?view=sql-server-ver16), 323 bytes
`DECLARE @n BIGINT=1;SELECT STRING_AGG(COALESCE(SUBSTRING(a,Y.value,1)+SUBSTRING(b,Z.value,1),''),'') WITHIN GROUP(ORDER BY Y.value+Z.value,Y.value)FROM(VALUES(@a,@b)) X(a,b)JOIN GENERATE_SERIES(@n,LEN(@a+'x')-1) Y ON LEN(@a+'x')>1JOIN GENERATE_SERIES(@n,LEN(@b+'x')-1) Z ON LEN(@b+'x')>1RIGHT JOIN (SELECT 1 AS c) W ON 1=1`
Explanation:
```
DECLARE @a VARCHAR(MAX) = '123'; --Input string @a
DECLARE @b VARCHAR(MAX) = 'ABC'; --Input string @b
DECLARE @n BIGINT=1; --GENERATE_SERIES requires all arguments have the same integer data type. LEN of a VARCHAR(MAX) returns BIGINT, need the value 1 (INT by default) to also be BIGINT.
--This query shows the result set that STRING_AGG would act upon, in the correct order. (The final column would be aggregated)
SELECT
Y.value --The 1-indexed index of string @a. NULL if either string is empty
, Z.value --The 1-indexed index of string @b. NULL if either string is empty
, Y.value+Z.value --The sum of indicies
, SUBSTRING(a,Y.value,1) --Single character of @a at the Y.value index. NULL if either string is empty
, SUBSTRING(a,Y.value,1) --Single character of @b at the Z.value index. NULL if either string is empty
, COALESCE(SUBSTRING(a,Y.value,1)+SUBSTRING(b,Z.value,1),'') --The concatenation of a character from @a and @b, empty string if either is NULL.
FROM(VALUES(@a,@b)) X(a,b) --A single row table with each input string as its own column
JOIN GENERATE_SERIES(@n,LEN(@a+'x')-1) Y --GENERATE_SERIES generates values from start to stop (With default step of 1). LEN function ignores TRAILING whitespace, so we concat a charcater and substract 1 from length.
ON LEN(@a+'x')>1 --INNER JOIN ensures an empty result set if the length of the string is 0, otherwise a cartesian product.
JOIN GENERATE_SERIES(@n,LEN(@b+'x')-1) Z --GENERATE_SERIES generates values from start to stop (With default step of 1). LEN function ignores TRAILING whitespace, so we concat a charcater and substract 1 from length.
ON LEN(@b+'x')>1 --INNER JOIN ensures an empty result set if the length of the string is 0, otherwise a cartesian product.
RIGHT JOIN (SELECT 1 AS c) W ON 1=1 --RIGHT JOIN ensures we always have at least one row. As STRING_AGG on an empty result set will result in NULL not an empty string.
ORDER BY Y.value+Z.value,Y.value -- The order with which the final concatentation should take place: sum of indicies, then index of first string.
```
Returns:
[](https://i.stack.imgur.com/vcv6B.png)
This will only work on SQL Sever 2022 or later (probably on Azure Database etc...) due to the compatibility of the new function, GENERATE\_SERIES.
]
|
[Question]
[
[Prefix normal words](https://arxiv.org/abs/1805.12405) arise in the context of binary jumbled pattern matching. A binary word \$w\$ consisting of \$0\$s and \$1\$s is said to be *prefix normal* \* if, among all of its substrings, none contains more \$1\$s than the prefix of \$w\$ of the same length does. In other words, if \$w\$ contains \$n\$ \$1\$s then it is prefix normal if, for all \$m\le n\$, the shortest (or equal shortest) substring containing \$m\$ \$1\$s is a prefix.
For example, \$w=\color{red}{11010}\color{blue}{11011}00100\$ is not prefix normal because it has a substring of length 5 (highlighted in blue) that contains four \$1\$s, whereas its prefix of length 5 (red) only contains three \$1\$s. If we flip the first \$0\$ to \$1\$, however, then the resulting word (\$111101101100100\$) is prefix normal.
### Task
Your task in this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge is to write a program or function that decides whether a binary word is prefix normal.
You may take input in any sensible format (e.g. string, numeric, list of characters/digits), which extends to using any pair of characters/digits instead of \$0\$ and \$1\$ if you wish.
Output/return a consistent value for every input that is prefix normal and another consistent value for every input that is not.
### Test cases
**Prefix normal**
```
00000
1101010110
111101101100100
11101010110110011000
1110010110100111001000011
```
**Not prefix normal**
```
00001
1011011000
110101101100100
11010100001100001101
1110100100110101010010111
```
---
\* Strictly, *prefix normal with respect to \$1\$*.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~9~~ 7 bytes
```
ṡJ§Ṁ€⁼Ä
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuaFKwqfhuYDigqzigbzDhCIsIj3igJ0xw4cpWSIsIiIsWyInMDAwMDAnLCcxMTAxMDEwMTEwJywnMTExMTAxMTAxMTAwMTAwJywnMTExMDEwMTAxMTAxMTAwMTEwMDAnLCcxMTEwMDEwMTEwMTAwMTExMDAxMDAwMDExJywnMDAwMDEnLCcxMDExMDExMDAwJywnMTEwMTAxMTAxMTAwMTAwJywnMTEwMTAxMDAwMDExMDAwMDExMDEnLCcxMTEwMTAwMTAwMTEwMTAxMDEwMDEwMTExJyJdXQ==)
-2 bytes thanks to Unrelated String
```
ṡJ§Ṁ€⁼Ä Main Link
ṡ Take overlapping slices of length(s)
J [1, 2, ..., length]
§ Take the sum of each slice of each length
Ṁ€ Is the maximum sum for each length
⁼ Equal to
Ä The cumulative sum of the original list?
```
[Answer]
# [Haskell](https://www.haskell.org/), 57 bytes
```
g x=x!x
p!s=p==[]||sum p>=sum s&&init p!tail s&&g(init p)
```
[Try it online!](https://tio.run/##fVBBCsMgELz7is0lJCBFH2B/0BeIFA8hlapIteAhf7dJTWpMSxGVnZ3Z2d2b9PdB65RGiCw2EbnGM8cYF9PknwbcmS2fb1tlVQDXBKn0Eo5dBvoUBh88MOCc4PUIBIA5xXQOyqX7BC3g@mZaRTmod0R6NCoVipDgOkM2LMs@wFblaPNjjj/tkp1v1WQRfs9GqonqIpsXFQIhI5Wdl2yku1yhcw9lw2ns4b389AI "Haskell – Try It Online")
---
# [Haskell](https://www.haskell.org/), 66 bytes
A bit longer, but actually runs in reasonable time.
```
g x|k<-[1..length x]=and[h x>=h(drop n x)|h<-(sum.).take<$>k,n<-k]
```
[Try it online!](https://tio.run/##fVBBDoMgELz7ij30oAkSuKM/6AsIaUgkYlBqCk08@HdqqhaxTUMgy@zOzO5q6Yzq@xBamGbDSk4x7pVtvYZJVNI2fAnqSufN4z6ChamYNStz9xxwgb00il1qgywrjQheOe@gAs4J2o7IABCniC6feOkxQSO4vWtZUnJiHwrp2SgqRCJBaYbs2Er7ALvK2ebHHH/aJQffpMlI/J6NJBOlIrsXFSLLBtnZZcmDHK83yMdHZz1uC3gvP7wA "Haskell – Try It Online")
[Answer]
# JavaScript (ES6), 57 bytes
Expects an array of binary digits. Returns *false* for prefix normal, or *true* for not prefix normal.
```
a=>a.map(v=>a=v-~a).some((p,i,a)=>a.some(q=>q-a[~i--]>p))
```
[Try it online!](https://tio.run/##TY4xb8MgEIV3fgXKEk6KEcwV3tqxS8Ykw9XBKRUGDI6lqGr@umsIqQpI9@6944MvnDF10YSpcf6sl14tqFrkAwY2r0LNzR2BJz9oxsLO7BByXPpRtWODh7tpmlMbAJaox6uJmm37tAUeNZ7fjNX7m@uYAD75/RSNu7AVF6yZ2OboNsB7H1@x@2SJqpZ@E0qtnihSRQ@c83QqP3m/Dh86wsuadt4lbzW3/sJ6hgDkBxaRF5FSlC2zlEWsZ3VK/8yKJUU1q5etx2hWpBTyN/5E/@cVnKioEtVHHjBRB/IV@Qs "JavaScript (Node.js) – Try It Online")
### How?
We first compute the cumulative sums of the incremented input values:
```
a.map(v => a = v - ~a)
```
(Using `a = v - ~a` allows us to re-use `a[]` to compute the sum, which is two bytes shorter than allocating a specific variable. That's the only reason why the values are incremented.)
For instance:
```
1, 0, 1, 1, 0, 1, 1, 0, 0, 0
=> 2, 1, 2, 2, 1, 2, 2, 1, 1, 1
=> 2, 3, 5, 7, 8,10,12,13,14,15
```
We then test whether there's some pair \$(i,j)\$ with \$j>i\$ such that \$a\_j-a\_{j-i-1}>a\_i\$.
```
.some((p, i, a) => a.some(q => q - a[~i--] > p))
// ^ ^ ^
// a[j] a[j-i-1] a[i]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~54...44~~ 41 bytes
```
(l=Most@l+#-(t={##2})&@@t)&/@(t=l=#)0&
```
[Try it online!](https://tio.run/##TY1NCsIwEIX3OYUkUFq0mLiPBMSlINRd6SKUVgPpD80sBLFn8DKeyyPEJk3FTGBevnnz0ki4VY0EVUpbcxtrfuoMCL0maQz8QcjumURCQBJtxQQ0J8nn9aaRPQ@qhZyk@1qQIhqzUrbjpTve@6EyRnWtONzkIEuoBiMymMzXrNcKckzdQYxRX8xJ5sV0J@Lfy8wjRgMMzKHZ6hTyDf3sS/R/no@jIcqPwidzGA0Gt8LwZoURLuwX "Wolfram Language (Mathematica) – Try It Online")
`` is `VectorGreaterEqual`.
```
(l=Most@l+#-(t={##2})&@@t)&/@(t=l=#) get all prefix differences by:
(t=l=#) l: difference list, t: input list
/@ over input length:
(l=Most@l )& drop last element of l
+#- {##2} &@@t foreach, add next in prefix, subtract next in substring
e.g. (a+b+c)-(b+c+d) -> (a+b+c)-(b+c+d)+d-e
(t= ) shift t left
0 all nonnegative?
```
\*strictly speaking, each element of `l` is also offset by corresponding input element . I suspect this doesn't matter - a [brute force test](https://tio.run/##jYuxDsIgFEVn@AtDQkp8RuxqSRhcHJo4uBGGF1MqCW2NxYnw7Ui6uDqec@6dMD6HCaN/YClO9X42TVD9skYd9uzQRJUYa7PgWkfBj7rG6pgQtpOcjn8d5O9RLouh5Pb2c52fKdmQXJ1xGndq1AhbMwhVQGVrKYGEcP@8wrCaJOGUIdhsKaQArcy2fAE "Wolfram Language (Mathematica) – Try It Online") of strings up to length 17 showed no differences - but I don't have a proof as to why.
If it does make a difference, +1 byte using `(l=Most@l+#-{t=##2}&@t)&/@(l=0{t=##})0&` instead. [Try it online!](https://tio.run/##TY3fCsIgGMXvfYpQkKJG2v1CiC6DYN2NXcjYmrB/6HcRxPYMvUzP1SMsdS5S4Tv@zvHYSKiKRoLK5VTG07qOL50BUW9J9ISYkMNABWzoXliHeTJsPq83o9NVqxZSEh1LIUhGxySX7Xjrzo9eF8aorhWnSmqZQ6GNSMCm70lfK0gxcwtxzvzmTnIv7LHE3xfPI84CDMyhOeoU8gP94kv1f5@vY6HKW@GTuYyFgHvC8W6FEc6mLw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
ẆẈṀƙ§Ɗ⁼Ä
```
[Try it online!](https://tio.run/##y0rNyan8///hrraHuzoe7mw4NvPQ8mNdjxr3HG75b/uoYa7h4XbNyP//1Q1AQF1H3dDQAAwNIRxDMBOIgGJQEZg8WNDQAC4MFQUJQpSDWEA5MAOkBqYJYQ2qyWCDDaCGgiXhFkKMNYAqAWkzVAcA "Jelly – Try It Online")
It feels like something less naive should be shorter yet, but I haven't had any luck.
```
Ẇ Get every substring of the input.
§ Sum each substring,
ƙ Ɗ group the sums by
Ẉ the lengths of the corresponding substrings,
Ṁ and take the largest element of each group.
⁼Ä Is the resulting list equal to the cumulative sums of the input?
```
[Answer]
# [Risky](https://github.com/Radvylf/risky), 31 [bytes](https://github.com/Radvylf/risky#format)
```
*00_{?*_1_+!?{_?+0_{?*_1_+_?*_1__[___{_0*__1*_1:____{_0{__1*_1
```
Input is a single argument which is a list of 0's and 1's; output is 1 if prefix normal, 0 if not. [Try it online!](https://radvylf.github.io/risky?p=WyIqMDBfez8qXzFfKyE_e18_KzBfez8qXzFfK18_Kl8xX19bX19fe18wKl9fMSpfMTpfX19fe18we19fMSpfMSIsIltbMSwxLDAsMSwwLDEsMSwwLDEsMSwwLDAsMSwwLDBdXSIsMF0)
### Explanation
This is a bit long, so I'll explain it in two halves.
```
00_{?*_1_+!?{_?+0_{?*_1_+_?*_1
? Input list
{ List of all sublists
*_1 Repeat once (no-op)
_ Same value (no-op)
_ Map this function to each of the sublists
(first arg is each sublist, second arg is original input):
!? Length of first arg
{ Take prefix of that length from
_? Second arg
+ Sum
0 Transpose (adds a level of nesting to a flat list)
+ Concatenate that list with the following:
{? List of all sublists of input list
*_1 Repeat once (no-op)
_ Same value (no-op)
_ Map this function to each sublist:
_? First arg
*_1 Repeat 1 time (no-op)
+ Sum
0 Transpose
```
At this point, we have a list of pairs \$(n\_l^0, n\_l^i)\$, where \$n\_l^i\$ is the number of ones in the \$i^{th}\$ sublist of length \$l\$ and \$n\_l^0\$ is the number of ones in the first sublist of length \$l\$. We now want to check if for every pair, \$n\_l^0 \geq n\_l^i\$. Equivalently, \$min(n\_l^0, n\_l^i) = n\_l^i\$.
```
__[___{_0*__1*_1:____{_0{__1*_1
_ Map this function to each pair (first arg is each pair,
second arg is original input):
__ List of both args
{_0 Get 0th element (the pair)
_ Same value (no-op)
*__1*_1 Repeat 1 time (no-op)
[ Minimum
: Equals
__ List of both args
{_0 Get 0th element (the pair)
_ Same value (no-op)
{ Get element of the pair at index
__1*_1 1 (the second element)
_ Same value (no-op)
_ Same value (no-op)
```
We now have a list containing 0 for every sublist with more ones than the equal-length prefix, and 1 for every other sublist. The `*` at the beginning of the code takes the product of this list, yielding 0 for inputs with any such substrings and 1 for inputs without any.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 49 bytes
```
((1)|0)+(?<=(?!(?>(?<-1>(?<-2>1)|0)*)(?(2)^))^.*)
```
[Try it online!](https://tio.run/##TY2xDsMgDER3/iJDJZsqlZ05jcf8BWqHDlkyRB377wRfnCqA4Hh3HNvnu6zveqP5VYmUf8J3svFJ1pFNTfWKfZjgZSajgQtzeWSuVXwkVcFUlwrRViO4nx6QSsBgjo6oq4Qj/eNn9bUPdRJVsOKTo0wi4E90Bw "Retina 0.8.2 – Try It Online") Outputs `0` for prefix normal, `1` for not normal. Explanation:
```
((1)|0)+
```
Match some `1`s and `0`s, keeping count of the `1`s and the total number of digits (very slightly golfier as we need a group for the `+`), ...
```
(?<=...^.*)
```
... then, at the beginning of the string, ...
```
(?>(?<-1>(?<-2>1)|0)*)
```
... try to consume all of the `1`s, matching up to the same number of digits...
```
(?!...(?(2)^))
```
... and fail if there were enough `1`s, showing that the prefix is normal.
Note that if there are two disjoint substrings with too many `1`s then I think the substring containing both substrings will also have too many `1`s and will therefore be found first, but I can't prove that.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Œε∍OyO@}P
```
Input as a list of 0s/1s.
[Try it online](https://tio.run/##yy9OTMpM/f//6KRzWx919PpX@jvUBvz/H22oA4EGKKQBhIwFAA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f@jk85tfdTR61/p71Ab8F@HCyTLVZ6RmZOqUJSamKKQmceVks@loKCfX1CiDzEESqGZa6OgAlabl/o/2kAHCmO5og11DIEsBDaEixoiRKAkRA1CHk0fkipDFPMRehG6DHRQZQxgYkA9cB5YP7rp6K7G5T4DJLtQXIXQheYTAxT3o5oAswWoBwA).
**Explanation:**
```
Œ # Get all sublists of the (implicit) input-list
ε # Map over each sublist:
∍ # Shorten the (implicit) input-list to a length equal to this sublist-length
O # Sum this prefix
yO # Sum the sublist as well
@ # Check that the prefix-sum is larger than or equal to the sublist-sum
}P # After the map: pop and take the product to check if all were truthy
# (after which it is output implicitly as result)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://github.com/abrudz/SBCS)
```
∧/∘∊+\≥⍳∘≢+/¨⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HHcv1HHTMedXRpxzzqXPqodzOI17lIW//QikddTf/THrVNeNTb96hvqqf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/NAUDGORKUzAEQgMkbAgXNUSIQEmIGoQ8mj4kVYYo5iP0InQZoMkYwMS41HXVuRBuNASbgW4DustxudEAyT4UlyF0ofnGAMUPqCbAbDEEAA "APL (Dyalog Unicode) – Try It Online")
A tacit function taking a vector of `0`'s and `1`'s
`⊂` The input vector enclosed in a singleton list.
`⍳∘≢` indices of the input (1 .. length input)
`¨` For each of the numbers on the left and the input vector on the right:
`+/` sums of all sublists of the right argument of the length given by the left argument.
`+\` sums of prefixes of the input.
`≥` for each prefix sum, is it larger or equal than each of the sublist sum of sublists of the same size.
`∊` flatten nested list.
`∧/` reduce with boolean *and*.
Example with input `1 0 0 1 1`:
```
┌──┬─────────┬──────────┐
│+\│⍳∘≢+/¨⊂ │+\≥⍳∘≢+/¨⊂│
├──┼─────────┼──────────┤
│1 │1 0 0 1 1│1 1 1 1 1 │
├──┼─────────┼──────────┤
│1 │1 0 1 2 │1 1 1 0 │
├──┼─────────┼──────────┤
│1 │1 1 2 │1 1 0 │
├──┼─────────┼──────────┤
│2 │2 2 │1 1 │
├──┼─────────┼──────────┤
│3 │3 │1 │
└──┴─────────┴──────────┘
```
[Answer]
# [Scala](http://www.scala-lang.org/), 74 bytes
```
s=>1 to s.size forall(l=>s.sliding(l).map(_.sum).forall(_<=s.take(l).sum))
```
[Try it online!](https://tio.run/##dVLBbsIwDL3zFV7FIZGgaq6IVNqmHXbZJjhO05SVlHWEpiQBoSG@vXOSgmDr2iZy/Z6fLdu2EEq0@uNLFg5ejCyr/ZM2a6HuP2WxArl3sl5YuG0aOAwAdkJB4ZEJzOXm9bF2bzy/01pJUQNvLc8ZOA02tdW3hFIboRRRPEeHqhZVvSSKpmvRkPfUbtc07RjvU25TJ1bSwx6gbczVXFQE3OckWAVAkvkngXEOzmzlKDoZy8LLehAW/PghoQ8@RQYGy/o5HcUzopC3fhODNzhLoew5/CSe/YUuU/@Lx2Td3aPfFRbhrPth7IKJRDrAC5sOhFi5mTszAiPtVjkK0/FVt2mYd5wCUrH5MaCbntNo4zzRwCWggVqVQMJyeG0KnJ@1oxRggqp2qiY2KbQxuHITGHrxZbWTFoaRnkS1I0isuSf0YTZ7nl0FxjgYHm6idQQi9w3Ky8VJlJ5UB/4c2x8 "Scala – Try It Online")
Strategy is as follows:
* for all possible prefix lengths (`1 to s.size forall{...}`) check the following
+ compute the number of 1's within each sliding window of current prefix length (`s.sliding(l).map(_.sum)`)
+ check whether all these sliding windows contain no more 1's than the first window/initial prefix (`.forall(_<=s.take(l).sum)`)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~70~~ 60 bytes
```
->s,r=0..s.size{r.any?{|i|r.any?{|j|s[j,i].sum>s[0,i].sum}}}
```
[Try it online!](https://tio.run/##nY/BCoMwDIbvfYquh6ngSnsV5m57gt1ERieKlbqJ0YOzPruz1Q7ZcW0hyZ8/5GvbP4a5OM@nGML2zCgFCvKdjy0Vz@EyaqldVmlIqlCmFPo6hoRt6TRNc9N3gMmt7btyiAhKCDOHhAgTzpm93JXcFstb1K/mPFbmbNfYdCOvIyYjKKW5yMpRg0bYbj8UNBNK@Qt@o2Tne15Aa9H4x6h73WUQTAgZHyFruAoFuRqwg@XrQsewZ/@Ftaxs47Tt3S9WUraZzOifsHj@AA "Ruby – Try It Online")
* Saved 9 Bytes thanks to @Dingus suggestions !
any? replaces first map
We reuse entire range L=0..s.size instead of just the length
* Saved another 1 again by @Dingus
Compares directly the sums of prefix and current range being checked
* Takes an array `s` of 0/1 and return `false` if it is prefix normal, `true` if not.
```
(1..L=s.size).map{|i| - every length by*
(X= ... ) - we save in X:
(0..L).map{|j| * every index: all substrings of same length
s[j,i].sum} * sum 1's in slice of length i at j
.max>X[0] - any > of 1st element?
}.any?} - any true?
```
[Answer]
# [R](https://www.r-project.org/), 92 bytes
Or **[R](https://www.r-project.org/)>=4.1, 78 bytes** by replacing two `function` appearances with `\`s.
```
function(s,n=sum(s|1)){for(i in 1:n)F=F|which.max(sapply(0:n,function(j)sum(s[1:i+j])))-1;F}
```
[Try it online!](https://tio.run/##hY/BC4IwFMbv/RXiaY809qCDGLsK3btFBxGGk5zilIrsb19uziBwte0w@H7f977Xac40H2TRi0YSFUmmhpqoEQGevOmICIQMMJWQsWy8laIod3V@Jypv2@uD0FRGH3MF1nrGVGyrCwDEeMhempOh58mpOcqehNScEOJ9ApsvAZHaix4VrTa9CfIhS4KlkPo5hxlqDjS/NdgqqynLnB/L/Klr21LX1NL@teau1HlMsIP1Gw "R – Try It Online")
Takes a vector of integers. Outputs `FALSE` for prefix normal and `TRUE` for non-prefix normal word.
---
Solution shorter in [R](https://www.r-project.org/)>=4.1:
# [R](https://www.r-project.org/), 98 bytes
Or **[R](https://www.r-project.org/)>=4.1, 77 bytes** by replacing three `function` appearances with `\`s.
```
function(s,n=sum(s|1),g=sapply)any(g(1:n,function(i)which.max(g(0:n,function(j)sum(s[1:i+j])))-1))
```
[Try it online!](https://tio.run/##hY9BCoMwEEX3PYarDNWSgS5E8ADduytdiBCN1ChNpBV699SMsbRg2iSLwHv5@XOzIrdiVJWRvWI6VrkeO6afCHGd63IYrhOUamI1w0zFb1HCvZFVc@jKx4z4J2qBEs6YyX17AYAEAaxgoxFp0Z@UYRF3K4LkmMLuCyBy2higSGw@sxRS1gSykIc9rzlrCXS3LZnIZsr6z49h/tSlttw3JTs81tKV@zcu2Mv2BQ "R – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~19~~ 18 bytes
```
⊙θΦκ‹Σ…θ⁻⊕κλΣ✂θλ⊕κ
```
[Try it online!](https://tio.run/##VYpNCsIwEIWvkuUUIiRrV1IoCApCT1DGgYZOp5qkQk8/dtBN3@L98D4ch4zLwKqPnKTCRTZ4e9clrpRh8u5GpUC/ztBuyNSOy8v@e5K1wFUw00xS6QlT4x03uxnbc0Iyjr07Qn@dVWOMIcSwu@VvBGt6@vAX "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-` for not normal, nothing for prefix normal. Explanation:
```
θ Input string
⊙ Φκ Any substring satisfies
…θ⁻⊕κλ Leading prefix
Σ Sum of digits
‹ Less than
✂θλ⊕κ Current substring
Σ Sum of digits
Implicitly print
```
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 186 bytes
```
mod P is pr NAT-LIST . var L P F X Y Z :[Nat]. ops n c : Nat ~> Nat . ceq
n(L)= F if P X 2 Y F Z := L 2 L /\ size(P)= size(F)/\ c(F)> c(P). eq c(X 1 Y)=
s c(X Y). eq c(L)= 0[owise]. endm
```
The answer is obtained by reducing the `n` function with the input bitstring as a Maude `NatList` of `0`s and `1`s. If the term is irreducible (result is an “error expression” of kind `[NatList]`), then the bitstring is prefix normal, otherwise (result of sort `NeNatList`, `Nat`, etc.) it is not.
### Example Session
```
\||||||||||||||||||/
--- Welcome to Maude ---
/||||||||||||||||||\
Maude 3.1 built: Oct 12 2020 20:12:31
Copyright 1997-2020 SRI International
Sun Oct 17 22:18:44 2021
Maude> mod P is pr NAT-LIST . var L P F X Y Z :[Nat]. ops n c : Nat ~> Nat . ceq
> n(L)= F if P X 2 Y F Z := L 2 L /\ size(P)= size(F)/\ c(F)> c(P). eq c(X 1 Y)=
> s c(X Y). eq c(L)= 0[owise]. endm
Maude> red n(0 0 0 0) .
result [NatList]: n(0 0 0 0)
Maude> red n(1 1 0 1 0 1 0 1 1 0) .
result [NatList]: n(1 1 0 1 0 1 0 1 1 0)
Maude> red n(1 1 1 1 0 1 1 0 1 1 0 0 1 0 0) .
result [NatList]: n(1 1 1 1 0 1 1 0 1 1 0 0 1 0 0)
Maude> red n(1 1 1 0 1 0 1 0 1 1 0 1 1 0 0 1 1 0 0 0) .
result [NatList]: n(1 1 1 0 1 0 1 0 1 1 0 1 1 0 0 1 1 0 0 0)
Maude> red n(1 1 1 0 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 0 0 0 0 1 1) .
result [NatList]: n(1 1 1 0 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 0 0 0 0 1 1)
Maude> red n(0 0 0 0 1) .
result NzNat: 1
Maude> red n(1 0 1 1 0 1 1 0 0 0) .
result NeNatList: 1 1
Maude> red n(1 1 0 1 0 1 1 0 1 1 0 0 1 0 0) .
result NeNatList: 1 1 0 1 1
Maude> red n(1 1 0 1 0 1 0 0 0 0 1 1 0 0 0 0 1 1 0 1) .
result NeNatList: 1 1 0 0 0 0 1 1 0 1
Maude> red n(1 1 1 0 1 0 0 1 0 0 1 1 0 1 0 1 0 1 0 0 1 0 1 1 1) .
result NeNatList: 1 0 1 0 0 1 0 1 1 1
Maude> quit
Bye.
```
### Ungolfed
```
mod P is
pr NAT-LIST .
var L P F X Y Z : [Nat] .
ops n c : Nat ~> Nat .
ceq n(L) = F if P X 2 Y F Z := L 2 L /\ size(P) = size(F) /\ c(F) > c(P) .
eq c(X 1 Y) = s c(X Y) .
eq c(L) = 0 [owise] .
endm
```
We use Maude's strong pattern matching and conditional equations to try every possible prefix and sublist. The `c` function counts the number of `1`s in a list.
Interesting note: If the input term is reducible, the result will be a witness sublist with more `1`s than the prefix of the same length. It did not cost any extra bytes to do so.
The `[owise]` attribute does not *seem* to be needed in the current Maude 3.1 interpreter (the interpreter seems to prefer earlier equations over later ones), but Maude's definition of an “admissible functional module” requires it. Otherwise we could save 6 bytes by omitting it.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~91~~ 79 bytes
```
lambda s:any(sum(s[:i-j])<sum(s[j:i])for i in range(len(s)+1)for j in range(i))
```
Take as input a list of integers.
Return `False` for prefix normal and `True` for prefix not normal
Thanks `@UnrelatedString` for -12 bytes using list of integers instead of strings
[Try it online!](https://tio.run/##jVJBDoIwELz3FRtOrZak1RsRP4LE1AhaAoVQPPB6VCBQSokmTdPd7czObLZqm2epjl0aXrpcFLe7AB0I1WL9KrCOAulnMTkNQRbImKRlDRKkglqoR4LzRGFN9rzPZ3NeEtI1iW6uqqwLkYcRihiF@cQURZwC7yPr5os6tyrGYwItv7sZVzjuEGPxWnxsKcjMz9UPWYzQ6H3LPx9bbsnbmM8f/tlKssOwxeeeHnONy9nBlDX6n9bEWIIAQVVL1WBJwQvPHoX0uycIDVnP93YHRtbYH/juDQ "Python 3 – Try It Online")
]
|
[Question]
[
[Euler's numerus idoneus](https://en.wikipedia.org/wiki/Idoneal_number), or idoneal numbers, are a finite set of numbers whose exact number is unknown, as it depends on whether or not the [Generalized Riemann hypothesis](https://en.wikipedia.org/wiki/Generalized_Riemann_hypothesis) holds or not. If it does, there are exactly 65 idoneal numbers. If not, there are either 66 or 67. For the purposes of this challenge, we'll revolutionise mathematics and say that the Generalised Riemann hypothesis is true (I'd prove it, but I'm trying to golf the challenge body).
Under this assumption, the idoneal numbers are
```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 16, 18, 21, 22, 24, 25, 28, 30, 33, 37, 40, 42, 45, 48, 57, 58, 60, 70, 72, 78, 85, 88, 93, 102, 105, 112, 120, 130, 133, 165, 168, 177, 190, 210, 232, 240, 253, 273, 280, 312, 330, 345, 357, 385, 408, 462, 520, 760, 840, 1320, 1365, 1848
```
This is [A000926](https://oeis.org/A000926), and many different ways to describe this sequence can be found there. However, we'll include two of the most standard ones here:
* A positive integer \$D\$ is idoneal if, for any integer expressible in the form \$x^2 \pm Dy^2\$ in exactly one way (where \$x^2\$ and \$Dy^2\$ are co-prime), that integer is either a prime power, or twice a prime power.
For example, let \$D = 3\$. \$3\$ is idoneal, meaning that all integers that can be expressed as \$x^2 \pm 3y^2\$ for exactly one co-prime pair \$(x, y)\$ are either primes \$p\$, powers of primes \$p^n\$ or twice a prime power \$2p^n\$. As an example, \$(x, y) = (2, 3)\$ yields \$29\$ as \$x^2 + 3y^2\$. \$29\$ is a prime, and cannot be expressed in the form \$x^2 \pm 3y^2\$ for any other co-prime pair \$(x, y)\$.
* Alternatively (and rather more simply), a positive integer \$n\$ is idoneal iff it cannot be written in the form \$ab + ac + bc\$ for distinct positive integers \$a, b, c\$
For example, \$11 = 1\times2 + 1\times3 + 2\times3\$, therefore, \$11\$ is not idoneal.
This is a standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge, you may choose one of the following three options:
* Take an integer \$n\$ (either \$0 \le n < 65\$ or \$0 < n \le 65\$, your choice) as input, and output the \$n\$th (either 0 or 1 indexed, also your choice) idoneal number. **You may choose how to order the idoneal numbers**, so long as its consistent.
* Take a positive integer \$1 \le n \le 65\$ and output the first \$n\$ idoneal numbers. Again, you may choose how to order the idoneal numbers.
* Output all 65 idoneal numbers, in any order, with no duplicates.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes
```
Range[7!]/.<|Array[+##(3#+#2)-#3#->Set@$&,49+0{,,}]|>
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PygxLz012lwxVl/PpsaxqCixMlpbWVnDWFlb2UhTV9lYWdcuOLXEQUVNx8RS26BaR6c2tsbuf0BRZl6JQxoXhPZJzUsvyXBI@w8A "Wolfram Language (Mathematica) – Try It Online")
Outputs all(?) 65 idoneal numbers. Filters out numbers of the form \$a(a+b)+(a+b)(a+b+c)+(a+b+c)a\$ with \$a,b,c\$ positive integers.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
2ȷœc3ṙ€1ḋƊḟ@R
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//Msi3xZNjM@G5meKCrDHhuIvGiuG4n0BS//8 "Jelly – Try It Online")
First Jelly answer! Prints all ideonal numbers.
Gosh this was painful. This *should* work given several terabytes of RAM and a couple of hours. To see, replace `2ȷ`(2000) with 20 or something.
-10 thanks to Dude coinheringaahing.
```
2ȷœc3 # Combinations of 1..2000 of length 3
ṙ€1ḋ # Calculate ab+ac+bc for each
Ɗḟ@ # Remove these from
2ȷ R # 1...2000
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
F⁹⁹FιFκ⊞υ⁺×⊕ι⁺⊕κ⊕λ×⊕κ⊕λI⁻…¹⊗φυ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw9JSUwHMyITS2ZoKAaXFGRqlOgoBOaXFGiGZuanFGp55yUWpual5JakpQJVQKWTBbKAgMj9HUxMogqkZmzpNa66Aosy8Eg3nxOISDd/MPKDZQYl56akahjoKLvmlSTlAhYYGBgYgI0tB6v///69blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⁹⁹FιFκ
```
Loop over distinct `100 > a > b > c > 0`. (Replacing `⁹⁹` with `φ` would save a byte but make the code too slow for TIO.)
```
⊞υ⁺×⊕ι⁺⊕κ⊕λ×⊕κ⊕λ
```
Calculate `ab + ac + bc`.
```
I⁻…¹⊗φυ
```
Take the range from `1` to `1999` and remove all values that resulted from the above calculation.
[Answer]
# [R](https://www.r-project.org/), ~~72~~ ~~65~~ 62 bytes
```
r=i=1:2e3
for(a in r)for(b in a+r)i[(b+r)*(a+b)+a*b]=F;r[i[r]]
```
[Try it online!](https://tio.run/##K/r/v8g209bQyijVmCstv0gjUSEzT6FIE8RMAjETtYs0M6M1koCUlkaidpKmdqJWUqytm3VRdGZ0UWzs//8A "R – Try It Online")
Outputs all idoneal numbers in ascending order.
The TIO link will time-out, since `r` is needlessly set to `1...2000` to save bytes; [here](https://tio.run/##K/r/v8jW0MrS0rqoyDYTyDJKNeZKyy/SSFTIzFMo0gQxk0DMRO0izcxojSQgpaWRqJ2kqZ2olRRr6wbUF50ZXVQUG/v/PwA) is a link to a version with `r` initialized to `1...99` instead, which doesn't time-out (and still gives the right output).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes
```
∞'£ɾ3ḋ'Ǔ*∑¥=;ḃ;?i
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%88%9E%27%C2%A3%C9%BE3%E1%B8%8B%27%C7%93*%E2%88%91%C2%A5%3D%3B%E1%B8%83%3B%3Fi&inputs=5&header=&footer=)
Warning: This will *not work* for n ≥ 7. It's just too slow.
```
∞' ;?i # Get the nth number where...
ḃ # None of
ɾ3ḋ' ; # The ways you can choose 3 numbers less than n
Ǔ*∑ # Have ab+ac+bc...
£ ¥= # Equal n
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~87~~ 85 bytes
*Saved 2 bytes thanks to @tsh*
A full program printing the sequence in reverse order.
```
for(i=2e3;--i;)for(a=99;--a?b=~a&&a:print(i);)while(c=--b)while(--c)a*=a*b+a*c+b*c!=i
```
[Try it online!](https://tio.run/##LcdBDkAwEAXQs9hIW5kNGzQTZ/mdECOClLBz9SKxe2/CiV2ibgeddUrDGo1y2VeeSL39Cm6ad@gC38hztFvU5TBqvb1GnXsjTBR@E4mFY7hQwEkRnGSsKT0 "JavaScript (V8) – Try It Online")
### Commented
```
for( // 1st loop
i = 2e3; // going from i = 1999 to i = 1
--i; //
) //
for( // 2nd loop
a = 99; // starting with a = 99
--a ? // decrement a; if it's not zero:
b = ~a && a // stop if a = -1, otherwise set b to a
: // else:
print(i); // we've reached a = 0: print i
) //
while(c = --b) // 3rd loop going from b = a - 1 to b = 1
while(--c) // 4th loop going from c = b - 1 to c = 1
a *= // clear a if ab + ac + bc is equal to i,
a * b + // which will turn it into -1 on the next
a * c + // iteration of the 2nd loop
b * c != i // (otherwise, leave it unchanged)
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 23 bytes [SBCS](https://github.com/abrudz/SBCS)
```
(⍳!7)~(1⊥2×/4⍴+\)¨⍳3⍴50
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=03jUu1nRXLNOw/BR11Kjw9P1TR71btGO0Ty0AihhDGSbGgAA&f=JY4xjgIxDEX7OYXpQGuJOHYmmbtwkKGhRAIJabutFwmJfvcE7E1ykv0/FPF4/L79/9rPn9t@@9nU3Wlr/frIf1/76Lffj8Pu9QRw9CVN/Xo/QmoqWcVVQqWozCpVpaksKpbwAA3UwAzQgDJ3MM9YyZhnzBxah86xHegDPMACrGBW8J0xr3xgFf8NvNGK9xONEl2GZaa3j0I6D3toreKYLYkpWHzkYFegy5WlMQuv@EjFGM4MTsNIuBIzaKFHZagWw@jtOaxatGntl@/j1C/39R8&i=AwA&r=tryapl&l=apl-dyalog&m=tradfn&n=f)
A full program that prints all 65 terms. Essentially the same strategy as [att's Mathematica answer](https://codegolf.stackexchange.com/a/233947/78410). All attempts to factor out `⍳!7` failed, so here goes an efficient solution.
### How it works
```
(⍳!7)~(1⊥2×/4⍴+\)¨⍳3⍴50 Full program; no input
⍳3⍴50 50x50x50 cube containing coordinates of each cell
( )¨ For each item...
+\ Cumulative sum
1⊥2×/4⍴ From a, b, c compute ab+bc+ca
(⍳!7)~ Remove all numbers appearing in ^ from 1..5040
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 75 bytes
```
p [*1..2e3]-(r=*1..56).product(r,r).map{|i|a,b,c=i;a<b&&b<c ?a*b+b*c+c*a:0}
```
[Try it online!](https://tio.run/##KypNqvz/v0AhWstQT88o1ThWV6PIFsQ2NdPUKyjKTylNLtEo0inS1MtNLKiuyaxJ1EnSSbbNtE60SVJTS7JJVrBP1ErSTtJK1k7WSrQyqP3/HwA "Ruby – Try It Online")
A full program printing an array.
An array of the numbers `1..2000` is created and all non-ideonal numbers deleted from it. The smallest value of range `r` that works is `1..56`. Reducing the number below 56 fails to delete `1012` corresponding to `a,b,c = 5,12,56`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~93~~ 82 bytes
```
R=range(1,2000)
print({*R}-{a*b+c*(a+b)for a in R for b in R for c in R if a<b<c})
```
[Try it online!](https://tio.run/##pZFNboMwEIX3nGJ2/MSV/Ad2pHAJtm0X4JIGVSKIUKkV4uz0jdMqB@jCw3i@mXlPZvpeLtfR7HtTz@343mdKaCllnkzzMC7ZWjTb09oW3SEUWXvo8vN1ppaGkRritHuk4Z4OZ2pP3Sls@X6r/zGe9F9TH5b@jWpalSAtyAiygkpBlSAnyAs6ClISB1CBKjAFqIA0z6CuMaJR16gZ9Br0GUxb5BbcglmwErUS3wp1xwfM4e7BPUvxfslCklWipGZtEwPTKsqjVzksU0fJLjiY6IOzEn3acfDshbeY6IptGPZgWNBKbLEVaMkajk15G4XumlHKW78l4dKHj37GK2Xpy6d2NqSCYqZM@vcbf5ueH29a0@01338A "Python 3 – Try It Online")
Outputs all the idoneal numbers (works but times out on TIO).
This version works on TIO:
# [Python 3](https://docs.python.org/3/), ~~103~~ 92 bytes
```
R=range(1,99)
print({*range(1,2000)}-{a*b+c*(a+b)for a in R for b in R for c in R if a<b<c})
```
[Try it online!](https://tio.run/##rVHLboMwELznK/bGI67kF9hI4SdybXsAlySoEkGESq0Q305nnUb5gR68jGd2d0Zm/Jkv18Fs27GemuHcpUpUVbYbp36Y0yV/cFpKma0vS5O3@5Cnzb7NTteJGuoHOhLD9gnDHfYnag7tIazZdqv/adWu@x67MHcfVNOiBGlBRpAVVAgqBTlBXlAlSEkciAqqgqYgKkiaZ8BrjGjwGpxBr0GfwbQFttAtNAutAFfgW4J3fKA53D10z1a8X7KRZJdoqdnbxMJqGe3RqxyWqUpyCi4m5mBUoE87Lp6z8BYTU3EMwxkMG1qJLbaEWrCH41DeRqO7Z7Ty1q@7cOnCZzfhldLk7Us7GxJBESmTPH7vX9Pr801rur1n2y8 "Python 3 – Try It Online")
*Saved 11 bytes thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)!!!*
[Answer]
# [jq](https://stedolan.github.io/jq/), 76 bytes
```
[range(2e3)+1]-[[range(56)+1]|.[]as$a|[.[]+$a][]as$b|$a*$b+($a+$b)*(.[]+$b)]
```
[Try it online!](https://tio.run/##yyr8/z@6KDEvPVXDKNVYU9swVjcayjc1A3Fr9KJjE4tVEmuigQxtlcRYMDepRiVRSyVJW0MlUVslSVNLAyyZpBn7/7@SEgA "jq – Try It Online")
I don't really know why `[.[]+$a][]` and `.[]+$a` have different behavior.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
Select[Range[7!],!Reduce[a(b+c)+b*c-#==0<a<b<c,Integers]&]
```
[Try it online!](https://tio.run/##BcG9CoAgEADgVymC6MfAdgXXtqgxGs7rMCEd7Hr@6/sS8E0JOCJIsLLTQ8jHBjmQm7VW9UbXh3RA50fsRz/g1FirDRhvUC2ZKVB5z/aUtcTMlQsiPw "Wolfram Language (Mathematica) – Try It Online") (here are values <100 because TIO times out)
-1 byte from Dude coinheringaahing
-8 bytes from @att
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
⁹œc3P-Ƥ€§ṬCTḣ
```
[Try it online!](https://tio.run/##y0rNyan8/9/I4OjkZOMA3WNLHjWtObT84c41ziEPdyz@b2xwuB0o4v4fAA "Jelly – Try It Online")
Monadic link that returns the first n terms. The leading `⁹` (constant 256) is necessary to get the correct output for n = 1 and 2 (otherwise the output is empty for those two inputs). The linked code has `⁹` replaced by `20` for demonstration purposes.
### How it works
```
⁹œc3P-Ƥ€§ṬCTḣ Monadic link. Left arg = n, the number of terms
⁹œc3 3-combinations of 1..256
P-Ƥ€§ ab+bc+ca for each row
ṬCT List of numbers in 1..max(above) that do not appear
in the above list
ḣ Take first n
```
In order to filter out all `ab+bc+ca` numbers before 1848, the input numbers should be at least:
* 56 if you use "3-combinations of 1..(some fixed number)"
* 44 if you use "cumulative sums of 3rd cartesian power of 1..(some fixed number)"
In both cases, the hardest one to filter out is `(5, 12, 56) → 1012`. The next hardest is `(8, 17, 51) → 1411`.
---
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
³œc3P-Ƥ€§2ȷR¤ḟ
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//wrPFk2MzUC3GpOKCrMKnMsi3UsKk4bif//8 "Jelly – Try It Online")
Full program that prints all 65 terms. This one finishes within a few seconds without modification.
### How it works
```
³œc3P-Ƥ€§2ȷR¤ḟ Niladic chain.
³œc3 3-combinations of 1..100
P-Ƥ€§ Compute ab+bc+ca for each row
2ȷR¤ḟ Filter out the above from 1..2000
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₄·LD3.ÆεĆü*O}K
```
Outputs all 65 values.
[Try it online (with `≤2000` replaced with `≤50`).](https://tio.run/##yy9OTMpM/f/f1MDHxVjvcNu5rUfaDu/R8q/1/v8fAA)
**Explanation:**
```
₄ # Push 1000
· # Double it to 2000
L # Pop and push a list in the range [1,2000]
D # Duplicate this list
3.Æ # Get all triplets with unique integers
ε # Map each triplet to:
Ć # Enclose; append its own head: [a,b,c] to [a,b,c,a]
ü # For each overlapping pair:
* # Multiply them together: [a*b,b*c,c*a]
O # Sum this list: ab+bc+ca
}K # After the map: remove all those non-idoneal numbers from the [1,2000] list
# (after which the result is output implicitly)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 17 bytes
```
Ṡ-omoΣSz*ṙ1Ṗ3ḣ□43
```
[Try it online!](https://tio.run/##ASQA2/9odXNr///huaAtb21vzqNTeirhuZkx4bmWM@G4o@KWoTQz//8 "Husk – Try It Online")
Returns all idoneal numbers in ascending order, but too inefficiently to run in <1min on TIO.
Instead, [try idoneal numbers less than 100 without timing-out](https://tio.run/##ASQA2/9odXNr///huaAtb21vzqNTeirhuZkx4bmWM@G4o@KWoTEw//8)
```
ḣ□43 # 1..1849 (square of 43)
Ṡ- # return those that aren't
omoΣ # sums of
Sz* # zipping together by multiplying
Ṗ3 # all combinations of picking 3 numbers
ṙ1 # with that combination rotated by 1
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 52 bytes
```
f()=[n|n<-[1..7!],![c-2|c<-quadclassunit(-4*n).cyc]]
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P01D0zY6rybPRjfaUE/PXDFWRzE6WdeoJtlGt7A0MSU5J7G4uDQvs0RD10QrT1MvuTI5NvZ/QVFmXokGUKvmfwA "Pari/GP – Try It Online")
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.