text
stringlengths 180
608k
|
---|
[Question]
[
# Inspiration
There is a problem on the most recent AMC 12B test, the one held on November 16, 2022, which goes like this:
>
> (AMC 12B 2022, Question 17)
>
> How many \$4\times4\$ arrays whose entries are \$0\$s and \$1\$s are there such that the row sums (the sum of the entries in each row) are \$1\$, \$2\$, \$3\$, and \$4\$, in some order, and the column sums (the sum of the entries in each column) are also \$1\$, \$2\$, \$3\$, and \$4\$, in some order? For example, the array
> $$\begin{bmatrix}1&1&1&0\\0&1&1&0\\1&1&1&1\\0&1&0&0\end{bmatrix}$$satisfies the condition.
>
>
>
(If any of you are curious the answer is \$576\$.)
# Task
Your task is, given some positive integer \$N\$, output all \$N\times N\$ binary matrices such that the row sums are \$1,2,\ldots,N\$ in some order, as well as the column sums.
# Test Cases
```
N ->
Output
-------
1 ->
1
2 ->
1 1
1 0
1 1
0 1
1 0
1 1
0 1
1 1
3 ->
1 0 0
1 1 0
1 1 1
1 0 0
1 0 1
1 1 1
0 1 0
1 1 0
1 1 1
0 1 0
0 1 1
1 1 1
0 0 1
1 0 1
1 1 1
0 0 1
0 1 1
1 1 1
1 0 0
1 1 1
1 1 0
1 0 0
1 1 1
1 0 1
0 1 0
1 1 1
1 1 0
0 1 0
1 1 1
0 1 1
0 0 1
1 1 1
1 0 1
0 0 1
1 1 1
0 1 1
1 1 0
1 0 0
1 1 1
1 1 0
0 1 0
1 1 1
1 0 1
1 0 0
1 1 1
1 0 1
0 0 1
1 1 1
0 1 1
0 1 0
1 1 1
0 1 1
0 0 1
1 1 1
1 1 0
1 1 1
1 0 0
1 1 0
1 1 1
0 1 0
1 0 1
1 1 1
1 0 0
1 0 1
1 1 1
0 0 1
0 1 1
1 1 1
0 1 0
0 1 1
1 1 1
0 0 1
1 1 1
1 0 0
1 1 0
1 1 1
1 0 0
1 0 1
1 1 1
0 1 0
1 1 0
1 1 1
0 1 0
0 1 1
1 1 1
0 0 1
1 0 1
1 1 1
0 0 1
0 1 1
1 1 1
1 1 0
1 0 0
1 1 1
1 1 0
0 1 0
1 1 1
1 0 1
1 0 0
1 1 1
1 0 1
0 0 1
1 1 1
0 1 1
0 1 0
1 1 1
0 1 1
0 0 1
```
# Note
The reason why I'm not doing a challenge on simply outputting the number of matrices that satisfy the condition is because there is a pretty simple formula to calculate that number. Brownie points if you can figure out that formula, and why it works!
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œ!cþþ`ẎṠ
```
A monadic Link that accepts a positive integer and yields a list of the binary matrices.
**[Try it online!](https://tio.run/##ASgA1/9qZWxsef//xZIhY8O@w75g4bqO4bmg/8OHR@KCrGrigb7CtsK2//8y "Jelly – Try It Online")**
### How?
We can first arrange the set of \$N\$ *sorted* rows any way we like leading to \$N!\$ matrices with sorted rows. Each of these matrices will have column sums from \$1\$ through to \$N\$ *in order*, so all column-wise permutations will be distinct, so there are \$N!^2\$ such matrices.
We can create these matrices by noting that each number in the set \$[1,N]\$ is greater than or equal to exactly \$N\$ of the elements in the set (including itself).
Thus a table of \$\geq\$ between two permutations of the first \$N\$ natural numbers is such a table, e.g.:
| \$\geq\$ | 1 | 3 | 2 |
| --- | --- | --- | --- |
| 3 | 0 | 1 | 0 |
| 2 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 |
Where one permutation defines the column sums (directly - i.e. \$\{1,3,2\}\$, above) and the other defines the row sums (in reverse order - i.e. \$\{3,2,1\}\$, above, defines the sums \$\{1,2,3\}\$)
```
Œ!cþþ`ẎṠ - Link: integer, N
Œ! - all permutations (of [1..N])
` - use as both arguments of:
þ - table of:
þ - table of:
c - n-choose-k (a golf to get a positive integer when n>=k else 0)
Ẏ - tighten to a list of the sub-tables
Ṡ - sign (convert the positives to ones)
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~34~~ 33 bytes
```
{{~⍉¨⍵∘.⍀⍨↓∘.≠⍨⍳1+≢⊃⍵}⍣2⍣⍵⊂0 0⍴⍬}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOrquke9nYdWPOrd@qhjht6j3oZHvSsetU0GczoXgDi9mw21H3UuetTVDFRU@6h3sREQg9R3NRkoGDzq3fKod03t/0d9U4HGpSkYcsFYRnCW8X8A "APL (Dyalog Classic) – Try It Online")
Returns an array of boxed matrices. +1 for a flat structure by putting `,` somewhere in the first few characters.
Illustrates another way to get \$f(N)=N!^2\$:
For each \$N\times N\$ matrix that satisfies this property, we can invert 0s and 1s, then insert a row and column of 1s to get a \$(N+1)\times(N+1)\$ matrix that also has this property. Furthermore, each such resulting matrix is uniquely determined by predecessor, row, and column. Since there are \$N+1\$ positions in which a row or column can be inserted, \$f(N+1)=(N+1)^2f(N)\$, and \$f(0)=1\$ (one empty matrix) completes the induction.
```
base 0x0 matrix ⊂0 0⍴⍬
⍵ times: { } ⍣⍵
1...N+1 ⍳1+≢⊃⍵
N+1 row inserts ⍵∘.⍀⍨↓∘.≠⍨
N+1 column inserts ⍉¨ ⍣2
invert ~
```
[Answer]
# [J](http://jsoftware.com/), 27 22 bytes
```
i.@!([A."1"{A.)>:/~@i.
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/M/UcFDWiHfWUDJWqHfU07az06xwy9f5rcvk56SmAJR311PRqrOpAbE0HRz2oCq7U5Ix8hTQF4/8A "J – Try It Online")
*-5 thanks to ovs!*
Create the "step" matrix, get all row permutations, then to each of those apply all permutations again, but to each row at the same time -- this is equivalent to applying it to the columns.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
ɾ:v≤Ṗv∩vṖÞf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvjp24omk4bmWduKIqXbhuZbDnmYiLCJ24oGLwrZkaiIsIjMiXQ==)
```
ɾ # Push range(1, n+1)
v # Over each...
ɾ: ≤ # Check if it's less than each of range(1, n+1)
Ṗ # Get all permutations
v∩ # Transpose each
vṖ # Get permutations of each
Þf # Flatten by one layer
```
[Answer]
# [Python](https://www.python.org) + NumPy, 94 bytes
```
from numpy import*
f=lambda n,p=0:1//n*[e:=eye(n)]or[1-w.T@e[j]for j in e<1for w in f(n+p,~p)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY349KK8nMV8kpzCyoVMnML8otKtLjSbHMSc5NSEhXydApsDawM9fXztKJTrWxTK1M18jRj84uiDXXL9UIcUqOzYtPyixSyFDLzFFJtDEHschA7TSNPu0CnrkAzFmqLSUFRZl6JRpqGoaYmF4xthMQ2hrNzUvOAfBNNTU2IXphLAQ)
Same logic as before but implemented in matrix algebra avoiding he expensive `insert`.
### [Python 3](https://docs.python.org/3/) + NumPy, 96 bytes (@att)
```
from numpy import*
f=lambda n,p=0:[insert(w,i,1+p,p)for i in r_[:n]for w in f(n+p,~p)]or[eye(0)]
```
[Try it online!](https://tio.run/##XYm9CsIwEID3PsWNiWZorS6FPkkIUjHBg@ZyXCOli68em0ERt@@Ht/xI1JcSJEWgZ@QNMHKSfGjCOE/xdp@ADI/tYJEWL1mtBk13ZMM6JAEEJJCrHchVXasGRft/sXZJrN@8arUrLEhZBdVp3Xz49MP9l2dPu5/1X7jUUN4 "Python 3 – Try It Online")
### [Python 3](https://docs.python.org/3/) + NumPy, 99 bytes
```
from numpy import*
f=lambda n,p=1:[insert(w,i,p,p)for i in r_[:n+1-p]for w in f(n-p,1-p)]or[eye(0)]
```
[Try it online!](https://tio.run/##XchBCsIwEEDRfU@RZUZTMFY3hZ4kBKmYYKCZDNNIyeljs1DE3f@PSn4mHGr1nKLAV6QiQqTE@dD5aZnj/TELVDTp0QRcHWe5qaBIEfjEIoiAgm9mxKPuyTbaGnmJPamdwCY2rjh5AluJA2bppQboPn3@6eHbi8P9L/AH1wb1DQ "Python 3 – Try It Online")
This works by alternating between inserting rows of zeros and columns of ones at every possible position.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 62 bytes
```
n->forperm(n,p,forperm(n,q,print(matrix(n,n,x,y,p[x]>=q[y]))))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN-3ydO3S8osKUotyNfJ0CnQQ7EKdgqLMvBKN3MSSoswKoECeToVOpU5BdEWsnW1hdGWsJhBATFmSpmEMZS5YAKEB)
Let \$p\$ and \$q\$ runs over all permutations of \$1,\dots,n\$. For each \$p\$ and \$q\$, construct an \$n\times n\$ binary matrix where the element at position \$(x,y)\$ (\$1\$-indexed) is \$1\$ if and only if \$p[x]\ge q[y]\$.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 8.5 bytes (17 nibbles)
```
+.;``p,$.@.$._`$/
```
Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/254772/95126): upvote that.
Sadly, [Nibbles](http://golfscript.com/nibbles/index.html) comes-out half-a-byte longer.
```
,$ # 1..input
``p # get all permutations of that
; # and save this list of lists
. # now map over each list
.@ # mapping over each saved list
.$._ # element-wise mapping over each x,y
`$ # sign of
/ # x integer-divided by y
+ # finally, flatten by one level
```
[](https://i.stack.imgur.com/n7nO2.png)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 132 bytes
```
n=>P(n).flatMap(x=>P(n).map(y=>x.map(u=>y.map(v=>u+v<n))))
P=(n,i=n)=>n?i--?[...P(n,i),...P(--n).map(r=>r.splice(i,0,n)&&r)]:[]:[[]]
```
[Try it online!](https://tio.run/##Rc7BCoMwDAbg@57Ck7Zoyw47jaXeB9uEHZ2H0qlUulRaFX16p05YyOFLID9p5CC9crrtGNp3OVcwI4iMIOWVkd1NtmTc58/iCcS4oQcxbRhA9PFwQbrUIQOCiQakIDDVjKU55zxbdzTZxNge5EA47lujVUl0ckyQhqGjxTlfOi@KWVn01pTc2JpU5PQ7GgMQwfX5uHPfOY21riYy/uNWKBCxWn/hjdVIohdGlM5f "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~147~~ 145 bytes
```
lambda n:[[[k[l]for l in j]for k in i]for j in p(range(n))for i in p([1]*i+[0]*(n-i)for i in range(1,n+1))]
from itertools import*;p=permutations
```
[Try it online!](https://tio.run/##TctLEsIgDIDhfU/BElqdsXan05MgCxxB00LC0Ljw9NiHju6@/EnSix@EXfH9pQQbrzcr8KS1HnUwnrIIAlAMK8eFsHJYmGS2eHcSlVoabE23poZGH0wtcQ@/zXbb7rBplTKVzxQFsMtMFCYBMVHm@pz65HJ8smUgnErKgCy9nF@qr49/7mZ/huBwC6q8AQ "Python 3 – Try It Online")
Based on my comment to this challenge. First generates a right triangular shaped matrix of 1s, then makes all possible different permutations of rows and columns. Outputs a list of 2D lists. -2 bytes thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314).
---
# [Python 3](https://docs.python.org/3/), ~~132~~ ~~121~~ ~~116~~ 115 bytes
```
lambda n:[[[1-(l>k)for l in j]for k in i]for i,j in product(*[[*permutations(range(n))]]*2)]
from itertools import*
```
[Try it online!](https://tio.run/##Tcg9EsIgEEDhPqegBEaLJJ0zehGkQANKArvMZlN4ehR/Zuy@98qD7whjDcdzTS5fJifgYIzp9zKdFhWQRBIRxGwbl8b4ZtzNLQrhtF1ZamN08ZQ3dhwRVkkObl6CUtbqQdkuEGYR2RMjplXEXJBY10IRWAbZK9X9PPx5fPkbycNnqPoE "Python 3 – Try It Online")
Uses the method entailed in [Jonathan Allan's answer](https://codegolf.stackexchange.com/questions/254768/1-to-n-column-and-row-sums/254772#254772). -12 bytes thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314), -5 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~125 ...~~ 79 bytes
```
->n{a=*[*1..n].permutation;a.product(a).map{|r,c|r.map{|x|c.map{|y|x>y ?0:1}}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtFWK1rLUE8vL1avILUot7QksSQzP886Ua@gKD@lNLlEI1FTLzexoLqmSCe5pgjCrKhJhjAqayrsKhXsDawMa4Hgf4FCWrRRLBeIMo79DwA "Ruby – Try It Online")
Switched to Jonathan Allan's approach.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
>€ḶŒ!Z€Œ!€Ẏ
```
[Try it online!](https://tio.run/##y0rNyan8/9/uUdOahzu2HZ2kGAVkASkQf1ff////jQE "Jelly – Try It Online")
Port of my Vyxal.
```
€ # Over each of...
# implicit range(1, n+1)
> # Are they greater than...
Ḷ # range(0, n)
Œ! # Permutations
Z€ # Transpose each
Œ!€ # Permutations of each
Ẏ # Flatten by one level
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LœDδδ@€`
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/254772/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f/f5@hkl3Nbzm1xeNS0JuH/fyMA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/squSZV1BaYqWgZO@nw6XkmFxSmpijkF9aAhP873N0ssu5Lee2ODxqWpPw31YpoCi1pKRSt6AoM68kNQWhVKes8tBunUPb7P8DAA).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
œ # Get all permutations of this list
D # Duplicate it
δ # Apply double-vectorized:
δ # Apply double-vectorized:
@ # a >= b check
€` # Then flatten the list of lists of matrices one level down
# (after which the result is output implicitly)
```
[Answer]
# JavaScript (ES6), 146 bytes
This is a naive solution based on bit masks and brute force.
Prints all valid matrices.
```
n=>{for(k=1<<n*n;k--;M+2>>n-~n&&console.log(m))for(M=m=[],y=n;y--;M|=1<<r|1<<c+n)for(m[y]=[c=r=0],x=n;x--;r+=q,c+=k>>x*n+y&1)m[y][x]=q=k>>y*n+x&1}
```
[Try it online!](https://tio.run/##TY1BcoMwDEX3nEIrwDGQ0smqRL5BTkBZMC7JEGKZOB7GniS9OrXbLLqR/v96mn/ul/4mzTjbkvTXsG63MDhrepDBwVEbmM1grS9nM5Id6ZRITTcLF30ChKj1ZaiCa5KXCfE9nj9AAYqoclWpfs6XaJfqrEfKM8gYe8lPyhhw@NvPJkmOuBKKeyjPJ6z3e9pQM5Vlc@DvQlD5TWn6rzhXjEX0gArbrvBIjY/wI76aRxiS0y@hWt9hK9HgW1e4wLnAGY7XQnKchHAb4j6tWeRa1@E1hj6ELq2f6zHfsfUH "JavaScript (Node.js) – Try It Online")
### Commented
```
n => { // n = input
for( // first loop:
k = 1 << n * n; // start with k = 2 ** (n * n)
k--; // decrement until k = 0
M + 2 >> n - ~n // if bits 1 to n * 2 (0-indexed)
&& // are all set in M:
console.log(m) // print the matrix
) //
for( // second loop:
M = // M = bit mask
m = [], // m[] = matrix
y = n; // start with y = n
y--; // decrement until y = 0
M |= 1 << r | // update the bit mask
1 << c + n // with row and column bits
) //
for( // third loop:
m[y] = [c = r = 0], // initialize m[y], c and r
x = n; // start with x = n
x--; // decrement until x = 0
r += q, // increment r if q is set
c += k >> x * n + y // increment c if the cell at
& 1 // (y, x) is set
) //
m[y][x] = // set m[y][x] to
q = // q, defined as
k >> y * n + x // the cell at (x, y)
& 1 //
} //
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
≔…⁰Nθ⊞υ⟦⟧Fθ≔ΣEυE⁻θκ⁺κ⟦μ⟧υF⊕υEυEι⭆κ›μξ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY-xCsIwEIZ3n-JwykEEwUXo5CQOSrFj6RBjbEubaJOc-C4uFRR9BR_FtzFBBae7_47v4-78kJWwci_avr-R342mr-fMubo0bC1MqdiYw8IcyK9Ib5RliBw6TAYpuYoRh7wIYbe3wDqEL5iRZktxiOtYlrUhxzoOTWDTNvRN4HSBGGX04xdGWqWV8WrLCBFSWxv_76k5ZD4MyxiCYm6V8OEkzeEUXZhc3Ua67xv3fDg6tsPiMvnkNw) Link is to verbose version of code. Explanation: Based on @Ausername's Vyxal answer.
```
≔…⁰Nθ
```
Start with a range from `0` to `N`.
```
⊞υ⟦⟧Fθ≔ΣEυE⁻θκ⁺κ⟦μ⟧υ
```
Generate all of the permutations of that range.
```
F⊕υEυEι⭆κ›μξ
```
Generate the comparison matrices between each pair of incremented permutation and permutation.
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
Related to [AoC2017 Day 16](https://adventofcode.com/2017/day/16). I'm using the wording from [my Puzzling SE puzzle based on the same AoC challenge](https://puzzling.stackexchange.com/q/106275/71652) instead of the original AoC one for clarity.
---
\$n\$ people numbered \$1, 2, \cdots, n\$ are standing in line in the order of their corresponding numbers. They "dance", or swap places, according to some predefined instructions. There are two kinds of instructions called Exchange and Partner:
* **E**xchange(m,n): The two people standing at m-th and n-th positions swap places.
* **P**artner(x,y): The two people numbered x and y swap places.
For example, if there are only five people `12345` and they are given instructions E(2,3) and P(3,5) in order, the following happens:
* E(2,3): The 2nd and 3rd people swap places, so the line becomes `13245`.
* P(3,5): The people numbered 3 and 5 swap places, so the line becomes `15243`.
Let's define a **program** as a fixed sequence of such instructions. You can put as many instructions as you want in a program.
Regardless of the length of your program, if the whole program is repeated a sufficient number of times, the line of people will eventually return to the initial state \$1,2,3,\cdots,n\$. Let's define the program's **period** as the smallest such number (i.e. the smallest positive integer \$m\$ where running the program \$m\$ times resets the line of people to the initial position). The states in the middle of a program are not considered.
For example, a program `E(2,3); P(3,5); E(3,4)` has the period of 6:
```
E(2,3) P(3,5) E(3,4)
1. 12345 -> 13245 -> 15243 -> 15423
2. 15423 -> 14523 -> 14325 -> 14235
3. 14235 -> 12435 -> 12453 -> 12543
4. 12543 -> 15243 -> 13245 -> 13425
5. 13425 -> 14325 -> 14523 -> 14253
6. 14253 -> 12453 -> 12435 -> 12345
```
Now, you want to write a program for \$n\$ people so that it has the period of exactly \$m\$. Is it possible?
**Input:** The number of people \$n\$ and the target period \$m\$
**Output:** A value indicating whether it is possible to write such a program or not. 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.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Truthy:
```
n, m
1, 1
2, 2
3, 6
3, 3
8, 15
8, 120
16, 28
16, 5460
```
Falsy:
```
1, 2
2, 3
3, 4
6, 35
6, 60
8, 16
16, 17
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 59 bytes
```
(n,m)->[[lcm(Vec(concat(p,q)))==m|q<-s]|p<-s=partitions(n)]
```
[Try it online!](https://tio.run/##NY3NDoMgEITvfYqNJ0gwUfyph@Jj9GI4EFJbEkVUemjiu9Ml4mXnY3dmcGoz@duFEUQgls0074dh0jN5vjTRi9XKE8dWSqkQ87E@8l0eDqdwavPGm8XuxFIZ/Pb1nx9RFASYkSgGJYOC3m7KuQn3kPfgNmM9YhYfGaSIVtNERgYK/2AwDJgrJQJnwKNWDNqkVdQO780FvIhUtujtLmrq9tymAp6CWFBHRUvVJDidsam94uVdShr@ "Pari/GP – Try It Online")
Let `x` and `y` loop over the integer partitions of `n`. Takes the LCM of all elements in `x` and `y`, and checks if it equals `m`. Outputs a list of lists, which is truthy when at least one element is truthy.
For a detailed explanation, please read (and upvote) [xnor's answer on Puzzle SE](https://puzzling.stackexchange.com/a/106278/10468).
Here I only list some facts about [permutations](https://en.wikipedia.org/wiki/Permutation) (please read this Wikipedia page for the definition of the terms):
Here by "permutation" I mean a permutation of the set \$\{1,\dots,n\}\$.
1. Every permutation can be written as a product of 2-cycles (swapping two elements).
2. So a "program" in this question can be seen as left multiplying a permutation \$X\$, and right multiplying another permutation \$Y\$. Let \$(X,Y)\$ denote such a program. Applying the program \$k\$ times is just left multiplying \$X^k\$ and right multiplying \$Y^k\$. The "period" of \$(X,Y)\$ is the smallest \$k>0\$ such that \$X^kY^k=\operatorname{id}\$. Here \$\operatorname{id}\$ is the permutation that changes nothing.
3. Every permutation can be written as a product of disjoint cycles.
4. If we write a permutation \$X\$ as a product of disjoint cycles, then the order of \$X\$ (i.e., the smallest \$k>0\$ such that \$X^k=\operatorname{id}\$) is the LCM of the lengths of these cycles. The cycle lengths corresponds to an integer partition of \$n\$.
5. If \$k\$, \$l\$ are the orders of permutations \$X\$, \$Y\$ respectively, then the period of the program \$(X,Y)\$ is a divisor of \$\operatorname{lcm}(k,l)\$, but not necessarily equals \$\operatorname{lcm}(k,l)\$.
6. But when \$k\$ and \$l\$ are coprime, the period of \$(X,Y)\$ does equal \$\operatorname{lcm}(k,l)=k\ l\$. A proof can be found in xnor's answer on Puzzle SE.
7. If \$k\$ is the order of some permutation, \$s\$ a divisor of \$k\$, then there exists a permutation with order \$s\$. This can be seen from the fact that, if \$k\$ is the order of a cycle \$C\$, \$s\$ a divisor of \$k\$, then \$C^{k/s}\$ has order \$s\$.
8. If \$\operatorname{lcm}(k,l)=m\$, \$u\$ a divisor of \$m\$, then we can always find \$s\mid k\$, \$t\mid l\$ such that \$s\$ and \$t\$ are coprime, \$s\ t=u\$.
9. So if \$k\$, \$l\$ are the orders of permutations \$X\$, \$Y\$ respectively, we can always find a program \$(X',Y')\$ (not necessarily the same as \$(X,Y)\$) with period \$\operatorname{lcm}(k,l)\$.
10. So the possible periods of programs are exactly these \$\operatorname{lcm}(k,l)\$, where \$k\$ and \$l\$ run over the LCM's of integer partitions of \$n\$.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Åœãε˜.¿}Iå
```
First input is \$n\$, second is \$m\$.
Port of [*@alephalpha*'s Pari/GP answer](https://codegolf.stackexchange.com/a/238494/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##ASAA3/9vc2FiaWX//8OFxZPDo861y5wuwr99ScOl//84CjEyMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P/DrUcnH158buvpOXqH9tdGHF76X@d/dLShjmGsTrSRjhGQNNYxA5PGQNJCx9AUhTIyANKGZjpGFhDa1MQMKKIANMAIbIAxWKsJkDTTMTYFUyAFIK1mEB2G5rGxAA).
**Explanation:**
```
Ŝ # Get all lists of positive integers that sum to the first (implicit)
# input `n`
ã # Use the cartesian power to create all possible pairs of these lists
ε # Map over each pair of lists:
˜ # Flatten it to a single list
.¿ # Pop and push the LCM (Least Common Multiple)
}Iå # After the map: check if the second input `m` is in this list
# (after which this is output implicitly as result)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 209, 187 (@pxeger), 180 179 bytes (merge)
```
lambda n,m:any(sum(g(m))-n<=s<=n for s in h(g(m)))
g=lambda a,p=2,e=0:a%p and[p**e][:e]+g(a,p+1)or g(a//p,p,e+1)if a+e>1else[]
h=lambda p,S=0:p and h(p[1:],S)+h(p[1:],S+p[0])or[S]
```
[Try it online!](https://tio.run/##PZDBbsIwEETv/opVqko22ZY4gRRFuEd@AA5IIQdXOBApcVaEHvj6dB1CL2t7Z95YGnrcr73PNnQba3MaW9v9nC147ArrH3L47eRFdkp9@K0ZtsZD3d9ggMbD9SkocTEzZJFMis4khX0nsP5c0mLhqrJwVXyRrMZaMc3X5ZKQ0PG7qcHG7lu7dnBlJa6vLMI950wp/BOVuqhwr@L/a0xlUnFaua/Gg4miSCNokSKkIkPIw8jEhnfraaYJW8SbztmweZ7rVT4txW7G04BngVwJ1rN1mHky8bkIiP6agFDBMVQgD7hThQC6Nf4ulZjKaYNy/Byobe4yOvkoOKDB3nSWJBuxfYkIEfcHM19LNik1/gE "Python 3.8 (pre-release) – Try It Online")
#### Older versions
```
lambda n,m:any(sum(g(m))-n<=s<=n for s in h(g(m)))
g=lambda a,p=2,e=0:a+e>1 and(a%p and[p**e][:e]+g(a,p+1)or g(a//p,p,e+1))or[]
h=lambda p,S=0:p and h(p[1:],S)+h(p[1:],S+p[0])or[S]
```
[Try it online!](https://tio.run/##PZDBboMwDIbveQqLaVJSvJVAyyrU7NgXoIdKlEOmAkWCYJXu0KdnDqW72I7//3Oknx736@CSHd2m2pynzvY/FwsO@8y6hxx/e9nIXqkPtzfj3jiohxuM0Dq4PgUlGrNAFsnEWJkos2H1rcG6i7Tv5HtBq1VVFllVho1kX6gV3@FxvSYkrPjNi6IU19cxwpwPzTB/RYXOSsxV@D@GVESlZ/JyOpogCDSCFjFCLBKE1JdE7Hi3nWscsUW86ZQNu2ffbtJ5KQ4LHns88eRGsJ5sfU2jmU@FR/TXDPgMTj4DecSDygTQrXV3qcScTueV0@dIXXuXwdkF3gEtDqa3JNmI3UtECDhAWPhaskmp6Q8 "Python 3.8 (pre-release) – Try It Online")
```
lambda n,m:(c:={x**g(m).count(x)for x in g(m)})!=1in(sum(c)-n<=s<=n for s in h(c))
g=lambda a,p=2:a%p and g(a,p+1)or[p]+g(a//p,p)if a>1else[]
h=lambda c:sum([h(c-{x})for x in c],[sum(c)])
```
^ ^ ^ ^ ^ ^
Big thanks @pxeger!
[Attempt This Online!](https://ato.pxeger.com/run?1=RZBdasJAEMff9xTTQGFX149NNJXg9tET-CCkedhGo4Fks5gIKeJJ-iKU9hI9QM_Q23QmRvoyw8z8f_P1_uXemkNlrx-Zfvk8Ndlo8ftdmPJ1a8DKMuJppM_tYLDnpRin1ck2vBVZdYQWcguUvYgHrXLL61PJUzGyS10vtQXS1KQ5YFawve6bGum0H5lHB8ZusQHGQyWqY-ySIUaTiZNO5BmYZ7Ur6l2csMMdTSOaEWPD0bm9_G-RJjK-TU9Ef8LPWnuepyQo5kvwWSAhJBOwBebmnfWnTIVYXHRuPguniLBVD_oEBsTMGJaDOdlw2pFhR6gn0tMWG9qCr-VKRAzcMccnCdZ9oKDKZly7Im-492I9UkAuK10ax1Eoi3tRgod_gp7POIpEf871evN_)
```
g=lambda a,p=2:a>1 and(a%p and g(a,p+1)or[p]+g(a//p,p))or[]
def h(c):
yield sum(c)
for x in c:
yield from h(c-{x})
def f(n,m):
c={x**g(m).count(x)for x in{*g(m)}}
return any(sum(c)-n<=s<=n for s in h(c))
```
[Try it online!](https://tio.run/##NZDPbsIwDMbveQqr0qQEAvQPdAiRHXkCDkgbh6ylUKlNo7RIrVCfvbOzcrFlf/7ls2OH7tGYZG/dNN1VpevfXIOWVsUH/RWBNjnXH5Yy3Dn2l5Fo3Le9LrHabKy0guory28FPHgmDgyG8lbl0D5rLBkUjYMeSgMZSrNWuKam6dWrH4VHC25kTXCmXv1icee1WGfN03S8F@8XXr49jgzcrXs6g0sN/N9mZY6qPSrj3Vpyo13EdFZBEEQSIhZLiFkiIaWQsD32dj7GIYtSFPc@7bZpiAhjp5mMiUwI2jLUkx3FNPRo6pHo0wPkfCFnfpYnusS6Eteff6Ai5bJubVV2PPgxAU1AKRtVa8txUFZvUUIgkJr5guMQXvIH "Python 3.8 (pre-release) – Try It Online")
#### Explanation
We can think of the two kinds of swaps as "multiplying from the left or right". The significance of this is that we can flip any adjacent pair of different kind swaps without changing the outcome and the space of possible chains of swaps is the same as one arbitrary permutation from the left and one from the right.
We therefore need to know the period of any n-permutation. This can be derived from the cycle representation. The period is just the lcm of the cycle lengths. And the combined (left and right) period is the lcm of the left and right lcms EDIT This is not generally true. What is, however, true is that cancellation can only affect shared prime factors. Indeed. let A and B the left and right permutations with periods m and n. If A^x B^x = 1 with x < lcm(m,n) and m has a prime factor p that is neither in n nor in x then by taking the n-th power we get A^(xn) = 1 contradicting the assumption that the period be a multiple of p.
#### Implementation
Straight forward: `g` extracts the prime factors. The main function `f` groups them into powers and `h` determines whether these powers can be distributed over two times n elements.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~136~~ 106 bytes
```
->n,m{z=([*0..n]*n).combination(n).select{|x|x.sum==n};z.product(z).any?{|a,b|m==(a+b-[0]).reduce(&:lcm)}}
```
[Try it online!](https://tio.run/##NY/bCoMwEER/JU8l2hi8V1psPyTkIVoLgoniBbwk3243qE9ndmd2YPupWPZfvntvReS25pi5PqWKu8qhZSuLWomxbhWGcaiaqhw3PeuZDpPMc2VeK@369juVI14dKtTy2bQghQYTi3vhMZ87tK8gUOHbsymlY8zOWEBQwAliIUGhZURQejKyzMBPLhH6VgUpZLNLJXF6bM@C8DyEgtgSIlFyiiNpm9LrPHhwTqXoNg1P6w79GJCb/Q8 "Ruby – Try It Online")
Port of Kevin Crujssen's 05AB1E answer, which was a port of alephalpha's Pari/GP answer, but explained in terms an engineer can understand. :-)
This is very slow because of the brute force partitioning: instead of trying to be clever, I just get all combinations of n numbers between 0 and n, and filter by sum, then remove the 0s when calculating lcm.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~64~~ ~~60~~ 59 bytes
```
NθNηF…·²ηW¬﹪ηι«⊞υ×ι⎇﹪∨Πυ¹ι¹⊟υ≧÷ι绬‹θ⌊EX²Lυ⌈E²↨¹Φυ⁼λ﹪÷ιX²ξ²
```
[Try it online!](https://tio.run/##TY/PTsMwDMbP61Pk6EhBYj0h9QRiSJPWEU28QOhCYylN2vzphhDPXhwQBV9ix58//9wZFTqv7LLs3ZjTMQ@vOsDEm@p/bah@84HB3nU2R5z1SbleQy2Y4ZxdDFrN4OgTtP6crQcjGHLqfFQbmaOBLNgLDjoCUqKDU@H9V/ocQAZKuwSZC7blZZRewaQf6YuiqTatGu9jxN6dsDeJONIjznjWJC4MTfVZyYAufUMcdIwwCdaiwyEPQMMg/YUOIeCDdn0yxZgE6roKqPWgogZa/IQ2kZigd1NWNoIl6Q/turhcsnpei1nN/6JZlju2rW@Xm9l@AQ "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for possible, nothing if not. Explanation: Based on @xnor's Puzzling.SE answer.
```
NθNη
```
Input `n` and `m`.
```
F…·²ηW¬﹪ηι«⊞υ×ι⎇﹪∨Πυ¹ι¹⊟υ≧÷ιη»
```
Decompose `m` into its prime power factors e.g. `120=3*5*8`.
```
¬‹θ⌊EX²Lυ⌈E²↨¹Φυ⁼λ﹪÷ιX²ξ²
```
Check whether the factors can be partitioned into two sets neither sum of which exceeds `n`, or expressed more golfily, the minimum possible maximum sums of two complementary sets of factors does not exceed `n`. In the case of `3*5*8` the sets are `{},{3,5,8}` maximum sum `16`, `{3},{5,8}` maximum sum `13`, `{5},{3,8}` maximum sum `11`, and `{8},{3,5}` maximum sum `8`. The minimum of these is `8`, so `n` needs to be at least `8` for an `m` of `120`.
[Answer]
# JavaScript (ES6), 107 bytes
Expects `(m)(n)` and returns \$0\$ for true or \$1\$ for false.
Based on [alephalpha's algorithm](https://codegolf.stackexchange.com/a/238494/58563).
```
m=>F=(n,i=a=[1],p=1,g=q=>v%p?g(q,v+=q):v)=>n?i>n||F(n-i,i,g(v=i++))&F(n,i,p):a.every(x=>g(v=x)-m,a.push(p))
```
[Try it online!](https://tio.run/##bY/BjoIwEIbv@x67zIRCBJQ1JlNvPMHe0EPjItZgKaCNJr47W6IH1zaZ0/dnku87CiOGXS/1OVLtbzXuaTwRLwgUkySoTLZMU8Jq6oibT72uoWMmpA5XBomrteTqfi9ARZJJVoMhGYaIX8X0zzSuRFyZqr/Blfi0XjE6MRHry3AAjTjuWjW0TRU3bQ1B@dNfzofbNsCPV76HBO29wxTtvcMcIXNg5oPJAmHp0nTmw@nSGuQOXszz2XP4twQbVRaiGTwpqS8l86XMvSnW2vWYLFxqvXyF3w/j8Q8 "JavaScript (Node.js) – Try It Online")
### Commented
```
m => // outer function taking the period m
F = ( // inner recursive function taking:
n, // n = number of people
i = // i = current value for integer partition
a = [1], // a[] = list of LCMs
p = 1, // p = previous LCM
g = q => // g is a helper function taking q
v % p ? // and computing LCM(p, q)
g(q, v += q) // it must be called with v = q
: //
v //
) => //
n ? // if n is not equal to 0:
i > n || // abort if i > n
F( // otherwise do a 1st recursive call:
n - i, // where i is subtracted from n,
i, // i is left unchanged
g(v = i++) // and p is updated to LCM(p, i)
) & //
F( // then do a 2nd recursive call:
n, // where n is left unchanged,
i, // i is incremented (this is done above)
p // and p is left unchanged
) //
: // else (n = 0):
a.every(x => // test whether all x in a[]
g(v = x) - m, // are such that LCM(p, x) ≠ m
a.push(p) // and append p to a[]
) //
```
[Answer]
# [R](https://www.r-project.org/), ~~139~~ ~~134~~ 129 bytes
*Edit: -5 bytes thanks to pajonk*
```
function(n,m)all(apply(expand.grid(rep(list(0:n),2*n)),1,function(v){while(sum(v[1:n])==n&sum(v)==2*n&any(T%%v[v>0]))T=T+1;m-T}))
```
[Try it online!](https://tio.run/##dVDLTsMwELz3K1ZUrbxgUJw0oRSlX5FbW5BpHbDkR2Q7gQjx7cH0wKFNbrszO7uz4wapG@u9fFPiVVnblEPdmmOQ1hBDNXKlCG8a1RPx1XBzenh38kScaIiSPpBkY5CmtwaRMvov7PD780MqQXyrSbdjG3PAsjTLcxurKFhy05Nqseh23TY5IFZldcee9X31gzgceSA3NVde7M0Nzi4cEkaBXaMphfQazSgUo2iGszlc4uu4OUeYg20D2Bq00Nb1UFsHZpsDqblUHoKFGIuNLgVw53j/N/r0wgoQSmhhgp/anSZjDCui9fUUk6@KqDpHsjfBtZOZpKOZZKPfr8auxWNZPkEUydRPxZRx9oiz4Rc "R – Try It Online")
Approach based on [alephalpha's answer](https://codegolf.stackexchange.com/a/238494/95126): upvote that!
Returns `TRUE` if the loop is impossible, or `FALSE` if the loop is possible.
Generates all pairs of integer partitions of `n` by first creating a *huge* array of twice all combinations of `0...n`, and then testing the LCM of rows whose first and second halves each sum to `n`. So runs out of memory for any `n` greater than 5.
---
# [R](https://www.r-project.org/), ~~204~~ ~~178~~ 176 bytes
*Edit: -2 bytes thanks to pajonk*
```
function(n,m,q=p(n),`[`=`for`){i[q,j[q,{k=1;while(any(k%%c(i,j)))k=k+1;F=F+!m-k}]];F}
p=function(x,y=x[1])c(list(x),if(y>1)unlist(lapply(2:y-1,function(i)p(c(i,y-i,x[-1]))),F))
```
[Try it online!](https://tio.run/##dY/NboJAFEb3PAW1Mbk3XpIOCDUl0yUvgaZQInFkHEZ@UibGZ6fowqR0XMzmJN89Z5pR120rvuX@S9a15mPZq6ITtQJFJzpzDQopSzOelXWT4UWkZzpO71JxFv8chNxDrgxUy2UBgo6IWPFqxeKEJ6uXk1ddd7s4uTqaP@4OZPiQsh0WIEXbwYAkSjCfDHt1BzLXWhrwP4zH6DETqOGmMJ6gIfWmPSIliGORd7Domr47mK1aoPPnP8DIZXPmk@vPWUBuZGHBnG2me6EN@m/ovLozeTSZNnYerqNpcY/fqjKX7ZN631IfWErXczY5gtACb9r/@ZG9kr2jM/4C "R – Try It Online")
Previous version with more-efficient (but significantly longer) integer partition function, allowing it to actually run on test cases with n>5 (although still times-out on TIO for n=16 and higher).
Returns `0` (falsy) if the loop is not possible, or a non-zero integer (truthy) if the loop is possible.
**recursive function p** gets all integer partitions (with some duplicates)
```
p=function(x,y=x[1])c(list(x),if(y>1)unlist(lapply(2:y-1,function(i)p(c(i,y-i,x[-1]))),F))
```
**function l** calculates the LCM of its vector argment
```
l=function(v){k=1;while(any(k%%v))k=k+1;k}
```
So, finally, **function possible\_loop** uses these to check if the loop is possible:
```
possible_loop=function(n,m,q=p(n)){for(i in q)for(j in q)F=F+!m-l(c(i,j);F}
```
[Answer]
# TypeScript Types, 526 bytes
```
//@ts-ignore
type a<A,B,Q=[]>=A extends[...B,...infer X]?a<X,B,[...Q,0]>:[Q,A];type b<A,B,N=[]>=A extends[0,...infer A]?b<A,B,[...N,...B]>:N;type c<A,B>=[]extends A|B?Exclude<A|B,[]>:c<B,a<A,B>[1]>;type d<A,N=[0]>=A extends[infer M,...infer A]?d<A,b<a<M,c<M,N>>[0],N>>:N;type e<T,A=[],N=[0]>=T extends[0,...infer U]?|e<U,[...A,N],[0]>|e<U,A,[...N,0]>:[...A,N];type f<T,N=[]>=T extends N["length"]?N:f<T,[...N,0]>;type M<M,N,P=e<f<M>extends[0,...infer T]?T:0>,Q=P,O=P extends P?Q extends Q?d<[...P,...Q]>:0:0>=f<N>extends O?1:0
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4BBAGgCFKBFAXgG0BdAPgfMPQA9x1EAE0hMAdONrjRsRADN0qQgA0WAfjJKalMeLqUADOwBcTPeRYBuXAUIAjCloByzdp258BwpvspSZ8xXNVeypaHVFHXwljRyt8IgBjB2oOVl5+IUhCcgAfalUAUR4EgBsAV0F0CjztYyTaMlC2JgBGdjibQQdnb1cudM8RfwVCAFko6TkRoK6qezJxpPHHNmbDShW2I1jrIiqAFUpyFw3mQw599wyvHz8pxQBVNRyqh+0pKkcWbXOX0jeqOFIucTB8NpZdoRZKRDj1XJcBplCI4mAAiEoCeDgAAWqLUjiM0MOQIM7Uho1Iy0oAAUGFVoaM2IibhNhop9mp9kZ9Gx6AxqZQAPL8q6DQjU1R0UVIuiqLrhAVSOjGfTcjjQlbMrKC1QtbmYbDxQj7fSEBhjUgtSiEFpsTAgQiOgB6qkNNn2LTNFoATNbvXaHc7XZD9t6vRSAMzWgBsAeAjsILrdRH2EfDpCjhAjcYTSZDABZ0wAOa0tACsOaDyeNZeLpe9PPt8ar1YAYqbzRSrYR-U3c8Gja3PZ3SL6s5XEwObK2wyPM-mJ3nB2mR9HrRGK32q5DW4XVzHG4HJ23ayOSzbY1vj0A)
>
> Port of Kevin Crujssen's 05AB1E answer, which was a port of alephalpha's Pari/GP answer, but explained in terms an engineer can understand. :-)
>
>
>
## Ungolfed / Explanation
```
// Returns [A / B, A % B]
type DivMod<A, B, Q = []> = A extends [...B, ...infer X] ? DivMod<X, B, [...Q, 0]> : [Q, A]
type Mult<A, B, N = []> = A extends [0, ...infer A] ? Mult<A, B, [...N, ...B]> : N
// Returns the GCD of A and B using the Euclidean algorithm
type Gcd<A, B> = [] extends A | B ? Exclude<A | B, []> : Gcd<B, DivMod<A, B>[1]>
// Returns the LCM of all the elements of A
type Lcm<A, N=[0]> = A extends [infer M, ...infer A] ? Lcm<A, Mult<DivMod<M, Gcd<M, N>>[0], N>> : N
// Returns a union of all integer partitions of T+1
type Partitions<
T,
// All previous numbers
Arr = [],
// The most recent number
N = [0]
> =
// U = T - 1
T extends [0, ...infer U]
// Return both:
?
// The paritions if we end N here
| Partitions<U, [...Arr, N], [0]>
// The paritions if we add one to N here
| Partitions<U, Arr, [...N, 0]>
// T is zero
: [...Arr, N]
// Converts a number literal into a tuple representation
type NumToTuple<T, N = []> = T extends N["length"] ? N : NumToTuple<T, [...N, 0]>
type Main<
M,
N,
P = Partitions</* M - 1 */ NumToTuple<M> extends[0,...infer T]?T:0>,
Q = P,
// Map over the cross of P and Q and compute the LCMs
Ns = P extends P ? Q extends Q ? Lcm<[...P, ...Q]> : 0 : 0
> =
// Return 1 if N is in Ns
NumToTuple<N> extends Ns ? 1 : 0
```
[Answer]
# [Rust](https://www.rust-lang.org/), 345 305 bytes
```
|n,m|{fn p(n:u64)->Vec<Vec<u64>>{let mut v=vec![];if n>0{v.push(vec![n]);for i in 1..n{for mut x in p(n-i).drain(..){x.push(i);x.sort();if!v.contains(&x){v.push(x)}}}}v}let q=p(n);for i in 0..q.len(){for j in i..q.len(){if(1..).find(|v|q[i].iter().chain(&q[j]).all(|a|v%a<1))==Some(m){return true}}}false}
```
[Try it online!](https://tio.run/##bZJhb4IwEIa/@yvqh5mewUZEnRnin1iyL4YsBEusgSqlMBLgt7s7dHGbXICkz/Xee9vDlIW9JpplkdIcWDNiGKm0LGHBtdVO1jaYvXD9Vq6XMNt9yHhLL652u4Y2ZqVlVVDJeLwPfZUwvZs3lbiUxZH3UIfgJ2fDFFOauULohlZUVRNB6ZkCcTBkQAho6lutAr8WxdlYDqg6rkR81hb3FHxSw0@DGjqMqiMfeYBSv1rNhchFKvFUfcMTMfVgKuFoBkSi9IG3VZvvVSiUlYaDiI9kZpLvTyGIKE15G7XVS7R1AYLg/ZxJnkFjpC2NZtaUEj0kUVrI7kq35/d3SD25dljmsEgXX9IAGZjs@yQFdx2GD9WD86ALhy2eqeew9SD1nukGdVfDeDF/5i4KLzbDfLVcD1X0FvsT/3PuDWBkywGM6t5qmFPPJ0721wOcoPv6NxHe/2OKqCiksZ8yH/OET3Eg0wzwc5/JbVbdqBtdvwE "Rust – Try It Online")
Also a port of @alephalpha's answer. A good chunk of it is just implementing partitioning and LCM.
* -40 bytes by replacing the LCM implementation
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 51 bytes
```
!Outer[LCM,l=LCM@@@IntegerPartitions@#,l]~FreeQ~#2&
```
[Try it online!](https://tio.run/##NYyxCsIwEIb3PsVJoFOEJmljl0pAEATFOpcOQVIttBVinEL76jGBZLn/4@6/b5bmrWZpxqd0AzRud/8Zpbvr6Yanxk8hxGUx6qV0K7UZzfhZvgLhqd/OWqnHhmjuWj0uprMIrbA/wtAh1PeQg3/NrCUYyIrBUgw0JMPAY7KQtb9XCWgRiHDfrRNVJffbDIKJRhOLhjKk77AqAi@Siqd/clhX9wc "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
*From [Codidact](https://codegolf.codidact.com/posts/282075) with [permission](https://chat.stackexchange.com/transcript/message/58267570#58267570).*
## Description
APL [trains](https://aplwiki.com/wiki/Tacit_programming#Trains) are a series of functions, that get applied to an argument in this way:
`(f g) x = f g x` here `f` and `g` are prefix functions
`(f g h) x = (f x) g (h x)` here `f` and `h` are prefix functions, while `g` is an infix function
`(a b c d e f) x = (a (b c (d e f))) x = a (b x) c (d x) e (f x)` here `f`, `d`, `b`, and `a` are prefix functions, while `e` and `c` are infix functions
Trains evaluate from the right to the left, so in the last example, `(f x)` is evaluated, then `(d x)`, then `(d x) e (f x)`, then `(b x)`, etc.
For the purposes of this challenge, when counting from the right, the the first, third, fifth, etc. functions are monads, and the second, fourth, sixth, etc. functions are dyads, except that if the leftmost function would be a dyad, it is instead a monad because there is nothing to its left that can provide it with a left argument.
The final evaluation order there is `fdebca`, or using numbers instead, `6 4 5 2 3 1`.
## Challenge
Given a number n, output the evaluation order of a train with n functions. Your result can be 0 indexed or 1 indexed.
## Examples
Here are the first 10 outputs starting from n=1 (1 indexed)
```
1 (0 if 0 indexed)
2 1 (1 0 if 0 indexed)
3 1 2
4 2 3 1
5 3 4 1 2
6 4 5 2 3 1
7 5 6 3 4 1 2
8 6 7 4 5 2 3 1
9 7 8 5 6 3 4 1 2
10 8 9 6 7 4 5 2 3 1
```
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
[:\:0 _2#:i.@-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61irAwU4o2UrTL1HHT/Kyj4OekpKHBFW@lbOejDZbg0udJtrVKTM/IdNKzTgBwlAwU7K4VMPUOD/wA "J – Try It Online")
Alternative solution that makes use of divmod with negative divisor.
### How it works
Example using `n = 5`:
* `i.@-` Generate descending range `4 3 2 1 0`
* `0 _2#:` Divmod each number by negative 2:
```
_2 0
_2 _1
_1 0
_1 _1
0 0
```
* `[:\:` Grade down; sort indices in the descending order of above `4 2 3 0 1`
Alternatively, ranking (grade up twice) on the forward range also works:
# [J](http://jsoftware.com/), 15 bytes
```
[:/:@/:0 _2#:i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o630rRz0rQwU4o2UrTL1/mtypdtapSZn5DtoWKcBOUoGCnZWCpl6hgb/AQ "J – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Trying out insomniac golfing.
```
o ÅÔò cÔiU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=byDF1PIgY9RpVQ&input=MTA)
```
o ÅÔò cÔiU :Implicit input of integer U
o :Range [0,U)
Å :Slice off the first element
Ô :Reverse
ò :Partitions of length 2
c :Map then flatten
Ô : Reverse
iU :Prepend U
```
[Answer]
# [J](http://jsoftware.com/), 16 14 bytes
```
[:/:>.@-:@i.@-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o630rez0HHStHDKB5H9NrnRbq9TkjHwHDWtD7TQgV8lAwc5KIVPP0OA/AA "J – Try It Online")
For 5:
```
[:/:>.@-:@i.@-
i.@- 4 3 2 1 0 count down
>.@-:@ 2 2 1 1 0 halve and round up
[:/: 4 2 3 0 1 grade up
(indices of lowest to highest values:
4 for 0,
2 for the first 1,
3 for the second 1, …)
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 8 bytes
```
<-2!-!-:
```
[Try it online!](https://tio.run/##y9bNz/6fZlVto2ukWKGrWFH7P90KxNZV1LX6n2BgpZCmrmCorWhowAXipCNzlJT@AwA "K (oK) – Try It Online")
A port of [xash's J solution](https://codegolf.stackexchange.com/a/229227/78410).
### How it works
```
<-2!-!-: Monadic train; input = n
-!-: Generate n..1; colon attached to force a monadic train
-2! Truncating division by 2
< Grade up
```
[Answer]
# JavaScript (ES6), 35 bytes
Returns a 0-indexed, comma-separated string.
```
n=>(g=k=>--n?n-k+[,g(-k|1)]:+!~k)``
```
[Try it online!](https://tio.run/##DcbBDoIwDADQO19Rb21mjVzF4ocYEpbJFh1pDRAuor8@Ob338qufw/R8L6z2GEqUotJikiwts96Us7sfE3Leauou7vDL1Pcl2oQKAnUDCtfd8x7nCD4VQDCdbRxOoyWMqERN9S1/ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~39~~ 38 bytes
Returns a 1-indexed array.
```
n=>(g=k=>n?[n---k||1,...g(-k|1)]:[])``
```
[Try it online!](https://tio.run/##DcY7DoMwDADQnVN4tEUTNSvU9CAICQQk4iO7AsQCnD3N9N7cnd3eb9PvMKLDGD1H4QoDL1zJtxZjzHLf7mWtDZjqqCnqhto2et1QgMGVIPBJvlPynODKAHqVXdfRrhrQoxCV2RP/ "JavaScript (Node.js) – Try It Online")
### How?
We start with `k = 0`. At each iteration, we output `n - k || 1`, decrement `n` afterwards and update `k` to `-k | 1`, which means that we alternate between `1` and `-1`.
The `|| 1` in `n - k || 1` is required for the last iteration if there's an even number of terms in the sequence:
```
n | 10 9 8 7 6 5 4 3 2 1
k | 0 1 -1 1 -1 1 -1 1 -1 1
n - k | 10 8 9 6 7 4 5 2 3 0
n - k || 1 | 10 8 9 6 7 4 5 2 3 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ṖUs2U;ƒ
```
[Try it online!](https://tio.run/##y0rNyan8///hzmmhxUah1scm/Tc0CDrc/qhpjTcQR/5XMORSMFIAkcZAUkHBiEvBRAEkYgwWNAUzTGBSZmC2KZICczDXDFWZBVjEHEOxJVjQAosWQwOwuCVWjQA "Jelly – Try It Online")
-2 bytes thanks to caird coinheringaahing
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ḶHĊUỤ
```
[Try it online!](https://tio.run/##y0rNyan8///hjm0eR7pCH@5e8t/QIOhw@6OmNe7/FQy5FIwUQKQxkFRQMOJSMFEAiRiDBU3BDBOYlBmYbYqkwBzMNUNVZgEWMcdQbAkWtMCixdAALG6JVSMA "Jelly – Try It Online")
By porting xash's [J answer](https://codegolf.stackexchange.com/a/229227/68942).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~47~~ ~~46~~ 45 bytes
Saved a byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Saved another byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
f=lambda n,k=0:n*[0]and[n-k or 1]+f(n-1,-k|1)
```
[Try it online!](https://tio.run/##bVDBToQwFLzzFXNrqyWhwC67JPVHKgeE1iVol0BNVOTbsTRrjIZeZt7MmzRvhg93udpsXY18qV@f2hqW9zIp7Z1Kqtq2ysY9riNEdW@ojQWP@y/BVqcnN0FirO2zpoJDCBbp90E3Trdep1Ci4lCpdzbMPHKkG809cmQ34xBo/msfw3T4s1QE4fh/9RS0YidwDvJpPyaSYJ3302BRc9FNr8ftDPL4lhZ5QzgCExlhkfF1OK7RWXx2Aw1VcPwcz8oI/m3lGOpYGIaxs44aMrsybRfED5inBfPtH6WlnKqFsPUb "Python 3 – Try It Online")
Uses idea from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/229221/9481).
[Answer]
# [Python 3](https://docs.python.org/3/), 44 bytes
```
lambda n:sorted(range(n),key=lambda i:n-i^1)
```
[Try it online!](https://tio.run/##LcoxDoAgDADA3Vd0bBMcGjcSfmJMMII2aiHIwutx0Pkut3oknXp0c7/8vW4e1D6p1LBh8boHVDJnaO5HsTrKwtRjKiAgCt9iA8xkB4BcRCtGFKL@Ag "Python 3 – Try It Online")
Thanks xnor for -3 bytes by change the key function for sorting.
[Answer]
# [Haskell](https://www.haskell.org/), ~~52~~ ~~48~~ ~~45~~ 42 bytes
Caught mistake thanks to rak1507
Saved 3 bytes thanks to Hakerh400 on Codidact
```
f n=n:g[n-1,n-2..1]
g(b:c:t)=c:b:g t
g t=t
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzbPKj06T9dQJ0/XSE/PMJYrXSPJKtmqRNM22SrJKl2hhAuIbUv@5yZm5ilYWSl4@itoaHKBebYKKflcCgq5iQW@8QoFRZl5JQoqIJ5CmkK0IdAsg9j/AA "Haskell – Try It Online")
`g` takes the rest of the trains.
```
-- This is a fork, so append c (monad) and b (dyad)
-- and continue with the rest of the train
g(b:c:t)#=[c,b]++g t
-- t is either empty or a single monad, so finish it off
g t=t
```
`f` simply starts it off with the last function `n` and the other trains `1..n-1` (in reverse).
```
f n=n:g[n-1,n-2..1]
```
[Answer]
# posix SH + [GNU sed](https://www.gnu.org/software/sed/manual/sed.html#The-_0022s_0022-Command "using the 'm' regex modifier"), 43 bytes
```
seq $1|tac|sed -zE 's/(\n.+)(\n.+)/\2\1/mg'
```
```
seq $1 # 1..the argument (inclusive)
|tac| # reverse
sed # replace
-z # null terminated. basically this means that \n is
# treated as a normal character, needed because
# seq and tr operate on lines
E # extended regex so we can use () instead of \(\)
' do this replacement '
s/(\n.+)(\n.+)/\2\1/mg
s/ / /mg # replace all occurences of
\n.+ # a newline followed by non-newlines
# the (GNU extension) m modifier makes
# . not match a newline
( )(....) # twice
/ # with
\2\1 # swap their places
```
# posix SH, 50 bytes
```
seq $1|tac|sed -zE 's/(\n[^\n]+)(\n[^\n]+)/\2\1/g'
```
From [codidact](https://codegolf.codidact.com/posts/282077/) with permission
[Answer]
# [Python 3](https://docs.python.org/3/), ~~48~~ 44 bytes
```
f=lambda n,x=2:-~n*[n]and[n][:n]+f(n-x,-x|3)
```
[Try it online!](https://tio.run/##DcSxCoAgFAXQva94o5YO5ib4JdHwoiyhbiINBtGvW2c46b62E7bW4Hc@ppkJqvje6RftgJEx/w8OYxcEdFG6PFbWcGaKFEGZsS7CKDJGuoYo5YhLBBGlrB8 "Python 3 – Try It Online")
The forward differences are always `-2, +1, -3, +1, -3, ...`, except for the last one for even cases. `[:n]` removes a `0` that would occur if we always use the same sequence of forward differences.
`-x|3` maps 2 and 3 to -1 and -1 to 3.
[Answer]
# [R](https://www.r-project.org/), 42 bytes
```
function(n)pmax(n:1-c(0,(-1)^(1:n)[-1]),1)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7MgN7FCI8/KUDdZw0BHQ9dQM07D0CpPM1rXMFZTx1Dzf1hqckl@UWZVqkaaJlDG0EDzPwA "R – Try It Online")
Implementing [@Arnauld's algoritm](https://codegolf.stackexchange.com/a/229221/55372)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
.+
$*
1
$.'¶
(¶.+)(¶.+)
$2$1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLy5BLRU/90DYujUPb9LQ1ISSXipGK4f//hlxGXMZcJlymXGZc5lwWXJZchgYA "Retina 0.8.2 – Try It Online") Link includes test cases. 0-indexed. Explanation:
```
.+
$*
```
Convert to decimal.
```
1
$.'¶
```
Create the range in reverse.
```
(¶.+)(¶.+)
$2$1
```
Swap pairs of values after the first.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
⟦θ⟧F⪪⮌…¹N²I⮌ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO6MFbTmistv0hBI7ggJ7NEIyi1LLWoOFUjKDEvPVXDUEfBM6@gtMSvNDcptUhDU1NTR8FIU1MBotk5sRihIRMoaf3/v6HBf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Explanation:
```
⟦θ⟧
```
Print the input on its own line.
```
F⪪⮌…¹N²
```
Reverse the range from 1 to the input, split into pairs, and loop over each pair.
```
I⮌ι
```
Print the reversed pair.
] |
[Question]
[
a.k.a. You Can Output Anything With Labyrinth Or Hexagony™
## Challenge
In a recent [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") [challenge](https://codegolf.stackexchange.com/q/223439/78410), I could print any character with only half of the allowed digits with very small character count, [by abusing the "digit commands" and modulo-256 output function](https://codegolf.stackexchange.com/a/223447/78410). Now, it's about time to make a general metagolfer for this kind of challenges.
For the sake of simplicity, we only consider Labyrinth programs of the form `<digits>.@`, i.e. construct a number, print it modulo 256 as character code, and halt. Also, the sequence of digits acts exactly like a number literal in this case.
Now let's assume we want to solve a [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenge in the form of:
>
> Given the characters `.@` and a subset of `0-9`, print a character.
>
>
>
Given a subset of digits `D` and the target character `c`, find the **shortest** number `N` which will solve the hypothetical challenge above. In other words, `N` should satisfy the following:
* All the digits of `N` are in `D`.
* The Labyrinth program `N.@` prints the character `c`, i.e. `N % 256 == ord(c)`.
+ The byte value of `c` can be anything between 1 and 255 inclusive.
* Out of all possible `N`s satisfying the above, your program should output one that has the shortest length. If there are multiple possible answers, your program is free to output any of them.
You may take `c` as a character or an integer (charcode), and digits in `D` as integers or digit characters. Also, you may assume `D` is already sorted.
Assume the answer exists. Note that some conditions will lead to "no answer", e.g. only odd digits are allowed but you need to print an even character, or vice versa. You may assume that such conditions will never be given as input.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
The value of `c` is given as its character code.
```
D = [1, 2, 3, 4, 5]
c = 1 => N = 1
c = 57 => N = 313
c = 254 => N = 254
c = 100 => N = 1124 or 4452
c = 107 => N = 1131, 2155, 2411, or 3435
D = [1, 2, 4, 6, 8]
c = 58 => N = 826
c = 71 => N = 1111111
c = 255 => N = 26111
D = [7]
c = 49 => N = 777777
```
[Answer]
# JavaScript (ES6), 46 bytes
*Saved 6 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
Expects `(D)(c)`, where `D` is a string of digits and `c` is an integer.
```
D=>c=>eval(`for(;/[^${D}]/.test(c);)c+=256;c`)
```
[Try it online!](https://tio.run/##bY/BasMwDIbveQpRdrBZ11S2FGcE95TzXmBsNLhJaQn1SEIvpc@eeetghlgHYaPP/vWdm2szuuH0Nb1c/KGdOzvXdufsrr02vdh3fhBV/v75dKvvH/lmasdJOFlJ92wVF5Xby7kGCytUmnhVZc5fRt@3m94fRSdqKRBASshzeAsYLudsorlGvSQU0z8RLomM7TbKQEXgByBilUJNjGpcg0Lm0AnDObzTpDnL/qSoKFNSXEZLl6pYEgZj7Uel1DhSK36YR7JJpdJr9Kf5rfkb "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ ~~10~~ 9 bytes
```
Ɠ+⁹$Dḟ³Ɗ¿
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//xpMr4oG5JEThuJ/Cs8aKwr///zI1Nf9bMSwgMiwgNCwgNiwgOF0 "Jelly – Try It Online")
-1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
Full program that takes `D` as the first argument and `c` in STDIN
## How it works
```
Ɠ+⁹$Dḟ³Ɗ¿ - Main link. Takes D on the left
Ɠ - Read c from STDIN, set N = c
¿ - While:
Ɗ - Condition:
D - Digits of N
ḟ³ - Remove all elements of D
This is an empty list (falsey) iff all digits of N are in D
$ - Body:
+⁹ - Add 256 to N
```
[Answer]
# Scala, 59 bytes
```
d=>n=>Stream.from(1)find(x=>s"$x".forall(d.toSet)&x%256==n)
```
[Try it in Scastie!](https://scastie.scala-lang.org/lcPKiy5sQPagQKn3XP67Kw)
Just a brute force solution.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
NθW⁻⪪Iθ¹⪪η¹≧⁺²⁵⁶θIθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05qrPCMzJ1VBwzczr7RYI7ggJ7NEwzmxuAQop6NgCMQQoQwQR1NTwTexwLG4ODM9LygzPaNEIyCntFhHwcjUTEcBZFZAUWYeXLum9f//5oZchkYmZhb/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input of `N` and `D` as a string. Explanation:
```
Nθ
```
Input `N` as an integer.
```
W⁻⪪Iθ¹⪪η¹
```
Filter out the digits of `D` from the digits of `N`. While some remain, ...
```
≧⁺²⁵⁶θ
```
... add 256 to `N`.
```
Iθ
```
Output the final value of `N`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
πdµ∞╔▓|▒
```
[Run and debug it](https://staxlang.xyz/#p=e364e6ecc9b27cb1&i=%5B1,2,3,4,5%5D,1%0A%5B1,2,3,4,5%5D,57%0A%5B1,2,3,4,5%5D,254%0A%5B1,2,3,4,5%5D,100%0A%5B1,2,3,4,5%5D,107%0A%5B1,+2,+4,+6,+8%5D,58%0A%5B1,+2,+4,+6,+8%5D,71%0A%5B1,+2,+4,+6,+8%5D,255%0A%5B7%5D,49&m=2)
## Explanation
```
WcEx-!CVB+
W loop forever
c copy c
E get digits
x push D
- set difference
!C if empty, break out of the loop
VB+ else add 256
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~13~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes `D` as an array and `c` as an integer, in reverse order.
```
@ìkV}f@±X©G²
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QOxrVn1mQLFYqUey&input=NTcKWzEgMiAzIDQgNV0)
[Answer]
# [J](http://jsoftware.com/), 29 24 22 bytes
```
(]256&+~0 e.e.~&":)^:_
```
[Try it online!](https://tio.run/##Zc67CsIwFAbgvU/x06G1qCE5uRroJDg5uauDpIiLb9BXj7FJl/TAWf6Pc/nElvUTRo8eB3D41EeG8@16ibs7adPtZ47AApu71g8P/4xDE17vLwTG1AQJBY0JIsdSyAq0zUJaVZKSsktQbYLz1eTmFLdNRkemmIKB@19z69hSldryJZmtkdZlq10qsU2xOsUf "J – Try It Online")
-2 thanks to Bubbler
Call it like: `1 2 3 4 5 f 57`, which returns 313.
* `]256&+~...^:_` Keep adding 256 while...
* `0 e.e.~&":` There is a digit of the right arg that's not in the left arg.
[Answer]
# [Haskell](https://www.haskell.org/), ~~38~~ 34 bytes
* -4 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor), for using `until`.
```
f d=until(all(`elem`d).show)(+256)
```
[Try it online!](https://tio.run/##XcxBDoIwEAXQfU8xiS7aOBpAKorUvYk3ICQQWoVYi4Ea4PSIxIW4fH/@nyJr7krrYbiCFC9jS00zrWmqtHqkkm2aomoZXXl8xwa6YOJKHllphKwIxBLzJFq3VS2baHm6KXspjSKglYVOFCqT03o80XoEyDCMz8Ym7NiLKcgJPOvSWNphj92iZwQ@z4fYRQ@36CNPwCW/4sGMHvdndh3nz9@@jzvcj/P9jIE7o8c5iYME/MMb "Haskell – Try It Online")
Takes `d` as a list of `Chars` (i.e. a `String`) and `c` as an integer.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 36 bytes
```
"$<%'"~L$`.+$
/[^$&]/+`.+¶$$.($*257*
```
[Try it online!](https://tio.run/##K0otycxLNPyvqhGcoPNfScVGVV2pzkclQU9bhUs/Ok5FLVZfG8g5tE1FRU9DRcvI1Fzr/39DHUMjYxNTLlNzKMPI1ATKMjQwgLNgsqYWQIaJmQWXuSGUYWRqCmWZWOqYAwA "Retina – Try It Online") Takes `N` and `D` on separate lines but test suite splits on `,` for convenience. Explanation:
```
"$<%'"~`
```
Evaluate the following generated Retina program passing in only `N` as input.
```
L$`.+$
```
Use `D` to generate the Retina program.
```
/[^$&]/+`
```
The generated program repeats while `N` contains a digit not in `D`.
```
.+¶$$.($*257*
```
Each loop of the generated program adds `256` to `N`. This is a little unclear due to the quoting. The generated program looks like this:
```
/[^12468]/+`.+
$.(*_[256 more `_`s]
```
The `*_` converts `N` to unary. The 256 `_`s then effectively adds 256, after which the `$.(` converts the sum to decimal.
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
f=lambda d,c:f(d,c+256)if{*str(c)}-{*d}else c
```
[Try it online!](https://tio.run/##PY3hCoMgFIX/@xT@1LbFtKwW9DDNjAQzUWNE9OxOmezCveeDczjXHH7ZdBXCPKhxfU8jnO68n1G8N8oaLOezcN4ijq/HWUyXUE5AHuRqNuuhOxyIWzrhreC7dXLTSq7SI/KMg8FnkUpA0oNUO0htdo9w6YyKEQygsVJ7lL4l5RjjQGhVM0jAT1mbgbI6U2z@U3LrpoOsy9CSDJQx0ML69QU "Python 3 – Try It Online")
My first attempt at golfing in Python (or, for that matter, in an imperative language). Suggestions are welcome! Especially about conditionals, I don't really know all those `and` and `or` tricks, but I almost never see `if`-`else` used in Python codegolfing, so I guess I'm doing something wrong :).
Also, I had to increase the default recursion limit for some testcases, I hope that's ok.
[Answer]
# [Python 3](https://docs.python.org/3/), 70 bytes
```
d,n=set(input()),ord(input())
while not set(str(n))<=d:n+=256
print(n)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P0Unz7Y4tUQjM6@gtERDU1MnvygFzuEqz8jMSVXIyy9RAKkpLinSyNPUtLFNscrTtjUyNeMqKMrMKwGK/f8PAA) Simple brute-force solution.
[Answer]
# [Python 3](https://docs.python.org/3/), 82 bytes
```
f=lambda d,c,k=0:(all(_ in d for _ in str(k))and chr(k%256)==c)and k or f(d,c,k+1)
```
[Try it online!](https://tio.run/##HYxbCoAgEACvsgjBLvnRy6DAs4QpUmga5k@nt/BvGIa533zEMJZipVfXbhQYrrmT3YrKe9zgDGDAxgQVn5zQEalgQB8/NoOYSUpdjYM/s1gHbU/lTmfIaJH1wzgJxtnCiMoH "Python 3 – Try It Online")
Plain brute force, takes `D` as a string of the numbers and `c` as a character.
[Answer]
# [R](https://www.r-project.org/), 68 bytes
```
f=function(D,C)"if"(all((utf8ToInt(paste(C))-48)%in%D),C,f(D,C+256))
```
[Try it online!](https://tio.run/##ZcpBCoMwEEDRfY4hCDN0CiZkTCp0FTfd9wIiHQhIlDaeP9KKdOHu8fnvUuQuaxpznBP0FLCKUsEwTQBrFv@cHynDMnzyCwLi1XqsY6p7pEDy/S@GW8QioDsmjWoHu0OG7UHdNH/@hhE0GbLUkkdif0pOn5Jh3ptDsjdUqmw "R – Try It Online")
Fails in TIO for larger test-cases.
---
**without recursion:**
### [R](https://www.r-project.org/), 75 bytes
```
function(D,C){while(T%%256-C|any(!(utf8ToInt(paste(+T))-48)%in%D))T=T+1;+T}
```
[Try it online!](https://tio.run/##ZcqxCsIwEIDhvW/hELgjV2hCro1Kp3ZxzwuU0mBBUtEUEfXZI1iKQ7ePn/@WfJ38HPo4TgFaavD1OI@XAZwQmsu8eXfhCTuYo7duOoUI1@4eB5AOMTcWxRhEi@hqJ9VRuk/yoA5MCrMFXK3SbFaqovjzN/SgSJOhkiwS202q1CZp5qVVSGaPWZa@ "R – Try It Online")
] |
[Question]
[
# Interpret Volatile
[Volatile](https://esolangs.org/wiki/Volatile) is a stack-based esolang made by A\_/a'\_'/A that only has 8 instructions and is turing complete. However, it is also non-deterministic... meaning that programs don't always give the same output. Your task is to interpret this language.
## Language specs
Taken from the esolangs page:
```
~: Push a random integer in any range of integers. Minimum range of 0 through 32768
+: Pop 2 values and push the sum of the 2 values
-: Like +, but subtracts
*: Multiply
/: Divide. 0-division will result in an error.
:: Duplicate the top of the stack
.: Output the top of the stack without popping it
(...): Execute ... inside a while loop when the top of the stack is not 0
```
Everything else is disregarded
## Input
*Note that these programs may randomly fail*
```
~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.~:/:::::::::::::::::::::::::::::::::+++++++++++++++++++++++++++++++++.~:/::::::::::++++++++++.
~:-.~:/+.(~:/+.)
~:-:/
```
## Output
```
73 102 109 109 112 45 33 120 112 115 109 101 34 11
0 1 2 3 4 5 6 7 8 9 ...
<Any Error Message>
```
More examples, as well as a reference implementation (use the second one, found under *(Another) python 3 interpreter*) can be found at <https://esolangs.org/wiki/Volatile>
## Scoring
This is code-golf, so shortest answer in bytes wins
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=191573;
var OVERRIDE_USER=78850;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 35 bytes
```
"~:/.()"”žGÝΩ DŠéõq}÷ = [D_# }”#‡.V
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fqc5KX09DU@lRw9yj@9wPzz23UsHl6ILDKw9vLaw9vF3BViHaJV5ZoRYorfyoYaFe2P//QA1WVALaVAJ6VHQTXRw8OHxDT0@N@m2oe48MH1Lb7EEYAwMUE6NpbrhF52jJODT8RJRfSDQFSRwA "05AB1E – Try It Online")
Transpiles Volatile code to 05AB1E, then evals it. `*`, `+` and `-` can be left as-is. `:`, `.`, and `)` have direct one-byte equivalent. The other commands take a few bytes each. Unfortunately, 05AB1E does not crash on division by 0, so this is instead implemented by a conditional "quit if top of stack == 0".
[Answer]
# [Julia 1.0](http://julialang.org/), 334 bytes
```
a\b=push!(a,b)
√a=pop!(a)
v(q,s=[],l=0)=(i=1;
for c in q
!r=c==r
i+=1
!')' ? (l<1 && break;l-=1) :
!'(' ? (while s[end]!=0 v(q[i:end],s) end;l+=1) :
l>0 ? continue :
!'~' ? s\rand(Int) :
!'+' ? s\(√s+√s) :
!'-' ? s\(√s-√s) :
!'*' ? s\(√s*√s) :
!'/' ? s\(√s÷√s) :
!':' ? s\s[end] :
!'.' ? print(s[end]," ") : 0
end)
```
My first "interpreter" of any type, it was easier than I expected. I did some basic golfing, but there is probably room for more. I made it print a space after the output for . to mach to example output. The ungolfed version is in the header at the TIO link. Example usage `v("~:-:/")`.
+41 bytes to fix the bug Night2 pointed out by adding a loop counter. Now I see why transpiling is a good option. A good test case is `~:-.(~:/+.)(~:/+.())~:-.` with expected output `0 0`
[Try it online!](https://tio.run/##7ZfdbpswFMfv/RQHFrV2gIR00jrBvF3vGZJeEOI0bi1DMWTpTa/3DHuRPkDfZC@SGjtpvCid2inqxxQkMP6f4/PhHyBx0QieDRZLUchzLsumBgr@TdJP9nQEezp6e6zpRQp@G928ZFOH3t57e//Q4b5jv0ECr0Ti8Mz9bzgPX8b30dOTenlmFEf30Qdo5HkhpmyCpo3Ma15ImM/xVajo8CwUNCaI0wGaFhXkwCVcIR7oeU7pMTmGb4DFlwEcHcG4YtllKiI6IJAYMzbmHzMuGKghk5Mzj8agQw950s5CRUCPKYjALhJfY70iL2TNZcNWUW7aKGWjZh5WYZXJCY6Tjyennz4TvQSMS@C6lEWpBxKsxnUx0Q6faMunu8Onu@XT3@Fzd7vllLhOtvW1qWdMFZc1tobQB781Gk1I7LOqaveadvIQOri@LlkxxTkh7cx2q28V7SifIB2gPZfZaExtviwcE/T756@Mmpoygv5gSbGGmbo0vYrqqJWl6v2Nqfdkoo8C9SxONTIgv8vaMPQsQTXCunAVtBebL3LkaCN3Hbm7kfuOfHe70ROr24KN8hgEiNvdJMs51r8dUQ/rtyboETtgQlrNJ@maFEF6bx/@VVy9rq6RjZH0NaU8q/MZsMUDY7Yw6FLYLFmltKlsXjfV8h4 "Julia 1.0 – Try It Online")
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), ~~266~~ 264 bytes
```
DS͗{r;'ui[0[0y̤<<<<<?+f2,;$"!0/"?*7≠0:S͗\
RS͗}:'~=?!\:':=?!\:'+=?!\:'-=?!\:'/=?!/:'.=?!\:'*=?!\:';=?!;:')≠3*?04B͍:'(=?!S͗
U/lA`R耀`S͗/?7 :S͗/?+f1+S͗/?3 -S͗/?3 $ '$:S͗/?7 *S͗/
U\m(d*?"SO!"$;
{:'(=?!\:')=?!\R
~/?)0l{͗/?8 {͗l}͗/U
\}͗21B͍
```
[Try it online!](https://tio.run/##NY5BCsIwEEX3OUVaCmkT20QrKBMlKO6FSldmUVAEoboQXEixeAHXXsBDeAi9h7eo0wZnMe9NmPzkdD7uN02zWH0e1Umz836t1uryfk7aMmI36OnA95T0DR9N3y8FuGhJhv0KrJ4azwIDB@EQO0iEBJa4iTtohAYWYVLKjRrOP3dgIR5iHsllOSuy7@1W4CTNiFLoROz6opOU0vgvWAFlAfxXeSskt4dwy42/Wnp@oEnlwm37IiIjtTSRKqv2zpgiyitqTqhFDvr4m6apIU5qkCIJux79AA "Runic Enchantments – Try It Online")
Due to limitations built into Runic, it can only support program lengths (and stack size) of ~501. Programs that are too large will simply fail. If the stack grows too large, it will error with `SO!` (wasn't required, but was better than silent termination; cost 24 bytes). If the program attempts to divide by 0, it will print `/0!`.
Errors are appended to the end of standard output as Runic has no way of writing to STDERR.
[This version](https://tio.run/##KyrNy0z@/98l@Oz06qKzvYXW6pnRBtEGlWeW2ECBvXaaqY61ipKigb6SvZa57ZkdBlZA1XUxXEFAqvZsr5WBqpV6na29YoyVuhWIUrBS14ZwdSGUPpDSt1LXg/C0IJQ1kLK2UtcEGmiiZV9nYOJ0tlddAygINJUrVEFBQd8xIehFQ0MCyDJ9ewsFKwhDO81QG8IyUdCFMYBARUFdxQqmVgvMABsTo5CTq2GuZa8U7K@opGLNFVQNdTLIrhig/UCSKxSoS0FB0yCnGmxAEpDKqT07XZ8LqB9IGxkCHff/f52VvhWVgDaVgB4V3UQXBw8O39DTU6N@G@reI8OH1DZ7EMbAAMXEaJobbtE5WjIODT8R5RcSTUESBwA) will support arbitrarily long programs, but is still limited to a stack of ~90 (and thus errors out on the 2nd result of the first test program) and has not been golfed very well (the increase in command length between `S͗}:` and `S͗}͍:0%:` required some additional spacing to get sections to line up, but that extra space also allowed for more `<` for a larger max stack size).
Alternatively, [this program](https://tio.run/##NY1BisJAEEX3fYpKCHTSPUl3VIhUjzQO7oUEV/ZCGBGEzCwEFxIMXsC1F/AQHkLv4S0ylTRTi3q/is//h@Pv/rvrFtXr1hwMP@7Xeq1Pz/tnP1buRh8mCgOtQiuK2fOhkYyOlbTPyNuZDRxy9JAeqYciKOSZv4SHIRjkCSWNhdWTr9cVeUxPymMrUPNN@b5cNnQpW6Q5DmIHIAcxBkj/BU0EPPKOAkD0giJcLuufeCtsWC2DMDJaUwdrfIvrqwnl0MxaZRNdN33CFAj1meSKgSOOcnJ0XYtp1qKSWTzs5A8) will avoid `~` generating a zero and the program will terminate after 1 million execution steps (a safeguard against infinite loops built into the Runic interpreter). Also includes a few bytes to skip over excess NOP space and run a little longer.
1. Stack oversize fizzling occurrs at (IP mana+10) and the check I put in for Volatile's stack is `sizeof(stack) < mana` and there are 5 IPs that merge and combine their mana (50 initial). Increasing that value to the true limit (the +10) would cost another 2 bytes and I left the logic golfy instead of accurate.
### Explanation
[](https://i.stack.imgur.com/1nuJz.png)
1. Program begins in the top-center blue area along the `<<<<<` and the five IPs merge together at the `y`
2. IP moves to the left, setting up the stacks and reading input and moves to the cyan section
3. IP moves to the right down this line checking the top char on the stack for what command it is. This line continues to the right further than is visible. when the correct instruction is found it executes the code on the line below to the left (skipping over other sections to return back to the cyan via the blue).
4. Magenta section is executed during `~` or `:` commands to error on Stack Overflow, yellow section is skipped if the stack is not overfull and returns via wraparound to the dark blue.
5. Far off to the right when the `)` is found the program branches to the red section and moves to the right.
6. This section rotates the command stack to the right until a `(` is found (proceed green).
7. For each additional `)` is found (proceed orange), the stack depth stack is bumped and when a `(` is found, the stack depth stack is popped once (proceed dark green and orange re-entry)
8. If the depth stack is empty continue following green to the `B` and return to cyan to main parsing loop, otherwise wrap via orange->yellow->red (re-entering the loop-reset loop).
9. The purple in the top right handles division, if the value to divide by is 0, the brown section handles the error and termination. Re-enters main parsing loop by skipping over the cyan section.
[Answer]
# [Lua](https://www.lua.org/), 323 bytes
```
l,s=load,{}u=l't=...s[#s+1]=t'o=l'n=t s[#s]=_ t=s[#s]return n'math.randomseed(os.time())l((...):gsub('[^-*+/:.()~]',''):gsub('.',{['~']='u(math.random(1e5))',['+']='u(o()+o())',['-']='u(o()-o())',['*']='u(o()*o())',['/']='u(0~=s[#s-1]and o()//o()or-_)',[':']='u(t)',['.']='print(t)',['(']='while 0~=t do ',[')']='end '}))()
```
[Try it online!](https://tio.run/##7ZTPasMwDMZfxbCDpPxxlsMuAT9JyEpKzBpw4mI77FCaV0@dZCk9biN07YjBxvpJfOhDxqorh0FFVihdVtHp3AkFTnDObf5iw7QQDrRHrXBsJIXYMSemm5GuMy1roSndgZuyrXRjpaxQW@7qRiKRQvRKlH3Ybo@Qv8dBmGQcqS8gAlg4h@iUQw@FgA5vxDCVb0QQ5RDOOY0U@j2h@IriBQVXFCwomdFrP7Ucp4UXZj6ZJP7QJt5NVdlc5aaAj8HR1K37AjiCz0OtJPM6jlWajZhGLL0cnImQhmHosyRbaYUrLb5iT3dp@DHc3NPU5u3Z7f3C4draDziBP5rE9ub@2zi3n/E5PH3Lyw9VbvgF "Lua – Try It Online")
Transpiles the Volatile code into Lua. Note that `s` represents the stack itself, `u` pushes onto the stack, `o` pops off the stack, and `t` represents the value at the top of the stack.
| Volatile | Lua |
| --- | --- |
| `~` | `u(math.random(1e5))` |
| `+` | `u(o()+o())` |
| `-` | `u(o()-o())` |
| `*` | `u(o()*o())` |
| `/` | `u(0~=s[#s-1]and o()//o()or-_)` |
| `:` | `u(t)` |
| `.` | `print(t)` |
| `(` | `while 0~=t do` |
| `)` | `end` |
[Answer]
# [PHP](https://php.net/), 196 bytes
```
eval(strtr($argn,[':'=>($v='$a[]=').$e='end($a);','~'=>$v.'rand();','+'=>($q=$v.$p='array_pop($a)')."+$p;",'-'=>"$q-$p;",'*'=>"$q*$p;",'/'=>"$q/$p;",'.'=>"echo' ',$e",'('=>"for(;$e){",')'=>'}']));
```
Input 1: [Try it online!](https://tio.run/##7ZTbCsIwDIZfRUYgrTvdr1bvfAkRKVoPIGvXjYGIProzszdeqgxPLBeF/2sS8pNSu7XNaGLp1LXas7JylWOg3CaPZpihHDOoJYKazSXyBLREna8ogQuM8Ez3UCfoFLEbCW8VhSQKVqJyTh0W1ti2guqDEKwIIowpLYAi9mro1dCr1KvUq6RVerk1OMAINBHWkrVxTIDmRwKcAJ5wzrlomnOWZh1F2FEkHc70loG/w807TfXeft3eCw677v2FG/jQJvo392/r7H/G3/D0kJcnu9zxi7HVzuRlE0@v "PHP – Try It Online")
Input 2 (0, 1, 2, ...): [Try it online!](https://tio.run/##JYtBCsIwFESvIuXDT2yS7hujOy9RigSNVpAmTUtBxB7d@NtsBt6bmdCFdDgFSjfbFxunOEUGNj560WCN5shgNgi2aQ1yBc6g62804BoFLtTDrDBacpspt8dgyEIwaGO070vwYX3Qvygh6EKgpFkBg8y0z7TPVGWqMqmV3LXzuEMBjgxbzd1HpsHxDwlOAr/Ycq5TWmqplroqFduS/3yYnr4fkzz/AQ "PHP – Try It Online")
Input 3 (Division by zero error): [Try it online!](https://tio.run/##JYvRCoIwFIZfJeTA2XTTe9fqrpcQiVErg3DHKUJEPnp2bDcHvu/8H3W07o/E18/uKcYpTlGAi/deNVijPQiYLYJrWouyBG/R91ceSIMKF/7DXGJ07P6m@BeDZQtk0cXoXmcKtBXcZwWQyRRqnmUw6ER5ojxRlahKVG7kL13AHSrwbMRmbiEKA16@WUgW@MFWSrOuS63r6htoeoR@XPXpBw "PHP – Try It Online")
Just translates the code to PHP and evaluates it!
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~178 172~~ 171 bytes
Transpiles to JS. May throw either `Z is not defined` or `x is not defined` if the code attempts to do something bad.
```
s=>eval(s.replace(/./g,c=>`S.push(${c>'}'?'x=Math.random()*1e5|0':c>'9'?'x':c=='.'?');print(x':c<')'?');while(x){(0':c<'*'?')}(0':`1/(x${c}=S.pop(S.pop()))?x:Z`});`,S=[]))
```
[Try the 1st program online!](https://tio.run/##7ZTPCoJAEMbfRYKd6c9qh6CstSfo1K0IXGxLw2pRM8Hs1W2tS8cKsQznsMx@AzPz41t2x2MeOoEno148zDcsD5klYu5DSAMhfe4I0Km@7TrMsudUnkIXWqljkYxMScJmPHJpwA/r4x6w3ReDi0FMVR0VVZUxRqhKcSwD7xBBIU0I3pWz6/kCEkzBuKvtQs2Ki93XIVFDMqYGHiU8TkScJubCznBsd@dsuULMN6BdTd0sKTolBS1xp0oW/g2aKqEatrrjfUBYdu8fdOBLTjRv7t/sbH7GejC9xPJmlyddw/wG)
[Try the 2nd program online!](https://tio.run/##JY1BDoIwFETvYkz6P0ILCxMFCydwxU5jQoNFMAgNIDZBuDoW3EzevFnMU/SiTZtCdU5/mDM@tzyUvSihpY1UpUglMMoedsrDJKbq3eawHdKQjCQimp9Fl9NGVPf6BWh5cv91iW/W47Ia4pxQgxiopqg6WNSJ4Go@eVFK0DiAu1prseNSEo@BNicjN4e1gn8iYqT9SzJikNgxv94Q5ww2k@/QyWc7CmviBucf)
[Try the 3rd program online!](https://tio.run/##JY1BDoIwFETvQkz6P5EWFiZaLJzAFTuNCQ0WwSA0gEiC9epYcDN582YxDznILmtL3XvDfs7F3IlIDbKCjrZKVzJTwCi7bzMRpQnVr66AzZRFxJCYjOIk@4K2sr41T0A3ULuPT7hdD8tqSQhCLWKo27LuYVFHgqt5F2WlYMQJ/NW6izVLSQMGoz0xwh42Gv6JiPHIz6nBMN0m4nJFnHNwvtzjzMH5Bw)
### How?
Each instruction is transpiled to `S.push(`, followed by a specific pattern, followed by `);`.
We have to test the division by zero explicitly because JS doesn't give the slightest damn about such a harmless operation. :-p
```
char. | JS code
-------+--------------------------------------
~ | S.push( **x=Math.random()\*1e5|0** );
+ | S.push( **1/(x+=S.pop(S.pop()))?x:Z** );
- | S.push( **1/(x-=S.pop(S.pop()))?x:Z** );
* | S.push( **1/(x\*=S.pop(S.pop()))?x:Z** );
/ | S.push( **1/(x/=S.pop(S.pop()))?x:Z** );
: | S.push( **x** );
. | S.push( **);print(x** );
( | S.push( **);while(x){(0** );
) | S.push( **)}(0** );
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/) for Linux x86\_64, ~~675 643 621 613 597 432 404~~ 399 bytes
```
printf();*z;*mmap();(*p)();*j(char*a){char*t=a,*n,c;for(p=0;read(0,&c,!p);t=!~c?n=j(t+9),z=mempcpy(t,L"\xf00f883Ƅ",5),*z=n-t-9,n:!c?p=*t++=233,z=t,*z=a-13-t,z+1:stpcpy(t,c-85?c-2?c-4?c-1?c-6?c-17?"PAPTYh%ld T_P^1\xc0QH\x83\xcc\bQA\xff\xd0\\AXX":"P":L"\xfef7995e":"[\xf7\xeb":"[)\xd8":"[\1\xd8":L"\xf0c70f50"))c-=41;return t;}main(){p=mmap(0,1<<20,6,34,0,0);p(strcpy(j(p),"j<X\xf\5"),0,0,0,printf);}
```
[Try it online!](https://tio.run/##LVFdb4IwFP0r2mRLC7euiMiXDfFtD3vAxAeXNVuwwpQM1mCXMI0@7bftb7GCS3N6T89tb3t6JX2XsutUc6h1gUlsnWKrqjJlKLYU6ZUSy33WWBk5D1HzDKwaZFx8NlhxFjd5tsMM7iWMFYk1H19lUvMSazskcOJVXimpvrGGJyTagrEiCNzfHwQeAevEa6ppCHU0lonilrZtPnVdc0z3yYw6LtVwsp3oqP@rSBp4iaRTg5mBYzDvo5@gdJmun/d3H7vR@i19dUQr2epRtIFrmBTb1dLcX4h2x4RYbjYoQimKhkflhR@GXm6UF7PyRZtve07M3mAQnRu7OZA@KzyGCJGUzxzjX3819UjHlyo71JicFR9@kIGzWEwZzMGdAQNGYoWPuuldlFgRQOViY8oJD5E@bcatCyS@dN01opNr9GBP8DCTPw "C (gcc) – Try It Online")
This is a JIT that directly translates Volatile instructions into x86\_64 machine language and executes the code. If your machine doesn't have the `rdrand` instruction, you can replace `L"\xf0c70f50"` with `"Pj*X"` for a "*less uniform PRNG*". To port to something other than Linux, replace the syscalls in the `printf()` and `exit()` blobs and adjust parameters to `mmap()`.
EDIT: This version calls `printf()` instead of implementing a subset from scratch.
EDIT2: Supported integers are now 32 bits instead of 64.
Slightly less golfed...
```
printf();*z;*mmap();(*p)();
// recursive function translates Volatile commands to x86_64 instructions
*j(char*a){
char*t=a,*n,c;
for(p=0;read(0,&c,!p);)
c-=41,
t=c=='('+41?
// cmp eax,0
// je n-t-9
n=j(t+9),
z=mempcpy(t,"\x83\xf8\x00\x0f\x84",5),
*z=n-t-9,
n
:
c==')'+41?
// jmp a-13-t
p=*t++=233,
z=t,
*z=a-13-t,
z+1
:
stpcpy(t,c-'~'+41?
c-'+'+41?
c-'-'+41?
c-'*'+41?
c-'/'+41?
c-':'+41?
// ; This calls printf("%ld ",%rax)
// push rax
// push r8
// push rsp
// pop rcx
// push 0x20646c25
// push rsp
// pop rdi
// push rax
// pop rsi
// xor eax, eax
// push rcx
// or rsp, 8
// push rcx
// call r8
// pop rsp
// pop r8
// pop rax
"\x50\x41\x50\x54\x59\x68\x25\x6c\x64\x20\x54\x5f\x50\x5e\x31\xc0\x51\x48\x83\xcc\x08\x51\x41\xff\xd0\x5c\x41\x58\x58"
:
// push rax
"\x50"
:
// pop rsi
// cdq
// idiv esi
"\x5e\x99\xf7\xfe"
:
// pop rbx
// imul ebx
"\x5b\xf7\xeb"
:
// pop rbx
// sub eax, ebx
"\x5b\x29\xd8"
:
// pop rbx
// add eax, ebx
"\x5b\x01\xd8"
:
// push rax
// rdrand eax
"\x50\x0f\xc7\xf0");
return t;
}
main(){
p=mmap(0,1<<20,6,34,0,0);
p(strcpy(j(p),"\x6a\x3c\x58\x0f\x05"),0,0,0,printf);
}
```
[Answer]
# Java 8, ~~420~~ ~~418~~ ~~402~~ ~~373~~ ~~359~~ ~~357~~ ~~341~~ 339 bytes
```
import java.util.*;s->f(s,new Stack());void f(String s,Stack<Integer>S){for(int i=0,c,t,u;i<s.length();){if((c=s.charAt(i++))<42&&S.peek()!=0)f(s.substring(40/c*i),S);if(c==46)System.out.println(S.peek());if(c>57)S.add(c>99?new Random().nextInt():S.peek());if(c<44|c==45|c==47){t=S.pop();u=S.pop();S.add(c<43?u*t:c<45?u+t:c<46?u-t:u/t);}}}
```
-2 bytes thanks to *@Grimy*.
-18 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##7VdBb9owFL7zK944VDYBwzZoRUJAO@zQwzppmXaZdjDGgGmII@e5HWLZX2dOgLaoVNsq1LUTOTiOn7/vvc8vir7M@BVvzEaXKzVPtUGYuWdmUcWsFgA0m@C97gJqwKmE4QJlQ2ibYEXEPMvgA1fJsgKgEpRmzIWEi@IR4EqrEQgSoVHJBDIauNW84oYLSCCEVdboj0lWT@Q1RMjFJaE0KDHjG0y9DPTOHfVEmn5El2NtiMsEKmzVRR3rNlC9jMUymeCU0IAu1ZgQEWZMTLl5h0R5HqW99puTk4ilUrokr8IWdXlZZodZmYa0W01RU7Qe0cChRRi2T2m0yFDOmbbIUrcJ44RsCda7@p0zGjE@GrlptzsoVHziyUjPCWWJ/I6uZkL9XUyv3f5R0HfK8YwuMXQbdOoKtzezDWmv/XZga@i7SWdgvXJyOrAN9G0TaZDn@codZWqHsRKQIUd3K09v7vqxOcCv34DTdTNQZkiqP/2mf6DLO9DFDljTkxT8PNQ8paijtpcu7xEKD839DDvwjzpxfOf@t3Yev4wvQ9MfaflLljvr1dLi3nqtht@8t1SAPUbKkd6P7gRKs3zX2pX7Nt5YJanFjbnbY1ar50UcvujYwWMJqdETw@c@bHPuwawpHww/HKl@tOigt@RoFuvKAApjXPwiFLaYiZ0cOQiOYko@T42@5kNXpaRb2L4s743RBrQQ1hg5ctk8uWV6RM2NKjMylRxJp0V/ozqv5Ktf)
**Explanation:**
```
import java.util.*; // Required import for 2x Stack and Random
s-> // Method with String parameter and no return-type
f(s,new Stack()) // Call the recursive function, with a new Stack
// Separated recursive method with String and Stack parameters
void f(String s,Stack<Integer>S){
int i=0, // Index integer
c, // Temp integer used for the current character
t,u; // Temp integers used for the peeked/popped top of the stack
for(;i<s.length();){ // Loop `i` in the range [0, String-length):
if((c=s.charAt(i // Set `c` to the current character
++)) // And increase index `i` by 1 right after
<42 // If the character is either '(' or ')',
&&S.peek()!=0) // and the top of the stack is not 0:
f(s.substring( // Take the substring, either removing everything before and
40/c*i), // including the "(", or keeping the string as is for ")"
S); // And do a recursive call with this String
if(c==46) // If the character is '.'
System.out.println( // Print with trailing newline:
S.peek()); // The peeked top of the stack
if(c>57) // If the character is ':' or '~':
S.add(c>99? // If the character is '~':
new Random().nextInt()
// Add a random [0,2147483647) integer to the stack
: // Else (the character is ':')
S.peek()); // Add the peeked top to the stack
if(c<44|c==45|c==47) // If the character is '*', '+', '-', or '/':
t=S.pop();u=S.pop();// Pop and set the top two values to `t` and `u`
S.add(c<43? // If the character is '*':
u*t // Add the product of the two values to the stack
:c<44? // Else-if the character is '+':
u+t // Add the sum of the two values to the stack
:c<46? // Else-if the character is '-':
u-t // Subtract the top two values, and add it to the stack
: // Else (the character is '/'):
u/t;}}} // Divide the top two values, and add it to the stack
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~460~~ ~~454~~ ~~428~~ ~~417~~ ~~413~~ ~~412~~ 406 bytes
```
from random import*
a=raw_input();i=v=0;s=[];o='p(s.pop()%ss.pop())';l=len;p=s.append
def L(u,c,N,r):
u=u[::r];f=0
for i in range(l(u)):
if c==u[i]:f+=1
if f==N:return l(u)-i+l(u)*(r>0)
while i<l(a):c=a[i];exec['v+=1;'+'i=L(a,")",v,1)'*(c=='('and not s[-1]),'i=L(a,"(",v,-1)-1'if')'==c and s[-1]else'v-=1','p(randint(0,4e4))','p(s[-1])','print(int(s[-1]))',o%c,o%c,o%c,o%c,'']['()~:.+-*/'.find(c)];i+=1
```
[Try it online!](https://tio.run/##VZBNbsMgEIXX9SlQpGjAxo5dZQWdniDKBSyrsmxokByM8E/aTa7uQtIuuhhm9PhmBp77ni@jfd027ccr8a3tQzJXN/o5TVr07e3DWLfMlEmDK5ZywrqRI4KjU@FGR9l@@i0YyAEHZaXDqWidU7ZPeqXJiS6842fumUjIgksthG@kxjIhevTEEGPj4k9FB7qwAL0YTToMoGmEzrB6CBrxLLyaF29J5HKTxZRS/16y5HYxgyLmbaAtEx22oVWqL9XVsIYBEjIweKIt37EdX3nFIKVhA1AIHyZ2nMlU51XD@B9GI5ZXLK/AaGCA2JGIPjA1TArWHCvgwYbombEzLflRHYMJUXtOi6WPVzGeUtDGffcvAJoaKLuLIsvTAxTa2J52rJEmvHzb7iIv7uKQFfRxsh8)
[Try it ungolfed!](https://tio.run/##tVLBbtswDD1XX0EUKCQ1ttfs6M77EcMwDIduhDmSQMvrdsmvZ5SMJE4bDNhhB8uiHsX3yCf/O@yd/Xo6DeQOQJ3d8c8cvKOQImODmNxMPULFB@@tsX4OSgtjp0BzH4yzrXechsQZo3O@HfEnjhy8iCl0/Q/e1Y1wHqkLjtqABz92IdaTCS8679Hu1BJ455WGpwlWoZZC7HBYqk/YUb9XE/UZhI7eMLT9vqMM@pnaK38GO0OY9OlSAKczIa91WV6A5hUGN9tdujYlxXxAYMDY2P0bqhFtpNJc48EMa0KolnqmKW@qbCrYptyb0tUHeSUQhpksnAkgZ9rNNXwGddEJ3@FFC/G@NyPCvcF/W@4ln2K3kStqrJaj@s6dRgD@wh5q8SBXrkX1knXIv/h7diDVzuBRP2awHvxWyyj/LCI2L5UEfk1gXViMrfNtozPm/gce9YEn38apsVwe9g2ZXsguRIDjhLBuM49tRvrPLzApS5gnlqPidwUS8vktP10E/G9YyqaWSh/LQhaDYdFnTLOj94YZHT2djmVeHMsvm0KlVf8B)
*-19 bytes thanks to emanresu*
*-26 bytes thanks to implicit loop errors*
*-2 bytes because `-1` wraps to the end of the array*
*-1 byte by moving operators into main array*
*-6 bytes by fitting everything into the exec array*
Transpiles to Python code.
### Explanation
```
from random import*
```
We need this for access to `randint`, and of course importing everything is golfier than just importing `randint`
```
a=raw_input();i=v=0;s=[];o='p(s.pop()%ss.pop())';l=len;p=s.append
```
This defines a few initial variables.
`a` is the source code, read from STDIN
`i` is the instruction pointer, ie the index of the current character in source
`v` is used to track nested loops
`s` is the stack
`o` is a string template used for the four operators, they're all the same logic just with a different operator, and that operator is conveniently also the instruction that triggers it, so we can just interpolate the char into this string
`l` and `p` are just short aliases to save bytes on repeated functions
`;l=len` costs 6 bytes, but saves 2 on each call to `len`, so as long as we use `len` more than 3 times in the program, we save bytes.
`;p=s.append` costs 11 bytes, but saves 7 on each push to the stack, meaning it's worth it even if we only push twice.
```
def L(u,c,N,r):
u=u[::r];f=0
for i in range(l(u)):
if c==u[i]:f+=1
if f==N:return l(u)-i+l(u)*(r>0)
```
This function is used to find the opposite end of a loop while considering nested loops. `u` is the source code, `c` is the char to find, `N` is the nest depth, and `r` is the direction. Returns the index of the first char after the found character.
If for any reason this function can't find a matching end of the loop, it returns `None`, which then throws an error on the next iteration of the main while loop.
```
while i<l(a):c=a[i];exec['v+=1;'+'i=L(a,")",v,1)'*(c=='('and not s[-1]),'i=L(a,"(",v,-1)-1'if')'==c and s[-1]else'v-=1','p(randint(0,4e4))','p(s[-1])','print(int(s[-1]))',o%c,o%c,o%c,o%c,'']['()~:.+-*/'.find(c)];i+=1
```
This is the main parsing loop
```
while i<l(a):
```
Keep looping while the instruction pointer has not reached the end of the code
```
c=a[i]
```
This is setup for each individual character.
`c` is the current character, ie the character at index `i` in the source code
```
exec['v+=1;'+'i=L(a,")",v,1)'*(c=='('and not s[-1]),'i=L(a,"(",v,-1)-1'if')'==c and s[-1]else'v-=1','p(randint(0,4e4))','p(s[-1])','print(int(s[-1]))',o%c,o%c,o%c,o%c,'']['()~:.+-*/'.find(c)]
```
Finally, we get the index of `c` in the string `'()~:.+-*/'`. ie 0 for `(`, 1 for `)`, 2 for `~`, 3 for `:`, 4 for `.`, 5-8 for an operator, and -1 for anything else, and then use that to index into this array with to get the relevant code to execute. As indexing with `-1` in Python wraps to the end of the array, `-1` will return `''` here.
```
'v+=1;'+'i=L(a,")",v,1)'*(c=='('and not s[-1])
```
The transpiled code for `(` increments `v` and, if the top of the stack is falsey, moves the instruction pointer to the end of the loop. We have to check that `c=='('` so that `s[-1]` is not being evaluated on every instruction, causing an error when the program first starts and the stack is empty.
```
'i=L(a,"(",v,-1)-1'if')'==c and s[-1]else'v-=1'
```
The transpiled code for `)` jumps to the beginning of the loop if the top of the stack is truthy, or otherwise decrements `v`. Again we have to check that `')'==c` first to prevent `s[-1]` incorrectly evaluating on an empty stack.
```
p(randint(0,4e4))
```
The transpiled code for `~` pushes a random value between 0 and 40,000 (inclusive). `4e4` was the smallest 3-byte expression I found that was greater than or equal to the required max of 32,768, because `2**15` is still 5 bytes. Unfortunately I don't think it's possible to create a number large enough in fewer bytes.
```
p(s[-1])
```
The transpiled code for `:` simply pushes the top of the stack to the stack.
```
print(int(s[-1]))
```
The transpiled code for `.` prints the top of the stack with a trailing newline. Unfortunately we have to cast to an int costing 5 bytes as otherwise every value that's touched division will be printed with a trailing `.0`
```
o%c
```
The transpiled code for operators is the operator template `o` interpolated with the operator. ie:
```
p(s.pop()Xs.pop())
```
Where `X` is whatever character (one of `+-*/`) we're currently on.
We then `exec` the result of this indexing, running the transpiled code for the current instruction.
```
;i+=1
```
Last but not least, we increment `i` and repeat the loop.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 176 bytes
```
for($k=0;$c=$args[$k++]){switch -r($c){~{$t=,((get-random)%32768)+$t}'[-+*/]'{$a,$b,$t=$t
$t=,("$a$c $b"|iex)+$t}:{$t=,$t[0]+$t}'\.'{$t[0]}'\('{$l=$k-1}'\)'{if($t[0]){$k=$l}}}}
```
[Try it online!](https://tio.run/##7VbbbtswDH3PVxAat1jzJb4kTZvBQIZhe93QDuiDZxSOrSRunCiQ1dtc99dTWXG3PuxhG4KuHUJAgkieQ/JAhqE1v2KinLOisFMu2AanYbWZcmHgInTfYRpiImZlhAvTjGlVXuUynYOt0imt7iqUoWUYMyZtkawyvqSvA394cEhNlHU3ss23vbhbYWLhxFJQlB1NIJhgCjghtzm71tiRroQycmNN/eYoWuOpo6GORYgL21MO7Vb51NApWqkRsaiVbepOZ2x0QJkFY4PcjXqjHZm5I3N2ONOTDPw81DylqL22ly7vLxTuuvYzvIF/dBP7b@5/u879n/FlaPotLX9Y5VGcWPql1RgZBuC5vlpH2@X50B9AoKK@qz3PG7RZD4K@cgnV7FftQ81u2piOoXdKLCCKBz4E0IcBHMAQDuGo5TxQRr0G915KtlxLloHkkOWXecZgcgPfmeCOIlC4hU9cfEzSuf15cs5SCZWuginPmAXIrtcqqOgh4JnOSHHTYjROsPKikCr9Bqcwblg6V@s9TZqH8K/QeOZ85SdS5KuZQR8xoi8nHy5KyZfbaeLxT/IpF1nZHEKwz3m@2s4YuY7jD@IfqONthwZF2nakrV9v7gE "PowerShell Core – Try It Online")
This is a special version that stops after a few iterations to validate the loop's behaviour: [Try it online!](https://tio.run/##7VZta9swEP7uX3GY62rNL/FL0rQphoyyfRpsrIN98ExwbCVx40RBVtp0jvvXM1nJtjD2YRuha0cOJO50z3O6BxlzC3ZHeTmhRWGnjNMNzpLVW8YWEILnajgKq82IcQOnoXuJaYgJH5cRTk0zJlV5l4t0ArZMp6R6qFCElmGMqbB5Ms/YjJwEfvfsnJgo6tPINl@24tMKEwuHloSi0BRBxwRTwKG@zulKYXuqEorIjRX1syNpTSRdQ7pFiFPbkwGRwTTEQstHBhay6yu2nAuwxwK@6SAVcCqWfH4JNexhTKmvrlUb65MKB3W9qTWtb2ggzYK@oT/0Wr0DmXkgcw7Y06M0/DTUPKaoo7bnLu8vFB669hN8gX/0Esdv7n97zuOf8Xlo@i0tf1hl71y31KTVmN4N5Kzpy3WxXZ4P7Q4E8tR3VeR5nV3Wg6AtQ53sz2l2c4vpGGonugW6pIEPAbShA2fQhXO4@InSazW4V0LQ2ULQDASDLL/NMwrDe/hCOXMkgcAa3jD@Okkn9rvhDU0FVKoKpiyjFiBdLeShpIeAA5UR/H6HUThOy2UhZPoFjqDfsFSuVnuaNOPzr9A4cD6ya8Hz@dgge4zo/fXVshRstu0m7v8gf2I8KxsnBPuG5fNtj5HrOH4n/o76sL2hQem76/Rd/XrzFQ "PowerShell Core – Try It Online")
I saved about 50 bytes by faking a stack using arrays concatenation and deconstruction:
* `$a,$t=$t` to pop values
* `$t=,$a+$t` to push values
[Answer]
# [Kotlin](https://kotlinlang.org), 412 bytes
Unfortunately I lost to Java, but I didn't want to `import java.util.Stack` (and I'm not sure it would close the gap anyway.)
```
{p->var i=0
var s=List(0){0}
var c=List(0){0}
while(i<p.length){when(val o=p[i]){'~'->s+=(0..32768).random()
in "+-*/"->{val(a,b)=s.takeLast(2)
s=s.dropLast(2)+when(o){'+'->a+b
'-'->a-b
'*'->a*b
'/'->a/b
else->0}}
':'->s+=s.last()
'.'->println(s.last())
'('->{if(s.last()!=0)c+=i else{var z=0
do{if(p[i]=='(')z++else if(p[i]==')')z--
i++}while(z>0)
i--}}
')'->if(s.last()!=0)i=c.last()else c=c.dropLast(1)}
i++}}
```
## Ungolfed
```
{ p -> // open lambda: p is the code string
var i = 0 // program counter
var s = List(0){0} // data stack
var c = List(0){0} // jump stack
// main loop
while(i<p.length) {
// match on the current character
when(val o = p[i]) {
// add random number to end of stack
'~' -> s += (0..32768).random()
// if a math op...
in "+-*/" -> {
// pick top stack items
val (a, b) = s.takeLast(2)
// pop two items and then push based on op
s = s.dropLast(2) + when(o) {
'+' -> a+b
'-' -> a-b
'*' -> a*b
'/' -> a/b
else -> 0 // else is required here
}
}
// duplicate top stack item
':' -> s += s.last()
// print top stack item
'.' -> println(s.last())
// open loop
'(' -> {
if(s.last()!=0)
// push to jump stack if top of data stack is nonzero
c+=i
else {
// skip ahead
var z=0
do {
// seek to matching brace
if(p[i]=='(') z++ else if(p[i]==')') z--
i++
} while(z>0)
// ensure program counter doesn't go too far
i--
}
}
// close loop
')' -> if(s.last()!=0) i=c.last() else c=c.dropLast(1)
}
// next character
i++
}
}
```
[Try it online!](https://tio.run/##XVHBUsMgEL3zFZhL2CIk6ow6GYk/0JvjyfFAE9oyTUkmwXamTPrrdUlrdeQAb98ub3nLpvWNdaedbuiubbS3jSkoe/O9dSugoqTvznqqTqET5U731KqcxHNQczt4lkPIx4mo/hL7Neow@9LJxriVX0PYr41jsUurug/7CSE9pqIcuGK5lA/3T4/PIHvt6nbLgFhHEy5mWSLKgHeYvl2AGqTXGzPX2OQeyIBx3bfdJeaTfouyHGU1X5BURCAQzCKYIcgiyBbENIMRZT6OJC3OjxhkE3WApBKJDs37xrEfFmmGdLDLK3Wjcqi4sjRqhej/gIOp21gT/SmFV@DAeczTXxKQFIJYzsfzjA5ljn6FiI8BbPKvh1XVJZqEKgyvru9gnITG0/LL0a22jgENhOKKg67a2lBFe6PruXUGc68FTZJz/vLVLBYBGU/HQshjkXHJph2@AQ "Kotlin – Try It Online")
[Answer]
# [Go](https://go.dev), 660 bytes, fixed seed
```
import."math/rand"
func f(C string){for i,S,P:=0,[]uint{},[]int{};i<len(C);i++{if c:=C[i];c=='~'{
S=append(S,uint(Int()))}else if c=='+'{b:=S[len(S)-1];S=S[:len(S)-1];a:=S[len(S)-1];S=S[:len(S)-1];S=append(S,a+b)}else if c=='-'{
b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a-b)}else if c=='*'{b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a*b)}else if c=='/'{b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a/b)}else if c==':'{S=append(S,S[len(S)-1])}else if c=='.'{println(S[len(S)-1])}else if c=='('{P=append(P,i)}else if c==')'{if S[len(S)-1]<1{i=P[len(P)-1]}else{P=P[:len(P)-1]}}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rZK_asMwEMaho55CZJFk-U-zFTmaMnUzeAyGKI6disaycZxJJE_RrYspdOsLtU9TyW6IbWiGUoHQfbrvfjrQvb7tyvajEumz2GWwEFK9H5vce_i6e5FFVdaNPytE8xTUQm1nID-qFOZ4CQ9NLdWO6LysoXRjN2L83l0lR6kafTJBd4Zysc8UXpJQUqplDlPGlyuZhCnn6Iw0iLmoqkxtcezaSvxoNiHklO0PGbR-46NIbxiPV5YUE2-ehLFR7CrFzezgCUE3Y7RnWhizwbgaiJvZIdubsJ1p239HOxN08H_oYIJmSA_SA8jY5iNdmf9v9ib7mwcjHV1QkSvHSYLsOAxqF3MtedTpyOrObQBR33l_Z1Y_nJ9FN4h2WjGBGqTlNoOMw_WZBYwyhzk2YIxSeo3M9nthFb06xjddSP01ADm2XAJ-Hm3b_vwG)
~~confirmed go worse than java~~
Most of this is handling the pops. The title has "fixed seed" because in Go, the random number generator starts with the same fixed seed, every time. You need to seed it with some changing value for it to be truly random (+29 bytes):
## [Go](https://go.dev), 689 bytes, truly random
```
import(."math/rand";."time")
func f(C string){Seed(Now().Unix())
for i,S,P:=0,[]uint{},[]int{};i<len(C);i++{if c:=C[i];c=='~'{
S=append(S,uint(Int()))}else if c=='+'{b:=S[len(S)-1];S=S[:len(S)-1];a:=S[len(S)-1];S=S[:len(S)-1];S=append(S,a+b)}else if c=='-'{
b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a-b)}else if c=='*'{b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a*b)}else if c=='/'{b:=S[len(S)-1]
S=S[:len(S)-1]
a:=S[len(S)-1]
S=S[:len(S)-1]
S=append(S,a/b)}else if c==':'{S=append(S,S[len(S)-1])}else if c=='.'{println(S[len(S)-1])}else if c=='('{P=append(P,i)}else if c==')'{if S[len(S)-1]<1{i=P[len(P)-1]}else{P=P[:len(P)-1]}}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=rZKxasMwEIaho55CeLFk2U67FTmaMnUpBtMpBKLYcioay8ZxaEEkL9IlFLp16eO0T1PJboltaIZSgdD9uv--u-GeX9bl8a3i6QNfC1hwqV53TR5cf168y6Iq6waFTsGb-0nNVeZEodPIQjgY5DuVwhzN4LappVpjnQiRodvyEeHwTsknhI2nrKH0Ez-m7NKfL3ZSNXpvgvaN5HQjFJrhSBKiZQ5TymZzuYhSxtyDq0HCeFUJlaHEt5XoxlyM8V5stgJav_ERV68oS-aWlODgahElRtGT5GezvRacrIbowIwwZINhNeBns312MGJ747H_jvZG6Mn_oScjNHV1L92DDG2hqyuzEs3GZH_zIFfHP6jYl8Mkdu069GqnV1qyuNWx1a3bAOJu8u7PnG5zP4p2N-0qIww1SMtMQMrg8kAnlFCPejaglBByiswNO2EVOTmGP21IwiUAObJcDL6bHo_d-wU)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 215 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 26.875 bytes
```
`~.(/``kεʀ℅`\…‛{:|`:0=ß•/`WḣĿ∑Ė
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJEPSIsIiIsImB+LigvYGBrzrXKgOKEhWBcXOKApuKAm3s6fGA6MD3Dn+KAoi9gV+G4o8S/4oiRxJYiLCIiLCJ+Oi06LyJd)
Translates volatile to its vyxal equivalent (which is almost 1 to 1, given that volatile is a subset of Keg which is a subset of Vyxal).
] |
[Question]
[
# Background
A [Ruth-Aaron pair](http://mathworld.wolfram.com/Ruth-AaronPair.html) is a pair of consecutive positive integers `n` and `n+1` such that the sum of the prime factors (counting repeated prime factors) of each integer are equal. For example, `(714,715)` is a Ruth-Aaron pair, since `714=2*3*7*17`, `715=5*11*13`, and `2+3+7+17=5+11+13=29`. The name Ruth-Aaron pair was chosen by [Carl Pomerance](https://en.wikipedia.org/wiki/Carl_Pomerance) in reference to [Babe Ruth](https://en.wikipedia.org/wiki/Babe_Ruth)'s career home run total of `714`, which stood as the world record from May 25, 1935 until April 8, 1974 when [Hank Aaron](https://en.wikipedia.org/wiki/Hank_Aaron) hit his `715`th home run. You can learn more about the fascinating history of these numbers in this [Numberphile video](https://www.youtube.com/watch?v=aCq04N9it8U).
# Goal
Write a complete program or function which, given a positive integer `n`, outputs the `n`th Aaron number, where the `n`th number is defined to be the larger integer of the `n`th Ruth-Aaron pair. Thus the `n`th Aaron number is `a(n)+1`, where `a(n)` is the `n`th term in the OEIS sequence [A039752](https://oeis.org/A039752).
# Test cases
The first few Aaron numbers are
```
6,9,16,78,126,715,949,1331,1521,1863,2492,3249,4186,4192,5406,5561,5960,6868,8281,8464,10648,12352,14588,16933,17081,18491,20451,24896,26643,26650,28449,28810,33020,37829,37882,41262,42625,43216
```
# Rules
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* [Input and output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) may be in any convenient format.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer (in bytes) wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ ~~10~~ 9 bytes
-1 byte thanks to Emigna
-1 byte thanks to Adnan
```
µN>Ð<‚ÒOË
```
Explanation:
```
µ While the counter variable (which starts at 0) is not equal to the input:
N> Store the current iteration index + 1, and then create an array with
Ð<‚ [current iteration index + 1, current iteration index]
ÒO Get the sum of the prime factors of each element
Ë If all elements in the array are equal,
implicitly increment the counter variable
```
1-indexed.
[Try it online!](https://tio.run/##MzBNTDJM/f//0FY/u8MTbB41zDo8yf9w9///ZgA "05AB1E – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 9 bytes
-2 bytes thanks to a clever golf by @Leo
```
€∫Ẋ¤=oΣpN
```
[Try it online!](https://tio.run/##ARsA5P9odXNr///igqziiKvhuorCpD1vzqNwTv///zY "Husk – Try It Online")
### Explanation
```
Ẋ N -- map function over all consecutive pairs ... of natural numbers [(1,2),(2,3),(3,4),(4,5)...]
¤= -- are the results of the following function equal for both in the pair?
oΣp -- sum of prime factors [0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0]
∫ -- cumulative sum [0,0,0,0,0,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3]
€ -- the index of the first value equal to the input
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~23~~ 20 bytes
This is 1-indexed.
```
WhQ=-QqsPZsPhZ=+Z1;Z
```
**[Test Suite](https://pyth.herokuapp.com/?code=WhQ%3D-QqsPZsPhZ%3D%2BZ1%3BZ&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0)** or **[Try it online!](https://pyth.herokuapp.com/?code=WhQ%3D-QqsPZsPhZ%3D%2BZ1%3BZ&input=6&debug=0)**
---
# Explanation
```
WhQ=-QqsPZsPhZ=+Z1;Z - Full program. Takes input from Standard input.
WhQ - While Q is still higher than 0.
sPZ - Sum of the prime factors of Z.
sPhZ - Sum of the prime factors of Z+1.
q - If the above are equal:
=-Q - Decrement Q by 1 if they are equal, and by 0 if they are not.
=+Z1; - Increment Z on each iteration.
Z - Output Z.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;‘ÆfS€Eµ⁸#Ṫ‘
```
A monadic link taking and returning non-negative numbers
**[Try it online!](https://tio.run/##y0rNyan8/9/6UcOMw21pwY@a1rge2vqocYfyw52rgGL///83AwA "Jelly – Try It Online")**
### How?
```
;‘ÆfS€Eµ⁸#Ṫ‘ - Link: number, n
# - n-find (counting up, say with i, from implicit 1)
⁸ - ...number of matches to find: chain's left argument, n
µ - ...action: the monadic chain with argument i:
‘ - increment = i+1
; - concatenate = [i,i+1]
Æf - prime factors (with duplicates, vectorises)
S€ - sum €ach
E - all (two of them) equal?
Ṫ - tail, the last matching (hence nth) i
‘ - increment (need to return i+1)
```
[Answer]
# PHP, ~~93 92~~ 91+1 bytes
```
while(2+$argn-=$a==$b)for($b=$a,$a=!$x=$n+=$k=1;$k++<$x;)for(;$x%$k<1;$x/=$k)$a+=$k;echo$n;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/3748c7b7f83fe2109c1f8115f01d8b35fa70e2d8).
-2 bytes with 3-indexed (fist Aaron number for argument `3`): remove `2+`.
**breakdown**
```
while(2+$argn # loop until argument reaches -2 (0 and 1 are false positives)
-=$a==$b) # 0. if factors sum equals previous, decrement argument
for($b=$a, # 1. remember factors sum
$a=! # 3. reset factors sum $a
$x=$n+= # 2. pre-increment $n and copy to $x
$k=1;$k++<$x;) # 4. loop $k from 2 to $x
for(;$x%$k<1; # while $k divides $x
$x/=$k) # 2. and divide $x by $k
$a+=$k; # 1. add $k to factors sum
echo$n; # print Aaron number $n
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17 bytes
```
`@:"@Yfs]vd~sG<}@
```
1-based. Very slow.
[**Try it online!**](https://tio.run/##y00syfn/P8HBSskhMq04tiylrtjdptbh/39TAA "MATL – Try It Online")
### Explanation
```
` % Do...while
@ % Push iteration index k, starting at 1
: % Range [1 2 ... k]
" % For each j in [1 2 ... k]
@ % Push j
Yf % Row vector of prime factors
s % Sum
] % End
v % Concatenate whole stack into a column vector
d % Consecutive differences. A zero indicates a Ruth-Aaron pair
~s % Number of zeros
G< % Is it less than the input? If so: next k. Else: exit loop
} % Finally (execute right before when the loop is exited)
@ % Push current k
% Implicit end. Implicit display
```
[Answer]
# Mathematica, 97 bytes
```
(t=r=1;While[t<=#,If[SameQ@@(Plus@@((#&@@# #[[2]])&/@FactorInteger@#)&/@{#,#+1}&@r),t++];r++];r)&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvtfo8S2yNbQOjwjMyc1usTGVlnHMy06ODE3NdDBQSMgp7QYSGkoqzk4KCsoR0cbxcZqquk7uCUml@QXeeaVpKanFjkog4SqlXWUtQ1r1RyKNHVKtLVjrYvAhKba/4CizLwSBYe0aNPY/wA "Mathics – Try It Online")
[Answer]
# Pyth, 12 11 bytes
```
e.fqsPtZsPZ
```
Indexing from 1 removes a byte, and puts Pyth ahead of Jelly
---
# Explanation
```
e.fqsPtZsPZ - Full program. Takes input from Standard input.
e.f - Last element of the list of the first $input numbers for which
q - Are equal
s s - The sum of
PtZ PZ - Prime factors of $number-1 and $number
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
ÆfS=’ÆfS$$µ³‘¤#ṖṪ
```
[Try it online!](https://tio.run/##y0rNyan8//9wW1qw7aOGmSBaReXQ1kObHzXMOLRE@eHOaQ93rvr//78hAA "Jelly – Try It Online")
# Explanation
```
ÆfS=’ÆfS$$µ³‘¤#ṖṪ Main link, argument is z
# Find the first elements that satisfy condition y: <y><z>#
³‘¤ z + 1
µ Monadic link, where the condition is:
S The sum of
Æf the array of primes that multiply to the number
= equals
S The sum of
Æf the prime factors of
’ the number before it
$$ Last two links as a monad, twice
Ṗ k -> k[:-1]
Ṫ Last element (combined with `pop`, gets the second last element)
```
1-indexed
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~89~~ 86 bytes
```
->n{(1..1/s=0.0).find{|x|r,c=2,0
0while x%r<1?(x/=r;c+=r):x>=r+=1
(c==s)?0>n-=1:!s=c}}
```
[Try it online!](https://tio.run/##FczdCoIwFADg@/MUdhFsqHOzH8E680HEi1qOhBqyEZ3QPfvC7wE@/7n/ksVUarcwJYSqAkohubCTeywrrb4wWBcS5Pc5vcaM9v6qOkYV@ovJ0fOWNPocFTCDGHgntStRtbuAJsa0lQ0X79u8XXPWU2F7GoaYFNRwgCOc4AzNHw "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 19 bytes
```
1+_°k x ¥Zk x «U´}a
```
Uses 1-indexing.
[Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=MStfsGsgeCClWmsgeCCrVbR9YQ==&input=MTA=)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~119 104 102~~ 101 bytes
```
f=lambda n,k=2:n/k and(f(n,k+1),k+f(n/k))[n%k<1]
i=input();g=0
while-~i:i-=f(g)==f(g+1);g+=1
print(g)
```
[Try it online!](https://tio.run/##JU7NDoIwGLt/T7GL2RYkuPmXgN9beDMeJoyxDD8IgagXX32OeGnapk07fuZuIB3robHIOY8t9ub5aAyjbUBdUhGYoUa0IulMyQSJFkHKG23CRd3Bo6dxmYWsHO7g1fne5l9f@hxb4SSumHqVy1DBOHmakxvT0j/KrtNiS2DMvm3N1hdRgYY9HOAIJzj/AA "Python 2 – Try It Online")
**-17 bytes** thanks to @ovs!
**-1 byte** thanks to @notjagan
Credit goes to [Dennis](https://codegolf.stackexchange.com/a/104591/59487) for the prime factorization algorithm. 1-indexed.
---
>
> **Note:** This is extremely slow and inefficient. Inputs higher than 7 will crash unless you set `import sys` and do `sys.setrecursionlimit(100000)`, but it works in theory.
>
>
>
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Èk x ¶Yk x}iU1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yGsgeCC2WWsgeH1pVTE&input=Ng)
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 13 bytes
```
⟨:)ḍΣ¤ḍΣ=⟩#e)
```
[Try it online!](https://tio.run/##S0/MTPz//9H8FVaaD3f0nlt8aAmYsn00f6Vyqub//0YA "Gaia – Try It Online")
] |
[Question]
[
You love lunch. However, you are on a diet and want to make sure you don't accidentally eat lunch twice in one day. So you need to make a program to help you make sure.
However, one complication is that you eat lunch on a very weird schedule. The time you eat lunch at is **MONTH:DAY PM** (you can use UTC or localized time zone). That's right, if the day is **July 14**, you eat lunch at **7:14 PM**.
For your program, you need to use the current date and time (don't take input), and output a consistent truthy value if you have already eaten lunch for the day (or it is lunch time now), or a consistent falsy value if you haven't.
**Examples:** (Time you run program => output)
* May 4th 11:35 AM => false (you will eat lunch at 5:04 PM)
* June 3rd 5:45 PM => false (you will eat lunch at 6:03 PM)
* July 28th 8:30 PM => true (you ate lunch at 7:28 PM)
* December 15th 3:25 PM => true (you ate lunch at 12:15 PM)
* February 29th 2:29 PM => true (it is exactly lunch time)
* October 12th 12:00 AM => false (day just started)
**Reference:**
[How a 12 hour clock works](https://en.wikipedia.org/wiki/12-hour_clock)
[Answer]
# [Swift 3](https://swift.org), 310 bytes
```
import Foundation;var n=String(describing:Date());var k=n.startIndex;print(Int(n[n.index(k,offsetBy:5)...n.index(k,offsetBy:6)])!*60+Int(n[n.index(k,offsetBy:8)...n.index(k,offsetBy:9)])!+720<=Int(n[n.index(k,offsetBy:11)...n.index(k,offsetBy:12)])!*60+Int(n[n.index(k,offsetBy:14)...n.index(k,offsetBy:15)])!)
```
[Check it out!](http://swift.sandbox.bluemix.net/#/repl/5969d5d9233cfd6caeb2c54c)
This prints `true` and `false`, for truthy and falsy respectively.
>
> **NOTE**: This only works until the year 9999, at 11:59:59 PM, because it uses Strings to compare the dates.
>
>
>
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 18 bytes
```
žežb‚žf12+ža‚т*+`‹
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6L7Uo/uSHjXMOrovzdBI@@i@RCD7YpOWdsKjhp3//wMA "05AB1E – Try It Online")
### Explanation
```
žežb‚žf12+ža‚т*+`‹
že # Push current day
žb # Push current minute
‚ # Wrap to array
žf12+ # Push current month and add 12 to it
ža # Push current hour
‚ # Wrap these two to array as well
т* # Multiply each element in the second array by 100
+ # Add both arrays together
` # Flatten the resulting array to stack
‹ # Is the first item smaller than the second one?
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 61 bytes
```
diff(str2num([(d=datestr(now,'mmddHHMM'))(1:4);d(5:8)]))>1200
```
[Try it online!](https://tio.run/##y08uSSxL/f8/JTMtTaO4pMgorzRXI1ojxTYlsSQVyNfIyy/XUc/NTUnx8PD1VdfU1DC0MtG0TtEwtbLQjNXUtDM0MjD4/x8A "Octave – Try It Online")
### Explanation:
First the functions:
* `now()` returns the time on a decimal format. The parentheses are optional.
* `datestr` converts a decimal number to a string on the format given in its second argument
* `str2num` converts a string to a number
* `diff` takes the difference between two numbers
### Breakdown:
We take this from the middle:
```
diff(str2num([(d=datestr(now,'mmddHHMM'))(1:4);d(5:8)]))>1200
```
**`datestr(now,'mmddHHMM')`**: First we take the current time `now` as input to `datestr` and specifies the format `mmddHHMM`. The letters mean: `mm = month`, `dd = day`, `HH = hour`, `MM = minutes` and `AM` specifies that the hours should be on a 12-hour format. No separators are included, to keep it as short as possible. It outputs [`d = 07142117`](https://tio.run/##y08uSSxL/f8/xTYlsSS1uKRIIy@/XEc9NzclxcPD19fRV13z/38A) on the time of writing this explanation. I'll refer to that part as `x` from now.
**`[(d=x)(1:4);d(5:8)]`**: Stores the string above, as `d`, then creates an array with two elements, the first four characters, then the 5-9 characters. This [gives](https://tio.run/##y08uSSxL/f8/WiPFNiWxJLW4pEgjL79cRz03NyXFw8PX19FXXVNTw9DKRNM6RcPUykIz9v9/AA):
```
ans =
0714
2122
```
Where the numbers are stored as strings, not numbers. We'll call the result above for `y` below.
**`str2num(y)`** converts the array of characters to numbers, where each row turns into one number. This gives `[714; 2122]`. We'll call the result for `z`.
**`diff(z)>1200`** takes the difference between the two numbers and checks if the current time is 1200 higher than the current date. This accounts for AM/PM. This gives us the desired result.
[Answer]
# Pyth, ~~22~~ ~~21~~ 20 bytes
```
<0+g.d7.d5-.d6+12.d4
```
*-1 byte thanks to @Mr.Xcoder*
[Try this!](https://pyth.herokuapp.com/?code=%3C0%2Bg.d7.d5-.d6%2B12.d4&debug=0)
## old approach, ~~22~~ 20 bytes
```
<+`+12.d4.d5+`.d6.d7
```
[Try it!](https://pyth.herokuapp.com/?code=%3C%2B%60%2B12.d4.d5%2B%60.d6.d7&debug=0)
## explanation
```
<0+g.d7.d5-.d6+12.d4
+12.d4 # Add 12 to the current month to make it PM
-.d6 # subtract that from the current hour: negative it is too early,
# positive when it is past this hour, zero when its the same hour
g.d7.d5 # Is the minute greater or equal than the day? True=1; False=0
+ # Add this to the hour result,
# so that 0 can turn positive if minutes are true
<0 # Is the result larger than 0 ?
```
[Answer]
# C#, 174 bytes
```
using System;public class Program{public static void Main(){Console.WriteLine(DateTime.Now>DateTime.Today.AddHours(DateTime.Today.Month+12).AddMinutes(DateTime.Today.Day));}}
```
[Try it online!](https://tio.run/##ZYqxCsIwEEB/JWODWNC1IIgODlYEC85nctSDNie5i1JKvz0qiINOj/d4TuaOI@achEJrToMo9tUtXTpyxnUgYo6R2wj9@ImioC/cmbypgUJhxw0H4Q7LcyTFPQUstqDYUI/lgR@rrzTsYSjX3u84RSl@es1Br7PF0r6PmkJS/Hu2MFhbTVPOTw "C# (.NET Core) – Try It Online")
[Answer]
# **PHP and other languages with these common functions: about 28 to 29 bytes:**
```
echo eval(date('Gi-1199>md'));
```
or alternatively
```
<?=eval(date('Gi-1199>md'))?>
```
both of which will print.
possibly with `?1:0` depending on representation. Possibly bytes cut if a language is used that has implicit echo, or no final ';'.
Why would one get the values into variables and all the rest, when it's not needed :)
`date()` leaves anything as literals that isn't defined, so for example, `7 May 2017 17:22:43` passes the expression `1722 - 1200 >= 507` to eval(). Byte saved by changing it to the equivalent `1722 - 1199 > 507`.
Who says eval is dead? ;-)
[Answer]
## Java, 81 bytes
```
n->new Date().after(new Date(){{setHours(getMonth()+13);setMinutes(getDate());}})
```
[Try it online!](https://ideone.com/x9C7Ty)
Ungolfed:
```
n -> new Date().after(new Date() { //new Date() returns current date
{ //instance initialization
setHours(getMonth() + 13); //month + 12 hours for PM + 1 because months are 0 indexed
setMinutes(getDate()());
}
})
```
[Answer]
# Haskell, 135 129 bytes
```
import Data.Time
x(ZonedTime(LocalTime d(TimeOfDay h m _))_)|(_,x,y)<-toGregorian d=return(mod x 12<h-12&&y<m)
y=getZonedTime>>=x
```
this unpacking is quite annoying, maybe string handling is better suited
//edit: pattern guards safe 5 bytes
[Answer]
# Mathematica, ~~65~~ ~~64~~ 62 bytes
### 3 Programs
```
p=Date[][[#]]&;{60,1}.#&/@(p[4;;5]>=p[2;;3]+{12+p@2~Mod~12,0})
```
```
{60,1}.#&/@(#[[4;;5]]>=#[[2;;3]]+{12+#[[2]]~Mod~12,0})&@Date[]
```
```
{60,1}.#&/@(#[4;;5]>=#[2;;3]+{12+#@2~Mod~12,0})&[Date[][[#]]&]
```
These are each one byte less if `≥` counts as a single byte in Mathematica.
### Explanations
1. `Date[]` returns a list in the form `{y,m,d,h,m,s}`. So
`Date[][[4;;5]]` are the hours and minutes of the current time.
2. `p=Date[][[#]]&;` makes `p` a function that takes in the indices we
want and gives us those parts of the date.
3. `{60,1}.#&` is an anonymous function that takes the dot product of `{60,1}` and the input to get a way to compare times. It's one byte shorter than `TimeObject`.
4. `p@2` is equivalent to `p[2]`, the number of the month.
5. `+{12+p@2~Mod~12,0}` adds `{12,0}` to the month and date when we're not in December, and adds `{0,0}` otherwise. (Thanks, michi7x7!)
6. `>=` is the comparison operator, but we can't compare {hours, minutes} to {adjusted month, date} entrywise...
7. `/@` maps `{60,1}.#&` to both sides of the inequality in parentheses, so we can compare times correctly.
8. For the programs that start with `{60,1}.#&`, they use `#` to represent the input to a big anonymous function, and `&` to signify the end.
9. `@Date[]` Applies the big function on its line (which extracts parts of a list) to the date list itself.
10. `[Date[][[#]]&]` Applies the big function on its line to another anonymous function, one which extracts parts of the date list.
### Bonus
As an aside, if we ate lunch between 1AM and 12:59PM, then we could save 25 bytes with just `{60,1}.#&[Date[][[#]]]&/@(4;;5>=2;;3)`.
You can test all of these out by pasting the code into the [Wolfram Cloud sandbox](https://sandbox.open.wolframcloud.com/) and clicking Gear->Evaluate Cell or hitting Shift+Enter or Numpad Enter.
[Answer]
## JavaScript (ES6), 75 bytes
```
f=
(d=new Date)=>(d.getHours()-d.getMonth()-13||d.getMinutes()-d.getDate())>=0
```
```
<input type=button value=Lunch? onclick=o.textContent=f()><tt id=o>
```
Those long function names...
[Answer]
# [Python 3](https://docs.python.org/3/), 104 bytes
```
from datetime import*
n=datetime.now();print(n>=n.replace(hour=[0,n.month+12][n.month<12],minute=n.day))
```
[Try it online!](https://tio.run/##NctBCsIwEEbhvafoMqklaF1qvEjpItiRBJx/wjBFevrYRd19PHh1syy4tfZW4W5JRlaYusJV1PoT4j8FyNf5e9UCc3hGBKX6SS9yWVaN02VAYIHl83Wcp8OP3QMXrEb7sKTN@9Z@ "Python 3 – Try It Online")
[All datetime tests.](https://tio.run/##jdHBasMgGAfwe57ioztUNylqYlvC0jcY7LBb2UEaQxyJBmPo8vSZa5OmGy2bKHwi/vyrTe9La@JhKJytIZdeeV0r0HVjnX@MclVAgUw2LayMPSKM0whCa5w2HpldZlZONZU8KFTazmV7SsyqtsaXT4y/78f6OdSk1qbzKmzIZY/xcBYWbzZMU1gQUCbPlkscFQhH0fXBiFO2ISAIJAROpzBGYORigTE8QLaDQlatAtTbDo66qkBJD1VnDiWEQqQ0gdcXfAteE4gneHOBk//B65TG9@DQ@XaUOZ0j00n2rhvhsHE2Nynf3jMZD0NMccUF5eIPlPGUiXsqv0rKkhnd/kS1B92C@pQHX/Uj/a3cTkrPaU/ofHtKf71r@H/46FoPrZfOqxwPXw) I replaced Feb 29th with Feb 28th because the invalid date wasn't working.
[Answer]
# [R](https://www.r-project.org/), 92 bytes
```
library(lubridate)
d=Sys.Date()
cat(Sys.time()>ymd_hm(paste0(d,'-',month(d)+12,'-',day(d))))
```
[Try it online!](https://tio.run/##HcexDYAgEEDRnkU4Ihq118oNHMAcHgkkoAbPgukR/dV/qZTgTcKUITwmeUK2StC05rtb6oMSOzJ8ZB8r5xxpcxEuvNn2QFq2UsfzYAekmmH8TZiraqW8 "R – Try It Online")
```
month(d)+12,'-',day(d) # get month and day and paste into a string, adding 12 hours for pm
paste0(d,'-', ) # add current date to beginning
ymd_hm( ) # turn whole thing into a date-time object
cat(Sys.time()> ) # compare with current date-time and print
```
[Answer]
# q, 31 bytes
```
x>12:+"T"$(-3!x:.z.P)5 6 13 8 9
```
Example:
```
q).z.P
2017.07.16D19:35:26.654099000
q)x>12:+"T"$(-3!x:.z.P)5 6 13 8 9
1b
```
Interpreter is available [here](http://kx.com/download)
Old version
```
{x:.z.p;x>"T"$":"sv"0"^2$/:string 12 0+`mm`dd$\:x}`
```
[Answer]
# JavaScript, 75 bytes
```
t=new Date,t.setHours(13+t.getMonth()),t.setMinutes(t.getDate()),new Date>t
```
Which is equivalent to the following code:
```
function didEat()
const d = new Date()
d.setHours(12 /* PM */ + d.getMonth() + 1)
d.setMinutes(d.getDate())
return new Date > d
}
didEat()
```
[Answer]
# Python 2.7, 130 bytes
```
from datetime import*
a=str(datetime.now()).split()
print int(''.join(a[0].split('-')[1:]))+1200<int(''.join(a[1].split(':')[:2]))
```
[Try it online](https://tio.run/##VcpBCsMgEIXhq7hzJiWiLk1zkpCF0JROqI6YgdDTWxdtoYu3@d9XXvLg7Fu7V07qFmUTSpuiVLjKMMX5kArfbDKfgGiO8iQBnEqlLKoPtDY7U4a42PVz61Hj4sKKeHHe2us/cz8WOgu@s9be)
Note: There may be a problem with the sign. Please excuse that because I follow IST and it's quite confusing because it's 2:28am here now. Do correct the sign if you feel it is wrong.
[Answer]
## Perl, 45 chars
```
sub c{@a=gmtime;$a[2]-12>$a[4]&&$a[1]>=$a[3]}
```
If I have to provide a method, it will be 45 for `sub c{...}`.
If I have to print
`say ()||0` even makes it 47. I will add that in if it's a requirement.
[Answer]
# Excel, ~~52~~ ~~50~~ 49 bytes
```
=TIME(MONTH(NOW())+12,DAY(NOW()),0)<=MOD(NOW(),1)
```
Input is this formula in any cell.
Output is either `TRUE` or `FALSE`.
Excel's built-in date handling helps a lot.
The `TIME` function returns the day's lunch time as a time value which, if converted to a date, would use `Jan 0, 1900`. We compare it against `NOW - TODAY` so we get the current time with a date value of `0` or `Jan 0, 1900`.
Saved 2 bytes thanks to Wernisch
Saved 1 byte thanks to Adam
[Answer]
# JavaScript, 62 chars
```
f=
_=>[,m,d,H,M]=(new Date).toISOString().split(/\D/),+m+12+d<=H+M
```
Test code below:
```
console.log(( // May 4, 5:03 PM, false (1 minute before lunch)
[,m,d,H,M]=(new Date("2017-05-04T17:03Z")).toISOString().split(/\D/),+m+12+d<=H+M
));
console.log(( // May 4, 5:04 PM, true (exact time)
[,m,d,H,M]=(new Date("2017-05-04T17:04Z")).toISOString().split(/\D/),+m+12+d<=H+M
));
console.log(( // May 4, 5:05 PM, true (1 minute after)
[,m,d,H,M]=(new Date("2017-05-04T17:05Z")).toISOString().split(/\D/),+m+12+d<=H+M
));
```
[Answer]
# Excel VBA, 55 Bytes
Anonymous VBE immediate window function that takes no input and outputs a Boolean value representing whether I've had lunch to the VBE immediate window
```
n=Now:?TimeValue(n)>TimeValue(Month(n)&":"&Day(n)&"PM")
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64+7 = 71 bytes
Requires the `-rtime` flag because for some reason `Time::parse` is like, the only function requires it out of the entire `Time` module.
```
p Time.parse("#{t=Time.now}"[/.+-(..)-(..) /]+[$1,$2]*?:+'pm')<t
```
[Try it online!](https://tio.run/##KypNqvxfoBCSmZuql5dfDmMWJBYVp2ooKVeX2MKkapWi9fW0dTX09DTBhIJ@rHa0iqGOilGslr2VtnpBrrqmTcn////yC0oy8/OK/@sWlQC1AgA "Ruby – Try It Online") (it also prints out the current time)
[Answer]
## Julia 0.6.0 99 bytes
`a=split(string(Dates.today()),"-");(Dates.hour(now())<parse(a[2]))&&Dates.minute(now())<parse(a[3])`
Julia has built in function to use the clock/calendar of the computer.
My computer is running on ubuntu 16.04 and already with 12 hour clock, so I can't say if what I did works with other machine using different clock, but seems to works on my machine.
[Answer]
# JavaScript ES6, 70 Bytes
```
_=>(h=x=>new Date().toJSON().substr(x,5).replace(/\D/,0))(5)+12e3<h(11)
```
Maybe not that right on some milliseconds...
[Answer]
# Matlab, 241 bytes
```
dt=datestr(now,'mm/dd');
dt(2)
dt(4:5)
CrctLchTm=[' ' dt(2) ':' dt(4:5) ' PM']
CrntTm=datestr(now,'HH:MM PM')
CrntTm(7)=='A'
if ans==1
Lch='false'
else
CrctLchTm=str2num([CrctLchTm(2) CrctLchTm(4:5)])
CrntTm=str2num([CrntTm(2) CrntTm(4:5)])
CrntTm<CrctLchTm
if ans==1
Lch='false'
else
Lch='true'
end
end
```
Explanation: First, I obtain the date as a string. Then, I isolate the month and day. Since the problem states that it is always interpreted as PM, then I automatically write false if the time is in AM. If the current time is in PM, then I continue on and just compare the numbers of the time.
Note: I've formatted it slightly differently here for readability.
] |
[Question]
[
The [Wilson score interval](https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval) is a confidence interval of the probability of success, based on the proportion of successes in a set of Bernoulli trials (a Bernoulli trial is a trial in which exactly two outcomes are possible: *success* or *failure*). The interval is given by the following formula:
[](https://i.stack.imgur.com/NU4Mq.png)
The two values given by the formula are the upper and lower bounds of the interval. *nS* and *nF* are the number of successes and failures, respectively, and *n* is the total number of trials (equivalent to *nS* + *nF*). *z* is a parameter dependent on the level of confidence desired. For the purposes of this challenge, *z* = 1.96 will be used (corresponding to a 95% confidence interval)*1*.
Given non-negative integers *nS* and *nF*, output the bounds of the Wilson score interval.
## Rules
* The outputs must be as accurate as possible to the true values, within the limits of your language's floating-point implementation, ignoring any potential issues due to floating-point arithmetic inaccuracies. If your language is capable of arbitrary-precision arithmetic, it must be at least as precise as IEEE 754 double-precision arithmetic.
* The inputs will be within the representable range for your language's native integer type, and the outputs will be within the representable range for your language's native floating-point type.
* *n* will always be positive.
* The order of the outputs does not matter.
## Test Cases
Format: `n_s, n_f => lower, upper`
```
0, 1 => 0.0, 0.7934567085261071
1, 0 => 0.20654329147389294, 1.0
1, 1 => 0.09452865480086611, 0.905471345199134
1, 10 => 0.016231752262825982, 0.3773646254862038
10, 1 => 0.6226353745137962, 0.9837682477371741
10, 90 => 0.05522854161313612, 0.1743673043676654
90, 10 => 0.8256326956323345, 0.9447714583868639
25, 75 => 0.17545094003724265, 0.3430464637007583
75, 25 => 0.6569535362992417, 0.8245490599627573
50, 50 => 0.40382982859014716, 0.5961701714098528
0, 100 => 0.0, 0.03699480747600191
100, 0 => 0.9630051925239981, 1.0
```
---
1. The `z` value is the `1-α/2`th quantile of the standard normal distribution, where `α` is the significance level. If you want a 95% confidence interval, your significance level is `α=0.05`, and the `z` value is `1.96`.
[Answer]
# Mathematica, 48 bytes (UTF-8 encoding)
```
({-1,1}√((s=1.4^4)##/+##+s^2/4)+#+s/2)/(s+##)&
```
Unnamed function taking two arguments in the order `n_s, n_f` and returning an ordered pair of real numbers. The three-byte symbol `√`, representing the square-root function, is U-221A.
Uses the fact that preceding `##` by a number results in the product of the two arguments, while `+##` results in their sum. Also uses the fact that products and sums automatically thread over lists, so that `{-1,1}√(...)` implements the ± in the formula. Defining the constant `s = z^2` instead of `z` itself also saved a couple of bytes. (Mostly I'm just proud of saving a byte by noticing that `1.4^4` is exactly `1.96^2`!)
[Answer]
# [Perl 6](http://perl6.org/), 66 bytes
```
->\s,\f,\z=1.96 {(s+(-z|z)*sqrt(s*f/(s+f)+z*z/4)+z*z/2)/(s+f+z*z)}
```
This function actually returns an or-junction of the lower and upper bounds; for example, if called with the arguments 100 and 0, it returns:
```
any(0.963005192523998, 1)
```
It's a non-traditional output format to say the least, but no particular format was specified, and both of the required values are present.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 34 bytes
```
"1.96"Dn©4/¹P¹O/+t*D()®;+¹0è+®¹O+/
```
Input is of the form `[n_s, n_f]`
Output is of the form `[upper, lower]`
[Try it online!](https://tio.run/nexus/05ab1e#@69kqGdppuSSd2ilif6hnQGHdvrra5douWhoHlpnrX1op8HhFdqH1gFFtfX//482N9VRMDKNBQA "05AB1E – TIO Nexus")
**Explanation**
```
"1.96" # push 1.96
Dn© # duplicate, square, store a copy in register
4/ # divide by 4
¹P¹O/ # product of input divided by sum of input
+ # add this to (z^2)/4
t* # sqrt and multiply with z
D() # wrap in list together with a negated copy
®;+ # add (z^2)/2
¹0è+ # add n_s
®¹O+/ # divide by z^2+n
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 105 bytes
#StillBetterThanJava
```
/:2,:2,i:3s:3s:i:3s*3s+::6s4s,+'qA{*:Z4s3TRr4s{++}\
\p2:,C1Ä'<> yyyyyyyyyyyyyyyyyyy'Ä1C,2p:2,//@S ',+ /
```
[Try it online!](https://tio.run/##KyrNy0z@/1/fykgHiDKtjItBCERrGRdrW1mZFZsU62irFzpWa1lFmRQbhwQVmRRXa2vXxnDFFBhZ6TgbHm5Rt7FTqMQE6odbDJ11jAqA5urrOwQrqOtoK@j//2@oYAgA "Runic Enchantments – Try It Online")
Input is of the form `n_s n_f`
Output is of the form `lower upper` and has a trailing space
AH GOD this one's a mess. Here's the unwrapped version:
```
>'Ä1C,:2p:2,:2,i:3s:3s:i:3s*3s+::6s4s,+'qA{*:Z4s3TRr4s{++}+,' S@
> yyyyyyyyyyyyyyyyyyy'Ä1C,2p:2,//
```
All those `y`s are to slow down the second IP so that it arrives at the `T`ransfer point at the right time (i.e. second). This shoves the top 3 items of the one pointer over to the other (the setup to this action is depicted below). `'Ä1C,` generates `z` by dividing character 196 by 100 (dup, square, dup, div 2, dup, div 2...). The everything-else is just a bunch of math and stack manipulation to shove future values down the stack until they're needed. For the most part, they end up in the right order and its only until `r4s{++}` that we have to reverse the stack and rotate the whole thing to get the values we want next to each other next to each other.
There's probably room for improvement, but its complex enough that I can't see it. Heck, had inadvertently read "z" instead of "n" in the original formula at one point and fixing *that* was rough.
I had to pull out notecards and simulate the stacks in order to make sure it was correct:
[](https://i.stack.imgur.com/X0bjn.png)
Every single one has a value on both ends due to how many variables there were (eg. I'd have one with S and one with F, I'd pop them both, flip one around and add the S+F that was on the other end to the top of the stack). You can see one of the `sqrt(...)` cards has an `S` on the lower edge.
[Answer]
# [R](https://www.r-project.org/), ~~58~~ ~~53~~ ~~51~~ ~~49~~ 41 bytes
-15 bytes thanks to J.Doe. -2 bytes thanks to Giuseppe.
```
function(x,y)prop.test(t(c(x,y)),cor=F)$c
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~38~~ 37 bytes
```
pGs/1.96XJU4/XI+X^J*t_hIE+G1)+GsJU+/S
```
Input is an array of two numbers, in any of these formats: `[25 75]`, `[25, 75]`, `[25; 75]`.
[Try it online!](https://tio.run/nexus/matl#@1/gXqxvqGdpFuEVaqIf4akdEeelVRKf4emq7W6oqe1e7BWqrR/8/3@0kamCuWksAA "MATL – TIO Nexus") or [verify all test cases](https://tio.run/nexus/matl#LUy7CoAgFN37iruWkPdKt3CvIR1LEKLH2BjY/1tmy3lyzuFtvGyQVOvWG9dIPwq/merez3EQlkphg3FCTrGf44JAa7EQ4IdZ02f@BkEnqzHHiqHjlzsGlZgROOWpzjN8vx4).
[Answer]
# [Haskell](https://www.haskell.org/), ~~70 69 68~~ 67 bytes
```
s#f|y<-1.96^2=[(s+y/2+k*sqrt(s*f*y/(s+f)+y^2/4))/(s+f+y)|k<-[-1,1]]
```
[Try it online!](https://tio.run/nexus/haskell#@1@snFZTaaNrqGdpFmdkG61RrF2pb6SdrVVcWFSiUayVplWpDxRL09SujDPSN9HUBPO0KzVrsm10o3UNdQxjY//nJmbmKdgqFJSWBJcU@eQpqCgUZ@SXK2gYGigoK1gaaP4HAA "Haskell – TIO Nexus")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 50 bytes
```
{(+/⍺⍵z)÷⍨(⍺+z÷2)(-,+).5*⍨z×(⍺×⍵÷⍺+⍵)+4÷⍨z←3.8416}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbmXEBOQACQY2z4v1pDW/9R765HvVurNA9vf9S7QgPI0646vN1IU0NXR1tTz1QLKFh1eDpI/PB0oDqQql3aQIamtglYRxXIJD0LE0Oz2v9pQPaj3j6gBZ7@j7qaD603ftQ2EcgLDnIGkiEensH/QQK9qzQMFAwh0ACELA0UjEwVzE0VTA0UQAIGmmmHVmgYKhhAVYAUAGmgAiOwGqAKBQNNAA "APL (Dyalog Unicode) – Try It Online")
Infix Dfn, taking \$⍺←n\_s\$ and \$⍵←n\_f\$.
Thanks to H.PWiz and dzaima for helping out.
### How:
```
z←3.8416 ⍝ Set z=1.96²
4÷⍨ ⍝ Divide it by 4
+ ⍝ plus
(⍺×⍵÷⍺+⍵) ⍝ (nf×ns)÷n
z× ⍝ ×z²
.5*⍨ ⍝ to the power .5 (square root)
(-,+) ⍝ ±
(⍺+z÷2) ⍝ ns+(z²/2)
(+/⍺⍵z)÷⍨ ⍝ all divided by nf+ns+z²
```
[Answer]
# Python, 79 67 bytes
```
lambda s,f,z=3.8416:2j**.5*(s-(-z*(f*s/(f+s)+z/4))**.5+z/2)/(f+s+z)
```
Output is a complex integer with the interval stored as the real/imaginary part.
[Answer]
# [dc](https://en.wikipedia.org/wiki/Dc_(computer_program)), 71 bytes
```
16k?dsa2*?sb1.96 2^dso+dlalb4**lalb+/lo+vlov*dsd+lalblo++2*dsx/rld-lx/f
```
Takes both inputs on two separate lines upon invocation, and outputs on two separate lines with the upper bound on the *bottom* and the lower bound on *top*.
For example:
```
bash-4.4$ dc -e '16k?dsa2*?sb1.96 2^dso+dlalb4**lalb+/lo+vlov*dsd+lalblo++2*dsx/rld-lx/f'
10 # Input n_s
90 # Input n_f
.0552285416131361 # Output lower bound
.1743673043676654 # Output upper bound
```
[Answer]
## Racket 134 bytes
```
(let*((n(+ s f))(z 1.96)(h(* z z))(p(/ 1(+ n h)))(q(+ s(/ h 2)))(r(* z(sqrt(+(/(* s f) n)(/ h 4))))))(values(* p(- q r))(* p(+ q r))))
```
Ungolfed:
```
(define (g s f)
(let* ((n (+ s f))
(z 1.96)
(zq (* z z))
(p (/ 1 (+ n zq)))
(q (+ s (/ zq 2)))
(r (* z (sqrt (+ (/(* s f) n) (/ zq 4))))))
(values (* p (- q r)) (* p (+ q r)))))
```
Testing:
```
(g 1 10)
```
Output:
```
0.016231752262825982
0.3773646254862038
```
[Answer]
# Java 7, 130 bytes
Golfed:
```
double[]w(int s,int f){double n=s+f,z=1.96,x=z*z,p=s+x/2,d=z*Math.sqrt(s*f/n+x/4),m=1/(n+x);return new double[]{m*(p-d),m*(p+d)};}
```
Ungolfed:
```
double[] w(int s, int f)
{
double n = s + f, z = 1.96, x = z * z, p = s + x / 2, d = z * Math.sqrt(s * f / n + x / 4), m = 1 / (n + x);
return new double[]
{ m * (p - d), m * (p + d) };
}
```
[Try it online](https://ideone.com/CHeljM)
Returns an array of type double of length 2, can probably be golfed more.
[Answer]
# [><>](https://esolangs.org/wiki/Fish) with `-v` flag, 100 bytes
```
:{:@:}*@+:@,24a,a,-:@:*:&4,+:\$~*{&:&2,+}:{:@@-{&+:&,nao+&,n;
,}:{::*@@-:0$0(?$-1a,:*:*:*(?\}:{:@,+2
```
Expects the input to be present on the stack at execution start, in the order `n_s, n_f`. [Try it online!](https://tio.run/##HYuxCsMwEEP3fkUHcwSfDI7JpA7xh2TxEtKlHQpdTPLrl0sQvEHSW9@/zYydlXusyooyNTQkLyJlgnIJR@xCKdD9OtbURSn4tK86Xw9cNaMPzCEPc0hjg9ueYV5uB1rMLP2fY755Ag "><> – Try It Online")
What a stupid language to attempt this in...
As ><> lacks an exponent or root operator, the square root is calculated in the second line of code using the [Babylonian method](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method), to an accuracy of `1e-8` - for every example I've tried, this is accurate to at least 10 decimal places. If this isn't precise enough, the bounds can be tightened by adding more `:*` in the second line, shuffling things around to keep the mirrors in line.
Output is in the following form:
```
<lower bound>
<upper bound>
```
[Answer]
# Pyth, 38 bytes
```
J*K1.96Kmc++dhQcJ2+sQJ_B*K@+cJ4c*FQsQ2
```
Input is as a list of values, `[n_s, n_f]`. Output is `[upper, lower]` Try it online [here](https://pyth.herokuapp.com/?code=J%2AK1.96Kmc%2B%2BdhQcJ2%2BsQJ_B%2AK%40%2BcJ4c%2AFQsQ2&input=%5B10%2C1%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=J%2AK1.96Kmc%2B%2BdhQcJ2%2BsQJ_B%2AK%40%2BcJ4c%2AFQsQ2&test_suite=1&test_suite_input=%5B0%2C%201%5D%0A%5B1%2C%200%5D%0A%5B1%2C%201%5D%0A%5B1%2C%2010%5D%0A%5B10%2C%201%5D%0A%5B10%2C%2090%5D%0A%5B90%2C%2010%5D%0A%5B25%2C%2075%5D%0A%5B75%2C%2025%5D%0A%5B50%2C%2050%5D%0A%5B0%2C%20100%5D%0A%5B100%2C%200%5D&debug=0).
```
J*K1.96Kmc++dhQcJ2+sQJ_B*K@+cJ4c*FQsQ2 Implicit: Q=eval(input())
K1.96 Set variable K=1.96 (z)
J*K K Set variable J=K*K (z^2)
*FQ Product of input pair
c sQ Divide the above by the sum of the input pair
cJ4 J / 4
+ Add the two previous results
@ 2 Take the square root of the above
*K Multiply by K
_B Pair the above with itself, negated
m Map each in the above, as d, using:
hQ First value of input (i.e. n_s)
cJ2 J / 2
++d Sum the above two with d
c Divided by...
+sQJ ... (J + sum of input)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
×÷++1.96²©HH¤×®½×Ø-+®H¤+³÷++®ɗ
```
[Try it online!](https://tio.run/##y0rNyan8///w9MPbtbUN9SzNDm06tNLD49CSw9MPrTu0Fyg@Q1f70DqggPahzSA1h9adnP7//39Lg/@GBgA "Jelly – Try It Online")
## Explanation
```
Inputs: s and f
×÷+ (s×f)÷(s+f)
1.96²©HH¤ (© ← 1.96²)÷4 (call this W)
+ (s×f)÷(s+f)+W
×® ((s×f)÷(s+f)+W)ש
½ sqrt[ ((s×f)÷(s+f)+W)ש ] (call this R)
ר- [ -R, +R ]
+®H¤ [©/2-R, ©/2+R ]
+³ [©/2-R+s, ©/2+R+s]
÷ Divide both by:
++®ɗ (s+f)+©
```
## Note
Some of these features are newer than the challenge. I believe around the time this challenge was posted, `++®¶×÷++1.96²©HH¤×®½×-,1+®H¤+³÷ç` was valid Jelly (32 bytes), lacking `ɗ` and `Ø-`.
[Answer]
# APL(NARS), 49 chars, 98 bytes
```
{k←1.9208⋄(2+n÷k)÷⍨(1+⍺÷k)+¯1 1×√1+2×⍺×⍵÷k×n←⍺+⍵}
```
test
```
f←{k←1.9208⋄(2+n÷k)÷⍨(1+⍺÷k)+¯1 1×√1+2×⍺×⍵÷k×n←⍺+⍵}
25 f 75
0.17545094 0.3430464637
0 f 1
0 0.7934567085
1 f 0
0.2065432915 1
```
] |
[Question]
[
Define a *prepend-append sequence* of length `n` to be a permutation of the numbers `1, 2, ..., n` that can be generated by the following procedure:
* Start with the number `1`.
* For each number from `2` to `n`, place this number to the beginning or end of the sequence (either *prepend* or *append* it, hence the name of the sequence).
For example, this is a valid way to generate a prepend-append sequence of length 4:
```
1
21 [beginning]
213 [end]
2134 [end]
```
Your task is to build a program or function that will take a number `n` from `3` to `30` as input, and print or return all prepend-append sequences of length `n` in lexicographical order (if you're outputting strings and not lists, numbers above 9 will be represented as letters `a-u`, to preserve string length). For example, this is that order for `n = 4`:
```
1234 [RRR]
2134 [LRR]
3124 [RLR]
3214 [LLR]
4123 [RRL]
4213 [LRL]
4312 [RLL]
4321 [LLL]
```
In general, there are 2n-1 prepend-append permutations of length `n`.
You may not use any built-in sorting functions in your language in your code. The shortest program to do this in any language wins.
[Answer]
# CJam, ~~22 20 19~~ 17 bytes
```
]]l~{)f+_1fm>|}/p
```
**Code expansion**:
```
]] "Put [[]] onto stack. What we will do with this array of array is";
"that in each iteration below, we will first append the next";
"number to all present arrays, then copy all the arrays and";
"move the last element to first in the copy";
l~ "Read input number. Lets call it N";
{ }/ "Run this code block N times ranging from 0 to N - 1";
)f+ "Since the number on stack starts from 0, add 1 to it and append";
"it to all arrays in the array of array beginning with [[]]";
_1fm> "Copy the array of array and move last element from all arrays";
"to their beginning";
| "Take set union of the two arrays, thus joining them and eliminating";
"duplicates. Since we started with and empty array and started adding";
"numbers from 1 instead of 2, [1] would have appeared twice if we had";
"simply done a concat";
p "Print the array of arrays";
```
**How it works**:
This is a debug version of the code:
```
]]l~ed{)edf+ed_ed1fm>ed|ed}/edp
```
Let's see how it works for input `3`:
```
[[[]] 3] "]]l~" "Empty array of array and input";
[[[]] 1] "{)" "First iteration, increment 0";
[[[1]]] "{)f+" "Append it to all sub arrays";
[[[1]] [[1]]] "{)f+_" "Copy the final array of array";
[[[1]] [[1]]] "{)f+_1fm>" "shift last element of each";
"sub array to the beginning";
[[[1]]] "{)f+_1fm>|}" "Take set based union";
[[[1]] 2] "{)" "2nd iteration. Repeat";
[[[1 2]]] "{)f+"
[[[1 2]] [[1 2]]] "{)f+_";
[[[1 2]] [[2 1]]] "{)f+_1fm>";
[[[1 2] [2 1]]] "{)f+_1fm>|}";
[[[1 2] [2 1]] 3] "{)";
[[[1 2 3] [2 1 3]]] "{)f+"
[[[1 2 3] [2 1 3]] [[1 2 3] [2 1 3]]] "{)f+_";
[[[1 2 3] [2 1 3]] [[3 1 2] [3 2 1]]] "{)f+_1fm>";
[[[1 2 3] [2 1 3] [3 1 2] [3 2 1]]] "{)f+_1fm>|}";
[[[1 2 3] [2 1 3] [3 1 2] [3 2 1]]] "{)f+_1fm>|}/";
```
[Try it online here](http://cjam.aditsu.net/#code=%5D%5Dl~%7B)f%2B_1fm%3E%7C%7D%2Fp&input=4)
[Answer]
# Haskell, 47 bytes
```
f 1=[[1]]
f n=(\x->map(++[n])x++map(n:)x)$f$n-1
```
[Answer]
# Python 2, 68
```
f=lambda n:[[1]]*(n<2)or[x*b+[n]+x*-b for b in[1,-1]for x in f(n-1)]
```
Outputs a list of lists of numbers.
A recursive solution. For `n==1`, output `[[1]]`. Otherwise, add `n` to the start or end of all `(n-1)`-permutations. Prepending makes the permutation lexicographically later than appending, so the permutations remain sorted.
The "Boolean" `b` encodes whether to put `[n]` at the start or end. Actually, we move the rest of the list `x` in the expression `x*b+[n]+x*-b`. Putting `b` as `-1` or `1` lets use flip by negating, since a list multiplied by `-1` is the empty list.
[Answer]
# Pyth, 19
```
usCm,+dH+HdGr2hQ]]1
```
[Try it online here](https://pyth.herokuapp.com/)
This is a full program that takes input from stdin.
This works in a similar way to xnor's solution, but generates the values a bit out of order, so they must be reordered. What happens at each level is that each previous list of values has the new value added to the end and to the beginning and these are each wrapped in a 2-tuple which are wrapped together in a list. For example, the first step does this:
```
[[1]]
[([1,2], [2,1])]
```
Then, this list of tuples is zipped (and then summed to remove the outermost list). In the first case this just gives the unwrapped value from above, as there is only one value in the list.
Steps showing 2->3:
```
([1,2], [2,1])
[([1,2,3],[3,1,2]),([2,1,3],[3,2,1])]
([1,2,3],[2,1,3],[3,1,2],[3,2,1])
```
[Answer]
# Mathematica, ~~57~~ ~~54~~ 49 bytes
```
f@1={{1}};f@n_:=#@n/@f[n-1]&/@Append~Join~Prepend
```
Example:
```
f[4]
```
>
> {{1, 2, 3, 4}, {2, 1, 3, 4}, {3, 1, 2, 4}, {3, 2, 1, 4}, {4, 1, 2, 3}, {4, 2, 1, 3}, {4, 3, 1, 2}, {4, 3, 2, 1}}
>
>
>
[Answer]
# J, 26 bytes
```
0|:<:((,,.,~)1+#)@[&0,.@1:
(0|:<:((,,.,~)1+#)@[&0,.@1:) 3
1 2 3
2 1 3
3 1 2
3 2 1
```
1-byte improvement thanks to [FUZxxl](https://codegolf.stackexchange.com/users/134/fuzxxl).
[Answer]
# Pyth, ~~34~~ ~~33~~ ~~31~~ 29
Basically a translation of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python answer](https://codegolf.stackexchange.com/a/47480/30164). I'm still not great with Pyth, so improvement suggestions are welcome.
Defines a function `y` to return a list of lists of integers.
```
L?]]1<b2smm++*kdb*k_dy-b1,1_1
```
**Update:** Saved 2 bytes thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman).
Explanation:
```
L define a function y with argument b that returns
?*]]1<b2 [[1]] if b < 2 else
s sum(
m map(lambda d:
m map(lambda k:
++*kdb*k_d k*d + [b] + k*-d
y-b1 , y(b - 1))
,1_1) , (1, -1))
```
[Answer]
# Pure Bash, 103
Longer than I'd hoped:
```
a=1..1
for i in {2..9} {a..u};{
((++c<$1))||break
a={${a// /,}}
a=`eval echo $a$i $i$a`
}
echo ${a%%.*}
```
[Answer]
# JavaScript (ES6) 73 ~~80~~
JavaScript implementation of @Optimizer's nice solution.
Recursive (73):
```
R=(n,i=1,r=[[1]])=>++i>n?r:r.map(e=>r.push([i,...e])+e.push(i))&&R(n,i,r)
```
Iterative (74):
```
F=n=>(i=>{for(r=[[1]];++i<=n;)r.map(e=>r.push([i,...e])+e.push(i))})(1)||r
```
**Test** In Firefox/FireBug console
```
R(4)
```
>
> [[1, 2, 3, 4], [2, 1, 3, 4], [3, 1, 2, 4], [3, 2, 1, 4], [4, 1, 2, 3], [4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 2, 1]]
>
>
>
[Answer]
My Java solution:
```
public static void main(String[] args) {
listPrependAppend(4);
}
private static void listPrependAppend(int n) {
int total = (int) Math.pow(2, n - 1);
int ps;
boolean append;
String sequence;
String pattern;
for (int num = 0; num < total; num++) {
sequence = "";
pattern = "";
append = false;
ps = num;
for (int pos = 1; pos < n + 1; pos++) {
sequence = append ? (pos + sequence) : (sequence + pos);
append = (ps & 0x01) == 0x01;
ps = ps >> 1;
if (pos < n) {
pattern += append ? "L" : "R";
}
}
System.out.format("%s\t[%s]%n", sequence, pattern);
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Œ!IṠIAƑƲƇ
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//xZIhSeG5oElBxpHGssaH/8OHWSlq4oG@wrbCtv//Ng "Jelly – Try It Online")
## How it works
```
Œ!IṠIAƑƲƇ - Main link. Takes an integer n on the left
Œ! - Permutations of [1,2,...,n]
ƲƇ - Keep those permutations for which the following is true:
I - Forward increments
Ṡ - Signs
I - Forward increments
AƑ - All non-negative?
```
To see why this works, take four permutations for \$n = 4\$:
* `[2,1,3,4]` which is a prepend-append permutation
* `[3,2,1,4]` which is a prepend-append permutation
* `[3,1,4,2]` which is not
* `[1,2,4,3]` which is not
Let's work through each of the 4 commands (`I`, `Ṡ`, `I` and `AƑ`) to see the difference. Each command is applied sequentially to the result of the previous one:
| Command | `[2,1,3,4]` | `[3,2,1,4]` | `[3,1,4,2]` | `[1,2,4,3]` |
| --- | --- | --- | --- | --- |
| `I` | `[-1,2,1]` | `[-1,-1,3]` | `[-2,3,-2]` | `[1,2,-1]` |
| `Ṡ` | `[-1,1,1]` | `[-1,-1,1]` | `[-1,1,-1]` | `[1,1,-1]` |
| `I` | `[2,0]` | `[0,2]` | `[2,-2]` | `[0,-2]` |
| `AƑ` | `1` | `1` | `0` | `0` |
It turns out that always `IṠI` yields an array consisting of `2`, `0` or `-2`, and that if a permutation does not contain `-2` after `IṠI` is applied, the permutation is a prepend-append permutation.
] |
[Question]
[
This challenge is similar to [Can you Meta Quine?](https://codegolf.stackexchange.com/questions/5510/can-you-meta-quine)
A quine is a program that produces itself on STDOUT. This challenge is to produce a program A which when run produces a program B on STDOUT. Program B when run produces program A on STDOUT. Programs A and B must be written in (and run in) the same language. The linked question constrained A != B. That looked too easy. So for this question, we insist A and B are antiquines, using the following rules:
1. Programs A and B may not use any of the same characters, save for whitespace and statement separators, and punctuation characters.
2. Programs A and B must each contain at least one character that is neither whitespace nor a statement separator, nor a punctuation character.
3. For the purpose of rules 1 and 2, the term 'whitespace' excludes any symbol or sequence of symbols which itself is a statement, operator or symbol that is interpreted (as opposed to a separator). Therefore in the Whitespace language, there is no whitespace.
4. A statement separator is a syntactic element conventionally used within the language to separate statements. This would include the newline in python, or the semicolon in Java, perl or C.
5. A punctuation character is an ASCII character which is neither whitespace nor in the POSIX word character class (i.e. an underscore is not punctuation for this purpose) - i.e `ispunct()` would return true, and it's not `_`.
6. Program A when run must produce a program (Program B) on its STDOUT, which when run in turn produces Program A.
7. Programs A and B must be in the same programming language.
8. The programming language used must actually be a programming language. Unless you make a good case otherwise, I'll suggest it must be Turing complete.
9. At least one of A and B must execute at least one statement within the language.
This is code golf, so the shortest answer wins, the score being the length of program A in bytes (i.e. the length of program B is not relevant).
[Answer]
## Pascal (731 characters)
Program A:
```
program s;{$h+}uses sysutils;const p='program s;{$h+}uses sysutils;const p=';a='a';aa=''';';aaa='a=''';aaaa='''';aaaaa='begin write(lowercase(p+aaaa+p+aa+aaa+a+aa+a+aaa+aaaa+aa+aa+a+a+aaa+aaa+aaaa+aa+a+a+a+aaa+aaaa+aaaa+aa+a+a+a+a+aaa+stringreplace(stringreplace(stringreplace(stringreplace(aaaaa,aaaa,aaaa+aaaa,[rfreplaceall]),''lower''+''c'',''tm''+''p'',[]),''up''+''c'',''lower''+''c'',[]),''tm''+''p'',''up''+''c'',[])+aa+aaaaa))end.';begin write(upcase(p+aaaa+p+aa+aaa+a+aa+a+aaa+aaaa+aa+aa+a+a+aaa+aaa+aaaa+aa+a+a+a+aaa+aaaa+aaaa+aa+a+a+a+a+aaa+stringreplace(stringreplace(stringreplace(stringreplace(aaaaa,aaaa,aaaa+aaaa,[rfreplaceall]),'lower'+'c','tm'+'p',[]),'up'+'c','lower'+'c',[]),'tm'+'p','up'+'c',[])+aa+aaaaa))end.
```
Outputs program B:
```
PROGRAM S;{$H+}USES SYSUTILS;CONST P='PROGRAM S;{$H+}USES SYSUTILS;CONST P=';A='A';AA=''';';AAA='A=''';AAAA='''';AAAAA='BEGIN WRITE(UPCASE(P+AAAA+P+AA+AAA+A+AA+A+AAA+AAAA+AA+AA+A+A+AAA+AAA+AAAA+AA+A+A+A+AAA+AAAA+AAAA+AA+A+A+A+A+AAA+STRINGREPLACE(STRINGREPLACE(STRINGREPLACE(STRINGREPLACE(AAAAA,AAAA,AAAA+AAAA,[RFREPLACEALL]),''LOWER''+''C'',''TM''+''P'',[]),''UP''+''C'',''LOWER''+''C'',[]),''TM''+''P'',''UP''+''C'',[])+AA+AAAAA))END.';BEGIN WRITE(LOWERCASE(P+AAAA+P+AA+AAA+A+AA+A+AAA+AAAA+AA+AA+A+A+AAA+AAA+AAAA+AA+A+A+A+AAA+AAAA+AAAA+AA+A+A+A+A+AAA+STRINGREPLACE(STRINGREPLACE(STRINGREPLACE(STRINGREPLACE(AAAAA,AAAA,AAAA+AAAA,[RFREPLACEALL]),'LOWER'+'C','TM'+'P',[]),'UP'+'C','LOWER'+'C',[]),'TM'+'P','UP'+'C',[])+AA+AAAAA))END.
```
Outputs program A.
[Answer]
# [ROT13](http://esolangs.org/wiki/ROT13_encoder/decoder) (*not competing anymore after rule update*)
Not sure if this counts as a language, but I certainly didn't make it up for the challenge. Usually answers for certain utilities such as `sed` are accepted as well. However, it's a judgement call, so if it doesn't count I'll remove it (is there a meta discussion somewhere on what counts as a language? Edit: [There is now](http://meta.codegolf.stackexchange.com/questions/2028/what-are-programming-languages))
```
A
```
Cycles between `A` and `N`:
```
~>> echo "A" | rot13
N
~>> echo "A" | rot13 | rot13
A
```
[Answer]
# GolfScript, 13 bytes
```
1{\~\".~"}.~
```
The output is
```
-2{\~\".~"}.~
```
which generates the initial program.
The byte count include the trailing LF, since the output of the output will contain it.
[Try it online.](http://golfscript.apphb.com/?c=MXtcflwiLn4ifS5%2BICAgIyBQcm9ncmFtIEEKCm4gbiAgICAgICAgICAgICMgTmV3bGluZXMKCi0ye1x%2BXCIufiJ9Ln4gICMgUHJvZ3JhbSBC)
### How it works
```
1 # Push 1.
{ # Start code block.
\~\ # Apply logical NOT to the second topmost element of the stack.
".~" # Push that string.
} # End code block.
.~ # Duplicate the code block and execute the copy.
```
GolfScript prints the stack's contents upon termination.
] |
[Question]
[
An ant starts on an edge of a [dodecahedron](https://en.wikipedia.org/wiki/Regular_dodecahedron), facing parallel to it. At each step, it walks forward to the next vertex and turns either left or right to continue onto one of the other two edges that meet there. A sequence of left/right choices that returns the ant to its initial state (edge and direction) is called a *round trip*.
Write a function (or program) that takes a string of `L`s and `R`s and returns (or outputs) one of two values, indicating whether the input represents a round trip.
Examples:
```
LLLLL -> yes
LRLRLRLRLR -> yes
RRLRRLRRL -> yes
(empty sequence) -> yes
R -> no
LLLLLL -> no (starts with a round trip but leaves initial state)
RLLLLR -> no (returns to initial edge but opposite direction)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 79 bytes
```
lambda s:all(n==reduce(lambda n,c:-~[n,n%3+n%4][c>'L']%5,s,n)for n in range(5))
```
[Try it online!](https://tio.run/##NYm7DoMgGIV3noKFCCkdenEhoU/AxGpNQxEqCf4axJgufXWrvZxz8g3nG5657eG4eHldounujcGjMDFSkDK5ZrKO/m7gVuxfFXAgpx2Qc13ZS6GKmpR85MB8nzDgADgZeDhaMrbMbYgOH8SQAmTsaTLzLcAwZbpKtQUp/S/SKz5DSCP11XqjfgM "Python 2 – Try It Online")
This uses the group-theoretic approach from [Ilmari Karonen's GolfScript answer](https://codegolf.stackexchange.com/a/35996/20260) to my [2014 challenge](https://codegolf.stackexchange.com/q/35978/20260), in particular to the bonus question.
Instead of the ant crawling around the dodecahedron, we imagine it stays in place while the dodecahedron turns under its feet. We must determine whether the sequence of rotations returns the dodecahedron to the initial position.
There are 60 rotation of the dodecahedron -- 12 faces times 5 positions per face. These rotations can be expressed as permutations of 5 elements. Specifically, they permute 5 colored tetrahedra shown below that partition the 20 vertices of the dodecahedron.
[](https://i.stack.imgur.com/zCRYMm.jpg)
We could take each rotation and write down which color tetrahedron moves onto which color's position to obtain a permutation of the five colors. Specifically, these are the [even permutations](https://en.wikipedia.org/wiki/Parity_of_a_permutation), which are half of the 5!=120 permutations of five elements, or 60, forming the [alternating group](https://en.wikipedia.org/wiki/Alternating_group) \$A\_5\$ on five elements. The other 60 odd permutations would involve reflecting the dodecahedron and well as rotating it, so they do not figure in this problem.
We want to choose two even permutations that represent the rotations from the ant turning left and right. As [noted by Ilmari Karonen](https://codegolf.stackexchange.com/a/35996/20260), the two permutations must have order 5, corresponding to five left or five right turns brining the ant back to the same place. Moreover, their product must have order 5 as well, and neither can be a power of the other.
There are many choices for the two permutations. If we think of them as permuting the values 0 to 4, the pair our code uses is `12340` and `13042`. The first one simply adds one modulo 5. From here, there's 5 choices for the other one: `13042, 14302, 24310, 32041, 32410`. The code uses `13042` because it happens to have a short expression in Python `1+(n%3+n%4)%5`, or just `n%3+n%4` if we "share" the `+1` and `%5` for the other case`. I found this via some brute-forcing.
Now let's take another look at the code:
```
lambda s:all(n==reduce(lambda n,c:-~[n,n%3+n%4][c>'L']%5,s,n)for n in range(5))
```
[Try it online!](https://tio.run/##NYm7DoMgGIV3noKFCCkdenEhoU/AxGpNQxEqCf4axJgufXWrvZxz8g3nG5657eG4eHldounujcGjMDFSkDK5ZrKO/m7gVuxfFXAgpx2Qc13ZS6GKmpR85MB8nzDgADgZeDhaMrbMbYgOH8SQAmTsaTLzLcAwZbpKtQUp/S/SKz5DSCP11XqjfgM "Python 2 – Try It Online")
To check that the sequence of permutations combines to the identity, we test each starting value `n` from `range(5)`, apply the sequence of permutations to it using `reduce`, and check that `all` of them end up at the initial value. The `-~` is a shortcut to add one.
---
**74 bytes**
```
lambda s:0in[n==reduce(lambda n,c:-~[n,48/~n][c>'L']%5,s,n)for n in 0,1,2]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYyiAzLzrP1rYoNaU0OVUDKpynk2ylWxedp2NioV@XFxudbKfuox6raqpTrJOnmZZfpJCnkJmnYKBjqGMU@788IzMnVcHQqqAoM69EIU2jKLE8PjOvoLREQ1Pzvw8IcPkEwSBXEJAAIy6uIC4fiHQQiAwCAA "Python 2 – Try It Online")
Outputs True/False swapped.
I found `48/~n` as a shorter alternative for the second permutation when it is incremented and taken mod 5.
Also, instead of checking that the permutation maps each of `0,1,2,3,4` to themselves, this only checks `0,1,2`. This suffices because the map is bijective, so once `0,1,2` are fixed, `3` and `4` have to either map to themselves or swap, and because the permutation is even they can't swap.
**65 bytes**
```
S=s=`321.`
for c in input():s=(s+s[ord(c)%9:3]+s)[3:8]
print s==S
```
[Try it online!](https://tio.run/##K6gsycjPM/pfnpGZk6pgaJVakZqspKT0P9i22DbB2MhQL4ErLb9IIVkhMw@ICkpLNDStim01irWLo/OLUjSSNVUtrYxjtYs1o42tLGK5Cooy80oUim1tg/@DTFHyAQElLiWfIBgEcoKAFBgB2SAuSB6mMAhEBykBAA "Python 2 – Try It Online")
This uses a different mapping pair: `34012, 34120`. These are nice to implement as operations on lists, moving the last two elements to the front in both cases, and for the latter cycling the last 3. To start, we just need any sequence of 5 distinct elements, so we use ``321.`` which equals `'321.0'`.
**61 bytes**
```
n=27
for c in input():n=n%16*64|n/16*4**(c>'L')%63
print n<28
```
[Try it online!](https://tio.run/##K6gsycjPM/pfnpGZk6pgaJVakZqspKT0P8/WyJwrLb9IIVkhMw@ICkpLNDSt8mzzVA3NtMxMavL0gbSJlpZGsp26j7qmqpkxV0FRZl6JQp6NkcV/kAlKPiCgxKXkEwSDQE4QkAIjIBvEBcnDFAaB6CAlAA "Python 2 – Try It Online")
This uses bitwise shenanigans, much like my [2018 answer](https://codegolf.stackexchange.com/a/157848/20260) with cubes. It implements the permutations `34012, 34120`.
The number `n` encode 5 fields of bits 2 each, say `abcde`. Each step permutes these bits to either `deabc` or `debca` using bitwise operations. `n%16*64` moves `de` into the first two positions, while `n/16*4**(c>'L')%63` makes `abc` in the last 3 positions and then conditionally transforms it to `bca` if an `R` is read.
Initial, these five fields are `00123`, which translates into `n=27` in base 4. It's fine that the first 2 of them are the same, as no sequence of permutations can solely swap them because all the permutations are even. Because `n=27` is the smallest possible permutation of the fields, we can use `n<28` to check that the final state is the same as the initial one.
**60 bytes**
```
L=1;R=1j
for c in input():exec c+"=(L+R)%5%5j"
print L*1j==R
```
[Try it online!](https://tio.run/##NUxBCoQwDLz3FSEg6Hrqgpdd8oOc8oVSsWWpRSqur6@NYGZgZsgw@SzLmt71WMLPg/34v3eIWJnsV8hGM68bOAipMe@lH@4GuBGp51GGbuqmiCZvIRXgl41EUnUAWQ8NsjxoQZrcbF6j/p@iqApe "Python 2 – Try It Online")
A new method based on [alephalpha's finding](https://codegolf.stackexchange.com/a/251549/20260) that \$A\_5 \cong PSL(2,5)\$. A cute trick here is using `L` and `R` for variables so we can plug the character we read and `exec`.
We interpret the `L`'s and `R`'s as instructions to set either `L=L+R` or `R=L+R`. If this always results in either getting back the original values mod 5 or getting back their negations mod 5, then the instructions give a closed loop.
It suffices to test that this works for both the initial "basis vectors" `L=1, R=0` and `L=0, R=1`. Instead of testing twice, we run both tests in parallel using complex numbers, with one case in the real part and the other in the imaginary part, so `L=1, R=1j`. Python 2 has a wacky complex modulus that lets us `%5` to reduce the real part and `%5j` to reduce the imaginary part.
In the end, we can if we're in one of the success cases of the original `L=1,R=1j` or its negation mod 5 of `L=4,R=4j`. It turns out it suffices to check `L*1j==R` as shown by [this code](https://tio.run/##RczBasMwEATQu75ioARsRw1NqS8B/YFP@gNZ2tQq9q5Q1oF@vSt6yWkGhnnlVxfhz@Pwrgb@pu7Djr3JW5GqyEpVRdaHuUtFsLONNiHza7iUKmmP2nlbqVBQ99XfDN6gC0GeVMO6QkpLzcLY9odiCU9CokZsmQMrhAlbY1bBaJDvYFF0YUjv8xD70@jctZmIwpp5J4PJhfM8XH8MvIvn9N/abWrFOX9Dqbmx3WR9fxx/ "Python 2 – Try It Online") testing for false positives.
**59 bytes**
```
L=1;R=1j
exec"=(L+R)%5%5j;".join(input()+' ')
print L*1j==R
```
[Try it online!](https://tio.run/##NUtLCoQwDN33FCUgtiMIHXCj5AZZ5QpSsGWoRSrOnL7TCCYP3icv@Ve2Pb3rtYWP1272X78CQCV0C6OL6g7Q0MC2m7opLjDGPSQTUj6LsUOve6vyEVLR9HIRkav8A8mAAuJnm@FGN5oWK/enyMIMfw "Python 2 – Try It Online")
Saves one byte from above using `.join` to create the string to execute.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 51 bytes
```
s->t=x;[t=Mod(t+p=c>"O",5)/(t*!p+1)|c<-Vec(s)];t==x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN42Lde1KbCuso0tsffNTNEq0C2yT7ZT8lXRMNfU1SrQUC7QNNWuSbXTDUpM1ijVjrUtsbSugWpMSCwpyKjWKFXTtFAqKMvNKgEwlEEdJIQ2oVlNHIVrJBwSUdBSUfIJgEMQLAtJgBOKABcBq4KqDgHSQUqwmxKYFCyA0AA)
Using the isomorphism \$A\_5 \cong PSL(2,5)\$. See this question on Mathematics SE: <https://math.stackexchange.com/q/93762/99103>
In this isomorphism, the permutations represented by `L` and `R` are mapped to the rational functions \$\frac{x}{x+1}\$ and \$x+1\$ respectively.
---
## [PARI/GP](https://pari.math.u-bordeaux.fr), 58 bytes
```
s->m=matid(2);[m=m*[1,p=c>"O";!p,1]%5|c<-Vec(s)];m==m[1,1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN62Kde1ybXMTSzJTNIw0raOBbK1oQ50C22Q7JX8la8UCHcNYVdOaZBvdsNRkjWLNWOtcW9tcoArDWKgJSYkFBTmVGsUKunYKBUWZeSVAphKIo6SQBtSgqaMQreQDAko6Cko-QTAI4gUBaTACccACYDVw1UFAOkgpVhNi04IFEBoA)
This uses the same isomorphism as above, but uses matrices (\$\bigl(\begin{smallmatrix}1&0\\1&1\end{smallmatrix}\big)\$ and \$\bigl(\begin{smallmatrix}1&1\\0&1\end{smallmatrix}\big)\$ for `L` and `R`) instead of rational functions to represent elements of \$PSL(2,5)\$.
---
## [PARI/GP](https://pari.math.u-bordeaux.fr), 63 bytes
```
s->prod(n=0,4,m=n;[m=[m+1,33%m+=9][c%5]%5|c<-Vecsmall(s)];m==n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN-2Lde0KivJTNPJsDXRMdHJt86yjc22jc7UNdYyNVXO1bS1jo5NVTWNVTWuSbXTDUpOLcxNzcjSKNWOtc21t8zShxiQlFhTkVGoUK-jaKRQUZeaVAJlKII6SQhpQsaaOQrSSDwgo6Sgo-QTBIIgXBKTBCMQBC4DVwFUHAekgpVioTQsWQGgA)
A port of [@xnor's answer](https://codegolf.stackexchange.com/a/251541/9288), but uses `33%(n+9)%5` instead of `(1+n%3+n%4)%5`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 13 bytes (thanks @Jonathan Allan!)
```
OH+53œ?@ƒ5FṢƑ
```
[Try it online!](https://tio.run/##y0rNyan8/9/fQ9vU@Ohke4djk0zdHu5cdGzi////g4J8IAgA "Jelly – Try It Online")
```
OH+53œ?@ƒ5FṢƑ
O ord() the input list (vectorizes)
H Divide by 2 (vectorizes)
+ Add...
53 ...53 (all these steps vectorize)
ƒ Reduce the input list with:
@ The preceding dyadic link, with its arguments swapped:
œ? The nth permutation of the right argument
...using the following as the starting value for the reduce:
5 5 (which gets implicitly converted to [1,2,3,4,5] by œ?)
F Flatten (wraps 5 into [5] in case the input list is empty)
Ƒ Check if the output of the previous link is equal to its left argument:
Ṣ Sort the output list
(The last two bytes effectively check if the list is already in sorted order.)
```
Uses essentially the same logic as [@xnor's answer](https://codegolf.stackexchange.com/a/251541/21775). The two permutations I used were `45231` and `45123`, since their indices (94 and 91, respectively) can be easily computed from the `ord` values of 'R' and 'L' (82 and 76, respectively): divide by 2 and add 53. I wrote a Python script to check all valid pairs of permutations to find the optimal ones (in terms of how many bytes are needed to calculate their indices from 82 and 76), and no other permutations were better than these.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ 32 bytes
```
≔E⁵ιθFSUMθ⎇›ιL﹪⁺³κ⁵÷↔⁻⁹×⁴κ²⬤θ⁼ικ
```
[Try it online!](https://tio.run/##JY3LCsIwEEX3/YrQ1QTiRu1CuioqUmihVH8gtrEG06TNo@DXxwnCzCyGc@8Z3twOhqsYK@fkpKHlCxSMSMrISsvsZSyBWi/B372VegJKCSJnM89cj7Ay8hBWc/uFmxXcCwuSkbzJMd6aMSgDnQoODox88FXg1tpf5CZHAdXTGRW8gFZqZE7YJWfh4Jhgiugeb5l16PVQKZVs1zVw5ZIkIWWMfd/8J@429QM "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a round trip, nothing if not. Explanation: I too read the linked post with the dodecahedral bonus but I decided to pick `[4, 2, 0, 1, 3]` and `[3, 4, 0, 1, 2]` as my permutations for which the formulas are ~~`max(n*2,9-n*2)%5`~~ `abs(9-4*n)//2` and `(n+3)%5`. (Porting @xnor's formulas would probably be shorter but that would have been boring.)
```
≔E⁵ιθ
```
Start with a list `[0, 1, 2, 3, 4]`.
```
FS
```
Loop over the input string.
```
UMθ
```
Update the list elements in-place.
```
﹪⎇›ιL⁺³κ⌈⟦⊗κ⁻⁹⊗κ⟧⁵
```
Apply one of the two permutations as appropriate.
```
⬤θ⁼ικ
```
Check that each list element is equal to its index.
[Answer]
# [Python+](https://github.com/nayakrujul/python-plus), 49 bytes
```
n=27
£c:§()
n=n%16*64|n/16*4**(c>'L')%63
$(n<28)
```
Basically just [xnor's Python answer](https://codegolf.stackexchange.com/a/251541/114446), converted to Python+
] |
[Question]
[
Your input is a ragged list of positive integers and a positive integer. Your task is to find that positive integer and return it's index, or if the positive integer doesn't exist, indicate it's nonexistence.
How are indices in ragged lists defined? They are simply lists of indices that when used consecutively to index the ragged list, return the desired element. For example, if the ragged list is `[1,[2,3],[[4,5]],[]]` then the index of `2` is `[1,0]` and the index of `5` is `[2,0,1]`.
If there are multiple integers, return the index of the first one. That is, the one whose index is the smallest when compared lexicographically.
# Rules
You can choose between 0 and 1 based indexing and also the order of the returned index.
You must indicate the non-existance of a solution in some easily identified manner. Here are some examples:
## Ok
* Return a value that is not a list. For example, -1 or None
* Return an empty list
* Error in some way
* Exit the program
## Not ok
* Infinite loop/recursion (if you want to use a resource exhaustion error, be sure to read [this](https://codegolf.meta.stackexchange.com/questions/24411/using-resource-exhaustion-with-a-semi-deciding-algorithm?cb=1))
* Undefined behavior
* A list of integers, even if those integers are out of bounds or negative.
An exception to the last point. You may use a single consistent value that can never be the output to indicate nonexistence. For example, a program that returns `[-1]` whenever there is no solution is allowed, but a program that returns `[-1]` or `[-2]` when there isn't a solution is not allowed.
Finally, you can also return a list of all solutions in sorted order. If you use this IO format, you must return an empty list if there are no solutions.
# Test cases
```
[], 1 -> None
[[[40]]], 40 -> [0,0,0]
[[1,[]],[[3]],3,[3]], 3 -> [1,0,0]
[5], 5 -> [0]
[[],[[],[]]], 5 -> None
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 8 bytes
```
Position
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyC/OLMkMz/vf0BRZl5JtLKuXZqDg3KsWl1wcmJeXTVXdbWhTrWRjnGtTnW1iY5pLZAGYqNaHRwypjhlzIAyQKlaHUOwEqCUQS1QGEiCuYZgRdXVxkDSWAdCgWVMYYZWg6TBZoFEuGr/AwA "Wolfram Language (Mathematica) – Try It Online")
Built-in that returns all indices, 1-indexed. A very interesting answer, I'm sure.
---
To return the first such index:
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes
```
FirstPosition
```
[Try it online!](https://tio.run/##dYwxC4NADIV3/4bQKULP87q1OHUWOpYOhyhm8ATNFuJfv8aUjg55j7zv8eZI0zBHwj7m8Z6fuG7ULRsSLil3KyZ6l9VjbNvyc9lffUw7F8wOuAYvwNxAEHW9WuCEhFNyU6JIwFlF0VU0VrXXWYnZq3r4mZHwH@UD29aRFJK/ "Wolfram Language (Mathematica) – Try It Online")
Another built-in. Returns [`Missing["NotFound"]`](https://reference.wolfram.com/language/ref/Missing.html) if `n` is not present. Almost as interesting as the above.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 14 bytes [SBCS](https://github.com/abrudz/SBCS)
Returns an empty list if the value is not present. 1-based indexing.
```
∊(∊↑⍸⍤=)∘(↑⍣≡)
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TRpfGoo@tR28RHvTse9S6x1XzUMUMDzF38qHOhJgA&f=e9TVZKiQpvCob6pXsL@fgnp0rDrXo64mEwMUwehoE4PYWIiUMaqMoU50bKxOdLQxkDTWAVFgVaYoqkyxCUaDtMWCtMeqAwA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
`↑⍣≡` Mix right argument until homogeneous (array). This converts the nested list to a rectangular array by inserting 0's.
`⍸⍤=` All indices where the left argument is equal to the resulting array.
`∊↑` Take 1 index if the left argument is present, 0 otherwise.
`∊` Flatten resulting list. This might not be necessary, but returning results with different levels of nesting seems wrong.
If returning an out-of-bounds index for the error case would be allowed, something like `⊃⍸⍤=∘(↑⍣≡)` could work.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
œi
```
[Try it online!](https://tio.run/##y0rNyan8///o5Mz/h5frP2qYeXTSw50zNCP//4@OjtVRMFQAEtFAYGIQGwtkAikw31AnGsiNjjYGksY6YErBGCxlCiRNIYpACmJBCsFCAA "Jelly – Try It Online")
Just the builtin. 1-indexed and outputs an empty list if not found.
Marginally less built in:
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
=ŒṪṂ
```
[Try it online!](https://tio.run/##y0rNyan8/9/26KSHO1c93Nn0//By/UcNM0HcGZqR//9HR8fqKBgqAIloIDAxiI0FMoEUmG@oEw3kRkcbA0ljHTClYAyWMgWSphBFIAWxIIVgIQA "Jelly – Try It Online")
1-indexed and outputs 0 if not found.
[Answer]
# Javascript, 54 bytes
```
t=>g=a=>r=a.some?.((n,i)=>s=g(n)&&[i,...r])?s:a==t&&[]
```
Input the target and the array. Output an array or `false` if not found.
```
f=
t=>g=a=>r=a.some?.((n,i)=>s=g(n)&&[i,...r])?s:a==t&&[]
console.log(f(1)([]))
console.log(f(40)([[[40]]]))
console.log(f(3)([[1,[]],[[3]],3,[3]]))
console.log(f(5)([5]))
console.log(f(5)([[],[[],[]]]))
```
# JavaScript 62 bytes
```
a=>t=>JSON.parse(a,(x,y)=>y.some?.(x=>z=x)?x?x+[,z]:z:y==t&&x)
```
```
f=
a=>t=>JSON.parse(a,(x,y)=>y.some?.(x=>z=x)?x?x+[,z]:z:y==t&&x)
console.log(f("[]")(1))
console.log(f("[[[40]]]")(40))
console.log(f("[[1,[]],[[3]],3,[3]]")(3))
console.log(f("[5]")(5))
console.log(f("[[],[[],[]]]")(5))
```
Input the array as JSON, and target value currying. Output a comma separated string or `false` if not found. It could be 58 bytes if a leading comma is acceptable.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
dbĖ|ċʰiʰgᵗz↰ʰkᵗc
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaaRx3LldISc4pT9ZRqH@7qrH24dcL/lKQj02qOdJ/akHlqQ/rDrdOrgGpPbcgGspL//4@Ojo7VUTBUABJAZrSJQWwskAmkwHxDnWggNzraGEga64ApBWOwlCmQNIUoAimIBSkEC8UCAA "Brachylog – Try It Online")
Input as a list `[list, item]`. Output 0-indexed, innermost index first, declarative failure if not found. There's definitely a byte or two left to shave off with all this list juggling, but it's already 5 down from how it started, so I'm giving it a rest for now.
# [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
h~t?bk|bB&hċi,B↰
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaaRx3LldISc4pT9ZRqH@7qrH24dcL/jLoS@6TsmiQntYwj3Zk6TkCl//9HR0fH6igYKgAJIDPaxCA2FsgEUmC@oU40kBsdbQwkjXXAlIIxWMoUSJpCFIEUxIIUgoViAQ "Brachylog – Try It Online")
This feels somehow worse.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 72 bytes
```
f(l,a)=if(l==a,[],#l'&&s=[concat(i,r)|i<-[1..#l],e!=r=f(l[i],a)],s[1],e)
```
[Try it online!](https://tio.run/##LU7RCsIwDPyVuMFsIR3OuTfrj4Q8hOGkUGbp9iL47zUrPiR3ucuRJMnBvVIpi4ko1gdF7wWJsY3nrts8ze91lt0EzPYb7o6Gvm8j4/Pks9dtCqxBxo0GFW2RlOLHCLgHpBzW3Yga0CA0IHRVdjgNLFXHqlmLQKQn4VCU0e3CrFShzoP@w0g0ah@xAozVmrRP/I/XqsGJ2ZYf "Pari/GP – Try It Online")
1-indexed. Returns `e` if not found.
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 64 bytes
```
f(l,a)=if(l==a,,#l'&&s=[r*x+i|i<-[1..#l],e!=r=f(l[i],a)],s[1],e)
```
[Try it online!](https://tio.run/##LUvNCsIwDH6VuMFcNRvO2Zv1RUIOOTgpFCmdBwXfvWbBQ77ffFlKHB651qVPKC5E5RAEsU37rlsDlcP7GL/xOtA0jm1ivO9CCfpFkXXAuNKkoauSc/r0AsMNconPVy9aQIPQgNBZ1dY0sFiOljmHQETqtkQVXU7MKpXMT0hqiWbFGY1gtsorev7P7WzomV39AQ "Pari/GP – Try It Online")
Returns a polynomial whose coefficient list is the index, e.g., `[[1, []], [[3]], 3, [3]], 3 -> x^2 + x + 2`. I'm not sure if this is allowed.
1-indexed. Returns `e` if not found.
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
```
f=lambda n,l,h=[],t=0:f(n,l[0],h+[t])or f(n,l[1:],h,t+1)if[]<l else(l==n)*h
```
[Try it online!](https://tio.run/##TY7RasQgEEWfN18xb9HubNFm8xLqfkJ/YJBiqSGCayRru/Tr0zHbQBEUzz3XMf@UaU4v6zqa6K4fnw4SRpwMWSxGDaPgKymL05GKlfMCD6IHRliOWoaR7GsEH29eRGOSfJrW@xSiBz00h4AzGFjc/T2k/FWEfL7lGIpo4XSBVjaHiImFq8vCf7uIYc@RU47zElIBlrA9XVrchsuVPwe6vvA2J98Q0VlZy@ysKiSFvCxzjcSYqOO9w@2AblP0n9Iz6R@lWqiyraUdbwP63akF/F/5BQ "Python 2 – Try It Online")
[Answer]
# [Python](https://www.python.org), 72 bytes (@att)
```
f=lambda L,n,*p:sum((f(l,n,*p,i:=i+1)for l in-1*L+L or[]),[p]*(i:=L==n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3PdJscxJzk1ISFXx08nS0CqyKS3M1NNI0csA8nUwr20xtQ820_CKFHIXMPF1DLR9tH4X8ouhYTZ3oglgtDaACH1vbPE1NqHlzCooy80qABkTH6igYamoqKCv45eelcsGFo6NNDGJjgZImBmDZaAMdIIxFUmCoEw2Uj442BpLGOmBKwRii1hBNrSlQyhRqDLIRIO2xIGPg8mBHQNwI8zsA)
### Old [Python](https://www.python.org), 75 bytes
```
f=lambda L,n,*p:[p]*(i:=L==n)+sum([f(l,n,*p,i:=i+1)for l in-1*L+L or[]],[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LCsIwEN17igE3SZtCQ1uQQk5g8AJDFhUNFmoSarvwLLroRu_kbUzTWooMzMD78ebxdvfuYs0wvPpOJ7vPXoumuh5PFUhmWORKdCoidSmkEIbGt_5KUJMmcMzDdcypti00UJuERzKWYFtUiqGic-TTtbXpiCaoGHBKYQsHa86bBUbMU-UtkKeBxZT5USsBZyESM78zFg5kk5b_aQtPFXPMOmK0j63UwocSU8ff-18)
1-based, outputs all matches.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~63~~ 59 bytes
```
f=->l,x{l*0==0?x==l:(x=l.index{|e|l=f[e,x]})&&[x,*l]-[1>0]}
```
[Try it online!](https://tio.run/##XY5NCoNADEb3PUWgICpRRtRNIfYGvUDIoj8jFIIthcIU9ezTGbtoK4Fk8R5fvsfz9PK@p6JTdKPmhsjsHZHuUkdaXoeLdeNkJ6WeLTqZsyRhh7lKwVVnZPZ36MvzUTUFFoQKsm3RweE22M0PYW6MSOCNgQyiwQbDyJ9UIQeHuQ67xuVAvegBre02wPbzjVc5MUNi1leJhfwb "Ruby – Try It Online")
f=->l,x{...}
Lambda taking *l* list, *x* element and return index or *nil*.
l\*0==0?x==l:
if *l* is a value, return if it's the value, else:
(x=l.index{|e|l=f[e,x]})&&
*x* becomes index of{..} which may be nil, in that case return nil(falsely).
Block calls recursively *f* on each element returning *true* or an array of indexes( which are both truthy ), or false otherwise.
~~[x,\*l==1>0?[]:l]~~ [x,\*l]-[1>0]
else return that index and append *l*(next indexes) removing `true`.
[Answer]
# [Whython](https://github.com/pxeger/whython), ~~63~~ ~~62~~ 59 bytes
*-3 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)*
```
f=lambda l,n,i=0:[i]+f(l[i],n)?[l[i]]*0+f(l,n,i+1)?l-n or[]
```
Returns the 0-based ragged index if found; raises an exception if not found. [Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWN63TbHMSc5NSEhVydPJ0Mm0NrKIzY7XTNHKAlE6epn00iBGrZQASAinQNtS0z9HNU8gvio6FGqFYUJSZV6KRphFtqBNtpGMcqxMdbaJjGgukgVjBVFMTohBmJwA) Or, [verify all test cases](https://ato.pxeger.com/run?1=hZBBTsMwFETFNqcYeRWTXylpGoSCoqzZcAHLi0BiNZJro8QRoKonYdMN4kxwGmzcwg42_49mnr7leX1_2r64rTXH49vi1Or640Y1utvd9x00GRqbvBajzFSq_SLDWxGEvMyDFYCs4K1eGdhJyHji8yJzw-weunmY0UAkSEVBEGtCKf0WG0IlgwpjzelvoPoPuIqAV0VUPs9lSDb5ySgokEKUfpb0vVDGrPp9QgREBvTkyUTZCXommGWH0eDnX3WCx2k0LlXs1vTDM6zC3kOHQO31fKgZPyMMjODbimc4WrA766DsYnrGY2fn-r8A).
### Explanation
We define a recursive function `f` that takes three arguments:
* `l` is the object we're searching--usually a list, but could also be an integer at the bottom of the recursion
* `n` is the number we're searching for
* `i` is the current index in `l` that we're testing
We want to error if the number is not found; using Whython's `?` operator, we can catch any errors from deeper recursive calls and try the next case. As soon as we find the right number, we return a result instead of erroring. Or, once we run out of options, the error propagates back to the caller.
The function body has three cases, connected by `?`:
```
[i]+f(l[i],n)
```
If `l` is a list and `i` is a valid index into that list, try recursing over `l[i]`. If that succeeds, it returns a list representing a ragged index, to which we prepend `i` and return. If the recursive call fails, or if `l` is not a list, or if `len(l) <= i` and therefore `i` is not a valid index into `l`, error and try the next branch:
```
[l[i]]*0+f(l,n,i+1)
```
If `l` is a list and `i` is a valid index into that list, try recursing over the same `l` with `i+1`. If that succeeds, it returns a list representing a ragged index, to which we add an empty list and return. If the recursive call fails, or if `l` is not a list, or if `i` is not a valid index into `l`, error and try the next branch:
```
l-n or[]
```
If `l` is an integer and is equal to `n`, we've found the number we're looking for; the difference is 0, so we return `[]`. If `l` is not an integer, `l-n` errors; if `l` is an integer not equal to `n`, returning some nonzero integer causes an error when we return from the recursive call and try to add the result to a list.
[Answer]
# Python3, 99 bytes:
```
f=lambda l,t,c=[]:next((m for i,a in enumerate([l,[]][l*0==0])if(m:=f(a,t,c+[i]))),0)if l!=t else c
```
[Try it online!](https://tio.run/##VY3BCgIhEIbvPcV00/Lg4i5E4JMMc7BNSVB3MYN6etOCaC8zzDf/x7@@ym1J6rTmWp0OJl6uBoIoYtZI52SfhbEIbsnghQGfwKZHtNkUyzAIJMJwkFpL4t6xeNaOmS4f0RPnXMiGIex1ARvuFua6Zp8KcwxJwMD57ncjjpKo0VFu8NBLBKJqU4nPAvWfmBqYNkqPU9e@n/oG)
[Answer]
# JavaScript (ES6), ~~62~~ 60 bytes
*Saved 2 bytes thanks to @l4m2*
Expects `(value)(array)`. Returns *false* if not found.
```
n=>g=(a,...o)=>a.map?a.some((v,i)=>g(v,...o,i))&&r:a-n?0:r=o
```
[Try it online!](https://tio.run/##bY/BCoMwDIbvewpPo4VaK@pFqL7BXiD0UFwVhzaiw9fv0rHD5mwgIcn/JenD7nbr1nF5ph7vLvQ6eN0MmlkhpUSuGytnu7RWbjg7xnYxUm2gGNuU8Ot1rW3qW1WvGkOHfsPJyQkH1rOcMzCcJ/8vy5Ibenf51ZeKAIBSGXPASA9KkJkDUkQiF2CMACjIFyIGoiOSnyEVIdXpWe8tZ3KI003c8s19PhFe "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ΔQƶʒZĀ}нZˆĀ*}¯¨
```
1-based. Results in `[[]]` if the ragged list doesn't contain the integer.
[Try it online.](https://tio.run/##MzBNTDJM/f//3JTAY9tOTYo60lB7YW/U6bYjDVq1h9YfWvH/f7ShTrSRjnGsTnS0iY5pLJCOjeUyBQA) (Or [here a scuffed attempt to create a test suite..](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWVCqNL/c1NcIgKPbTs1KepIQ@2FvVGn2440RGjVHlp/aMV/Jb2wQ1tc0uMzgbwdtTr/o6OjDXWijXSMY3Wio010TGOBNBArmAJxdDSQMAQzgHIGsSBxIAXmG4KVRUcbA0ljHTClYAyWMoXrjgYpAJsHFooFAA))
Uses the legacy version of 05AB1E, because there apparently is a bug with `Ā` (Python-style truthify) incorrectly resulting in `1` for (some) empty strings..
**Explanation:**
```
Δ # Loop until the result no longer changes:
Q # Check for each value in the ragged list if it's equal the to
# second (implicit) input-integer
# (will use the implicit first input-list in the first iteration)
ƶ # Multiply each inner value by its 1-based index
ʒ }н # Find the first inner list which is truthy for:
Z # Push the flattened maximum ("" if it lacks integers)
Ā # Check if this is truthy (thus not 0 nor "")
Z # Push the flattened maximum of the found list (without popping)
ˆ # Pop and add it the global array
Ā # Truthify the integers in the ragged list
* # Multiply it by the second (implicit) input-integer
}¯ # After the loop: push the global array
¨ # Remove the last value, since the `Δ`-loop will have looped an
# additional time before it stops; otherwise we could have printed
# the flattened maximum directly instead of using the global array
# (after which this list is output implicitly)
```
[Answer]
# [Perl 5](https://www.perl.org/), 83 bytes
```
sub{($_,$n,@_)=@_;/\[/?push@_,0:/]/?pop:/,/?$_[-1]++:/^$n$/?return\@_:0for/\d+|./g}
```
[Try it online!](https://tio.run/##fZFNT8JAEIbP9ldMyCKtLGwL1MM2tRy4mcjF23Zp0G4rEUrtR6JB/Os4W0CCErdJOzvzPvNOM7kqlu6OJP6urJ82Jokoyeg4svxx5LFQsCCvy5dxRG3OJF7WOWeUBSQSPUd2u5zNSEZYUKiqLrJwHHE7WRcsjLuffZZud55Rlwom82rO@aRe5arwAH0gXuUb7GHLYJ81sbHlf5UsLD89xtJCx7P@TYATCFbwOotVsjWwt2kIwCMkBQcuHP8OGvEpI@kBEWJkS4ngyP6NCJviI/8iDhVICDHE95A2HxjuEecy4qLCvTyYOMnPXbSD1E7n7H//8oNQ4fT77pHULgM6kmeItTF0tPowyVKvlyhcL4m8Q5ak/jVJTNwJ1i0UWPtKXiyyKmm1e7clwHJRVhzavYGLF8iaMNYq9Z6r50rFOuMMdDFda2UZZi1qXDVdlQXqDZowtSCAzvq1Axw6D9NHmN53jjI0BxwPDgw9EtTY7r4B "Perl 5 – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), ~~95~~ ~~78~~ ~~77~~ ~~75~~ ~~73~~ 72 bytes
```
l::Int\n=l==n&&[]
l\n=for(i,v)=pairs(l);0∈(p=[i;v\n])||return p;end==0
```
[Try it online!](https://tio.run/##PYo9CoMwFMd3T@EkCWRIiC7Kg649w8sbhFqaEqLEj3bwAJ6zF0kTaF3@n7/n6myv3jG6tr36xXhwAL6qkAqXyn0MzIqNw9TbMDPHO/k5DjYB2m4znvi@h2FZgy@nbvA3ABkv82N8lUhGFb@IWEsiMrU8FyWQSCDqpFpkM/p/NmSaE8wQZTiN8Qs "Julia 1.0 – Try It Online")
Returns `false` for not found, 1-based indices for found.
`l::Int\n = l==n && []` - base case, when first argument is an Integer: if it's equal to the second argument, return empty Array `[]`; if it's not, return `false` (== 0).
`0 ∈ (p=[i;v\n]) || return p` - 1-based index `i` can never be 0, so if `[i; v\n]` contains a 0, that means the recursive call failed, move on. If `v\n` isn't 0, we found the number, so prepend the current index and return that back to the caller.
`==0` at the end - This check happens at the end of the loop and always returns `false` (thanks to @MarcMush for -1 byte by using this). If `for` loop completed without returning, we didn't find the number anywhere. So return `false` to indicate failure.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
⊞υ⟦⟦⟧θ⟧FυFE⁺⟦⟧§ι¹⟦⁺§ι⁰⟦λ⟧κ⟧⊞υκI⌊Φυ⁼⊟ιη
```
[Try it online!](https://tio.run/##TUzLCsIwELz7FTnuQgRLjz2JKHgo5L7sIdRKQ9NXHuLfx6QiOIcZmFc3aNct2qakoh8gSkHEUmyMzeG5OAERxa6tXkHZ6KHE53CfH/0bjBQVYt7syZ97KqblzCMjit/3mF@VM3OAi/YBWjObKU5wMzb0rhSuW9TWg1pWMHk8YEGTEhFVkpglUZ25ll/hdHzZDw "Charcoal – Try It Online") Link is to verbose version of code. Outputs `None` if the desired element is not present in the ragged array. Explanation:
```
⊞υ⟦⟦⟧θ⟧Fυ
```
Start a breadth-first enumeration of all the elements and their ragged indices with the input list and an empty index.
```
FE⁺⟦⟧§ι¹⟦⁺§ι⁰⟦λ⟧κ⟧⊞υκ
```
If this element is a non-empty list then push all of its elements and their ragged indices to the search list.
```
I⌊Φυ⁼⊟ιη
```
Output the lexicographically earliest (if any) index of the desired element.
] |
[Question]
[
In this challenge, your past self comes back to help or hurt someone else!
The task is simple: write a **full program**, not a function, that prints the first code submission on this site submitted by the previous user, **in the language of *your* first answer**. (In the case that your first answer was purely prose, for example [pxeger's first answer to a "Tips for Golfing" thread](https://codegolf.stackexchange.com/questions/209734/tips-for-restricted-source-in-python/209920#209920), use the first code-based answer.)
[My first answer](https://codegolf.stackexchange.com/questions/133486/find-an-illegal-string/189644#189644) was
```
*/```
```
That's a newline followed by `*/````. Suppose that [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob) was the first to answer this question. His first answer was in JavaScript, so he might respond to this challenge
```
alert("\n*/```")
```
And the next answerer here would have to print [his first answer](https://codegolf.stackexchange.com/questions/11877/generate-a-pronounceable-word/11878#11878),
```
s='';c=5;r=Math.random;while(c--)s+='bcdfghjklmnpqrstvwxz'[r()*20|0]+'aeiouy'[r()*6|0]
```
Only accounts that submitted an answer before this question was posted are eligible to participate. **Each user may submit only one answer.**
This is code golf, so the shortest answer wins. The fun is that who can win depends on who answers!
[Answer]
# 5. [user](https://codegolf.stackexchange.com/a/207412), [Java (OpenJDK 8)](http://openjdk.java.net/), 75 bytes
```
interface T{static void main(String[]a){System.out.print("print(\"N\")");}}
```
[Try it online!](https://tio.run/##y0osS9TNL0jNy0rJ/v8/M68ktSgtMTlVIaS6uCSxJDNZoSw/M0UhNzEzTyO4pCgzLz06NlGzOriyuCQ1Vy@/tESvAChYoqEEoWKU/GKUNJU0rWtr//8HAA "Java (OpenJDK 8) – Try It Online")
My first language was Java, lol. [This](https://codegolf.stackexchange.com/a/55991/68942) is my first answer. It's 1055 bytes. Have fun.
```
interface T{static void main(String[]a){System.out.print("The basic idea of a [tag:kolmogorov-complexity] challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean Rings](_%s/53417/ascii-borromean-rings) to [The Gettysburg Address_%s/15395/how-random-is-the-gettysburg-address). \n##Your Task\nThis % is similar, except that it requires printing of a special text - the text of this %. Specifically, the very Markdown code that I am typing right now. \nTo prevent an infinite recursion in the %, the exact text you have to print can be found [here_revisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source). \n##Clarifications\n- You are not allowed to use any external sources like the internet. \n- This means that the purpose of this % is not to download this % text and parse it, but instead to store it in you program. \n- This is [tag:code-golf], so shortest code in **bytes** wins!".replaceAll("_","])http://codegolf.stackexchange.com/").replaceAll("%","question"));}}
```
[Answer]
# 10. [Neil](https://codegolf.stackexchange.com/users/17602/neil) - [GolfScript](https://esolangs.org/wiki/GolfScript) and [Funge-98](https://esolangs.org/wiki/Funge-98), ~~154~~ ~~153~~ ~~151~~ ~~147~~ 146 bytes
```
#.c5*01:$pd-1x
v "var isSorted = function(array) { return \""'"'" + array == array.sort(function(a, b) { return a - b; }); }"
#>:'\-#^_$
#^@#, _
```
[My first answer](https://codegolf.stackexchange.com/questions/116152/calculate-a-square-and-a-square-root/223970#223970) was:
```
#>&:*.@
~2-1??
```
[Answer]
# 1. [Purple P](https://codegolf.stackexchange.com/users/88456/purple-p), [√ å ı ¥ ® Ï Ø ¿](https://github.com/cairdcoinheringaahing/UnprintableName), 9 bytes
```
'
*/```'W
```
[Try it online!](https://tio.run/##zTxdcxvJcc@HX7GSc1ksuSQBXZ0fEOFsmeLZjCVKOerunEAIbwkMyDEXu6vdBQWerCqXn/KW11Re8uCyq1ypSlVekwdXKckf8R@5dM/37MwuQEr@YBVFoGe6p7unv@ZLxU19mWeffEeXRV7WwTKpL3vic5lk83wpv1U3lfpYlzS76PVmaVJVwVdJelPS/Kgs87J/tJ6RoqZ5Fo16vQB@5mQRnJ3RjNZnZ/2KpIt4WV2MT/KMxLPLpBwPoGMgfrB5H5qDcQD/2mDsDHD8oxroAvsFtAqQnqbDkFYFKfsmbzHSifYVMyGDBot8lc0DmgWzfE7CSBEhaXV7kofI5ZvB21HwZvg23F/kJSi0j0yj2FFk6qQkRSl0YuigJPWqzAJFKSjKfL6akblFUakkljqL5HQcZzUpCyBDym2nxBiea7@pGippJkhnP@zZKmkO2VSLyd5pncyuBCNhGAaHJUlqEiQBbyavVvSapiSrgzoHaEqrGvtB/4282wZT4UAgy2Rqw6@TdEUAjiZjt8xJSpfQ8smDnt1QnK4KEA/YGwcvylUDLSmK9AZaPk/AYuwm8KALclqTwt9cabK8daN1gMVneR0k2U1fCxnZZiotqB@FTasCx@3XqyIlJrZllBTmsNUosdHENBFhylrxoM2PViXXBPypiWbZxXVS0uQ8JcGizJdBfQkfaAlGwecRjBNBjDA3E6UoPTkNNzatAO3L4s3bS3eYDKaa/QtSt3D/fFVdMsZmTIy5lsLHpBClYnPrCWXMBoFiX/cWSvxhhS45WxII4nM9G7R6XtIl6a/blMrRgsUqm6FHo6/NLgn4C8QXiDiAWzU5XaOuJ4N4OPWam23eSIYiAvOA/oN43TBSRvBj6DMeBwO7qZWoADIPVPHjOCtWdXCYL5eQrTjTSg8U23jS4UrzTFKS8W58knAeGnLXNwXpc3RkFkJh2@yIiWlPIEAtvB@iWlhXV2xpb2G4//OcZk2K3uFsaZ9Ie47RWdHimvmV4e4wu1ddmlS@yEGbggx@P2to7kVyRYISOwXZaglE0iqG/Jldk5LFbQCek7IC5c4DHM/SaZ3XSQpCDhQkzfOrFcbIN@FxOBrG4Vfh6NM4/Bl8HsThE/gCfw7xG/x9jF/h71P2ffBWS6fJXI2umQlexdeo7W9p0eeN@1fkpupH8TIp@hAMYwFlqgR4FBnk2Dyor7N8WdiQ1Anqrvlz7TUMJtgdS2YndLob/iLsWaOyuVnQFKMtK5Sq/apIad2HnsBix3Dc21i4jfaGrsulrsm5UmiJs5pmK7uhSRHcoV@BFFHwUH7eHU4jd5w1hlFIP0anYE@jR17GrGTr9ylFG6g4DT1bHphBUP3a1riYWEfprMFWvKXwGa8Zl4XND7fuXRYo@rOo53E@1iXyM4suuMyvybEOXWCrBZTbPhdMoF4vmJchDks44NPLykqLQTKb5eUcSKBrIpibu@WUs8JKc/uzvLjpR56Kan@WkqQ0msiyqG/sOktwDMA5ndV9KUCvy2BnReTaK@sj0IXrurPPGMBET7I5kJmI/mAP02gL42mi0waWL3qWBCJdReZ9hiwtA6eFlbct6ajICxlT52RtrXwQ9QvCJjERWUCVO2ISYZJVGWZNnazt9BThQGwMjySMEVlLxDvcFNqqF2Eowmw4cYvk8UL3wwImEWvDmId9bHt0enh8LDOC5tspgkS9DoY0mO5AZPdkWU9J3x4LOe@uSVU0AzrZjPRpDMx6DEp5N3XbGs4gzAbcC3y9aW3N0SAieEZzqWHkoBupLdI8eR96Pl8oE1oRa0GvLfuEpsm8xbKT86qzCob2PF3V3sjTUan78hqO0ik1ODCYiORIwToX9rrj3tCDDUCjQkrmc8@yrE2GtYyr6JTRhxLP/r4brDdJp5cPjA9A0V9M2VJnOaPRZaO7bgSLOGvHM4bFKOYfWKxo/QPby10TDRX@qIVpuTDXCwaGUs08Uqq5wMpwdin2VXzLa1gdoT/F4Fnj0NgvsuKYDwURgHJf7zVYklQzCs5XNxnDRHzX1KyEQhRPcv0M9zrYnNDg4TgYPvh@i@WxWaA2t1AjNXnlcioZtfPE3bKf53l6yFcPnZ4FE92RFVgFh9OH5OLAMphb@D5i@3crQOQZLJ8z@HXszc5KSvFtFlGZmcOMzZWx@qu8k8xdymKr6PCdHcdyLNRVVrds2lh4spvjt7PVOTnhub2Dhwnd2fmkGe@Gsaa4O4zMEDtfFeSJDIea4rrTEbYMpwZba2PIRTKr85ImHfEP98b37X5CHyYdep5nUHFTx5JrXBF7k0ESn0PDMB7qQfVUQ2OrjIzm3oOGhJzceZzsnrdIfm4yDCtRWB1c/1FzmnTETZnt4GB8@1x2cODPKRdkQ07S1XKEsbAJM0nVtyHVRekySRdOjL9rgEfE2YQtn6KDgwejqc/5ZuboJE3zr/MynbfLI8NP@BPsHAes@73Q2iSqzm5hLre2CSuVTijG5XuNmqejMmdCDCJvBx7bWkxqGG1veeZ8jztNh1Yn@W2s594Ganxnt5UeW4Dun5n9jEQc9RpLQVqd5mVN5tswyDaAK91dTGDsgGKxPh5j5WUF9vQ2LvmwUxMpWdSnl3RRb1N4WnhZO4ZOGgZCftGOgAUPywuyFx8vNpODSes2lvCwS/xlsu7KVOuWgnlJO6SXjR60fP4XkR8@vkN6@NifHZar9C9CpJ07iLTjFynLa/8yzCgn0GDxmMkxLZPOatm1ROpe5oiVUfDhlkbATutioylGHHTTysuzW3ggSNzhgkWS0mxe5sutgpqdJiajkb2rUOSv/8y7Cjt3ssQWU2SzI4/N/eoxDtWVQSpgz9qsHA7aNTwcRHbnTzs6f9rsPBx0knZpdxJvdj/GTdhtjGOilTht0Hhxma86WWwO@kJsM28a0ra/Vyvq5CaEnfmzKL8bdJx15DPeBe9AzKm1fIz9Kydur21LPtvQ2fHxw@bJccVvWuxNhvKiROMWBhq1QW6Kp/lW4ZlhRb037PICPsZ7DjHcfMTAtDGI17uAEeOolq7YWcHRtaeWERtGkzWLBGs7YIu1hTx@f8CO36fbLDXMHQUk4jDzzN0WvT0vw/fnhVWeH3IXTeDiH@/yqsEAvbjsqEv5EDSrcK9roD1hb2hNb@4uGbLALYfbdkbsRs1strPTHx6s7aFW2bz1JlVHCrK@ZO35yOn7HtvemlkFjfdwsz6LOgZ1nbhtB3DQGISHqz11HCBjlnOi9oE3bhVu3efmtdnuoO9jLHa8VidvthlTpBFfrZJyuz08eostvOpVWW/YSlNd3FxQrc7/zNXQ3h2KoT1/LVStlh0JWTQ6W9UKvc4vLlLymCySVVo/W7XEFU8xJWHN24N2peWrx8P/@1W4Yc@ec/WFL2c7Vx/dNGnQKSkA020MEFUl7Y6CuUW3MMf18/x1yxAt1tMS0hq72pnLQ7DmY6uJlAcUbGsGSDUxBvImgLFMw6JOlmVQgtVJvarG8kYPugKDsJRp12vo2qfPjw6PHz05xdQbTsI4nMLvG/h9C799@I3g993v4Z8fhPH98H4cvnwJX47g9wR@b8Jpr3f47OnTRyePkcYbrsbvBfcfpel9dQQsjobPw5Hg2yz5Y974D7JRnt8I@N9LuGFGvEkM9VNy8zovYRAOCMcSgVZngsYvJAjWdAJ0T4JwJSxgf61YyOYA48BEA29Ev0cKpLjc14Oe5HUs1fAUglfwrCCloYWHsmtaC@TPJORCQv5G9RGyhiPVR0L2JAQioADtKsbmcwHakaDlSvL6sQLlstc/qpnJXwvQgQTJXX@pkL9Sg5zLuTvTrCwF6N2vFQxitwCuJQyrFkkvVbLmF6Jfqfrp2Q4LrWK2YSnAC8WnPG5R2ude3LTCd7/RXED6Nmwp/MIYl69ZxCA/U/phC0EBfWJCP5XQQ7uvBD@2O0vwCxOMCziplm@1/oysK7Bq5RR2TBTNmWw2ztxE06VsMsKcHPJKiS/LdIH0U7sBFxNKyfY1JkHph9p@M0HjuTaxQoBOlYhEKnqpbJNKxKcKlKwFaKbkg8pGwP7ndxKI5yYC@CPdcaUmc26pXHHzjRaSLQwk3X@RcHHUKOBEuYE4jpf9/03bKd8wFw2fK0OV536i4W@1ssQ@tWj43/80OWU7BKLlS9WgNpZEy0@UFtT5jWj5uZJPrTtEy0q2GKfrUprfaA2qI23TZb6n5lCXpwK3sptw719ZzbP6EnRs0Pk72RkzkyDwKhyxpCbt80IR5I8BRLcf69BYf2W4P7/vjXcWoBSCj8ZouYr@bMNQEHpmQHVof21MtO77tQFVfXkTVERWytL1mBQkNgyfleKy4VjZDvIuhqIWEK9ty@5/@Kd/1bFc3ASVE/fPFha7pi1D83@EoxMlSe9tTz24mZW0qFtfY@GrJ37Ju2KvsuQjIaOQAz@YW/e1GZywJ0LmO5rG1qxx35Mu2OsqcZEAdRmp3Qdv/TnGn@DZly@ef/kiYF9eZqFBsK7q0n41o4p99qwMqyvCr6bXpI9ju5dL@YuyMV7JdxcDYgCsXPFjKy6w5T2/lIgd55RSgdb7OXwcF57kQUZeQwwgFd7Iyl@Techfy9HmhWIUjW1OzIl39X6ZVEnNrl3jDMehfOET@m5FsE7yJg3HiPhG9aaVkMSccKxpmw2pjUAu/D1uPk2hyJrMVuKSDZMw3tGjuBpga2V8L9VvvOFp3RHAhxgnIZsk8fCvucnXCH4NY2YLGlEbdayiXmYvs7HzE27xCtBa9XYMJN96hS6magp7e/jzvMwvymQZHDHl4qOf44y/JoTP2KF3iLYkfkbBm7c9FnoqA8DLAgPw472v5MMmDvjRTU0CyKcXUCIzwNGa1lhO4GqFA9jMGzT2tvrpgSD260e0C20WsTKGmCuMXTWNTW2pkzkWD2LDMmNtk9YS94pk9FuiAyV/t7ojXGPkBDj/U1Tho2roxn4w0/HY8CMjzBH2NsF9e7KgGXtDY9w5g2jXuIVWJCX3OgOGF4hLfjefZoJuI4quWay33zqIkMo9pTUY/uGX/@WJhuclSa46H5EoAnu@SFze@IOo0PkElttTKMvm9AJXv6NW72fK3G08Id7q0QsLfOwVrZ96kcgDq4ZQXWy1ssNC7EcffeRLK4jk5wGnX14qxF7@KCgMyrAkHz6yZAc8d1x3vJ47iPtgBtHcTMwm/92/@1KpNFLnKZDG@@8uPPdtE3u15D7cseZki7vynbPB/NNUzy6yeds58Q/s0DdfGYkowNonxn2wOUld4N0m6n5436dvFVd4VhX/R4CjeA7/U6r@T6B1taPHerg3rdnBQpvmUGpoca9n84vZUCOFgb/IpDq@4FUFOYw3jOqE0PUspFv@Br6hAFFs8A5x8Cb8PC/DUQhroq8vaUr4R6g38MNbnWHNQo@vRDy5VRB9kucFVigqV6r0bCEqtM9Zcc2Gh78wNkt50Ie9jHIiA6yJFs0wg8nAzY/8TSfGSHZZ@5jCgg0WZv6MyZn35Mw88yQTa8DW1NSaPm/CVpL6DYRVWZY81stK2BCtwbLAAKX6TUPNzoRN/ZS9cZXkfZTYxGykxa1nMzWY3o200Pw2U@KaoC3kNs/BUWsF1PESjf1PHi3Pw/SZgJ/nVpbYtWA2u5@ZhwQthCdDfiHpdhKDzaiDAgxX8j@nmIARxGzyYlD7NPJbkyTRbXb4IweZYKepWJtOtDtP/UHe8PddvHThiXXm3OEeSq9jwS6i1V1H71yS2tF3GyVEvZ5fFNCoPAHq0DsKPGlJFDx2OiXXJmc3r8kFu6DP34adw087h/dHQe/4Ywc0sXYtOjVucvSmhSOZRrZRSSNmYZrlb4rMy5Zb6eftBm620pBkZ@wB3lFL/Ra@eJL16shEjzrRtxKKx/KxA7qjQO9@38KSqAqc@euk9oNuYm4qdjYVX4ajjWGInyabb9S6CzgdyJ0LElfkBoOGUqYH2dI19J96BRhtp3rRHYdFcVmt2Loil@@m2NNC@f8xgOdEUO22b/X5Hkp17A04Md4eadgx0jYSssq3lcJr5s5oFrdh8P04EmV51z7IgpbszpDeC23eZXSFEGgfTo5WPpprCOEOuJA4Ws9OGw93GZrYKZbN/ltZzdbm1UODkHwopf43CPUClT0glj0j88aYvb@tuvR6fMuYH9b0wzD8LuztHHzzzTfh19/BN16dxcFkGkXf/T8)
[This](https://codegolf.stackexchange.com/a/112720/66833) was my first answer:
```
Ißo
```
---
Ignore the `OUTPUT` and `Program execution information` banners. Those are automatically printed by the interpreter when any program in `√ å ı ¥ ® Ï Ø ¿` is executed.
It's been a while since I used `√ å ı ¥ ® Ï Ø ¿` (or remembered that it existed). This pushes the string
```
*/```
```
to the stack, then outputs it with `W`
[Answer]
# 6. [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino), [Brain-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), 19516 bytes
```
(((((<(((((((((((((<(((((((((((((((((<(((((((((((((((((((((((((((((((((<((<((((((((((((<((((((<(((((((<((<((((<((((((((<(((((((((((((((((((<((<(((((((((<(((((((<(((<((<((<(((((<((<(((((((<((((<((<(((((<(((<((((((<((((<((((((((<((<(((<((((<((((<((<(((((((<(((<((((<(((((<(((((((((<((((((((<(((<((((<(((((((<((((((((<(((<(((<((<(((((((<(((<(((<((((((((((((((((((((((<((((<((((((<((((((<(((((((((((((((((<((((((((((((((((((((((((((((((((<(((((<((<(((<(((((<((<((((<(((<((((<(((((<((((((<(((<((<(((((((((<((((((((<((<(((((((<(((((<(((<(((((<((((((<((<(<((((<((((<((((((((<((((<((((<(((((((((((((((<((((<((<((((<(((((<((((<(((((((<(<((<((((((((<((((((((<((<((((<(((((((<(((((((<((((<((((((((((<(((((<((((<((((((((((((((((((((((<(((((((((<(((((((((((<((((((((<((((((((((<((((<(((<(((((((((((((((((((((((((((((<(<((((((<((((((((((<(((((<((((<((<((((<(((<((((<((((<(((<(((((((<(((<(((((((<((((<(((((((<((((<((((((((<(((<((<((((((<(((<(<(((((<((<((<(((((((((<(((<(<((((<<(((((((((((((((<(<((<(((((((((((((((<((((<<(((<(((((((<((((((((((((((<(((((((((((((<(((((((((()(((()((()()()){}){}){}){}){})()()()()[])(()[]){})[()(()([]){}){}])()(()()[]){})[(()[]){}])[()()()()()])()())()())>(()()(()[])({}){})((()()()[]){}){})(()()[])({}){})[(()()()()){}])())[()()()()()[]])()()()()[])[()(()()()()()){}])[(()()()){}])[()(()()()()[])({}){}])(()(()()[]){}){})[()(()()()){}])[(()()()){}])[()()()()()])>(()()()()()()()()()[])()()(()[])({}){})[((()()()){}){}])(()()()()){})()()()()())[(()()()()()()()[]){}])()(()((()()()()()){}){}){})()()()[])[()()])[()(()()()()){}])()()()()())[()(()()()){}])[((()()()){}){}])()())()()()())>(()()()[])(()()[]){})[[]])(()(()(()()()()){}){}){})[(()()()){}])())[()(()(()()()){}){}])(()()()()){})>([])()((((()()()()){}){}){}){})(()()()){})[()])>((()(()(()()()()()){}){}){})>((()()()()()[]){})()())[()(()()()()){}])()()()()())(()()()){})>((((()()()()()){}){}){})[(()()()){}])(()(((()()()){}){}){}){})((()()()()()){}){})[()()()])[()()()()()()()()[]])()()()()[])[()])(()(()()()()){}){})[(()()()()()){}])[(()()()){}])[[]])()()()()()[])[()()()()()])())[()()()()])>((((()()()()){}){}){})()()()()()()[])[()(()()()()){}])>((((()()()()){}){}){})()((((()()()()){}){}){}){})>((((()()()()){}){}){})()(()((()(()()()){}){}){}){})()(((()()()){}){}){})[()(()(()()()()){}){}])(()()()){})[()((()(()()()()()){}){}){}])()((((()()()){}){}){}){})()()()())[()()()])())()())[(()()()()){}])(()()()()){})()()())[()()()])()(()()()){})>(()((()(()()()()()){}){}){})>(()()()()()[])((()()()){}){})[()()])()()())[()()()()])>(()()[])()(()(()()()()){}){})>(()()()()[])()(()()()()()){})()()()()())[((()(()()()){}){}){}])>((((()()()()){}){}){})()(()(((()()()()){}){}){}){})()()()()())[()(()()()){}])()(()()()()()){}))[()(()()()){}])()(()()()()){})[()(()()()){}])[()()])>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})(()()()()()){})>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[()()()()()])>((((()()()()){}){}){})((((()()()()()){}){}){}){})()())[()(()()()()){}])()()()()())(()()()){})>((((()()()()){}){}){})()((((()()()()){}){}){}){})>((((()()()()){}){}){})()(()(((()()()()()){}){}){}){})[(()(()()()){}){}])()(()(()()()){}){})>((((()()()()){}){}){})()((()((()()()){}){})({}){}){})(()()()){})[()])[()()()()])()()()()())[()])>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()()()()())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()()()])>((((()()()()){}){}){})()(()(((()()()()()){}){}){}){})[()(()()()()()){}])()(()()()){})()()())()())[()(()(()()()){}){}])(()(()()()){}){})())>((((()()()()){}){}){})()(()(((()()()()){}){}){}){})((()()()){}){})[()(()()()()()){}])())>((((()()()()){}){}){})(()()()()){})((()(()(()()()()){}){}){}){})[((()()()){}){}])()(()()()){})(()()()){})[(()(()()()){}){}])())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()(()()()){}])()(()(()()()()){}){})>((((()()()()){}){}){})()((()(()(()()()()){}){}){}){})[(()()()()){}])[()()()()])()((()()()){}){})[()()()()()])()()()()())[()(()()()){}])>((((()()()()){}){}){})(((()(()()()()){}){}){}){})[()(()()()){}])(()(()()()()){}){})>((((()()()()){}){}){})()(()(((()()()()){}){}){}){})()()()()())[()(()()()){}])()((()()()){}){})[()(()()()){}])[()()])[()])>((((()()()()){}){}){})((()((()()()){}){})({}){}){})())(()()()()){})>(()(((()()()()()){}){}){})()()()()())[(()(()()()){}){}])()(()(()((()()()){}){}){}){})(()(()()()){}){})>((((()()()()){}){}){})(((()(()()()()){}){}){}){})[()(()()()){}])()((()()()()()){}){})[()((()()()()){}){}])>((((()()()()){}){}){})(((()(()()()()){}){}){}){})[()(()()()){}])()()())>((((()()()()){}){}){})()((()(()(()()()()){}){}){}){})[((()()()){}){}])()((()()()){}){})()(()()()()()){})>((((()()()()){}){}){})()((()((()()()){}){})({}){}){})[()(()()()()){}])>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()()()])(()()()()){})>(((()(()()()()()){}){}){})[((()()()){}){}])(()(()((()()()()){}){}){}){})((()()()){}){})[()()()])[()()])>((((()()()()){}){}){})()(()((()(()()()){}){}){}){})[()(((()()()){}){}){}])()((()(()()()()()){}){}){})()()()))[()()()])[()()])[(()()()()){}])[()()()()])()((()()()){}){})>((((()()()()){}){}){})(()(((()()()){}){}){}){})()(()(()()()()()){}){})()()()()())[()(()()()){}])((()()()){}){})[(()(()()()()()){}){}])>((((()()()()()){}){}){})()(()(()((()()()){}){}){}){})>(()((()(()()()()){}){}){})((()((()()()){}){})({}){}){})[((()((()()()()){}){}){}){}])(()()()){})[()()])())[()()()])(()()()){})[(()()()()){}])(()(((()()()){}){}){}){})(()(()()()()){}){})[((()()()()){}){}])(()()()){}))[((()(()(()()()){}){}){}){}])()((()((()()()){}){}){}){})()((()()()){}){})()()()))[()()()])[()()])[(()()()()){}])[()()()()])()((()()()){}){})[()((((()()()()){}){}){}){}])()((()((()()()()){}){}){}){})[()(()()()()){}])()()()()())[()(()()()){}])((()()()){}){})>(()(((()()()()()){}){}){})[()(()()()()){}])((()((()()()()()){}){}){}){})[()()()()()])>((((()()()()){}){}){})()(()((()(()()()){}){}){}){})[()(()()()){}])((()()()()()){}){})[()()()])>((((()()()()){}){}){})(()((()()()){}){})({}){})(()(()(()()()){}){}){})()(()(()()()){}){}))()()()()())[(()()()){}])[()((()()()()){}){}])()(()(()()()()){}){})[()()()])[()(()()()()()){}])>((((()()()()){}){}){})()(((()()()()){}){}){})()(()((()()()()){}){}){}))(()(()()()){}){})[()((()()()){}){}])(()(()()()){}){}))[((()()()()()){}){}])>(()((()(()()()()){}){}){})((()((()()()){}){})({}){}){})[((()((()()()()){}){}){}){}])()())()()()())[()()])(()()()){})[()()()()])[(()()()){}])()(((()(()()()){}){}){}){})()(()()()){})(()()()()){})>(()((()(()()()()()){}){}){})()((()((()()()()){}){}){}){})[()((()()()()){}){}])()((()()()){}){})[(()()()()()){}])()(()()()()()){})[()()])[((((()()()()){}){}){}){}])((()(()(()()()){}){}){}){})(()()()()()){})>(()((()(()()()()()){}){}){})()(()(()((()()()()){}){}){}){})[((()()()){}){}])[()()()])[(((()(()()()){}){}){}){}])(()((()(()()()){}){}){}){})[()()])()(()(()()()){}){}))()()()()())[(()()()){}])[()((()()()()){}){}])()(()(()()()()){}){})[()()()])[()(()()()()()){}])[(()((()(()()()){}){}){}){}])((()((()()()){}){}){}){})()()()))(()(()()()){}){})[()((()()()){}){}])(()(()()()){}){}))>(()(((()()()()()){}){}){})()()()()())[(()(()()()){}){}])((()(()(()()()){}){}){}){})(()(()()()()){}){})>(()(()((()()()()){}){}){}))(()(()((()()()){}){}){}){})(()(()()()()()){}){})(()()()){})[()()()])>((((()()()()){}){}){})((()((()()()){}){}){}){})()((()()()){}){})(()(()()()()){}){})[(()()()()){}])[()(()(()()()){}){}])(()(()()()()){}){})[(()((()()()){}){}){}])((()()()()()){}){})())(()()()()()){})>((((()()()()){}){}){})()()()()())[()()()()()])()(((()(()()()()){}){}){}){})(()()()()()){})>((((()()()()){}){}){})()(()(((()()()()()){}){}){}){})[(()()()()()){}])()()()())[()()()()])()()())[()(()()()()()){}])()((()()()()){}){})>(((()(()()()()()){}){}){})[((()()()){}){}])()((()((()()()()){}){}){}){})()(()(()()()()){}){})[()((()()()()()){}){}])()())()(()()()()()){})()()()())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()(()()()){}])()(()(()()()()){}){})>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()(()()()()()){})>((((()()()()){}){}){})(()(((()()()()()){}){}){}){})[()((()()()){}){}])((()()()){}){})()()()())[((()()()){}){}])()(()()()()){})[()((()()()){}){}])(()(()()()){}){})>((((()()()()){}){}){})((((()()()()()){}){}){}){})()())[()(()()()()){}])()()()()())(()()()){})[()(()()()()()){}])()()()()())[()(()()()){}])>((((()()()()){}){}){})()((()((()()()){}){})({}){}){})[()(()()()()){}])>((((()()()()){}){}){})()((((()()()()){}){}){}){})>((((()()()()){}){}){})()(()(((()()()()()){}){}){}){})[()()()])[()(()()()()()){}])[()()])(()()()){})[(()()()()){}])()(()()()()()){})>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[()(()(()()()){}){}])()(()(()()()()){}){})[()()()()])>((((()()()()){}){}){})()((()()()){}){})[()((()()()){}){}])((()((()()()()()){}){}){}){})[((()()()){}){}])[()()()])>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[()(()(()()()){}){}])()(()(()()()()){}){})[()()()()])>((((()()()()){}){}){})()((()((()()()){}){})({}){}){})[()(()()()()){}])>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])())(()()()()()){})>((((()()()()){}){}){})()()()()())()(()()()()){})[(()(()()()){}){}])()(()(((()()()){}){}){}){})()((()(()()()){}){}){})[()(()()()()()){}])[()()])(()()()){})[()()()])()()())[(()()()){}])[()()])()(()()()()()){}))()((()()()){}){})>(((()(()()()()()){}){}){})[((()()()){}){}])((()((()()()()()){}){}){}){})[((()()()){}){}])[()()()])>((((()()()()){}){}){})(()(()((()()()()()){}){}){}){})[()((()()()()){}){}])()((()()()){}){})()(()()()){})>((((()()()()){}){}){})()((()(()()()()()){}){}){})((()()()()()){}){})()((()()()()){}){})[()(()()()){}])[()(()()()){}])()(()()()()()){})(()()()()){})[()(()()()()){}])>((((()()()()){}){}){})()(()(((()()()()){}){}){}){})((()()()){}){})[()(()()()()()){}])())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()(()()()){}])()(()(()()()()){}){})>((((()()()()){}){}){})()(((()()()()()){}){}){})>((((()()()()){}){}){})()((((()()()()){}){}){}){})((()()()){}){})>((((()()()()){}){}){})((()((()()()()()){}){}){}){})()()()()())[()(()()()()){}])[()(()()()){}])()()()()())[()(()()()){}])>((((()()()()){}){}){})(()(((()()()()()){}){}){}){})[()(()()()()){}])[()()])())((()()()){}){})>((((()()()()){}){}){})((()((()()()){}){})({}){}){})())(()()()()){})>((()(()(()()()()()){}){}){})[(()(()()()){}){}])((()(()(()()()){}){}){}){})(()(()()()()){}){})[(()((()()()){}){}){}])()(()((()()()){}){}){})>((((()()()()){}){}){})((((()()()()()){}){}){}){})()())[()((()()()){}){}])()((()()()()){}){})[()((()()()()){}){}])()(()()()()){})(()()()){})>((((()()()()){}){}){})()((((()()()()){}){}){}){})()((()()()){}){})>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()()()()())[(()()()()){}])()()())()()()()())[()()()()()])()(()()()()()){})[()(()(()()()){}){}])>((((()()()()){}){}){})(()(((()()()()()){}){}){}){})[()((()()()){}){}])[()()])(()(()()()()){}){})[()()()])())[(()()()()()){}])(()()()){})[()])>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()()()()())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()()()])>((((()()()()){}){}){})()()()()())()(()()()){})[((()()()){}){}])((()((()()()()()){}){}){}){})[((()()()){}){}])[()()()])>((((()()()()){}){}){})()((()((()()()()){}){}){}){})()(()(()()()()){}){})[()(()(()()()()()){}){}])()())()((()()()()){}){})>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[()(()(()()()){}){}])()(()(()()()()){}){})[()()()()])>((((()()()()){}){}){})()(((()(()()()()()){}){}){}){})[(()()()()()){}])(()()()){})>((((()()()()){}){}){})(((()(()()()()){}){}){}){})[()(()()()){}])()((()()()()()){}){})[()((()()()()){}){}])>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[()()()()()])>((((()()()()){}){}){})((((()()()()()){}){}){}){})()())[()(()()()()){}])()()()()())(()()()){})>((((()()()()){}){}){})()(()(((()()()()){}){}){}){})[()()])()((()()()){}){})>((((()()()()){}){}){})(()(((()()()()){}){}){}){})()()())>((((()()()()){}){}){})(()(()((()()()()){}){}){}){})()(()()()()){})(()()()){})[()(()()()){}])[(()()()()()){}])>((((()()()()){}){}){})()(()((()(()()()){}){}){}){})()((()()()){}){})[()()()])()((()()()){}){})[()((()()()){}){}])[(()()()){}])()(()(()()()()){}){})[()((()()()){}){}])()((()()()()){}){})[()((()()()){}){}])(()()()()()){})[(()()()()()){}])(()()()){})[()])()()()()())[((()((()()()()){}){}){}){}])()())()((()((()()()){}){}){}){})[()(()(()(()()()()()){}){}){}])[()()()()])[()()])((()((()()()){}){}){}){})[()()()()])[(()(()(()()()()()){}){}){}])[(()()()){}])()()())()(()()()()){})[()()()()])[()()()()()])[()()()])()(()()()){})(()(()(()()()()()){}){}){})>(((((()()()){}){}){}){})()()())[(()()()){}])((()((()()()){}){}){}){})()()()())[((()(()()()()()){}){}){}])[()()()()])[(()()()()){}])()()()()())()())(()(((()()()){}){}){}){})[()()()()()])[()(((()()()()()){}){}){}])[()(()()()){}])())()(()(()(()()()()()){}){}){})[(((()()()()()){}){}){}])(((()()()()()){}){}){})>((()(((()()()){}){}){}){})(()()()){})[()(()()()()){}])()(()(()((()()()()){}){}){}){})[()((()()()){}){}])[()()()()])(()(()()()()){}){})>(()((()(()()()()()){}){}){})(()(()((()()()()){}){}){}){})[()()()()])(()()()){})[()()()])[()(()(()()()){}){}])()())>(()(((()()()()()){}){}){})()()()()())[(()(()()()){}){}])((()(()(()()()){}){}){}){})(()(()()()()){}){})>(()(()((()()()()){}){}){}))(((()()()()){}){}){})()(((()()()()()){}){}){})[()(()()()()()){}])()((()()()()){}){})[()(()()()()){}])[()()()])()()())[(()()()){}])[()()])()(()(()()()()){}){})[()(()()()()()){}])(()()()){})[()])()()()()())[()(()(()()()()()){}){}])(()(()()()()){}){})[()((((()()()()){}){}){}){}])[()((()()()){}){}])()(((()(()()()){}){}){}){})(()(()()()()()){}){})(()()()){})>((((()()()()){}){}){})()((((()()()()){}){}){}){})()((()()()()){}){})[()((()()()){}){}])>((((()()()()){}){}){})((()((()()()){}){})({}){}){})())()()()()())>((((()()()()){}){}){})()((((()()()()){}){}){}){})()(()()()()()){}))()()())(()()()()){})[(()(()()()()){}){}])[()])>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[()()()()()])>((((()()()()){}){}){})()((()((()()()()()){}){}){}){})[()()])[(()(()()()){}){}])>((((()()()()){}){}){})()((((()()()()){}){}){}){})()((()()()){}){})()(()()()()()){})>((((()()()()){}){}){})()((()((()()()()){}){}){}){})()(()(()()()()){}){})[()()()()])[()(()(()()()){}){}])()((()()()){}){})[()()()()])[()((()()()){}){}])()(()()()()()){})>((((()()()()){}){}){})()(()(((()()()()()){}){}){}){})[()()()()])(()()()){})[()()()])[()(()(()()()){}){}])()())(()(()()()){}){})>((((()()()()){}){}){})((()(()(()()()()){}){}){}){})[()()()])()())[(()()()){}])>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()()()])>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()()()()())(()()()){})[()(()(()()()){}){}])()((()()()){}){})[()()()()])[()(()()()()){}])()(()(()()()){}){})>((()(()(()()()()()){}){}){})[(()(()()()){}){}])((()(()(()()()){}){}){}){})(()(()()()()){}){})[()((((()()()()){}){}){}){}])[()((()()()){}){}])((()((()()()){}){}){}){})((()()()()()){}){})())(()()()()()){})>((((()()()()){}){}){})()((()(()(()()()()){}){}){}){})[(()()()()){}])[()()()()])()((()()()){}){})()()()()())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()(()()()){}])()(()(()()()()){}){})>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])[()()()])>((((()()()()){}){}){})((((()()()()()){}){}){}){})()()()()())[()()()])[()()])[()])()()()())[(()(()()()){}){}])>((((()()()()){}){}){})()((()((()()()){}){})({}){}){})[()(()()()()){}])>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])())(()()()()()){})>((((()()()()){}){}){})()()()()())[()()()()()])()(((()(()()()()){}){}){}){})(()()()()()){})>((((()()()()){}){}){})((()((()()()){}){})({}){}){})())()()()()())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[()()()()()])>((((()()()()){}){}){})((()((()()()()){}){}){}){})()(()()()()()){})(()()()()){})[()(()()()()){}])[()()])()()())[(()(()()()){}){}])()()())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[((()()()){}){}])())(()()()()()){})>((((()()()()){}){}){})()()()()())[()()()()()])((()((()()()()()){}){}){}){})[()(()(()()()){}){}])()(()(()()()()){}){})[()()()()])>((((()()()()){}){}){})()((((()()()()){}){}){}){})()((()()()){}){})[(()()()()()){}])>((((()()()()){}){}){})((((()()()()()){}){}){}){})[()(()(()()()){}){}])()((()()()()){}){})())[(()(()()()){}){}])>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()(()()()()()){})>(((()(()()()()()){}){}){})[((()()()){}){}])(()(((()()()()){}){}){}){})()(()(()()()()){}){})[()])>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()()()()())()()()()())())[()(()(()()()){}){}])[()()()()])()()())>((((()()()()){}){}){})((()((()()()()()){}){}){}){})[()()()()()])>((((()()()()){}){}){})()(()(((()()()()()){}){}){}){})())[()()()()()])()()())[()((()()()){}){}])>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()(()()()()()){})>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()()()()())>((((()()()()){}){}){})()(((()(()()()()()){}){}){}){})[(()()()()()){}])(()()()){})>((((()()()()){}){}){})((((()()()()()){}){}){}){})()())[()()()])[(()()()()){}])()(()()()()()){})[()((()()()()){}){}])((()()()){}){})>((()(()(()()()()()){}){}){})[(()(()()()){}){}])((()(()(()()()){}){}){}){})(()(()()()()){}){})[()((((()()()()){}){}){}){}])[()((()()()){}){}])((()((()()()){}){}){}){})((()()()()()){}){})())(()()()()()){})>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})(()()()()()){})>((((()()()()){}){}){})()(()((()(()()()){}){}){}){})()(((()()()){}){}){})[()(()(()()()()){}){}])(()()()){})[()((()(()()()()()){}){}){}])()(((()()()()()){}){}){})((()()()){}){})[()(()()()()()){}])())[(((()(()()()){}){}){}){}])(()((()(()()()){}){}){}){})(()()()()){})[()()()])[(()()()){}])[()(()()()()){}])[()((((()()()){}){}){}){}])[((()()()){}){}])()(()(((()()()()()){}){}){}){})[()()()()])>((((()()()()){}){}){})()(()(((()()()()()){}){}){}){})[()(()()()()()){}])()(()()()){})()()())()())[()(()(()()()){}){}])(()(()()()){}){})())>((((()()()()){}){}){})()(()(((()()()()){}){}){}){})((()()()){}){})[()(()()()()()){}])())>((((()()()()){}){}){})()(((()(()()()()){}){}){}){})()()()()())>((((()()()()){}){}){})(()()()()()){}))(((()(()()()){}){}){}){})()(()(()()()()()){}){})[()()()()()])[()(()(()()()){}){}])(()(()()()){}){})>((()((()()()()()){}){}){}))[(()()()()()){}])(()((()(()()()){}){}){})({}){})[(()(()()()){}){}])()()()()())()()()()())>(()(((()()()()){}){}){})())((()()()){}){})((()((()()()()){}){}){}){})[()((()()()){}){}])()(()()()()()){})[()()()()])[()(()()()()()){}])()())()())[((()(()()()()){}){}){}])()(()((()()()()()){}){}){}))>((((()()()()()){}){}){})[(()()()){}])()((()(()(()()()){}){}){}){})>((()((()()()()){}){}){})(()()()()()){})[(()()()()()){}])()(()((()(()()()){}){}){}){})[((()((()()()){}){}){}){}])(()((()()()()()){}){})({}){})((()()()){}){}))[()()()()])[(()(()((()()()){}){}){}){}])[()(()()()()()){}]))((()((()()()){}){}){}){})((()()()){}){})[()(()()()()()){}])())()())(()()()()){})[()()()])[(()()()){}])[(((()(()()()){}){}){}){}])()((()((()()()()){}){}){}){})())[()(()(()()()()){}){}])()())(()()()()){})[(()()()){}])()(()(()()()()){}){})[()((()()()()()){}){}])()()()()())[()(()()()){}])()((()()()){}){})[()(()()()){}])[()()])>((()(()(()()()()()){}){}){})()((()((()()()){}){}){}){})((()()()){}){})[()()])[(()(()(()(()()()){}){}){}){}])[()((()()()){}){}])()(()()()){})()()()()())((()((()()()()){}){}){}){})[()((()()()){}){}])()(()()()()()){})[()()()()])[()(()()()()()){}])()())()())[((()(()()()()){}){}){}])()(()((()()()()()){}){}){}))>((((()()()()()){}){}){})[(()()()){}])()()())[()()()])(()()()()()){})[(()()()()()){}])()((()((()()()){}){})({}){}){})()()()())[((()()()()){}){}])(()(()()()){}){})())[()(()()()()()){}])(()()()){})[()])>((()((()()()()){}){}){})()(()()()){}))(()(()()()()){}){})(()(((()()()()){}){}){}){})){({}<>)<>}<>
```
[Try it online!](https://tio.run/##5VzLjiM3DPwd6pA/EAzkOwQdNrkkCJBDroP99smM3Q9RrKKo7rYzm91ZGGO7Ww8@imSJPb/98@3Pv//49vtf7@/y@S9L@0@/w5@AKzK4I3dfZ29ENUZz5/JF7i/K6n3uZs3dsNne0n8Bpu@vAN@A4TIVUi@ZA7LOZldKvHY7mcnWCFMPuV2RoVD7j5BWstVHVmsxS8lA/@0cWejMRoAZfZqBPvJA4Bnfavea4bCZ7Scjg1Jaa/WrN7aqJaPVYqVkZMbiI0BaX9LnT3r7rv7L8lPqxyWfrx@flc/LkzzevH2v6fF@@3b5rd4vXH7qY/T7y@0x12PQZRrZplk/SO33RdaBlgnbsUut7TqX5bXXF1Fv9u@3Ge7bE7WE/To8xrazWzNdO3C/yaKFXFO7qebeZreNVFYx670pNS2bT3qP67376P2@ulWtimqVtRjApuS7zGUTml6NEtU@o7P5mzwEJgKGW83h8VlZRK4nb6@/tTJ6rLfbuBWKtGsRLGS9rdVx7FLNvWW1lGLNpDfdimRafINuR9mtYHe8/X3Vu7N@DnzoPge/janMuSNJbw5qOCN2IJLamYQQY9BWBaFtV88KUD3aWDdt79GmQ1eiYOLuTdZGajf8ji5lc3897k004uiJNaZYmdeRlrAzUiwxC3AugBA7MFHBeLMDBPThzjehcnYv9dcg9PbDEHOFN9EtWdg1UOyupjdToZBcdKjfDeSgQlUIOqDMbt9lDIC@JE1SocQoTX5Dw52WZDrmfBY2zLq4xFpsoOEbpipqs63qgYVdpzEjbgt/nuny3SWUzNUkEJaxXUsgPIqzhmTSifDeDkIzsZwWe4sPfg4cpD6jo@7UZ7oEoITAfEhIccGzhM0kHFdMNfD6WY/sACUYBH1FhlO/Y/ArZoWJJdsQQMOouCfc9VAuWlAyWpOT4C3vzewTcOMAN8th0WIcGBBbWPS3V14Cuc5pst8gdBShijVpvqpnqolEofoMlVdOdbGnznB9idInyEPPGkjhOWK/FieDGVAC1igTLYn7QU9n2EOftOtEnu96ErBDomLwKWJq9oTFGBI2uGR5mkil7Yir@8Kuu/RbB0lp6woKDp7g2IpmKsCf0y6lPmBz@qBPUgOF@dhtkFJ9gsZMtbs6RzqGMiCw@7tJ3n5YZC5MrnXkkqn@B35S@KKqi8l3CD7mHceTWl@3iNTx3Xo00u6NxqNm8nsWyDyKsi3emEC7BMRmWSiniee3hkbbYulJ/ihAt6AQa8kRRiigGjCaIHswRt0LwP2KzJhL/BrFvUMbBZnAEdkDHNgm2A5RoqlpD1aeyzViQ5vkMS4qGa/nN734MKoQriKNXY7VMkkjKQ9i0qWk54u39lrO4UjEMO7LJODESa9Icoyzjw/gcnO8ggmEMKNyrS2loTUN82iJnpKQ3BdSITDsoX4ADAvkxGoMdU/i8F8cZuHx@hy4R0kuZ2cwZFEFzrL0wYMf7YsHthVhzXlfw@m6giXbuKI4k5YwN/cZdulPqE4cmIap1eAhZEG5lltrJIAbwROFudy0CSasfu6aigCz@sOc0ppI/YrYdqy0Sl5xFUThl2ZoBHhgaRvJm194BvfV@zpoMlCOHwVhbiuYn7GyGZBGoPEsmv@kEJ9UBucdnbOOMprpEGR6EvuCkUCm7a/yuW5GsO2ODFvYFBW@YL0zUsua8yFhMDOMtelbrKT1bdCP6ZGxRcgBEmvXiwmK@uvqtL4AN1qBT6UTdk@HK7meENPJe1hFhr2wiNOIHGYAkVEmmlZbg6kSr3JZ6PoiHPtMPRRjcnEdESr4nZEiuMQSEYabBMMYqI4ljs4iziT0HoIfLcLGeay/MkPLmNKuoCbmcoacS5NZK048Srwumai2jjUjRTPrAYiIewOtOc8d/RyEu4nTgOTm0/tDNkWuZlLLZPHAakQZFMRD3SWS@umo@TT6ZBIe@UHtqdPNi1pbn1G7H@Uarz7VCNKIugkrVTe/@NGPNi4/DD8fUy8o21M0KPs0frG5mAXrqzzlvPZeywrFQn6YGpD5pVu0nE1bpvoFZlqS51KX8yG0/RULzDabPDPDTB7aoucnZtL2S1o9ThLYTyFGR2Qj4TDAoYKt637KlOiaxq4XP5XqHGG7Z8PHWjURu@c8G9/oULB63c4Ir0T6mZ/BO3uc1jENfi8064/3qlJSVCGlYPSDffTeA6kgtt2ENrzbZtQZvhM3ZtMustaioNrcP8sQ/VsCHure2P6GhxV@2zZB4kp2I9D04XkDjQV6feNg4PoXYtgwpEns2R2cvCCMx9xe9EiKGP@x5zXd8C5TItZHRhMUMPpzA/8Lp0SPmrnu5hbEfcewH5cCLD9HBvX4GpCQE9vS28ea8y3l28fr@/v7L7/@Cw "Brain-Flak (BrainHack) – Try It Online")
This is a bit of a placeholder, since golfing brain-flak is a lot of work and I'd rather not lose all my progress since someone else posted an answer. The current code was generated by [this hyper-neutrino answer](https://codegolf.stackexchange.com/a/157665/56656).
[My first answer](https://codegolf.stackexchange.com/a/86570/56656) was:
```
(<({}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}<>(({}<{}>)){{}{}(<(())>)}{}
```
Should present a interesting challenge.
[Answer]
# 7. [Wheat Wizard‚ô¶](https://codegolf.stackexchange.com/users/56656/wheat-wizard), MATLAB/Octave, 94 bytes
```
disp('(<({}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}<>(({}<{}>)){{}{}(<(())>)}{}')
```
[Try it online!](https://tio.run/##LYsxCoBADASfc5s/hHzksBC1sFJQbELeHjenTZhhJ8dyz8@Wue7XiQaFh5qYqDmxQyYiiJDOSxWnVFfKMuojvkg9bAQjwT83yXwB "Octave – Try It Online")
Meh, a no-brainer. Didn't find any smarty way to golf it.
[My first answer](https://codegolf.stackexchange.com/questions/211460/plot-a-centered-circle/211558#211558) was:
```
ezpolar(@(x)r);s=r+5;axis([-s,s,-s,s])
```
(it was later edited but if I understand correctly we're supposed to do the *original* first answers)
---
Alternative solution, trying to golf, but is longer (**110 bytes**)
```
e='$&\IIEPW0+,H&X*&Y9.W$&XW)I^\OE WF])V^X@!-/W'-32;c='()[]<>{}';disp(c(reshape([floor(e/8);mod(e,8)],1,[])+1))
```
[Try it online!](https://tio.run/##y08uSSxL/f8/1VZdRS3G09M1INxAW8dDLUJLLdJSL1xFLSJc0zMuxt9VIdwtVjMsLsJBUVc/XF3X2Mg62VZdQzM61sauulbdOiWzuEAjWaMotTgjsSBVIzotJz@/SCNV30LTOjc/RSNVx0IzVsdQJzpWU9tQU/P/fwA "Octave – Try It Online")
Each character in`$&\IIEPW0+,H&X*&Y9.W$&XW)I^\OE WF])V^X@!-/W` represents two characters to display (more exactly their indices in `()[]<>{}`). Needed to add 32 to chars (and subtract them in the decoding process) to avoid using non-printable characters that render the code unrunnable.
[Answer]
# 12. [tail spark rabbit ear](https://codegolf.stackexchange.com/users/100411/tail-spark-rabbit-ear), [Vyxal](https://github.com/Lyxal/Vyxal), 6 bytes
```
kH‚Äõ.p+
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=kH%E2%80%9B.p%2B&inputs=&header=&footer=)
**Explanation**
```
kH # Hello, World! pre-defined constant
‚Äõ # Two byte string literal
.p # Capture next two bytes: .p and push to stack
+ # Concatenate top two items on stack
(implicit output of top of stack)
```
Prints `Hello, World.p`, couldn't waste the big chance and I am winner until now!!!
My first answer, `1.."$args"-match"2$"`
[Answer]
# 9. [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) - JavaScript, 136 bytes
```
function(){return'x=function(){rev(rawToBits(rev(charToRaw(sprintf("x=%s;x()",gsub("\\\\s","",paste(deparse(x),collapse="")))))))};x()'}
```
My [first answer](https://codegolf.stackexchange.com/a/22365/17602) was [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'"):
```
var isSorted = function(array) { return "" + array == array.sort(function(a, b) { return a - b; }); }
```
[Answer]
# 14. [SjoerdPennings](https://codegolf.stackexchange.com/users/45220/sjoerdpennings), [JavaScript (Node.js)](https://nodejs.org), ~~310~~ ~~302~~ 297 bytes
```
alert(`def f(i):
i=i.split(" ")
print i[0],i[2],
for f in i[0:3]: print f,
print ""
for t in["TT","TF","FT","FF"]:
p,q=t[0],t[1]
y = t[0]+" "+t[1]
if i[1]=="^${a='": r=(False,True)[p'}==q]
if i[1]=="v${a}!=q]
if r: y+=" T"
else: y+=" F"
print y`.replace(/\n/g,(b,i)=>b+' '.repeat(4+(i>90)*4)))
```
[Try it online!](https://tio.run/##TY5NTsMwEIX3OcUwQopNTNpCN1hylz5BdiGobupURpbjOiZShHr24JQIsZmfN9@bmU81qqENxsdn15/1PKoAyuoQRdu7obe6tP1lvivkeNYddMRQnhlhysFbEwkC0swH4yKYetswU780LOv6AB0Yt2j8teHwS3RsRRHvSPK4GqsKGVYyBblUUmLDM8@uIi4LY71rsgkELF2RzhV3xaT1KQuBH4/fSuTIIQgilR00q8KXprXPb0Jc/5NjIm8PqxY4TIVAAKgw08n210tcv5yOZdDeqlaTzbvbXBg5MUPF4VTkkC8jrSLZF8Qc3rb0aU8pnecf "JavaScript (Node.js) – Try It Online")
### My first [answer](https://codegolf.stackexchange.com/a/217893/99744), 68 bytes
```
l=(a,b,c)=>b.startsWith(a.slice(c=~~c,-1))?a.slice(0,c)+b:l(a,b,++c)
```
[Answer]
# 16. [Aaron Miller](https://codegolf.stackexchange.com/users/101522/aaron-miller), AArch64 machine code, 41 bytes
Machine code dump (xxd):
```
00000000: 20 00 80 52 c1 00 00 10 a2 01 80 52 08 08 80 52 ..R.......R...R
00000010: 01 00 00 d4 a8 0b 80 52 01 00 00 d4 3a 2e 5c 21 .......R....:.\!
00000020: 2b 3a 22 64 22 60 23 40 5f +:"d"`#@_
```
Assembly source:
```
.text
.globl _start
_start:
// write(1, .Lstr, strlen(.Lstr))
mov w0, #1
adr x1, .Lstr
mov w2, #13
mov w8, #64 // SYS_write
svc #0
// exit(dontcare)
mov w8, #93 // SYS_exit
svc #0
.Lstr:
.ascii ":.\\!+:\"d\"`#@_"
```
Given how all instructions are 4 bytes long, there isn't any point in doing anything but a direct write.
[My first submission](https://codegolf.stackexchange.com/a/216822/94093) (xxd)
```
00000000: e4 03 27 1e 00 44 40 bc 01 58 20 0e 21 38 30 2e ..'[[email protected]](/cdn-cgi/l/email-protection) .!80.
00000010: 23 3c a4 0e 02 1c a3 2e 24 1c a3 2e 21 04 00 f1 #<......$...!...
00000020: 21 ff ff 54 40 00 26 1e c0 03 5f d6 !..T@.&..._.
```
**You must emit the raw bytes**, not the assembler source or the hexdump. üòè
[Answer]
# 17. [EasyasPi](https://codegolf.stackexchange.com/users/94093/easyaspi), Python 3 2, 110 bytes
*I realised that my first answer was written in Python 2 after I had posted. Here is the updated and golfed version.*
```
import os,base64 as b
os.write(1,b.b64decode("5AMnHgBEQLwBWCAOITgwLiM8pA4CHKMuJByjLiEEAPEh//9UQAAmHsADX9Y="))
```
[This](https://codegolf.stackexchange.com/a/99331/61979) was my first answer:
```
n='\n'
p,a='p'*8+n,'rnbqkbnr'+n
print a+p+('.'*8+n)*4+(p+a).upper()
```
[Answer]
# 2. [caird coinheringaahing](https://codegolf.stackexchange.com/a/112720) - [Python 3](https://docs.python.org/3/), 13 bytes
```
print("Ißo")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8nz8Px8Jc3//wE "Python 3 – Try It Online")
[My first (code-based) answer](https://codegolf.stackexchange.com/a/209923) is long and high-entropy, so good luck :P
```
import zlib;lambda x:filter(33 .__ne__,zlib.decompress(b'x\x9cKJM-PH\xc2A(\x92\xc7\xa26\x97nb4!\0hm{7')[:x*5])
```
[Answer]
# 4. [A username](https://codegolf.stackexchange.com/a/218314/95792), [Scala](https://www.scala-lang.org/), 141 bytes
```
_=>"<?php $w=0;foreach(str_split($argv[1])as$v){if($v=='o'){echo$w.' ';}else{$w=$v=='s'?$w**2:($v=='i'?++$w:--$w);}if($w==256||$w<0){$w=0;}}"
```
[Try it in Scastie!](https://scastie.scala-lang.org/8KPgnrYHSEu93eScW1CyjA)
[My first answer](https://codegolf.stackexchange.com/a/207412/95792)
```
print("N")
```
Simple string replacement can't be done here, as there aren't any patterns. Using `GZIPOutputStream` and stuff gets really long just from the names of the classes involved, and the string's too short for the compression algorithm to work its magic. In contrast to A username's first answer, mine is really short and easily printed.
[Answer]
# 3. [pxeger](https://codegolf.stackexchange.com/a/226462/100664), [PHP](https://php.net/), 110 bytes
```
import zlib;lambda x:filter(33 .__ne__,zlib.decompress(b'x\x9cKJM-PH\xc2A(\x92\xc7\xa26\x97nb4!\0hm{7')[:x*5])
```
[Try it online!](https://tio.run/##K8go@P8/M7cgv6hEoSonM8k6JzE3KSVRocIqLTOnJLVIw9hYQS8@Pi81Pl4HJK@Xkpqcn1tQlFpcrJGkXhFTYZns7eWrG@ARU5Fs5KgB5BsBWeYxFYlGZkCOeV6SiWKMQUZutbm6ZrRVhZZprOb//wA "PHP – Try It Online")
My first answer was [this](https://codegolf.stackexchange.com/questions/218260/write-a-deadfish-interpreter/218314#218314):
```
<?php $w=0;foreach(str_split($argv[1])as$v){if($v=='o'){echo$w.' ';}else{$w=$v=='s'?$w**2:($v=='i'?++$w:--$w);}if($w==256||$w<0){$w=0;}}
```
[Answer]
# 8. [elementiro](https://codegolf.stackexchange.com/users/98428/elementiro) [R](https://www.r-project.org/), 45 bytes
```
cat("ezpolar(@(x)r);s=r+5;axis([-s,s,-s,s])")
```
[Try it online!](https://tio.run/##K/r/PzmxREMptaogPyexSMNBo0KzSNO62LZI29Q6sSKzWCNat1inWAdExGoqaf7/DwA "R – Try It Online")
A rather boring program that just `cat`s the previous person’s first answer. My first answer was [this one](https://codegolf.stackexchange.com/questions/179485/quine-outputs-itself-in-binary/179537#179537):
```
x=function(){rev(rawToBits(rev(charToRaw(sprintf("x=%s;x()",gsub("\\s","",paste(deparse(x),collapse="")))))))};x()
```
[Answer]
# 13.[Wasif](https://codegolf.stackexchange.com/users/92116/wasif), Python 2, 27 bytes
EDIT: My sleepy brain didn't notice the "language of your first answer" rule, it has been fixed at the cost of 5 bytes.
Just a simple print.
There's not enough of a pattern to try replacements or formatted strings, compressed versions of the strings are longer than the original, and since this is Python 2, using `exit('text')` won't save me a byte. As far as I know, the best way to golf this is to simply print it, and remove the space between `print` and the string.
```
print'1.."$args"-match"2$"'
```
[Try it online!](https://tio.run/##zVtpc9s2E/6uX4HKaS3Vkiw7SZP4tdzGSZq6beKM7U77jseVIRGymJIEQ0KR1euvp7vgIYIERTA@NZNYIoHdZ09cC38hptx7@NQPPtmuzwNBwkXYIS4V0w6xBQsE507YmATcJcJ2GUlaOYz50eOAehb8iV/gL/h3wRrxAxHQMRvR8R@NxtihYUj2AxqO6Qv8vtMg8Gk2m8cCGnRIwC7sEJiGBKiQjzSw6chhITSQDS02IcOh7dliOGyFzJm0dxryBX7WJA3ZMSWTvsTGvVA2GJDTM/U5hWd99dFIebTk8TxgZM6AAbVs74KwjywABeJXGpLxlIKsyPfbPOMAmgxdbjGg@z11QpbB/c72mdW1PWJRQdPH9oR4XFoDugOznh1SIRat9k7aJEMfGgyxO5Bf9kCUrfbpzk5360zpNOEBGXbIkABT5s1cFlDBWjlSOUYaZmivcOYIZKq@OUWWncLTPA7VMj3q@8yzWjywWhHhdjttzkBnVZKDlyy1@gNFJ4qNM2LMIz4YQTCLLJjI2Yc6qKrFMGlRtNHJ1A7J3HYcEgoOPkDhm5gyMgKD/8EE8XloC5t7OY@bT22HDR3O/RCI/vWPQpGRMToEOiyS8jkyD1QC2GIYvyl66ThyqKzc8jlEnmOPIUrAtqkw@haC@6q4a@9m4ZRAxxFwFFxCk@ZJI9CHBsOogfSZDrbOeEvRovg@S/0jdWaM8MkyYpCThgu@j3ng15VM0G1ko3a5ICMuBKQq4LxSrGHUrko62wshP7b6UZNqAY0QYA@Vf7nkSwBF4cGuMjvnWHA/SZz5RJOSVcMsYGIWeBnPK0Zi3CQDDNlEsZtDU6kC7meFvwWY/URjxxDGCCgZPFJMIRPD5GFskuSnii95SgYQk7SpSVc0SZVLBUVY871Hut6jYu@Mz2Wxr4exC2oDGJPddUmkhGAkY1svd7@uuEXSo7ZeKf3YhEc4HodMK7J8k3eqDJ@kRTulJb0FSTnMuxBTvcNG7/J0Y1eDl60li0xozhwYcCU1OUIQHCGIA/ogrfy40U5ZjWa2Y0UP8/wEc311YoNPhjDvUOYc6ksYGB32YcYFU6yDk4NkOIPkw10XR6jiTAEHn9wcAcxaIL1H@sWJRKFVd0C2lFbSR4o4B@XUcrLmgSWCoLudNqNRV@kXd9STT9wwUUy7CDbL4KwWA/COACdRkpGaGcpmE6eyzxl0ShBVd0laYi/ZfbUM681KTZ8EM1Zt2wHZXs3pvLY5ss0KIEzpY8dq8rE3NXANcryAjOUSGlxAJHgCli@@XD7hNBCWND1/QSZkdwIq96jL9opvx2QXw2av0TjhEE@4uIHQHs0uOmQGeWtibY4x1IALtTDfTDbHPWwaOnxOLD73CJ8Jfybi5uHmOJTAbFwXIc/hUEo8HLoU5sXD2IQRADBEZukVO1mMLZ1JNj@db/V6zQcgY9jswjJwPG1uP2ief4oXalEKI/uYi6LkiKnLpX6WWjZTJVmPvAFEsrX8HeW9DPd0lrsr02bmTTbPBQvVYqmZs6RONWTP8vkgbqMszUp9rvBgjcgxdxdS4p46d12RdvqaiMpoLTuv7hdTQMGtt8zJbRmQ2zYnt21A7qE5uYcG5B6Zk3tkQO6xObnHBuS@MSf3jQG5J@bknhiQe2pO7qkBuWfm5J4ZkHNquLFJWPxcg56J57EacWFi3Fc1AsMk0KwakWFi3pc1fNkkNqY13MXEm3@o4y8mDvNTLYImFP9q7pC1l2wcMJwmmBJPHuEEsGuSsf9BNgfeFdhsmLAJkI0c7o7kvq6OD12OwPoJrARj0giXHzYuN@QmcmvUIRRQ6i1UIqHdbhQHbClANNrDtGlKg0rB18/XVzqGuqurnQsbTarzUshNr4rpzMbWWXsVIWVGtYGLq6JG3lBc1Pq4pOOZrfJS7BvoB88t64YdQOeyG9TAT7uI73g2wgMHcQcguyYgv0aQb2aOsH1ncQcgvzYBuRklFsEuwHss@6Md6haYNw92c9ME7ZdSpdyaOfwOMH5pAvF3hPjq0udeWaK@YasbmT2UAfQhuArCInM8SuxNYOEXfw2BQYu227okvW@LuQ0r2xpZ6V8E/fbw5Fox/2uirq9kPnz78g7s@ZUJvr8R3@HRHcD72wTeEOH9dif4fgd8Gu871i7iC8ApAvflljtfbmM/XzlVyB4hAAED9Yy0XPbNuYxMuDyXXJLTGTNh1OMDM2n29Xz2a/AxkqeDfOKt/JJNGYVDsudfSXgHCVszPDWVW/cgCp@s4PC5mYdepWUB9f9U1MuTN1PgyWGcKaqkPb2GDgVpXJTG5R9V9WN8RES0LKNzsM8yRoJNkjDA9ybFl1O0PIaLNz6r8dXVuTE@v0J/xJMlPqHeL1w@84TpCs5bruD6najrijWcsY2ux07vKux0j/Sw2heu6A/fymQZVW/FdRL97tb2E1O/S0u9WrDOzO8rtA0AfJGOccsj1sqkrdnLiA9hTVg@QJbhnPrS0GLOscjNDQn3rpzMbzzjjwzkO5I25SIZpMQ0YOx2ZRzfuCLGV1GZ9jynoMdj1OOYezhueqkywV0iwuHt@wnGWChQpA38Q40i7CIvRrkDxDUEyGZ9vfee255k57WXiSzd@MJqhvKkN8Y0B8kkk/oyR3px7@odvTrKQfAG6nitVYc8HQ5hkqRf@K6db/W2H/YePT4n6z1ik9dksEe2yPZD8uixtoMFfF0TKwNPrNrAwo/WItLzZYcsUHFp6W3vIuAzf7RQ1NchDnVHFiV/7pA/UTLJsp0USV2e3ZltpAxIHWQrJ1Pia7EOpAIu27XGPEMHsGMHgHm/IEDEtnHMjwe/Vld3QKJorhOP0Uo5jKK8cqEBStR5b0AePY0rnPH37oA8flLeT9lyBhanEglWccjuALpa7oOs3MuayEgDrY1bk7uviv3ss6UGyI1qsS/l@scGIoFVvWZb6dwF2r9laZusrExmdQUuM@Tyi9c91pL0TOehsoArSuf1jlIgQi2TgeaXGOdFKc5soF@2l4lC8aJGlRuoVW7XLaZmU@hg89DA0bjca5O1OXgT4Pnxi4ODuOK1yuuWtSiFMvTSepScKMX6de1pFH5kk9Z4qp4DtjsQ1tZgfd3A0oelopoEwd1LmwZfHaE9Veg4g95fA2eNW0PMt@Vi3lfjagy7FFgTzy@4JwLukO8dPq9WyC4q5GcWhrCQojd9BIbq26W1EteWnhIzUXXderM91MVrMI@8znA76ti7v@oYyDO9DzNw61tQxGBwbzWx/v910MQ@E3PGvPuwt4D6wtnlGP@7vw70HTrQCQtcG5eijetJinj7j13awmRuuYYAIB9asiycOuT9zPUrErvUOuq1X6mPYg1KJaL3iOhHQIGzuTlMrMM6RS5qAVU1tx9Tbng9tR67rspuw4DdKbL7Feueu7JouliDX1R3NOf9Aie9KxdYykqpu3VWYaEyqVKhsvcGKquptdKe5aSFIfmmZN27UVFNPOnF6rKu3H1Ms1KxE0Oa0Q1OSbOhrlyi@0pSCj9gctcnTK8u4/XYuB6ueHtCXxyvvzCxdoJXnWwBU8MJmU@ZB0t8DowDGVXCBpsC2wms3q2KAvl6BXfqlaYUzSGylkUk8mBBs6dXnswLVXgxuFypytobeYaWXODNX9w1SoHscsx8QX5iixGHxIPFVkEw80XuHlwxm8cdX8k/kLbRkDlx1o65y6KLz3PmCTIPuHfRwaMAPgfjEODEVbjRVLr56ujo8GiH6LrnDt@jDunV/h6ka5eKIYDLn8JkRIgughzEjhtfZWnUXTgs2yohAD6mWWGsPOi/wn4oHaychWgwYujrMRYXq7RqzVZCXB@gS9q0SFZLLtZnkdwKsWuLXC1ufVFLxcTPp/8A "Python 3.8 (pre-release) – Try It Online")
[My first answer is:](https://codegolf.stackexchange.com/a/58461/45220)
```
def f(i):
i=i.split(" ")
print i[0],i[2],
for f in i[0:3]: print f,
print ""
for t in["TT","TF","FT","FF"]:
p,q=t[0],t[1]
y = t[0]+" "+t[1]
if i[1]=="^": r=(False,True)[p==q]
if i[1]=="v": r=(False,True)[p!=q]
if r: y+=" T"
else: y+=" F"
print y
```
[Answer]
# 11. [Ross Long](https://codegolf.stackexchange.com/users/103272/ross-long), [Pxem](https://esolangs.org/wiki/Pxem), 0 (content) + 17 (filename).
Since it was 15 bytes, terminating LF is also output.
Filename is as follows:
```
#>&:*.@
~2-1??
.p
```
Content is empty.
[Try it online!](https://tio.run/##jVhrV9pKF/7urxjSSGZIQjIIisSoFDyWc5SqtS4roCuQoGAIHBIUDfSv9@yZBIHQt@t1Lc3Ms6@zL3Px2X/69elT0dm3Onsdp53r5naK9p6@u9sp2Ppuodu2urqt5/IFvVCghS3fCZDqTIzJwPKfka7ncoYzHQ3HATqrPJTPzsyKgYO3kYMenaAz9LrpNJ91hoOB5dnkULOdF82buC7KHaZpOh0LX5Svv5iCiGM@pI4WCjiJiCH7yKV5NFDnwsLs93rt9uHbddXM6frOArz4@q12e/bjofL16uqkcm1So4EEMfxc/vbl4ebk6lvta70kv80FZKI31Eqn@aqGaDT0e9NoJn@ORO7@h4QzmLhW4CD/ifMPRwEMX4dj2x@5vSCdttye5SP1EUliSGVBPBbmkimxr5RO17@fnVXOq2aJ28DMnm34T71uYPAxYnwx4HSehkj8RJhlyiynwFBu6NqHaQj9i@UiIYW6lus7wmy2SuOqufR05js2knxtqr1phg9/3jWJK3xHLSbEuYBnIdrBBA8hCWUPqS/BhM6CMVIrPmo2dHW/haRG08u0pNnj2BmhbKRcu8/vilpYKhti26gbWtPj8wswd5/NNj1NM9plYx5NG/dMD6U5URtpRrAKFvVNjFIqasMEuLe/iVEK0l6SsbiJUb0gar0k484mtg98D0kMLHcS2O7eJkYpCPvJ9e1sYpSCiy9Jxt1NjOoQsW7SbX0TozpEzEn6uL@JUZoXtXHSdG4ToxSkX5OMe5sYzYE/0yRjcROjOfDxLcm4v4nRHPjznkyC/hsM3LGSiy5sYpRCbIOk5fwmRnVwZ5CM994mRnVwx06aLm5ieUi/nMTARTWB7QBfKomB12ISA2e2GTaXZrhjxduFTeKm5P2qhaesKaeGDf13yqSbONskTdz02N9spklErbnTzDWpBly@ls1At07X@7vkGmIq1Bqv07d3y25pqbButF1QODfeoNk1pBla4z6mshIXNWRrazpUD0mx@cb9sdICu@ABbkRDcCF3jJgLTzFPhKNsBkjcs8g6rGfE3RQ1haFtcAFSHMIsFfowKmsjo30JaMSmHIOCD0b7g9HWqgvGNbYFJY5DaWyIYWTuGDHVsMVxblReIEGZh1ZM1YHS9BpIfW9lbKYtGK8gsCQen1a0WI2TLGAb8ZxGi7MiqTl4W7r8UJnlvgWXiT03jscXiEy1DHGZxsnlkV3GLYrPaayJ/0auRJ7EWf@doIQWR8dKQrReF7tW23FNU2hSgYR8JbgxGnq9h47/0nXGwUBOidtqi3E3KSaG9hjxsHpshlRpzhnpAjdpTLNWXfInbSywhAgKkz6CsVASjgWFmyXz2OA6/5@Yq6LWHjvWM59A3spYcIfDEfKGARpYQeep5z0KwCotlitjorUxJdw3lU/UeJbiMz2aiDD5dzHZ5hPGBs3IG1HqDsdxrMAjwyChZHx0qTSXCPn1V718fmJKnw7TpUz2eOtnTqVHR1vZkbRV@Vq/Pqlfm5K0hUfjnhd04UTn7GJMEmavHaR2CJzZv/xxx5Q@n5zW6iHkR/Ydxyb@GO5SmA/n3YnXCXpDD13gKgm/NZ6VfzBpmVUDhi1ZXtJPMAnHTjAZeyglA8@S8veSAvghXVL@WVKYuiXheo3ATKp0hXyLr0h4ZQIXd0NVjZj5askzwRUS8vWjyhI9xVfK3YduuCu6Pc851I9EvaSuOPYlMiBSg9fIPS9AGUpFEMgahCJo0/x3Zn7imSu2y/h84dH5TIB8QvzZfbQXoBXTI1j661PPdXAKQkqGq5GESQjgbDbBt0BbEjxcU26UquISlkUuGN6YwGO4put4j8ETviEGq6oaXGprB6ZrkAnGVRPW4gdjfKPUZFmhhPwU@LqEo6qcL5byBTJfGumB9Qt8umb4AZ8rFeVO@UHCc1PIPpRQHXrDQrbT6Q3gkgmLdR6dMXxHk0AwKiaIG3fgA/OFFTa4m987qKTTlYNCkfBuMwCr/BTu842dQkuEjeLOzOfVSiwcNSSw4GIkRvMQkIpp7uRIGLHA/T/oeRNnziLOWCsH@SLwHBb2CIMi40uzkWbyw8Q/CKqo@aLBsmdc4LvMj5W1dhbRv8DXa0HwF4Tb1WS9QE76yg0Ja6bOLfZNXscQ/j4rW6Wvqi3zhiWKzWotDkIeWnzeb62Efrw0DRHFvD9JhtXAisHXZdNsejPFlwq3lYJ2ZBFOweySl8iNeXnAeGPZm6XQ2x@FDn8v9P7hBpPibqhrrgSLxTxB75prpAGQnqFYEDyPLjCjrxDb2IKARiX@N6vwC2wdgbhssUiUbuOIGMsdI2NSNZfB1oFOMixn8F0J6r9Jff24Y27jxeJ@xiVQMWBGyG7D6ZCFahRK6M4Zw2Wp99LzQY3ACoUlxTrqH7pH/W235G73S3ys8THkaB7tsOCZqbegHOBFl9ibhVmHCNLSuS5EYo3rY@/efGH94YFlRidTdB2A2xacVOyhq469ZzrrTGBkS0hCaje3OMLg9nKB04S99FbccXgxR0djCIXLC/pZlg1Z7h9gtgmzooWQR@Hvx1MYEOP3y2DLtR3Xgccw5BlaId6eoEFkuXYA4jKNWoKfNDWuUabQJ9GmL0fz1lwy2EnF/gsA96UO4v8pmLAOGQ7YuxfA8Qa4jKGdR2o9v8Ywm@ERvMHL8LDv2YoT9AaOMuqMJsqL/27Y8HonqznI//mViwKr58IdNr8SYHaPDovsLsNvTNLMen0GXcgy1RzN7@WLO7v5IpJCSzZFfX5Sr8anhgUnv7D1f@c/1hpHh30ESAAc@AInSaIOFzH4EZAfpQcL20NBEXUizabW@BFiUJuiOHPTLfTrPw "ksh – Try It Online")
[My first post](https://codegolf.stackexchange.com/questions/55422/hello-world/217589#217589):
* Filename: `Hello, World!.p`
* Content: empty
[Answer]
# [Alex bries](https://codegolf.stackexchange.com/users/99744/alex-bries), [Befunge-93](https://github.com/catseye/Befunge-93), 79 bytes
```
")c++,b,a(l:b+)c,0(ecils.a?))1-,c~~=c(ecils.a(htiWstrats.b>=)c,b,a(=l">,# :# _@
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X0kzWVtbJ0knUSPHKklbM1nHQCM1OTOnWC/RXlPTUFcnua7ONhkmpJFRkhleXFKUWFKsl2RnC1QN0mibo2Sno6xgpawQ7/D/PwA "Befunge-93 – Try It Online")
### My first [answer](https://codegolf.stackexchange.com/a/220561/101522):
```
:.\!+:"d"`#@_
```
] |
[Question]
[
Significantly harder version of [Spanning tree of a rectangular grid](https://codegolf.stackexchange.com/q/195408/78410).
## Background
A spanning tree ([Wikipedia](https://en.wikipedia.org/wiki/Spanning_tree)) of an undirected graph is a subgraph that is a tree which includes all of the vertices of the original graph. The following is an example of a spanning tree of a 4-by-4 grid graph.

## Task
Given two positive integers `w` and `h`, output **a randomly generated spanning tree of the grid graph** which has `w` vertices horizontally and `h` vertices vertically. Your program/function should be able to generate **every possible spanning tree with nonzero probability**.
One possible algorithm to solve this task is [random minimum spanning tree](https://en.wikipedia.org/wiki/Random_minimum_spanning_tree), which calculates the minimum spanning tree of the given graph with randomized edge weights.
## Input and output
The input is two positive integers `w` and `h`.
The output is a representation of a spanning tree. You can choose any representation that can describe such a graph without ambiguity, which includes (but is not limited to):
* ASCII-formatted grid
* A standard graph structure, e.g. adjacency matrix, adjacency list, incidence matrix...
* A list of pairs of numbered vertices
Please specify the output format in your submission.
## Scoring & winning criterion
The standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest valid submission in bytes wins.
## Example I/O
### `w=3, h=2`
* ASCII grid
```
+-+-+
| |
+ +-+
```
* Adjacency matrix
```
0 1 0 1 0 0
1 0 1 0 1 0
0 1 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 1
0 0 0 0 1 0
```
* List-of-vertex-pairs representation
```
[(0, 1), (0, 3), (1, 2), (1, 4), (4, 5)]
```
or
```
[((0, 0), (0, 1)),
((0, 0), (1, 0)),
((0, 1), (0, 2)),
((0, 1), (1, 1)),
((1, 1), (1, 2))]
```
### `w=1, h=1`
The graph is a single vertex with no edges, and its only spanning tree is the graph itself.
[Answer]
# [Python 2](https://docs.python.org/2/), 134 bytes
```
from random import*
w,h=input();w+=1
t={1}
while 1:z=choice([{a,b}for a in t for b in{a-1,a+1,a-w,a+w}-t if b%w>0<b<w*h]);print z;t|=z
```
[Try it online!](https://tio.run/##FcZNCsIwEEDhfU8xG6E/KZi6s40XERdJbcmATUIYGUzt2WNcPL4XPmS9G3Jeo98gavcs4BZ8pLZiYRW68Ka6GblTsiK1y6Nii68F5DWp2Xqcl/q@a2GO1UfQgA4I/mvK7rqXQnelnot89AS4gjnx7TyZiVv7aMYQ0RGkkb4q5XwRww8 "Python 2 – Try It Online")
A small improvement over [xnor's answer](https://codegolf.stackexchange.com/a/197624/78410) by using row size `w+1` instead of `w` and not using the zeroth column. For example, the following coordinates are used for the input `3,2`:
```
1-2-3
| | |
5-6-7
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 146 bytes
```
Block[{c,g=GridGraph@{##}},Graph[Range[1##],Join@@Reap[Do[c@n/._c:>#0[Sow[#<->n];n],{n,RandomSample@AdjacencyList[g,c@#=#]}]&@1][[2]],Options@g]]&
```
[Try it online!](https://tio.run/##HctBC4IwFADgvxIMPK3SjpWxIhAiKPT4eMSYc67c29BBhPjbLbp9l8/J2Gono1Vybhb5fOq8esGouMmL3tZFL0MrRsamif8NpSSjIWMM@cVbEqLUMsDZgxK0Xj3U9sBSqPwb2H55INwR8pH4b9XeVdKFTotj/ZRKk/pc7RDBcCVYznDCRGQIsEHktxCtp0EYxGS@95YiNJClPEsR5y8 "Wolfram Language (Mathematica) – Try It Online")
Based on my answer to the question [Maze Generation](https://codegolf.stackexchange.com/a/25970/9288).
Returns a [`Graph`](https://reference.wolfram.com/language/ref/Graph.html) object.
For example, `w = 20, h = 20` gives:
[](https://i.stack.imgur.com/edMNn.png)
[Answer]
### Ruby, 159 bytes
```
->w,h{c=(v=[*1..w].product [*1..h]).product;((f,(a,b)),(g,(d,e))=c.shuffle.map{|z|[z,z.sample]};(c=c-[f,g]+[f+g];p(a,b,d,e))if(a-d).abs+(b-e).abs<2)while c[1]}
```
[Try it online!](https://tio.run/##NYzLCoMwEEV/xeWkjgHr0qY/EmaRxIwRlAatlfr49lSE7u45cO44229ilYrngmFzCj5K30opF5JxfDWze2cXBxJ/UQMwgkErBEKL0KAXQjk5hZm593IwcdvXXa@4yskMsfd01OCUKzRjS7nmvKU6Zvq8wDMm0TGYohHS2CkHW/hrPe5iCV3vM6dLOhLrCitKPw "Ruby – Try It Online")
Uses simple Kruskal's algorithm with a few pessimizations (no union-find, inefficient - and non-uniform! - sampling of the purely virtual edge list, returns via stdout), at a byte cost relatively close to Value Ink's Prim implementation.
Prints each edge as a set of four lines; if you want something slightly more sensible, replace `p(a,b,d,e)` with `p [a,b,d,e]` at the cost of one byte.
Unsqueezed version:
```
->w, h{
v=[*1..w].product [*1..h]
c=v.product
while c.size > 1
(f, (a, b)), (g, (d, e)) = c.shuffle.map{|z| [z, z.sample]}
if (a-d).abs + (b-e).abs < 2
c = c - [f, g] + [f + g]
p [a,b,d,e]
end
end
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
,þ;Z$ṡ€2ẎẊḣ1;ẎḟL’ɗÐḟ@ḣ1ʋ¥ƬƊṪ
```
[Try it online!](https://tio.run/##y0rNyan8/1/n8D7rKJWHOxc@alpj9HBX38NdXQ93LDa0BjF3zPd51DDz5PTDE4BMB5Dwqe5DS4@tOdb1cOeq////G/83AQA "Jelly – Try It Online")
A dyadic link taking the width and height as its arguments and returning a list of pairs of vertices indicating the edges of the random minimum spanning tree. Based on [Prim’s algorithm](https://en.wikipedia.org/wiki/Prim%27s_algorithm) with the edge costs randomised.
## Explanation
```
,þ | Outer table using pair function
$ | Following as a monad:
; | - Concatenate to:
Z | - Transposed table
ṡ€2 | Split each into overlapping lists of length 2
Ẏ | Join outer lists
Ẋ | Randomise order
Ɗ | Following as a monad:
ḣ1 | - First list item (still in a list)
¥Ƭ | - Repeat following as a dyad, collecting up results, until no new result seen (will have the randomised list of vertex pairs as its right argument)
; ʋ | - Concatenate to the following as a dyad:
Ẏ | - Join outer lists (making list of vertices seen so far)
ɗÐḟ@ | - Keep only items from the randomised list of edges where the following is false:
ḟ | - Filter out the vertices already used
L | - Length
’ | - Decrement by 1
ḣ1 | - First list item (still in a list)
Ṫ | Final iteration of the above
```
[Answer]
# [Python 2](https://docs.python.org/2/), 136 bytes
```
from random import*
w,h=input()
t={0}
while 1:z=choice([{a,b}for a in t for b in{a-~a%w/~w,a+a%w/~w,a-w,a+w}-t if-1<b<w*h]);print z;t|=z
```
[Try it online!](https://tio.run/##NcdBDoIwEEDRPaeYjQlgGwV3Qk9iXBSEdBJpm2ZIY2u5eoWFq/@@/ZAyus15dmYBJ/VrDy7WOKoLz5RAbVcqq4JEvKbCK3xP0NyDGJXBcSofUbIhzcaBBNRAcHDYGSXf5MlfNs/k@Q9@jE@cAGfe9EPva/WsOutQE4SOviLk3LLbDw "Python 2 – Try It Online")
Prints edges as two-element set of vertices given by single-number index, terminating with error. The strategy is to to build up the set of vertices `t` in the tree until it contains the whole rectangle rectangle. At each step, we add an edge to the spanning tree consisting of a vertex in `t` and one of its neighbors that's not in `t`, and we add the new vertex to `t`. We search for neighbors by adding one of `{1,-1,w,-w}` to the 1D index with some trickery to avoid unwanted wraparounds, and checking that the result lies within the bounds of the rectangle.
---
# [Python 2](https://docs.python.org/2/), 142 bytes
```
from random import*
w,h=input()
t={0}
while 1:z=choice([{a,b}for a in{k/w+k%w*1jfor k in range(w*h)}-t for b in t if(a-b)**4==1]);print z;t|=z
```
[Try it online!](https://tio.run/##FcxBDoIwEEDRPaeYjUlbSxR0JelJjIuCYEegbZoxjSBnr3T1k7f4/kvG2TqlIbgZgrbPPTh7F0gUURqF1n@I8YLUet6KaHDqobotqjMOu57dVy3bbXABNKBdx1M8jocoqnemcaf8fPUsCsO3kiBzm5kAB6bLlgtxVap68MYHtARLQz@1pFTLyx8 "Python 2 – Try It Online")
Prints edges as two-element sets of complex numbers, terminating with error.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~185~~ 164 bytes
A huge mess. Outputs a vertex-pair list, where vertex coordinates are complex numbers in the form `x+yi`.
Long story short, it takes all vertices that have already been chosen, randomly picks a neighbor that has not been picked before, and attaches it to the graph, then repeats the process until all vertices have been chosen.
* -4 bytes by optimizing `r>=0&&i>=0` to `r|i>=0` -- If either number is negative, the bit-or will ensure that the combined result is negative.
* -17 bytes by realizing my filter function in the second neighbor check could be switched to a simple set intersection...
```
->w,h,*e{*v=q=0i;d=1,-1,1i,-1i
(q=v.flat_map{|x|d.map{|c|x+c}.select{|e|r,i=e.rect;r|i>=0&&r<w&&i<h}-v}.sample
(v<<q;e<<[(d.map{|c|q+c}&v).sample,q])if q)while q;e}
```
[Try it online!](https://tio.run/##TY5BCoMwEEX3PYWroDYGbZcmXkRENI4YUGqijYrJ2W1qS@lmmIE373/1rLejZUeULbjDIeyhZpLFIm1YgqMEJ8JNcfEl06Ttq7kcqnE3q2nIuXCzXrklE/TA592AUVgwIMpdqTIiYzFCii4ICdrZSDuyGsYeLr6mVKZAae7/TNKZkA6@CJZFIFpPBksnevAcbI82v@F7QaaHmst6e8fBXylu@Bls7ccIZvTc0ws "Ruby – Try It Online")
### Explanation
```
->w,h,*e{ # Proc taking 2 arguments, e=[]
*v=q=0i; # Add first vertex 0+0i to list
d=1,-1,1i,-1i # Save 4 cardinal directions
( )while q # While there is a valid neighbor:
q= # Set next vertex to:
v.flat_map{|x|d.map{|c|x+c} # Get all neighbors to used vertices
.select{|e| # Filter neighbors by:
r,i=e.rect # Get real/imaginary components
r|i>=0&&r<w&&i<h # Vertex coordinates are in-bounds
}
-v # Filter already-used vertices
}.sample # Pick a random valid neighbor
( )if q # If a neighbor was found:
v<<q # Add it to the vertex list
e<<[ # Add an edge to the edge list.
( # First vertex of edge is:
d.map{|c|q+c} # Get vertex neighbors
&v # Intersect w/ used vertices
).sample # Pick one by random
,q] # Second vertex of edge is neighbor
# (end while)
e # Return the edge list
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 64 bytes
```
{e@&~~':i{@[x;&|/x=/:y;:;&/x y]}\e:0N?,/(2':'m),+'2':m:x#i:!*/x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6pOdVCrq1O3yqx2iK6wVqvRr7DVt6q0trJW069QqIytjUm1MvCz19HXMFK3Us/V1NFWBzJyrSqUM60UtfQrarm40hRMFEwAIAwT4A==)
arg: `w,h` pair. result: list of vertex pairs.
`i:!*/x` create the list 0 .. (w\*h)-1 and assign to `i`
`m:x#` reshape to a w-by-h matrix `m`
`2':` pairs of neighbouring rows
`+'` transpose each (make them rows of pairs)
`(` `),` prepend
`2':'m` pairs of neighbouring cells in each row
`,/` concat into a single list
`e:0N?` shuffle and assign to `e` for "edges"
`i{` `}\` scan the edges with the function in `{` `}` and a starting value `i`.
the left arg will map vertices to their "tree ids" in the forest.
initially the vertex ids and tree ids coincide.
`@[x;&|/x=/:y;:;&/x y]` amend the current forest by merging the tree(s) corresponding to the ends of the new edge
`~':` which forests match the previous ones? boolean list
`e@&~` select from `e` where not
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~77~~ 63 bytes
```
NθNηJ⊗‽θ⊗‽ηP+ ¦+W‹№KA+×θη«J⊗‽θ⊗‽η¿¬℅KK«≔⌕AKV ι¿ι«P+ P✳⁻χ⊗‽ι²+
```
[Try it online!](https://tio.run/##lZAxT8MwEIVn51ecMp3VIAHqBFNFhQSioUIVe5oYcsI@p3YMA@pvN3bKUKALkgffu3ffPbvtG9faRsd4x0MY62C2yuFOXhfHdZ/q@2CGjcWlDVutOnxquLMmOWUFv7ReyuRfBT3S4IhHvJpVUAKUSV1PQjnL94@etAJ8UN7jjQ1JXyv1ttAaEzNbKtiQUR53FWQmfBbivykEvQDWdsRH1xE3elqB8psmFt7TK@MtcZf35uaz5VoF0zBPMSDHoEyaUHSYE6df97OxJKfakSzjijh4vDj/E5JykgouD7PHnyPEvkhnH@Mc5vHsXX8B "Charcoal – Try It Online") Link is to verbose version of code. Outputs a whitespace-bordered ASCII grid. Explanation:
```
NθNη
```
Input the width and height.
```
J⊗‽θ⊗‽ηP+ ¦+
```
Jump to a random position and mark it with a `+` surrounded with spaces. (Unfortunately Charcoal's Multiprint operator special-cases a leading `+` so I have to output the `+` separately.)
```
W‹№KA+×θη«
```
Repeat until `w*h` `+`s have been output.
```
J⊗‽θ⊗‽η
```
Jump to a random position.
```
¿¬℅KK«
```
If the position is vacant,
```
≔⌕AKV ι
```
find any neighbouring spaces,
```
¿ι«
```
and if there is at least one, then
```
P+ P✳⁻χ⊗‽ι²+
```
surround the current position with spaces, draw a `-` or `|` in a random matching direction, and finally draw a `+` in the current position.
[Answer]
# JavaScript (ES6), ~~151 147 145~~ 143 bytes
Takes input as `(width)(height)`. Returns a list of pairs of numbered vertices.
```
w=>g=h=>(m=1,n=a=[],F=v=>[++v%w&&v,--v%w&&v-1,v+w,v-w].map(V=>V<0|V/w/h|m>>V&1|Math.random()<.5||F(V,m|=1<<V,n=a.push([v,V]))))``|~n+w*h?g(h):a
```
[Try it online!](https://tio.run/##ZYy9DsIgGEV338PmwwKKP4vph1s3V5amicSfohFobIWF@Oq1xsl4c4abM5ybDro7Pq5tz5w/nYcLDhFlgwYlWBTUocaqpiUGlFWeh2nMskAZ@x4maMgjDSzW3OoWFEpVLJKax7lJVkqVibTXveEP7U7eAin4JqUSFLUJRVGoT5@3z85AFaiqybjDIb1cHmdm14AhWz0cvev8/czvvoELCDJCJr9yRWD5J9dkhAxv "JavaScript (Node.js) – Try It Online")
### Commented
```
w => // w = width
g = h => ( // h = height
m = 1, // m = bitmask of visited vertices
n = // n = number of visited vertices - 1
a = [], // a[] = pairs of connected vertices
F = v => // F is a recursive function, taking the current vertex v
[ ++v % w && v, // try v + 1 if (v + 1) mod w is not equal to 0
// we temporarily increment v to coerce it to a number
--v % w && v - 1, // decrement v; try v - 1 if v mod w is not equal to 0
v + w, // unconditionally try v + w
v - w // unconditionally try v - w
].map(V => // for each new vertex V:
V < 0 | // abort if V is negative
V / w / h | // abort if V is greater than or equal to w * h
m >> V & 1 | // abort if V was already visited
Math.random() < .5 || // abort with 50% probability
F( // otherwise, do a recursive call:
V, // using the new vertex
m |= 1 << V, // update the bitmask of visited vertices
n = a.push([v, V]) // append [v, V] to a[] and update n
) // end of recursive call
) // end of map()
)`` | // initial call to F with v = [''] (zero'ish)
~n + w * h ? // if n is not equal to w * h - 1:
g(h) // try again
: // else:
a // success: return a[]
```
[Answer]
# [R](https://www.r-project.org/), 156 bytes
```
function(w,h){b=rbind(x<-1:(s=w*h),c(x+1,1:(s-h)+h))[,1:w*-h][,sample(s+s-h-w)]
y=b[,1]
while(!all(z<-matrix(b%in%y,2)))y=rbind(y,b[,colSums(z)==1][1:2])
y}
```
[Try it online!](https://tio.run/##VY/BToQwEIbvfYq1SU2ntDHFxMQNfQRPHrGHgrAlYVlC2ZSi@@w4GKPxNv/88898M22t2drrUM/dZeBReviozFR1wztfCqWPPJgoPMiaL5mWu1YeMg9QoohCeVvK4M5j3/CQoaciWJJMhbYl0XfYv3N9z9dCnd08dQuvWDewJHMASD@XksT5@tK/Xs@Br2CMtqU@5hZIum2nQv3nIwjWfpdKk7@99EClF7mMIsdcoaZLfGncEBCcL@yBeeHFI@w1Q3yyljpLtlA1p4pK@klhbzCWW7QwixwoEOUewX6FPRTqQAUltZu5G8c@8VVqObowN/sHvRtDYygFGZrR0LeBAlnIjZz4k3yG7Qs "R – Try It Online")
A function taking the width and height and returning a two-matrix of 1-indexed pairs of points (numbered from top left, moving down and then right). The footer also prints an ASCII representation. Implements [Prim’s algorithm](https://en.wikipedia.org/wiki/Prim%27s_algorithm).
] |
[Question]
[
A [*nondeterministic finite automaton*](https://en.wikipedia.org/wiki/Nondeterministic_finite_automaton) is a finite state machine where a tuple \$(state,symbol)\$ is mapped to multiple states. Ie. we replace the usual \$\delta : Q \times \Sigma \to Q\ \$ transition function of a [DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) with another function \$\Delta : Q \times \Sigma \to \mathcal{P}(Q)\$.
If you know what an NFA is you might want to skip the next section.
### Formal Definition
An NFA is uniquely described by
* \$Q\$ a finite set of states
* \$\Sigma\$ a finite set of symbols
* \$\Delta : Q \times \Sigma \to \mathcal{P}(Q)\$ the transition function
* \$q\_0 \in Q\$ the initial state
* \$F \subseteq Q\$ a set of final states
The machine starts out in \$q\_0\$ and reads a finite string of symbols \$w \in \Sigma^\*\$, for each symbol it will simultaneously apply the transition function function with a current state and add each new set of states to the set of current states.
## Challenge
For this challenge we will ignore \$F\ \$ to simplify it, furthermore the alphabet will always be the (lower-case) letters \$\texttt{a}\ \$ to \$\texttt{z}\ \$ and the set of states will be \$\{0 \dots N\}\$ for some non-negative integer \$N\$. The initial state will always be \$0\$.
Given a word \$w \in \{\texttt{a}\dots\texttt{z}\}^\*\$ and a description of the NFA, your task is to determine all the final states.
### Example
Consider the string \$\texttt{abaab}\$ and the following description:
```
state, symbol, new-states
0, 'a', [1]
1, 'a', [0]
1, 'b', [1,2]
```
The machine will start in \$q\_0 = 0\$:
1. read an \$\texttt{a}\$: new states \$\{1\}\$
2. read a \$\texttt{b}\$: new states \$\{1,2\}\$
3. read an \$\texttt{a}\$: new states \$\{0\}\$
4. read an \$\texttt{a}\$: new states \$\{1\}\$
5. read a \$\texttt{b}\$: new states \$\{1,2\}\$
So the final states and thus the output would be \$\{1,2\}\$.
**Note:** In step *(2)* the transition of state \$2\$ maps to \$\emptyset\$ as the description only includes transitions to non-empty sets.
## Rules
The input will consist of a string and some kind of description of the NFA (without \$\epsilon\$-transitions):
* the input string will always be element of \$\{\texttt{a}\dots\texttt{z}\}^\*\$
* valid inputs (not limited to):
+ list/array of tuples/lists
+ new-line separated input
* the description of the NFA will only contain transitions with non-empty sets as result
+ you may abbreviate rules with the same characters if their result is the same (eg. rules `0,'a',[1,2]` and `0,'b',[1,2]` could be abbreviated with `0,"ab",[1,2]`
+ you may take each rule separate (eg. rule `0,'a',[1,2]` can be `0,'a',[1]` and `0,'a',[2]`)
* you may choose upper-case letters if you want
* you may take the number of states as input
* you may assume some kind of ordering of the inputs (eg. ordered by state or symbols)
The output will be a list/set/new-line separated output etc. of the final states
* order doesn't matter
* no duplicates (as it's a set)
### Test cases
These examples will be in the format `description word -> states` where `description` is a list of tuples `(state,symbol,new-states)`:
```
[] "x" -> []
[] "" -> [0]
[(0,'a',[1]),(1,'a',[0]),(1,'b',[1,2])] "abaab" -> [1,2]
[(0,'a',[1]),(1,'a',[0]),(1,'b',[1,2])] "abc" -> []
[(0,'p',[0,1]),(0,'g',[2]),(1,'c',[1]),(1,'g',[4]),(1,'p',[2]),(2,'c',[0])] "ppcg" -> [2,4]
[(0,'f',[1]),(1,'o',[1,2]),(2,'b',[3]),(3,'a',[4]),(4,'r',[0,4])] "foobar" -> [0,4]
[(0,'f',[1]),(1,'o',[1,2]),(2,'b',[3]),(3,'a',[4]),(4,'r',[0,4])] "fooooooobar" -> [0,4]
[(0,'f',[1]),(1,'o',[1,2]),(2,'b',[3]),(3,'a',[4]),(4,'r',[0,4])] "fobarfo" -> [1,2]
[(0,'f',[1]),(1,'o',[1,2]),(2,'b',[3]),(3,'a',[4]),(4,'r',[0,4])] "foobarrf" -> [1]
[(0,'d',[1,2]),(1,'u',[2]),(2,'u',[2,3]),(2,'p',[3]),(3,'p',[3])] "dup" -> [3]
[(0,'a',[0,2]),(0,'b',[3]),(1,'a',[1]),(1,'b',[1]),(2,'b',[1,4]),(4,'b',[2])] "aab" -> [3,1,4]
[(0,'a',[0,2]),(0,'b',[3]),(1,'a',[1]),(1,'b',[1]),(2,'b',[1,4]),(4,'b',[2])] "abb" -> [1,2]
```
[Answer]
# [Haskell](https://www.haskell.org/), 66 bytes
```
import Data.List
f d=foldl(\s c->nub[r|(y,r)<-d,g<-s,(g,c)==y])[0]
```
[Try it online!](https://tio.run/##Tc7NCoMwEATgu0@xSMENrEV7Np567BtYDxujNjT@kKQHoe@eVtqDt4@BGebB/tlbG6OZ1sUFuHLg8834kAyg5bBYbfHuocvr@aUa98aNnKhyTWOVe8KROiHl1oqmaKPufefMGswyg4QGsaCMM0GlIMTy5@Jvdch3X0SbTGz24urMHOAE3wOHwZQVs0rjBw "Haskell – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 42 bytes
```
,0{hẸ&t|∋₁B∋IhJ&tJ&hhC∧I∋₁C∧It∋S&hb;B,S↰}ᵘ
```
input as [string, nfa]
where nfa is a list of state transitions [ initial state, letter, new states as list ]
# Explanation
```
,0 # Append 0 to the input (initial state)
{ }ᵘ # Find all unique outputs
h # if first element (string)
Ẹ # is empty
&t # then: return last element (current state)
| # else:
∋₁B # save the state transitions in "B"
∋I # take one of these transitions, save in "I"
hJ # take the initial state requirement, store in "J"
&tJ # make sure "J" is actually the current state
&hhC # Save first char of string in C
∧I∋₁C # make sure the char requirement for the state transition is the current char
∧It∋S # Make "S" equal to one of the new states
&hb # Behead the string (remove first char)
;B,S # Add B (the state transitions) and S (the new state)
↰ # recur this function
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X8egOuPhrh1qJTWPOrofNTU6ASnPDC@1Ei@1jAznRx3LPSHiYGYJkB2slpFk7aQT/KhtQ@3DrTP@/49WSkxKTExS0omONtBRSgTShrGxQALCNoCyQfKGOkaxsbH/owA "Brachylog – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 31 bytes
```
{b,Ȯ,Ȯ\c↔,0↔ġ₃kH&hg;Hz{∋ᵈ}ᵐtt}ᵘ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vzpJ58Q6IIpJftQ2RccASBxZ@KipOdtDLSPd2qOq@lFH98OtHbUPt04oKQGSM/7/j46ONtCxNNcxjNWJNgQxDCAMC5iIhY5RLJAFlAEyQSSIERv7PwoA "Brachylog – Try It Online") ([or with a more complex example](https://tio.run/##SypKTM6ozMlPN/r/vzpJ58Q6IIpJftQ2RccASBxZ@KipOdtDLSPd2qOq@lFH98OtHbUPt04oKQGSM/7/j46ONtBRSlTSMYjVgbKMIKwkJR1jIMsQLGYIYSVBWEZoLBMgywTMMooFMkEawDhJKTb2fxQA "Brachylog – Try It Online"))
Brachylog is really good at this sort of problem, and really bad at problems that require two separate inputs and an output. Almost all of this program is just plumbing.
Input format is a list containing two elements: the first is the list of state transitions (`[oldState, symbol, newState]`), and the second is the list of symbols. I originally planned this program to work with character codes for symbols (because Brachylog's string handling can be a bit weird sometimes), but it turns out that characters work too (although you have to write the input string as a list of characters, not as a string). If a state-symbol pair can transition to multiple different states, you write multiple transitions to deal with that.
## Explanation
```
{b,Ȯ,Ȯ\c↔,0↔ġ₃kH&hg;Hz{∋ᵈ}ᵐtt}ᵘ
{ }ᵘ Find all distinct outputs that can result from:
b taking the input minus its first element,
,Ȯ appending a singleton list (i.e. an element)
,Ȯ then appending that same element again
\ and transposing;
c then concatenating the resulting lists,
↔,0↔ prepending a 0,
ġ₃ grouping into blocks of 3 elements
k (and discarding the last, incomplete, block),
H& storing that while we
h take the first input element,
g z pair a copy of it with each element of
;H the stored value,
{ }ᵐ assert that for each resulting element
∋ᵈ its first element contains the second,
ᵈ ᵐ returning the list of second elements,
t then taking the last element of
t the last element.
```
It's probably easier to follow this by looking at what some partial versions of the program would produce. Using the following input each time:
```
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]
```
we can observe the outputs of some prefixes of this program:
```
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ
[[97,98,97,97,98],L,L]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\
[[97,A,A],[98,B,B],[97,C,C],[97,D,D],[98,E,E]]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\c↔,0↔
[0,97,A,A,98,B,B,97,C,C,97,D,D,98,E,E]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\c↔,0↔ġ₃k
[[0,97,A],[A,98,B],[B,97,C],[C,97,D],[D,98,E]]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\c↔,0↔ġ₃kH&hg;Hz
[[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[0,97,A]],
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[A,98,B]],
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[B,97,C]],
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[C,97,D]],
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[D,98,E]]]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\c↔,0↔ġ₃kH&hg;Hz{∋ᵈ}ᵐ
e.g. [[0,97,1],[1,98,1],[1,97,0],[0,97,1],[1,98,1]]
```
For the first example here, `L` is initially an unknown element, but when we transpose it via `\`, Brachylog realises that the only possibility is a list with the same length as the input. The last example here is nondeterministic; we're modelling nondeterminism in the NFA using the nondeterminism in Brachylog itself.
## Possible improvements
Some of the syntax here, like `↔,0↔` and especially the mess with `H&hg;Hz{…ᵈ}ᵐ`, is fairly clunky. It wouldn't surprise me if there were a terser way to phrse this.
`{∋ᵈ}ᵐ` is in its own right a fairly suspicious structure – you'd expect to just be able to write `∋ᵈᵐ` – but it doesn't parse for some reason.
[Answer]
# Python 3, ~~103~~ 80 bytes
*thanks to @BWO*
```
w=lambda n,f,a={0}:w(n,f[1:],{y for(x,c,y)in n if c==f[0]and{x}&a})if''<f else a
```
[TIO](https://tio.run/##LcmxDoMgFIXh3ae4cSiQ3AFsJ1OehDhQFEtikVgTNIZnp0Z6pi/nD/v6nv095ygn/Xn1Gjxa1PLgqY30tBJth8cOdl7ohgZ35jx4cBaMlFbxTvv@2NJNJ@YsIU8Lw/QdQOewOL/SCs5FqihHEghyhn@JopFgc0ogMeUT1/coCqU2V@WsQ6hDMGPNKpZ/)
Previous "elegant" list comprehension(103 bytes):
```
def w(a,b):
q=[0]
for c in b:q=[j for s in q for i in a if s in i if i[1]==c for j in i[2]]
return q
```
[Answer]
# JavaScript (ES6), 99 bytes
Takes input as `(nfa)(string)`. Returns a Set.
```
a=>g=([c,...b],s=[0])=>c?g(b,a.reduce((p,[x,y,z])=>s.includes(x)&y==c?[...p,...z]:p,[])):new Set(s)
```
[Try it online!](https://tio.run/##tdPdboIwFADg@z0F8WK2SUUErkzQh9hl04u2/MSF0AZkU1@e9Term2YmQy7IKZR@55Sed/pBB94f5HHVibKa6mKixa4pAOYojmNG0FDghMBix/cNYIjGfVWOvAJAInxCZ3TR74b40PF2LKsBnODruSj4HquvpV7iQrZqKoFw21Wf0Vt1BAOcuOgG0VZxKxpQA/UWLE4LCKNZr/U6Wu0iTF5uaLNjXkt@cThBS7pEeEOIutk4cTHTz1FKiM6JMkrZo4k5Tn/8D5A/vg/3dlNrUgvIeGrUqFHqPB7koZ/nLpZ@TmrnJDYjKXljUnJaivKbYB0sK3xJZjFdYKbjzBZuwBwte5NibplaCEb7q9r973saaK5AfTaoqFqEJf5xYmbZ0r4ORA/e5MpvQoFjcBxMjDI3kgHuYs2Vo/x5dB2X3e2HxHJJUNHmulOYj1PfKb5WZhM0XWOb1HNoc@cPzkmykNTbNn0B "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 81 bytes
```
function(a,b,e,s)Reduce(function(A,x)unique(e[a%in%A&b==x]),el(strsplit(s,"")),0)
```
[Try it online!](https://tio.run/##PYzRCoMwDEXf9xWlw9lABm3x1YG/sFfpg3ZVCuI6a8G/71p1I9zkJLncJQ51HMKsV/ueWYc9GvTwNK@gDfvfG9wgzPYTDDNtV9i5aG59XW8K0EzMr4t3k12ZR0oBkEO8Mo6lK7HlKJIpb2PaZGaBpU4sTs736mT388jDwxUoQqhzeqTk/iCtxEpdBqZTYC6xlwTUjDqKu8YkfU63c35nr0yqUueARyTELw "R – Try It Online")
Straightforward answer using `Reduce`. Takes rules as three vectors of `state, symbol, new-states` called `a,b,e`.
Rules are separate (eg. rule `0,'a',[1,2]` is `0,'a',1` and `0,'a',2`).
[Answer]
# [Coconut](http://coconut-lang.org/), 64 bytes
```
d->reduce$((s,c)->{r for(*y,r)in d for S in s if[S,c]==y},?,{0})
```
[Try it online!](https://tio.run/##Tc1LCoMwEAbgfU4xSMGkjKJdFmIP4dK6iImRbBKJShHr2VNToXQ137z4pZPOLnPQ/BlUVvleLbK/UDqhZFm1edDO0@uKnhkLKnZQw8EJjG5qlC3n644P3IqdBdVP0ptxNs4Ch4YWmIoUS4a0/Ko41f1mh26sJcNxrenfNyMkJr2cVzEsEZ0QXYIRMpbkTuDcvisYvbFzng/hAw "Coconut – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 68 bytes
This one based on ovs's Haskell solution is a bit shorter than my initial approach was.
*now includes a test harness*
```
import StdEnv
?d=foldl(\s c=removeDup[r\\(y,r)<-d,g<-s|(g,c)==y])[0]
```
[Try it online!](https://tio.run/##vZS7boMwFIbn8hSWOmAkI3Ebg7KkQ6UOlTICg7EBIQG2jEkbqc9eim1I3bRblTCg7/jy/8f2sUlX4WHuGZ26CvS4Hea250xIcJT0aTg5e5rWrKMdzEdAUlH17FQdJp6JPIdnJLydT1Gz88cP2CDipem58LKgmI8SC@k8AlmNcgQpyGBWoMx9d5d/4SHnwcQqDNYYwgC52PVQ6CEIQ8PByqXVrjjy1HRcYlwqjRBF/1EhVlpagG@TVg5XbvQkI0AsMdWerMy3MZEZE2gTzkmjXCKU2Ea1JcKueBNRmcaKY7MabZQgV2xJrpxoo5qxEgu9sXew0t/9/Banmv1x4LfaRlFrM9uKWuVArXKYLKtrjlfmVgqGlRWduHKJryt4K0C8qQXWIsKfVX6p7Og3bwu1Kt7cmhiFP4/sxq7l910tlrehngYiWzYsz8PeSQEeKMgubbQaiWi55jcmKEhTwCbJJwnyHECrG@l@tPZ6YOebV6eYP0nd4Wac/eeX@XAecN8SE7x2WNZM9F8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
⊞υ⁰Fη«≔υζ≔⟦⟧υFζFθ¿∧⁼§λ⁰κ⁼§λ¹ιF§λ²¿¬№υμ⊞υμ»Iυ
```
[Try it online!](https://tio.run/##ZY6xCoMwFEXn5iseTnmQgro6iXToUtxDhqi1SjWiMaVY@u1pohUKHUI471wut2zkVA6yszY3uqGGQYgJqYcJaIPwIodU6/amvFic2JELBsbzmlwQ1n9EaGugqaroaTSy0zSdz6q6Pmnnexnc3fs3kbu2iN@SHxHjVngZZpoNRs1@Ru@T@9jebXiTfGqdy6R2AcTEWs55yCCQAQMeCbeV8Gjn0PGGxapZLPwlkIWURSDs8dF9AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⁰
```
Push `0` to the predefined empty list to set the inital state to \$\{0\}\$.
```
Fη«
```
Loop over the input.
```
≔υζ
```
Copy the state.
```
≔⟦⟧υ
```
Reset the state.
```
Fζ
```
Loop over the copy of the state.
```
Fθ
```
Loop over the NFA entries.
```
¿∧⁼§λ⁰κ⁼§λ¹ι
```
If the entry matches, then...
```
F§λ²
```
... loop over the new states...
```
¿¬№υμ
```
.... if they are not already in the list...
```
⊞υμ»
```
... add them to the list.
```
Iυ
```
Cast the list of states to string for implicit output on separate lines.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~61~~ 54 bytes
```
->\n,\s{set +s&&reduce {n.grep(*[^2]⊆@_)[*;2]},0,|s}
```
[Try it online!](https://tio.run/##tZPRboMgFIbv9xSkSxQ6ahDNbpo1ew/rFlDxZq0EZ7Km6@0u9ph7EScglTa9WeK8wPyHc77/CEdZqbfHfncAgQBP/Wqz3eNte2yrd/DQBoGqyq6owHEf1aqScJm90Pzn@@v5FWXLNc1PmODP9tS37AAEjDKSYxBlcR4VzY4jIBp1ByHCYPGxGNZ7sNoAiMbQFCFYx4ZXyEIMY4yQXo0gTnCzQxHSpYwzxqd6Hf8roLhsSNdKkx7r/EHVg6KuuPCxeid1Qp7TqE3ThtpCyqKePChOnY3wWY3rytTrHhOzldjurU2KQ2XIqUWLpuFM@ec3L9w8/@kwsEVz8/7mOhwlfLyjlxNwwHf@1VmRjEr6Xk5oetnJCZxczC2xYOJ3Gl9NJD8L6kQ6fgQfuzHj6U93guPp9Oc24te/0br/BQ "Perl 6 – Try It Online")
Takes a list of state transitions and an input string as list of characters.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 31 bytes
```
W=[W]c;Ê?ßUÅVVf!øW føUg)mÌc):Wâ
```
[Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=Vz1bV11jO8o/31XFVlZmIfhXIGb4VWcpbcxjKTpX4g==&input=ImFiYWFiIgpbWzAsImEiLFsxXV0sClsxLCJhIixbMF1dLApbMSwiYiIsWzEsMl1dXQotUQ==)
Saved 2 bytes with better use of Japt's ability to implicitly form a function out of some inputs
Explanation:
```
W=[W]c; Initialize the state set to [0] on the first run
Ê? :Wâ If the input is empty return the unique states; else...
Vf!øW Get the transitions valid for one of the current states
føUg) Of those, get the ones valid for the current character
mÌc) Merge the states of the remaining transitions
ßUÅV Repeat with the remaining characters as input
```
The new "initialize states" code could use a bit more detail. Japt initializes `W` to 0 if there are fewer than 3 inputs, so on the first run `[W]` is `[0]`, and `c` "flattens" an array. `[0]` is already as flat as it gets, so it isn't changed. On subsequent runs `W` has a different value, for example `[1,2]`. In that case `[W]` becomes `[[1,2]]`, a single-element array where that element is an array. This time `c` unwraps that and gets back to `[1,2]`. Thus, on the first run it's `W=[0]` and on subsequent runs it's `W=W`.
] |
[Question]
[
Given a *triangulation* of the surface of a polyhedron `p`, calculate its Euler-Poincaré-Characteristic `χ(p) = V-E+F`, where `V` is the number of vertices, `E` the number of edges and `F` the number of faces.
### Details
The vertices are enumerated as `1,2,...,V`. The triangulation is given as a list, where each entry is a list of the vertices of one face, given in clockwise or counterclockwise order.
Despite the name, the triangulation can also contain faces with more than 3 sides. The faces can assumed to be simply connected that means that the boundary of each faces can be drawn using one closed non-self-intersecting loop.
### Examples
**Tetrahedron**: This tetrahedron is convex and has `χ = 2`. A possible triangulation is
```
[[1,2,3], [1,3,4], [1,2,4], [2,3,4]]
```

**Cube**: This cube is convex and has `χ = 2`. A possible triangulation is
```
[[1,2,3,4], [1,4,8,5], [1,2,6,5], [2,3,7,6], [4,3,7,8], [5,6,7,8]]
```

**Donut**: This donut/toroid shape has `χ = 0`. A possible triangulation is
```
[[1,2,5,4], [2,5,6,3], [1,3,6,4], [1,2,7,9], [2,3,8,7], [1,9,8,3], [4,9,8,6], [4,5,7,9], [5,7,8,6]]
```

**Double Donut**: This double-donut should have `χ = -2`. It is constructed by using two copies of the donut above and identifying the sides `[1,2,5,4]` of the first one with the side `[1,3,6,4]` of the second one.
```
[[2,5,6,3], [1,3,6,4], [1,2,7,9], [2,3,8,7], [1,9,8,3], [4,9,8,6], [4,5,7,9], [5,7,8,6], [1,10,11,4], [10,11,5,2], [1,10,12,14], [10,2,13,12], [1,14,13,2], [4,14,13,5], [4,11,12,14], [11,12,13,5]]
```
(Examples verified using [this Haskell program](https://tio.run/##tVPLTsMwELz7K/ZQiURsEUmTviS4UA5IHLlFFnKLaSLStEocaL@@rB95NCpHcvHs7sys145TUX3JPD@fs91hXypYCSXuXrNKMfYpNrKC5RKS5KVQnMP4EQi4vCozeIBcFluV6oCxb1mq7LqkLfVVo6Jewwg2@2IjlLWQH9urepsfikdWOoKdOIDe1dv@uSEy@EllKS/S3nF5rHyy8CoaNTliLioFx4r7sOwTbxyTgf2GpdPA5sT9of70pz555yRNOGObNLsyqs7aQS8ObQzdGdxCewV0ZEQ7qTQrtk7mOQf0@gbY6bGT@z5j6k2qUug9JQGGOOEIBCYYWRBaEJoMZ@qpXsuO3LAinGPcCKYW6vIMpxpGBs4JQhJTXWPyWu2LWrVmcdNJM9ptTLuNzHDR@M5xZrMLghPbQkPXLW64GuisaVavc9m1/Jc@hhvcYxA4OwNjDLtKiEFTIjihhKtFOgqtsQ1iFwQ9lcW6Rr8Q24msoGkOZVYoekvmJfT@iMReLoK5NlrM@GZtD4Oz8/kX).)
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
f m=maximum(id=<<m)-sum[0.5|_:_:l<-m,x<-l]
```
[Try it online!](https://tio.run/##tY3NasMwEITvfgodemhhHaI/2wnWkwgRDE2oqTeEWoEc@u7urn6avkAPgm9nRjMf0/p5XpZtuwh0OD1mvOPr/O7GEd/a9Y5@v7Pfp@PpuIwtwmNsl7BF6byXoEAHEAQaTAaVQSUlNFHVXA0YGMDWbJeR7R46RpNwIBTeks9MNbrU2FrP3u9291zv4VAbB@izeiDUuZyx7NiaZWCVZgzN/Et3yso9SFnqElpQT0eBrBahJqF4hi@Vi/NhyyH//MrMXmiaeF7jKpzwUYKIip6mZ0KD03x1t6/5Gl9wuomLSMntBw "Haskell – Try It Online")
Combines the face and edge terms by subtracting 0.5 for every edge on a face beyond the first two.
Alt 42 bytes:
```
f m=maximum(id=<<m)-sum(0.5<$(drop 2=<<m))
```
[Try it online!](https://tio.run/##tY1LjsIwEET3OUUvWIDUg3DbToIUnyTKIhIgosEQESPN7TPd/gxzARaWXleVq67j8n2@3db1At758WfyL7@dTq7r/O5rYT7sbbfZnp6PGSiquzUo1/cKCfWAwKDRJKAEFJWhClRyJWCwRVuydUKxG6wFTcSWEXrLvjDX6FxjS714f9v1e73BY2lssUnqkVGncsG8Y0tWQFSeMTzzke6YVQdUKtdFtEhvh1AVi1GzkD0jF6XidNh8qH@/Eos3VFU4L2EBB31QCIH4aX5mqPw43d38nO5h48cZLhCT6y8 "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~49~~ 46 bytes
```
u=length
f x|j<-x>>=id=maximum j+u x-u j`div`2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v9Q2JzUvvSSDK02hoibLRrfCzs42M8U2N7EiM7c0VyFLu1ShQrdUISshJbMsweh/bmJmnm1BUWZeiUpadLShjpGOcayOApBhrGMCYRhBGEZgkdj/AA "Haskell – Try It Online")
I get the number of vertices by concating the faces and finding the maximum. I find the number of faces by taking the length. I find the number of edges by summing the lengths of the faces and dividing by 2.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 13 bytes
```
⌈/∘∊+≢-2÷⍨≢∘∊
```
[Try it online!](https://tio.run/##rY09boNAEEZ7n2I6QBYyu7D8@DbIERYKEhamsSx3VkScEKWJlDqVu1RRpJTxTeYieGYHcwI3zJs3H9/mm8p/2OVVvfZXVb7dlqsB3z7KGp/eg6GgL752C@w@sTvN8fnL15df7M9E4oahpcwe@x9SDWGB/d/SKfKycojIN/hydOpH5zBzFWgIPRohRJ7daGi7taDHu5wiSMFIJmbgQwKx50YWUs81dGCY/jTSxn58JL49k0AmFSkkbDKCkLsYbKmRDA82LQSze3VRRgWglC2wYEDfrAYlmiCk1fqIWXOVoLGoprQQ@xb@v/UV "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~17~~ ~~11~~ ~~10~~ 9 bytes
*1 byte thanks to Erik the Outgolfer, and 1 more for telling me about `Ɗ`.*
```
FṀ_FLHƊ+L
```
[Try it online!](https://tio.run/##Tcy9EYMwDAXgVejziki2@VmAo/AGPi5VGo4F6FKzURbIHkwiZMsc6T69J2l5r@smMh7fz2uM029/RBFJiRHQws1oEsEpvZHRYchkTXt0lg7KsusLW2O4djNqSqAniOq7wgC@GwZdldJpUDufJ7bHNoQ60N@VOXfzCQ)
Uses the actually intelligent not-hacked-together solution everybody else is probably using. (Credit to [@totallyhuman](https://codegolf.stackexchange.com/a/158169/30164) for the only other solution I could understand enough to reimplement it.)
## Old solution (17 bytes)
```
ṙ€1FżFṢ€QL
;FQL_Ç
```
[Try it online!](https://tio.run/##y0rNyan8///hzpmPmtYYuh3d4/Zw5yIgM9CHy9ot0Cf@cPv///@jo410THXMdIxjdRSiDXWMgUwTCNNIx1zHEsQ0Aopa6JhDRC2BTLBaEzDTDMI0hakFMaCihjqGBjqGhlDjwExTHSOEjJGOIUwKyDQGCkDlTEA8I4jBEI4plGOIpAvCBsnFAgA)
I hope I got everything right. Assumes that all faces contain at least 3 vertices and that no two faces have the same vertices; I'm not good enough in topology to come up with something that breaks the code.
Alternative 17 byte solution:
```
ṙ€1FżFṢ€,;F$QL$€I
```
### Explanation
```
;FQL_Ç Main link. Argument: faces
e.g. [[1,2,3],[1,3,4],[1,2,4],[2,3,4]]
F Flatten the list. We now have a flat list of vertices.
e.g. [1,2,3,1,3,4,1,2,4,2,3,4]
; Append this to the original list.
e.g. [[1,2,3],[1,3,4],[1,2,4],[2,3,4],1,2,3,1,3,4,1,2,4,2,3,4]
Q Remove duplicates. We now have a list of faces and vertices.
e.g. [[1,2,3],[1,3,4],[1,2,4],[2,3,4],1,2,3,4]
L Get the length of this list. This is equal to V+F.
e.g. 8
Ç Call the helper link on the faces to get E.
e.g. 6
_ Subtract the edges from the previous result to get V-E+F.
e.g. 2
ṙ€1FżFṢ€QL Helper link. Argument: faces
e.g. [[1,2,3],[1,3,4],[1,2,4],[2,3,4]]
ṙ€1 Rotate each face 1 position to the left.
e.g. [[2,3,1],[3,4,1],[2,4,1],[3,4,2]]
F Flatten this result.
e.g. [2,3,1,3,4,1,2,4,1,3,4,2]
F Flatten the original faces.
e.g. [1,2,3,1,3,4,1,2,4,2,3,4]
ż Pair the items of the two flattened lists.
e.g. [[2,1],[3,2],[1,3],[3,1],[4,3],[1,4],[2,1],[4,2],[1,4],[3,2],[4,3],[2,4]]
Ṣ€ Order each edge.
e.g. [[1,2],[2,3],[1,3],[1,3],[3,4],[1,4],[1,2],[2,4],[1,4],[2,3],[3,4],[2,4]]
Q Remove duplicates. We now have a list of edges.
e.g. [[1,2],[2,3],[1,3],[3,4],[1,4],[2,4]]
L Get the length of the list to get E.
e.g. 6
```
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 29 bytes
This one is tailor made for the perl `-a` option which does almost all the work already
```
#!/usr/bin/perl -a
@V[@F]=$e+=@F}{say$#V+$.-$e/2
```
[Try it online!](https://tio.run/##LYs/D4IwEMX3foqX2I2AvWsLMpAwsbmyGAcGBhMjRFyM8atb76rL/d6fe@t8v8aU@vHUD@fOzkXXD@/XNj3tbixsVdp5zykxImp4Q/DCIGQ0aA2LP6AR3wq9CZm1MOZer3oCORDpMjOCDQX8YtaQQT5LaO6lD38V9TPoSmu9Of0s6@Oy3LZUTqk8xopc5b4 "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
*-1 byte thanks to... user56656 (was Wheat Wizard originally).*
```
lambda l:len(l)-len(sum(l,[]))/2+max(sum(l,[]))
```
[Try it online!](https://tio.run/##XYtNDoIwGET3nGISN622MRYXhoSlHoENuqjwVUhKIaX4cwKP55FQdGNYzcubme4RqtapcQG5lCjasnaXBEMwcjeZKFrg9WQdR4pM7lcHgVtFnpCh7hEqghuaM3m0BlfyoS6oF9jPGiov1EO7EodZY/TnEEUmPY5WN@dSwyaWHLNcTtEPDbMiP3G@VqtG3//E2PnaBWZYnm@EEvFJ4AOx2P5A/UB9zTR/Aw "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
-3 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).
```
Max@#-Tr[Tr/@(1^#)/2-1]&
```
[Try it online!](https://tio.run/##vY5LCoMwEIavMhiQFiI2MfGxaPEChS7ciYVQKnVhF@KiIJ49zbPRC3QRmG/mn/kyivn1HMU8PITs4QzyKj41Spqpbaa0PpA7OqY0IV0sb9PwnluEIYLkAhGGvkVdBzGkNSzLQjBQDNmKQZcZBuZK6krqurr26ZBiGEoMPOzkjmysUA1NzFOpiZuYoc1VHoQ2sPlUvvuX2qyCQ/kLN6sMZc5oyft52LOlmRn/X412j5zUI97hQKXodq5s5BfQkOmmTzDboM7mmXsmuwueTGJd5Rc "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ÑF4╨Ω◙╜#├
```
[Run and debug online](https://staxlang.xyz/#p=a54634d0ea0abd23c3&i=[[1,2,3],+[1,3,4],+[1,2,4],+[2,3,4]]%0A[[1,2,3,4],+[1,4,8,5],+[1,2,6,5],+[2,3,7,6],+[4,3,7,8],++[5,6,7,8]]%0A[[1,2,5,4],+[2,5,6,3],+[1,3,6,4],+[1,2,7,9],+[2,3,8,7],+[1,9,8,3],+[4,9,8,6],+[4,5,7,9],+[5,7,8,6]]%0A[[2,5,6,3],+[1,3,6,4],+[1,2,7,9],+[2,3,8,7],+[1,9,8,3],+[4,9,8,6],+[4,5,7,9],+[5,7,8,6],+[1,10,11,4],+[10,11,5,2],+[1,10,12,14],+[10,2,13,12],+[1,14,13,2],+[4,14,13,5],+[4,11,12,14],+[11,12,13,5]]&a=1&m=2)
It's a straight-forward port of totallyhuman's [python solution](https://codegolf.stackexchange.com/a/158169/527).
```
% length of input (a)
x$Y flatten input and store in y
%h half of flattened length (b)
- subtract a - b (c)
y|M maximum value in y (d)
+ add c + d and output
```
[Run this one](https://staxlang.xyz/#c=%25%09length+of+input+%28a%29%0Ax%24Y%09flatten+input+and+store+in+y%0A%25h%09half+of+flattened+length+%28b%29%0A-%09subtract+a+-+b+%28c%29%0Ay%7CM%09maximum+value+in+y+%28d%29%0A%2B%09add+c+%2B+d+and+output&i=[[1,2,3],+[1,3,4],+[1,2,4],+[2,3,4]]%0A[[1,2,3,4],+[1,4,8,5],+[1,2,6,5],+[2,3,7,6],+[4,3,7,8],++[5,6,7,8]]%0A[[1,2,5,4],+[2,5,6,3],+[1,3,6,4],+[1,2,7,9],+[2,3,8,7],+[1,9,8,3],+[4,9,8,6],+[4,5,7,9],+[5,7,8,6]]%0A[[2,5,6,3],+[1,3,6,4],+[1,2,7,9],+[2,3,8,7],+[1,9,8,3],+[4,9,8,6],+[4,5,7,9],+[5,7,8,6],+[1,10,11,4],+[10,11,5,2],+[1,10,12,14],+[10,2,13,12],+[1,14,13,2],+[4,14,13,5],+[4,11,12,14],+[11,12,13,5]]&a=1&m=2)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 28 bytes
```
x->#x+#Set(y=concat(x))-#y/2
```
[Try it online!](https://tio.run/##tY09DoMwDEavEsECqqM2gfAzwCU6IgaESlWpohFiCKencZxAL9Dt2e/zZz0sL/7U@8QathvexuYS3x9rsjXjZx6HNTFpyuPtKvdB6/eWGMZbppfXbA2LcIjYhCFgXdcJkJD1FgVkkBNIAuk2SJQKOocKVEgWhKhLKBBzhxWishrx6FChGc3xtjgfl1CHugpK2tYWM2pG9E9UyCLg1j35S7PLihsI4escKpCnkSCCspjZhXc5TpKKaVB@ED9XxOj6Pt2/ "Pari/GP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes
```
ZsgI˜g;-+
```
[Try it online!](https://tio.run/##TczBDYMwDAXQVbjzkbAThyImYIVGHKhUZQDWYSOGSp04iN6e/7c9yv6hb87vI63XmZahzzlGhiDAbegiwSm9kTFhLmRNX5gsnZV111cGo9y7BS0l0Aii9q5SwE/DoLtSOg1a58vE9tgGaQP9XZlLt/0A "05AB1E – Try It Online")
**Explanation**
```
Z # push number of vertices (V)
sg # push number of faces (F)
I˜g; # push number of edges (E)
- # subtract (F-E)
+ # add (F-E+V)
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 12 bytes
```
+-eSsQ/lsQ2l
```
**[Try it here](https://pyth.herokuapp.com/?code=%2B-eSsQ%2FlsQ2l&input=%5B%5B2%2C5%2C6%2C3%5D%2C+%5B1%2C3%2C6%2C4%5D%2C+%5B1%2C2%2C7%2C9%5D%2C+%5B2%2C3%2C8%2C7%5D%2C+%5B1%2C9%2C8%2C3%5D%2C+%5B4%2C9%2C8%2C6%5D%2C+%5B4%2C5%2C7%2C9%5D%2C+%5B5%2C7%2C8%2C6%5D%2C+%5B1%2C10%2C11%2C4%5D%2C+%5B10%2C11%2C5%2C2%5D%2C+%5B1%2C10%2C12%2C14%5D%2C+%5B10%2C2%2C13%2C12%5D%2C+%5B1%2C14%2C13%2C2%5D%2C+%5B4%2C14%2C13%2C5%5D%2C+%5B4%2C11%2C12%2C14%5D%2C+%5B11%2C12%2C13%2C5%5D%5D&debug=0)**
[Answer]
# [Scala 3](https://www.scala-lang.org/), 46 bytes
A port of [@Wheat Wizard♦'s Haskell answer](https://codegolf.stackexchange.com/a/158165/110802) in Scala.
---
```
x=>{val j=x.flatten;j.max+x.length-j.length/2}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RYwxDoJAEEV7TjElxAUjWBjMmliaaGWsDMWIu8hmXQ2MBmM8iQ0Wegav4m3ElYRm_rw_f_79VaaoMao_78NGiZRggbmBqwOwFRL2DbhYZGUM06LAy3pJRW6yxIthZXICbpMAZ9SwRcLGmOcluXYMWMgij0ELERt2EHYQ2otne45NO2njSvfXZs2b49h6Gdv42o6ZoSThk0aAP08k_dEnqPjk-gsqXgVSI5EwYxXssepVgRYmo52v2qUf3v5fj1br-q9f)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes
```
{(#x)+(|/y)--2!#y}/,/\
```
[Try it online!](https://ngn.codeberg.page/k#eJytkE0SwiAMhfecAqcbGGUo4a81V3HdM9hR724SaF3pxrLJFx7wXliuDzPc7dk8/Wqdg9OwvvzF35RajAkIGC1SjZikglSQ3mqvQR++duNumXDC3M2LEGsVC1ESmogyaUx/hNqMc5+Rn9ymL/v8FeceYcIqezNRlDBMLVbu57jyHscafxkfa8fnwoiBfs8qrU3jjLArgEEsRvIIkfqmJG5A3mycG4fPjYas8FDu+2erN7LubE8=)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->a{a.size+a.flatten!.max-a.size/2}
```
[Try it online!](https://tio.run/##tY7JDsIwDETvfEU54xaydTnAj0Q5BKmVkAAh2kos4ttDHCe0cOf2PDP2@Dru767bunxnn7boD492ZYvuaIehPS@Lk73lpK75y13Goc86rTUDDsJA5kGAJOAEPCjGLL7DKSWhBpUWSkK0KygRZcDaY6aV95F/b6lUhIHPF@X0RwVNOltDRWrjUVADYixTKYuA6rzrLwUhyzbAWDwXUAGfHA4sWR6FF6InceJ0mAYVBzbbIkbPGPcG "Ruby – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 35 bytes
```
l=>max(f=sum(l,[]))-len(f)/2+len(l)
```
[Try it online!](https://tio.run/##KyjKL8nP@59m@z/H1i43sUIjzba4NFcjRyc6VlNTNyc1TyNNU99IG8TI0fxfUJSZV6KRphEdbahjpGMcq6MAZBjrmEAYRhCGEVgEqP0/AA "Proton – Try It Online")
[Answer]
## JavaScript (ES6), 60 bytes
```
a=>a.map(b=>(v=Math.max(v,...b),d+=b.length/2-1),d=v=0)&&v-d
```
Explanation: Loops over each face, keeping track of the largest vertex seen in `v` and tracking the number of edges minus the number of faces in `d` as per @xnor's answer.
] |
[Question]
[
The famous Fibonacci sequence is `F(0) = 0; F(1) = 1; F(N+1) = F(N) + F(N-1)` (for this challenge we are beginning with 0).
Your challenge: Given *n*, output the sum of all the *d*th Fibonacci numbers for all divisors *d* of the *n*th Fibonacci number. If you prefer more formal notation,
%7DF(d))
**Input**: a positive integer *n*
**Output**: the sum
For example, consider `n=4`. `F(4) = 3`The divisors of 3 are 1 and 3, so the output should be `F(1) + F(3) = 1 + 2 = 3`.
For `n=6`, `F(6) = 8`, and the divisors of 8 are 1, 2, 4, 8, so the output is `F(1) + F(2) + F(4) + F(8) = 1 + 1 + 3 + 21 = 26`.
Test Cases:
```
1 => 1
2 => 1
3 => 2
4 => 3
5 => 6
6 => 26
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ÆḞÆDÆḞS
```
[Try it online!](https://tio.run/##y0rNyan8//9w28Md8w63uYDp4P///5sBAA "Jelly – Try It Online")
Explanation:
```
ÆḞÆDÆḞS Main link (Arguments: z)
ÆḞ zth Fibonacci number's
ÆD divisors'
ÆḞ Fibonacci numbers'
S sum
```
[Answer]
## Mathematica, 29 bytes
```
f=Fibonacci;f@#~DivisorSum~f&
```
[Answer]
# [Mathematica Simplified](https://github.com/1ekf/Mathematica-Simplified/blob/master/README.md), 14 bytes
```
Fi@#~Div9`~Fi&
```
Oh well, this ended up being identical to @MartinEnder's solution...
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
MgU â x@MgX
```
[Try it online!](https://tio.run/nexus/japt#@@@bHqpweJFChYNvesT//2YA "Japt – TIO Nexus")
[Answer]
## [Alice](https://github.com/m-ender/alice), ~~38~~ 36 bytes
*Thanks to Leo for saving 2 bytes.*
```
/ow;B1dt&w;31J
\i@/01dt,t&w.2,+k;d&+
```
[Try it online!](https://tio.run/nexus/alice#@6@fX27tZJhSolZubWzoxRWT6aBvAOTqAAX0jHS0s61T1LT//zcDAA "Alice – TIO Nexus")
Almost certainly not optimal. The control flow is fairly elaborate and while I'm quite happy with how many bytes that saved over previous versions, I have a feeling that I'm overcomplicating things that there might be a simpler *and* shorter solution.
### Explanation
First, I need to elaborate a bit on Alice's return address stack (RAS). Like many other fungeoids, Alice has a command to jump around in the code. However, it also has commands to return to where you came from, which lets you implement subroutines quite conveniently. Of course, this being a 2D language, subroutines really only exist by convention. There's nothing stopping you from entering or leaving a subroutine through other means than a return command (or at any point in the subroutine), and depending on how you use the RAS, there might not be a clean jump/return hierarchy anyway.
In general, this is implemented by having the jump command `j` push the current IP address to the RAS before jumping. The return command `k` then pops an address of the RAS and jumps there. If the RAS is empty, `k` does nothing at all.
There are also other ways to manipulate the RAS. Two of these are relevant for this program:
* `w` pushes the current IP address to the RAS *without* jumping anywhere. If you repeat this command you can write simple loops quite conveniently as `&w...k`, which I've already done in past answers.
* `J` is like `j` but *doesn't* remember the current IP address on the RAS.
It's also important to note that the RAS stores no information about the *direction* of the IP. So returning to an address with `k` will always preserve the *current* IP direction (and therefore also whether we're in Cardinal or Ordinal mode) regardless of how we passed through the `j` or `w` that pushed the IP address in the first place.
With that out the way, let's start by looking into the subroutine in the above program:
```
01dt,t&w.2,+k
```
This subroutine pulls the bottom element of the stack, **n**, to the top and then computes the Fibonacci numbers **F(n)** and **F(n+1)** (leaving them on top of the stack). We never need **F(n+1)**, but it will be discarded outside the subroutine, due to how `&w...k` loops interact with the RAS (which sort of requires these loops to be at the *end* of a subroutine). The reason we're taking elements from the bottom instead of the top is that this lets us treat the stack more like a queue, which means we can compute all the Fibonacci numbers in one go without having to store them elsewhere.
Here is how this subroutine works:
```
Stack
01 Push 0 and 1, to initialise Fibonacci sequence. [n ... 0 1]
dt, Pull bottom element n to top. [... 0 1 n]
t&w Run this loop n times... [... F(i-2) F(i-1)]
. Duplicate F(i-1). [... F(i-2) F(i-1) F(i-1)]
2, Pull up F(i-2). [... F(i-1) F(i-1) F(i-2)]
+ Add them together to get F(i). [... F(i-1) F(i)]
k End of loop.
```
The end of the loop is a bit tricky. As long as there's a copy of the 'w' address on the stack, this starts the next iteration. Once those are depleted, the result depends on how the subroutine was invoked. If the subroutine was called with 'j', the last 'k' returns there, so the loop end doubles as the subroutine's return. If the subroutine was called with 'J', and there's still an address from earlier on the stack, we jump there. This means if the subroutine was called in an outer loop itself, this 'k' returns to the beginning of that *outer* loop. If the subroutine was called with 'J' but the RAS is empty now, then this 'k' does nothing and the IP simply keeps moving after the loop. We'll use all three of these cases in the program.
Finally, on to the program itself.
```
/o....
\i@...
```
These are just two quick excursions into Ordinal mode to read and print decimal integers.
After the `i`, there's a `w` which remembers the current position before passing into the subroutine, due to the second `/`. This first invocation of the subroutine computes `F(n)` and `F(n+1)` on the input `n`. Afterwards we jump back here, but we're moving east now, so the remainder of the program operators in Cardinal mode. The main program looks like this:
```
;B1dt&w;31J;d&+
^^^
```
Here, `31J` is another call to the subroutine and therefore computes a Fibonacci number.
```
Stack
[F(n) F(n+1)]
; Discard F(n+1). [F(n)]
B Push all divisors of F(n). [d_1 d_2 ... d_p]
1 Push 1. This value is arbitrary. [d_1 d_2 ... d_p 1]
The reason we need it is due to
the fact that we don't want to run
any code after our nested loops, so
the upcoming outer loop over all
divisors will *start* with ';' to
discard F(d+1). But on the first
iteration we haven't called the
subroutine yet, so we need some
dummy value we can discard.
dt&w Run this loop once for each element [d_1 d_2 ... d_p 1]
in the stack. Note that this is once OR
more than we have divisors. But since [d_i d_(i+1) ... F(d_(i-1)) F(d_(i-1)+1)]
we're treating the stack as a queue,
the last iteration will process the
first divisor for a second time.
Luckily, the first divisor is always
1 and F(1) = 1, so it doesn't matter
how often we process this one.
; Discard the dummy value on the [d_1 d_2 ... d_p]
first iteration and F(d+1) of OR
the previous divisor on subsequent [d_i d_(i+1) ... F(d_(i-1))]
iterations.
31J Call the subroutine without pushing [d_(i+1) ... F(d_i) F(d_i+1)]
the current address on the RAS.
Thereby, this doubles as our outer
loop end. As long as there's an
address left from the 'w', the end
of the subroutine will jump there
and start another iteration for the
next divisor. Once that's done, the
'k' at the end of the subroutine will
simply do nothing and we'll continue
after it.
; Discard the final F(d_i+1).
d&+ Get the stack depth D and add the top [final result]
D+2 values. Of course that's two more
than we have divisors, but the stack is
implicitly padded with zeros, so that
doesn't matter.
```
[Answer]
# [Actually](https://github.com/Mego/Seriously), 5 bytes
```
F÷♂FΣ
```
[Try it online!](https://tio.run/##S0wuKU3Myan8/9/t8PZHM5vczi3@/98MAA "Actually – Try It Online")
### How it works
```
(implicit) Read n from STDIN.
F Compute F(n).
÷ Get F(n)'s divisors.
♂F Map F over the divisors.
Σ Take the sum.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
!ÅFDI<èÑ<èO
```
[Try it online!](https://tio.run/nexus/05ab1e#@694uNXNxdPm8IrDE4GE////ZgA "05AB1E – TIO Nexus")
**Explanation**
```
! # factorial of input
ÅF # get the list of fibonacci numbers (starting at 1)
# smaller than or equal to this
D # duplicate list of fibonacci number
I<è # get the element at index (input-1)
Ñ # get the list of its divisors
< # decrement each
è # get the fibonacci numbers at those indices
O # sum
```
[Answer]
## Haskell, 54 bytes
```
f=0:scanl(+)1f
g x=sum[f!!d|d<-[1..f!!x],mod(f!!x)d<1]
```
Usage example: `g 6` -> `26`. [Try it online!](https://tio.run/nexus/haskell#@59ma2BVnJyYl6OhrWmYxpWuUGFbXJobnaaomFKTYqMbbainB2RXxOrk5qdogFiaKTaGsf9zEzPzFGwVUvK5FBQKijLzShRUFNIVTFF4Zig88/8A "Haskell – TIO Nexus")
[Answer]
# R, 77 bytes
```
F=gmp::fibnum;N=F(scan());i=n=N-N;while(i<N)if(N%%(i=i+1)<1)n=n+F(i);print(n)
```
Makes use of the 'gmp' library. This has a builtin Fibonacci function and provides the ability to do large numbers. It caused a few issues with seqs and applys, though it is still smaller than creating my own Fibonacci function.
**Explanation**
```
F=gmp::fibnum; # Set F as fibnum function
N=F(scan()); # get input and set N to the fibonacci number of that index
i=n=N-N; # set i and n to 0 with data type bigz
while(i<N) # loop while i < N
if(N%%(i=i+1)<1) # if incremented i is divisor of N
n=n+F(i); # add F(i) to rolling sum
print(n) # output final result
```
**Test**
```
> F=gmp::fibnum;N=F(scan());i=n=N-N;while(i<N)if(N%%(i=i+1)<1)n=n+F(i);print(n)
1: 6
2:
Read 1 item
Big Integer ('bigz') :
[1] 26
> F=gmp::fibnum;N=F(scan());i=n=N-N;while(i<N)if(N%%(i=i+1)<1)n=n+F(i);print(n)
1: 10
2:
Read 1 item
Big Integer ('bigz') :
[1] 139583862540
> F=gmp::fibnum;N=F(scan());i=n=N-N;while(i<N)if(N%%(i=i+1)<1)n=n+F(i);print(n)
1: 15
2:
Read 1 item
Big Integer ('bigz') :
[1] 13582369791278266616906284494806735565776939502107183075612628411498802812823029319917411196081011510136735503204397274473084444
```
**Without using gmp**
**81 bytes**, Recursive function that is hopelessly slow when large (9+) numbers are picked
```
F=function(n)`if`(n<2,n,F(n-1)+F(n-2));sum(sapply(which((N=F(scan()))%%1:N<1),F))
```
**88 bytes**, Binet's formula that will work reasonably well with larger numbers, but still hits integer limit quite quickly
```
F=function(n)round(((5+5^.5)/10)*((1+5^.5)/2)^(n-1));sum(F(which(F(N<-scan())%%1:N<1)))
```
[Answer]
# Axiom, 68 bytes
```
g==>fibonacci;f(x:NNI):NNI==(x<3=>1;reduce(+,map(g,divisors(g(x)))))
```
some test
```
(46) -> [[i,f(i)] for i in [0,1,2,3,4,5,6,10,15] ]
(46)
[[0,1], [1,1], [2,1], [3,2], [4,3], [5,6], [6,26], [10,139583862540],
[15,
135823697912782666169062844948067355657769395021071830756126284114988028_
12823029319917411196081011510136735503204397274473084444
]
]
Type: List List NonNegativeInteger
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes
```
n->sumdiv((f=fibonacci)(n),x,f(x))
```
[Try it online!](https://tio.run/nexus/pari-gp#Dco9DoAgDAbQqzRObVIGFze4i2JKvsFi8CfcHl3e9ApFGh7S9Rw7XmaLhq36mjOEXbSrcRcZVhsjzkqL0tngN4MmCumnMOQfHw "Pari/GP – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~89~~ 84 bytes
-5 bytes thanks to ovs
```
lambda n:sum(f(i)for i in range(1,f(n)+1)if f(n)%i<1)
f=lambda x:x<3or f(x-1)+f(x-2)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfbhvzPycxNyklUSHPqrg0VyNNI1MzLb9IIVMhM0@hKDEvPVXDUCdNI09T21AzM00BxFLNtDHU5EqzheqrsKqwMQbqSNOo0DXU1AZRRpr/0cww17TiUigoyswrUcjUSQfa8f8/AA "Python 2 – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 49 bytes
```
{my \f=0,1,*+*...*;sum f[grep f[$_]%%*,1..f[$_]]}
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 26 bytes
```
qi_[XY@{_2$+}*]_@\f%:!.*:+
```
[Try it online!](https://tio.run/nexus/cjam#@1@YGR8dEelQHW@kol2rFRvvEJOmaqWop2Wl/f@/GQA "CJam – TIO Nexus")
I'm sure it can be done better. Explanation:
The idea is to have an array of Fibonacci numbers and dot product it with an array with 1s and 0s if that number is or is not a divisor of the input.
```
qi Read the input (n)
[XY ] Array starting with [1,2,...]
_ @{_2$+}* Append n times the sum of the previous two
_ Duplicate the array
@\f% Modulo each item with n (0 if divisor, a number otherwise)
:! Logical NOT everything (1 if divisor, 0 otherwise)
.*:+ Dot product those two arrays
```
[Answer]
## JavaScript (ES6), ~~76~~ 65 bytes
```
f=(n,i=k=(F=n=>n>1?F(n-1)+F(n-2):n)(n))=>i&&(k%i?0:F(i))+f(n,i-1)
```
### Test cases
```
f=(n,i=k=(F=n=>n>1?F(n-1)+F(n-2):n)(n))=>i&&(k%i?0:F(i))+f(n,i-1)
console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))
console.log(f(5))
console.log(f(6))
```
[Answer]
# JavaScript (ES6), ~~105~~ ~~104~~ ~~103~~ ~~101~~ 97 bytes
```
i=>[...Array((g=(n,x=0,y=1)=>n--?g(n,y,x+y):x)(i)+1)].map((_,y)=>s+=g((z=g(i)/y)%1?0:z|0),s=0)&&s
```
---
## Try it
```
f=
i=>[...Array((g=(n,x=0,y=1)=>n--?g(n,y,x+y):x)(i)+1)].map((_,y)=>s+=g((z=g(i)/y)%1?0:z|0),s=0)&&s
o.innerText=f(j.value=4)
oninput=_=>o.innerText=f(+j.value)
```
```
<input id=j type=number><pre id=o>
```
[Answer]
## Q, 75 bytes
```
{f:{$[x<2;x;.z.s[x-1]+.z.s[x-2]]};sum f each m where(~)b mod m:1+til b:f x}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~93~~ ~~90~~ 80 bytes
```
F(n){n=n<2?n:F(n-1)+F(n-2);}i,s;f(n){for(s=0,i=F(n);i;i--)s+=F(n)%i?0:F(i);n=s;}
```
[Try it online!](https://tio.run/##HYtNCsMgEIX3niIEBAcV0mwKnUh2OUU3wdR2hE5K7C547K5tzNs8vvfj7dP7UibFsLPjoR/5doC9gK7WA2YyCUPtw7qp5DpDrs6RkKyFpE@SNHbHkQDZJcwl4nsmViB20RyqV9Q6DleEM6j6bMTfoNpJyQUaudy5NdEEFQFQ5PLj1frZvx5/ "C (gcc) – Try It Online")
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 89 bytes
```
D,f,@@@@*,V$2D+G1+dAppp=0$Qp{f}p
D,r,@,¿1=,1,bM¿
D,g,@,¿1_,1_001${f},1¿{r}
D,d,@,{g}dF€gs
```
[Try it online!](https://tio.run/##S0xJKSj4/99FJ03HAQi0dMJUjFy03Q21UxwLCgpsDVQCC6rTagu4XHSKdBx0Du03tNUx1EnyPbQfKJIOEYnXMYw3MDBUAarTMTy0v7qoFiiXApSrTq9NcXvUtCa9@P///2b/8gtKMvPziv/r6mbmFuRkJmeWAJnFBanJmWmVtikA "Add++ – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ṁ!İfḊ!İf
```
[Try it online!](https://tio.run/##yygtzv7//@HORsUjG9Ie7ugCUf///zcDAA "Husk – Try It Online")
] |
[Question]
[
You should write 3 programs and/or functions in one language.
All of these programs should solve the same task but they all should give different (but valid) outputs. (I.e. for every pair of programs their should be some input which generates different (but valid) sets of output numbers.)
## The task
* You are given an integer `n`, greater than 1
* You should return or output `n` **distinct** positive integers, and **none of them should be divisible by `n`**.
* The order of the numbers doesn't matter and a permutation of numbers doesn't count as different outputs.
A valid triplet of programs with some `input => output` pairs:
```
program A:
2 => 5 9
4 => 5 6 9 10
5 => 2 4 8 7 1
program B:
2 => 1 11
4 => 6 9 1 2
5 => 4 44 444 4444 44444
program C (differs only in one number from program B):
2 => 1 13
4 => 6 9 1 2
5 => 4 44 444 4444 44444
```
## Scoring
* Your score is the sum of the lengths of the 3 programs or functions.
* Lower score is better.
* If your programs/functions share code, the shared code should be counted into the length of every program that uses the code.
[Answer]
# J, 16 bytes
### Function 1, 5 bytes
```
p:^i.
```
### Function 2, 6 bytes
```
+p:^i.
```
### Function 3, 5 bytes
```
>:^i.
```
## How it works
### Function 1
```
p:^i. Right argument: y
i. Compute (0 ... y-1).
p: Compute P, the prime at index y (zero-indexed).
^ Return all powers P^e, where e belongs to (0 ... y-1).
```
Since **P** is prime and **P > y**, **y** cannot divide **Pe**.
### Function 2
```
+p:^i. Right argument: y
p:^i. As before.
+ Add y to all results.
```
If **y** divided **Pe + y**, it would also divide **Pe + y - y = Pe**.
### Function 3
```
>:^i. Right argument: y
i. Compute (0 ... y-1).
>: Compute y+1.
^ Return all powers (y+1)^e, where e belongs to (0 ... y-1).
```
If **y** divided **(y+1)e** some prime factor **Q** of **y** would have to divide **(y+1)e**.
But then, **Q** would divide both **y** and **y+1** and, therefore, **y + 1 - y = 1**.
[Answer]
# Pyth, ~~17~~ 16 bytes
## 5 bytes:
```
^LhQQ
```
Outputs:
```
2: [1, 3]
3: [1, 4, 16]
4: [1, 5, 25, 125]
```
## 6 bytes:
```
mh*QdQ
```
Outputs:
```
2: [1, 3]
3: [1, 4, 7]
4: [1, 5, 9, 13]
```
## 5 bytes:
```
|RhQQ
```
Outputs:
```
2: [3, 1]
3: [4, 1, 2]
4: [5, 1, 2, 3]
```
Alternate version, in increasing order: `-ShQQ`
[Answer]
## Dyalog APL, ~~16~~ 17 bytes
```
1+⊢×⍳
⊢+1+⊢×⍳
1+⊢*⍳
```
[Answer]
# [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 54 bytes
### Programs:
```
V1V\[DV*1+N' 'O1+]
```
```
V2V\[DV*1+N' 'O1+]
```
```
V3V\[DV*1+N' 'O1+]
```
### Outputs:
```
2 => 3 7
4 => 5 9 13 17
5 => 6 11 16 21 26
```
```
2 => 5 7
4 => 9 13 17 21
5 => 11 16 21 26 31
```
```
2 => 7 9
4 => 13 17 21 25
5 => 16 21 26 31 36
```
### How it works (using the first program as the explanation):
```
V1V\[DV*1+N' 'O1+]
V Capture the implicit input as a final global variable.
1 Push one to the stack for later use.
V\[ ] Do everything in the brackets input times.
D Duplicate the top item of the stack.
V Push the global variable to the stack.
*1+ Multiply, then add 1. This makes it non-divisible.
N' 'O Output the number followed by a space.
1+ Add one to the number left in the stack.
```
[Try it online!](http://vitsy.tryitonline.net/#code=VjFWXFtEVioxK04nICdPMStd&input=)
[Answer]
## Perl, 79
One char added to each program because this requires the `-n` flag.
```
for$a(0..$_-1){say$_*$a+1}
for$a(1..$_){say$_*$a+1}
for$a(2..$_+1){say$_*$a+1}
```
Fairly straightforward.
[Answer]
## Mathematica, 12 + 12 + 12 = 36 bytes
```
# Range@#-1&
# Range@#+1&
#^Range@#+1&
```
Tests:
```
# Range@#-1&[10]
(* -> {9, 19, 29, 39, 49, 59, 69, 79, 89, 99} *)
# Range@#+1&[10]
(* -> {11, 21, 31, 41, 51, 61, 71, 81, 91, 101} *)
#^Range@#+1&[10]
(* -> {11, 101, 1001, 10001, 100001, 1000001, 10000001, 100000001, 1000000001, 10000000001} *)
```
[Answer]
## CJam, 8 + 8 + 8 = 24 bytes
```
{,:)))+}
{_,f*:)}
{)_(,f#}
```
These are three unnamed functions which expect `n` to be on the stack and leave a list of integers in its place. I'm not sure this is optimal, but I'll have to hunting for a shorter solution later.
[Test suite.](http://cjam.aditsu.net/#code=%7B%2C%3A)))%2B%7D%0A%7B_%2Cf*%3A)%7D%0A%7B)_(%2Cf%23%7D%0A%5D%5B2%203%204%205%5Df%7B1%24pf%7B_o%22%20%3D%3E%20%22o%5C~p%7DNo%7D)
Results:
```
{,:)))+}
2 => [1 3]
3 => [1 2 4]
4 => [1 2 3 5]
5 => [1 2 3 4 6]
{_,f*:)}
2 => [1 3]
3 => [1 4 7]
4 => [1 5 9 13]
5 => [1 6 11 16 21]
{)_(,f#}
2 => [1 3]
3 => [1 4 16]
4 => [1 5 25 125]
5 => [1 6 36 216 1296]
```
The first one also works as
```
{_),:)^}
```
or
```
{_(,+:)}
```
[Answer]
## Python 2, 79 bytes
```
lambda n:range(1,n*n,n)
lambda n:range(1,2*n*n,2*n)
lambda n:range(1,3*n*n,3*n)
```
Three anonymous function that start at `1` and count up by each of `n, 2*n, 3*n` for `n` terms.
[Answer]
## Seriously, 20 bytes
```
,;r*1+
,;R*1+
,;R1+*1+
```
Yeah, this isn't optimal...
[Answer]
# [Par](http://ypnypn.github.io/Par/), 16 bytes
The custom encoding, described [here](https://github.com/Ypnypn/Par/blob/gh-pages/README.md#the-encoding), uses only one byte per character.
```
✶″{*↑ ## 3 => (0 1 2) => (0 3 6) => (1 4 7)
✶″U{ⁿ↑ ## 3 => (1 2 3) => (3 9 27) => (4 10 28)
✶U¡↑◄ ## 3 => (1 2 3) => (1 2 4)
```
## Outputs
```
2 => (1 3)
3 => (1 4 7)
4 => (1 5 9 13)
5 => (1 6 11 16 21)
2 => (3 5)
3 => (4 10 28)
4 => (5 17 65 257)
5 => (6 26 126 626 3126)
2 => (1 3)
3 => (1 2 4)
4 => (1 2 3 5)
5 => (1 2 3 4 6)
```
[Answer]
# Haskell, 54 bytes
```
f n=n+1:[1..n-1]
g n=5*n+1:[1..n-1]
h n=9*n+1:[1..n-1]
```
These three functions are pretty straightforward so…
[Answer]
# Octave, 11 + 13 + 13 = 37 bytes
```
@(a)1:a:a^2
@(a)a-1:a:a^2
@(a)(1:a)*a+1
```
[Answer]
## Python 2, 125 bytes
```
N=input();print[i*N+1for i in range(N)]
N=input();print[i*N+1for i in range(1,N+1)]
N=input();print[i*N+1for i in range(2,N+2)]
```
Each line here is a complete program. The most obvious solution in my mind.
**EDIT** @Sherlock9 saved two bytes.
[Answer]
# Haskell, 50
```
f n=n+1:[1..n-1]
f n=1:[n+1..2*n-1]
f n=[1,n+1..n^2]
```
Examples:
```
f1 5=[6,1,2,3,4]
f2 5=[1,6,7,8,9]
f3 5=[1,6,11,16,21]
```
[Answer]
# Golfscript, 50 ~~51~~ ~~57~~ bytes
A Golfscript version of what used to be [quintopia](https://codegolf.stackexchange.com/users/47050/quintopia)'s Python code. Each function takes `n` off the stack.
```
{.,{1$*)}%\;}:f; i*n+1 for i in range(n)
{.,{)1$*)}%\;}:g; i*n+1 for i in range(1,n+1)
{.,{1$)\?}%\;}:h; (n+1)**i for i in range(n)
```
[Answer]
# TI-Basic (TI-84 Plus CE), ~~55~~ 40 bytes total
```
PRGM:C 12 bytes
seq(AnsX+1,X,1,Ans
```
```
PRGM:B 14 bytes
seq(AnsX+1,X,2,Ans+1
```
```
PRGM:C 14 bytes
seq(AnsX+1,X,3,Ans+2
```
Simple, similar to many other answers here, each displays a list of the numbers (X+A)N+1 for X in range(N) and with A being which program (1, 2, or 3).
Old solution (55 bytes):
```
PRGM:C 17 bytes
Prompt N
For(X,1,N
Disp XN+1
End
```
```
PRGM:B 19 bytes
Prompt N
For(X,2,N+1
Disp XN+1
End
```
```
PRGM:C 19 bytes
Prompt N
For(X,3,N+2
Disp XN+1
End
```
Simple, similar to many other answers here, each displays the numbers (X+A)N+1 for X in range(N) and with A being which program (1, 2, or 3).
] |
[Question]
[
**Edit: Allowed to reuse whitespaces.**
Your task is to write *n* programs (or functions, or bodies of functions without using parameters or the function names) in the same language. The *k*th program should output the [(cardinal) number *k* in standard English](http://en.wikipedia.org/wiki/English_numerals#Cardinal_numbers) in lowercase (with an optional trailing newline). So the first program should output `one`, the second should output `two`, etc. For a number having two parts, they should be separated by a hyphen like `twenty-one`.
But no two programs in your submission can share non-whitespace characters or whitespace characters doing useful works. For example, if your first program is just `"one"`, then none of `"` `o` `n` and `e` can be used again in your other programs.
You can use whitespace characters (spaces, newlines and tabs) in two or more programs, if they only serve as separators or indentation and don't do anything by themselves. So you can't reuse them in the [Whitespace](https://esolangs.org/wiki/Whitespace) language, and you can't use them in strings in more than one program.
You can only use printable ASCII characters, tabs, and newlines (including CR and LF). Every program must contain at least 1 character.
Your score is the sum of 1/program size^1.5. Highest score wins. You can use this Stack Snippet ([or this CJam code](http://cjam.aditsu.net/#code=qN37c~%3A%2C-1.5f%23%3A%2B&input=)) to calculate your score:
```
function updatescore(a){var l=a.value.split("\n"),s=0;for(var i=0;i<l.length;i++){var t=l[i].length;t-=t&&l[i][t-1]=="\r";if(t)s+=Math.pow(t,-1.5);}document.getElementById('result').textContent=s;}
```
```
<textarea id="input" placeholder="Put your code here, one per line." style="width:100%;height:150px;box-sizing:border-box" oninput="updatescore(this)" onpropertychange="updatescore(this)"></textarea><div>Your score: <span id="result">0</span></div>
```
[Answer]
# CJam, 0.24075
### Programs
```
BA1]100cf|
"two"
{hree}`W<7a.-
N)92+_9+_6+_2~+
S(84^I^U$F^X$G^Y$(
's'i'x
```
*Thanks to @user23013 for his suggestion to use `'` for **six**.*
### Output, length, score, used characters
```
one 10 0.03162 01 AB ] c f |
two 5 0.08944 " o tw
three 13 0.02133 -. 7 < W `a e h r { }
four 15 0.01721 )+ 2 6 9 N _ ~
five 18 0.01309 $ ( 4 8 FGI SU XY ^
six 6 0.06804 ' i s x
```
Verify the results yourself in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2F%3AQ%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Read%20the%20input%20and%20split%20at%20finefeeds.%0A%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20For%20each%20line%20of%20input%3A%0A%20%20%20%20_%5B%5B_~%5D%20s7Se%5Do%20%20%20%20%20%20%20%20e%23%20%20%20%20%20Evaluate%20the%20input%20and%20print%20the%20result.%0A%20%20%20%20%2C%20s2Se%5B4Se%5Do%20%20%20%20%20%20%20%20%20e%23%20%20%20%20%20Print%20the%20code%20length.%0A%20%20%20%20_%2C-1.5%23_%20%22%25.5f%20%20%22e%25o%20e%23%20%20%20%20%20Compute%20and%20print%20the%20score.%0A%20%20%20%20V%2B%3AV%3B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20%20%20%20%20Compute%20the%20accumlated%20score.%0A%20%20%20%20Qs%24_%26_%40-Ser%20oNo%20%20%20%20%20%20e%23%20%20%20%20%20Compute%20and%20print%20the%20characters%20used%20by%20this%20program.%0A%7D%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%0A%22valid%22Q%7B_%26%7D%25s__%26%3D*%20%20%20%20%20%20e%23%20Push%20%22valid%22%20if%20all%20characters%20are%20unique%20to%20each%20program%20and%20%22%22%20if%20otherwise.%0ANosBSe%5DoV%22%25.5f%22e%25o%20%20%20%20%20%20%20e%23%20Print%20a%20linefeed%2C%20the%20string%20and%20the%20accumulated%20score.&input=BA1%5D100cf%7C%0A%22two%22%0A%7Bhree%7D%60W%3C7a.-%0AN)92%2B_9%2B_6%2B_2~%2B%0AS(84%5EI%5EU%24F%5EX%24G%5EY%24(%0A's'i'x).
[Answer]
# [gs2](https://github.com/nooodl/gs2), 0.38669200758867045
Remove whitespace from all of these programs but **three**, it's only for *(coughs)* readability. **one** and **six** are gs2 programs that crash (by underflowing the stack), which conveniently [makes them quines](https://github.com/nooodl/gs2/blob/aca24d4ed258dfbb6affb895bd51a2ae89afda16/gs2.py#L302).
## one (3 bytes)
```
one
```
## two (1384 bytes)
```
A?"A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0
A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0000000000000
000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000A?"A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A
"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"00000000000000000000
000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000A?"A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"0A"
0A"0A"0A"0A"000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
0000
```
## three (92 bytes)
```
0a 21 2c 21 20 21 20 21 20 21 20 21 20 21 20 21
20 21 20 21 20 21 20 21 20 21 20 21 20 21 20 21
20 21 20 2f 20 0a 21 28 3c 0a 21 2c 21 20 21 20
21 20 21 20 2f 20 0a 21 28 3c 45 21 20 21 20 21
2f 20 0a 21 28 3c 0a 21 2c 21 20 2f 20 0a 21 28
3c 0a 21 2c 21 20 2f 20 0a 21 28 3c
```
Lots of significant whitespace so here's a hex dump. It has a single line feed character at the start:
```
!,! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! /
!(<
!,! ! ! ! /
!(<E! ! !/
!(<
!,! /
!(<
!,! /
!(<
```
## four (276 bytes)
```
f$f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$
31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$
31Mf$f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f$f$31f
$f$31f$f$31Mf$f$f$31f$f$31f$f$31f$f$31f$f$31Mf$f$f$31f$f$31f
$f$31f$f$31f$f$31f$f$31f$f$31f$f$31M
```
## five (178 bytes)
```
hd+++&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&Khd+++&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&Khd+++&&&&&&&&&&&&&&&&&&&&
&&&&&&&Khd+++&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&K
```
## six (3 bytes)
```
six
```
[Answer]
## [Insomnia](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/41868#41868), 0.100688383057110116
Just to get things started. It's very unlikely that this is going to win. Under the current scoring scheme, any language that can print `one` in 5 or less characters has overwhelming advantage.
### one (8 bytes, 0.04419417382415922)
```
uuyp>~p~
```
### two (9 bytes, 0.037037037037037035)
```
oeoojdoLj
```
### three (21 bytes, 0.010391328106475828)
```
*FFFFF
=
=z"
n=nnFzzB
```
### four (23 bytes, 0.009065844089438033)
```
)HGGGkGGGtGkGk<GGh$HGGt
```
[Answer]
# [Headsecks](https://github.com/TieSoul/Multilang/blob/master/headsecks.py), 0.044623631135793776
**[Generated here](http://ideone.com/N9OzWL)**
This language is a simple BF substitution where the only thing that matters is the character value modulo 8.
Unfortunately, longer programs give a worse score, despite being able to get to **twelve**! (I could get higher if I could use non-printable ASCII, and Unicode.)
### one
```
##%%%%%%%&##$%&#&%&%%%%%%%%%&
```
### two
```
--------+--.+++,-..+++.--------.
```
### three
```
5555555535563334566555555555555633333333336555555555555566
```
### four
```
==;=====>;<=>>;;;;;;;;;>;;;;;;>===>
```
### five
```
EECEEEEEFCDEFFCCCFCEFCCCCCCDEFFCCEFCCCDEFF
```
### six
```
KKMMMMMMMMMNKKLMNKNMMMMMMMMMMNMKMMMNKLMNN
```
### seven
```
SSUUUUUUUUUVSSTUVSVSSSSSUVSSSTUVVSUUUVSTUVUVSSUVSSSTUVVSSSSSSSSSV
```
### eight
```
]][]]]]]^[\]^]^[[[[^]]^[^[[[[[[[[[[[[^
```
### nine
```
cceeeeeeefccdeffeeeeefcccccfeeeeeeeeef
```
### ten
```
mmmmmmmmkmmnkkklmnnkkkkmnkkklmnnkkkkkkkkkn
```
### eleven
```
uusuuuuuvstuvuvsssssssvuuuuuuuvsuuuvstuvuvssuvssstuvvsssssssssv
```
### twelve
```
}}}}}}}}{}}~{{{|}~~{{{~{}~{{{|}~~{{{{{{{~{{{{{{{{{{~{{}~{{{|}~~
```
[Answer]
## [///](https://esolangs.org/wiki////), 0.19245008972987526
```
one
```
This answer is inspired by @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳'s answer, in which he said
>
> Under the current scoring scheme, any language that can print `one` in 5 or less characters has overwhelming advantage.
>
>
>
[Answer]
# SmileBASIC, .10062
### "one"
```
?"one
```
### "two"
```
PRINT MID$(@two,1,3)
```
[My other answer](https://codegolf.stackexchange.com/a/166487/64538) is more interesting, but this one gets a higher score.
An important strategy to get the longest chain is to use MORE characters to save on UNIQUE characters (for example, using `x - -x` in program 2 to save `y + y` for program 3)
The problem with the scoring system is that it scores 2 short programs better than 3 long programs, so there is no reason to save characters for later programs if it makes the current program longer.
Also, it values individual short programs higher than a smaller TOTAL size. If I swap `?` and `PRINT` in my answer I can save 1 character, but my score is HALF as much.
I think it would've been better to base it only on *number* of programs, with total size as a tiebreaker.
] |
[Question]
[
Write a program that outputs the contents of the first HTML `<code>...</code>` block of the answer to this question that is just above yours when the answers are sorted by votes. Output `Top!` if you are the top answer.
Ignore answers that have negative votes or no `<code>...</code>` tags. The source of your program must appear in the first `<code>...</code>` block in your post. These blocks are created automatically when you `use backticks` or
```
indent things with 4 spaces.
```
This is code-golf, the answer with the fewest characters wins.
**Additional Rules (Updated)**
* Answer in any programming language you want but if you answer multiple times use different languages.
* You may not hard code your output. Your program's ability to run correctly should not depend on it's vote count or on what the answer above is. If the vote distribution changed drastically your program should still correctly output the code of the answer above it.
* You *may* hard code your program to search for itself on this page (so as to find the next highest) via some unique property of your answer, such as your username (if you only have one answer) or the answer's direct link.
* If two answers have equal votes you should still use the one just above yours (which I believe will be the newest one).
* You may have multiple `<code>...</code>` blocks in your answer but the first one must contain your program's source.
[Answer]
## PHP 666 611 593 588 580 Characters
Edit: Used even smaller url than previously from tinyurl.
Edit: Following comment on other answer I used int rather than boolean. Also needed to correct an error that became apparent but fixed now.
Here is my code
```
<?
$a=34727;$b=new DOMDocument();$b->loadHTMLFile("http://turl.no/t2u");$c=$b->saveHTML();$d=$e=1;$f='data-answerid="';$g=strpos($c,$f);$h=substr($c,0,$g);$c=substr($c,($g+15));while($d==1){$g=strpos($c,'"');$i=substr($c,0,$g);if($i==$a){$j=$h;$k=$e;}$g=strpos($c,'vote-count-post ">');$c=substr($c,($g+18));$g=strpos($c,'<');$l=substr($c,0,$g);$g=strpos($c,'data-answerid="');if($g){++$e;++$e;$h=substr($c,0,$g);$c=substr($c,($g+15));}else{$d=2;}}if($k==1){echo 'Top!';}else{$g=strpos($j,'><code>');$m=strpos($j,'</code></pre>');$n=$m-$g-7;$o=substr($j,($g+7),$n);echo nl2br($o);}
```
I am sure this can be improved using DOMXPath and nodes. However am quite pleased with it. I could not decide what to do in the case of mine is the only answer but with -ve points so ignored. However another answer was posted so not a problem any more.
I also used tinyurl to shorten the url, saving lots of characters.
I hope you like it,
Paul.
PS This will not run in codepad so can't show a fiddle.
Edit: saved 5 more with the php tags being altered
You can see it working [here](http://www.websitethinktank.co.uk/golf.php) on a domain I do not currently use (so am not just trying a sneaky link). This is not a permanent link though but is currently available.
[Answer]
# Javascript + jQuery (~~92~~ ~~86~~ 64 char)
**To test, open Dev Tools on *this* page (usually F12), and run my code!**
This Javscript needs to be run using the console from this page (and only this page).
```
alert($("code",$("#answer-34767").prev().prev()).html()||"Top!")
```
So short, it doesn't even need a scrollbar!
Basically, it finds my answer by ID, and then gets two nodes ahead (skipping the anchor link). If that does not exist, I must be on top. Then it digs down to the first `code` element and gets it's `.innerHTML`.
The nice thing is that SE uses jQuery by default, so I get that advantage without even trying.
[Answer]
## Dart 412 403
```
import"dart:io";import"dart:convert";main(){new HttpClient().get("pi.vu",0,"BYga").then((v)=>v.close()).then((r)=>r.transform(UTF8.decoder).join()).then((s,[i,c="Top!"])=>new RegExp(r'<div id="answer-(\d+)[^]*?vote-count-post ">(\d+)[^]*?<table class="fw"').allMatches(s).forEach((m)=>m[1]=="34735"?print(c):m[2][0]!='-'&&(i=(s=m[0]).indexOf("<code>"))>0?c=s.substring(i+6,s.indexOf("</code>",i)):0));}
```
Ungolfed (well, with newlines and leading whitespace)
```
import"dart:io";
import"dart:convert";
main(){
new HttpClient().get("pi.vu",0,"BYga")
.then((v)=>v.close())
.then((r)=>r.transform(UTF8.decoder).join())
.then((s,[i,c="Top!"])=>
new RegExp(r'<div id="answer-(\d+)[^]*?vote-count-post ">(\d+)[^]*?<table class="fw"')
.allMatches(s)
.forEach((m)=>
m[1]=="34735"?print(c)
:m[2][0]!='-'&&(i=(s=m[0]).indexOf("<code>"))>0
?c=s.substring(i+6,s.indexOf("</code>",i)):0
));
}
```
[Answer]
# Delphi (~~688 873 859 848~~ 840)
I will still try to shave off some characters but it will do the job :)
**Edit:** instead of getting it shorter I made it longer :P
I forgot to add in the ignoring of answers when it has a negative votecount or no code blocks.
I'm just updating the un-golfed version while editing.
Thanks to @manatwork for the suggested edits that took off 8 characters.
### Golfed version:
```
uses IdHTTP,Classes,MSHTML;const u='http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours/34718#34718';var g:TIdHTTP;m:TMemoryStream;l:TStringList;p,t,r,o:OleVariant;s,i,j:int32;c:boolean;begin L:=TStringList.Create;g:=TIdHTTP.Create(nil);m:=TMemoryStream.Create;g.Get(u,m);m.Position:=0;L.LoadFromStream(m);p:=coHTMLDocument.Create as IHTMLDocument2;p.write(l.Text);for I:=0to p.body.all.length-1do begin c:=0>1;t:=p.body.all.item(i);if(t.classname='answer')and(t.id='answer-34718')then if s=0 then writeln('Top!') else for j:=0to o.all.length-1do begin t:=o.all.item(j);if t.tagname='CODE'then writeln(t.innertext);end else if t.classname='answer'then begin for j:=0to t.all.length-1do begin r:=t.all.item(j);if r.tagname='CODE'then c:=1>0 else if c and(r.class='vote-count-post')and(r.innertext[1]<>'-')then begin o:=t;s:=1;end;end;end;end;end.
```
### Ungolfed version:
```
uses
IdHTTP,Classes,MSHTML;
const
u='http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours/34718';
a='answer';b='CODE';
var
g:TIdHTTP;
m:TMemoryStream;
l:TStrings;
p,t,r,o,z:OleVariant;
s,i,j:int32;
c:byte;
begin
L:=TStringList.Create;
g:=TIdHTTP.Create(nil);
m:=TMemoryStream.Create;
g.Get(u,m);
m.Position:=0;
L.LoadFromStream(m);
p:=coHTMLDocument.Create as IHTMLDocument2;
p.write(l.Text);
z:=p.body.all;
for I:=0to z.length-1do
begin
c:=0;
t:=z.item(i);
if(t.classname=a)and(t.id='answer-34718')then
if s=0 then
write('Top!')
else
for j:=0to o.all.length-1do
begin
t:=o.all.item(j);
if t.tagname=b then
write(t.innertext)
end
else if t.classname=a then
for j:=0to t.all.length-1do
begin
r:=t.all.item(j);
if r.tagname=b then
c:=1
else if(c=1)and(r.class='vote-count-post')and(r.innertext[1]<>'-')then
begin
o:=t;
s:=1;
end;
end;
end;
end.
```
[Answer]
**Python - 280**
```
import os, sys, cgi
os.system('wget http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours.html -q -O a')
b=[ x[:-2] for x in open('a').read().split('code>') if x[-1]=='/']
for i, m in enumerate(b):
if m == cgi.escape(open(sys.argv[0]).read()):
print b[i-1]
```
This is my first codegolf, so I hope this is golf-y enough!
Edit: Thanks for the tips! It's looking a bit golfier now.
[Answer]
# Mathematica - 159
First time doing parsing in Mathematica
```
FirstCase[
Cases[Import["http://bit.do/JGta1","XMLObject"],
{__,a_,_,_,_,XMLElement[_, {_, "id""answer-34780",__},_],__}a,∞],
XMLElement["code",_,{c_}]c,"Top!",∞]
```
[Answer]
## Ruby 283+17 = 300
This succeeds regardless how few votes this answer gets and no matter if there's a second (or fifteenth) page of answers or not. It uses the data API.
```
d=34849
JSON.parse(Net::HTTP.get(URI("http://api.stackexchange.com/2.2/questions/34705/answers?site=codegolf&filter=8G3Ng9T*")))['items'].map{|a|abort$1.gsub(/&.+?;/){|g|g[?a]??&:g[?g]??>:?<}if !d&&a['score']>=0&&/<code>(.*?)<\/code>/m=~a['body']
d=p if a['answer_id']==d}
$><<'Top!'
```
must be run with `ruby -rnet/http -rjson` (hence the +17)
ungolfed:
```
d = 34849 # this answer id
i = JSON.parse(Net::HTTP.get(URI("http://api.stackexchange.com/2.2/questions/34705/answers?site=codegolf&filter=8G3Ng9T*")))['items'] # stackexchange api answers for this question
i.map{ |a|
# if we've already hit this answer, the score's above 0 and there's code...
if !d && a['score']>=0 && /<code>(.*?)<\/code>/m=~a['body'] then
# abort with html-unescaped code
abort $1.gsub(/&.+?;/){ |g|
# this turns &, > and < into &, > and <, respectively
g[?a] ? ?& : g[?g] ? ?> : ?<
}
end
# if we are at our answer, set d = nil
if a['answer_id']==d then
d = p
end
}
# no abort. puts 'Top!'
$><<'Top!'
```
### Changelog
**300** removed parens in symbol regex
**302** initial commit
[Answer]
# Python 3, ~~197 191~~ 186 bytes
```
import urllib.request as u,gzip,json;p='Top!'
for r in json.loads(gzip.decompress(u.urlopen("https://bit.ly/Ƶ").read()).decode())["items"]:
if r['answer_id']==82837:exit(p)
p=r['body']
```
The rules don't say that I can't use the API and that I can't use a url shortener.
`https://bit.ly/Ƶ` expands to `https://api.stackexchange.com/2.2/questions/34705/answers?order=desc&sort=votes&site=codegolf&filter=withbody&pagesize=100`
This only works if it is in the top 100 answers sorted by votes.
[Answer]
# PHP 135
```
<?
preg_match_all('@(\d+?)"></a.*de>(.*)</c@Us',join('
',file('http://pi.vu/BYga')),$m);echo$m[2][array_search(34786,$m[1])-1]?:'Top!';
```
**Edit:** lrn's URL shortener produces the shortest URL :)
The RegEx matches the anchor before each answer (together with the answer ID) and the contents inside the first `<code>` tag. The `U` flag triggers the `U`ngreedy mode and the `s` flag make `.` matches new lines (very handful). I'm not worried if this matches something else as the answers are escaped, so nobody can insert the `<` literal in the page's source.
After I get all the answers in `$m[2]` and their IDs in `$m[1]`, I just use `echo` to print the answer above mine, as it's in `$m[2][array_search(34786,$m[1])-1]`, or "Top!", if my answer eventually gets first :)
I like the fact that in PHP the ternary operator can be used as a short-circuit operator `?:`
[Answer]
## Delphi, ~~461 bytes~~, 553 bytes
*Now handles multiple pages too!*
Golfed:
```
uses IdHTTP,RegularExpressions;var T,S,O:String;K,V,C:Int32;begin repeat Inc(C);Str(C,S);S:=TIdHTTP.Create.Get('http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours?page='+S);T:=T+S;until Pos('<span class="page-numbers next',S)=0;O:='Top!';for T in TRegEx.Split(T,'<a name="') do begin S:=T;Val(Copy(S,1,Pos('"',S)-1),K,C);if C=1then Continue;Delete(S,1,Pos('post ">',S)+6);Val(Copy(S,1,Pos('<',S)-1),V,C);C:=Pos('<code>',S);if(C=0)or(V<0)then Continue;if K=34844then Break;O:=Copy(S,C+6,Pos('</code>',S)-C-6);end;Write(O)end.
```
(slightly) Ungolfed:
```
uses
IdHTTP,RegularExpressions;
var
T,S,O:String;
K,V,C:Int32;
begin
// download all pages in thread and concat them
repeat
Inc(C);
Str(C,S);
S:=TIdHTTP.Create.Get('http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours?page='+S);
T:=T+S;
until Pos('<span class="page-numbers next',S)=0;
O:='Top!'; // initialize code string to 'Top!'
for T in TRegEx.Split(T,'<a name="') do begin
S:=T;
Val(Copy(S,1,Pos('"',S)-1),K,C); // try to extract user id
if C=1then Continue; // if failed, continue loop
Delete(S,1,Pos('post ">',S)+6); // prepare S for next parse
Val(Copy(S,1,Pos('<',S)-1),V,C); // try to extract vote count
C:=Pos('<code>',S); // check if <code> tag exists
if(C=0)or(V<0)then Continue; // make sure vote count is positive and <code> tag exists
if K=34844then Break; // if its our answer, break the loop
O:=Copy(S,C+6,Pos('</code>',S)-C-6); // get string in <code> tag
end;
Write(O); // write <code> string
end.
```
How to run:
```
app.exe > output.txt
```
[Answer]
## PHP - 412 - 422 - 416 - 252 - 248:
Still a work in progress, I haven't done anything regarding multiple pages (nor has anyone else?)
I got the 200 character drop by cutting out a lot of extra dom, why search for objects when I can just find their position?
This is also my first code golf! I'm happy to have done it in the 200s and using dom methods. Thanks to comments, I just shaved off 4 more characters.
I wanted to do something like jquery/jscript in regards to traversing the dom, and am still working on slimming this down. Maybe I could get away with searching for "asi" as my user name?
Golf:
```
<? $d=new DOMDocument;$d->loadHTMLFile("http://bit.do/JGta");$x=new DOMXPath($d);$r=$x->query("//*[@class='answer']");$a=-1;while($f=$r->item(++$a))if(strpos($f->nodeValue,"Asitaka"))echo$x->query(".//pre//code",$r->item($a-1))->item(0)->nodeValue;
```
Formatted:
```
<?php
$d = new DOMDocument();
$d->loadHTMLFile("http://bit.do/JGta");
$x = new DOMXPath($d);
$r = $x->query("//*[@class='answer']");
$a = -1;
while($f = $r->item(++$a))
if ( stripos($f->nodeValue, "Asitaka")!= 0)
echo $x->query(".//pre//code",$r->item($a-1))->item(0)->nodeValue;
?>
```
Cheers
] |
[Question]
[
Write the shortest function to convert an integer into a numeric representation given a radix between 2 and 62. e.g.:
```
to_string(351837066319, 31) => "codegolf"
```
[Answer]
## dc - 43 chars
```
[sb[58-]s_[lb~dZ39*+dB3<_9+rd0<xrP]dsxxk]sf
```
We can shorten this a little if we assume the stack contains only the two arguments.
```
[[58-]s_dSb~dZ39*+dB3<_9+SadLbr0<fLaPc]sf
```
As a standalone program, we only need 37 characters:
```
?o[58-]s_[O~dZ39*+dB3<_9+rd0<xrP]dsxx
```
Instead of using `[39+]sz9<z`, we simply use `Z39*+`, which will add 39 for a single digit number, and 78 for a double digit number. Instead of `113`, we use `B3` (`AD` also works).
[Answer]
# Ruby 1.8 - 75 characters, with recursion.
```
f=proc{|n,b|(n<b ? "":f[n/b,b])+([*'0'..'9']+[*'a'..'z']+[*'A'..'Z'])[n%b]}
```
### Without recursion
```
f=proc{|n,b|d=[*'0'..'9']+[*'a'..'z']+[*'A'..'Z'];s=d[n%b];s=d[n%b]+s while(n/=b)>0;s}
```
(both based on Dogbert's 1.9 solution.)
[Answer]
# Python - 86
```
from string import*
def t(n,r,s=''):
while n:s=printable[n%r]+s;n/=r
return s or'0'
```
Credit due to Hoa Long Tam for the string import trick
[Answer]
# Python, ~~93~~ 99
```
from string import *
d=digits+letters
def t(n,b):
s=''
while n>0:s=d[n%b]+s;n/=b
return s or '0'
```
**EDIT**: " or '0'" added for empty string case
[Answer]
# dc, 61 chars
```
[sr[lr~rd0<x]dsxxk[39+]sa[58-]sb[d9<ad78<b48+anz0<p]dspxIP]sf
```
Run as:
```
dc -e'[sr[lr~rd0<x]dsxxk[39+]sa[58-]sb[d9<ad78<b48+anz0<p]dspxIP]sf' -e'351837066319 31 lfx'
```
or:
```
dc -f base.dc -e '351837066319 31 lfx'
```
Explanation:
We take the number and base on the stack. `sr` saves the base in register r. The recursive function `[lr~rd0<x]dsxx` decomposes a number `TOS` into its digits in base `register r`. The first digit is always 0, removed from the stack by `k` (set precision, which by default is 0 also, so it's equivalent to a nop). Then, the recursive function `[48+d57<ad122<banz0<p]dspx` outputs each digit in ASCII, with the help of functions a (`[39+]sa`) and b (`[58-]sb`). `IP` outputs a newline. The function is stored in register `f`, and can be invoked by `lfx`.
[Answer]
# Ruby - 72 70 59 chars
```
f=->n,b{(n<b ? "":f[n/b,b])+[*?0..?9,*?a..?z,*?A..?Z][n%b]}
```
## Without recursion, 70 chars
```
f=->n,b{d=*?0..?9,*?a..?z,*?A..?Z;s=d[n%b];s=d[n%b]+s while(n/=b)>0;s}
```
Test
```
irb(main):080:0> f[351837066319, 31]
=> "codegolf"
irb(main):081:0> f[0, 31]
=> "0"
```
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 4 bytes
```
peB!
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/INVJ8f9/Y1NDC2NzAzMzY0NLBWNDAA "Burlesque – Try It Online")
Luckily a built-in in Burlesque
```
pe # Parse and push
B! # Convert base
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
f=lambda n,b:n and f(n/b,b)+chr(n%b+48+(n%b>9)*39-n%b/36*58)or''
```
[Try it online!](https://tio.run/##FcZBDoMgEADAr3BpZAFjcZWCSfsXtoRooqshXvp6qqeZ43fOO/e15vcaN0pRsKGJReQksuSODIH@zkXyg/Tg9e0ngMLQXuvQqdHDXpqmHmXhU2aJo/X4ejqHNhi0APUP "Python 2 – Try It Online")
[Answer]
## Haskell, 109 characters
```
m=divMod
d(0,x)b=[f x]
d(r,x)b=f x:d(m r b)b
f=(!!)$['0'..'9']++['a'..'z']++['A'..'Z']
s x b=reverse$d(m x b)b
```
[Answer]
## Befunge - 53 x 2 = 106 characters
Or 53 + 46 = 99 characters if you're willing to route other parts of your program through the bottom left.
```
11p01-\>:11g%\11g/:#v_$>:1+!#v_:45+`!#v_:75*`!#v_ v
^ < ^, $# +"0" < +"'" <-":"<
```
First place the number to be converted on the stack, then the radix and enter this function from the top-left going right. Will output the string for you (since Befunge doesn't support string variables) and leave from the bottom `$` going down. Requires the `(1,1)` cell for radix storage.
E.g. for the example given put `351837066319` into the input and run:
```
&56*1+ 11p01-\>:11g%\11g/:#v_$>:1+!#v_:45+`!#v_:75*`!#v_ v
^ < ^, $# +"0" < +"'" <-":"<
@
```
[Answer]
## Golfscript - 32 chars
```
{base{.9>39*+.74>58*48--}%''+}:f
```
[Answer]
# Bash, 79 chars
```
f(){
dc<<<$2o$1p|perl -pe"y/A-Z/a-z/;s/ \d+/chr$&+($&<10?48:$&<36?87:29)/ge"
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
b‘ịØB
```
[Try it online!](https://tio.run/##y0rNyan8/z/pUcOMh7u7D89w@v//v7GpoYWxuYGZmbGh5X9jQwA "Jelly – Try It Online")
The case will be reversed (codegolf - CODEGOLF) because of Jelly built-in base characters string.
### How?
```
b‘ịØB - Link, input x & y
b - Convert x to base y
‘ - Increment (because Jelly use based-1 indexing)
ị - List (string) indexing
ØB - "0-9 A-Z a-z"
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Follows the example of the Jelly solution in reversing the casing.
```
;sVîEowi%
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O3NW7kVvd2kl&input=MzUxODM3MDY2MzE5CjMx)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 bytes
```
VL(:B
```
[Run and debug it](https://staxlang.xyz/#c=VL%28%3AB&i=351837066319,+31)
Same size packed, a custom base conversion.
[Answer]
# Ruby 1.9 - 80 74 68
```
t=->n,b{d=*?0..?9,*?a..?z,*?A..?Z;s='';(s=d[n%b]+s;n/=b)while n>0;s}
```
With '0' for empty string, 95 89 82 characters:
```
t=->n,b,s=''{d=*?0..?9,*?a..?z,*?A..?Z;(s=d[n%b]+s;n/=b)while n>0;s.empty?? ?0: s}
```
Ruby 1.9 - unfortunately only works up to base 36:
```
t=->n,b{n.to_s(b)}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-Minteger -ap`, 52 bytes
```
do{$\=(0..9,a..z,A..Z)[$_%$F[1]].$\}while$_/=$F[1]}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z8lv1olxlbDQE/PUidRT69Kx1FPL0ozWiVeVcUt2jA2Vk8lprY8IzMnVSVe3xYsVFv9/7@xqaGFsbmBmZmxoaWCseG//IKSzPy84v@6vqZ6BoYGQDozryQ1PbXov25iAQA "Perl 5 – Try It Online")
[Answer]
# [Go](//golang.org), 76 bytes
```
package m
import."math/big"
func e(n int64)string{return NewInt(n).Text(62)}
```
bonus decode:
```
package m
import."math/big"
func d(s string)int64{o,_:=NewInt(0).SetString(s,62)
return o.Int64()}
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
вžLšRsè
```
-1 byte by switching to the legacy version of 05AB1E, where the switch\_case builtin was one byte (it's `.š` in the new version).
Inputs in the order \$radix,number\$. Output as a list of characters.
[Try it online.](https://tio.run/##MzBNTDJM/f//wqaj@3yOLgwqPrzi/39jQy5jU0MLY3MDMzNjQ0sA)
**Old 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) non-legacy 05AB1E answers (same I/O as above):**
* `žhži«£Åв` - [Try it online.](https://tio.run/##AScA2P9vc2FiaWX//8W@aMW@acKrwqPDhdCy//8zMQozNTE4MzcwNjYzMTk)
* `вžK9݆sè` - [Try it online.](https://tio.run/##yy9OTMpM/f//wqaj@7wtD8991LCg@PCK//@NDbmMTQ0tjM0NzMyMDS0B)
**Explanation:**"
```
в # Convert the second (implicit) input to base-(first implicit input) as list
žL # Push string "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210"
š # Switch case: "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210"
R # Reverse it: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
s # Swap so the list is at the top
è # Index each into this string
# (after which the resulting character-list is output implicitly)
```
```
žh # Push constant string "0123456789"
« # Append
ži # Constant string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
# "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
£ # Only keep the first (implicit) input amount of characters from this string
Åв # Convert the second (implicit) input to this custom base-"0-9a-zA-Z"
# (which basically converts it to base-length, and indexes it into the string)
# (after which the resulting character-list is output implicitly)
в # Convert the second (implicit) input to base-(first implicit input) as list
žK # Push string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789"
9Ý # Push list [0,1,2,3,4,5,6,7,8,9]
† # Filter all those characters to the front:
# "012346789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
s # Swap so the list is at the top
è # Index each into this string
# (after which the resulting character-list is output implicitly)
```
] |
[Question]
[
The following data contains the (approximate) population of each UTC timezone in the world ([source](https://observablehq.com/@mattdzugan/population-by-time-zone-creating-a-dataset)):
```
UTC;Population (in thousands)
-11;57
-10;1853
-9.5;8
-9;639
-8;66121
-7;41542
-6;272974
-5;332101
-4.5;31923
-4;77707
-3.5;499
-3;248013
-2;4855
-1;3285
0;285534
+1;857443
+2;609921
+3;496279
+3.5;81889
+4;129089
+4.5;31042
+5;305642
+5.5;1458945
+6;199668
+6.5;50112
+7;439650
+8;1679526
+9;220112
+9.5;1814
+10;29482
+11;5267
+11.5;2
+12;6112
+13;308
+14;11
```
(for the sake of simplicity, I'm removing `+X.75` UTC times from the list)
Assuming that every person in the world wakes up at 8AM and goes to sleep at midnight (in their local time), how many people are simultaneously awake in the world at a given UTC time?
For example, suppose the given time is 2PM UTC. These are the timezones where the local time at 2PM UTC is between 8AM inclusive and midnight exclusive:
```
-6 08:00 272974
-5 09:00 332101
-4.5 09:30 31923
-4 10:00 77707
-3.5 10:30 499
-3 11:00 248013
-2 12:00 4855
-1 13:00 3285
+0 14:00 285534
+1 15:00 857443
+2 16:00 609921
+3 17:00 496279
+3.5 17:30 81889
+4 18:00 129089
+4.5 18:30 31042
+5 19:00 305642
+5.5 19:30 1458945
+6 20:00 199668
+6.5 20:30 50112
+7 21:00 439650
+8 22:00 1679526
+9 23:00 220112
+9.5 23:30 1814
```
Now, just add the population of these timezones and output 7818023 (corresponding to ~7.8 billion people).
## Input
An UTC time. You may accept two natural numbers ***h*** and ***m***, where ***0 ≤ h ≤ 23*** and ***m ∈ {0, 30}***.
[Standard I/O](https://codegolf.meta.stackexchange.com/q/2447/91472) applies, so you can accept them as lists, strings, etc. You can even accept ***m*** as a boolean value, where 0 means `HH:00` and 1 means `HH:30`.
There are two ways of solving this question: hardcoding the output (since there are only 48 possible inputs) or hardcoding the population data and solving by time arithmetic. However, to make this challenge more interesting, you are allowed to accept the population data as an additional input, so you don't need to hardcode it (thus saving you some bytes) and focusing only on the time arithmetic. So you can read it as additional lines from STDIN or an additional function argument.
## Output
How many people are awake at the given time, in thousands.
### Test cases
```
00:00 -> 3024211
00:30 -> 3024211
01:00 -> 3460576
01:30 -> 3510688
02:00 -> 3705501
02:30 -> 5164446
03:00 -> 5222075
03:30 -> 5252618
04:00 -> 5304000
04:30 -> 5353966
05:00 -> 5518144
05:30 -> 5518144
06:00 -> 5855091
06:30 -> 5855091
07:00 -> 6670992
07:30 -> 6670992
08:00 -> 6890405
08:30 -> 6890405
09:00 -> 6893051
09:30 -> 6893043
10:00 -> 6896034
10:30 -> 6896034
11:00 -> 7143682
11:30 -> 7144181
12:00 -> 7215776
12:30 -> 7247697
13:00 -> 7574531
13:30 -> 7574531
14:00 -> 7818023
14:30 -> 7816209
15:00 -> 7637639
15:30 -> 7637639
16:00 -> 6024234
16:30 -> 6024234
17:00 -> 5585223
17:30 -> 5535119
18:00 -> 5337315
18:30 -> 3878370
19:00 -> 3573093
19:30 -> 3542051
20:00 -> 3419074
20:30 -> 3337187
21:00 -> 2846175
21:30 -> 2846175
22:00 -> 2265736
22:30 -> 2267550
23:00 -> 1630219
23:30 -> 1630219
```
Try to make your code with the fewest bytes as possible.
---
[Sandbox](https://codegolf.meta.stackexchange.com/a/26237/91472)
[Answer]
# Google Sheets, 38 bytes
```
=sumproduct(B:B,1/3<=mod(A:A/24+C1,1))
```
Paste UTC offset and population data in cells `A1:B`, put the time of the day in cell `C1`, and the formula in cell `D1`.
There was some confusion whether the expected results shown in the test cases were correct. The above formula matches the updated expected results.
Spreadsheet [dateserials](https://webapps.stackexchange.com/a/153710/269219) use a system where the duration of one day is 1. Eight hours, `8:00 am`, is one third of a day, i.e., `1/3`, and the value of 24 hours is exactly `1`. In spreadsheets, `mod()` always takes the sign of the divisor rather than that of the dividend which lets the formula wrap around midnight.
The rules allow some flexibility with input formats. If UTC offsets are input as durations like `-11:00`, `-10:00`, `-9:30` in column `A1:A`, they require no manipulation and can simply be added to the time of day (**35 bytes**):
```
=sumproduct(B:B,1/3<=mod(A:A+C1,1))
```

[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ḅ.+%24>7.ḋ⁵
```
[Try it online!](https://tio.run/##JVAxTgNBDPzKKRIVSVh7vV67IBIfoKNAUTpoonyALiBR0dFAATUNLSjUiIJn3H1kGS/Sjb1ez4y9t73e7W5aGw/3y@MjllVdjoeH6fajiY2Hzyu@@Hkcv57n32@/T9Pd@xaY9i/D6WqY9q@Xrc3OT85mbb0gmg8LSgi@LBEBAyqgQNxJ7wiQ@ykDHLL5ACEiCtz1JlidHl9keGhk@MEW7n1MDIzJRL2CnmBAsmnrAiZZyZ2vGQpVYnCFioDIlb1iSs5MCdeZnEGutSYoxSFgsRR@YgXumQ0RoWTIrFQR9DS5d1dXrtAYmXms4ilyphTDcioamaSYS6zqrorFSqLYWrJribdo9cJ4K/N/g4wwjF0MBTq1/yTtvZwsXr75Aw "Jelly – Try It Online")
A full program taking three arguments (time as [m/30, h], timezones, populations) and printing the total population awake.
*Thanks to @JonathanAllan for saving two bytes and fixing a bug!*
## Explanation
```
ḅ. | Base convert from base 0.5
+ | Add timezones
%24 | Mod 24
>7. | Greater than 7.5
ḋ⁵ | Dot product with populations
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
IΣEΦθ‹⁷·⁵﹪⁺⁺∕ζ⁶⁰ηκ²⁴ι
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LZHPTsMwDMbFm0Q7pWo7xc7_cARxYtIkjoND2YZWURis7Q4gXgQuO4DgleBpsNsdkvzifra_uB8_y021W26r5nD46ru7Mvxez3f1YyfPqraTV_2DnFVP8qJuuvVOPhfict220k9tIWbbVd9s5bzp23E7r_f1ai1fCuFUVogNrXtaaLKMjpr27PSzvV22x07fi0m5byY3fyfvi9cSIAnrC1GCSgKC1YRxapMIDEk4HQkCgQMEQp-EAWuQ0CWBHqM3xJShNYJiieF8DRG5mEnCe6-4hea4iVxQU6oJCliBFAzWsgdKw0BEXui0mirnFAzWG0PSnKROxchGcs21HPrIPDiGEPhCHQGjGnm0othvzqisG5k_gLEhGuqX01MgRucCM3-yCoB1_FwdnVXENAVwPlp0dKHZIB5Fw8AgwGCXvUcTOD4MF50fkDVDkB8x5oFmR9wT2DS8FQLIjVY346_6Bw) Link is to verbose version of code. Takes arguments in the order `zones`, `h`, `m`. Explanation:
```
θ Input zones
Φ Filtered where
⁷·⁵ Literal number `7.5`
‹ Is less than
ζ Input minutes
∕ Divided by
⁶⁰ Literal integer `60`
⁺ Plus
η Input hours
⁺ Plus
κ Current key
﹪ Modulo
²⁴ Literal integer `24`
E Map over entries
ι Take the value
Σ Take the sum
I Cast to string
Implicitly print
```
Python's `sum` sums the keys of a dictionary for some reason.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 48 bytes
```
c=>t=>c.map(([x,y])=>s+=(t+x+40)%24<16&&y,s=0)|s
```
[Try it online!](https://tio.run/##PZDBbsIwDIbvPAWXoVYxKHYcJ5ZWLn0M1APqYNrEKFqrCaS9excS2O374z/2b3/uf/Zj//1xmdbn4e0wH5u5b7ZTs@03X/tLVe2ucOvqZjuapprM1bCtX4hfUVarG4yNrX/HuW2XzXK3WyOCDx0sElnA6F1m3XiIhUCcZooggoSZAzB6pswCFEgDZ@HBOUJbXJy6OFQqPRlCCLbMcqnCWvo6II4Wi4mAo/clDziKGS0k8C5PMAjRB@ZsNwRiVUso41JLoaBF3DfAGItiQFL7FDmWLfFNYuvlKVIJ2UflPNgIoKpILCIVvUUs1nQCp@JtFhFQgnqSrBSI/n33U2LER/i0inIslfvpScKDk@3xnJZ6fkaX0pXpmHbArlv0w3kcTofNaXivjlXb1hVyXc9/ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Funge-98](https://esolangs.org/wiki/Funge-98), 126 bytes
```
"HTRF"4(0& 2*&+: 0'v00p
>&2*&+-: 0wv>&:bwv> RR+'0%'`0w$:0
^$vvp16+'<> ^ > ^p10v'<>j#80:\+R<
$$<> 3j^ <^ >'>02p ^@.
```
[Try it online!](https://tio.run/##JZBNS8RADIbvc/EvhHVtxWEkme@UUjyJ5@JRiiyswh6kF7v462syO4eZJ5l8vMnp/PX78312XN3613DfD2/v8@shPmIH/qmzA2C/Ia5m6tR0Yl@3qRtOcoOeebY9PvR3n3g9DmiW47atlG0/TrDIt9wr4Sbm5b7i8GHn0RyPo@aGywKjxsDUT@hXWF6e9x0BjSMChFQExASqKRjHQFD1QciBjasKmTwZVwQjpeiNy4K@eC7RuCQcgieUkCjZgdgHRYRSCkr5IN7IrCBpsSLJv9dqNSXprgV8TUZVyJtCNFadNZUYg7EampFZRFgtETn7wsqilWoV1G7kGW@sIlB02qYNU74xAcVUOSZjdQBizrkqEyQkkpg2YuCc0FidnHLh5LOxug/vb0G6IqqkIptijlW8t2X6XBoSqKsJbzkUmhLpRk0qmX8)
First reads `h`, then `m` as 0 or 1, and finally each timezone as (`h`, `m`, `population`).
Contains a non-printable character, so here is a hex dump:
```
00000000: 2248 5452 4622 3428 3026 2032 2a26 2b3a "HTRF"4(0& 2*&+:
00000010: 2030 2776 3030 700a 3e26 322a 262b 2d3a 0'v00p.>&2*&+-:
00000020: 2030 7776 3e26 3a62 7776 3e20 2020 2020 0wv>&:bwv>
00000030: 5252 2b27 3025 270f 6030 7724 3a30 0a5e RR+'0%'.`0w$:0.^
00000040: 2476 7670 3136 2b27 3c3e 205e 2020 203e $vvp16+'<> ^ >
00000050: 205e 7031 3076 273c 3e6a 2338 303a 5c2b ^p10v'<>j#80:\+
00000060: 523c 0a24 243c 3e20 2020 336a 5e20 3c5e R<.$$<> 3j^ <^
00000070: 2020 2020 3e27 3e30 3270 205e 402e >'>02p ^@.
```
[Answer]
# [Perl 5](https://www.perl.org/) List::Util, 65 bytes
```
sub{($t,%p)=map$_*2,@_;sum map$p{$_}/2*(($t+$_-16)%48<32),keys%p}
```
[Try it online!](https://tio.run/##bVZbb@NUEH7PrzhaXJrs2vTMzLkmBK3EAy8g8dB9YldRUdPFoomtxpEoVfnr5Vzs8SEiqhRlvvnm9s3Y7fdPj/rtfNqLn9vTsF5/GtpHcX06H643i2i93UfrL93TfrM4PIvqQWzF2@n8@8uyGuqrfrU93PXV7j3WH3ebwBLxZ/9S7V5v8P0y@Hyodg2Y1ZVy3xOu6j/3z6er/vUtBrvqu367FN98uv1RbH8Qv3b9@fFuaLujWLZHMfzRnU93x/vTaiEaACGij7a1yJ8GZDSA0zSaGv@djiY3uSRbtBjy9SL8cDmIMYCQnRobDQq0Qg5sogkteqtGpxSWCEFCiqNyIgKPY/JGRYO1Vo4FNpR9lPdcTkMpsnISKMXBXI9yWk89QAqMTs9NpD6DRdNYj0hOTlulUhwxxjHS@6kxyskN2jH/WI8D57iiVDSgly7NR3BfkseRDVKbyaKzDyjtvBqrTBMD741xKY7JPloCTHHynMkbLafsLrGM9RpNtiWxEBMtxhkFBQfceR6GV471gjSNEGOcPEBm5RCAeTRzJUC5pWJNIA8CxGqzeOielpEofruWci3ldfZGhQBfagbo/wFghjJSW1MAE0ODNM59qackyBQrdRgZU3CiaDBKqTkWTQyNYVhWF8DEwDAPKJIoppBUUkqmKKaQDurMSTQzdJy/KgC6AKYkhilhWaWfOzFMuQDsxDDGxuUtALoApiSOKc6HVubmHVMuAF8wwiZDAVABKOIkIAuKkcTNgywo/wFYeAuKjMMCIAZUGNichIW3CNrOuwIsvEVljbcMsPA23L4mKAC6AKYkLLwNly@RmMLCB8Cg9Ayw8NZQ@CsBugCmJCy8iedQTIWFvwTsvF0ubDEVAG9XuBQokrh5hckSsL7AwpOzLhwRAyw8aUvSUwHwMSpMGzEmwfniFXhpuWCcLz5kB8eaIAuPThmYjxFZeAamJCw8ogmVsfDIwgfAhkthgIUHE5444AuALoDF6iXlOTwvRdUe@1pU@796sQqv7Y/VbpOwaBfbf8TN8vP95/vVOn/dbEaiqL52Q/D/tnoIMUB8EBXemPDcji/s@IyMbu1pmfxy/Fq8u20P@3UOLeK7vGmPzRBsf3fHaI9FCPFTN6wT7V2M87q4D@BuCP9itMevm7d/AQ "Perl 5 – Try It Online")
[Answer]
**[T-SQL](https://learn.microsoft.com/en-us/sql/t-sql/language-reference?view=sql-server-ver16) 64 Bytes**
```
declare @x table (utc int, pop int)
declare @t time(7)
insert @x values ...
```
`select sum(pop)from @x where datediff(h,utc,@t) between 8 and 24`
] |
[Question]
[
Given a positive integer `N`, output this doubling pattern of slash squares/rectangles.
For `N=1`, the base is:
```
/\
\/
```
The next square is added in the bottom right direction for `N=2`:
```
/\
\/\
\/
```
After that, a 2x1 rectangle is added in the bottom left direction for `N=3`:
```
/\
/\/\
\ \/
\/
```
Then a 2x2 square is added in the top left direction for `N=4`:
```
/\
/ \
\ /\
\/\/\
\ \/
\/
```
A 2x4 rectangle is added in the top right:
```
/\
/ \
/\ \
/ \ \
\ /\ /
\/\/\/
\ \/
\/
```
And so on. The direction in which squares and rectangles are added cycles counterclockwise, and the shape which is added alternates between squares and rectangles.
You may output as an array of lines / matrix of characters, and input may be 0-indexed or 1-indexed. Trailing whitespace in the output is allowed.
[Reference implementation](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIoXG4gIG7igLlbXG4gICAgbiA0ICUgMiA9IFtcbiAgICAgIDQgbiA0IOG4rSBlIDog4oaSeCDGmyBcXC8gJCDigLnqmI07IOKBiyDDuOG5gCDihrUg4biCUkog4oaQeCAoIMKkIHAgKSAkIOKGkHggKCDCpCBKKSAkICtcbiAgICB8IG4gNCAlIDMgPSBbXG4gICAgICA0IG4gNCDhuK0gZSA6IMKjIMabIFxcLyAkIOKAueqYjTsg4oGLIMO44bmAIOKGtSDCpSDJviB2XFxcXCDCpSDqmI0gduKIniDIriDhuZhSSkogwqUgICggwqQgcCApICQgwqUgKCDCpCBKKSArXG4gICAgfCBuIDQgJSAwID0gW1xuICAgICAgNCBuIDQg4bitIGUgwr0gOiDihpJ4IMabIFxcLyAkIOKAueqYjTsg4oGLIMO44bmAIOKGtSDhuIJSSiDihpB4ICggwqQgSiApICQg4oaQeCAoIMKkIHApICtcbiAgICB8XG4gICAgICA0IG4gNCDhuK0gZSDCvSA6IMKjIMabIFxcLyAkIOKAueqYjTsg4oGLIMO44bmAIOKGtSDCpSDJviB2XFxcXCDCpSDqmI0gduKIniDIriDhuZhSSkogwqUgICggwqQgSiApICQgwqUgKCDCpCBwKSAkICtcbiAgICBdXV0gxpvigJsvLyBcXC8gViBgXFxcXGAgXFxcXCBWO1xuICB8XG4gICAgay/huIJcIlxuICBdXG4pXG4/IOKItyBbXG4gw7jEiuKBi1xufCA/IMK9IEUgOiDCvSDKgSDhuZggJCDKgSBKICQg6piNIOKBiyIsIiIsIjEwIl0=)
Testcases:
```
1:
/\
\/
2:
/\
\/\
\/
4:
/\
/ \
\ /\
\/\/\
\ \/
\/
7:
/\
/ \
/\ \
/ \ \
/\ /\ /\
/ \/\/\/ \
/ \ \/ \
/ \/ \
\ \ /
\ \ /
\ \ /
\ \/
\ /
\ /
\ /
\/
10:
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/\ \
/ \ \
/ \ \
/ \ \
/ \ \
/ \ \
/ \ \
/ \ \
\ /\ /\
\ / \ / \
\ /\ \ / \
\ / \ \ / \
\ /\ /\ /\ / \
\ / \/\/\/ \ / \
\ / \ \/ \ / \
\/ \/ \/ \
\ \ / \
\ \ / \
\ \ / \
\ \/ \
\ / \
\ / \
\ / \
\/ \
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\/
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
↶⁴FNF⁵«↷¹X²÷⁺﹪κ²ι²↷¹¶
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gsyy/xCc1rUTDRNOaKy2/SEHDM6@gtMSvNDcptUhDU1MBLGaqqVDNxQlWHJSZnlGiYQhUzRlQlJlXohGQXw5UaaSj4JlX4pJZlpmSqhGQU1qs4ZufUpqTr5Gto2CkqaOQqQmiwbqwmqIUk6cE5NX@/29o8F@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
↶⁴
```
Make the output upside-down relative to the output Charcoal would like to produce.
```
FN
```
Loop over each quadrilateral.
```
F⁵«
```
Draw five sides, so that the cursor is in the correct place to draw the next one.
```
↷¹X²÷⁺﹪κ²ι²↷¹¶
```
Draw one diagonal of the quadrilateral. The pivots and newline conspire to place the cursor in the correct place to draw the next diagonal.
[Answer]
# JavaScript (ES6), 240 bytes
1. Make it work without giving a dime about leading whitespace.
2. Realize that leading whitespace is not allowed.
3. Add an insane amount of code to start drawing the smallest square at the correct coordinates.
4. Oh well ... post it anyway. :-)
Returns a matrix of characters.
```
n=>(x=1<<(h=n=>n-=n&1||n&3)(n)/2,y=(g=k=>k<4?k:-~g(k-4)*4)(h(n-1)),F=i=>i<n?F(-~i,(g=k=>k--?g(k,(h=Y=>m[Y+=y+k]=m[Y]||Array(1<<n/2+1).fill` `)``[x+k]=h(d)[x+k-d]='\\',h``[X=x+~k]=h(d)[X+d]='/'):x+=i%4%3?-d:d)(d=1<<i/2),y+=i%4?-d:d):m)(m=[])
```
[Try it online!](https://tio.run/##XZDRboJQDIbvfYqTJUq7w4GAXCGF7MZn0CgJREQQKAaXBTLmq7PD5m521S/9/rRpr@lHej915e1dcZudp5wmphB6coIACtLMinjljCOv1giMtmsOBBeqKKwCL6p89bhApTx89RAKYOUgmlsqKSwDjragHqX5jCsV6aipx@4pbA57SYOsYtIUj@Nb16UD6K1su9JBKy/rOhEJJsmhn1MFZDiTymIyjkfDLLTZUS8ff3InZ2Ub6PeSyqW3XEcq8zOEbD6mtF00hx/x2/YbhIYOMU552wELEs5GsAh0dTVIieJzIcSp5Xtbn626vcDLnHoRUjBu/qlcv8Zq0ht0gkLRWde2ZDAMxCcdWfNm8TV9Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# Python/NumPy, 154 bytes
```
from numpy import*
r=rot90
def f(n):
a=diag([1,1]);y=x=2-a
for i in r_[:n]:x=pad(r(x),a);y=pad(r(y),a)|x.T;x^=x.T;a<<=i&1
return r(choose(y," /\\"),-n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9BTsMwEEX3PsXIi2pcOYGwQCWtD8CeXVOQRezWqLGtiSPZEieBTTdwJ25DQ0Gsvr70Z_7775-xpEPwp9PHlGy1-nqzFAbw0xALuCEGSktGikK6u2a9sWDRi5aBVr3Te9w2stmJdVFZ3VSagQ0EDpwHetq2ftdmFXWPhFlIPccurszuNdcP6_yoZtGbjXKLhgGZNNH5Gp8PIYwGi-Rw1XVcyMqLX8L7_xLt9wZvZ55IzidcIuf1S3D-XPjDkueYRSfqFI5uTCiEHE1UvPNcsMvDv-nf)
#### Old Python/NumPy, 156 bytes
```
from numpy import*
a=c_[:3]==[1,2]
r=rot90
def f(n):
y=x=2-a[1:]
for i in r_[:n]:y,x=pad([r(y),r(x)],a<<i//2);y|=x.T;x^=x.T
return r(choose(y," /\\"),-n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY_LTsQgGIX3PAVh9TOhrVMTo53hAdy7a9GQGXAwFshfmkDim-hiNvpOvo2tl7g6m3P5zutHLOkU_Pn8PidbXX--WQwj9fMYC3VjDJg2RMvDQ99dKin7rWgVQYkh3VyQo7HUgucdoUVm2Va633aKUBuQOuo8xSXmVVdEllEfoUcoXCBkroTe713TtHxXXmSu73b5fhVC0aQZlyQcTiFMBopgtBkGxkXl-S_j7f-A9o8GrlaCiM4n2ABj9VNwfhn55sirzYLjdQrPbkrAuZhMlGzwjJOfwr_zXw)
#### Old Python/Numpy, 159 bytes
```
from numpy import*
a=c_[:3]==[1,2]
r=rot90
def f(n):
y=x=2-a[1:]
for i in r_[:n]:y,x=pad([r(y),r(x)],a<<i//2);y|=x.T;x^=x.T
return r(choose(y,[*" /\\"]),-n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9LTsMwFEXnXoXl0XPkJDRICNJ6AZ0zSwyKWpsaNbb14ki2xE4Y0Ansid2Q8BGjO7mfc18_Qo4n7y6X9zma8vbzzaAfqZvHkKkdg8dYkEEeHrv2WknZbUSjCEr08e6KHLWhBhxvCc0yyaYcuk2rCDUeqaXWUVxiTrVZJBmGI3QImQuExJUYdjtb1w3f5heZqvtteliFUNRxxiUJh5P3k4YsuoLRuu-Z4qJ0_Bdz_78xuCcNNytEQOsiFMBY9eytW3a-UdJqM2B5Ff3ZThE4F5MOkvWOcfJT-Pf_Cw)
#### Old Python/NumPy, 163 bytes
```
from numpy import*
a=c_[:3]==[1,2]
def f(n):
y=x=2-a[1:]
for i in r_[:n]:y,x=pad([rot90(y),rot90(x)],a<<i//2);y|=x.T;x^=x.T
return rot90(choose(y,[*" /\\"]),-n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZDBTsQgFEX3fAVhBQ1tnZoY7Qwf4N4dRUNmwMHYB6E0gcQ_cTOJ0X_yb2xnNK7eXZzce_Lev0JJRw-n0-ecbH37_WGjHzHMYyjYjcHHVCEt9k-yv1ZCyA3vFDoYiy0F1iNcRBZdreWmVwhbH7HDDnBccFB94VkEfaAy-nR3RQvjl5CZ4nq3c23bsW15E7l52ObH9SAcTZrj0nAG90fvJ0MLlxXB7TAQxXgN7Ff1_n9Pw7OhN6tQiA4SrSghzYt3sGydtfKKWepYk_yrmxJljE8mCDIAYehS-PeDHw)
#### Old Python/NumPy, 168 bytes
```
from numpy import*
a=c_[:3]==[1,2]
def f(n,o=2*[a[1:]+1]):
for i in r_[:n]:y,x=b=pad(o,a<<i//2);y|=x.T;x^=x.T;o=rot90(b.T,3).T
return rot90(choose(o[0],[*" /\\"]),~n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZBBTsMwFET3PoXllR1M0qQSoml9APbZOQa5bUxdEX_LcSRHQlyETTcgrsRtaAMVq5FGo5mnef_0UzyAO50-xmhu77-_TIAeu7H3E7a9hxAzpMXuSdZLJYQseaXQvjPYUMdBVJnUsqzVTalYjbCBgC22Dodz3ql64klshdd7ClxvNrYoKraeXkXKm3V6nAVEgLha0G3e8CXLG4RDF8dwrpjt3QFg6CjIheIyI7hoW6IYf3Psj_fhf1O7547eXTh8sC7SjBKSH8E6mtiMli4xQy3LI7zYIVLG-NB5QVpHGPotvB7xAw)
#### Old Python/NumPy, 173 bytes
```
from numpy import*
def f(n,o=2*[mat("2 1;1 2")]):
for i in r_[:n]:y,x=b=pad(o,eye(3,2,-1,int)<<i//2);y|=x.T;x^=x.T;o=rot90(b.T,3).T
return rot90(choose(o[0],[*" /\\"]),~n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZBBTsMwFET3OYXl1f-RmzSphCCpD8A-uySglNrUVeNvOY6USIiLsOkGdhyI29AGEKuRRqOZp3n7cHM4kD2f38egV7dfn9pTz-zYu5mZ3pEPcbRXmmmwgmQe130XgOcsKzOWc2yxiJgmzwwzlvnHurBtMYtJ7qTr9kBCzQo2IherTBgbcLs1aZpjOb_IKanK6WERkp7C3Rp2SSU2mFQR8yqM_lK42E8HokEB1etW1DFnadPwFsWrxV_o-3-Czj4ruLlSOX8ZhBg4T45kLEy4gE7XmAaDSaCTGQIgikE5yRvLMfop_HvjGw)
## How it works
It loops up to size `n` maintaining a full (`y`) and an outline only (`x`) version of the pattern at each size. The patterns are rotated 90° in each step such that the next larger rectangle always is added bottom left. In each step `x` and `y` are padded with whitespace such that the transpose of `x` can serve as the new rectangle. And we can simply `or` `x.T` and `y` to create the next `y`. The new `x` is obtained similarly, only we erase the joining line by using `xor` instead of `or`.
[Answer]
# Python 3, ~~328~~ 239 bytes
* Merged the two fors thanks to @oupson and added `v=i//h` (-3)
* Changed to one space indentation (-2)
* Changed `v=i//h` to `v=i//h*(t+1)` (-2)
* Changed the for to a while (-1)
* Removed the space before `and` (-1)
* Added z=i%h\*-~-t-t (-5)
* And much more, done with @oupson (-75)
```
def f(n):
t=(1<<~-n//2)*(3-n%2)+1;l=list((" "*~-t+"\n")*t);s=0
while n:
w=1<<n//2;h=w>>~n%2;a=h*t;i=w*h
while i:i-=1;v=i%w*-~t+s;z=i%h*-~-t-t+s;l[v+h],l[a+z]=l[a+v],l[w*t+a+w+z]="\\/"
s+=(w*t+w,a,0,h)[n%4]//2;n-=1
print(*l,sep="")
```
[Try it online!](https://tio.run/##HVDLasMwELz7KxaBQU8cJT1F2fyI7YOhTiUQG2MLi@bgX3elnnZmmNnX8pv8m27n@T2/4MVJ3BtIyO3jcRjququQ/GaovQplXcQYtsQ5AyYPkxQbiAmZhNvw0kD2Ic5AJQ8ZS76mncf8fB4l7yb0MrmAWfrq@DeHezBo3Y6hzdIcSW3uU7Av2CRTaex35Ucd@0l9RqxlryzLpCaVq8aGoWOl46aQVznrSV@0Fz21X2NdgcqIBpY1UOIy6m1ekDHRNK/3CgECwTrRz8ytBmvr9eULQZznHw "Python 3 – Try It Online")
I would like to learn from this first experience, so please give me advice and golf bytes away. (Looks like a lot had to be golfed)
I probably took the wrong approach (as in lengthy/inefficient), but still decided to make the best of it.
* The f function creates the matrix and then the string to print.
* The q fonction draws a rectangles of size n to the list l. It is recursive, and for each subsequent call we offset the origin (s in the first version, x and y in the second).
Output of f for n=4 without the recursive call in q:
```
/\
/ \
\ \
\ \
\ /
\/
```
Moving the origin - where to write the next rectangle - is certainly the part of the program that needs the most improvements.
Original ungolfed version:
```
def f(n):
t = 2**(n//2) + 2**((n-1)//2)
lines = [[" "]*t for _ in range(t)]
def squares(n, x=0, y=0):
w = 2**(n//2)
h = 2**((n-1)//2)
for i in range(w):
lines[y+i][x+i+h] = lines[y+i+h][x+i] = "\\"
for i in range(h):
lines[y+h-i-1][x+i] = lines[y+w+h-i-1][x+w+i] = "/"
if n>1:
squares(n-1, x + w//2 * (n%4==0) + h//2*(n%4==3), y + (w//2) * (n%4==0) + (h//2) * (n%4==1))
squares(n)
print("\n".join(map("".join, lines)))
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 216 bytes
```
n=>[...Array(h(n)+h(n-1))].map((_,y,a)=>a.map((_,x)=>g(n,x,y)))
g=(n,x,y,p=h(n),q=h(--n),r=p+q)=>x>=0&y>=0&x<r&y<r&(x==q+~y|x==q+y|x==y-q|x==r+p+~y)?'\\/'[(x+y+q)%2]:n?g(n,n--&2?x-h(n):x,n&2?y-h(n):y):' '
h=n=>1<<n/2
```
[Try it online!](https://tio.run/##NY/dboMwDIXv@xS5GYmVnxYuKQbtOUo1oa5QKpZAOk2JNO3VmUO3C/s7xzqJ5Xv31T0ufpw/tXXv17XH1WJ9Msa8et9FcRMWJDWdA5zNRzcL8aai6gDr7t8GMoOwKqgIALsBn1rNmF6rhaA1CY@zXCgbajxkMbVQ@SxSiYC4yJ/4vXFD1EuClzPNoeFtu@cnEWSkL16Kc2mbtNJqnRVN0GlRGZQlE58mQskZ392Qzsmryu6LtXeeiZEhy49sZBXxQEJKYBdnH266mskNFJCMl63lxF6MsF05YT2Zuxut4BzgT1EGUjhx/QU "JavaScript (Node.js) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 135 bytes
```
' /\\/'{~[:p:inv@{.@q:"+@>({.!.1*[({.!.1|.~*@[*$@])](*+1-])1 p:])&.>/@((<p:1+i.2 2)}.@|.@, ::[[:;/$&(4 2$1|.4#1 _1)*]{.3*/\@,$&4r3 3r2)
```
[Try it online!](https://tio.run/##JcyxboMwFEbhvU/xlyKwDVzHhnS4TaMrRcqUKauxOlSJQoeGMnSB8uoEqcPRt52vJaH8indGjhIb8FpFOJxPxyWHbVubj3PgnrvvXxlJfjgpZK9GeiZnwr8TzUaCSSXqqEzhqqgdeo46o70VpXY9u6IjD6//SCaSEswh8JtNM9XAp@uheXH4cNrEkWpjWynTrBlq1IPXi366fN7uuCYFHDxqNNjidXkA "J – Try It Online")
## the idea
Notice that each iteration is a diagonal rotation of the previous one,
layered on top of it. Let's draw this out to clarify. We'll
use `.` instead of space in our drawings:
```
/\.
\/. Initial state layer, expanded with spaces down and right.
...
...
./\ Initial state layer, diagonally rotated down and right.
.\/
/\.
\/\ The two layers stacked and "added" together elementwise.
.\/
```
The "addition" of those two layers (3rd picture) is the new state, with the
center `/` repeated. We need to track that, because we want to remove repeats
when we iterate again:
```
./\.
.\/\ Current iteration, expanded with spaces down and left.
..\/
....
....
/\.. Current iteration, diagonally rotated down and left, with all
\.\. previous "repeats" removed.
.\/.
./\.
/\/\ Those two layers stacked and added elementwise.
\.\/
.\/.
```
Note that now, in the 3rd picture, we have 3 "repeat" slashes. I'll highlight
their locations with `*`:
```
./\.
/**\ Elements that have been added to themselves in any previous
\.*/ iteration.
.\/.
```
We continue this process -- expanding, rotating and removing repeats, and
"adding" layers. The next direction will be up and left, then up and
right, then down and right again, continuing cylically:
```
down & right down & left up & left up & right
\ / * *
\ / \ /
* * \ /
```
## implementation notes
The entire calculation is a single fold, which begins with the initial 2x2
diamond matrix, and precalculates the magnitude and direction of all the
diagonal rotations:
* `]{.3*/\@,$&4r3 3r2` Precalculates the new side of each iteration's square
matrix:
```
3 4 6 8 12 16 24 32
```
This is a geomtric series, with an alternating multiplier: Start with 3,
multiply by `4/3`, then multiply that result by `3/2`, then that result by
`4/3`, and so on.
* `4 2$1|.4#1 _1` A golf for the directions of the diagonal rotations. It
evaluates to:
```
1 1 down/right
1 _1 down/left
_1 _1 up/left
_1 1 up/right
```
* `(<p:1+i.2 2)` To track repeats, we encode the starting matrix using primes:
```
┌────┐
│3 5│ corresponds to /\
│7 11│ \/
└────┘
```
+ And when we "add" the layers we'll use multiplication, with spaces encoded
as ones. This lets us detect repeats by checking if a cell is prime.
* `[:p:inv@{.@q:"+` At the very end, each element will either be a prime or a
prime power. So we can take the first factor `{.@q:` to recover the
"non-repeat" version of each cell. Finally, we use the inverse prime function
`p:inv` to turn the pries back into the numbers `1 2 3 4`, which we use to
index into `/\\/`.
[Answer]
# Ruby, 339 bytes
```
f=->n{a,j,v={0=>r=t=[0,1],1=>r},[[1,-1],[-2,2]],[1,1]
n.times{|q|a.merge!(a.to_h{|y,x|[y+v[0],[x[0]+v[1],x[-1]+v[1]]]}){|k,x,y|t|=x|=y
x.sort}
v=v.zip(j[q%2]).map{|x,y|x*y}
r,t=[a.keys,t].map &:minmax}
o=(0..r[1]-r[0]).map{" "*(t[1]-t[0])}
a=a.to_h{|y,x|[y-r[0],x.map{|z|z-t[0]}]}
a.each{|y,c|c.map{|x|o[y][x]="/\\"[(x+y+(n>1?1:0))%2]}}
o}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZHPTsMgHMfjlaeYNZp2o1h2MkuYD-GREoNLq91WujHWwIDEh_DmxYM-lB59Emm7xXgxIfD78-H3_QZe3-X-wby9fexVmd58nd2VJJ0Ly-EStsRmZC6JIjSDmEEcEg8pxTANGU2ncMrCiUMPCKSquthZt3Uc1YV8LM5jjlRz_2SdgdpRM2lpFmgd9hCGAZqGMX3ImE-sW0ENjVOOaEcM0GjXSOVBS1p0qDbxkm4vpyxBNd9Y14F6bDyQMJjjaFWYHVSsa46uZnUlaq49aEicISSDQCqD6nA3GkXjWHU11dU84OSvz56FehA6uEPPeRZAVPBFjy3c4ujDNdQwqhmJrvM8orGemEks5vgWz7IkCYZ9sOGHt_1sOjsYJ8c5woGNrIQaRbkoL6zwuYhASQU79tduaK9_scif4u_nl39WLjp2kD197Q8)
* Not the best answer around but I tried at least to do the job.
* Thanks @emanresu A for providing an online compiler(Tio Ruby version didn't work ).
* Returns an array of strings.
We generate an Hash where Keys are row indexes(allowing negative keys) and Value is an Array of written indexes on each row(also negative allowed)
```
/\ 0(0,1) > We get bounds.
\/ 1(0,1) > Pivot starts at 1,1
```
>
> Add Pivot to Bounds
>
> Add to Hash
>
>
>
```
/\ 0(0,1) H<= (1,1)+S
\/\ 1(0,1,2)
\/ 2(1,2) B=0(0,1)1(0,2)2(1,2)
```
next pivot is P\* [1,-1]or[-2,2] alternately
```
/\ 0(0,1) H<=(1,-1)+B=
/\/\ 1(-1,0,1,2) 1(-1,0)2(-1,1)
\ \/ 2(-1,1,2) 3(0,1)
\/ 3(0,1)
B=0(0,1)1(-1,2)2(-1,2)3(0,1)
```
To draw the pattern we take an array of strings of spaces of minMax(Keys,values) dimensions
and we iterate our Hash to overwrite / or \ based on modulo2(x+y)
* n=0 and 1 require to invert
] |
[Question]
[
Your challenge is to write a function/program that takes a matrix of integers m and a number n as input and:
* Splits m into n by n chunks
* Replaces each chunk with the most common value in that chunk (In case of a tie, any of the tied values is fine).
* Outputs the resulting matrix.
Note: You can take either the size of a single chunk, *or* the number of chunks to a side.
Example:
```
0 1 0 1
0 0 1 1
0 0 0 0
0 0 1 1,
2
```
Divide into chunks:
```
0 1|0 1
0 0|1 1
---+---
0 0|0 0
0 0|1 1
```
Take the most common value in each sub-matrix
```
0|1
-+-
0|0
```
So
```
0 1
0 0
```
is the result!
Note: You can assume that there will always be an integer amount of chunks with integer size.
Input will always be square.
# Testcases
These are formatted as taking the size of a single chunk.
```
0 1 2 1 2 1
2 2 1 0 2 2
2 1 2 0 1 0
0 0 1 0 3 2
3 0 2 0 3 1
1 0 3 2 0 1,
3 =>
2 1
0 0
(The 1 is a tie, any of 012 are fine)
0 1 2 1 2 1
2 2 1 0 2 2
2 1 2 0 1 0
0 0 1 0 3 2
3 0 2 0 3 1
1 0 3 2 0 1,
2 =>
2 1 2
0 0 3
0 2 1
(The 3 is a tie, any of 0123 are fine)
1,
1 =>
1
(kinda obvious edgecase)
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~40~~ 38 bytes ([SBCS](https://github.com/abrudz/SBCS))
Anonymous tacit infix function taking chunk size as left argument and the input matrix as right argument.
```
{(∪⊃⍨∘⊃∘⍒⊢∘≢⌸)∘,¨↑(⊂⊂¨⊂[1]∘⍵)(≢⍵)⍴⍺↑1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rjUceqR13Nj3pXPOqYAWIAyd5Jj7oWgRidix717NAEsnQOrXjUNlHjUVcTEAHZXU3RhrFgpVs1NUDKgPSj3i2PencBlRnW/k971DbhUW8f2OA1QIlD642BEo/6pgYHOQPJEA/P4P9GCmkKEEGvYH8/9ehoAx1DHSCO1QGyQGwYCwiRxGLVuXR1dbmMsek2gmCgaiMw2wBIGoF5IHGw@XCTDHSMwXLGYFUgHkgfVBzsDqhNRnSzyRDdJpAMAA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` [dfn](https://apl.wiki/dfn); `⍺` is chunk size and `⍵` is matrix:
`2` and
`⎡0,1,0,1⎤`
`⎢0,0,1,1⎥`
`⎢0,0,0,0⎥`
`⎣0,0,1,1⎦`
`⍺↑1` take "chunk size" elements from 1, padding with zeros
`[1,0]`
`(≢⍵)⍴` cyclically reshape that to the number of rows in the matrix
`[1,0,1,0]`
`(`…`)` apply the following tacit prefix function:
`⊂[1]∘⍵` use the argument to partition the matrix vertically
`⎡0,1,0,1⎤ ⎡0,0,0,0⎤`
`[⎣0,0,1,1⎦,⎣0,0,1,1⎦]`
`⊂⊂¨` use the entire argument to partition each of those horizontally
`⎡0,1⎤ ⎡0,1⎤ ⎡0,0⎤ ⎡0,0⎤`
`[[⎣0,0⎦,⎣1,1⎦],[⎣0,0⎦,⎣1,1⎦]]`
`↑` mix into a matrix
`⎡ ⎡0,1⎤ ⎡0,1⎤ ⎤`
`⎢ ⎣0,0⎦,⎣1,1⎦ ⎥`
`⎢ ⎡0,0⎤ ⎡0,0⎤ ⎥`
`⎣ ⎣0,0⎦,⎣1,1⎦ ⎦`
`(`…`)∘,¨` for each element, ravel (flatten) it and then apply the following tacit prefix function:
`⎡ [0,1,0,0],[0,1,1,1] ⎤`
`⎣ [0,0,0,0],[0,0,1,1] ⎦`
`⊢∘≢⌸` for each unique element, count the indices it occurs at
`⎡ [3,1],[1,3] ⎤`
`⎣ [4] ,[2,2] ⎦`
`∪`… with the unique elements…
`⎡ [0,1],[0,1] ⎤`
`⎣ [0] ,[0,1] ⎦`
`∘⊃∘⍒` get the index of the largest count (lit. first element of the permutation vector that would sort the counts descending), then…
`⎡1,2⎤`
`⎣1,1⎦`
`⊃⍨` use that to pick from the list of unique elements
`⎡0,1⎤`
`⎣0,0⎦`
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
(0{~.\:1#.=)@,;.3~2 2&$
```
[Try it online!](https://tio.run/##fU3BCsIwDL3nKx5T3Ao1tOmtZTAQPHnyLHgQN/HiBwj79Zp1xYMHCUle3iPvPXPD7Yg@ooWFQ9TeMw7n0zF37j3zJfoN92awicMskN02G5r6eL89XkOX0jgbWjAEExpOfBV0xceQg1c7r3tB69b63v8/ZW2SgpxOoZUrvtXFISgfir5gT5UryTXBa4KNPxmq5g8 "J – Try It Online")
J's `u;.3` is pretty handy for this. It splits a matrix into rectangles. You just need to give the size of the rectangles and the offset between rectangles. So for `3x3`-tiles the input would be `[[3 3],[3 3]]`. That is handled by `2 2&$` (if we can take width and height of a tile as input, that would be `;.~` for -2 bytes). For each tile `;.3~` we flatten the tile `,` and sort `\:` the unique values `~.` by their occurences `1#.=` and take the first one `0{`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
2Æ=yòV)ËËc ü ñÊÌÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=MsY9efJWKcvLYyD8IPHKzMw&input=WwpbMCAxIDIgMSAyIDFdClsyIDIgMSAwIDIgMl0KWzIgMSAyIDAgMSAwXQpbMCAwIDEgMCAzIDJdClszIDAgMiAwIDMgMV0KWzEgMCAzIDIgMCAxXQpdCjIKLVE)
```
2Æ=yòV)ËËc ü ñÊÌÌ :Implicit input of 2D-array U and integer V
2Æ :Map the range [0,2)
= :Reassign to U
y : Transpose
òV : Partition rows to length V
) :End reassignment
Ë :Map
Ë : Map
c : Flatten
ü : Group & sort by value
ñ : Sort by
Ê : Length
Ì : Last element
Ì : Last element
:Implicit output of last element in the range
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
thZCtvXM[]e
```
[Try it online!](https://tio.run/##y00syfn/vyQjyrmkLMI3Ojb1/38jrmgDBUMFILYGEiAmlAGEcJFYAA) Or [verify all test cases](https://tio.run/##y00syfmf8L8kI8q5pCzCNzo29b@6rq56hEvIf2OuaAMFQwUjCLYGEiCmAYi2hoqC5A2sgRSYoWAMkjEGKwFxgHqgoiD5WC4jahtoyBVtGAsA).
### How it works
```
th % Implicit input: number n. Horizontally concatenate with itself to give [n n]
ZC % Implicit input: matrix m. Im2col: arrange each [n n] block as a column of
% length n*n
tv % Vertically concatenate with itself. This makes columns twice as long without
% affecting their mode. This is needed in case the previous result had a single
% row (n=1), which would cause the subsequent mode function to compute the mode
% of that row, instead of the mode of each column
XM % Mode. This gives the mode of each column (the input has at least 2 rows)
[]e % Reshape as a square matrix. Implicit display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
Zs€Zs€ẎF€ÆṃḢ€
```
[Try it online!](https://tio.run/##y0rNyan8/z@q@FHTGjDxcFefG5A63PZwZ/PDHYuAzP8Pd295uGMTkBUGxCC55Ye2Fvscbju0V8X9/38DBUMFIwjmMgKzDICkERdEDCRrwGUAoRWMgeLGYHkQ25ALKgaS/W8EAA "Jelly – Try It Online")
## How it works
```
Zs€Zs€ẎF€ÆṃḢ€ - Main link. Takes M on the left and n on the right
Z - Transpose M
s€ - Slice each row into n pieces
Z - Transpose
s€ - Split each group of columns into n pieces
Ẏ - Flatten into a list of n x n matrices
F€ - Flatten each matrix
ÆṃḢ€ - Get the first mode of each
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
sZ€FÆṃḢƊ⁹ÐƤ€
```
[Try it online!](https://tio.run/##y0rNyan8/7846lHTGrfDbQ93Nj/csehY16PGnYcnHFsCFPx/eLm@u2bWo8Z9h7Yd2vb/fzRXdHS0gY6CoY4CiIzVUQDxIAJIPBBCk4vVMYrVQeg2gpMgdUYwAQMwwwgqBlEBtQ7FPCBpDFVnDNMFEQObh1ABdWesjvGA2g71O4hpGMsVCwA "Jelly – Try It Online")
After several 13s, I found a 12. A dyadic link taking the grid as a list of lists of integers on the left side and the size of the split on the right.
## Explanation
```
s | Split into sublists of the length specified by the right argument
Z€ | Transpose each
Ɗ⁹ÐƤ€ | For each sublist, do the following for each non-overlapping infix of the length specified by the original right argument:
F | - Flatten
Æṃ | - Mode
Ḣ | - Head
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
```
BlockMap[Commonest[Join@@#,1]&,#2,{#,#}]&
```
[Try it online!](https://tio.run/##vY5BCsIwEEX3PUUh0NWAabIWguJGEASXpYsQWlo0iWh2Ib16nKSt1AvIMANv/s/8aOmGTks3Khn7fTw8rLpf5LM5Wq2t6d6uOdvRCEGgbisgDDwBEtoqXl@jcTvRC3FSgxWkmm5KmskXnkFRek@hBuyAUCIk3ADWrxIQPf@@ZHPPHpaR4mTrIqk5YXuFAl8dPNvTYrmxqPlLOYv9MavOWQmKED8 "Wolfram Language (Mathematica) – Try It Online")
Input `[n, m]`. Returns a matrix of singleton lists.
[Answer]
# [R](https://www.r-project.org/), ~~130~~ ~~124~~ ~~121~~ ~~116~~ 111 bytes
*-5 bytes and another 3 thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*
```
function(M,n,k=dim(M))array(Map(function(x)el(names(sort(-table(x))):0),split(M,t(a<-(row(M)-1)%/%n)*k+a)),k/n)
```
[Try it online!](https://tio.run/##ZY/dDoIwDIXv9x4mrZa4QeKFkUfgzntTESOBDR0jwtNjwZ8YTbN0@057uvqxvXXsi0N@6VyVjufO5aFsHGTkqEpPpYUMkb3nATK@wkfvsajBsS1aaBsfIAp8rAvBiFuN1F7rMohJAN5F4Ju72EQGF@uFw2W1YkSq1g5Hm1oOvuwhB02G4tdR8Zw0TVk9qZ6B0q9LMinJXDI9pOdNRUfaSBwHGZzuUanvJcFSgr8k/iPmlzz/aWSS2BscHw "R – Try It Online")
Longer approach than [@Dominic's](https://codegolf.stackexchange.com/a/229841/55372), but I thought it's worth a try.
Builds matrix mask `t(a<-(row(M)-1)%/%n)*dim(M)+a` used then in `split`, for example for matrix \$6\times6\$ and \$n=2\$:
```
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 6 6 12 12
[2,] 0 0 6 6 12 12
[3,] 1 1 7 7 13 13
[4,] 1 1 7 7 13 13
[5,] 2 2 8 8 14 14
[6,] 2 2 8 8 14 14
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~29~~ 28 bytes
-1 byte from @Traws
```
{(*>#'=,/)''2(+(0N;y)#/:)/x}
```
[Try it online!](https://ngn.bitbucket.io/k/#eJytkE0KwjAQhfc5xaNdNNFA87Nr0CN4AXFRtEVBk9JWtIie3SStIIo7EzLz3gxkPqYubnS2TLMFz1mWKTqnYmUGluYFy693QqiANAKCPep10Ji8V2P29+WZURtCcsiuR+suHMrusHXH88liX3ZIZALaVC0a1/UcpR3gagipULYV6oOtGKHqY54an1FRCR+VGWuRZpotoH1dx37Q0ky10GVGR66AE7l0+8V1sGiO5bYKRIn+wak/QP1IMS3Eu/8ih1VSzuOvPhnp/dt5Aj33X88=)
Based off of @Shaggy's [Japt answer](https://codegolf.stackexchange.com/a/229833/98547). Takes the input matrix as `x` and the chunk size as `y`.
* `2(...)/x` set up a do-reduce, seeded with `x` and run twice
+ `(+(0N;y)#/:)` slice each row into `y`-length chunks, then transpose them
* `(...)''` run the code in `(...)` on each chunk in the transformed matrix
+ `(*>#'=,/)` group the flattened chunk contents, counting the number of times each distinct number appears, then sort descending and return the first value (i.e. the mode)
[Answer]
# JavaScript (ES6), ~~136~~ 135 bytes
Expects `(matrix)(chunk_size)`.
```
m=>n=>m.slice(-m.length/n).map((_,y,a)=>a.map((_,x)=>eval("for(o=K={},i=n*n;i--;)(o[v=m[y*n+i/n|0][x*n+i%n]]=-~o[v])<K?0:K=o[V=v];V")))
```
[Try it online!](https://tio.run/##rY9Bb8IgHMXvfArSZBHUIqu3dXSn7WKyi4mX2iysUmUpfzpaG41zX72j7cy@wA7Ae7/3IPw/ZCvr3OmqCcHuVFeIzogERGJYXepckdCwUsG@OSyAMiMrQt7m57mkIpE3e/JGtbIkQWEdsWIlLte5FjCFWIdhTIlNW2HS8xRmegFfPEtPvbyDLBPhtw8z@rh64g8rYdONaLN4E1BKO6c@j9opMinqCWVOyd2LLtX6DDnhlDV23TgNe0JZXZW6IcEWthBQ5v/wLPMDqbFI8AVhLLHA9V8poLGH4OFMsspWZPDG@3Eg199ztz4Oxqlfj@ZdOTp0cwu1LRUr7Z4UxFACPb/SjuN7HI0LRYPifo/QyPqUIz6eeOn5csh7fY9@WZ@iJUL/9VSEkAc/ "JavaScript (Node.js) – Try It Online")
### Commented
This is a version without `eval()` for readability.
```
m => n => // m[] = matrix; n = chunk size
m.slice(-m.length / n) // get an array of m.length / n entries
.map((_, y, a) => // for each value at position y in this slice:
a.map((_, x) => { // for each value at position x in this slice:
for( // chunk loop:
o = // o is used to store all counts
K = {}, // K is used to store the highest count
i = n * n; // start with i = n * n
i--; // stop when i = 0 / decrement it
) ( o[ //
v = m[ // v is the value in m[]
y * n + i / n | 0 // at row y * n + floor(i / n)
][ // and column x * n + (i mod n)
x * n + i % n //
] //
] = -~o[v] // increment o[v]
) < K ? 0 // do nothing if it's less than K
: K = o[V = v]; // otherwise update V to v and K to o[v]
return V // implicit end of for(); return V
}) // end of inner map()
) // end of outer map()
```
[Answer]
# Python 2, 174 bytes
Quite long, very ugly, possibly the most comprehensions I've used in one statement. There is undoubtedly a better way to do this but I can't look at this thing anymore.
```
def f(m,n):l=len(m);r=range(0,l,n);b=l/n;print('%s '*b+'\n')*b%tuple(max(v,key=v.count)for v in[sum([x[k][j:j+n]for k in range(n)],[])for x in[m[i:i+n]for i in r]for j in r])
```
[Try it online!](https://tio.run/##tVFLcoMwDN37FN5ksBO1JWYHw0kcLyA1LT/BgGHI6ak/NM0FOh55nvSeLEsaH@Z7QLHvn7qiFesBedrlnUbW82zKpwK/NIuhs/GszLsPzMapRsOi00yjc3mJbhjxc3kyy9hp1hcbW6HVj3x9vw8LGl4NE11pjXJeeiY32SrZpM0FlSNaS9BQArkCqbx8c/Je1ml9yGov87AJkO9Gz@ZezHqmOZWESRnDFawpIBY65wnteY0qAoLDb4oI5gTCO7G9RXAd45/9S48hCWzihc71uQfjf0AUJP9d4OjAdgNXThQhbjh2eW48z9GkhB7LeovOIg67IseWySvF9x8 "Python 2 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 96 bytes
Takes as input an integer matrix \$ m \$, and an integer \$ n \$ denoting the chunk size.
```
lambda m,n:[[max(x:=sum(j,()),key=x.count)for j in zip(*[zip(*i)]*n)]for i in zip(*[iter(m)]*n)]
```
[Try it online!](https://tio.run/##rY5NjoMwDIX3PoV3xAghCpsREicBFkwBTTqNiZJUgrk8daBqLzAL/73Pz7Ldws/C1Zd1@9x0@30w3@OAJuO6bc2wqrVu/MOoW6aIst9pa9b8ujw40Lw4vKFm/NNWpe2RNfUpUx@R/iAdJqfMiXZt7OIC@s1DXLsOfoqbMuc@jJpzNw2jIhmcmKXauw4q6bjjhGrA1GTI2BzGD0wI0IgqL1ulOWSoX5AI3@@YHg6vLCgWh3Wxm1U8SbQXeMHyDCiPrpBcwqlFWkBxVqxErw4e@wu8tEihAvivUyWACE8 "Python 3.8 (pre-release) – Try It Online")
Very messy use of the [split into chunks](https://codegolf.stackexchange.com/a/184881/88546) golfing tip.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 37 ([SBCS](https://github.com/abrudz/SBCS))
Anonymous tacit infix function taking chunk count as right argument and the input matrix as right argument.
```
((∪⊃⍨∘⊃∘⍒⊢∘≢⌸)∘,⍤2)1 3 2 4⍉⊣⍴⍨4⍴⊢,≢⍛÷
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X0PjUceqR13Nj3pXPOqYAWIAyd5Jj7oWgRidix717NAEsnQe9S4x0jRUMFYwUjB51Nv5qGvxo94tQE0mIKprkQ5Iae/sw9v/pz1qm/Cotw9s5Bqg5KH1xo/aJj7qmxoc5AwkQzw8g/8bKaQBtSpAxL2C/f3Uo6MNdAx1gDhWB8gCsWEsIEQSi1Xn0tXV5cJlgBEEAzUYgdkGQNIIzAOJg62AG2agYwyWMwarAvFA@qDiYKdALTOmp2WGWCwDSQIA "APL (Dyalog Extended) – Try It Online")
`{`…`}` [dfn](https://apl.wiki/dfn); `⍺` is matrix and `⍵` is chunk size:
`⎡0,1,0,1⎤`
`⎢0,0,1,1⎥`
`⎢0,0,0,0⎥`
`⎣0,0,1,1⎦`
and `2`
`≢⍛÷` the matrix size divided by the chunk size
`2`
`⊢,` prepend the matrix size
`[2,2]`
`4⍴` cyclically reshape to size 4
`[2,2,2,2]`
`⊣⍴⍨` use that to reshape the matrix
`⎡ ⎡0,1⎤ ⎡0,0⎤ ⎤`
`⎢ ⎣0,1⎦,⎣1,1⎦ ⎥`
`⎢ ⎡0,0⎤ ⎡0,0⎤ ⎥`
`⎣ ⎣0,0⎦,⎣1,1⎦ ⎦`
`1 3 2 4⍉` switch the middle two axes
`⎡ ⎡0,1⎤ ⎡0,1⎤ ⎤`
`⎢ ⎣0,0⎦,⎣1,1⎦ ⎥`
`⎢ ⎡0,0⎤ ⎡0,0⎤ ⎥`
`⎣ ⎣0,0⎦,⎣1,1⎦ ⎦`
`(`…`)∘,⍤2` on each 2D leaf, ravel (flatten) it and then apply the following tacit prefix function:
`⎡ [0,1,0,0],[0,1,1,1] ⎤`
`⎣ [0,0,0,0],[0,0,1,1] ⎦`
`⊢∘≢⌸` for each unique element, count the indices it occurs at
`⎡ [3,1],[1,3] ⎤`
`⎣ [4] ,[2,2] ⎦`
`∪`… with the unique elements…
`⎡ [0,1],[0,1] ⎤`
`⎣ [0] ,[0,1] ⎦`
`∘⊃∘⍒` get the index of the largest count (lit. first element of the permutation vector that would sort the counts descending), then…
`⎡1,2⎤`
`⎣1,1⎦`
`⊃⍨` use that to pick from the list of unique elements
`⎡0,1⎤`
`⎣0,0⎦`
[Answer]
# [R](https://www.r-project.org/), ~~113~~ ~~111~~ 108 bytes
*Edit: -2 bytes, and then -3 more bytes, thanks to pajonk*
(or [105 bytes](https://tio.run/##ZY/bCsIwDIbv@ySJZthu4IW4txBvhkg3Kg5til2Hmy8/uzlFlJDT9yeQ@KG5tdqbY3Vu@ZIPp5arUDsGS4yuDcaD2yZyA@zdHSyuOFG4YHK0N1Vwvn4Y@Ox01CNraxponA@QBF1eDdiiW6oNUz/GA2KhYsDB5lYHX3dQgSRF6ewinZKkMYsXlRMQci6yUcmmkbGJO28adaR1tLKP5@Y7FOL7vfhUhr8k/SMKhyc) by outputting a matrix of text strings representing the integers)
```
function(m,n)outer(o<-0:(nrow(m)/n-1)*n,o,Vectorize(function(x,y)el(names(sort(-table(m[x+1:n,y+1:n]))):0)))
```
[Try it online!](https://tio.run/##ZY/bCsIwDIbv@ySJZthu4MVwbyHeiMg2Kg5til2Hmy9fuzlFlJDT9yeQuNDeutLpY33u@FKEU8e1byyDIUbbee3AbhKZAzt7B4MrThQumCztdO2tax4aPjs9DaivwKXRLbTWeUh8WV01mH2/VDnTMMYDIuYyhmAKU3rX9FCDJEXp7CKdkqQxixeVExByLrJRyaaRsYk7bxp1pHW0aogXF1sU4vvD@FeGvyT9IwrDEw "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2F¹δôø}εε˜.M
```
First input is chunk-size \$n\$, second input is matrix \$m\$.
[Try it online](https://tio.run/##yy9OTMpM/f/fyO3QznNbDm85vKP23NZzW0/P0fMFCnJFRxvoGOoYQXCsTrQRmG0AJI3APJA4SIUBkGcAYekYg@WMwapAPJA@qDhIRWwsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/ipuSZV1BaUmyloGTvEmqvpJCYlwJk2v43cos4t@XwlsM7as9tPbf19Bw93/@1tTqHttn/N@KKjjbQMdQB4lgdIAvEhrGAEEkslssYqtYIgoFyRmC2AZA0AvNA4mDT4PoMdIzBcsZgVSAeSB9UHGxrLJcRjcw1BJoLpAE).
**Explanation:**
```
2F # Loop two times:
δ # Map over each row of the second (implicit) input-matrix:
¹ ô # Split it into parts equal to the first input-integer
ø # Zip/transpose; swapping rows/columns
}ε # After the loop: map over each row of matrices:
ε # Inner map over each matrix:
˜ # Flatten this matrix to a list
.M # Pop and only leave the most frequent integer in this list
# (after which the mapped matrix is output implicitly as result)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 159 bytes
```
n=>k=>n.flatMap((e,i)=>i%k?[]:e.flatMap((h,j)=>j%k?[]:(M=n.slice(i,i+k).map(K=>K.slice(j,j+k)).flat()).sort((a,b)=>(X=Y=>M.map(Z=>z+=Z==Y,z=0)|z)(b)-X(a))[0]))
```
[Try it online!](https://tio.run/##zZBLboMwEIb3nMKbKjOKgwzsKo17gIiuk1CkmNS0BscgoF2g3p2aR9VFL9DFPPT9M6NfU6lP1d860w4H17zqqaTJkaxJurC0akhVC6C5QZLmoX7K8kf9y9955Xm1ckjJhb01Nw2Gm32N4d3PHEkeN1rxylNc1sHXvukGAMULfwNOdCaZLisXkuOeLkRnPpLArxGhwMMJFGImcsTp1ri@sTq0zRuUcBUsYvEaQbx0wuc4WNmsikCslSWeJ4s@91GwsVm9hn1rzQC7F7dbvWvLSDJtfwS28eePe6E7RIQEMfg/buI/brIsynOEyD/tGw "JavaScript (Node.js) – Try It Online")
Golfing languages which have built-ins for occurrence count or chunks have concise programs. Mine is 159 bytes long.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes
```
F⪪Eθ⪪ιηη«≔⟦⟧ζFL§ι⁰«≔⟦⟧εFι≔⁺ε§λκε≔Eε№ελδ⊞ζ§ε⌕δ⌈δ»⊞υζ»Iυ
```
[Try it online!](https://tio.run/##TY7BasMwDIbP9VPoaIMGXnrcqRQGgxUCO5ocTJ01Zq7TxfEoHX12z46SdBch//o@WcdOD8deu5Q@@wH4x8XZkR/0hX8j0MMidEJMBX7ZZheCPXmuGoSbeGGbSXtv/Wns@G5886a9FkUKwv/zbeFJsALmQe1i4C3C4jqEr/IdwTNUDsrMvo9@LI0rhJmIOoaO3x5@nr5ab7hBOOirPcczN/mWwt4Z0ZFOv7N6sHnfXoeRx0ykpJSSCM8I1VobZACqWiI5NdWaEkWSpFSub4Ttym4Xl9J574MiqWmKkJ5@3B8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⪪Eθ⪪ιηη«
```
Split each column into chunks of size `n`, then split the rows into chunks of size `n` and loop over the chunks.
```
≔⟦⟧ζ
```
Start collecting the results for this chunk of rows.
```
FL§ι⁰«
```
Loop over the number of chunks of columns.
```
≔⟦⟧εFι≔⁺ε§λκε
```
Collect all of the values in this chunk of matrix into a single array.
```
≔Eε№ελδ
```
Get the frequencies of all the values.
```
⊞ζ§ε⌕δ⌈δ
```
Collect the value with the greatest frequency (chooses the first such value in case of a tie).
```
»⊞υζ
```
Save the results for this chunk of rows.
```
»Iυ
```
Output all of the results using Charcoal's default array output format.
] |
[Question]
[
**Find the runs inside an array**
A run is defined as three or more numbers that increment from the previous with a constant step. For example `[1,2,3]` would be a run with step 1, `[1,3,5,7]` would be a run with step 2, and `[1,2,4,5]` is not a run.
We can express these runs by the notation `i to j by s` where `i` is the first number of the run, `j` is the last number of the run, and `s` is the step. However, runs of step 1 will be expressed `i to j`.
So using the arrays before, we get:
* `[1,2,3] -> "1to3"`
* `[1,3,5,7] -> "1to7by2"`
* `[1,2,4,5] -> "1 2 4 5"`
In this challenge, it is your task to do this for arrays that may have multiple runs.
**[Example Python code with recursion](https://tio.run/##hVNfb5swEH/nU9zah4BCJuimqorE3jZp2mulPURRZOAIVsBGZ7M0qvrZs8PQ1Chr54dD2Hf3@3N2d7K1Vl/O5xIrEES7QrfdjrAIRQzGCrI7qUp8itYB8LqF74KaE@CTtCBUCZzZk5FaAfJfp6WyLlFWfjVkGTSoQhGt0rHRsAhtT4rzKBSbVbqN3Ak279VeVS4WwcTqF2IHlkRxAF1BJclYKLGxAqyGQZIghGMtGwSDgopaqr0rdam7MTUDsfGAl@kWVvOtratpBHfP4JF6HHtoAglSAQm1x9DLjy@qPfJvYPIVQm4vpyx@TPiU@eTeyj0GP0RjcHaQE4rD5MnPCnhIzAlsTbrf1/xFR7bRuovhiKAQy8GhVhzYmJ494oo9WuNSHcof0Uwymdmws2atywzS4HVTsgR/Xt/Am/EtPNY49DXQav7amvncgerbHMlAjvaIqBycq0bjOzGbTub3HXv/Rii1WthRSH4arx1fhYGfnzpdmJvnF6ufX@DmM9vQChvOpxu7UUSwvHoJPKno0hDZ9fUH7fPT/yBiX9mHeHMsz02t@BlqhZOVwzQLtnZkElwTe4/QP9GjIOiIn3I4O9mkSZLEwPHOxa8u3rv4MMQ0YWVJFJ3PfwE "Python 3 – Try It Online")**
[IO is flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
**Input**
Array of sorted positive ints (no duplicates)
**Output**
String of the runs separated by a space, or a string array of the runs
Does not need to be greedy in a particular direction
Can have trailing whitespace
**Test Cases**
```
In: [1000, 1002, 1004, 1006, 1008, 1010]
Out: "1000to1010by2"
In: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
Out: "1to3 5 8 13 21 34 55 89 144 233"
In: [10, 20, 30, 40, 60]
Out: "10to40by10 60"
In: [5, 6, 8, 11, 15, 16, 17]
Out: "5 6 8 11 15to17"
In: [1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 30, 45, 50, 60, 70, 80, 90, 91, 93]
Out: "1to7 9to15by2 30 45 50to90by10 91 93"
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so least number of bytes wins.
[Answer]
# Swift, 246 bytes
```
func f(_ a:[Int]){
var c=a.count,m=a+a,z=0,r:String=""
for i in 1..<c{m[i]-=a[i-1];if m[i]==m[i-1]{m[i-1]=0}};m[0]=1
for i in 0..<c{if m[i]==0 {z=1}else if z==0{r+=" \(a[i])"}else{r+="to\(a[i])"+(m[i]>1 ? "by\(m[i])":"");z=0;m[i+1]=1}}
print(r)
}
```
[Try it online!](https://tio.run/##XU7LboMwELzzFSufQDiRzSshqdtzzz0SVFEUV5YKqQhpVRDfTseGtlIPs/bOzszu9dPoPplnfWtr0v4zVYfise3LYPQ@qo5qVW3ry63teaOqsOKDErw7PPWdaV8VY56@dGTItCS327t6bApTblRVmI0sj0aT7ZVqXD8ujxLTdGwKUSr55xbO/WsQNA5KTue365lADmDGLlSMTj6yy4C5kaP6yw8X@tZ8L@mB2MvXyXUBOzAWHHE1VpoQ2@U0ee@4vve7wJs87RdSCMEJNXI1cTVzdW@rFGXgdJygiDmlnOwAvwhcDENqqRxcgiaK49WA2AiIgQTI1iCIsyUCdolO2m27f1sStwiTHad81caL3gXiTV0oFMAeyC2gy3HAPH8D "Swift 4 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~42~~ 40 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-2 thanks to Kevin Cruijssen (filter out twos, `ḟ2`, rather than replacing twos with zeros, `2,0y`)
```
ŒṖIE×LƲ€ḟ2SƊÞṪµ.ịU,Iḟ1ƊQ€Fż“to“by”ṁṖƊ$)K
```
A full program printing the result.
(As a monadic Link a list containing a mixture of integers and characters would be yielded)
**[Try it online!](https://tio.run/##y0rNyan8///opIc7p3m6Hp7uc2zTo6Y1D3fMNwo@1nV43sOdqw5t1Xu4uztUxxMoaHisKxAo7XZ0z6OGOSX5QCKp8lHD3Ic7G4Haj3WpaHr///8/2lRHwUxHwVxHwVJHwdAQiI2BGChobKCjYAKkTYG0GRCbA7EFEFuCMFCdpXEsAA "Jelly – Try It Online")**
(Too inefficient for the largest test-case to complete within 60s, so I removed `[1,2,3,4]`.)
### How?
```
ŒṖIE×LƲ€ḟ2SƊÞṪµ.ịU,Iḟ1ƊQ€Fż“to“by”ṁṖƊ$)K - Main Link: list of numbers
ŒṖ - all partitions
ƊÞ - sort by last three links as a monad:
Ʋ€ - last four links as a monad for €ach:
I - incremental differences (of the part)
E - all equal?
L - length (of the part)
× - multiply
ḟ2 - filter discard twos
S - sum
Ṫ - tail (gets us the desired partition of the input)
µ ) - perform this monadic chain for €ach:
. - literal 0.5
ị - index into (the part) - getting [tail,head]
U - upend - getting [head,tail]
Ɗ - last three links as a monad:
I - incremental differences (of the part)
1 - literal one
ḟ - filter discard (remove the ones)
, - pair -> [[head,tail],[deltasWithoutOnes]]
Q€ - de-duplicate €ach -> [[head,tail],[delta]] or [[head,tail],[]] or [[loneValue],[]]
F - flatten -> [head,tail,delta] or [head,tail] or [loneValue]
$ - last two links as a monad:
Ɗ - last three links as a monad:
“to“by” - literal list [['t', 'o'], ['b', 'y']]
Ṗ - pop (get flattened result without rightmost entry)
ṁ - mould ["to","by"] like that (i.e. ["to","by"] or ["to"] or [])
ż - zip together
K - join with spaces
- implicit print
```
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 102 bytes
```
{1_,//${H:" ",h:*x;l:+/&\x=h+(!#x)*d:--/2#x;$[l>2;(H;"to";x l-1;(~d=1)#,"by",d;o l_x);l;H,o 1_x;""]}x}
```
[Try it online!](https://tio.run/##fU9da8IwFH3frziLMlptaT5aa3Nxz/4HV3QizmExIHlIEf3r3U2FsadBOOTmnq@c88vXZRiO9qa2WVFMb2srILKTnQXq7Lx4@wir0zx5nYR0drB5XuhJoOmme9eUrEl4JyigyxUlj8NKpZNM7HuRHcih24aUOlpnDmobSIj2Hu6Dt7fppn9c7RGBdu5Mye74@d1RoJ6uaXt/8RslpQSDjlBGWERYMihJIq69i/d9r0UbBdAwqMAMA61gSlQ8NVBlCW0Ma7z7j/B0kdASRqKUWIw53pWcoeI4MiosooWCqqC4U03izxN3qv/U4Qje1WjGrYma6F2hin6oJZYSDR@F5tmQuexR8a9@md41zwYjS7TDDw "K (ngn/k) – Try It Online")
[Answer]
# JavaScript (ES6), 129 bytes
Returns an array of strings.
```
a=>(a.map((n,i)=>n+[n-a[i+1]||''])+'').replace(/(\d+)(-\d+)(?:,\d+\2)+,(\d+)/g,(_,a,b,c)=>a+'to'+(~b?c+'by'+-b:c)).split(/-\d+,/)
```
[Try it online!](https://tio.run/##nZHLasMwEEX3/QqRjSQkP@S3A0k@JAlFdpzg4lomMYVA6K@7V3JWTUtDDTOyhplzfcdv@kNf6nM7jF5vDs10XE16tWbaf9cDY71s@Wrdi23v6W0r1P52o3TPBaXcPzdDp@uGBWx3EJx5Lm@WEucu4kK6cnCS7FVqWckaIC3oaKhgn9WmFrS6UuFVy5pz/zJ07cgCy5ABn2rTX0zX@J05sSPbqjAMJUGOXE5czlwubFbhnnPy1BMEZGFxo7Fj1TVavHwXkwQysSSpJJaOtwi1GKqpLZWoJbhEcfyXqhMbTUxSUgAEDjCgAGIZFvEoD6cRIkYkiOx5bz97HU0CnyoE6UEMfrLZJRwq3JTdav4fRSuWkswaVUBhv/nvq03cdqGVS1Le1eP5C5xvnKnzjg5EgShtoK@ct35fbU5KKKX4jxjEHMZGU85@S4XmxfQF "JavaScript (Node.js) – Try It Online")
## How?
### Step #1
We first append to each number a suffix consisting of a leading `'-'` followed by the difference with the next number, except for the last entry which is left unchanged. This new array is coerced to a string.
```
(a.map((n, i) => n + [n - a[i + 1] || '']) + '')
```
Example:
```
Input : [ 1, 2, 3, 5, 9, 11, 13, 20 ]
Output: "1-1,2-1,3-2,5-4,9-2,11-2,13-7,20"
```
### Step #2
We identify all runs in the resulting string and replace them with the appropriate notation.
```
.replace(
/(\d+)(-\d+)(?:,\d+\2)+,(\d+)/g,
(_, a, b, c) => a + 'to' + (~b ? c + 'by' + -b : c)
)
```
Example:
```
Input : "1-1,2-1,3-2,5-4,9-2,11-2,13-7,20"
Output: "1to3-2,5-4,9to13by2-7,20"
```
### Step #3
Finally, we split the string on the remaining suffixes, including the trailing commas.
```
.split(/-\d+,/)
```
Example:
```
Input : "1to3-2,5-4,9to13by2-7,20"
Output: [ '1to3', '5', '9to13by2', '20' ]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~125~~ 118 bytes
```
->a{i=y=0;a.chunk{|x|-y+y=x}.map{|z,w|2-i<(s=w.size)?"#{w[i*s]}to#{w[~i=0]}"+"by#{z}"*(z<=>1)+' ':' '*i+w*' '*i=1}*''}
```
[Try it online!](https://tio.run/##VVDLboMwELznKyxyIAGDbAwktHH6IcgHEiWKVTWJCoin@@t07PTSw8zujmdnJX@3p2G5yiU6VpOWg2TvVXy@tffPae7naAgH2Zv4q3pO80i7OYn0YVPLLq71eNl@eOupK3VQK9M8bPujJVPGC73TsJ5G4wWb8SCPfBv6xH8DAh12gauSm8D3zdLIclVyxhgl4MRx6jh3vLfMmaJwUYJ3QUlGiZXRJdAE7JmVCmgphkQIZ0dkAgggBXIXAmP@Wscqx8Ttnd2//NSdgL6jpPhzipfbhaFmLhAOYA8UFvAVQq1UfKnON/t9z7apybXslVl@AQ "Ruby – Try It Online")
### Explanation
Ruby's Enumerable has a useful `chunk` method that does precisely what we need here - it groups items by consecutive runs of the same return value from the block, in our case - the difference between the current (`x`) and previous (`y`) value.
The caveat is that such strategy won't capture the first element of the run, e.g. here only the two last elements are grouped together:
```
Input: [5, 6, 8, 11, 15, 16, 17]
Grouped: [[5, [5]], [1, [6]], [2, [8]], [3, [11]], [4, [15]], [1, [16, 17]]]
```
Therefore, while mapping to the correctly formatted strings, when we encounter a new potential run (chunk with > 1 item), we must track if the previous item was single (`i=1`) or already used in another run (`i=0`). If there is an unused single item, it becomes the starting point of the run, and lowers the chunk size threshold from 3 to 2.
[Answer]
# [R](https://www.r-project.org/), ~~180~~ 175 bytes
```
r=rle(c(0,diff(a<-scan())));for(j in 1:sum(1|r$l)){l=r$l[j];v=r$v[j];i=T+l-1;cat("if"(l>2-F,paste0(a[T][!F],"to",a[i],"by"[v>1],v[v>1]," "),c("",a[T:i])[-3^F]));T=i+1;F=l<3-F}
```
[Try it online!](https://tio.run/##nU/RaoQwEHzvV0xzfYicQtYYPfW8R7/AN7GQWoUc9q6oFUrbb79uWvoDDcvsLLMzbObbrhmWFb1dhqW425FSCgyxh8RD6uHAQIplxNAw4FkjJugEhqcclCSItfYBiBW0QqKQssMg9dsEMiDOyv5C2MlShvxH1F73LgPjjcgUDgo5FyHXt7map0H2UoXPbhylPUZLby8y4FeO11me4S6gYnl7kfQ5P0xB8DFV3NtzV25MNk9c1eyniMrerlK4UcjpFEd1@GqXdVDStk3X3tddKNarCG3rmD29i3Y7URduv01ABGEvhdebwnVBG@nHuuMjmsrtqayr6aij@uv2nz9@Aw "R – Try It Online")
Conceptually, this is a port of my [Ruby answer](https://codegolf.stackexchange.com/a/171287/78274), though obviously quite a bit different technically.
5 bytes saved by JayCe.
[Answer]
# [R](https://www.r-project.org/), ~~238~~ 217 bytes
Thanks @digEmAll for -19 bytes.
```
function(v,R=rle(diff(v)),L=R$l,S=sum(L|1),Y=0)if(!S)cat(v)else for(i in 1:S){D=R$v[i]
N=L[i]-F
if(N>1){N=N+1
cat(v[Y+1],'to',v[Y+N],'by'[D>1],D[D>1],' ',sep='')
F=1}else{N=N+(i==S)
if(N>0)cat(v[Y+1:N],'')
F=0}
Y=Y+N}
```
[Try it online!](https://tio.run/##dVHLbsIwELznK1xaKV5hJDsJj9CaE@KEciAnRDm0NK4spQGRgFRRvj0dO1UPRT3M7Ho1M7uSj615GrTmVO0au6/4Waz0sSz4mzWGn4nEUq8eSpHr@vTBl1@KxFpLsobf5bR7aSApyrpgZn/kltmKqWlOlzk8543dBpleogwWAQzZTNEl01lfBd64WffVVoTNPhSuz9C/foab@QzTeVdCFoq6OOgwpGCh1dWt8hHcap1TlyrpN27qQrxWXoO1Rui1NXzHlZRSMHDkOfE88jxxrCTRo0vpPVc9CrxFMIhjwYaCOQ26CLMY3qEbpZgleERxfOvFsgiIgQQY3cYjYtQFI1Thpdw54//PSPwlEI0FS39scWf1a1CHfhUUwARIHaBL/16YErtnta3eywJfdjg17Tc "R – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~177~~ 173 bytes
```
a=>{for(h=t=p=d=0,o=[];(c=a[t])||h<t;p=c,t++)d||!c?c-p!=d?(o.push(...[[a[h]+"to"+p+(d>1?"by"+d:"")],[p],[p-d,p]][t-h<3?t-h:0]),d=0,h=t--):0:!d&&t-h?d=c-p:0;return o.join` `}
```
[Try it online!](https://tio.run/##fU7BjoMgFLzvV1APDQY0KNpWLfVDCEmt2LVNI8TSTTbrfrv7sHvbZg8zwGPmzVybj@bejhfrosHobj6LuRGHr7MZcS@csEILRo2QqsKtaKRT4TT1e1dZ0VJHSKinadXWbWRXQtfYxPZx73Ecx1I2slckcCYglmB9SOrg9BkQXQZBqKi0HpGmVinpon7Pa@CSqZD6QIiOorBk5Uqv1/BRawERJavGzj3GAZn4ai7DER2/56o1w93cuvhm3vEZy4QxRhFwunC28GbhnecEMsK3Py6KQM8pyinyMrilMONgz/2ogFkGj5Tzl3aITAEckAE2L0Ng0ea5HlYn8Ep8r@2/fbKlEui2FBW/Tv50L2Fw5ksgKAA7QOEBusJXnX8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~208~~ ... 185 bytes
```
import StdEnv,Data.List,Text
l=length
$[]=""
$k=last[u<+(if(v>[])("to"<+last v<+if(u<v!!0-1)("by"<+(v!!0-u))"")"")+" "+ $t\\i=:[u:v]<-inits k&t<-tails k|l(nub(zipWith(-)i v))<2&&l i<>2]
```
[Try it online!](https://tio.run/##JY5Ba8JAEIXv/opxCWFDNsWYqlU2nuyh4KFgoYeYwxqjDm42Yiahlv72xrGFebx575vDFLY0rq/qfWtLqAy6HqtLfSXY0P7VdWplyDytsSH1UX7RwKa2dEc6DbwsT4UYeOfUmoayVocSD7JbZnkgBdVCh48eOh1y3epuOBxFMaPdjZH8i20QCPGYUIAIwaPtFtNF1i66XEfokBo4@6QjMmh5/bHStTv5jZdPpJOMAoQuCPTY9y2gXo7zfkOGH0/BgyxWMFaQKHhWMFEwVTBTMFcQM4i5jrlMRozZJ@xT1oz1wpo/xHfzJO9/i4M1x6aP3tb96uZMhcV/eLeGDvW1ugM "Clean – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes
```
ŒṖIE€Ạ$>Ẉ2eƊƲƇṪµ.ịṚj⁾to;IḢ⁾by;ẋ⁻1$ƲƊµḊ¡€K
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7p3m6Pmpa83DXAhW7h7s6jFKPdR3bdKz94c5Vh7bqPdzd/XDnrKxHjftK8q09H@5YBGQlVVo/3NX9qHG3oQpQYdehrQ93dB1aCDTC@////9GGBjoKRkBsDMQmQGxmEAsA "Jelly – Try It Online")
Full program.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~170~~ 166 bytes
```
def f(a):
j=len(a)
while j>2:
l,r=a[:j:j-1];s=(r-l)/~-j
if a[:j]==range(l,r+1,s):return[`l`+'to%d'%r+'by%d'%s*(s>1)]+f(a[j:])
j-=1
return a and[`a[0]`]+f(a[1:])
```
[Try it online!](https://tio.run/##bU5BboMwEDzHr9hLBBSjYgwkuCIfQUhQAQ0WIpGhqnLp1@nYVKoi9TDj3fXM7N4f6/U2J9vW9QMNfhsoRrqc@hklo6/rOPWkL4lih4mbsq2UVjoS9dtS@iaagtfvSLPDOJD9qcvStPNH70MaCr4EyvTrp5mrZmpCb70dO@9oQu/9YYvlxV8uIqhDLK20qgN20FEpGO0eaqmdu6ppq7hudpGAaLubcV5xaCXiOOYEThynjnPHZ8siRiT7k3OCUHLKONl/VAlmEr7MjgrMUjSJlM8@LEkACaRA/hwLa74HIkygE/aE0/@rU7cdghOn4tcid5uLx5u5FVAAZ6CwgK7AVdsP "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~138~~ 136 bytes
-2 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer).
```
r=[];d=0
for n in input()+[0]:
a=n-([n]+r)[-1]
if(a-d)*d:
if r[2:]:r=["%dto"%r[0]+`r[-1]`+"by%s"%d*(1%d)]
print r.pop(0),
r+=n,;d=a
```
[Try it online!](https://tio.run/##TU7baoQwFHzefMVBELzEkou6q8UvCYG1q1JfoqQWul9vJ9k@FDKTnDlzJmd/Hp@bU@djm@YhSZLTD8a@T4Ngy@bJ0RrO/n1keWmE7RmNg6sy42zpc1NJy2hdsrGa8mLq2WVdyBvV2x4pSTodW5J6jJV3H7z3Mvl4pl9oFJlMp9yyy@5Xd5B/27c9Ezln5MvBcfw/nrHFsBKbf@YHhQWL5jRSCMEJrCLXkdvIt8BSWGYkJ7Q1p4ZTUPFS0DTcTZA6aDUKpXVwI1ABGqiBNkTA1r6GMShRyfDJ9X94HfMhXzl1f0b9Msco3E2MgwO4AV0AfJ22vw "Python 2 – Try It Online")
[Answer]
# [gvm](https://github.com/Zirias/gvm) (commit [2612106](https://github.com/Zirias/gvm/commit/26121066d5955d1b1e11ee8e34715f8ac5d60fc2)) bytecode, 108 bytes
Expects the size of the array in one line, then the members each in one line.
Hexdump:
```
> hexdump -C findruns.bin
00000000 e1 0a 00 10 00 e1 0b 00 ff c8 92 00 f4 f7 10 00 |................|
00000010 01 b0 20 03 00 ff 0a 01 a2 01 c8 92 00 f4 01 c0 |.. .............|
00000020 03 00 ff 0a 02 d0 72 01 0a 03 c8 92 00 f4 05 b0 |......r.........|
00000030 20 a2 02 c0 02 02 6a 03 8b 00 ff f6 06 b0 20 a2 | .....j....... .|
00000040 02 f4 ce 0a 02 c8 92 00 f6 07 6a 03 8b 00 ff f6 |..........j.....|
00000050 f2 b9 66 01 a2 02 00 01 8a 03 f6 05 b9 69 01 a2 |..f..........i..|
00000060 03 92 00 f4 ac c0 74 6f 00 62 79 00 |......to.by.|
0000006c
```
Test runs:
```
> echo -e "7\n5\n6\n8\n11\n15\n16\n17\n" | ./gvm findruns.bin
5 6 8 11 15to17
> echo -e "20\n1\n2\n3\n4\n5\n6\n7\n9\n11\n13\n15\n30\n45\n50\n60\n70\n80\n90\n91\n93\n" | ./gvm findruns.bin
1to7 9to15by2 30 45 50to90by10 91 93
```
Manually assembled from this:
```
0100 e1 rud ; read length of array
0101 0a 00 sta $00 ; -> to $00
0103 10 00 ldx #$00 ; loop counter
readloop:
0105 e1 rud ; read unsigned number
0106 0b 00 ff sta $ff00,x ; store in array at ff00
0109 c8 inx ; next index
010a 92 00 cpx $00 ; length reached?
010c f4 f7 bne readloop ; no -> read next number
010e 10 00 ldx #$00 ; loop counter
0110 01 ; 'lda $20b0', to skip next instruction
runloop:
0111 b0 20 wch #' ' ; write space character
0113 03 00 ff lda $ff00,x ; load next number from array
0116 0a 01 sta $01 ; -> to $01
0118 a2 01 wud $01 ; and output
011a c8 inx ; next index
011b 92 00 cpx $00 ; length reached?
011d f4 01 bne compare ; if not calculate difference
011f c0 hlt ; done
compare:
0120 03 00 ff lda $ff00,x ; load next number from array
0123 0a 02 sta $02 ; -> to $01
0125 d0 sec ; calculate ...
0126 72 01 sbc $01 ; ... difference ...
0128 0a 03 sta $03 ; ... to $03
012a c8 inx ; next index
012b 92 00 cpx $00 ; length reached?
012d f4 05 bne checkrun ; if not check whether we have a run
012f b0 20 wch #' ' ; output space
0131 a2 02 wud $02 ; output number
0133 c0 hlt ; done
checkrun:
0134 02 02 lda $02 ; calculate next ...
0136 6a 03 adc $03 ; ... expected number in run
0138 8b 00 ff cmp $ff00,x ; compare with real next number
013b f6 06 beq haverun ; ok -> found a run
013d b0 20 wch #' ' ; otherwise output space ...
013f a2 02 wud $02 ; ... and number
0141 f4 ce bne runloop ; and repeat searching for runs
haverun:
0143 0a 02 sta $02 ; store number to $02
0145 c8 inx ; next index
0146 92 00 cpx $00 ; length reached?
0148 f6 07 beq outputrun ; yes -> output this run
014a 6a 03 adc $03 ; calculate next expected number
014c 8b 00 ff cmp $ff00,x ; compare with real next number
014f f6 f2 beq haverun ; ok -> continue parsing run
outputrun:
0151 b9 66 01 wtx str_to ; write "to"
0154 a2 02 wud $02 ; write end number of run
0156 00 01 lda #$01 ; compare #1 with ...
0158 8a 03 cmp $03 ; ... step size
015a f6 05 beq skip_by ; equal, then skip output of "by"
015c b9 69 01 wtx str_by ; output "by"
015f a2 03 wud $03 ; output step size
skip_by:
0161 92 00 cpx $00 ; length of array reached?
0163 f4 ac bne runloop ; no -> repeat searching for runs
0165 c0 hlt ; done
str_to:
0166 74 6f 00 ; "to"
str_by:
0169 62 79 00 ; "by"
016c
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~49~~ 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.œʒε¥Ë}P}Σ€g2KO>}¤εD©g≠i¬s¤„toý¬®¥0èDU≠i„byX««]˜ðý
```
Way too long, but I'm already glad it's working. This challenge is a lot harder than it looks imo.. Can without a doubt be golfed further.
`Σ€g2KO>}¤` is a port of `2,0ySƲÞṪ` [from *@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/171266/52210) (thanks!).
[Try it online.](https://tio.run/##AXoAhf8wNWFiMWX//y7Fk8qSzrXCpcOLfVB9zqPigqxnMktPPn3CpM61RMKpZ@KJoGnCrHPCpOKAnnRvw73CrMKuwqUww6hEVeKJoGnigJ5ieVjCq8KrXcucw7DDvf//WzEsMiwzLDExLDE4LDIwLDIyLDI0LDMyLDMzLDM0XQ) (NOTE: Times out for the big test cases.)
+1 byte as bug-fix because `0` is always put at a trailing position when sorting.
**Explanation:**
```
.œ # Get all partions of the (implicit) input-list
# i.e. [1,2,3,11,18,20,22,24,32,33,34]
# → [[[1],[2],[3],[11],[18],[20],[22],[24],[32],[33],[34]],
# [[1],[2],[3],[11],[18],[20],[22],[24],[32],[33,34]],
# [[1],[2],[3],[11],[18],[20],[22],[24],[32,33],[34]],
# ...]
ʒ } # Filter this list by:
ε } # Map the current sub-list by:
¥Ë # Take the deltas, and check if all are equal
# i.e. [1,2,3] → [1,1] → 1
# i.e. [1,2,3,11] → [1,1,8] → 0
P # Check if all sub-list have equal deltas
Σ } # Now that we've filtered the list, sort it by:
€g # Take the length of each sub-list
# i.e. [[1,2,3],[11,18],[20,22,24],[32,33],[34]]
# → [3,2,3,2,1]
# i.e. [[1,2,3],[11],[18,20,22,24],[32,33,34]]
# → [3,1,4,3]
2K # Remove all 2s
# i.e. [3,2,3,2,1] → ['3','3','1']
O # And take the sum
# i.e. ['3','3','1'] → 7
# i.e. [3,1,4,3] → 11
> # And increase the sum by 1 (0 is always trailing when sorting)
¤ # And then take the last item of this sorted list
# i.e. for input [1,2,3,11,18,20,22,24,32,33,34]
# → [[1,2,3],[11],[18,20,22,24],[32,33,34]]
ε # Now map each of the sub-lists to:
D© # Save the current sub-list in the register
g≠i # If its length is not 1:
# i.e. [11] → 1 → 0 (falsey)
# i.e. [18,20,22,24] → 4 → 1 (truthy)
¬s¤ # Take the head and tail of the sub-list
# i.e. [18,20,22,24] → 18 and 24
„toý # And join them with "to"
# i.e. 18 and 24 → ['18to24', '18to20to22to24']
¬ # (head to remove some access waste we no longer need)
# i.e. ['18to24', '18to20to22to24'] → '18to24'
® # Get the sub-list from the register again
¥ # Take its deltas
# i.e. [18,20,22,24] → [2,2,2]
0è # Get the first item (should all be the same delta)
# i.e. [2,2,2] → 2
DU # Save it in variable `X`
≠i # If the delta is not 1:
# i.e. 2 → 1 (truthy)
„byX« # Merge "by" with `X`
# i.e. 2 → 'by2'
« # And merge it with the earlier "#to#"
# i.e. '18to24' and 'by2' → '18to24by2'
] # Close the mapping and both if-statements
˜ # Flatten the list
# i.e. ['1to3',[11],'18to24by2','32to34']
# → ['1to3',11,'18to24by2','32to34']
ðý # And join by spaces (which we implicitly output as result)
# i.e. ['1to3',11,'18to24by2','32to34']
# → '1to3 11 18to24by2 32to34'
```
[Answer]
# [Perl 5](https://www.perl.org/), 154 bytes
```
{my(@r,$r);@r&&(@$r<2||$$r[1]-$$r[0]==$_-$$r[-1])?push@$r,$_:push@r,$r=[$_]for@_;join" ",map@$_<3?@$_:("$$_[0]to$$_[-1]by".($$_[1]-$$_[0]))=~s/by1$//r,@r}
```
Same with spaces, newlines, #comments and `sub by`:
```
sub by {
my(@r,$r);
@r && # if at least one run candidate exists and...
( @$r<2 # ...just one elem so far
|| $$r[1]-$$r[0] == $_-$$r[-1] ) # ...or diff is same
? push @$r, $_ # then add elem to curr. run candidate
: push @r, $r=[$_] # else start new run cand. with curr elem
for @_;
join " ",
map @$_<3 # is it a run?
? @$_ # no, just output the numbers
: ("$$_[0]to$$_[-1]by".($$_[1]-$$_[0]))=~s/by1$//r, # yes, make run, delete by1
@r # loop run candidates
}
```
[Try it online!](https://tio.run/##ZVDBbqMwEL3zFZblVhA5AUNIQggbKvWyl@2lt4CsZZdms20wC460KM3@evbZSatKPcx4PH7vzRu3dfcSn/tDRarhfNwPbt5x1nlp3t3eujnrVuHrK2PdRpRjcwRlljFpy7EovXV76H8BxZlc2tKQsw2T5ZPqcpn@VruGEsr339ucyVW0Rl66lDEJJa3MCZlqoBPX1HaIefK87F/vV4Ngvt/xvDud9wPJdd3rDFJHv9i4k5FXlJMRNQX1@3TTty877fpFP@IInzPhcRaWJ9v3i6ZofG79UL66v3u8@5I6MOlaVe/oEIIRrM5aZaym1/s2q/AlTHqm0Xa7Rj/Rm/GsJzfjOOwJIfXftv6h659LdKJ5T7ZKX8uiodxlNan/QGZNH57pkn5Tmqhn6lkjrvkZo81Zzdk2dU6OlMaZlM7XZkk2IggCTpBDm6c2z2xemCyC0nk4YB41SK1MpxpC6lzpnIAYcRJzYvCoQvQi6MSmlaA3xSWMoncdrSISkwXAwAIKJIAGZ2DvyrAVIiLEFDH7YESrKUyIAM03OIbNLhYwXuAmzBLzN05MZmaiwBN2mH@yP7UbgDLnJLmKRBchawBnbE0AgVggEhPAJR83m5ME@jF@CDzQwNIquZhNBLD0/B8 "Perl 5 – Try It Online")
...for passing tests from OP.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 77 bytes
```
\d+
$*
(1+)(?= \1(1+))
$1:$2
1:(1+) (1+:\1 )+(1+)
1to$3by$1
:1+|by1\b
1+
$.&
```
[Try it online!](https://tio.run/##LYxLCsJAEET3fYpaDJIYkK7pmfxAvEg2Bl24URA3gneP3SIMj3lUVz2vr9v9vG3LpZO0l4Zd25yOWBi/VhLnlIVzGBzzQrRdmPD1SLa@E2Vm91nfXFYR@spht21UVThyoAT6wOigCpFhqHA1ZMIKqtsEloJsJlRkhSmKolep6OOWYAV9aPgveM2TAdMvs4ijU1GjhkExKiZ/xGRf "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert to unary.
```
(1+)(?= \1(1+))
$1:$2
```
Compute consecutive differences.
```
1:(1+) (1+:\1 )+(1+)
1to$3by$1
```
Convert runs to `to...by` syntax.
```
:1+|by1\b
```
Remove unconverted differences and `by1`.
```
1+
$.&
```
Convert to decimal.
] |
[Question]
[
## Challenge
Given an integer, n, as input where `0 <= n <= 2^10`, output the nth even perfect number.
## Perfect Numbers
A perfect number is a number, x where the sum of its factors (excluding itself) equals x. For example, 6:
```
6: 1, 2, 3, 6
```
And, of course, `1 + 2 + 3 = 6`, so 6 is perfect.
If a perfect number, `x`, is even, `x mod 2 = 0`.
## Examples
The following are the first 10 even perfect numbers:
```
6
28
496
8128
33550336
8589869056
137438691328
2305843008139952128
2658455991569831744654692615953842176
191561942608236107294793378084303638130997321548169216
```
Note that you may index this however you wish: 6 may be the 1st or the 0th even perfect number.
## Winning
Shortest code in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
6Æṣ=$#Ṫ
```
[Try it online!](https://tio.run/##y0rNyan8/9/scNvDnYttVZQf7lz1//9/EwA "Jelly – Try It Online")
### How it works
```
6Æṣ=$#Ṫ Main link. Argument: n
6 Set the return value to 6.
# Execute the link to the left with argument k = 6, 7, 8, ... until n
values of k result in a truthy value. Yield the array of matches.
$ Combine the two links to the left into a monadic chain.
Æṣ Compute the sum of k's proper divisors.
= Compare the result with k.
Ṫ Tail; extract the last match.
```
[Answer]
# Mathematica, 13 bytes
Not surprisingly, there is a built-in.
```
PerfectNumber
```
Example:
```
In[1]:= PerfectNumber[18]
Out[1]= 33570832131986724437010877211080384841138028499879725454996241573482158\
> 45044404288204877880943769038844953577426084988557369475990617384115743842\
> 47301308070476236559422361748505091085378276585906423254824947614731965790\
> 74656099918600764404702181660294469121778737965822199901663478093006075022\
> 35922320184998563614417718592540207818507301504509772708485946474363553778\
> 15002849158802448863064617859829560720600134749556178514816801859885571366\
> 09224841817877083608951191123174885226416130683197710667392351007374503755\
> 40335253147622794359007165170269759424103195552989897121800121464177467313\
> 49444715625609571796578815564191221029354502997518133405151709561679510954\
> 53649485576150660101689160658011770193274226308280507786835049549112576654\
> 51011967045674593989019420525517538448448990932896764698816315598247156499\
> 81962616327512831278795091980742531934095804545624886643834653798850027355\
> 06153988851506645137759275553988219425439764732399824712438125054117523837\
> 43825674443705501944105100648997234160911797840456379499200487305751845574\
> 87014449512383771396204942879824895298272331406370148374088561561995154576\
> 69607964052126908149265601786094447595560440059050091763547114092255371397\
> 42580786755435211254219478481549478427620117084594927467463298521042107553\
> 17849183589266903954636497214522654057134843880439116344854323586388066453\
> 13826206591131266232422007835577345584225720310518698143376736219283021119\
> 28761789614688558486006504887631570108879621959364082631162227332803560330\
> 94756423908044994601567978553610182466961012539222545672409083153854682409\
> 31846166962495983407607141601251889544407008815874744654769507268678051757\
> 74695689121248545626112138666740771113961907153092335582317866270537439303\
> 50490226038824797423347994071302801487692985977437781930503487497407869280\
> 96033906295910199238181338557856978191860647256209708168229116156300978059\
> 19702685572687764976707268496046345276316038409383829227754491185785965832\
> 8888332628525056
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
`@Z\s@E=vtsG<}n
```
Very slow. It keeps trying increasing numbers one by one until the *n*-th perfect number is found.
[Try it online!](https://tio.run/##y00syfn/P8EhKqbYwdW2rKTY3aY27/9/YwA "MATL – Try It Online")
### Explanation
```
` % Do...while
@ % Push iteration index, k (starting at 1)
Z\ % Array of divisors
s % Sum
@E % Push k. Multiply by 2
= % Equal? If so, k is a perfect number
v % Concatenate vertically. This gradually builds an array which at the k-th
% iteration contains k zero/one values, where ones indicate perfect numbers
ts % Duplicate. Sum of array
G< % Push input. Less than? This is the loop condition: if true, proceed with
% next iteration
} % Finally (execute right before exiting loop)
n % Number of elements of the array
% End (implicit). Display (implicit)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
e.fqsf!%ZTStZ
```
[Try it online!](http://pyth.herokuapp.com/?code=e.fqsf%21%25ZTStZ&input=3&debug=0)
Please do not try any higher number. It just tests the even numbers one by one.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
µNNѨOQ½
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/wx1@focnHlrhHxhwaO///yYA "05AB1E – Try It Online")
**Explanation**
```
µ # loop over increasing N until counter equals input
N # push N
NÑ # push factors of N
¨ # remove last factor (itself)
O # sum factors
Q # compare the sum to N for equality
½ # if true, increase counter
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~198 153 83 78 77 75~~ 74 bytes
```
i=input()
j=0
while i:j+=1;i-=sum(x*(j%x<1)for x in range(1,j))==j
print j
```
[Try it online!](https://tio.run/##BcE7DoAgDADQnVN0MQE/iRgntYdxUGmjhSBGPD2@F77kvAylEJKEJ2mjGHv1Ojo3oIkbtDN1eD@XzrXmKi/W7D5CBhKIqxybti0bg8gqRJIEXMr4Aw "Python 2 – Try It Online")
Now it just reads like psuedocode.
* Saved ~~45~~ Countless Bytes because @Leaky Nun taught me about the sum function and list comprehension.
* Saved 2 bytes thanks to @shooqie's suggestion to remove the uncessary brackets.
We just iterate through every even number until we have found n perfect numbers.
[Answer]
# PHP, 111 Bytes
0-Indexing
Works with the concept that a perfect number is a number where `n=x*y`
`x=2^i` and `y=2^(i+1)-1` and y must be prime
```
for(;!$r[$argn];$u?:$r[]=$z)for($z=2**++$n*($y=2**($n+1)-1),$u=0,$j=1;$j++<sqrt($y);)$y%$j?:$u++;echo$r[$argn];
```
[Try it online!](https://tio.run/##RYwxDsIwEAR7foG0SD5fkDAFBZdTHoJSIARYLhxjcJF83jg0dLs7q0k@1X5IPm1wzc@oJ6mPKRvZIl9@yygow7m1UbHQyrDo0VpmRGswr9kgsqO9ow5FDx2COkFg7t@v/GkfEsK8Q2iewiz3m5/@@lq/ "PHP – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
f=lambda n,k=1:n and-~f(n-(sum(j>>k%j*j for j in range(1,k))==k),k+1)
```
[Try it online!](https://tio.run/##DcMxDsIgFADQ3VP8xRT014h1MqEXUQe0oED5EKBDF6@OfclLa/1GGpoNKeYKZS277anomvV7ycVGmm2wlYnzhjcjZxVekwJCL8WNQNHU/wyjnpUlMDeOfu8ODkzM4MASZEUfzQR6zqX0HP1R8JaypcoOQSVm8C4QLggDwvXJEYpOIKF7UMfbHw "Python 3 – Try It Online")
[Answer]
**Scala, 103 bytes**
```
n=>Stream.from(1).filter(_%2==0).filter(x=>Stream.from(1).take(x-1).filter(x%_==0).sum==x).drop(n).head
```
[Answer]
# Haskell, 61 Bytes
```
(!!)(filter(\x->x==sum[n|n<-[1..x-1],x`mod`n==0]||x==1)[1..])
```
[Answer]
# [Haskell](https://www.haskell.org/), 52 bytes
```
([n|n<-[1..],n==sum[d|d<-[1..div n 2],mod n d<1]]!!)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WIzqvJs9GN9pQTy9WJ8/Wtrg0NzqlJgUikpJZppCnYBSrk5ufAmSk2BjGxioqav7PTczMsy1KTUzxybOzsy0oyswrUdBTSPtvBAA "Haskell – Try It Online")
Starts at n = 0. Not particularly fast
[Answer]
# JavaScript (ES6), 68 bytes
```
n=>eval(`for(x=5;n;s||n--)for(f=s=++x;f--;)(x/f-(x/f|0))||(s-=f);x`)
```
```
F=n=>eval('for(x=5;n;s||n--)for(f=s=++x;f--;)(x/f-(x/f|0))||(s-=f);x')
console.log(
F(1),
F(2),
F(3),
//F(4),
//F(5),
)
```
[Answer]
# [Perl 6](http://perl6.org/), 42 bytes
```
{(grep {$_==[+] grep $_%%*,^$_},^∞)[$_]}
```
The input index is 1-based.
[Answer]
## Clojure, 79 bytes
```
#(nth(for[i(range):when(=(apply +(for[j(range 1 i):when(=(mod i j)0)]j))i)]i)%)
```
Following the spec, heavy usage of for's `:when` condition.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 152 bytes
```
$ErrorActionPreference='SilentlyContinue'
function p{param($x)(1..($x-1)|?{!($x%$_)})|%{$s+=$_};$s}
1..$args[0]|%{if(((p -x $_)-eq$_)-and(!($_%2))){$_}}
```
[Try it online!](https://tio.run/##HYvRCoIwGIXvfQqDiRuhaF2GRET3QZcRMuzXBmtb/5SMuWdfq5tzDpzvM/oNaB8gZQjkhKjx0I1CqzNCDwiqgya/CAlqlJ@jVqNQE@RJP6k/lRpnOPInJTOjdVnGLmq27N0qroy0zLMlc8SuG9L6HbE@iRDhONhrdYuP6CmlJi3mNLIFvH7J1Z1Gvc02jDEXPR9C2FZf "PowerShell – Try It Online")
] |
[Question]
[
## Background
A **[linear recurrence relation](https://en.wikipedia.org/wiki/Linear_difference_equation)** is a description of a sequence, defined as one or more initial terms and a linear formula on last \$k\$ terms to calculate the next term. (For the sake of simplicity, we only consider *homogeneous* relations, i.e. the ones without a constant term in the formula.)
A formal definition of a linear recurrence relation looks like this, where \$y\_n\$ is the desired sequence (1-based, so it is defined over \$n\ge 1\$) and \$x\_i\$'s and \$a\_i\$'s are constants:
$$
y\_n =
\begin{cases}
x\_n, & 1\le n\le k \\
a\_1y\_{n-1}+a\_2y\_{n-2}+\cdots+a\_ky\_{n-k}, & k<n
\end{cases}
$$
In this challenge, we will accelerate this sequence by [converting it to a matrix form](https://en.wikipedia.org/wiki/Linear_difference_equation#Solution_by_conversion_to_matrix_form), so that the \$n\$-th term can be found by repeated squaring of the matrix in \$O(\log n)\$ steps, followed by inner product with the vector of initial terms.
For example, consider the famous Fibonacci sequence: its recurrence relation is \$y\_n=y\_{n-1} + y\_{n-2}\$ with \$k=2\$, and let's use the initial values \$x\_1=x\_2=1\$. The recurrence relation can be converted to a matrix form:
$$
\begin{bmatrix} y\_{n-1} \\ y\_{n} \end{bmatrix} = \begin{bmatrix} y\_{n-1} \\ y\_{n-1}+y\_{n-2} \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}\begin{bmatrix} y\_{n-2} \\ y\_{n-1} \end{bmatrix}
$$
So multiplying the matrix once advances the sequence by one term. Since this holds for any \$n\$, it can be extended all the way until we reach the initial terms:
$$
\begin{bmatrix} y\_{n-1} \\ y\_{n} \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}\begin{bmatrix} y\_{n-2} \\ y\_{n-1} \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}^2\begin{bmatrix} y\_{n-3} \\ y\_{n-2} \end{bmatrix} \\
= \cdots = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}^{n-2}\begin{bmatrix} y\_{1} \\ y\_{2} \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}^{n-2}\begin{bmatrix} 1 \\ 1 \end{bmatrix}
$$
In general, one way to construct such a matrix is the following:
$$
\begin{bmatrix} y\_{n-k+1} \\ y\_{n-k+2} \\ \vdots \\ y\_{n-1} \\ y\_{n} \end{bmatrix} = \begin{bmatrix} 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ & \vdots & & & \vdots \\ 0 & 0 & 0 & \cdots & 1 \\ a\_k & a\_{k-1} & a\_{k-2} & \cdots & a\_1 \end{bmatrix}\begin{bmatrix} y\_{n-k} \\ y\_{n-k+1} \\ \vdots \\ y\_{n-2} \\ y\_{n-1} \end{bmatrix}
$$
Note that, if you reverse the vectors and the matrix in every dimension, the equation still holds, retaining the property of "advancing a term by matmul-ing once". (Actually any permutation will work, given that the rows and columns of the matrix are permuted in the same way.)
## Challenge
Given the list of coefficients \$a\_1,\cdots,a\_k\$, construct a matrix that represents the recurrence relation (so that its powers can be used to accelerate the computation of \$n\$-th term of the sequence).
You can take the coefficients in reverse order, and you can optionally take the value \$k\$ as a separate input. \$k\$ (the number of terms) is at least 1.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
In all cases, any other matrix that can be formed by permuting rows and columns in the same way is also valid.
```
Input
[1,1]
Output
[[0, 1],
[1, 1]]
Input
[5]
Output
[[5]]
Input
[3, -1, 19]
Output
[[0, 1, 0],
[0, 0, 1],
[19, -1, 3]]
or reversed in both dimensions:
[[3, -1, 19],
[1, 0, 0],
[0, 1, 0]]
or cycled once in both dimensions:
[[3, 19, -1],
[0, 0, 1],
[1, 0, 0]]
etc.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~8~~ 7 bytes
-1 byte thanks to @LuisMendo
```
Xy4LY)i
```
Takes the coefficients in reverse order
[Try it online!](https://tio.run/##y00syfn/P6LSxCdSM/P/f2OuaGMFXUMFQ8vY/wA "MATL – Try It Online")
## Explanation
```
Xy4LY)i
Xy : Create an identity matrix of size equal to input
4LY) : Remove the first row
i : Insert input onto the stack
```
[Answer]
# [J](http://jsoftware.com/), 10 8 bytes
Returns the matrix reversed in both dimensions.
```
,}:@=@/:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/dWqtHGwd9K3@a/63SVMwVDDkAlKmIMJYIR7ItQQA "J – Try It Online")
### How it works
```
,}:@=@/: input: 3 _1 19
/: indices that sort: 1 0 2
(just to get k different numbers)
=@ self-classify: 1 0 0
0 1 0
0 0 1
}:@ drop last row: 1 0 0
0 1 0
, prepend input: 3 _1 19
1 0 0
0 1 0
```
[Answer]
# JavaScript (ES6), 36 bytes
```
a=>a.map((_,i)=>i?a.map(_=>+!--i):a)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQEMjXidT09Yu0x7Cjbe101bU1c3UtErU/J@cn1ecn5Oql5OfrpGmEW2oo2AYq6nJhSZsikXMWEdBF6TcEij3HwA "JavaScript (Node.js) – Try It Online")
Returns:
$$
\begin{bmatrix} a\_1 & a\_2 & a\_3 & \cdots & a\_{k-1} & a\_k \\ 1 & 0 & 0 & \cdots & 0 & 0 \\ 0 & 1 & 0 & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & & \vdots & \vdots \\ 0 & 0 & 0 & \cdots & 1 & 0 \end{bmatrix}
$$
[Answer]
# [Io](http://iolanguage.org/), 56 bytes
```
method(a,a map(i,v,if(i<1,a,a map(I,v,if(I==i-1,1,0)))))
```
[Try it online!](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0UjUSdRITexQCNTp0wnM00j08ZQBybkCRHytLXN1DXUMdQx0ASB/2kaOZnFJRpAEU3NgqLMvJKcPC6omKmmpgKakLGOAlCzgqElQuo/AA "Io – Try It Online")
## Explanation
```
method(a, ) // Input an array.
a map(i,v, ) // Map. i = index, v = value
if(i<1, ) // If the indice is 0,
a, // Return the inputted list
a map(I,v, ) // Otherwise, map: (I is the current index)
if(I==i-1, ) // If I == i-1,
1, // Return 1,
0 // Otherwise 0
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/)
```
⊢⍪¯1↓⍋∘.=⍋
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXoke9qw6tN3zUNvlRb/ejjhl6tkD6f9qjtgmPevsedTU/6l3zqHfLofXGj9omPuqbGhzkDCRDPDyD/6cD1VQDOWClWx91t0DY6upwZpoChoS6ei1XuoKhgiGIBBpsCqSNFYAOUDC0BAA "APL (Dyalog Unicode) – Try It Online")
Tacit function taking the list of coefficients on the right.
## Explanation
```
⊢⍪¯1↓⍋∘.=⍋
⍋ ⍋ ⍝ Grade up to obtain a list of k distinct values
∘.= ⍝ Outer product with operation `equals` (identity matrix)
¯1↓ ⍝ Drop the last row
⊢⍪ ⍝ Prepend the list of coefficients
```
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
lambda l,k:[l]+zip(*[iter(([1]+[0]*k)*~-k)]*k)
```
[Try it online!](https://tio.run/##HYzBDoIwEETv/Yq9sUUgovEgiV9SOWAoccOyNG094MFfr4U5vZm8jNvie5VLmuABz8TD8hoH4GruDPenLzksDUXrEU3bn8y5L2dd/upZ75BocauPELag1LR6YBILJPvQhDiSdApyOH/Hj2OLy@CQJFaH2QTHFLGAQmt9iJJFtoKs1dGdzzJOyBWI1qmFVt3UFeoM9z8 "Python 2 – Try It Online")
Takes input as a tuple `l` and number of terms `k`, and outputs with both rows and columns reversed.
The idea is to use the [zip/iter trick](https://codegolf.stackexchange.com/a/184881/20260) to create an identity-like matrix by splitting a repeating list into chunks. The is similar to my solution to [construct the identity matrix](https://codegolf.stackexchange.com/a/70415/20260) but changed to have one fewer row by changing the inner multiplier `k` to `k-1` (written `~-k`).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
IEθ⎇κEθ⁼⊖κμθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyEktSgvsahSI1tHASriWliamFOs4ZKaXJSam5pXkpqika2po5CrCSQKNYHA@v//6GhjHQVDSx0FXcPY2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Produces the "reversed in both directions" output. Works by replacing the first row of a shifted identity matrix with the input. Explanation:
```
Eθ Map over input list
⎇κ If this is not the first row then
Eθ Map over input list
⁼⊖κμ Generate a shifted identity matrix
θ Otherwise replace the first row with the input
I Cast to string for implicit print
```
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
function(r,k)rbind(diag(k)[-1,],r)
```
[Try it online!](https://tio.run/##FckxCoAwDADA3Vd0TCAdgjgI@hJx0NbUUokQ6vurLrecNXGTd00eDTXfCkZlvg5N9QRDtD1rhJi3BAUXz7SSYRMIwMSIncDwE6CnL3lEbC8 "R – Try It Online")
Takes the length as well; the TIO link has a `k=length(r)` argument so you can just input the recurrence relation.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~60~~ 58 bytes
-2 bytes thanks to @JonathanAllan
```
lambda a,k:[map(i.__eq__,range(k))for i in range(1,k)]+[a]
```
[Try it online!](https://tio.run/##VY7BCoMwEETv@Yq9maWpINJDhX6JlbDF2C7RmCa5@PU2plDonnaHN7Pjt/RaXbtPcIP7PtPyGAlI2a5fyEuutTZvrVUg9zTSIk5rAAZ28FUaZXE49TTsvPg1JIhbFOKAZnbm4LJQxzSy6wTkofxn5phkiXdJFbCOfuYkK6gQsXD24IyThKLcPmRY9v9WRoRfoUmSgtwG9wYacREtnPNy/QA "Python 3 – Try It Online")
Takes the coefficients in reverse order
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āDδQ`\)
```
Outputs reversed in both dimensions.
[Try it online](https://tio.run/##yy9OTMpM/f//SKPLuS2BCTGa//9HG@voGuoYWsYCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I40u57YEJsRo/tf5Hx1tqGMYqxNtCsTGOrpAjiWIp2OkY6pjEhsLAA).
**Explanation:**
```
ā # Push a list in the range [1,length] (without popping the implicit input-list)
D # Duplicate it
δ # Apply double-vectorized:
Q # Check if it's equal
# (this results in an L by L matrix filled with 0s, with a top-left to
# bottom-right diagonal of 1s; where `L` is the length of the input-list)
` # Pop and push all rows of this matrix separated to the stack
\ # Discard the last row
) # And wrap all list on the stack into a list
# (after which the matrix is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
W;J⁼þṖ$$
```
A monadic Link accepting a list which yields a list of lists in the reversed rows & columns permutation.
**[Try it online!](https://tio.run/##y0rNyan8/z/c2utR457D@x7unKai8v///2hjHQVdQx0FQ8tYAA "Jelly – Try It Online")**
### How?
```
W;J⁼þṖ$$ - Link: list A e.g. [5,2,5,4]
W - wrap (A) in a list [[5,2,5,4]]
$ - last two links as a monad - f(A):
J - range of length (A) [1,2,3,4]
$ - last two links as a monad - f(J):
Ṗ - pop [1,2,3]
þ - (J) outer product (that) with:
⁼ - equals? [[1,0,0,0],[0,1,0,0],[0,0,1,0]]
; - (W) concatenate (that) [[5,2,5,4],[1,0,0,0],[0,1,0,0],[0,0,1,0]]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~90~~ ~~89~~ 80 bytes
Saved 9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
i;j;f(a,k)int*a;{for(i=k;i--;puts(""))for(j=k;j--;)printf("%d ",i?i-1==j:a[j]);}
```
[Try it online!](https://tio.run/##dZJRa4MwEMff/RRHoJDYyKqlD20qfRh72NM@gMoItm7RLi1qoaz42d1FTVuUBSSX@//ur3cm9b7StG2VyEVGJS@Y0rUrxS07lVSFhVCeJ86XuqKEMGaSOSZzTLJziWhGyWwPhKud8vwwzDcyyhMmmrZTqTGDIwfcQTO4OYALXcAooCCEhcBtC1rAfK4Y3E2r2Z5g3Y4A2RCMjpFCX6dxTOGPVJoyp7czifpQ1Z9yESXoePM5@I0YaX6vrSZC0AtLDp4pXD8AdyCqnhjewa2hDYKxZdHzAbpxWA5q@i1LF8peIvH1LYiv61d8Vtjc83lJsGI0J70/XIdZdeEWKvV7OGV0@ED2Mpxdm@jGaVg79HtPEo1sXx2RiGcAoLBAMdHt33nXeCViTdhI6i7QFI/1x6WeVGT/0N59PfjGado/ "C (gcc) – Try It Online")
Inputs an array of coefficients (in forward order) along with its length.
Prints a matrix that represents the recurrence relation.
[Answer]
# Google Sheets, 52
Closing Parens discounted.
* Input cells is Row `1`, starting in column `B`.
* `A2` - `=COUNTA(1:1)`. Rules say that we can take this as input too, so I have discounted this as well. (Our "k")
* `A3` - `=ArrayFormula(IFERROR(0^MOD(SEQUENCE(A2-1,A2)-1,A2+1)))`
The output matrix starts in `B1`.
## How it works
1. Since this is a spreadsheet, the input cells give us free output too. As long is it's the first row and we end up with a square set of cells, we're good. If this didn't count, we'd have to do this with Column 1 instead to use `TRANSPOSE()` to copy the input. (Because it's smaller than `ArrayFormula()`)
2. Cache the number of columns in A2
3. Generate a **k-1** x **k** matrix using `SEQUENCE`. Values are `MOD` number of columns + 1. (Diagonals are 0, otherwise something else).
4. Since `0^0` is `1` in Sheets, that means this effectively is a Boolean `NOT()` converted to an integer.
5. `IFERROR` handles input size of 1. (Output a Blank)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes
```
a->matcompanion(x^#a-Pol(a))~
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P1HXLjexJDk/tyAxLzM/T6MiTjlRNyA/RyNRU7Puf2JBQU6lRqKCrp1CQVFmXgmQqQTiKCmkgRToKERHG@oYxgJpUxBhrKOga6ijYGgZG6v5HwA "Pari/GP – Try It Online")
] |
[Question]
[
If we assign each letter a respective integer, starting from 1, then a is 1, b is 2, c is 3, and so on. After z, the letters loop back around, but with a in front (aa, ab, ac). It then goes to ba, bb, bc... After this is completed, as you may have figured, another letter is added (aaa, aab, aac). "Prime letters" would be letters that are associated with a prime number. b would be the first prime letter, followed by c, e, g, et cetera.
# The Challenge
Given an input *n*, find the nth "prime letter."
**Examples**
Input:
```
1
```
Output:
```
b
```
Input:
```
4
```
Output:
```
g
```
Input:
```
123
```
Output:
```
za
```
# Scoring Criteria
This is code golf, so the shortest answer in bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/),~~262~~ ~~236~~ ~~209~~ ~~196~~ ~~179~~ ~~114~~ ~~93~~ ~~92~~ 97 bytes
```
def f(n):
m=k=1;s=''
while n:m*=k*k;k+=1;n-=m%k
while k:s=chr(~-k%26+97)+s;k=~-k//26
return s
```
[Try it online!](https://tio.run/##NclLCsMgEADQvaeYTYhGQj6FlCpzmlYxTJwGNYRuenWbTZePt39KePOt1pfz4CUrIyAi4WQztq2AM6ybAzaxQ@rIkr6Ge4wN/Y9MxmdI8ttTMy/6cVc6W8KLwzAvApIrR2LIdU8rF@nlNCpVfw "Python 3 – Try It Online")
Fixed a bug mentioned by @benrg about getting a wrong output for the input 123.
Thanks to:
- @AdmBorkBork for help me getting started and save a few bytes
- @Sriotchilism O'Zaic for saving me 6 bytes
- @mypetlion for saving me 65 bytes and bringing me under 150 bytes :)
- @dingledooper for saving me 21 bytes and bringing me under 100 bytes :D
- @Jitse for saving 1 byte
---
**98 bytes**
```
f=lambda n,i=1,p=1:n and-~f(n-p%i,i+1,p*i*i)
g=lambda n,s='':n and g(~-n//26,chr(~-n%26+97)+s)or s
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIU8n09ZQp8DW0CpPITEvRbcuTSNPt0A1UydTGyislamVqcmVjlBcbKuuDlGpkK5Rp5unr29kppOcUQRiqxqZaVuaa2oXa@YXKRT/LyjKzCvRSNdI0zA00NTU/A8A "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 83 bytes
```
f=(n,k=0)=>n?f(n-(g=d=>~k%d--?g(d):!d)(++k),k):k<0?'':f(n,k/26-1)+Buffer([k%26+65])
```
[Try it online!](https://tio.run/##FcxBDoIwEEDRq4wLwkxKtSWxC6SQeA3jglBKsGRqirr06hV3f/PfY/gM25iW50tydFPO3iJXwSqyHfceWeJsne2@oXBS9jM6ag6OUIhAVaAmtKovy8b/p1NtpCZxfXs/JbyFojbCnO@UfUzIYEFfgKEFrdQeQhCMkbe4Tsc1zjsAu0KUfw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
k = 0 // k = counter
) => //
n ? // if n is not equal to 0:
// == 1st pass: find the requested prime ==
f( // do a recursive call:
n - ( // pass the updated value of n
g = d => // g is a recursive function which takes d = k
// and tests the primality of k + 1:
~k % d-- ? // if d is not a divisor of (k + 1):
// (decrement d afterwards)
g(d) // do recursive calls until it is
: // else:
!d // return true if d = 0
)(++k), // increment k and invoke g
// so we decrement n if k is prime
k // pass k
) // end of recursive call
: // else:
// == 2nd pass: convert the prime to a string ==
k < 0 ? // if k is negative:
'' // return an empty string and stop
: // else:
f( // do a recursive call:
n, // pass n (which is now 0)
k / 26 - 1 // pass k / 26 - 1
) + // end of recursive call
Buffer([ // append the letter corresponding to
k % 26 + 65 // k mod 26
]) //
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆNḃ26ịØa
```
A monadic Link which accepts a non-negative integer that yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8//9wm9/DHc1GZg93dx@ekfj//39DI2MA "Jelly – Try It Online")**
### How?
```
ÆNḃ26ịØa - Link: integer, n
ÆN - nth prime
26 - literal 26
ḃ - bijective base
Øa - literal list of characters = ['a', 'b', ..., 'z']
ị - index into
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes
```
Flatten[Tuples[Alphabet[],#]&/@Range@4,1][[Prime@#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y0nsaQkNS86pLQgJ7U42jGnICMxKbUkOlZHOVZN3yEoMS891cFExzA2OjqgKDM31UE5NlbtP5CZV6LgkB5tGMsFZ5sgsQ2NjJF5BgYGsf//AwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-rprime`, ~~48~~ ~~47~~ ~~46~~ 43 bytes
-5 bytes from GB.
```
->n{(?A..?Z*n).take(Prime.take(n)[-1])[-1]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsPeUU/PPkorT1OvJDE7VSOgKDM3FcLM04zWNYwFE7X/NQz19IwMNPVSE5MzFFLyFWoyaxQKSkuKFZRUjVIUVI2KlVSjM3UU0qIzY2OtFVLzUv7/yy8oyczPK/6vW1QAMhQA "Ruby – Try It Online")
[Answer]
# [PHP](https://php.net/), 69 bytes
```
for($n=1,$a=a;$argn||!print$a;$m||--$argn,$a++)for($m=$n++;$n%$m--;);
```
[Try it online!](https://tio.run/##HYoxCoAwDADfIkSwxAyCWyxu/qOL2qFpqI55u7V0Objj9Na67dp45jKB@GWG4ANDKJeYDVqivNA8mRH12gZE1/fkQRAZZIRExI5rXb@sb8zyVDp@ "PHP – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~170~~ ~~163~~ ~~158~~ ~~157~~ 155 bytes
```
String p(int n){int c=0,i,v=1;String s="";while(c<n){v++;for(i=2;i<=v;i++)if(v%i<1)break;if(i==v)c++;}while(v>0){s=(char)(~-v%26+97)+s;v=~-v/26;}return s;}
```
[Try it online!](https://tio.run/##LY7BbsIwEER/xUJC2pUhhKgCVY77B5w4Vj0YY2AhOJHtLKqi9NdTt3Aazcyb1V4Nm@X1eJu6/tCQFbYxMYqdIT@IVxSTSVm4paO45wL2KZA/f36ZcI447L9jcvei7VPR5Tw1Hrx7/J8ALDp4K0tENU7PleggM8Lj8CdWlwtasF6rVxv1bKYeF2oc2DpDLKU6tQFIV4pqzYqkRDoBz6le4yE4c1PZktaMNrPjc8sfJQ5Rg72YgPCz5Hm1ke9blFGxznZVbdQYXOqDFzH/Nk6/ "Java (JDK) – Try It Online")
Thanks to @Delta for saving me 14 bytes in total
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
<Ø[₂‰˜0KZ27‹#}<Asè
```
Isn't there a convenient builtin to do this shorter?.. I have the feeling I should be able to use one of the base-conversion builtins here, but it isn't really working out.. Can without a doubt be golfed substantially, though..
[Try it online](https://tio.run/##ASgA1/9vc2FiaWX//zzDmFvigoLigLDLnDBLWjI34oC5I308QXPDqP//MTIz) or [verify some more test cases](https://tio.run/##AT8AwP9vc2FiaWX/dnk/IiAtPiAiP3n/PMOYW@KCguKAsMucMEtaMjfigLkjfTxBc8Oo/yz/WzEsNCwxMjMsMTAwMF0).
**Explanation:**
```
< # Decrease the (implicit) input-integer by 1 to make it 0-based
Ø # Get the 0-based n'th prime
[ # Start an infinite loop:
₂‰ # Take the divmod 26
˜ # Flatten the resulting list
0K # And remove any 0s
Z # Get the maximum of the list (without popping)
27‹ # If it's smaller than 27:
# # Stop the infinite loop
}< # After the loop: decrease all values by 1 to make it 0-based
A # Push the lowercase alphabet
sè # And index the list of integers into it
# (after which the resulting character-list is output implicitly as result)
```
[Answer]
# Java, 169 Bytes
isProbablePrime is only valid for 32 bit integers, but it is correct for every 32 bit integer, so this is a valid solution.
```
(int n)->{int x=-1;for(int i=0;i<n;){x++;if(BigInteger.valueOf(x).isProbablePrime(15))i++;}String r="";while(x>0){x--;int m=x%26;r=(char)(m+97)+r;x=(x-m)/26;}return r;};
```
[Answer]
# [Icon](https://github.com/gtownsend/icon), 135 bytes
```
procedure f(n)
k:=seq()&s:=0&0=k%(i:=2to k)&s+:=1&i=k&s=1&p:=k-1&n-:=1&n=0
t:="";until t[1:1]:=char(97+p%26)&p:=p/26-1&p<0;return t
end
```
[Try it online!](https://tio.run/##TY7BDsIgDIbve4qGZAQyFwGTGdH6IsaD2TASFJAxjU@vTC@e2nzt3362D/79jin0ZpiSgTPzvHIaR3NnnI4aBRXoamY1qhzAFdZolNSio2OpUaNrJfXtDD2KKmskZDv5bK@QD1LLo8b@ckpss25irTo@R@JSdSUVd2KbTJ6Sh1wZP/x53E7WM14BgHmY9ILyX0IRUAKGAM9ks2F2AaTdk0WRtvy7@@NEqtXMz6w0ZTBf/gA "Icon – Try It Online")
[Answer]
# Pyth, 27 bytes
`VQ.VhZIP_b=ZbB;p*\a/Z26@GtZ`
Explaination:
```
# Implicit Q = eval(input())
# Implicit Z = 0
VQ # for N in range(Q)
.VhZ # for b in infinite_range(Z+1)
IP_b # if is_prime(b)
=Zb # Z = b
B; # break
p*\a/Z26 # print("a"*Z//26, end="")
@GtZ #
# Implicit print(G[Z-1])
```
] |
[Question]
[
Your task is to decipher a non-empty string consisting of printable ASCII characters in the range **[32..126]**.
Reading the string character per character:
* each time you encounter a letter in lowercase, associate it with the next letter in uppercase, starting with **'A'**
* each time you encounter a letter in uppercase, replace it with the letter in lowercase it's associated with
* other characters do not require any special processing and are just left unchanged
## Example
For the input string `"endlAsEBAEE"`:
* Associate `e` to `A`, `n` to `B`, `d` to `C` and `l` to `D`
* Replace `A` with `e`
* Associate `s` to `E`
* Replace `EBAEE` with `sness`
The final output is `"endlessness"`.
## Clarifications and rules
* The input string is guaranteed to contain each lowercase letter at most once. All further instances will be replaced with the corresponding capital letter.
* The input string is guaranteed to be valid. (You will not encounter a capital letter that is not yet associated with a lowercase letter.)
* Once a capital letter has been associated to a lowercase letter, it may or may not be used later in the string. For instance, `C` and `D` are not used in the above example.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
## Test cases
**Inputs:**
```
abcd
honk! ABCD!
abrAcAdABCA
endlAsEBAEE
helCo wDrCd!
dermatoglyphics
progBamFinD AuzJles & cCdL DCKf
sphinx of black quKrtz, jOdge my vGw. K NODLM IPGZE HGF SOWBA GYVP QCV JKRX TGU.
petBr AiABD AEckBd a ABFG of AEFGlBH ABAABDs. hJw mIny AEFGLBH ABAABDM HEH ABCBD AEABD AEFG?
```
**Answers:**
```
abcd
honk! honk!
abracadabra
endlessness
hello world!
dermatoglyphics
programming puzzles & code golf
sphinx of black quartz, judge my vow. a quick brown fox jumps over the lazy dog.
peter piper picked a peck of pickled peppers. how many pickled peppers did peter piper pick?
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
```
fØaØA,y
```
[Try it online!](https://tio.run/##PY0/UoNAHEZ7TvHZWGW4gvPbZVkCROK/aOwIC4FkgQiJSEobr5BDWKaz5CR6ESRxxu775s28t4q1bvs@6Q5hd6BR239/HbuPn/fPed@Hi0gZ4aKiiBQxTkZcKE21YCSEkcaal2isiqsLY1OVSxbmdlZYoN3e1XGNS0Rc@bC4lxj1Js2KN5QJFjqM1njZedV2P8IqUMsYeYtX2ZjwcB1Y/gTjqXwWcKSNu@CREeR8NsUNn8H1bp9wLx9MYxNvWQXKiA1BEa2ZQghitjw1SNhSM2f4NPDaROo2yMdFeyb@P5nAEafNz5I/lS2vfgE "Jelly – Try It Online")
### How it works
```
fØaØA,y Main link. Argument: s (string)
Øa Yield the lowercase alphabet.
f Filter; keep only characters that appear in the lowercase alphabet.
Call the result r.
ØA Yield the uppercase alphabet (u).
, Pair; yield [u, r].
y Translate s, using the substitutions in [u, r].
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Code:
```
AÃAus‡
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f8XCzY2nxo4aF//8XFOWnOyXmumXmuSg4llZ55aQWK6gpJDun@Ci4OHunAQA "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), 62 bytes
```
s=>s.replace(/[A-Z]/g,c=>s.match(/[a-z]/g)[parseInt(c,36)-10])
```
Each capital letter is converted to its base 36 value, less 10.
We then match on the lowercase letter that's at that index.
```
let f=
s=>s.replace(/[A-Z]/g,c=>s.match(/[a-z]/g)[parseInt(c,36)-10])
console.log(f('abcd'))
console.log(f('abrAcAdABCA'))
console.log(f('endlAsEBAEE'))
console.log(f('helCo wDrCd!'))
console.log(f('progBamFinD AuzJles & cCdL DCKf'))
console.log(f('sphinx of black quKrtz, jOdge my vGw. K NODLM IPGZE HGF SOWBA GYVP QCV JKRX TGU.'))
console.log(f('petBr AiABD AEckBd a ABFG of AEFGlBH ABAABDs. hJw mIny AEFGLBH ABAABDM HEH ABCBD AEABD AEFG?'))
```
[Answer]
# Pyth, 36 bytes
```
JKr1GVQI&}NG!}NH=XHNhK=tK)p?}NJ@_HNN
```
[Try it here](https://pyth.herokuapp.com/?code=JKr1GVQI%26%7DNG%21%7DNH%3DXHNhK%3DtK%29p%3F%7DNJ%40_HNN&input=%22sphinx%20of%20black%20quKrtz%2C%20jOdge%20my%20vGw.%20K%20NODLM%20IPGZE%20HGF%20SOWBA%20GYVP%20QCV%20JKRX%20TGU.%22&debug=0)
### Explanation
```
JKr1GVQI&}NG!}NH=XHNhK=tK)p?}NJ@_HNN
JKr1G Let J and K be the uppercase alphabet.
VQ For each character in the input...
I&}NG!}NH ) ... if the character is lowercase and not
yet in H, ...
=XHNhK ... add the letter and the next uppercase
letter to H...
=tK ... and move to the next uppercase letter.
p?}NJ@_HNN Print either the next character or the
letter it represents.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ñ·í=Üò°f1èb
```
[Run and debug it](https://staxlang.xyz/#p=a5faa13d9a95f866318a62&i=abcd%0AabrAcAdABCA%0AendlAsEBAEE%0AhelCo+wDrCd%21%0AprogBamFinD+AuzJles+%26+cCdL+DCKf%0Asphinx+of+black+quKrtz,+jOdge+my+vGw.+K+NODLM+IPGZE+HGF+SOWBA+GYVP+QCV+JKRX+TGU.%0ApetBr+AiABD+AEckBd+a+ABFG+of+AEFGlBH+ABAABDs.+hJw+mIny+AEFGLBH+ABAABDM+HEH+ABCBD+AEABD+AEFG%3F&a=1&m=2)
[Answer]
# [R](https://www.r-project.org/), 79 bytes
```
function(x){s=utf8ToInt(x)
s[j]=s[s>96&s<123][s[j<-s>64&s<91]-64]
intToUtf8(s)}
```
[Try it online!](https://tio.run/##PZBbb4JAEIXf@RWnPigkamLbmJqIzS4CKlptq/ZifUAuiuJi2aV4ib/dgk36NPPNmTknmfjiqxc/YY4IIibvlRNXE@E/jKMuExlKfLaeq3zGW416kTdrt3fzWTZqVnirfp8NGrV5pX4/lwImxtEkO5S5cr6kUexyqHBkqWAvHLdQzmtMHOISqpEcPeaGhOuU6HqOKy/UIqTtWHNvct7F0ZLaWyNgbZDk2As9jiIcze2jrVl@vsJ3q4DtEflYhLazwXdixeJYxnroLj1sD/gx0yosPA3b/QG6I/NTR8c08Dp8owTmx3SEZ22KnvXyjrE5qV5jPUFjkIDQLFZ3NtSFDUINM48humGGtJMxyXRexaqXYttlh6vS/1cG6Oh5r11N/qwM8zH3P4lVwEE8LqBxJNzzk/BcUCQ/iuUUAcP1c8pJAhxbyL6cKuXSFysp0vnyCw "R – Try It Online")
[Answer]
## [Perl 5](https://www.perl.org/) with `-p`, 27 bytes
```
eval"y/A-Z/".y/a-z//cdr."/"
```
[Try it online!](https://tio.run/##PZDLTsMwFET3@YpLFqzamA1rdO04bpuUFCgFykNyY7cJdR44fZAifp2QFondjI50RppKW3PZtnonjdsQ7M@J6zVE9g@EJMp6LnHbVi4S5ciFxQQVUoaOLpTBmlPk3Em1YSXsfcvUmVPZckVlHmSFD7g9jIyu4RwSpiLwWbh06irNik8ol7AwMlnDxza0m0MP3mO10pA3sBN7D0K4jv1oDMOJmHMYiADu4geKIJ5mE7hhMxiFt48wFfeeU@kNtYAZ0m6QJ2uqQALSQBw3kAfC0EHXseO1B@loD/mwaE4k@idjGPBjZifJnyoQVz9ltcnKom77VUCe37pPXurXr4veN/kF "Perl 5 – Try It Online")
-2 bytes thanks to [@breadbox](https://codegolf.stackexchange.com/users/4201/breadbox)!
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 37 bytes
```
00000000: 2505 cd03 8030 0176 fe7b 300c fe61 3011 %....0.v.{0..a0.
00000010: fe5b 3004 fe41 3003 ff18 e7d6 414f 0a18 .[0..A0.....AO..
00000020: f777 2318 f3 .w#..
```
[Try it online!](https://tio.run/##fYzNjoJAEITvPkUlxmunhwGGeNnMqKBmN/sAnhCY1Yi6WY1GfXi2wZ@jdarqqv6uCf/sa980/NAQQcQRipI1EtYMViaGr8wSmrkQFytxSgEDEjGd6MZEOVPvTlDC8FXU7UNxYbsXmvcqQWXKGKEKPTiXCFrIr@WWRPabnoygZRhjEGhZeY13onOfqGl@q6P7g11bN4adFBtXIod1aYa9l0Oa1W4q2Up/IKzmZ2xnu0vXfL6aL0wnrR91kDsqzT7@AQ "Z80Golf – Try It Online")
z80 does pretty good at this! Here is a disassembly:
```
dec h ; HL = cipher write pointer
dec b ; BC = cipher read pointer
; meaning of 'A'..'Z' is written to $ff00~$ff19
next:
call $8003 ; getchar
jr nc, ok ; not EOF?
halt
ok:
cp '{'
jr nc, other ; a ≥ '{'
cp 'a'
jr nc, lower ; 'a' ≤ a ≤ 'z'
cp '['
jr nc, other ; '[' ≤ a ≤ '`'
cp 'A'
jr nc, upper ; 'A' ≤ a ≤ 'Z'
other:
rst $38
jr next
upper:
sub 'A'
ld c, a
ld a, (bc)
jr other
lower:
ld (hl), a
inc hl
jr other
```
We point both HL and BC at the `$ff00` range with `dec`, and use `rst $38` as a short alternative to `call $8000`, but otherwise there isn't much trickery going on.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 25 bytes
```
~["T`L`"|""L$`[a-z]
$&-$&
```
[Try it online!](https://tio.run/##PY3bTsJAFEXf5yu2TSU@SBO/wJyZTqe0RVARL8Sk006BSinYcpHG@OsVMPFt76xkrSrb5KW@aS@vVNz@TKxRHMXWt2VFdjzR3ead2Z2u3WlbnaSG6aSilAxxQSwrTUG15CQlm2eFWGHvVsJcsHW1mnG99PLSBW2boMhqdJAKE8EV4ZTV63lefmE1RVLodIHPbVhtmmt8DMwsw/KAndo7CHE3cKM@ekP1JuErD4@DZ05Qr@Mh7sUYQfjwgpF6ctg62/AKlBM/BmW64AYaxD11apD0VMH946cjrx3Mgz2WvfJwJtE/6cOXpy3Okj@Vp25/AQ "Retina – Try It Online") Explanation:
```
[a-z]
```
Match lowercase letters.
```
$`
$&-$&
```
Replace each letter with a degenerate range of itself. (This prevents the later transliteration from treating it as a character class; backslash can't be used because some lower case letters have a special meaning after a backslash.)
```
["T`L`"|""L
```
List the degenerate ranges, but without line separators, and with a preceding `T`L``.
```
~
```
Evaluate the resulting transliteration program on the original input.
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
lambda s:''.join('@'<c<'['and filter(str.islower,s)[ord(c)-65]or c for c in s)
```
[Try it online!](https://tio.run/##PZBJU4NAEIXP@iueF4dUIQer9JBK1Bm2rCZucYk5EAYCCQw4Q8TkzyNglZfu99Xr7lfV@aGIMnFZhf3PKvHSNfeguoQY2ywWGrkjPb9HlsQTHGGcFIHUVCGNWCVZGUhddZaZ5Jrfubi@WmUSPsK2xgKqUzVaNbreX/uc6Ki7pD7llJm0wUDwhCqbUdtuMAoSM0NpSZOfNZzLbMO81ImFBbo/jpJA4Ry@ySewzHHYjKg8isUPshDrxPN3@NqPZXHUsZ3xTYD0gG@3NDDG/cyaTDGcux82Bq6Dp9kro3DfF3M8mAuMxo9veHZfjDY2KJgEjSmrY21/xzg8UOa4TQy1HTdhg5pp7SsD0ahEOhSH1pn8O1MM7Eab7ZG/U457S1bd05NcxqKA0kn/huihVr@q@gU "Python 2 – Try It Online")
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 109 bytes
```
s->{var r=s.replaceAll("[^a-z]","");for(char i=64;i++<64+r.length();)s=s.replace(i,r.charAt(i-65));return s;}
```
[Try it online!](https://tio.run/##ZVFNc9owEL3zKzY@dOwCOqUc6pCObGyTACUtbfqRSWeELRuBLLuSDIUMv53KOAVmetCsdt/b3bfzlmRNustkdWB5WUgNS5OjSjOO3rqt/2ppJWLNClGDMSdKwYQw8dICKKs5ZzEoTbQJ64IlkBvInmnJRPb0DERmyoGaChC@jrlp0E4TbiGF/kF1b1/WRILsKyRpyUlMMee29fSLdHfPVseyHDctpB0vDIn1e9cua7dvetdtiTgVmV7Yjuuoc7PNOhLVZKxt1u29cxxXUl1JAcrdH9yjnpNITZVW0H@VCWCReZxYnX/ZohCrK8CeP7g6F8lc4hgnporPRSoSjlXg4SC4aKfcL2AzkH5y0Z9QmRNdZHxbLliszkApi8wjecjEAHC1u@dUwRuI/WQMA3@UnonKNIo/UKQwNxev4Hc1knrXgeU0ySjkW1hHGwQj@DgdjCdw9xD9DGAYhTCbfvMwRD8eH@CT/wj3o8/f4Uv0FV1IoNqTgBn2jIQgXnkJEHN/GNXLcBBG3BuaHBtcIVjcbyC/E9sjMj4hExgG9d8/DmlGhdEH67hk3zhQO1q7XhvwvrHBObkw2ypNc1RUGpXGKM2FnSJSlnxr10zjaDOqVb/94S8 "Java (JDK 10) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 105 bytes
```
C;f(char*Z){for(char*z=--Z,c,*s;c=*++z;putchar(c))for(C=64,s=Z;*z>64&91>*z&&C^*z;c=*s)C+=*++s>96&*s<123;}
```
[Try it online!](https://tio.run/##ZZBtb5swFIU/N7/iFmlRoCRSu6pSxdLKEELbpGv31m0RmuTYhrCAzWzSNFT57ZmdkEjrPmAu5xyfx4Z0U0I2m8BLOmSGpTOxXxMhd3Pd73YnLnEd5ZG@c3JSe@WiMk6H2LZJBf2Lc1f1J55TX12cty9Pr5y63Q5@ObXZoOzgxGxTV5cXbUd9OD177603VcNxty9mv5Yy41XSsSDpxNY7FVt2zPt9iC3Lndj6WHrZR2Ir5tfGMrGYx9xyme2tWwXOeMd@bR1VHQtPCbXc1hHAbrS9rTwTfH4MyA8Gx427U7brPoSnEhFEdQodKiQmmJrXPsQ4zZEKfRSGTcgoTCmunwOO5YGA5UAG9MBjea4lIXN6AFImC1yJNF@Vs4yoJvlWbcKlFKmPi2HGB4AW9Z1mQhtIQMcwCEZJs9mkJC6KjKdQLuq6SQnKIBV5si9Tupq/gEhgmmMyhz@LkaxqF34/0JRBsYLnaNmDEXx8GIzv4fYxmoRwEw3hy8N3H0H08@kRPgVPcDf6/AO@Rt96Df3/WryrXexrha7FWs@0O5ViySERL9ovSgXimUmoZgxyXK@AirR3uDurfAkoQ76@e0jmPtUlyB9GBoXCYZT7N/obaV/1YHa3hOKWr7bO@ODcw01o5mBbsqsaRtf7H8cqTS@zcruSOTOIkuljaoQRcq2UrNS@QQiNwBrxxgGamfnfqmtzjfXmLw "C (gcc) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ØAi
Çị¥¹Ç?€
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//w5hBaQrDh@G7i8KlwrnDhz/igqz///9hYnJBY0FkQUJDQQ "Jelly – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
Fork of [Dennis' brilliant Jelly answer](https://codegolf.stackexchange.com/a/166573/48934)
```
XQr1G@G
```
[All testcases.](https://pyth.herokuapp.com/?code=XQr1G%40G&test_suite=1&test_suite_input=%22abcd%22%0A%22abrAcAdABCA%22%0A%22endlAsEBAEE%22%0A%22helCo+wDrCd%21%22%0A%22progBamFinD+AuzJles+%26+cCdL+DCKf%22%0A%22sphinx+of+black+quKrtz%2C+jOdge+my+vGw.+K+NODLM+IPGZE+HGF+SOWBA+GYVP+QCV+JKRX+TGU.%22%0A%22petBr+AiABD+AEckBd+a+ABFG+of+AEFGlBH+ABAABDs.+hJw+mIny+AEFGLBH+ABAABDM+HEH+ABCBD+AEABD+AEFG%3F%22&debug=0)
] |
[Question]
[
This is the Cop post. The [Robber post is here](https://codegolf.stackexchange.com/q/146927/31516).
---
Your task is to take an integer input **N** and output the **Nth** digit in the sequence [OEIS A002942](http://oeis.org/A002942).
The sequence consists of the square numbers written backwards:
```
1, 4, 9, 61, 52, 63, 94, 46, 18, 1, 121, 441, ...
```
Note that leading zeros are trimmed away (**100** becomes **1**, not **001**). Concatenating this into a string (or one long number gives):
```
1496152639446181121441
```
You shall output the **Nth** digit in this string/number. You may choose to take **N** as 0-indexed or 1-indexed (please state which one you choose).
### Test cases (1-indexed):
```
N = 1, ==> 1
N = 5, ==> 1
N = 17, ==> 1 <- Important test case! It's not zero.
N = 20, ==> 4
N = 78, ==> 0
N = 100, ==> 4
```
Your code should work for numbers up to **N = 2^15** (unless your language can't handles 32 bit integers by default, in which case **N** can be lower).
---
### Cops:
You must write two functions/programs, in the same language, that do the same thing. You have to post one of the functions/programs, as well as the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between the two functions/programs you have written. The Levenshtein distance is measured in characters (so addition of a two byte character will give a LD = 1).
The unrevealed code can not be longer than the original solution (but it can be the same size). The robbers will attempt to write a code with the exact Levenshtein distance you gave (it can be different from your unrevealed code, as long as it works).
The winner will be the uncracked submission that has the lowest Levenshtein distance.
You may [check the Levenshtein distance here!](https://planetcalc.com/1720/)
---
If your submission goes uncracked for 7 days then you may reveal the alternative code you have written and mark your submission as safe.
---
[Answer]
# [Haskell](https://www.haskell.org/), LD = 13, [cracked](https://codegolf.stackexchange.com/a/146966/56433)
```
((snd.span(<'1').reverse.show.(^2)=<<[1..])!!)
```
[Try it online!](https://tio.run/##Xc3RCoIwFIDhe59iQuCE43C2XILrEbrp0gyGzYzUhrO6iF69FTMQOpcf/zmnkeai2tbWYm8xNv2RGC17nAc0CMmg7mowipjm@iD4kIQizwtKSBn6fmg7ee6RQPo27sYBLVAnNapRwYCmQDPgHLIMEs5ouiy9Z@Rtv/EKkBshNog6oRz@JIlnYU74epZ42oqnaG7cIwa/O9HLvqu6lSdjo0rrDw "Haskell – Try It Online")
I double-checked that leading zeros are trimmed ;)
**Explanation:**
```
[1..] -- for each element in [1,2,3,4,5,...]
=<< -- apply the following functions
(^2) -- square [1,4,9,16,25,...]
show. -- convert to string ["1","4","9","16","25",...]
reverse. -- reverse ["1","4","9","61","52",...,"001",...]
span(<'1'). -- split into leading zeros and remainder [("","1"),("","4"),...,("00","1"),...]
snd. -- only keep remainder ["1","4","9","61","52",...,"1",...]
-- and concatenate the result "1496152..."
(( )!!) -- index into the sequence
```
[Answer]
# [cQuents 0](https://github.com/stestoltz/cQuents/tree/cquents-0), LD = 1, [Cracked](https://codegolf.stackexchange.com/a/146961/65836)
```
":\r$*$
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/X8kqpkhFS@X/f0MDAyMA "cQuents 0 – Try It Online")
I thought this didn't work for leading zeroes, but it actually does - the reverse function in cQuents is coded as `int(reversed(str(n)))`.
## Explanation
```
" Concatenate sequence together, get nth term in the string instead of the sequence
: Mode: Sequence: given input n, output the nth term, 1-indexed
Each term in the sequences equals:
\r reverse(
$*$ the index * the index
or
$$ the index * the index
) (implicit)
```
[Answer]
# JavaScript (ES6), LD = 103 ([cracked](https://codegolf.stackexchange.com/a/146992/3852))
Using such a high Levenshtein distance is probably not the best strategy, but let's try it anyway.
```
n => { for(i = 0, str = ''; i <= n; i++) { str += +[...i * i + ''].reverse().join(''); } return str[n]; }
```
### Test cases
```
let f =
n => { for(i = 0, str = ''; i <= n; i++) { str += +[...i * i + ''].reverse().join(''); } return str[n]; }
console.log(f(5)) // 1
console.log(f(17)) // 1
console.log(f(20)) // 4
console.log(f(78)) // 0
console.log(f(100)) // 4
console.log(f(274164)) // 1
```
### Intended solution
```
$=>eval(atob`Wy4uLkFycmF5KCQrMSldLm1hcCgoXyxpKT0+K1suLi5pKmkrJyddLnJldmVyc2UoKS5qb2luYGApLmpvaW5gYFskXQ`)
```
Encoded part:
```
[...Array($+1)].map((_,i)=>+[...i*i+''].reverse().join``).join``[$]
```
[Answer]
# Python 2, 104 bytes, LD=21 [Invalid AND Cracked](https://codegolf.stackexchange.com/questions/146927/levenshtein-distance-oeis-robbers/147015#147015)
```
d=lambda y:y if'0'!=str(y)[-1]else d(y/10)
lambda n:''.join([str(d(x*x))[::-1]for x in range(1,n)])[n-1]
```
~~P.S. Is an unlimited amount of whitespace and commenting allowed? If so this will not be hard to crack.~~
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), LD = 1 ([cracked](https://codegolf.stackexchange.com/a/147643/71420))
```
00 C0 20 FD AE A0 00 99 5B 00 C8 20 73 00 90 F7 99 5B 00 A2 0B CA 88 30 09 B9
5B 00 29 0F 95 5B 10 F3 A9 00 95 5B CA 10 F9 A9 00 A0 03 99 69 00 88 10 FA A0
20 A2 76 18 B5 E6 90 02 09 10 4A 95 E6 E8 10 F4 A2 03 76 69 CA 10 FB 88 F0 11
A2 09 B5 5C C9 08 30 04 E9 03 95 5C CA 10 F3 30 D6 A2 03 B5 69 95 57 CA 10 F9
A9 01 85 FB A2 03 A9 00 95 FB CA D0 FB A2 03 B5 FB 95 22 95 26 CA 10 F7 A9 00
A2 03 95 69 CA 10 FB A0 20 A2 02 46 25 76 22 CA 10 FB 90 0C A2 7C 18 B5 AA 75
ED 95 ED E8 10 F7 A2 7D 06 26 36 AA E8 10 FB 88 10 DD A0 0B A9 00 99 5A 00 88
D0 FA A0 20 A2 09 B5 5C C9 05 30 04 69 02 95 5C CA 10 F3 06 69 A2 FD 36 6D E8
D0 FB A2 09 B5 5C 2A C9 10 29 0F 95 5C CA 10 F4 88 D0 D7 E0 0A F0 05 E8 B5 5B
F0 F7 09 30 99 5B 00 C8 E8 E0 0B F0 04 B5 5B 90 F1 88 B9 5B 00 C9 30 F0 F8 A2
7C 18 B5 DB E9 00 95 DB E8 10 F7 90 14 88 30 05 B9 5B 00 D0 EA A2 7C F6 7F D0
03 E8 10 F9 4C 73 C0 B9 5B 00 4C D2 FF
```
**[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"sqdig.prg":"data:;base64,AMAg/a6gAJlbAMggcwCQ95lbAKILyogwCblbACkPlVsQ86kAlVvKEPmpAKADmWkAiBD6oCCidhi15pACCRBKleboEPSiA3ZpyhD7iPARogm1XMkIMATpA5VcyhDzMNaiA7VplVfKEPmpAYX7ogOpAJX7ytD7ogO1+5UilSbKEPepAKIDlWnKEPugIKICRiV2IsoQ+5AMonwYtap17ZXt6BD3on0GJjaq6BD7iBDdoAupAJlaAIjQ+qAgogm1XMkFMARpApVcyhDzBmmi/TZt6ND7ogm1XCrJECkPlVzKEPSI0NfgCvAF6LVb8PcJMJlbAMjo4AvwBLVbkPGIuVsAyTDw+KJ8GLXb6QCV2+gQ95AUiDAFuVsA0OqifPZ/0APoEPlMc8C5WwBM0v8="%7D,"vice":%7B"-autostart":"sqdig.prg"%7D%7D)**, usage: `sys49152,n` where `n` is the 0-indexed input.
---
For the last test case, you need a bit of patience, as this poor machine has to do millions of bit-shifts and additions to present you the result ;)
The language here is the machine code, so LD is measured in this format -- nevertheless, to give something to start with, here's the program in [`ca65`](http://cc65.github.io/cc65/) assembler source:
```
NUMSIZE = 4 ; 32 bit integers ...
NUMSTRSIZE = 11 ; need up to 11 characters for 0-terminated string
.segment "ZPUSR": zeropage
v_x: .res NUMSIZE ; next number to be squared
.segment "ZPFAC": zeropage
v_n: .res NUMSIZE ; input index (0-based), counts down
nc_string: .res NUMSTRSIZE ; string buffer for numbers
.segment "ZPTMP": zeropage
mpm_arg1: .res NUMSIZE ; arg1 for multiplication
mpm_arg2: .res NUMSIZE ; arg2 for multiplication
.segment "ZPFAC2": zeropage
mpm_res: .res NUMSIZE ; numeric result (mult and str convert)
; load address for creating a C64 .PRG file:
.segment "LDADDR"
.word $c000
.code
; first read number from command argument and convert to unsigned
; integer in little-endian:
jsr $aefd
ldy #$00
rn_loop: sta nc_string,y
iny
jsr $73
bcc rn_loop
sta nc_string,y
ldx #NUMSTRSIZE
stn_copybcd: dex
dey
bmi stn_fillzero
lda nc_string,y
and #$f
sta nc_string,x
bpl stn_copybcd
stn_fillzero: lda #$0
sta nc_string,x
dex
bpl stn_fillzero
lda #$0
ldy #(NUMSIZE-1)
stn_znumloop: sta mpm_res,y
dey
bpl stn_znumloop
ldy #(NUMSIZE*8)
stn_loop: ldx #($81-NUMSTRSIZE)
clc
stn_rorloop: lda nc_string+NUMSTRSIZE+$80,x
bcc stn_skipbit
ora #$10
stn_skipbit: lsr a
sta nc_string+NUMSTRSIZE+$80,x
inx
bpl stn_rorloop
ldx #(NUMSIZE-1)
stn_ror: ror mpm_res,x
dex
bpl stn_ror
dey
beq main
stn_sub: ldx #(NUMSTRSIZE-2)
stn_subloop: lda nc_string+1,x
cmp #$8
bmi stn_nosub
sbc #$3
sta nc_string+1,x
stn_nosub: dex
bpl stn_subloop
bmi stn_loop
main:
ldx #(NUMSIZE-1)
argloop: lda mpm_res,x
sta v_n,x
dex
bpl argloop
lda #$01
sta v_x
ldx #(NUMSIZE-1)
lda #$00
initxloop: sta v_x,x
dex
bne initxloop
mainloop:
; prepare arguments for multiplication:
ldx #(NUMSIZE-1)
sqrargloop: lda v_x,x
sta mpm_arg1,x
sta mpm_arg2,x
dex
bpl sqrargloop
; do multiplication:
lda #$00
ldx #(NUMSIZE-1)
mul_clearloop: sta mpm_res,x
dex
bpl mul_clearloop
ldy #(NUMSIZE*8)
mul_loop: ldx #(NUMSIZE-2)
lsr mpm_arg1+NUMSIZE-1
mul_rorloop: ror mpm_arg1,x
dex
bpl mul_rorloop
bcc mul_noadd
ldx #($80-NUMSIZE)
clc
mul_addloop: lda mpm_arg2+NUMSIZE+$80,x
adc mpm_res+NUMSIZE+$80,x
sta mpm_res+NUMSIZE+$80,x
inx
bpl mul_addloop
mul_noadd: ldx #($81-NUMSIZE)
asl mpm_arg2
mul_rolloop: rol mpm_arg2+NUMSIZE+$80,x
inx
bpl mul_rolloop
dey
bpl mul_loop
; convert result to string:
ldy #NUMSTRSIZE
lda #$0
nts_fillzero: sta nc_string-1,y
dey
bne nts_fillzero
ldy #(NUMSIZE*8)
nts_bcdloop: ldx #(NUMSTRSIZE-2)
nts_addloop: lda nc_string+1,x
cmp #$5
bmi nts_noadd
adc #$2
sta nc_string+1,x
nts_noadd: dex
bpl nts_addloop
asl mpm_res
ldx #($ff-NUMSIZE+2)
nts_rol: rol mpm_res+NUMSIZE,x ; + $100 w/o zp wraparound
inx
bne nts_rol
ldx #(NUMSTRSIZE-2)
nts_rolloop: lda nc_string+1,x
rol a
cmp #$10
and #$f
sta nc_string+1,x
nts_rolnext: dex
bpl nts_rolloop
dey
bne nts_bcdloop
nts_scan: cpx #(NUMSTRSIZE-1)
beq nts_copydigits
inx
lda nc_string,x
beq nts_scan
nts_copydigits: ora #$30
sta nc_string,y
iny
inx
cpx #(NUMSTRSIZE)
beq strip0loop
lda nc_string,x
bcc nts_copydigits
; search for first non-0 character from the end of the string:
strip0loop: dey
lda nc_string,y
cmp #$30
beq strip0loop
; decrement n for each digit:
founddigit:
ldx #($80-NUMSIZE)
clc
decnloop: lda v_n+NUMSIZE+$80,x
sbc #$00
sta v_n+NUMSIZE+$80,x
inx
bpl decnloop
bcc foundresult
dey
bmi next_x
lda nc_string,y
bne founddigit
; increment x to calculate next square number:
next_x:
ldx #($80-NUMSIZE)
incxloop: inc v_x+NUMSIZE-$80,x
bne incxdone
inx
bpl incxloop
incxdone: jmp mainloop
foundresult: lda nc_string,y
jmp $ffd2
```
... and here's the linker script for `ld65`:
```
MEMORY {
LDADDR: start = $bffe, size = 2;
CODE: start = $c000, size = $1000;
ZPTMP: start = $0022, size = $0008;
ZPFAC: start = $0057, size = $000f;
ZPFAC2: start = $0069, size = $0004;
ZPUSR: start = $00fb, size = $0004;
}
SEGMENTS {
LDADDR: load = LDADDR;
CODE: load = CODE;
ZPTMP: load = ZPTMP, type = zp;
ZPFAC: load = ZPFAC, type = zp;
ZPFAC2: load = ZPFAC2, type = zp;
ZPUSR: load = ZPUSR, type = zp;
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 59 + 1 (`-a`) = 60 bytes, LD=55
```
$j.=int reverse$_**2for 1..$_;$_--;say$j=~s/.{$_}(.).*/$1/r
```
[Try it online!](https://tio.run/##BcFBCoAgEADAr3TYQwmuGkQH8Qm9QToYKJGyShBRT2@bKYH2iRkSuni0jsIZqAbwQoxbps4ggrfgpbR1vSC5tyq8wT89DigUGEXMZv5yaTEfleUyoTaa5foD "Perl 5 – Try It Online")
[Answer]
# Java 8, (177 bytes) LD = 92 ([Cracked by *@Arnauld*](https://codegolf.stackexchange.com/a/147074/52210))
([Ive used this online LD-calculator.](https://planetcalc.com/1721/))
```
n->{String r="",t=r;for(int i=1,j;r.length()<=n+1;i++)if(Math.sqrt(i)%1==0){for(t="",j=(i+"").length();j>0;t+=(i+"").charAt(--j));r+=t.replaceAll("^0+","");}return r.charAt(n);}
```
This is probably not too hard if you simply golf this. :)
**Explanation:**
[Try it here.](https://tio.run/##hVHLasMwELz3KxZDQUK2iduQEFQF8gHJJcfSguooiVxFdtfrQDH@dlfOo7dg0B40O7PszBb6rJOyMr7Yffe503UNa219@wRgPRnc69zAZvgC5EeNkLOAg@cyQF2o8GrSZHPYgAcFvU@W7ZbQ@gOgiqKYFMp9iReZVVlcSEyd8Qc6Mv6mvMikFYLbPVtrOqb1DxKz/DlTasLbQUfDkEIxK6KI/ytlsZxIEnd4WG1FLEkKziUKRSmayoXdV86x6HMiojjQZIeGGvSAd0Hw0fXyaqNqvlywcXNzLu0OTiEKdjXz/gGaX3PY/tZkTmnZUFqFFjnPfJqzKb@E8rCfzcYIixHCfD5CWIxNeJlPs9krv12v6/8A)
```
n->{ // Method with integer parameter and character return-type
String r="", // Result-String, starting empty
t=r; // Temp-String, starting empty
for(int i=1,j; // Index-integers
r.length()<=n+1;i++) // Loop (1) as long as the length is at least n+1
if(Math.sqrt(i)%1==0){ // If the current number `i` is a perfect square:
for(t="", // Reset the temp-String to empty
j=(i+"").length(); // Set `j` to the length of the current number
j>0; // Inner loop (2) as long as `j` is larger than 0
t+= // Append the temp-String with:
(i+"").charAt(--j) // The digit of integer `i` at index `j-1`
// (by first decrease `j` with 1 with `--j`)
); // End of inner loop (2)
r+=t // And then append the temp-String to the result-String
.replaceAll("^0+","");}// after we've removed any leading zeroes
// End of loop (1) (implicit / single-line body)
return r.charAt(n); // Return the `n`'th character of the result-String
} // End of method
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), LD = 63, [Cracked](https://codegolf.stackexchange.com/a/147117/42295)
```
@(t)[arrayfun(@(t)num2str(str2num(flip(num2str(t)))),(1:t).^2,'uni',0){:}](t)
```
[Try it online!](https://tio.run/##NYmNBsMwFIUfJ/cSkYRJhdH3qJaYXcqaVnpTqvrsWTJ2OJ/zs744HO9CT6VU6YFxCCmFk3KE1mJe7M4Jqm3NQJ95g//IWCXBeEY1WSlynIXUePl7rF8ZCAxKgkeDcY1WN7rut2iNoyhf "Octave – Try It Online")
The submission is 77 bytes, so you need to substitute quite a bit =)
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), LD = 1, safe
```
00 C0 20 FD AE A0 00 99 5B 00 C8 20 73 00 90 F7 99 5B 00 A2 0B CA 98 88 30 09
B9 5B 00 29 0F 95 5B 10 F2 95 5B CA 10 FB A0 20 A2 76 18 B5 E6 90 02 09 10 4A
95 E6 E8 10 F4 A2 03 76 69 CA 10 FB 88 F0 11 A2 09 B5 5C C9 08 30 04 E9 03 95
5C CA 10 F3 30 D6 A2 03 B5 69 95 57 CA 10 F9 A9 01 85 FB A2 03 A9 00 95 FB CA
D0 FB A2 03 B5 FB 95 22 95 26 CA 10 F7 A9 00 A2 03 95 69 CA 10 FB A0 20 A2 02
46 25 76 22 CA 10 FB 90 0C A2 7C 18 B5 AA 75 ED 95 ED E8 10 F7 A2 7D 06 26 36
AA E8 10 FB 88 10 DD A2 0B A9 00 95 5A CA D0 FB A0 20 A2 09 B5 5C C9 05 30 04
69 02 95 5C CA 10 F3 06 69 A2 FD 36 6D E8 D0 FB A2 09 B5 5C 2A C9 10 29 0F 95
5C CA 10 F4 88 D0 D7 E8 B5 5B F0 FB 09 30 99 5B 00 C8 E8 E0 0B F0 04 B5 5B 90
F1 88 B9 5B 00 C9 30 F0 F8 A2 7C 18 B5 DB E9 00 95 DB E8 10 F7 90 14 88 30 05
B9 5B 00 D0 EA A2 7C F6 7F D0 03 E8 10 F9 4C 68 C0 B9 5B 00 4C D2 FF
```
**[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"sqdig.prg":"data:;base64,AMAg/a6gAJlbAMggcwCQ95lbAKILypiIMAm5WwApD5VbEPKVW8oQ+6AgonYYteaQAgkQSpXm6BD0ogN2acoQ+4jwEaIJtVzJCDAE6QOVXMoQ8zDWogO1aZVXyhD5qQGF+6IDqQCV+8rQ+6IDtfuVIpUmyhD3qQCiA5VpyhD7oCCiAkYldiLKEPuQDKJ8GLWqde2V7egQ96J9BiY2qugQ+4gQ3aILqQCVWsrQ+6Agogm1XMkFMARpApVcyhDzBmmi/TZt6ND7ogm1XCrJECkPlVzKEPSI0NfotVvw+wkwmVsAyOjgC/AEtVuQ8Yi5WwDJMPD4onwYtdvpAJXb6BD3kBSIMAW5WwDQ6qJ89n/QA+gQ+UxowLlbAEzS/w=="%7D,"vice":%7B"-autostart":"sqdig.prg"%7D%7D)**, usage: `sys49152,n` where `n` is the 0-indexed input.
---
**Intended solution:** (diff)
```
B9 5B 00 29 0F 95 5B 10 F2 95 5B CA 10 FB A0 20 A2 76 18 B5 E6 90 02 09 10 4A
-95 E6 E8 10 F4 A2 03 76 69 CA 10 FB 88 F0 11 A2 09 B5 5C C9 08 30 04 E9 03 95
+95 E6 E8 10 F4 A2 03 76 69 CA 10 FB 88 F0 11 A2 09 B5 5C C9 08 90 04 E9 03 95
5C CA 10 F3 30 D6 A2 03 B5 69 95 57 CA 10 F9 A9 01 85 FB A2 03 A9 00 95 FB CA
```
The `30` (opcode `bmi`) is replaced by `90` (opcode `bcc`). This corresponds to the following part in the assembler source:
```
stn_subloop: lda nc_string+1,x
cmp #$8
bmi stn_nosub ; use bcc here for same result
sbc #$3
sta nc_string+1,x
```
It works because this code checks whether a number is smaller than 8. The `cmp` instruction performs a subtraction for that, setting the flags accordingly. So, if the accumulator holds a number smaller than 8, this underflows, clearing the carry flag, therefore the correct branch instruction is indeed `bcc`. `bmi` (branching when negative), as in the original code, just happens to work here as well, because the compared numbers are small enough, so the result of the subtraction ends up in the negative range (`$80-$ff`) when an underflow occurs.
**[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"sqdig-secret.prg":"data:;base64,AMAg/a6gAJlbAMggcwCQ95lbAKILypiIMAm5WwApD5VbEPKVW8oQ+6AgonYYteaQAgkQSpXm6BD0ogN2acoQ+4jwEaIJtVzJCJAE6QOVXMoQ8zDWogO1aZVXyhD5qQGF+6IDqQCV+8rQ+6IDtfuVIpUmyhD3qQCiA5VpyhD7oCCiAkYldiLKEPuQDKJ8GLWqde2V7egQ96J9BiY2qugQ+4gQ3aILqQCVWsrQ+6Agogm1XMkFMARpApVcyhDzBmmi/TZt6ND7ogm1XCrJECkPlVzKEPSI0NfotVvw+wkwmVsAyOjgC/AEtVuQ8Yi5WwDJMPD4onwYtdvpAJXb6BD3kBSIMAW5WwDQ6qJ89n/QA+gQ+UxowLlbAEzS/w=="%7D,"vice":%7B"-autostart":"sqdig-secret.prg"%7D%7D)**
---
This is an improved/compacted version of [my previous submission](https://codegolf.stackexchange.com/a/147042/71420). Among some other tricks to reduce the size, it removes the useless code that was contained and allowed a kind of "simple"\*) crack. All in all, the size is reduced by 16 bytes. This time, it should be a bit harder to find the equivalent program with LD 1 :)
\*) probably still quite some work to find, of course :)
Again, here's the [`ca65`](http://cc65.github.io/cc65/) assembler source, to help getting started with the code:
```
NUMSIZE = 4 ; 32 bit integers ...
NUMSTRSIZE = 11 ; need up to 11 characters for 0-terminated string
.segment "ZPUSR": zeropage
v_x: .res NUMSIZE ; next number to be squared
.segment "ZPFAC": zeropage
v_n: .res NUMSIZE ; input index (0-based), counts down
nc_string: .res NUMSTRSIZE ; string buffer for numbers
.segment "ZPTMP": zeropage
mpm_arg1: .res NUMSIZE ; arg1 for multiplication
mpm_arg2: .res NUMSIZE ; arg2 for multiplication
.segment "ZPFAC2": zeropage
mpm_res: .res NUMSIZE ; numeric result (mult and str convert)
; load address for creating a C64 .PRG file:
.segment "LDADDR"
.word $c000
.code
; first read number from command argument and convert to unsigned
; integer in little-endian:
jsr $aefd
ldy #$00
rn_loop: sta nc_string,y
iny
jsr $73
bcc rn_loop
sta nc_string,y
ldx #NUMSTRSIZE
stn_copybcd: dex
tya
dey
bmi stn_fillzero
lda nc_string,y
and #$f
sta nc_string,x
bpl stn_copybcd
stn_fillzero: sta nc_string,x
dex
bpl stn_fillzero
ldy #(NUMSIZE*8)
stn_loop: ldx #($81-NUMSTRSIZE)
clc
stn_rorloop: lda nc_string+NUMSTRSIZE+$80,x
bcc stn_skipbit
ora #$10
stn_skipbit: lsr a
sta nc_string+NUMSTRSIZE+$80,x
inx
bpl stn_rorloop
ldx #(NUMSIZE-1)
stn_ror: ror mpm_res,x
dex
bpl stn_ror
dey
beq main
stn_sub: ldx #(NUMSTRSIZE-2)
stn_subloop: lda nc_string+1,x
cmp #$8
bmi stn_nosub
sbc #$3
sta nc_string+1,x
stn_nosub: dex
bpl stn_subloop
bmi stn_loop
main:
ldx #(NUMSIZE-1)
argloop: lda mpm_res,x
sta v_n,x
dex
bpl argloop
lda #$01
sta v_x
ldx #(NUMSIZE-1)
lda #$00
initxloop: sta v_x,x
dex
bne initxloop
mainloop:
; prepare arguments for multiplication:
ldx #(NUMSIZE-1)
sqrargloop: lda v_x,x
sta mpm_arg1,x
sta mpm_arg2,x
dex
bpl sqrargloop
; do multiplication:
lda #$00
ldx #(NUMSIZE-1)
mul_clearloop: sta mpm_res,x
dex
bpl mul_clearloop
ldy #(NUMSIZE*8)
mul_loop: ldx #(NUMSIZE-2)
lsr mpm_arg1+NUMSIZE-1
mul_rorloop: ror mpm_arg1,x
dex
bpl mul_rorloop
bcc mul_noadd
ldx #($80-NUMSIZE)
clc
mul_addloop: lda mpm_arg2+NUMSIZE+$80,x
adc mpm_res+NUMSIZE+$80,x
sta mpm_res+NUMSIZE+$80,x
inx
bpl mul_addloop
mul_noadd: ldx #($81-NUMSIZE)
asl mpm_arg2
mul_rolloop: rol mpm_arg2+NUMSIZE+$80,x
inx
bpl mul_rolloop
dey
bpl mul_loop
; convert result to string:
ldx #NUMSTRSIZE
lda #$0
nts_fillzero: sta nc_string-1,x
dex
bne nts_fillzero
ldy #(NUMSIZE*8)
nts_bcdloop: ldx #(NUMSTRSIZE-2)
nts_addloop: lda nc_string+1,x
cmp #$5
bmi nts_noadd
adc #$2
sta nc_string+1,x
nts_noadd: dex
bpl nts_addloop
asl mpm_res
ldx #($ff-NUMSIZE+2)
nts_rol: rol mpm_res+NUMSIZE,x ; + $100 w/o zp wraparound
inx
bne nts_rol
ldx #(NUMSTRSIZE-2)
nts_rolloop: lda nc_string+1,x
rol a
cmp #$10
and #$f
sta nc_string+1,x
nts_rolnext: dex
bpl nts_rolloop
dey
bne nts_bcdloop
nts_scan: inx
lda nc_string,x
beq nts_scan
nts_copydigits: ora #$30
sta nc_string,y
iny
inx
cpx #(NUMSTRSIZE)
beq strip0loop
lda nc_string,x
bcc nts_copydigits
; search for first non-0 character from the end of the string:
strip0loop: dey
lda nc_string,y
cmp #$30
beq strip0loop
; decrement n for each digit:
founddigit:
ldx #($80-NUMSIZE)
clc
decnloop: lda v_n+NUMSIZE+$80,x
sbc #$00
sta v_n+NUMSIZE+$80,x
inx
bpl decnloop
bcc foundresult
dey
bmi next_x
lda nc_string,y
bne founddigit
; increment x to calculate next square number:
next_x:
ldx #($80-NUMSIZE)
incxloop: inc v_x+NUMSIZE-$80,x
bne incxdone
inx
bpl incxloop
incxdone: jmp mainloop
foundresult: lda nc_string,y
jmp $ffd2
```
... and here's the linker script for `ld65`:
```
MEMORY {
LDADDR: start = $bffe, size = 2;
CODE: start = $c000, size = $1000;
ZPTMP: start = $0022, size = $0008;
ZPFAC: start = $0057, size = $000f;
ZPFAC2: start = $0069, size = $0004;
ZPUSR: start = $00fb, size = $0004;
}
SEGMENTS {
LDADDR: load = LDADDR;
CODE: load = CODE;
ZPTMP: load = ZPTMP, type = zp;
ZPFAC: load = ZPFAC, type = zp;
ZPFAC2: load = ZPFAC2, type = zp;
ZPUSR: load = ZPUSR, type = zp;
}
```
[Answer]
## Lua : LD=1, [cracked](https://codegolf.stackexchange.com/questions/146927/levenshtein-distance-oeis-robbers/146935#146935)
```
i=1s=""while(#s<...+0)do s=s..((i*i)..""):reverse():gsub("(0+)(%d+)$","%2")i=i+1 end print(s:sub(...,...))
```
No fancy tricks here :)
[Answer]
# Mathematica, LD=43 [cracked](https://codegolf.stackexchange.com/a/146967/67961)
```
Flatten[Table[(k=IntegerDigits)@FromDigits@Reverse@k[i^2],{i,10^4}]][[#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfLSexpCQ1LzokMSknNVoj29YzryQ1PbXIJTM9s6RY08GtKD8XwnYISi1LLSpOdciOzowzitWpztQxNIgzqY2NjY5Wjo1V@x9QlJlXouCQFm0UZ2ga@x8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# PHP, LD = 35 ([Cracked](https://codegolf.stackexchange.com/a/147591/75557))
1-indexed
```
<?while(strlen($s)<$argv[1])$s.=(int)strrev(++$i*$i);echo substr($s,$argv[1]-1,1);
```
[Try it online!](https://tio.run/##Ncs9CoAwDEDhqzhkaPzDzioeRBxUig1IW5qqtzd2cX2PL9ggMkyPpdMoTvE0TgHjAGs87lkvCNyOilzCPKO5VVUBlUDYm936gq8t9yzqHzS61tiLiO6614dE3rE07gM)
[Answer]
# Python 3: LD = 9 | [Cracked](https://codegolf.stackexchange.com/a/146932/68942)
```
lambda i:"".join(str(k*k+2*k+1)[::-1].lstrip("0")for k in range(i+1))[i]
```
This one should be fairly (very) easy to get :P
[Answer]
# C++, LD = 159
0-indexed, input in `argv[1]`, compiled on GCC 7.2.0
```
#import<bits/stdc++.h>
char*h,b[1<<17],*q=b;int x,y;main(int,char**j){sscanf(j[1],"%d",&y);do{x++;q+=sprintf(h=q,"%d",x*x);while(*--q==48);std::reverse(h,++q);}while(q-b<=y);b[y+1]=0,printf(b+y);}
```
[Answer]
# [Groovy](http://groovy-lang.org/), 61 bytes (LD = 23)
```
{(1..it).collect{0.valueOf("${it**2}".reverse())}.join()[it]}
```
[Try it online!](https://tio.run/##BcFRCoAgDADQu0gfmx9Du0gHiD5CVixEw5YQ4tntvbPkXL9xF0kKMBp4IlGkkGPkoM1R3ePLywFmaqLWzt1Q4crlYUDsdGVJgKvo1geCd4jjBw "Groovy – Try It Online")
] |
[Question]
[
Consider a connected undirected graph. A [matching set of edges](https://en.wikipedia.org/wiki/Matching_(graph_theory)) on this graph is defined as a set of edges such that no two edges in the set share a common vertex. For example, the left figure denotes a matching set in green, while the right figure denotes a non-matching set in red.
[](https://i.stack.imgur.com/HgmAr.png)
A matching set is said to be `maximally matching`, or a `maximal matching` if it is impossible to add another edge of the graph to the matching set. So both examples above are not maximal matching sets, but both of the sets below in blue are maximal matchings. Note that maximal matchings are not necessarily unique. Furthermore, there's not requirement that the size of each possible maximal matching for a graph is equal to another matching.[](https://i.stack.imgur.com/vitrF.png)
The goal of this challenge is to write a program/function to find a maximal matching of a graph.
# Input
Assume all vertices of the input graph have some consecutive integer numbering starting at any beginning integer value of your choice. An edge is described by an unordered pair of integers denoting the vertices the edge connects. For example, the graph shown above could be described with the following unordered set of edges (assuming the numbering of vertices starts at 0):
```
[(0,1), (0,2), (1,3), (1,4), (2,3), (3,4), (3,5), (5,6)]
```
An alternative way to describe a graph is via an adjacency list. Here is an example adjacency list for the above graph:
```
[0:(1,2), 1:(0,3,4), 2:(0,3), 3:(1,2,4,5), 4:(1,3), 5:(3,6), 6:(5)]
```
Your program/function must take as input a graph from any source (stdio, function parameter, etc.). You may use any notation desired so long as the no additional non-trivial information is communicated to your program. For example, having an extra parameter denoting the number of input edges is perfectly acceptable. Similarly, passing in an unordered multiset of edges, adjacency list, or adjacency matrix is fine.
You may assume:
1. The graph is connected (e.g. it is possible to reach any vertex given any starting vertex).
2. There is at least one edge.
3. An edge never connects a vertex directly to itself (ex. the edge `(1,1)` will not be given as input). Note that cycles are still possible (ex.: the above graphs).
4. You may require that the input vertices start at any index (e.g. the first vertex can be 0, 1, -1, etc.).
5. Vertex numbering is sequentially increasing from your chosen starting index (ex.: `1,2,3,4,...`, or `0,1,2,3,...`).
# Output
Your program/function should output a list of edges denoting a maximal matching set. An edge is defined by the two vertices which that edge connects. Ex. output for the left blue set (using the example input vertex ordering):
```
[(1,4), (2,3), (5,6)]
```
Note that the order of the vertices are not important; So the following output describes the same matching set:
```
[(4,1), (2,3), (6,5)]
```
Output may be to stdout, a file, function return value, etc.
# Examples
Here are a few example inputs (using the adjacency list format). These examples happen to start counting vertices at `0`.
Note that no example outputs are given, instead I've included a Python 3 validation code.
```
[0:(1), 1:(0)]
[0:(1,2), 1:(0,3,4), 2:(0,3), 3:(1,2,4,5), 4:(1,3), 5:(3,6), 6:(5)]
[0:(1,2), 1:(0,2,3,4,5), 2:(0,1), 3:(1), 4:(1), 5:(1)]
[0:(1,2), 1:(0,2,3), 2:(0,1,4), 3:(1,4,5), 4:(2,3), 5:(3)]
```
## Validation Python 3 code
Here's a Python 3 validation code which takes in a graph and set of edges and prints out whether that set is maximally matching or not. This code works with any vertex start index.
```
def is_maximal_matching(graph, edges):
'''
Determines if the given set of edges is a maximal matching of graph
@param graph a graph specified in adjacency list format
@param edges a list of edges specified as vertex pairs
@return True if edges describes a maximal matching, False otherwise.
Prints out some diagnostic text for why edges is not a maximal matching
'''
graph_vtxs = {k for k,v in graph.items()}
vtxs = {k for k,v in graph.items()}
# check that all vertices are valid and not used multiple times
for e in edges:
if(e[0] in graph_vtxs):
if(e[0] in vtxs):
vtxs.remove(e[0])
else:
print('edge (%d,%d): vertex %d is used by another edge'%(e[0],e[1],e[0]))
return False
else:
print('edge (%d,%d): vertex %d is not in the graph'%(e[0],e[1],e[0]))
return False
if(e[1] in graph_vtxs):
if(e[1] in vtxs):
vtxs.remove(e[1])
else:
print('edge (%d,%d): vertex %d is used by another edge'%(e[0],e[1],e[1]))
return False
else:
print('edge (%d,%d): vertex %d is not in the graph'%(e[0],e[1],e[0]))
return False
if(e[1] not in graph[e[0]]):
print('edge (%d,%d): edge not in graph'%(e[0],e[1]))
return False
# check that any edges can't be added
for v in vtxs:
ovtxs = graph[v]
for ov in ovtxs:
if(ov in vtxs):
print('could add edge (%d,%d) to maximal set'%(v,ov))
return False
return True
```
Example usage:
```
graph = {0:[1,2], 1:[0,3,4], 2:[0,3], 3:[1,2,4,5], 4:[1,3], 5:[3,6], 6:[5]}
candidate = [(0,1),(2,3)]
is_maximal_matching(graph, candidate) // False
candidate = [(0,1),(2,3),(5,6),(0,1)]
is_maximal_matching(graph, candidate) // False
candidate = [(0,1),(2,3),(5,6)]
is_maximal_matching(graph, candidate) // True
```
# Scoring
This is code golf; shortest code wins. Standard loopholes apply. You may use any built-ins desired.
[Answer]
## CJam (16 chars)
```
{M\{_2$&!*+}/2/}
```
[Online demo](http://cjam.aditsu.net/#code=%5B%5B0%201%5D%20%20%5B0%202%5D%20%20%5B1%203%5D%20%20%5B1%204%5D%20%20%5B2%203%5D%20%20%5B3%204%5D%20%20%5B3%205%5D%20%20%5B5%206%5D%5D%0A%0A%7BM%5C%7B_2%24%26!*%2B%7D%2F2%2F%7D%0A%0A~p)
This is a greedy approach which accumulates edges which don't have any vertex in common with the previously accumulated edges.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
ef{IsTty
y power set (gerenate all set of edges)
t remove the first one (the first one is
empty and will cause problems)
f filter for sets T satisfying:
T T
s flatten
{I is invariant under deduplicate, i.e. contains no
duplicating vertices, as the elements represent vertices
e pick the last one (the power set is ordered from
smallest to largest)
```
[Try it online!](http://pyth.herokuapp.com/?code=ef%7BIsTty&input=%5B%280%2C1%29%2C+%280%2C2%29%2C+%281%2C3%29%2C+%281%2C4%29%2C+%282%2C3%29%2C+%283%2C4%29%2C+%283%2C5%29%2C+%285%2C6%29%5D&debug=0)
## Specs
* Input: `[(0,1), (0,2), (1,3), (1,4), (2,3), (3,4), (3,5), (5,6)]`
* Output: `[(1, 4), (2, 3), (5, 6)]`
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
⊇.c≠∧
?⊇.cL≠ implicit ? at the beginning;
∧ breaks implicit . at the end;
temporary variable inserted.
?⊇. input is a superset of output
.cL output concatenated is L
L≠ L contains distinct elements
```
[Try it online!](https://tio.run/nexus/brachylog2#@/@oq10v@VHngkcdy///j4420DGM1QGSRkDSUMcYTJoASSMw2xjMNtYxBZKmOmaxsf@jAA "Brachylog – TIO Nexus")
This is guaranteed to be maximal, since Brachylog searches from the largest subset.
[Answer]
# Wolfram Language, ~~25~~ 22 bytes
Saved 3 bytes thanks to @MartinEnder
```
FindIndependentEdgeSet
```
This takes input as a `Graph` object (defined as `Graph[{1<->2,2<->3,1<-3>}]` etc.)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
►LOfoS=uΣṖ
```
[Try it online!](https://tio.run/##yygtzv7//9G0XT7@afnBtqXnFj/cOe3////R0QY6hrE6QNIISBrqGINJEyBpBGYbg9nGOqZA0lTHLDYWAA "Husk – Try It Online")
[Answer]
## JavaScript (ES6), 67 bytes
```
let f =
a=>a.map(b=>r.some(c=>c.some(d=>~b.indexOf(d)))||r.push(b),r=[])&&r
let g = a => console.log("[%s]", f(a).map(x => "[" + x + "]").join(", "))
g([[0,1]])
g([[0,1], [0,2], [1,3], [1,4], [2,3], [3,4], [3,5], [5,6]])
g([[0,1], [0,2], [1,2], [1,3], [1,4], [1,5]])
g([[0,1], [0,2], [1,2], [1,3], [2,4], [3,4], [3,5]])
```
Uses the greedy approach for maximal golfiness.
[Answer]
## JavaScript (ES6), ~~68~~ 66 bytes
```
f=a=>a[0]?[a[0],...f(a.filter(b=>!a[0].some(c=>~b.indexOf(c))))]:a
f=([b,...a])=>b?[b,...f(a.filter(c=>!c.some(c=>~b.indexOf(c))))]:a
```
I thought I'd give the recursive approach a go, and by stealing @ETHproduction's set intersection trick I managed to undercut his answer!
I was not the first to misread the original question, and I was about to submit the following recursive function which finds a maximal set of matching edges, rather than a set of maximal matching edges. Subtle difference, I know!
```
f=a=>a.map(([b,c])=>[[b,c],...f(a.filter(([d,e])=>b-d&&b-e&&c-d&&c-e))]).sort((d,e)=>e.length-d.length)[0]||[]
```
Simple recursive approach. For each input element, deletes all conflicting edges from the set and finds the maximal set of matching edges of the remaining subset, then finds the maximal result over each input element. Somewhat inefficient for large sets (9-byte speed-up possible).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
FQ⁼F
ŒPÇÐfṪ
```
[Try it online!](https://tio.run/nexus/jelly#@@8W@KhxjxvX0UkBh9sPT0h7uHPV////ow10DGN1gKQRkDTUMQaTJkDSCMw2BrONdUyBpKmOWSwA "Jelly – TIO Nexus")
Sample input: `[0,1],[0,2],[1,3],[1,4],[2,3],[3,4],[3,5],[5,6]`
Sample output: `[[1, 4], [2, 3], [5, 6]]`
### How it works
```
FQ⁼F - Helper function, returns 1 if a set of edges is non-matching
F - Flatten input
Q - Remove repeated elements
⁼ - Return boolean value. Is this equal to
F - The flattened input list
ŒPÇÐfṪ - Main link.
ŒP - Power set of input list of edges
Ðf - Remove all elements which return 1 if
Ç - (Helper function) it is a non-matching set
Ṫ - Get the last element in the resultant list (the longest).
Always maximal because it is the longest, so any
edge added would not be in this list (not matching)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 68 bytes
```
f=lambda g:len({*sum(g,())})<2*len(g)and max(f(g-{k})for k in g)or g
```
[Try it online!](https://tio.run/##Jc3RDoIwDAXQX@ljS2oim/hg9GNmcJXACgFMNAvfPrfs6dzbPtzlt79ntSn5x@TCs3cgt@mlGJvtE1AYiQ66m6bchJz2ENwXPcopjgf5eYURBgWhnCQt66B7/kY8c0sMGVNo2VYuBVObrc1yV@j4mpco/QE "Python 3 – Try It Online")
Takes input as set. Recursively removes one item until there are no duplicate vertices. It then returns the set with the most items.
] |
[Question]
[
From what I've seen throughout my time here on PPCG, most JavaScript entries involving fat arrow functions tend to be one of two camps:
1. The simple ones that are capable of running as a single statement and returning an answer, straight off the bat, like `x=(a,b)=>a*a+b`
2. The more complex ones that usually have curly braces because of the use of loops, and as a result require the use of a `return` statement.. like `p=b=>{m=b;for(a=1;~-m;)--m,a*=m*m;return a%b}`
Taking the above example from category 2 with the curly braces concept as proof-of-concept... Would there be a way to re-golf this code (or similar) like this so as to eliminate the curly braces as well as the `return`? I'm only asking this as this could *potentially* (not saying this will happen all the time) eliminate 8 bytes from a JS golfer's code. Are there any techniques that one could use in this instance? I've tried recursion, but the `m=b` statement has proven to be a bit of a bugbear, as I can't seem to shake it.
For the above code, how would one golf that further so as to eliminate the `return` statement, regardless of whether it golfs shorter or not?
[Answer]
## Use Recursion
I've found that recursion is (almost) always shorter than `eval`+`for`. The general way to convert from for to eval is:
```
for(a=n;b;c);d
(f=a=>b?f(c):d)(n)
```
So let's see your example:
```
b=>{m=b;for(a=1;~-m;)--m,a*=m*m;return a%b}
```
We can first simplify it to:
```
for(m=b,a=1;~-m;--m,a*=m*m)a%b;
```
What did we do here? Well we simply moved everything inside the `for` statement, this helps us reduce the amount of semicolons which is not directly better but almost always leads to some golf.
---
Let's put this in eval and compare it to the recursion version:
```
b=>{m=b;for(a=1;~-m;)--m,a*=m*m;return a%b}
b=>eval('for(m=b,a=1;~-m;--m,a*=m*m)a%b')
b=>(f=a=>~-m?(--m,f(a*=m*m)):a%b)(1,m=b)
```
The first part of the for loop (`a=n`), we can start that off by passing those variables in as arguments. The condition is simply: `b?(c,f(a)):d` where `d` is the return value. Usually `c` just modifies `a` so it can be merged into it. So we can golf it even more using what I've mentioned:
```
b=>(f=a=>~-m?(--m,f(a*=m*m)):a%b)(1,m=b)
b=>(f=a=>~-m?f(a*=--m*m):a%b)(1,m=b) // --m moved into a*=
b=>(f=a=>--m?f(a*=m*m):a%b)(1,m=b) // --m moved to condition
```
That said, as noted by @Niel is simplifying your algorithm. An algorithm golfy in one language may not be golfy in another so make sure to try different algoriths and compare them.
[Answer]
# Abuse eval.
It's simple. Instead of:
```
f=n=>{for(i=c=0;i<n;i++)c+=n;return c}
```
Use
```
f=n=>eval("for(i=c=0;i<n;i++)c+=n;c")
```
Eval returns the last evaluated statement. In this case, since the last evaluated statement would be `c+=n`, we would be left with `c` anyhow, saving two bytes.
```
f=n=>eval("for(i=c=0;i<n;i++)c+=n")
```
In general:
```
f=n=>eval("code;x")
```
is shorter than this, by a byte:
```
f=n=>{code;return x}
```
---
As a note, using graves to call eval to possibly save bytes doesn't work, since:
```
eval`string`
```
is equivalent to
```
["string"]
```
Helpful for obfuscation! Not so much for code golf.
] |
[Question]
[
Write a program that is capable of randomly generating itself.
It must do this based on the *tokens* used in its source code. If your program's source code is composed of 50 unique tokens and is 60 tokens long, then the program should output 60 tokens where each token is randomly chosen from one of the 50 unique tokens.
For example, this program would have a one in 50^60 chance to reproduce itself.
**What is a token?** That depends on the language. For example, identifiers (`foo_bar`), keywords (`while`), and numbers (`42`) would count as tokens in most languages. Whitespace would not count in most languages.
**Additional rules:**
* Output may only contain tokens found in the programs source code, separated by the appropriate delimiter
* Output must be the same length as the program's source code, counted by tokens
* Only one programming language may be used
* Source code must have at least 3 unique tokens
* Exclude comments from the source code
* Program should only have a one in U^L chance to reproduce itself
**Scoring:** The program that has the best chance to reproduce itself, wins.
[Answer]
## Python 2, 3^-3 = 0.037
`exec` abuse is quite handy for reducing the token count. Now updated to not read the source file!
```
exec '' """
s = '''{a}
s = {b}
s = s.format(a='"'*3, b="'"*3+s+"'"*3)
import random
tokens = ['exec', "''", s]
print random.choice(tokens), random.choice(tokens), random.choice(tokens),
{a}'''
s = s.format(a='"'*3, b="'"*3+s+"'"*3)
import random
tokens = ['exec', "''", s]
print random.choice(tokens), random.choice(tokens), random.choice(tokens),
"""
```
The extra `''` between `exec` and the giant triple-quoted string is just to pad the token count to the required minimum of 3. It gets merged into the second string due to implicit string literal concatenation.
Original, opening-the-source-file version:
```
exec '''
# String literals are one token!
import random
import tokenize
with open(__file__) as f:
tokens = [x[1] for x in tokenize.generate_tokens(f.readline)][:-1]
''' '''
# Splitting the string into two strings pads the token count to the minimum of 3.
print random.choice(tokens), random.choice(tokens), random.choice(tokens),
'''
```
Strictly speaking, the Python grammar places an ENDMARKER token at the end of the source file, and we can't produce a source file with ENDMARKERs randomly strewn about. We pretend it doesn't exist.
[Answer]
## Javascript, 102 tokens, 33 unique, 7.73×10-154
Note, this is a true quine. It doesn't read the file or use `eval` or `Function.toString`
```
meta = "meta = ; out = '' ; tokens = meta . split ( '\\u0020' ) ; tokens . push ( '\"' + meta + '\"' ) ; length = tokens . length ; tmp = length ; unique = { } ; while ( tmp -- ) unique [ tokens [ tmp ] ] = unique ; unique = Object . keys ( unique ) ; tmp = unique . length ; while ( length -- ) out += tokens [ ~~ ( Math . random ( ) * tmp ) ] + '\\u0020' ; console . log ( out )";
out = '';
tokens = meta.split('\u0020');
tokens.push('"' + meta + '"');
//console.log(tokens);
length = tokens.length;
tmp = length;
unique = { };
while(tmp--) unique[tokens[tmp]] = unique;
unique = Object.keys(unique);
//console.log(unique);
tmp = unique.length;
while(length--)
out += unique[~~(Math.random() * tmp)] + '\u0020';
console.log(out)
```
[Answer]
# Python: P(generating program in 1 trial) = 3.0317 \* 10^-123
34 unique tokens, 80 total tokens. Note that there is a space at the end of each line.
```
import tokenize , random
tokens = [ x [ 1 ] for x in tokenize . generate_tokens ( open ( __file__ , 'r' ) . readline ) ] [ : -1 ]
s = ''
for x in tokens : s += random . choice ( list ( set ( tokens ) ) ) ; s += [ ' ' , '' ] [ s [ -1 ] == '\n' ]
print s
```
Sample output:
```
' ' random len set 'r' , for ( list , import ] ] tokens : random [ for '\n' import readline readline 'r' tokens [ len 'r' import '' choice '' '' for in ( readline ( = open readline , list 1 list s += for s 1 , '' : 1 += list len - __file__ ; open __file__ print . - ] 'r' for import [ print . ,
; . [ [ print print __file__ generate_tokens ] ; open ] , readline
```
Thanks to the other Python solution by user2357112 for reminding me to discard the last token and use `__file__` which I was previously ignorant of.
[Answer]
# J - 1 in 1117 = 1.978 x 10-18
```
;(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''
```
J has a bunch of handy little tools for getting these kinds of jobs done.
* First of all, *any space separated string of numbers is one token*. It means a one-dimensional array of those numbers. This is how J's lexer works. By the way, that's seventeen `11`s, if anyone is curious.
* `(,,,{:,{:)'QUINE'''` is a common quine trick in J, made to use as few tokens as possible: `{:` means *Tail*, so it appends the string to itself, and then adds two copies of the last character to the end of that. Since the last character is a single quote (J uses Pascal-style strings), the result is `QUINE'QUINE'''`.
* `;:` is a tokenizer, and breaks up an input string as though it was J code, returning a list of boxes. The length of this result is 17.
* `~.` takes all the unique elements of this array. The length of this result is 11.
* `?` is called *Roll*. For each integer in its argument, it selects a random positive number greater than or equal to zero, less than that number. So here J will generate 17 numbers from 0 to 10 inclusive.
* `{` uses the random indices to select items out of our list of unique-tokens-in-boxes.
* `;` opens all these boxes and runs the result together.
Some examples follow. The indented lines are the input prompts, and the lines flush with the left side are the interpreter's output.
```
;(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''
~.~.(?;;:11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''(){11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){(;:;
;(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''
{';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)''',?{:;:{:';(?11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11){~.;:(,,,{:,{:)'''11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11{:{;(;:{:,~.
```
[Answer]
# Postscript
This was a fun one
```
/cvx /cvx cvx /exec /exec cvx /dup /rand /mod /get /== /array /astore /realtime
/srand /repeat 6 17 54 17 /array cvx exec /astore cvx exec 54 /dup cvx /rand
cvx 17 /mod cvx /get cvx /== cvx 6 /array cvx exec /astore cvx exec cvx /realtime
cvx exec /srand cvx exec /repeat cvx exec
```
There are 17 unique tokens and 54 tokens total for approx 1 in 3.6e-67 chance.
[Answer]
## Whitespace, 3^-205 3^-189 3^-181 3^-132 ~= 10^-63
This is a Whitespace program that, when seeded with random characters, has a 1 in 3^132 chance of reproducing itself (3 distinct tokens, repeated 132 times). It must be seeded with at least 132 random characters when run, (Whitespace has no built-in random or date function to seed with) e.g. `some_whitespace_interpreter my_quine.ws <some_random_source >quine_output.ws`. The score would be improved if the program could be golfed any more, but this is my first "real" Whitespace program, so I'll just leave it with my meager amount of golfing.
Plain Whitespace code, or [see it run](http://ideone.com/jOwCS0): (to try it, click "edit", copy the stuff inside the <pre> tags; should be 132 characters with Unix-style EOL)
```
```
Code annotated with what command is what (not technically a quine, as it won't reproduce the comments):
```
stack push_number + 0 end
stack push_number + 1 0 0 1 end
heap store stack push_number + 1 end
stack push_number + 1 0 0 0 0 0 end
heap store stack push_number + 1 0 end
stack push_number + 1 0 1 0 end
heap store stack push_number + 1 0 0 0 0 0 1 1 end
flow
make_label loop_begin
stack push_number + 1 1 end
IO
read character stack push_number + 1 1 end
heap retrieve stack push_number + 1 1 end
arithmetic modulo heap retrieve IO
print char stack push_number + 1 end
arithmetic subtract stack duplicate
flow
jump_if_zero end_prog
flow
jump_to
loop_begin
flow
make_label end_prog
flow
end_program
```
If the seed just happens to be equivalent (the characters are taken mod 3 to be converted to the tokens) to this, it will succeed:
```
CCCCACCCBCCBABBCCCCBACCCBCCCCCABBCCCCBCACCCBCBCABBCCCCBCCCCCBBAACCBACCCBBABABCCCCBBABBBCCCBBABCBBBBBBACCCCCBABCCBCACABBAACABAACCAAAA
```
It's a pretty simple program, roughly equivalent to this Ruby program:
```
i = 131
while true
print '\t \n'[STDIN.getc.ord % 3]
i = i - 1
break if i < 0
end
```
[Answer]
## Perl, 27 tokens, P = 1.4779 x 10-34
```
@ARGV=$0;print$W[rand@W]for@W=split/(\W)/,readline
```
Last edit: use `@ARGV=$0` instead of `open*ARGV,$0` to save a token.
* 15 unique tokens
* 4 tokens appear 2 times (`=`, `/`, `@`, `$`)
* 1 token appears 4 times (`W`)
So I think that makes the probability (pow(2,2\*4) \* pow(4,4))/pow(27,27),
about 1.48E-34.
If the source code is in a file called `ARGV`, then you can use this 26 token solution with P =~ 2.193 x 10-31:
```
@ARGV=ARGV;print$ARGV[rand@ARGV]for@ARGV=split/(\W)/,readline
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), \$1\$ in \$3^3\$ = \$0.037037...\$
(I know this isn't code-golf, but...)
```
q[say |roll <<~~"q[$_]".EVAL>>: 3]~~.EVAL
```
[Try it online!](https://tio.run/##K0gtyjH7/78wujixUqGmKD8nR8HGpq5OqTBaJT5WSc81zNHHzs5KwTi2rg7M4fr/HwA "Perl 6 – Try It Online")
Much the same as the Python answer, where the first token is a string literal that is evaluated. The tokens are
```
q[say |roll <<~~"q[$_]".EVAL>>: 3] String literal
~~ Smartmatch operator
.EVAL Function call
```
### Explanation:
```
q[say |roll <<~~"q[$_]".EVAL>>: 3] # Push as string literal
~~ # Smartmatch by setting $_ to the string literal
.EVAL # Eval the string
<<~~"q[$_]".EVAL>> # From the list of tokens
roll : 3 # Pick 3 times with replacement
say | # Join and print
```
] |
[Question]
[
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through n-1.
So the sequence [4,1,2,4] has absolute differences [3,1,2] which is equivalent to the set [1,2,3] (1 to n-1 where n is the length of original sequence) so it is therefore a jolly jumper.
Sequences have length n>0.
Assume n=1 is a jolly jumper.
*Easy mode:* Don't worry about stdin/stdout. Just a function that accepts arguments however and returns *something* that indicates jolly or not
*Hard mode:* Input on stdin (space separated), and output is "Jolly" / "Not jolly". Capitalization matters.
This is code golf.
EDIT: Sequences can contain negative integers and input on stdin is space separated.
```
$ jolly 2 -1 0 2
Jolly
$ jolly 19 22 24 25
Jolly
$ jolly 19 22 24 21
Not jolly
```
[Answer]
## Haskell
## Easy 4 characters
Returns a list of jolly integers if and only if a list of jolly integers is given as input. This is legal based on "Just a function that accepts arguments however and returns something that indicates jolly or not".
```
j=id
```
Alternative easy solution with 61 characters:
Takes in a list and returns the empty list if the sequence is jolly.
```
import List
j n=zipWith(\x->abs.(x-))n(tail n)\\[1..length n]
```
[Answer]
### Ruby, 92 93 characters
The hard version with input on STDIN.
```
f=gets.split.each_cons(2).map{|a|eval(a*?-).abs}.sort
$><<(f==[*1..f.size]??J:"Not j")+"olly"
```
If you start it with `-pa` (counts as 4) you can save 5 chars:
```
f=$F.each_cons(2).map{|a|eval(a*?-).abs}.sort
$_=(f==[*1..f.size]??J:"Not j")+"olly"
```
[Answer]
# Java (Hard)
Assumes that input is given through stdin. (not through command line arguments as per example)
**Golfed - 325**
```
class JollyJumper {
public static void main(String[] args) {
String[] in = new Scanner(System.in).nextLine().split(" ");
int[] j=new int[in.length-1],k=j.clone();
for(int i=0;i<in.length-1;i++){j[i]=Math.abs(Integer.parseInt(in[i])-Integer.parseInt(in[i+1]));k[i]=i+1;}
Arrays.sort(j);System.out.println(Arrays.equals(j, k)?"Jolly":"Not jolly");
}
}
```
**Un-Golfed**
```
public class JollyJumper {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] jolly;
String[] in;
in = sc.nextLine().split(" ");
jolly = new int[in.length-1];
for (int i = 0; i < in.length-1; i++)
jolly[i] = Math.abs(Integer.parseInt(in[i]) - Integer.parseInt(in[i+1]));
Arrays.sort(jolly);
for (int i = 1; i <= in.length-1; i++) {
if (jolly[i-1] != i) {
System.out.println("Not jolly");
return;
}
}
System.out.println("Jolly");
}
}
```
[Answer]
## Scala, easy mode, 123 characters
```
def j(s:String)={var a=s.sliding(2,1).map(x=>math.abs(x(0)-x(1))).toList
for(c<-1 to a.size)
if(!a.contains(c))false
true}
```
To run or test on ideone.com:
```
object Main
{
def main(args:Array[String])
{
def j(s:String):Boolean=
{
var a=s.sliding(2,1).map(x=>math.abs(x(0)-x(1))).toList
for(c<-1 to a.size)
if(!a.contains(c)) false
true
}
println(j("4124"))
}
}
```
[Answer]
## Golfscript, easy mode, 21 18 chars
```
{.@-abs\}*;0]$.,,=
```
Accepts arguments as an array of ints on the stack, with nothing else on the stack; leaves 1 on the stack if it's jolly and 0 otherwise. To take input on stdin as a space-separated list of ints, prepend
```
~]
```
and to output "Jolly" / "Not jolly" (assuming that we're turning this into a program) postpend
```
"Not jJ"5/="olly"
```
[Answer]
# J (easy), 18
```
(i.@#-:<:/:])|2-/\
```
```
(i.@#-:<:/:])|2-/\2 _1 0 2
1
(i.@#-:<:/:])|2-/\19 22 24 25
1
(i.@#-:<:/:])|2-/\19 22 24 21
0
```
# J (hard), 68
```
2!:55]1!:2&2'olly',~>('Not j';'J'){~(i.@#-:<:/:])|2-/\".@>2}.ARGV_j_
```
```
$ jconsole jumper.ijs 2 -1 0 2
Jolly
$ jconsole jumper.ijs 19 22 24 25
Jolly
$ jconsole jumper.ijs 2 19 22 24 21
Not jolly
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes (easy)
```
s₂ᶠ-ᵐȧᵐo~⟦₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRU9PDbQt0H26dcGI5kMivezR/2aOmxv//o410FOINdRQMdBSMYv8DAA "Brachylog – Try It Online")
`s₂ᶠ-ᵐ` - Consecutive differences
`ȧᵐ` - Absolute values
`o` - Sort
`~⟦₁` - Is the result the range 1 to something?
[Answer]
## J, 30 26 easy mode, 81 76 hard mode
*edit:* handle lists shorter than 3, fix stdin reading
First line takes care of easy mode, second adds hard mode.
```
j=:[:*/[:(>:@i.@#=/:~)[:|2-/\]
exit('olly',~[:>('Not j';'J'){~[:j 0".}:)&.stdin''
```
J reads generally right-to-left:
`2-/\` : for every two successive numbers in the list, take the difference
`|` : absolute value
`/:~` : sort in ascending order
`>:@i.@#` : 1 to *n*, for a list of *n* numbers
`=` : compare the sorted differences with the sequence (using a J "fork")
`*/` : multiply all the element-wise booleans; if all the comparisons were 1, their product is 1, so it's jolly
[Answer]
## Ruby, 97 102 106 (hard)
Might as well, since everyone else is:
```
h,*t=gets.split
d=t.map{|i|h,i=i,h;eval(i+?-+h).abs}.sort
$><<(d==[*1..d.size]??J:"Not j")+"olly"
```
Input taken on stdin.
[Answer]
# D
## easy (~~103~~ 83 chars)
returns sum of 1..i.length on Jolly some other number if not (a bit of rules laywering here)
```
import std.math;auto jolly(I)(I i){int t,l;foreach(r;i){t+=abs(l-r);l=r;}return t;}
```
## hard (142 chars)
input is whitespace delimited and ends on EOF
```
import std.stdio;import std.math; void main(){int i,j,l,t;while(readf("%d ",&i)>0){t+=abs(l-i);l=i;j++;}write(t==j*++j/2?"J":"Not j","olly");}
```
[Answer]
# Groovy
## Easy: 78
```
j={m=[];it[1..-1].inject(it[0]){p,n->m<<p-n;n};m*.abs().sort()==1..<it.size()}
assert [[2, -1, 0, 2,], [19, 22, 24, 25], [19, 22, 24, 21]].collect { j(it) } == [true, true, false]
```
## Hard: 151
```
j={m=[];it[1..-1].inject(it[0]){p,n->m<<p-n;n};m*.abs().sort()==1..<it.size()};System.in.eachLine{println "${j(it.split()*.toLong())?'J':'Not j'}olly"}
```
[Answer]
## PowerShell, hard, 117 ~~126~~
```
('Not j','J')["$(($a=-split$input)|%{if($x-ne$0){[math]::abs($x-$_)}$x=$_}|sort)"-eq"$(1..($a.Count-1)|sort)"]+'olly'
```
History:
* 2011-11-18 17:54 (**123**, −3) – Changed `$null` to a non-existent variable
* 2011-11-18 18:02 (**117**, −6) – inlined all variable declarations
[Answer]
# Scala
A quick stab - there are probably improvements possible.
## Easy: 77
```
def j(? :Int*)=(?tail,?).zipped.map(_-_).map(math.abs).sorted==(1 to?.size-1)
```
## Hard: 124
```
val? =args.map(_.toInt)toSeq;print(if((?tail,?).zipped.map(_-_).map(math.abs).sorted==(1 to?.size-1))"Jolly"else"Not jolly")
```
[Answer]
# Q, 64 (hard), 30 (easy)
hard
```
{$[(1_(!)(#)x)~asc abs 1_(-':)x;(-1"Jolly";);(-1"Not jolly";)];}
```
easy
```
{(1_(!)(#)x)~asc abs 1_(-':)x}
```
[Answer]
## J (easy), 19 characters
```
*/(=i.@#)<:/:~|2-/\
```
Usage:
```
*/(=i.@#)<:/:~|2-/\4 2 1 4
1
```
Vary similar to [DCharness's answer](https://codegolf.stackexchange.com/a/3614/737), and I would have just added it as a comment but for the fact that he hasn't visited since the 23rd of February.
`2-/\` takes the difference between successive pairs of numbers,
`|` gets the absolute value of each number,
`/:~` sorts into ascending order,
`<:` decrements each number by 1,
`(=i.@#)` a [J hook](http://www.jsoftware.com/help/learning/09.htm) which generates the sequence of numbers from 0 to the length of the differences list - 1 (`i.@#`) and compares it with that list `=`.
`*/` multiples the list of `1`s and `0`s generated by the previous verb.
[Answer]
### Scala easy:138 153, 170 (was errornous, improved later)
```
def j(i:String)={
def a(s:Seq[Int])=(s zip s.tail).map(x=>(x._2-x._1))
a(a(i.split(" ").map(_.toInt)).map(math.abs).sorted).toSet.size==1}
```
ungolfed:
```
def jolly (input: String) = {
val list = input.split (" ").map (_.toInt)
def stepsize (s: Seq[Int]) =
(s zip s.tail).map (x=> (x._2 - x._1))
val first = stepsize (input.split (" ").map (_.toInt))
val pos = first.map (math.abs)
val unique = stepsize (pos.sorted).toSet
(unique.size) == 1
}
```
The idea is, that we build the second derivation:
```
Original: 4 1 2 4
Stepsize: -3 1 2 (first)
abs: 3 1 2
sorted: 1 2 3
Stepsize: 1 1
to Set: 1
size: 1
```
### Scala hard 172 182, 205 (was errornous/improved):
```
def j{
def a(s:Seq[Int])=(s zip s.tail).map(x=>(x._2-x._1))
println((if(a(a(readLine.split(" ").map(_.toInt)).map(math.abs).sorted).toSet.size==1)"J"else"Not j")+"olly")}
j
```
more or less the same as above.
[Answer]
# PHP, easy, 129
For a given array `$s` of integers:
```
for($i=1;$i<count($s);$i++)$a[abs($s[$i]-$s[$i-1])]=1;
for($i=1;$i<count($s);$i++)if(!isset($a[$i]))die('Not Jolly');echo 'Jolly';
```
The ungolfed version:
```
for( $i=1; $i<count( $s ); $i++ )
$a[ abs( $s[$i] - $s[$i-1] ) ] = 1;
for( $i=1; $i < count($s); $i++ )
if( !isset( $a[$i] ) )
die( 'Not Jolly' );
echo "Jolly";
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 6 bytes (easy)
```
IAṢ⁼J$
```
[Try it online!](https://tio.run/##y0rNyan8/9/T8eHORY8a93ip/P//30hH11DHQMcIAA "Jelly – Try It Online")
```
IAṢ⁼J$ jolly function on N:
IAṢ the increment list: get all the Increments, take their Absolute values, and Ṣort them
⁼ compare that to...
J$ range from 1 to len(N) -- this has an extra number, but that's fine because...
...the increment list is one shorter, and ⁼ will only compare that many values
```
Takes input as comma-separated numbers in the first argument. Returns 1 if the sequence is jolly, and 0 if it isn't!
**7-byte solution:**
```
LRṖḟIA$
```
[Try it online!](https://tio.run/##y0rNyan8/98n6OHOaQ93zPd0VPn//7@Rjq6hjoGOEQA "Jelly – Try It Online")
Takes input as comma-separated numbers in the first argument. Returns nothing if the list is a jolly jumper sequence, and *something* if it isn't.
Adding this line makes it work with the hard spec:
# [Jelly](https://github.com/DennisMitchell/jelly), 27 22 bytes (hard, feedback welcome!)
```
ɠḲVIAṢ⁼J$ị“¢⁼D“¡KṀȥƘạ»
```
[Try it online!](https://tio.run/##y0rNyan8///kgoc7NoV5Oj7cuehR4x4vlYe7ux81zDkE4riAGAu9H@5sOLH02IyHuxYe2v3/v5GCrqGCgYIRAA "Jelly – Try It Online")
```
ɠḲVIAṢ⁼J$ị“¢⁼D“¡KṀȥƘạ»
ɠḲV read a line, split on spaces and eValuate the numbers
IAṢ⁼J$ jolly function: see above!
ị ịndex the result into (remember Jelly is one-indexed, so 0 wraps around to the back):
“¢⁼D“ "Jolly" compressed if true,
¡KṀȥƘạ» or, "Not jolly" compressed if false!
```
**27-byte (hard) solution:**
```
LRṖḟIA$
ɠḲVÇ“¡KṀȥƘạ»“¢⁼D»L?
```
[Try it online!](https://tio.run/##AUQAu/9qZWxsef//TFLhuZbhuJ9JQSQKyaDhuLJWw4figJzCoUvhuYDIpcaY4bqhwrvigJzCouKBvETCu0w///8yIC0xIDAgMg "Jelly – Try It Online")
Takes space-separated numbers on `stdin`, and outputs "Jolly" or "Not jolly".
Explanation:
```
LRṖḟIA$ jolly function:
LRP make a range (R) from 1 to the input length (L), popping off (P) the last number to make it 1 to N-1.
ḟ reverse filter: remove all the elements from that range that are members of...
IA$ the increment list: get all the increments, take their absolute values (expressed as one monad via '$').
ɠḲVÇ“¡KṀȥƘạ»“¢⁼D»L? i/o main function:
ɠḲV read a line from stdin, split it on spaces and have Python parse each number (handling negative signs)
Ç ? run the above, and use the result on the following conditional:
L? if the length of the result is truthy (non-empty):
“¡KṀȥƘạ» then, return Jelly compressed string "Not jolly",
“¢⁼D» else, return Jelly compressed string "Jolly".
```
Any feedback much appreciated!
[Answer]
# [Haskell](https://www.haskell.org/), ~~59~~ 57 bytes
```
f n=all(`elem`map abs(zipWith(-)n$tail n))[1..length n-1]
```
Easy mode, returns jollyness as a boolean. Thanks to @Laikoni for two bytes.
[Try it online!](https://tio.run/##ZYsxDgIhEEV7TzGFBSQDCWQtLPYI1haEuJiwQhwmxKXy8oiF29j8vPeSn8L2jES9r8BzIBJLpFiWEiqE@ybeuV5zS0JJPraQCVhKZ7SmyI@WgJXxvYTMMMO4XG4g6itz06s8ADhwBi2qMX4o7mp2nX50RmvRTmjNXzl9i@8f "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~32~~ 30 bytes Hard
*-2 Bytes from @Shaggy*
```
`not jo¥y`s4*Näa n äa e¥1
hUÎu
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=YG5vdCBqb6V5YHM0Kk7kYSBuIORhIGWlMQpoVc51&input=MiAtMSAwIDI=)
[Answer]
## Python 3, 117 (hard)
```
l=[*map(int,input().split())]
print(["Not j","J"][{abs(a-b)for a,b in zip(l[1:],l[:-1])}=={*range(1,len(l))}]+"olly")
```
[Try it online!](https://tio.run/##DcgxDsIgFADQ3VP8MP1fwUjdmnCBDl6AMNCkKuYLhOJQm54dO73k5bW@Ury1xsZ2H58xxCpDzN@KdFkyh0Nyp1yORyvuqcJbSDEKZzc/LejVRI9UwMsJQoRfyMhWD06yHZR2tBuzdcXH54xa8hyRiXZ3Fol5FdRaD0rDFfo/ "Python 3 – Try It Online")
[Answer]
## JavaScript: 105 (easy mode)
[Golfed:](http://jsfiddle.net/briguy37/vhjdx/)
```
function a(l){for(r=i=1;i<(m=l.length);i++){for(j=t=0;j+1<m;)t+=(d=l[j]-l[++j])*d==i*i;t||(r=0)}return r}
```
[Un-golfed:](http://jsfiddle.net/briguy37/6f6y6/)
```
function isJolly(list){
//Iterate over i to list.length-1
for(r=i=1;i<(length=list.length);i++){
//Check the differences between all consecutive elements squared minus i squared. Set t to true if one was found.
for(j=t=0;j+1<length;)t+=(diff=list[j]-list[++j])*diff==i*i;
//if t is not true, return value is 0
t||(r=0)
}
return r
}
```
[Answer]
## Perl, 89 (hard)
86 characters of code + 3 for running with the `-p` option
```
@a=0;$a[abs($1-$2)]=1while s/(\S+) (\S+)/$2/;$_='Jolly';(grep{!defined}@a)&&s/J/Not j/
```
[Answer]
## [Javascript (hard): 138](http://jsfiddle.net/AFk2W/)
```
a=prompt().split(" ")
i=0;b=[];c=[]
while(b[i]=Math.abs(a[i]-a[++i]),c[i-1]=i,i<a.length-1);b.sort()
alert(b+""==c+""?"Jolly":"Not jolly")
```
[Answer]
## R, Easy, 110
```
f=function(s){p=NULL;l=length;for (i in 2:l(s))p=c(p,abs(s[i]-s[i-1]));ifelse(all(sort(p)==(1:(l(s)-1))),1,0)}
```
Usage:
```
f(c(2, -1, 0, 2))
[1] 1
f(c(19, 22, 24, 25))
[1] 1
f(c(19, 22, 24, 21))
[1] 0
```
[Answer]
## Python, 72 (easy), 114 (hard)
**Easy:**
```
def f(a):return len(set(map(lambda x,y:abs(x-y),a[1:],a[:-1])))>len(a)-2
```
**Hard**:
```
a=map(int,raw_input().split())
print('Not j','J')[len(set(map(lambda x,y:abs(x-y),a[1:],a[:-1])))>len(a)-2]+'olly'
```
[Answer]
## Python, 255 characters
```
r=[19,22,24,25]
i=0
k=[ i+1 for i in range(len(r)-1)]
def jolly(a):
p=[]
i=0
while i<len(a)-1:
p.append(abs(a[i+1]-a[i]))
i+=1
p.sort()
if p==k:
return 'jolly'
else:
return 'Not jolly'
print(jolly(r))
```
[Answer]
# C, 119(hard), 97(easy)
```
b,c,a[];main(k){while(~scanf("%d",a+c))k=c++;for(c=k;b<c*c;)k-abs(a[b%c]-a[b++%c+1])?:k--;puts(k?"Not jolly":"Jolly");}
```
The easy solution reads the input from the arguments and returns a 0 as exit code if the input is a jolly jumper sequence:
```
i,k;main(int c,char**a){for(k=c-=2,a++;i<c*c;)k-abs(atoi(a[i%c])-atoi(a[i++%c+1]))?:k--;exit(k);}
```
[Answer]
## APL (~~50~~ ~~49~~ 47, hard)
```
'Not jolly' 'Jolly'[1+K[⍋K←¯1↓|Z-1⌽Z]≡¯1↓⍳⍴Z←⎕]
```
Easy (24):
```
{K[⍋K←¯1↓|⍵-1⌽⍵]≡¯1↓⍳⍴⍵}
```
The function takes an array and returns 0 or 1.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ 10 bytes
```
Êo1 eUäa n
```
[Run it online](https://ethproductions.github.io/japt/?v=1.4.5&code=ym8xIGVV5GEgbg==&input=WzE5IDIyIDI0IDI1XQ==)
*Saved 1 byte thanks to Shaggy*
] |
[Question]
[
According to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers), every WebSocket message is sent as one or more *frames*. Your job is to extract the payload given a (masked) client-to-server text frame. The steps to extract the payload is as follows:
* ignore byte 1; read byte 2
+ if it is 254, skip the next 2 bytes
+ if it is 255, skip the next 8 bytes,
+ otherwise, continue
* interpret the next 4 bytes as an [XOR-cipher](https://en.wikipedia.org/wiki/XOR_cipher) key
* decrypt the final bytes using the (repeating) key and interpret it as a UTF-8 encoded string
For reference, here is an ungolfed solution:
```
#!/usr/bin/env python3
frame = open(0, 'rb').read()
pos = 2
if frame[1] == 254:
pos += 2 # skip 2 bytes
if frame[1] == 255:
pos += 8 # skip 8 bytes
# read the key (4 bytes)
key = frame[pos:][:4]
pos += 4
# decode the payload
payload = bytes(x ^ key[i % 4] for i, x in enumerate(frame[pos:]))
# output
print(payload.decode("utf-8"))
```
## Test Cases
| frame (octets are represented in hex) | payload |
| --- | --- |
| `81 83 3D 54 23 06 70 10 6D` | `MDN` |
| `81 85 3D 54 23 06 55 31 4F 6A 52` | `hello` |
| `81 FE 01 BD 3D 54 23 06 71 3B 51 63 50 74 4A 76 4E 21 4E 26 59 3B 4F 69 4F 74 50 6F 49 74 42 6B 58 20 0F 26 5E 3B 4D 75 58 37 57 63 49 21 51 26 5C 30 4A 76 54 27 40 6F 53 33 03 63 51 3D 57 2A 1D 27 46 62 1D 30 4C 26 58 3D 56 75 50 3B 47 26 49 31 4E 76 52 26 03 6F 53 37 4A 62 54 30 56 68 49 74 56 72 1D 38 42 64 52 26 46 26 58 20 03 62 52 38 4C 74 58 74 4E 67 5A 3A 42 26 5C 38 4A 77 48 35 0D 26 68 20 03 63 53 3D 4E 26 5C 30 03 6B 54 3A 4A 6B 1D 22 46 68 54 35 4E 2A 1D 25 56 6F 4E 74 4D 69 4E 20 51 73 59 74 46 7E 58 26 40 6F 49 35 57 6F 52 3A 03 73 51 38 42 6B 5E 3B 03 6A 5C 36 4C 74 54 27 03 68 54 27 4A 26 48 20 03 67 51 3D 52 73 54 24 03 63 45 74 46 67 1D 37 4C 6B 50 3B 47 69 1D 37 4C 68 4E 31 52 73 5C 20 0D 26 79 21 4A 75 1D 35 56 72 58 74 4A 74 48 26 46 26 59 3B 4F 69 4F 74 4A 68 1D 26 46 76 4F 31 4B 63 53 30 46 74 54 20 03 6F 53 74 55 69 51 21 53 72 5C 20 46 26 4B 31 4F 6F 49 74 46 75 4E 31 03 65 54 38 4F 73 50 74 47 69 51 3B 51 63 1D 31 56 26 5B 21 44 6F 5C 20 03 68 48 38 4F 67 1D 24 42 74 54 35 57 73 4F 7A 03 43 45 37 46 76 49 31 56 74 1D 27 4A 68 49 74 4C 65 5E 35 46 65 5C 20 03 65 48 24 4A 62 5C 20 42 72 1D 3A 4C 68 1D 24 51 69 54 30 46 68 49 78 03 75 48 3A 57 26 54 3A 03 65 48 38 53 67 1D 25 56 6F 1D 3B 45 60 54 37 4A 67 1D 30 46 75 58 26 56 68 49 74 4E 69 51 38 4A 72 1D 35 4D 6F 50 74 4A 62 1D 31 50 72 1D 38 42 64 52 26 56 6B 13` | `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.` |
Standard loopholes are forbidden. Shortest code wins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
```
a=>a.slice(K=[8,14][a[1]^255]^6).map((n,i)=>n^a[K-4+i%4])+''
```
[Try it online!](https://tio.run/##bVXbbiM3DH3vV/CliI14nblJM0bhAOMbUGy7L8U@pQmgnZEdFXPbGSnYv8@SlMZJsXkxbIY8POeQVP5TL2qqRjPYT11f69fz9lVt79V6akylF5@3D8Uqzh4f1EP8@JQI8fgkl@tWDYtFtzLL7X33pB4@f8puze/Z4/L25ubVwhYm2N7Dzp3Pelyfx75dTFhiq@fF3b//3N5dPMALJX1x7TdMGtQ46T87u3hZQSyXy@Ufv1V9N/WNXjf9ZXFe2MVNEUORQlqDyCBJIZKQRxBHIOsbKoC7O/j78OXjOvG/OoE/Y8hOIEsQybX6WTdN/2H96QhRDLsDpId33WNIdyBikCmICPIMshJyCdkRkpg/sdOGcqjThj4xBzPlCbIN5ycgEaGAJILoxPlHzj9ALiie5iBywsd8xMRelLOHNAq9iEwOGWMKNAeJpcwnZqo5JCXEB86RIBP6TrV7xik4R3KviPvmFMdeKfMn/IQihOnxc@qLONgXcbBWFkEL4Xj8gnVloRb7@l6kMeXahHP2XFWwD0eQqLSEtKTaoLFgjdgReQqIDhSXV5yU@Rxmn9kTiu@YW8k8d6w9Ye0FxwXne08E8z@x0ow8pxkdCR/dy1OaHcVR15H5y@Az@SN4LifWUlLf3HtezDPlORKfkrnJWS/Pi@LFPLuSka@68nl2CWNiThb0ZiLwwRzyOSdM6jXPDvm/xQvSgnMMOHvGZw9z3iXyVnC@CLMLsyj5s3g3u192mLwt2EPOoZ0/8c7s5rlEHPd6o7f9oYggHNrkmCNJ4OZ7IUK4zOuN8H56LYQjeI4FM7neXR4wr/dIumLSRfx3rDdjDvuZT8F7xTjez4Tv0XP280V86sLzzdj/NJ/1bgI@5of7Kt9ugfwXvAOC5yXe9RXsbTbfkdeezLdThtl5PqRlE24tu95awfvGOJgv@Gb9zl/xUZdIZ13znhP@jlTIiPM953x@E2R4cwjt3V3TbW7m3S5nnoLv5fT27oW3JebIR@8AYeI9ptfX9q9@1C2YYXIt1H3TjzAZC6rVdgX0BuvKautGULUZzFSZ7gK6MfjHSddYANq4qe1rsLodsNh0lalN7ToLzkKjviE8aOuhNbTq0ilQjfnu1Bq@WtCdaREbWkNfXvCnalfw3ZkJun6yo6tB/9BjZayypu/ANY1qq94jU5KZDHViSDNgMmiFxFvk1HsB2Mqu4UCQylkNZnTIxGs1HYx6GPWz7mo9onAMvPSNG7CdRjqoFPQ0aahM08wOoSAHZ3cxykJHhAD/b@IPN67h@KPSg9WObEQP@qpSusK8yg2mVpYqUMUw9qbWHblITmHTyjWDIt3Qn8@mMgpqPemR/tr2DdFQZJBBO6bgq2vXrz8B "JavaScript (Node.js) – Try It Online")
Input a `Buffer`, output string.
Or [83 bytes in browser](https://tio.run/##bcxRS8MwEMDxdz/FvcgurGubtokF6WAwBBnuxflUW4hptlWytCSx6qevrYIg@HZ33O//KgbhpG17vzJdo8ZjMYpibdQ7HNSH3yo5HS2SsPmeUIROt1LhrijzgGZVKUpa1QljVc1JeBE9oglaMhVqUe5W2bK9zipCRg8FOCjWMJefWuPzjbXiE91kvDxj9Py4jE4/hWH@279dXpQNe2GdujcehwAoJ4TcXsnOuE6rUHcnPKLHRU4hTyFtgGWQpBBzuImBxsCbxQwgiuBhu//fsT@OTSuF7A74Bljyq89K6278Ag), which accept `Uint8Array` as input.
[Answer]
# [J](http://jsoftware.com/), ~~44~~ ~~42~~ 35 bytes
*-~~2~~ 9 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!*
```
4(}.]u:@XOR#$4$])}.}.~3^1-254*@-1&{
```
[Try it online!](https://tio.run/##bVRNaxVBELznVzQmZBNJlvme2SdCZr9OgpCTIFFEEtSLoniS@Nef3TUz@14wBx@mqamu6ureb/sXffdAr3fU0RUp2vG/656m2zfr3l089ne/dzfv3t6enrmzu8vH/rH/az/oa@Pdy5trff5nf3ny49PPX/dC8H5HFzrQaU@d0sY6H2Ia8jjNy9qdf@0vX/UfNXfpzq9O7j9/@U4PVJ52SVOyZGfyjowlFSgq0orC3D2D9E@Qnv/U5FYKmbx5Br8upDSN81N@TXYkrylY8oqiI5cpBnILGY1fZh4EI8yD/DKGkWElNwBvKDBDIqNIrcAvwM8UvdRtJB@Fn/HMyb0EM5FVtZeIieTA6dk@C7PQoyE1ksmkZ2ACBSP/l7cTeBIwAb0U@kapcy8L/cJvpCKchT9KX@bhvszDb0OqXoSn8Cf4cvUt9y29xKPFWwPMhFcJc1gosNNMNsvb6jHBI3dknZ7ULPWw8VjomducMROpj9CWoXOEdwPvCXUPfJmJh/4VTp3MXDJahJ@nF61kJ3X2tUB/qHOW@XjkssJLlr6xzDy1TJGj6MnQFppf5CX11LLLYN58xZadASdjXPXrfNXDGJlzFE7p1bJj/Yd6Ei@cY@WZwI8ZRuySzNYD72t2NYuM33SU3X87LLNNmCEwsvMrdmZsuSjUi1912B@peOGRTdaomKqt9GKGeonbjWA/ixfh8cgxQcl2d7FybvcovrT4Ev0j/DpomJqehL0CT5mnwT0WzSVf5pcuyNdh/jY2v0PlZ3y9r3y4BZm/xw545OWP@nrM1rU7Kt5Nu51csyt6xMtQb81tt5awb@BhvMfNlp3f@NmXt81X23PhH8VFUMAXzbF9E0L95gjb0V3LbQ5tt3PT6XEv6@G7V78tGpXnvgPCyfdou/0/ "J – Try It Online")
Expects a list of numeric bytes as input.
## Explanation
```
4(}.]u:@XOR#$4$])}.}.~3^1-254*@-1&{
*@- sign of difference between
254 254
1&{ and the second byte
3^1- transform to the correct start byte - 1
}.~ chop off that many bytes from
}. the head of the input
( ------------) monadic forks
4$] select the key
#$ repeat that to the length of entire message
] XOR bitwise xor with the entire message
u:@ convert to characters
4 {. remove xor'd key
```
[Answer]
# [Python](https://www.python.org), ~~101~~ 83 bytes (@sheared)
thanks to @tsh for golfing the decryption part and the neat dict work!
```
def n(f):f=f[(*[2]*254,4,10)[f[1]]:];return[x^m for x,m in zip(f[4:],f[:4]*len(f))]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVTLbhNBEDzxH61cskuMtTtvG-Wwa3tv8AOWkQCvwVJiO44jJSC-hEsu8E_ha-iumbEtwWVttaqrq_oxP3_vng5ft5vn518Ph9Wb8NIv-xVtilU5vrtezYvd-Pq7snZcVwNlzdj8GH7pD8VqXi8GqizHi_nYLN7u-8PDfkOfng79ffH44ZZW2z09Dm5pvaFv6x3Dd1dmvBjcvb7phbosU7F3u_16cyg2xVx-LqvHy6v1oHYlCNaSvt1xRlUO9_3HZVEO73c3awbSZbkoh8v-83bZFxfgusikz39evQ81dTOqamqnpKdkDSlNlSNfk27J1uQ02Yq8IdOQd2RmpGp8HdmRYExHbiRfxjDSdWRGwCtyzBBIVVR1wM-An5K3EteerBd-xjMn1xLMhHSVaokYTwacVpNmYRp6akj1pBqqp8A4ckr-S-4EPAEYh1oV6nqJcy0N_cKvJCKckd9LXebhuszDuS4kL8IT-QN8mZTLdWMt8aiRq4CZICugDzNy7LQh3Uhu8hjgkSuyTkvVVOLuyKOhZ5r7jJ5IvIW2BjpbeFfwHhC3wMeeWOjv4NRIz2VGM-Hn7nkts5M4-5pBv0t9lv5YzKWDl0bq-tjzkGeKOYqeBtpc9ot5STzk2TVgPvryeXYKnIwxya-xSQ9jpM9eOKVWnh3rP8WDeOE5Jp4J-NFDj12S3lrgbZpdmkWDbzib3T87LL0N6CEwsvMddqbNc6kQj36r0_5IxAqPbHKNiEraYi1mEJ7u7Eawn9GL8FjMMUDJ8e584jzeo_iqxZfob-HXQMMk6wnYK_DEfircY9Qc58v8UgXzNei_9tnvKPEzPt1Xc7oF6b_FDljMy57VteityXcUvat8O02aXdQjXkbp1szx1gL2DTyMt7jZuPNHfvZldfaV91z4W3HhKuCjZp_fBJfeHGE7u2u5zVHe7SbrtLiX7vTupbelRuR_74Bw8j3q-K7-BQ)
[Answer]
# [Raku](https://raku.org/), ~~64~~ 60 bytes
```
{Buf(.[^4] «+^«.[4..*]).decode}o{.[(2 max.[1]*6-1520)..*]}
```
[Try it online!](https://tio.run/##dU/basJAFPyVg0jx0i67m70Y0EDTmJ8IUUSTp9oUpVQJ@SL/wh9LdzYkbR98GWbPmZkz@1mc3k17vNJTSau2jr9K9lF8T1i2UTndb/PN/cYyxdgsn7JDsa8ORVPVLJtIOu4uLBP5zLwILfkUkqY97640Gm9pFVFd0njbjKisTrTkl4UgB4GDIHGglQOJJzcOLHcgACaJnn/1@oFe@wUkKoXpFTP5x5muIQWLk0c3sQ1iLMAMFhoVLHQKkRY6hSgpBubvh723ux/2zHt9isFThUOexMxfWyAFEp4OeeshD02t7nWBBbN9P5/nu/jOnfcNOv6vc/dVG7U/ "Perl 6 – Try It Online")
(I discovered that I could shave off four bytes by calling `Buf` like a function to create a new buffer object, but the increasingly ancient version of Perl 6/Raku on TIO doesn't allow this syntax, so the link is to a previous version of my code that uses `.new`.)
This is two anonymous functions, composed together using the `o` operator.
The right brace-delimited expression is the first function to be applied, to an input list of integers, assumed to be in the range 0-255. It returns the tail of that list, starting with the xor key at the appropriate index given by the byte at index 1, `.[1]`. `.[1] * 6 - 1520` gives 10 if 255 is at that index, 4 if 254 is at that index, and some number less than zero for any other byte. `2 max` makes that number 2 if it's less than 2, giving the correct index for all cases.
The left brace-delimited function takes that key-plus-payload list of bytes and formats them into the output string. `Buf(...).decode` takes the list of bytes as the argument to construct a `Buf` object and decodes the utf-8 bytes into a regular string. The argument to `Buf` is `.[^4] «+^« .[4..*]`. `.[^4]` is the first four bytes (the xor key), and `.[4..*]` is rest of the bytes (the payload). `+^` is the bitwise-xor operator, and the guillemets that surround it make it a "hyperoperator" with very useful semantics. The elements of both lists are xor-ed in sequence, and since the guillemets are pointing leftwards at the list of key bytes, those bytes are cyclically re-read as many times as needed to match the number of payload bytes. An equivalent construction would be to reverse both the order of the lists and the direction of the guillemets: `.[4..*] »+^» .[^4]`.
[Answer]
# Java 19, 214 bytes
-45, see @Kevin Cruijseen's comments. Thanks!
```
interface A{static void main(String[]a){var f=java.util.HexFormat.of().parseHex(a[0]);int l=f.length,g=f[1]&255,p=g>254?10:g>253?4:2,x=p+4,i=x;while(i<l)f[i]^=f[p+(i++-x)%4];System.out.print(new String(f,x,l-x));}}
```
---
## Java 19, 259 bytes
-1 for space between `String[]` and `a`. Thanks!
```
interface A{static void main(String[]a){var f=java.util.HexFormat.of().parseHex(a[0]);var p=2;if((f[p]&0xff)==254)p+=2;if((f[p]&0xff)==255)p+=8;var x=p+4;for(var i=x;i<f.length;i++)f[i]=(byte)(f[i]^f[p+(i-x)%4]);System.out.print(new String(f,x,f.length-x));}}
```
## Java 19, 260 bytes
```
interface A{static void main(String[] a){var f=java.util.HexFormat.of().parseHex(a[0]);var p=2;if((f[p]&0xff)==254)p+=2;if((f[p]&0xff)==255)p+=8;var x=p+4;for(var i=x;i<f.length;i++)f[i]=(byte)(f[i]^f[p+(i-x)%4]);System.out.print(new String(f,x,f.length-x));}}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 21 (or 20?*†*) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¦¬₅<.S>3sm.$D4£Þ^4.$ç
```
Input as a list of integers; output as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//0LJDax41tdroBdsZF@fqqbiYHFp8eF6ciZ7K4eX//0cbGlnqKBgaG@somBnqKFiY6CgYmwLZQCaQMgHKmYPkDUACRrEA) or [verify all test cases](https://tio.run/##bVTLblMxEN3zFaPQZYl8bY/tIErlm5srxAqJJQKpQBeVoK3aFKlbJH6DDRJsWPMB6Z/wI2Hm2L5JgY2VzD0@c848fHF98vbsdPtp9uLqdL2@fXR5dXa@Pn1PZ@eXN@vHNDu@PXwwy@/WNycf9mIPnw1HU/jiZl3j2833zc/fn788mb986q4/zg8Gv/l29/WNnx/c/dge/Z1jd/H54ebX8fbVLHWUHLmB2JN1ZAJFQ52hMMwOCV/53leWvx35kUImthUzrsh01A/3eTpyPXFHwREbip58phjIr8h2OIVtoRhlW@gpGEGGkfwCeEtBGBJZQ2YEfgX8QJE17iJxVH7BC6fkUsySnKm5VEwkD04WmyLMQU8HqZFspm4AJlCw@lvvLsGTgAnIZZA3alxyOehXfqsR5Sz8UfMKj@QVHrkbUvWiPIU/wZevdyVvyaUeHe5aYJa4lVCHFQVxmsllvVs9JniUjKKTyQwaDxOPg56h1Rk10XgPbRk6e3i38J4QZ@BLTRj6Rzj1WnPt0Ur5pXrRae80Lr5W0B9qnbU@jL6M8JI1byw1T62n6KPqydAWml/0S@Op9S6DefIVW@8sOAXjq1/PVY9gtM5ROTVX653o38WTepE@Vp4l@FHDiFnS2jLwXHtXe5Fxpr3e/TPDWtuEGgKjMz9iZvrWF4N48Wt286MRVh6d5A4RW7WVXMJQt2/aEcxn8aI8jD4mKJn2LlbOaR/VV6e@VH8Pvx4alk1PwlyBp9TTYh@L5tJf4dcs6K9H/V1sfheVX/B1v/JuF7T@jBlg9Iv38jJq69seFe@27U6uvSt61Mui7pqfdi1h3sAjeMbOlpmf@MUXu@arzbny9@oiGOCL5tjehFDfHGXb22vdzUWb7dx0MvZl3L179W3pEPnfO6Ccso9u9voP).
**Explanation:**
```
¦ # Remove the first value of the (implicit) input
¬ # Push its new first value (without popping the headless list)
₅< # Push 254 (255 decreased by 1)
.S # Compare: -1 if <254; 0 if ==254; 1 if >254
> # Increase it by 1: 0 if <254; 1 if ==254; 2 if >254
3sm # Take 3 to the power that: 1 if <254; 3 if ==254; 9 if >254
.$ # Remove that many leading items from the headless list
D # Duplicate the remaining list
4£ # Pop the copy, leave just its first 4 values
Þ # Cycle this list indefinitely
^ # Bitwise-XOR the values at the same positions in the lists together
# (ignoring trailing items of the infinite list)
4.$ # Remove the four leading 0s †
ç # Convert every integer to a character with that codepoint
# (after which this list of characters is output implicitly)
```
† `4.$` could be golfed to `0Ú` (trim all leading 0s), if the encrypted text is guaranteed to never start with a leading ␀-byte.
[Answer]
# [C (GCC)](https://gcc.gnu.org), 120 bytes
```
#define g getchar()
x[4];i;n;y;main(){g;for((y=g)>253&&(n=y-255?2:8);n+4;)x[n--&3]=g;for(;(n=g)+1;)putchar(n^x[i--&3]);}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LZHdbpswGIalHXIVlSZVQVUl85M2GeomEn4CEc4A2xBX3URwAiSY0JYmZNOuZCc96e5pu5q56w4_6fH7vPL78yX_WuT58_PLU7e5HP3u37P1pmrWZ8VZse7yMnsYyFJ_q98ZldEYJ4NnVTOQvxfGZv8wGJxuCvmjOtTOzwfNzelSHQ4_qR9GstFc6Ibc3zaXl-fa3c0bbAikkC8UQ26f3oKbL_1t9Q-RjR9v_v81nv-8y4uNPjkgBXtH2i8UZ4tn0Zzt9BJVlC7AuEVaFK5ADULeLT1zxNNtBxkpNKJC3yM2T63JnNVhE7pjJAVHuMVISeclaCLuscA-8sRSEkbM6-hE_QAPVVwtrZUSaDH3ceDQfZxGSV4CPeRR7O-WPJma1rL2dAnNoiWzh02ybad-fdTjhnkwBDx7BZRgLBrmgQkfiNXOsx5UES8xxPr9LCbJCgwBSuqF5zjfkjRypU1dcFHRh4Qd8HZv5YotjN16cYT3qUUD5oSNqZbYB3seCwFV7DFuIPZNuI1EAO2BhtwuXADWSjPEgszWewHkngn4OnbmLAIKaXzRuAXxlLp-vbtGav1Z3PtZTF22G_WxClFgU0CEYKVAQJI6kjwCT-l04vq7xx6pY5_ZVEFb26Ik1JEGQ2azFqMuWvagJxVdeTg6pCIgswsdqTnzbR8Qi6Q5GF9JJoAOBFSNkZOwCWhiXorAvk63xKXkWJgq8Xy7rYRwKj79CrkF8x2nJdbEzexaNzXiLeqcE2tvSRQXOn41EHqYoc5ZOqFYLRerUiWZ0kQ8AIjX0cJuTzNE4EqZgPh1dTIRdzmljscJf0S_Vtnj-kr_Cw)
] |
[Question]
[
## Challenge
Your goal is to write a function that puts quotes around a sequence of capital letters in a string.
## So some examples (everything on the left (before function) and right (after function) are STRINGS):
`Hello the name's John Cena` -> `"H"ello the name's "J"ohn "C"ena`
`I got BIG OLD truck` -> `"I" got "BIG" "OLD" truck`
`[OLD, joe, SMOE]` ->`["OLD", joe, "SMOE"]`
`'BIG')` -> `'"BIG"')`
`fOOd` -> `f"OO"d`
`"78176&@*#dd09)*@(&#*@9a0YOYOYOYOYOYOOYOYOYOY28#@e` -> `"78176&@*#dd09)*@(&#*@9a0"YOYOYOYOYOYOOYOYOYOY"28#@e`
## Assumptions and Clarifications
* The sequence of capital letters can have a length of one (e.g. a string containing one character: H -> "H")
* You can assume there will be only a string inputted.
## Winning Criteria
Code golf, fewest bytes wins.
[Answer]
# [Perl 5](https://www.perl.org/), 15 bytes
```
s/[A-Z]+/"$&"/g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP9pRNypWW19JRU1JP/3/f4/UnJx8hZKMVIW8xNxU9WIFr/yMPAXn1LxELk@F9PwSBSdPdwV/HxeFkqLS5GyuaCBTRyErP1VHIdjX3zWWSx0or67Jlebvn8KlZG5haG6m5qClnJJiYKmp5aChpqzlYJloEOmPgDCGkYWyQ@q//IKSzPy84v@6BTkA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
0.ø.γ.u}'"ý¦¨
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fQO/wDr1zm/VKa9WVDu89tOzQiv//PVJzcvIVSjJSFfISc1PVixW88jPyFJxT8xIB "05AB1E – Try It Online")
```
0.ø # surround input string with 0s
.γ } # group characters by:
.u # is uppercase?
'"ý # join groups with quotes
¦¨ # remove the first and last characters (0s)
```
[Answer]
# [Gema](http://gema.sourceforge.net/), 8 characters
```
<K>="$0"
```
Sample run:
```
bash-5.0$ gema '<K>="$0"' <<< 'Hello the name’s John Cena'
"H"ello the name’s "J"ohn "C"ena
```
[Try it online!](https://tio.run/##S0/NTfz/38bbzlZJxUDp/3@P1JycfIWSjFSFvMTcVPViBa/8jDwF59S8RC5PhfT8EgUnT3cFfx8XhZKi0uRsrmggU0chKz9VRyHY1981lksdKK@uyZXm75/CpWRuYWhupuagpZySYmCpqeWgoaas5WCZaBDpj4AwhpGFskMqAA "Gema – Try It Online")
[Answer]
# JavaScript (ES6), ~~32~~ 30 bytes
### Using a reference to the last match
*Version suggested by @Grimmy*
*Saved 2 bytes thanks to @Shaggy*
```
s=>s.replace(/[A-Z]+/g,'"$&"')
```
[Try it online!](https://tio.run/##bYzLDoIwFET3fsVNMZQiKLoQXWjwFR/RdOFKjYsGLvioraHo76MbY6JkNpM5J3MRT2Hi/HwvfKUTLNNBaQZD08zxLkWMTusw8vfHRivzKKnbhLIy1spoiU2pMyd1yAKl1FCcEJS4ITWw0icFE1SCMFb7kZeQ6QLGyznw9RSK/BFfK6zDG3pw0ejBdsNnxwqFvj8oqwAp58n/TEnYa4ddO3KtJAn6zI0c23Kjvgh2/JtP6fSsCClj5Qs "JavaScript (Node.js) – Try It Online")
# JavaScript (ES6), 35 bytes
### With a callback function
```
s=>s.replace(/[A-Z]+/g,s=>`"${s}"`)
```
[Try it online!](https://tio.run/##bYzJCsIwFEX3fsUjFdPUOi4cFkqdcEDJwpWKYGhf6xATaaob8dtrNyJouZvLPYd7Fg9h/Ph0SypKB5iGvdT0@qYa400KH@3ablDZ7su1yM3mAyk@zYscWOprZbTEqtSRHdpkhlJqSI4ISlyRGljoo4IRKkEYK/zIc4h0AsP5FPhyDEl89y851i6DLpw1urBe8ck@R6HZB2U5IOQ8@J8paXca7VbJc6wgqHeZ49kly/G6or7h33xKs2N5SBlL3w "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 47 bytes
```
lambda s:re.sub('([A-Z]+)',r'"\1"',s)
import re
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqihVr7g0SUNdI9pRNypWW1Ndp0hdKcZQSV2nWJMrM7cgv6hEoSj1f0FRZl6JRpqGUkhGqkJeYm6qerGCV35GnoJzal6ikqbmfwA "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r"%A+"`"$&"
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIlQSsiYCIkJiI&input=IkkgZ290IEJJRyBPTEQgdHJ1Y2si)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
Blatant port of RGS's Python answer. (I relized that I posted to the wrong challenge, whoops!)
```
:Q"([A-Z]+)""\"\\1\"
```
[Try it online!](https://tio.run/##K6gsyfj/3ypQSSPaUTcqVltTSSlGKSbGMEbp/38lT4X0/BIFJ093BX8fF4WSotLkbCUA "Pyth – Try It Online")
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~26~~ 21 bytes
Saved 5 bytes thanks to [Xcali](https://codegolf.stackexchange.com/users/72767/xcali)!!!
```
s/[[:upper:]]\+/"&"/g
```
[Try it online!](https://tio.run/##K05N0U3PK/3/v1g/OtqqtKAgtcgqNjZGW19JTUk//f//kIxUhbzE3FT1YgWv/Iw8BefUvEQA "sed – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 11 bytes
```
[A-Z]+
"$&"
```
[Try it online!](https://tio.run/##K0otycxLNPz/P9pRNypWm0tJRU3p/3@P1JycfIWSjFSFvMTcVPViBa/8jDwF59S8RC5PhfT8EgUnT3cFfx8XhZKi0uRsrmggU0chKz9VRyHY1981lksdKK@uyZXm75/CpWRuYWhupuagpZySYmCpqeWgoaas5WCZaBDpj4AwhpGFskMqAA "Retina – Try It Online")
I thought Retina has a shortcut for `[A-Z]` but apparently that only works in transliterations and not substitutions? Hmm...
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 9 bytes
```
ͨõ«©/"±"
```
**[Try it online!](https://tio.run/##K/v//3DvoRWHtx5afWilvtKhjUr//3uk5uTkK5RkpCrkJeamqhcreOVn5Ck4p@YlcnF5KqTnlyg4ebor@Pu4KJQUlSZnc3FFA9k6Cln5qToKwb7@rrFcXOpAFeqaXFxp/v4pXFxK5haG5mZqDlrKKSkGlppaDhpqyloOlokGkf4ICGMYWSg7pAIA "V (vim) – Try It Online")**
This instructs Vim to replace all occurrences on all lines (`Í`)
...using the substitution `\(\u\)\+/"\1"`. Each `\x` may be replaced by `x` with the high-bit set, thus `\1` becomes `±`, etc...
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 10 bytes
Port of @Adám's answer.
```
[A-Z]+
"&"
```
[Try it online!](https://tio.run/##KyxNTCn6/z/aUTcqVptLSU3p/3@P1JycfIWSjFSFvMTcVPViBa/8jDwF59S8RAUuT4X0/BIFJ093BX8fF4WSotLkbK5oIFNHISs/VUch2NffNZZLHSivrsmV5u@fwqVkbmFobqbmoKWckmJgqanloKGmrOVgmWgQ6Y@AMIaRhbJDKgA "QuadR – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~100~~ \$\cdots\$ ~~74~~ 72 bytes
Saved ~~21~~ 23 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved a byte thanks to [S.S. Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne)!!!
```
t;u;f(int*s){for(t=1;*s;printf(s++),t=u)(u=*s<65|*s>90)^t&&putchar(34);}
```
[Try it online!](https://tio.run/##bYzJCsIwAETvfkVoISapQt26ECtFBVEEL16kIoQ0XRBTaZJT9durBcWLzGVmeDN8mHPetpoamqFSaqJwk1U10tGIEkXv9bvLkHIcPNCRwchERM292YOoRejii4bwbjQvWI0mU0yf7Y2VEuGml6G9dSwEkOwm@grsqkKClZDMwrT3ObXOsksduQV5pcFyuwGH/Rro2vDrf9APRr4HY2KnqRsmJE6gTeKQuafDT18zDuxYdMNn@wI "C (gcc) – Try It Online")
Uses `wchar_t` strings for input.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 31 bytes
```
0&?(:A$Z$•[⑻[|1⑼\",],|⑻[\",]0⑾,
```
[Try it online!](https://tio.run/##y05N///fQM1ew8pRJUrlUcOi6EcTd0fXGD6auCdGSSdWpwbEBbEMHk3cp/P/v0dqpUJ6aWWxjkJ5Rr56sYKSV36qkr2Cl7@rgq@jr6MiAA "Keg – Try It Online")
But seriously, don't ask who Joe is.
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
gsub("([A-Z]+)","'\\1'",scan(,''))
```
[Try it online!](https://tio.run/##K/r/P724NElDSSPaUTcqVltTSUdJPSbGUF1Jpzg5MU9DR11dU/O/kkdqTk6@QklGqkJeYm6qerGCV35GnoJzal6iEpeSp0J6fomCk6e7gr@Pi0JJUWlyttJ/AA "R – Try It Online")
Simple use of Regular Expressions.
# 39 bytes
```
cat(gsub('([A-Z]+)','"\\1"',scan(,'')))
```
[Try it online!](https://tio.run/##BcFLCoAgEADQfacYZjNKtugIfaAPQfuyhYkUZApq57f3Qs5aJXbF72TE9qbajpKTIJSyRhJRK8cEEec842is9ZBuA069hiLM/nbQGaewwAkun6CdBliXHlL49IP5Bw "R – Try It Online")
This method is the only way I can get the double quotes to work.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
```
->s{s.chars.chunk{|c|c<c.downcase}.map{|u,c|u ??"+c*''+?":c}*''}
```
[Try it online!](https://tio.run/##FcZBDsIgEADAr2y4oFZ5gFE5eDH@Yl23IZEuTenGGODtqJfJLPr49BHO0A@XXLKjgMtflVepVOlE7pneQpi5uQnnUnVPVcF7M9DO2sGbI7VfWp91zTA6whg35sYxJlgDg@DENsM9BYErC5pt/wI "Ruby – Try It Online")
Longer than the other Ruby solution, but one that doesn't use regex. I also love an excuse to use [`chunk`](https://apidock.com/ruby/Enumerable/chunk).
This groups successive characters of the string depending on whether or not they're uppercase, and then surround the ones that *are* uppercase with `"`. I had to do the `downcase` check rather than checking with `upcase`, because otherwise non-character strings (spaces, punctuation, etc.) would also be considered uppercase letters.
## Golfy Tricks:
* `*''` instead of `.join`
* `<` instead of `!=`
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 22 bytes
```
gsub("[A-Z]+","\"&\"")
```
[Try it online!](https://tio.run/##SyzP/v8/vbg0SUMp2lE3KlZbSUcpRkktRklJ8///kIxUhbzE3FT1YgWv/Iw8BefUvEQuT4X0/BIFJ093BX8fF4WSotLkbAA "AWK – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
F⁺S «ω✂"⁼№⪪α¹ω№αι≔ιω
```
[Try it online!](https://tio.run/##NYu7CgIxEEVr8xVDqgnEwnorXywLggvb2oSgMTgkax5uIX57TBCLC5dzOPqugvaKSrn5ADhSjji4OacpBesMCgkcuBDwZquxkoSL6P53IquvyC@cSzg@s6KIe5@bmMkmVBI2tV/qfrgCK0TrtzFa49A227FPKQMYn2A39HA@HSCFrB@srF/0BQ "Charcoal – Try It Online") Link is to verbose version of code. Port of my answer to the question linked by @manatwork in the comments.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
e€ØAŻIœṗj”"
```
[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzMcj@72PDr54c7pWY8a5ir9///fAyibr1CSkaqQl5ibql6s4OTpruCVn5Gn4JyalwgA "Jelly – Try It Online")
A monadic link taking a string and returning a string.
[Answer]
# perl -pE, 16 bytes
```
s/\p{Lu}+/"$&"/g
```
Unicode compliant, unlike the `s/[A-Z]+/"$&"/g` solution presented earlier.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 30 bytes
```
->s{s.gsub(/([A-Z]+)/,'"\1"')}
```
[Try it online!](https://tio.run/##KypNqvyfpmCr8F/Xrri6WC@9uDRJQ18j2lE3KlZbU19HXSnGUElds/Z/QWlJsUKaXnJiTo6GkkdqTk6@QklGqkJeYm6qerGCV35GnoJzal6ikiYXikpPhfT8EgUnT3cFfx8XhZKi0uRsdCXqQFl1TSXN/wA "Ruby – Try It Online")
A simple regex substitution.
] |
[Question]
[
A [permutation](https://en.wikipedia.org/wiki/Permutation) of a set \$S = \{s\_1, s\_2, \dotsc, s\_n\}\$ is a [bijective](https://en.wikipedia.org/wiki/Bijection) function \$\pi: S \to S\$. For example, if \$S = \{1,2,3,4\}\$ then the function \$\pi: x \mapsto 1 + (x + 1 \mod 4)\$ is a permutation:
$$
\pi(1) = 3,\quad
\pi(2) = 4,\quad
\pi(3) = 1,\quad
\pi(4) = 2
$$
We can also have permutations on infinite sets, let's take \$\mathbb{N}\$ as an example: The function \$\pi: x \mapsto x-1 + 2\cdot(x \mod 2)\$ is a permutation, swapping the odd and even integers in blocks of two. The first elements are as follows:
$$
2,1,4,3,6,5,8,7,10,9,12,11,14,13,16,15,\dotsc
$$
## Challenge
Your task for this challenge is to write a function/program implementing any1 permutation on the positive natural numbers. The score of your solution is the sum of codepoints after mapping them with the implemented permutation.
## Example
Suppose we take the above permutation implemented with Python:
```
def pi(x):
return x - 1 + 2*(x % 2)
```
[Try it online!](https://tio.run/##LYxBCoAgFAX3neIhBFq60DbRorsEabn5ysfATm8RzXJgJt/lTDS1tvuAHGVVS4cX9uViQsUICwM3yIoeTrWQ@LWRwBsdXtr5DzJHKrJqAbNC6G@l2gM "Python 3 – Try It Online")
The character `d` has codepoint \$100\$, \$\texttt{pi}(100) = 99\$. If we do this for every character, we get:
$$
99,102,101,31,111,106,39,119,42,57,9,31,31,31,31,113,102,115,118,113,109,31,119,31,46,31,50,31,44,31,49,41,39,119,31,38,31,49,42
$$
The sum of all these mapped characters is \$2463\$, this would be the score for that function.
## Rules
You will implement a permutation \$\pi\$ either as a function or program
* given an natural number \$x\$, return/output \$\pi(x)\$
* for the purpose of this challenge \$\mathbb{N}\$ does **not** contain \$0\$
* the permutation must non-trivially permute an infinite subset of \$\mathbb{N}\$
* your function/program is not allowed to read its own source
## Scoring
The score is given by the sum of all codepoints (zero bytes may not be part of the source code) under that permutation (the codepoints depend on your language2, you're free to use SBCS, UTF-8 etc. as long as your language supports it).
The submission with the lowest score wins, ties are broken by earliest submission.
---
1. Except for permutations which only permute a finite subset of \$\mathbb{N}\$, meaning that the set \$\{ x | \pi(x) \neq x \}\$ must be infinite.
2. If it improves your score, you can for example use a UTF-8 encoded Jelly submission instead of the usual SBCS.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score ~~288 250 212~~ 199
-38 thanks to Erik the Outgolfer!
```
C-*+
```
Swaps even with odd.
The score is \$67+45+44+43=199\$ - see [self-scoring here](https://tio.run/##y0rNyan8//9RwxxnXS3tRw1zD618uLMl0@FR05rDM7yAzEPryh5tXAdkBP//DwA "Jelly – Try It Online").
**[Try it online!](https://tio.run/##y0rNyan8/99ZV0v7f9DRPYfbHzWtcf//39DAAAA "Jelly – Try It Online")**
[Answer]
# JavaScript (ES6), Score = ~~276~~ 268
```
$=>(--$^40)+!0
```
[Try it online!](https://tio.run/##dY/NasMwEITvfoopCLTCsTC0Jxs5lJInSG@lJUKJ84MjBVkpBqNndyXaQy49Lfsxsztz0d96NP58C5V1@8PSq4WpjqqKfb3UonyqF5MwFHoZ3Db4sz2SaIvxfk2sbosPKWVWfMre@Y02JzJQHeYCMM6ObjjIwR1px9lsIm/wd43NZNMw0py0f0vsNZAQDy/kTe@3QftAzyKu0FM2il/nlOOQ/V8PYvOEDhZr8JKjAecxowo2il3KD@QGpcLUFjHtj1n5uwt6aPgqa0S7/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), Score: 201
```
*-!0+^40+!0
```
[Try it online!](https://tio.run/##XcrBCoIwGADgu0/xK6KVNSZIh0ZChw5Bh8DoGA73C4LbdJuQT7@MLtH5@wY0/d7LGWIORxhrv9mFNHsWNAupr4kznWTBwkm7cBTziJwfpysLAstnSG9o5OS467SCCscJVYMHSLernJCc0nVZkqRl33tRAl8ooNECB90pZz8z5kQbYX/jXTveQ9Vog/@D2Eky/wY "Perl 6 – Try It Online")
Port of [Arnauld's answer](https://codegolf.stackexchange.com/a/181263/76162). This benefits from xor (`+^`) having the same precedence as `-` and `+`, and the use of a Whatever lambda to reduce overall characters. Other than that, I couldn't find a way of representing it differently that got a better score.
# [Perl 6](https://github.com/nxadm/rakudo-pkg), Score ~~804~~ 702
```
{{(++$∉ords(q[!$%()+-2?[]_doqrsx{}∉])??++$+22-$++%2-$++%2!!++$)xx$_}()[-!$+$_]}
```
[Try it online!](https://tio.run/##XY5BS8MwGIbv/RXpyLqE2I@tBw8WVxQ8CB6EiZdSuthkUlmTNUmho/Suf9M/0mXMg3r5Ds/3wPMepNlfT80RYY5uUbudhoEwhr8/v7QRlrR5iOeEsjjJ8qIUujW2H0b/LWiWeY8lSYwZm//cMPSM9j0uR0LzOMQMl8U4bcGZukkDn4l2PjOLMJ/Bw@vdUxoElh/R4lmapnPc1VqhjWw7qSp5gxZXZAWwWi7peg3RLr24j0rIXgpUaSEPulbOnk3M4bz4t/iiHd@jTaWN/G@A7ZqL5Wmlmze45@9/QadqvwOsNg4@fCadTg "Perl 6 – Try It Online")
The first quine-y type answer here, and I think it scores pretty well.
This produces the sequence \$23,22,25,24...\$ from the question body with the range \$1,2,3,4...21\$ inserted at the indexes of the unique sorted codepoints of the code. For example, the 30th through 35th elements of the sequence are \$50, 53, 52, 1, 55, 54\$ since the 33rd codepoint is `!` and that's the lowest codepoint in my code.
[Answer]
# [Python 2](https://docs.python.org/2/) score: ~~742~~ ~~698~~ 694 points
```
lambda a:a^96or~~96
```
[Try it online!](https://tio.run/##VZBBasMwEEXX0SkGupCGGGGnxeCAVj6GcYgiy46KLQlZgXaTq7tSm7YEtJk/82f@k/@MV2cPm3KDBgGU0m2Wy2WQII/y1NQu3O9NvSWdrzEYz5DoD60YHQXdZxMSH4yNQFflgqYFrLeFjcyFgSlEGF0ABcbC06xZ4WLetYrGWUivqzivysNrn/0uRD2wRXo2FkHaSbOqSM03RBTiSSAk5SIvEB0oOavbLKMG56NZ5Az2@7Y8pQMBLOecpGSr6HqSdZMz/S8rSzySXZt@IOfkQftZKs1oU9PibM5Idj/UU6JuU5VX7UXHMuz0C/vH2mJhsH/APniyA3Pe7Qs "Python 2 – Try It Online")
-44 points thanks to Ørjan Johansen; -4 points thx to xnor.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 6 bytes, score 260
```
T`O`RO
```
[Try it online!](https://tio.run/##K0otycxL/P8/JME/Icj/v542l4oWl@F/CxMuSzMuc0sQaWEEZAAA "Retina 0.8.2 – Try It Online") Link includes self-scoring footer. Simply swaps digits `1` and `9` and `3` and `7` in the decimal representations, so that numbers that contain no digits coprime to `10` are unaffected.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 22 bytes, Score ~~247~~ 245
```
A=>A>65?A-1+A%2*2:66-A
```
[Try it online!](https://tio.run/##bY49D4IwEEB3fkVDYmilmBYjA6WYLk5uDs6mUr3BQvhwIfx2PJgYHG645L17Z7vEdjBfBm8L8D3HKRvQs9GlKbPT2SQyNrt0n@ZZlphZBV3fgn8RWz8rHf6nQhW4uq0e9k2/j5Y4An7lWXBvoa@u4CsaRqOYopyMciJJScZ0CrnjFPPM8QaoY0xt8dvwQVggtVw64Eqtxk@pZQuJvcUloKWCQgqhII7Zxkd17Ui8AEsAUJszwdPjDw "C# (Visual C# Interactive Compiler) – Try It Online")
Simple, if less than 66, return 66 minus input, else use the formula in the question that swaps even and odd numbers.
[Answer]
# TI-BASIC, 9 bytes, score ~~1088~~ ~~1051~~ 1000
```
Ans-cos(π2fPart(2⁻¹Ans
```
Swaps even with odd. Even maps to `Ans-1` and odd maps to `Ans+1`.
TI-BASIC is tokenized, so this program will have the following hex-values:
```
Ans - cos( π 2 fPart( 2 ⁻¹ Ans
72 71 C4 AC 32 BA 32 0C 72
```
Thus the score is: \$113+114+195+171+49+185+49+11+113=1000\$
**Output test program:**
```
For(I,1,10
I
Ans-cos(π2fPart(2⁻¹Ans
Disp Ans
Pause
End
```
Which outputs:
```
2
1
4
3
6
5
8
7
10
9
```
---
**Notes:**
* TI-BASIC's token values can be found [here](http://tibasicdev.wikidot.com/tokens).
* `Pause` is used in the output program to better see the permutation, as the calculator only has 8 lines. Press **[ENTER]** to view the next permutation.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes, score 681
```
⁻⁺²³²ι⊗﹪⊖ι²³³
```
[Try it online!](https://tio.run/##S85ILErOT8z5/37PynOL3@9Zem7Ho47l/x817n7UuOvQpkObD206t/NR1/T3O1c96pp2bidYaPP//9HRBhWOLjoKQNIJRDoZgUljBNvVEkRauoLVmILZLghxFPXGsbEA "Charcoal – Try It Online") Link is to self-scoring version with header to map over an array of byte codes. (Charcoal has a custom code page so I've manually inserted the correct byte codes in the input.) Works by reversing ranges of 233 numbers, so that 117, 350, 583 ... are unchanged. Explanation:
```
ι Value
⁺ Plus
²³² Literal 232
⁻ Minus
ι Value
⊖ Decremented
﹪ Modulo
²³³ Literal 233
⊗ Doubled
```
[Answer]
# Haskell, score 985
```
(\((.),(-))->(.)*200+mod(-39+(-))200+1).(\(*)->divMod((*)-1)200)
```
[Try it online!](https://tio.run/##pY/BSgMxEIbv@xQ/rWDSmrBrvSgqlFV6sVIonmwPIZvtLjabZZIKIj77moBYxIMHL8PMfDMfM43yL2a/H97FGA/zx8XTfHGPcrXCWHxkre0dBdypoGTZKMqsajvcoHIZtOuC6YLHtcDOhPKrzNAfwjoQRss39OR2pOyph9eOzBVGEVPbBZzAH2yMVvVgNSQcVfzbeZSs055H7QhG6QY6XqF0MPTD9Zcl8RrPhZQXeb79tXpEWR2/2wxsw5jkZ0xwLm5jNjnP86l1FROzy2nqprrgMs5N4kTVvi4jTHmREB/wb8Un "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 488 [in 05AB1E's code page](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
È·<-
```
Swaps odd and even like the example function.
Will try to improve the score from here.
[Try it online with input in the range `[1, 100]`](https://tio.run/##yy9OTMpM/W9oYODqZ6@koGunoGTvBwT/D3cc2m6j@1/nPwA) or [Try it online with the codepoints.](https://tio.run/##yy9OTMpM/e/h8v9wx6HtNrr//f9HKzlbKOkoOZkDCWNnIGHkohQLAA)
**Explanation:**
```
È # Check if the (implicit) input is even (1 if truthy; 0 if falsey)
· # Double (2 if truthy; 0 if falsey)
< # Decrease by 1 (1 if truthy; -1 if falsey)
- # Subtract it from the (implicit) input (and output implicitly)
```
[Answer]
# Brainfuck, 47 bytes, score 2988
```
,[-<+<+>>]<[->[>+<[-]]+>[<->-]<<]>[-<<++>>]<<-.
```
[Try it online!](https://tio.run/##hYqxDYAgEEVHYYDznOBylYUdA5ArhEhUAgGjJk6P6AK@4v/iPbtPa/KnCxX@MEhUu7ZAwCxkkA1DOxFgQ8goRMJvBl9A2NdmuSFVl7wUm9IWF6Wv@w7@UDY6NWTn1ZjD/AA "brainfuck – Try It Online")
I used the permutation given in the introduction. Since this is bijection you can use it as a simple symmetric cipher similar to ROT13 or Atbash. My solution works on unbounded cells. However, by restricting yourself to 8-bit cells, you could save 2 points by replacing `[-]` with `[+]`.
] |
[Question]
[
Write a program or function that draws an ASCII star, given the size of the arms as input.
Here's a star of size `1`
```
_/\_
\ /
|/\|
```
Here's a star of size `2`
```
/\
__/ \__
\ /
\ /
| /\ |
|/ \|
```
Here's a star of size `3`
```
/\
/ \
___/ \___
\ /
\ /
\ /
| /\ |
| / \ |
|/ \|
```
And so on.
### Input
A single positive integer [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), `n > 0`.
### Output
An ASCII-art representation of a star, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the points line up appropriately.
### Rules
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 17 bytes
*-3 bytes thanks to Neil.*
```
Nν↙ν↑↑ν↖ν ×_ν↗ν‖M
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SCNPk4sroCgzr0TDyiW/PM8nNa1ERwEo6JtflqphFVqAkA4tAEsguHC1EBElBSW4rJaGUrwSSE4ToTwoMz0Dop4rKDUtJzW5xDezqCi/SEPz/3/j/7pl/3WLcwA "Charcoal – Try It Online") Link is to verbose version.
I'm pretty happy with this golf so...
## Explanation
```
Nν take a number as input and store in ν
↙ν print / ν times downwards to the left
‚Üë move up once
↑ν print | ν times upwards
↖ν print \ ν times upwards to the left
print a space
×_ν print _ ν times
↗ν print / ν times upwards to the right
‖M reflect horizontally
```
```
/\
/ \ "No, this is Patrick!"
___/ \___
\ ‚òâ ‚òâ /
\ ùê∑ /
\ /
| /\ |
| / \ |
|/ \|
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~27~~ 24 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
╔*¹.╚№┼№.╝+ø┐.∙.1ž.╚┼+╬³
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTU0KiVCOS4ldTI1NUEldTIxMTYldTI1M0MldTIxMTYuJXUyNTVEKyVGOCV1MjUxMC4ldTIyMTkuMSV1MDE3RS4ldTI1NUEldTI1M0MrJXUyNTZDJUIz,inputs=Mw__)
Explanation:
```
‚ïî* push a string with input amount of underscores
¬π wrap that in an array
.‚ïö push a "/" diagonal of the size of the input (the top lines)
‚Ññ reverse vertically
┼ add horizontally the underscores behind the array
‚Ññ reverse vertically back
.‚ïù+ below that add a "\" diagonal (middle lines)
√∏ push an empty string as the base of the vertical bars
‚îê.‚àô get an array of "|" with the length of the input
.1ž at [input; 1] in the empty string insert that
.╚┼ horizontally append a "/" diagonal
+ add that below everything else
╬³ palindromize horizontally
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~166 160 157 155~~ 152 bytes
The `exec` approach is exactly the same byte count.
```
i=input();t,z=" \\";y=t*2
for k in range(i*3):s=k%i;o=i+~s;p=i+o;g="_ "[i>k+1]*p;print[g+"/"+y*k+z+g,t*s+z+y*p+"/",~-i*t+"|"+o*t+"/"+y*s+z+o*t+"|"][k/i]
```
[Try it online!](https://tio.run/##JcpBCsIwEIXhvacIA0I7UylW3BjiRdoiLjQOgSQ04yJFevXY6uqD/72Y5RV8Vwob9vEtVa2lmQ2oYQCdjWC3e4ZJOcVeTXdvHxXjqb4k4/asg2Fako4rQVsDNwU9Xx0dR4w6TuyltwQtUEZHM9lGMK1mjFttlgOjEHyAwubvt@3hX8fetTyWcv4C "Python 2 – Try It Online")
*Saved 3 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech).*
[Answer]
# Java 8, ~~385~~ ~~376~~ ~~344~~ ~~304~~ ~~285~~ ~~280~~ ~~268~~ ~~264~~ ~~252~~ 250 ~~+ 19~~ bytes
```
n->{int s=2*n,w=2*s,e=n-1,i=0,o,l[][]=new int[n*3][w];for(;i<n;l[i][s+~i]=l[n+i][w+~i]=l[o][s+~i]=47,l[i][o]=l[o][o]=l[n+i][i]=92,l[e][i]=l[e][w-++i]=95,l[o][e]=l[o][s+n]=124)o=s+i;for(int[]b:l)System.out.println(new String(b,0,w).replace(" "," "));}
```
[Try it online!](https://tio.run/##PZAxb8MgEIW72r8CecIxRkmaqGodsnTq0CkjYiAOiUjJYQGOVUXpX3ex62YB3ruP43hneZWlbRScD1990@6NrlFtpPfoU2pAtzTxQYZoniNI26ANPbZQB22Bvlvw7UW5zQcEdVJuixqnIeyCdIj1UG5vUSHPljMgXVw9UQzKBdFsTiwxXHDBQHUoUhxmz4J3ojpahyu9gcpwLbgvfrRghkMRRTcJ@@@vXshI2cm1DzQWX5exqMbjuHdlUQz2moysenQCwRbLVW6ZL/T4/DCO2L@ZfPftg7pQ2wY6fswAHsbdhShOeE/mpMupU42RtcLZU0YylOV5de@TKk2TKcwpvqvVB3SJkeK/61wg6U4@HxJOHrFRWdeqCXgKlDbSeRUFHlg@F7F7mtzTe9@vfwE "Java (OpenJDK 8) – Try It Online")
[Answer]
# Mathematica, 189 bytes
```
nÔí°(
s_±x_±y_:=s->Array[If[x==y,s," "]&,{n,n}];
StringRiffle[Characters@{"_/\\_","\\ /","|/\\:"}/.
{"_"±#±n,"|"±#2±n,":"±#2±1,"\\"±#±#2,"/"±(n-#+1)±#2," "±0±1}
/.":"->"|"//ArrayFlatten,"
",""])
```
Line 2 defines the helper operator `±`, which is used to make line 4 evaluate to:
```
{"_" -> Array[If[#1 == n, "_", " "] &, {n, n}],
"|" -> Array[If[#2 == n, "|", " "] &, {n, n}],
":" -> Array[If[#2 == 1, ":", " "] &, {n, n}],
"\\" -> Array[If[#1 == #2, "\\"," "] &, {n, n}],
"/" -> Array[If[1 + n - #1 == #2, "/", " "] &, {n, n}],
" " -> Array[If[0 == 1, " ", " "] &, {n, n}]}
```
In line 3, the `ReplaceAll` (`/.`) takes a matrix representing the star of size 1 as well as the list of rules above. For the final steps, we use `ArrayFlatten`, which is shorter than `SubstitutionSystem`, and `StringRiffle`.
[Answer]
# Java 7, 295 bytes
Solution is method `f`.
```
String s(String s,int n){while(n-->0)s=" "+s;return s;}String f(int x){String n="\n",s="/",b="\\",o="",u="_";int i=0;for(x--;i<x;u+="_")o+=s(s,2*x-i+1)+s(b,2*i++)+n;o+=u+s+s(b,2*i)+u+n;while(i>=0)o+=s(b,x-i)+s(s,4*x-2*(x+~i--))+n;while(i++<x)o+=s("|",x)+s(s,x-i)+s(b,2*i)+s("|",x-i)+n;return o;}
```
[Try It Online](https://tio.run/##RVDdbsIgGL2uT0G4AgGnZrtCfINdeTmXpdXqcAqmgLJ03at3Hy1mCcnH@c5P4JzKWynstTan/Vd/DdVZ79DuXDqHXkttUNtvfKPNETnyuHBtPDK0vX/qc02MEOs5dQojzJxsah8ag5zssvpAkjrSNmOj8NZgDvonzCsAW8ytwpgHhT@wTGKt5vJgGxKFkHoVZWCJopYpRxxfTqPQbEGZIxUAzRhlRgIZmHvsKAuwG9@n12o@eisOzuRz/BlCllMS2a8WgtJ/MWOrOKrxD@ZxVGdbjs5U2pnHf63s@iKX53zpYdys3qMLVJh7e3tHZXN0FLWTohiqTSRSyNT3oWpCJTDwcTRUlqiFhLFCL2kwgKO52Hw7X19mNvjZFaI9SUmzAzF0iOgmcLr@Dw) (JDK 8)
## Ungolfed
```
String s(String s, int n) {
while (n-- > 0)
s = " " + s;
return s;
}
String f(int x) {
String
n = "\n",
s = "/",
b = "\\",
o = "",
u = "_"
;
int i = 0;
for (x--; i < x; u += "_")
o += s(s, 2*x - i + 1) + s(b, 2 * i++) + n;
o += u + s + s(b, 2 * i) + u + n;
while (i >= 0)
o += s(b, x - i) + s(s, 4*x - 2*(x + ~i--)) + n;
while (i++ < x)
o += s("|", x) + s(s, x - i) + s(b, 2 * i) + s("|", x - i) + n;
return o;
}
```
## Acknowledgments
* -1 byte thanks to Kevin Cruijssen
[Answer]
# [Python 2](https://docs.python.org/2/), 137 bytes
```
n=input()
b,f,s,v='\/ |'
for i in range(3*n):u=i/~-n*n*'_';d=f+i%n*2*s+b;print[u+d+u,b+s*2*(3*n+~i)+f,v+d.center(2*n)+v][i/n].center(4*n)
```
[Try it online!](https://tio.run/##NcxNCsIwEEDhfU@RjaTJRAtRN5acpBaxJtHZTEN@CoL06rEu3H7wXnjn10y6VjJIoeRWNJPyKqnF8GvHPrzxc2TIkFi809O1R0niUgx2654kSX7jvTUecEdSywRTHyJSHgpYKGqCtOmvgRUFeLWAPTwcZRdbvY1gGQfsaPzbabNaz/UL "Python 2 – Try It Online")
] |
[Question]
[
The task is as follows: Given a positive integer `x` and a prime `n > x`, output the smallest positive integer `y` such that `(y * y) mod n = x`. An important part of this question is the time limit specified below which excludes brute force solutions.
If there is no such value `y` then your code should output `N`.
**Test cases**
```
(2, 5, N),
(3, 5, N),
(4, 5, 2),
(524291, 1048583, N),
(529533, 1048583, N),
(534775, 1048583, 436853),
(540017, 1048583, 73675),
(536870913, 1073741827, 375394238),
(542239622, 1073741827, 267746399),
(547608331, 1073741827, N),
(552977040, 1073741827, 104595351),
(1099511627676, 1099511627791, N),
(1099511627677, 1099511627791, 269691261521),
(1099511627678, 1099511627791, 413834069585),
(1267650600228229401496703204376, 1267650600228229401496703205653, 5312823546347991512233563776),
(1267650600228229401496703204476, 1267650600228229401496703205653, N)
(1267650600228229401496703204576, 1267650600228229401496703205653, N)
(1267650600228229401496703204676, 1267650600228229401496703205653, 79905476259539917812907012931)
```
**Input and output**
You may take input and give output in any way that is convenient. If you don't like to output `N` then any `Falsey` value will do.
**Restrictions**
Your code must answer all the test cases in under 1 minute on a standard desktop. This time limit is only to prevent brute force answers and I expect good answers to run almost instantly. You may not use any library or builtin that solves this problem or that tests if a number is a quadratic residue.
[Answer]
# Python 2, 166 bytes
```
def Q(x,n,a=0):
e=n/2
while pow(a*a-x,e,n)<2:a+=1
w=a*a-x;b=r=a;c=s=1
while e:
if e%2:r,s=(r*b+s*c*w)%n,r*c+s*b
b,c=(b*b+c*c*w)%n,2*b*c;e/=2
return min(r,-r%n)
```
[Answer]
# Pyth, ~~83~~ 82 bytes
```
=eAQM.^GHQKf%=/H=2;1=gftgT/Q;1HJg~gGHh/H2WtG=*J=gT^2t-K=Kfq1gG^2T1=%*G=^T2Q;hS%_BJ
```
[Test suite](http://pyth.herokuapp.com/?code=%3DeAQM.%5EGHQKf%25%3D%2FH%3D2%3B1%3DgftgT%2FQ%3B1HJg~gGHh%2FH2WtG%3D%2aJ%3DgT%5E2t-K%3DKfq1gG%5E2T1%3D%25%2aG%3D%5ET2Q%3BhS%25_BJ&test_suite=1&test_suite_input=1%2C+2%0A2%2C+5%0A524291%2C+1048583%0A536870913%2C+1073741827%0A1099511627676%2C+1099511627791%0A1267650600228229401496703204376%2C+1267650600228229401496703205653%0A1267650600228229401496703204476%2C+1267650600228229401496703205653&debug=0)
This program implements the [Tonelli-Shanks algorithm](https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm). I wrote it by closely following the Wikipedia page. It takes as input `(n, p)`.
The absence of a square root is reported by the following error:
```
TypeError: pow() 3rd argument not allowed unless all arguments are integers
```
---
This is very intricately golfed code, written in the imperative style, as opposed to the more common functional style of Pyth.
The one subtle aspect of Pyth I'm using is `=`, which, if not immediately followed by a variable, searches forward in the program for the next variable, then assigns the result of the following expression to that variable, then returns that result. I will refer throughout the explanation to the wikipedia page: [Tonelli-Shanks algorithm](https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm), as that is the algorithm I am implementing.
**Explanation:**
```
=eAQ
```
`A` takes a 2-tuple as input, and assigns the values to `G` and `H` respectively, and returns its input. `Q` is the initial input. `e` returns the last element of a sequence. After this snippet, `G` is `n`, and `H` and `Q` are `p`.
```
M.^GHQ
```
`M` defines a 2 input function `g`, where the inputs are `G` and `H`. `.^` is Pyth's fast modular exponentiation function. This snippet defines `g` to mean exponentiation mod `Q`.
```
Kf%=/H=2;1
```
`f` defines a repeat until false loop, and returns the number of iterations it runs for, given `1` as its input. During each iteration of the loop, we divide `H` by 2, set `H` to that value, and check whether the result is odd. Once it is, we stop. `K` stores the number of iterations this took.
One very tricky thing is the `=2;` bit. `=` searches ahead for the next variable, which is `T`, so `T` is set to 2. However, `T` inside an `f` loop is the iteration counter, so we use `;` to get the value of `T` from the global environment. This is done to save a couple of bytes of whitespace that would otherwise be needed to separate the numbers.
After this snippet, `K` is `S` from the wikipedia article (wiki), and `H` is `Q` from the wiki, and `T` is `2`.
```
=gftgT/Q;1H
```
Now, we need to find a quadratic nonresidue mod `p`. We'll brute force this using the Euler criterion. `/Q2` is `(p-1)/2`, since `/` is floored division, so `ftgT/Q;1` finds the first integer `T` where `T ^ ((p-1)/2) != 1`, as desired. Recall that `;` again pulls `T` from the global environment, which is still 2. This result is `z` from the wiki.
Next, to create `c` from the wiki, we need `z^Q`, so we wrap the above in `g ... H` and assign the result to `T`. Now `T` is `c` from the wiki.
```
Jg~gGHh/H2
```
Let's separate out this: `~gGH`. `~` is like `=`, but returns the original value of the variable, not its new value. Thus, it returns `G`, which is `n` from the wiki.
This assigns `J` the value of `n^((Q+1)/2)`, which is `R` from the wiki.
Now, the following takes effect:
```
~gGH
```
This assigns `G` the value `n^Q`, which is `t` from the wiki.
Now, we have our loop variables set up. `M, c, t, R` from the wiki are `K, T, G, J`.
The body of the loop is complicated, so I'm going to present it with the whitespace, the way I wrote it:
```
WtG
=*J
=
gT^2
t-
K
=Kfq1gG^2T1
=%*G=^T2Q;
```
First, we check whether `G` is 1. If so, we exit the loop.
The next code that runs is:
```
=Kfq1gG^2T1
```
Here, we search for the first value of `i` such that `G^(2^i) mod Q = 1`, starting at 1. The result is saved in `K`.
```
=gT^2t-K=Kfq1gG^2T1
```
Here, we take the old value of `K`, subtract the new value of `K`, subtract 1, raise 2 to that power, and then raise `T` to that power mod `Q`, and then assign the result to `T`. This makes `T` equal to `b` from the wiki.
This is also the line which terminates the loop and fails if there is no solution, because in that case the new value of `K` will equal the old value of `K`, 2 will be raised to the `-1`, and the modular exponentiation will raise an error.
```
=*J
```
Next, we multiply `J` by the above result and store it back in `J`, keeping `R` updated.
```
=^T2
```
Then we square `T` and store the result back in `T`, setting `T` back to `c` from the wiki.
```
=%*G=^T2Q
```
Then we multiply `G` by that result, take it mod `Q` and store the result back in `G`.
```
;
```
And we terminate the loop.
After the loop's over, `J` is a square root of `n` mod `p`. To find the smallest one, we use the following code:
```
hS%_BJ
```
`_BJ` creates the list of `J` and its negation, `%` implicitly takes `Q` as its second argument, and uses the default behavior of Pyth to apply `% ... Q` to each member of the sequence. Then `S` sorts the list and `h` takes its first member, the minimum.
[Answer]
# [SageMath](http://www.sagemath.org/), 93 bytes
By reduction to a [much harder problem](https://en.wikipedia.org/wiki/Discrete_logarithm) for which SageMath happens to have fast enough builtins.
```
def f(x,n):g=primitive_root(n);k=Zmod(n)(x).log(g);y=pow(g,k//2,n);return k%2<1and min(y,n-y)
```
[Try it on SageMathCell](https://sagecell.sagemath.org/?z=eJytjt1KxDAQRu8F36E3QgrVnZ8kk1j7It6I0G4p3SZLqbp9e-OCYKGVXuzdfJxvzkzdHLOjuhQhf26r89gN3dR9Nm9jjJMKedlXr0Os06Qu-dMptqrNy7k6xy_VFv3hQGmvHJvpYwxZ_0Av-B7qbOiCmovwOOf3d8kYpnSAisz8ibyMehkNafJYZAjaGccL4g3zKmEtYlaJBkBZ37FOwONVKCwaHclik4i9JdrkYsEx4xZP74qAhg2O4L1BtCRW7E_nN4rHjZrsq7l_apSOGbAARI7Ia0DtrQATaL6-sV0w1vBOlb6dytxOZfeovgGOjLkG&lang=sage)
[Answer]
# [Haskell](https://www.haskell.org/), 326 bytes
Usually I like brute force answers.. Since this is strongly discouraged by the time limit, here's the most efficient way I know of:
```
r p=((\r->min(mod(-r)p)r)$).f p
f p x|p==2=x|q x=f 0 0|mod p 4==3=x&div(p+1)4|let(r,s)=foldl i(p-1,0)[1..t 1o]=m$x&(d$r+1)*(b&d s)where q a=1/=a&o;m=(`mod`p);a&0=1;a&e|even e=m$a&d e^2|0<1=m$(a&(e-1))*a;b=[n|n<-[2..],q n]!!0;i(a,b)_|m(x&d a*b&d b)==p-1=(d a,d b+o)|0<1=(d a,d b);o=d p;t y x|even x=t(y+1)(d x)|0<1=y;d=(`div`2)
```
[Try it online!](https://tio.run/##rZRLc9owFIX3/IqbGYaREkP1lhWibDLdtZt2SWhiQDSe4keM25oZ/3d6cQIJTTrDogtrfDnfPTpXAh6S9Y@wWm3TrCyqGm6KvK6K1ehjMw9lnRZ5r5claQ4elqu0hCwpP0Md1vVNsg5r6MMtSaJZNKcwvIZF0QOo4WoIdbUBUoX6Z5VD/wwqmEFCUZxjFxLFEt8BvqTfH2oUsbWs0ryGzquKKu/ntCM@hWUN4S8gRHPv2RMA8PshVAHuMGC4vPxaZOFV8pegHukJEBGBjqDrjYDIo0p1lXiutFDC8Qg4U7GO5QumhdNSvidIZa1@JShpYi33qmKM21eqlcbqQ6uJLXO8s7XSKh4LZKXV0ikh44OHENIZIY4xYaxVRjp3wKxhsZT8GDvkxAmsZYodyxhM42SaP2OcOac5N8Iaa3byvrS7Y2HvUPYNJYwzjgvDtXjPNn7ToLiMpWLG6Xh/NthujWaGMSFiIZxiXDljmRRMyS7ZvwFt9O6OJUdBajwjZZ3jmuMxSm2kteaETdRJm7ATnPR/czInOeGwbPdlELuLxcFtzIVjluEqu/uYbisoPSG31fA6S3OSFQsyrGhJK9qnoyWUPXygaUvvhW/aR2j8EhiwFkEUlPfSN4NF@ouUF5yqdhVqUkVr6pfFarGClJRDHjE64aNRDbyY@qzfDMiiXyF9TmaDBazp0@/3ERLPP/hkUIwzT@7R/76k42TAPMc1tOFXyCFgf4JN4Zto2RXHiiQDEoac0vNkPPOTvM2vhhMxGk2jR8inZ2dsnO7@MuhdmxEMCsn5btMZ9R6TeYIfRFheFLTz29d0XHicb1zDBofvtm58TTaYGpHmCd6MFxgUZ78XdLv9Aw "Haskell – Try It Online")
I'm sure this can be golfed down further, but this should do for now.
] |
[Question]
[
# Background
Ramanujan's number, \$1729\$, is called a [taxi-cab number](https://simple.wikipedia.org/wiki/Taxicab_number) due to the (possibly apocryphal) tale of Hardy boarding a cab to visit Ramanujan in hospital having this number, which seemed bland to him.
It's since known as the most famous of a class of integers known as "taxicab numbers" which are expressible as the sum of two \$n\$th powers (of positive integers) in two (or sometimes \$k\$) different ways.
\$1729\$ is the smallest natural number expressible as the sum of 2 cubes in 2 different ways, making it the first \$3,2\$ taxicab number (\$n,k\$ being general).
# Challenge
Given a number, decide whether it is a \$3,2\$ 'secondary taxicab number' - meaning it fulfils the same constraint as \$1729\$ (2 unique sums of cubes), but does not have to be the smallest such integer of the \$3,2\$ class (that being 1729, of course).
### Example cases
$$1729 = 10^3 + 9^3 = 12^3 + 1^3 \\
4104 = 15^3 + 9^3 = 16^3 + 2^3 \\
13832 = 2^3 + 24^3 = 18^3 + 20^3$$
As well as \$20683, 32832, 39312...\$
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins.
---
Rough Matlab code to find other cases by brute force:
```
for k = 1729:20000
C = sum(round(mod(real((k-[1:ceil(k^(1/3))].^3).^(1/3)),1)*10000)/10000==1);
if C > 1
D = (mod(C,2)==0)*C/2 + (mod(C,2)==1)*((C+1)/2);
disp([num2str(k),' has ',num2str(D),' solns'])
end
end
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
Credits to Erik the Outgolfer.
```
Œċ*3S€ċ>1
```
[Try it online!](https://tio.run/##y0rNyan8///opCPdWsbBj5rWHOm2M/z//7@huZElAA "Jelly – Try It Online")
This is too slow that it won't even work for `1729` online.
## Much faster, 12 bytes
Credits to Dennis.
```
R*3fRŒċS€ċ>1
```
[Try it online!](https://tio.run/##y0rNyan8/z9Iyzgt6OikI93Bj5rWHOm2M/z//7@huZElAA "Jelly – Try It Online")
[Answer]
# Mathematica, 35 bytes
```
Count[#^3+#2^3&~Array~{#,#},#,2]>2&
```
Pure function taking a positive integer and returning `True` or `False`.
`#^3+#2^3&~Array~{#,#}` tabulates all sums of cubes of two integers between 1 and the input. (This would be much faster with a sensible bound on the integers to be cubed, like the cube root of the input; but that would take precious bytes. As it is, the code takes about 30 seconds on the input `13832` and scales at least quadratically in the input.) `Count[...,#,2]` counts how many times the input appears in this list at nest-level 2; if this number is greater than `2`, then the input is a semi-taxicab number (greater than 2, rather than greater than 1, since a^3+b^3 and b^3+a^3 are being counted separately).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
### Code (very slow)
```
L3mãOQO3›
```
### Code (much faster), 12 bytes
```
tL3mDδ+˜QO3›
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f@/xMc41@XcFu3TcwL9jR817Pr/39DcyBIA "05AB1E – Try It Online")
### Explanation
```
t # Square root (not necessary but added for speed)
L # Create a list [1 .. sqrt(input)]
3m # Raise to the power of 3
D # Duplicate
δ+ # 2 dimensional addition
˜ # Deep-flatten the entire list
Q # Check which are equal to the input
O # Sum up to get the number of equalities
3› # Checks whether there are 4 or more equalities. In order for a number
to be a secondary taxicab number, there are at least two distinct
ways to get to that number and 4 ways when you also take reversed
arguments in account.
```
[Answer]
# Mathematica, ~~38~~ 37 bytes
```
Tr[1^PowersRepresentations[#,2,3]]>1&
```
*-1 byte thanks to @GregMartin*
As always, there is a Mathematica builtin to everything.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 15 bytes
```
{4≤⍵⍧∘.+⍨3*⍨⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/apNHnUse9W591Lv8UccMPe1HvSuMtYDEo97NQNHa/5r/0xQMzY0s/@sWAwA "APL (dzaima/APL) – Try It Online")
Same method as all the other answers. Only works till 4104 due to brute forcing.
more than 20 bytes golfed off with dzaima's help at the APL orchard.
The output appears with a ⊂ next to it, which has been patched in the latest version of the interpreter.
## Explanation
```
{4≤⍵⍧∘.+⍨3*⍨⍳⍵} ⍵ → input
3*⍨⍳⍵ range 1 to n, cubed
∘.+⍨ dot product, addition with itself
⍵⍧ number of times ⍵ appears in the sums
4≤ is 4 less than or equal to that?
```
[Answer]
## JavaScript (ES7), 63 bytes
A relatively fast recursive function which eventually returns a boolean.
```
f=(n,k,r=0,x=n-k**3)=>x<0?r>3:f(n,-~k,r+=(x**(1/3)+.5|0)**3==x)
```
### Demo
```
f=(n,k,r=0,x=n-k**3)=>x<0?r>3:f(n,-~k,r+=(x**(1/3)+.5|0)**3==x)
console.log([...Array(40000).keys()].filter(n => f(n)))
```
[Answer]
# Mathematica, 48 bytes
```
Length@Solve[x^3+y^3-#==0<x<y,{x,y},Integers]>1&
```
**input**
>
> [4104]
>
>
>
**output**
>
> True
>
>
>
[Answer]
## Python, 71 bytes
[Try it online](https://tio.run/##K6gsycjPM/rvYxvzPycxNyklUaHCKic1TyM6UyEtv0ghUyEzT6EoMS89VaNCEySQhRDI1KnQzExTyNTSMtbOAhK2thWxmnaG/wuKMvNKFHw0DM2NLDX/AwA)
```
lambda x:len([i for i in range(x)for j in range(i,x)if i**3+j**3==x])>1
```
[Answer]
# MATL (16 15 bytes) (13 12 ideally)
```
.4^:3^2XN!sG=sq
```
[Try it online!](https://tio.run/##y00syfn/X88kzso4zijCT7HY3ba48P9/Q3Mjy695@brJickZqQA)
## Explanation:
Based on the Jelly solution of 'Leaky Nun', just converted to MATL, probably redundant in some parts and can be improved:
```
.4^ % rough cube root of input, as maximum potential integer N.
:3^ % create array of all cubes from 1^3 up to N^3.
2XN % do nchoosek on cube array, creating all possible pairs (k=2) to add.
!s % transpose array and add all pairs to find sums.
G= % find all pairs that equal the original input.
sq % if there is more than one solution, then pass the test.
```
Note: falsy outputs include 0 and -1, while truthy output is 1. Thanks to Luis Mendo for saving an extra byte here replacing "s1>" with "sq".
## Ideally (13 12 bytes):
```
:3^2XN!sG=sq
```
...is enough, but for larger numbers this crashes on tio.run's page.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 52 bytes
```
->n{r=*1..n;r.product(r).count{|i,j|i**3+j**3==n}>1}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cur7rIVstQTy/PukivoCg/pTS5RKNIUy85vzSvpLomUyerJlNLy1g7C0jY2ubV2hnW/i/PyMxJVUhPLSnmUihQSItWidcryY/PjOVKzUv5b2JoYAIA "Ruby – Try It Online")
Since this version creates a massive n2 sized array, it fails on all true testcases higher than `1729`, here is a modified version that has a smaller array size of about n2/3, which successfully checks at least up to 31392.
[Try it online! (modified)](https://tio.run/##KypNqvyfZhvzX9cur7rIVstQTy9PS8tAzxgITKyL9AqK8lNKk0s0ijT1kvNL80qqazJ1smoytbSMtbOAhK1tXq2dYe3/8ozMnFSF9NSSYi6FAoW0aJV4vZL8@MxYrtS8lP/GlsaGRgA "Ruby – Try It Online")
[Answer]
# [PHP](https://php.net/), 76 bytes
```
for(;$i++<$argn**(1/3);)for($n=1;$n<$i;)$n++**3+$i**3!=$argn?:$c++;echo$c>1;
```
[Try it online!](https://tio.run/##HYrBDoMgEAXv/QvNOwibpiGkae1C/RazUeGyEP/dM7Ze5jAzNdUWpprqDfO@aezfr6cfvRt7bmvZB0YmClezdnAPb9j8PTQ6hgZkNlAiaz0h/9jFa54@ECJeJBXI13Frh5a7zJKWEw "PHP – Try It Online")
[Search till 400000 Try it online!](https://tio.run/##HYq7DoJAEEV7/0IyIfsg6gYrB6QwFDbaWJqQDVlhm2EzYGX011fgFrc454Q@xKIKfdg45oEbdmHgyVMnfnVzuz@ul1ri5jWws20v2FLnhMmOh2XSjmC5I/l50@gmAT6DVmKca4HgtS5WrZQw@1yiXDhQaRCoAI8SSGulcg1@/m25xtUJWq0R2rNJ08CephXvkiclGL/xDw "PHP – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 49 bytes
```
$_=1<grep{//;grep$'**3+$_**3=="@F",$_.."@F"}1..$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tbQJr0otaBaX98aRKuoa2kZa6vEA0lbWyUHNyUdlXg9PRCj1lBPTyX@/39DcyPLf/kFJZn5ecX/dQsScwA "Perl 5 – Try It Online")
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 32 bytes
```
D,g,@,3^AR3€Ω^$€+
L,R€gb+A€=b+2=
```
[Try it online!](https://tio.run/##S0xJKSj4/99FJ13HQcc4zjHI@FHTmnMr41SAlDaXj04QkE5P0nYEUrZJ2ka2/6FCTm5OsXBBLi6VnMTcpJREBSM7Q1MDLn8UAXMjS1QRE0MDEy7//wA "Add++ – Try It Online")
The Footer in the TIO link is simply a faster version (`b+` \$\to\$ `BFB]`)
## How it works
```
D,g,@, ; Define a helper function, g
; It takes an int; STACK = [5]
3^ ; Cube; STACK = [125]
AR ; Argument range; STACK = [125 [1 2 3 4 5]]
3€Ω^ ; Cube each; STACK = [125 [1 8 27 64 125]]
$€+ ; Add the cube to each; STACK = [[126 133 152 189 250]]
L, ; Define the main function
; Takes an int; STACK = [1729]
R ; Range; STACK = [[1 2 3 ... 1728 1729]]
€g ; Run g over each; STACK = [[[2] [9 16] ... ]]
b+ ; Concatenate; STACK = [[2 9 16 ...]]
A€=b+ ; Count argument; STACK = [2]
2= ; Equals 2? STACK = [1]
```
] |
[Question]
[
Yup, you read the title right. play the sound of pi.
More specifically, for every digit of pi in the first 1000, map it to a musical note and output the resulting melody to a file.
Basically, each digit turns to a note on the C Major scale (basically the normal scale). so 1 turns to Middle C, 2 turns to D4, 3 turns to E4, 9 turns to D5 and so on.
# Rules
* Each note should be exactly 0.5 seconds long.
* The melody should contain the first 1000 digits of pi, including the starting 3.
* 1 to 7 represent Middle C to B4, 8 is C5, 9 is D5 and 0 is E5
* All well supported file formats are allowed, as long as they were created before this challenge.
* There may be no pauses anywhere in the file, including the start and end.
* The instrument played does not matter. It could be a piano, sine wave, anything really, as long as the **correct** sound is easily hearable.
* It must take no input and produce no output except for the file. Reading from other files is disallowed.
* Standard loopholes are forbidden.
Example mathematica code:
```
(*please forgive me for this horrible, horrible mess of code*)
digits = RealDigits[Pi, 10, 1000][[1]] /. {0 -> 10};
weights = {0, 2, 4, 5, 7, 9, 11, 12, 14, 16};
melody = {};
For[i = 1, i < 1001, i++, melody = {melody , Sound[SoundNote[weights[[digits[[i]]]], 0.5]]}]
final = Sound[Flatten[melody]];
Export["C:\\Mathematica Shenanigans\\pi.wav", final];
```
Example melody showing first 100 digits: <http://vocaroo.com/i/s0cfEILwYb8M>
For your sanity, A table of pitches for each note and what note does each digit represent:
```
Digit 1: C: 261.63 Hz
Digit 2: D: 293.66 Hz
Digit 3: E: 329.63 Hz
Digit 4: F: 349.23 Hz
Digit 5: G: 392.00 Hz
Digit 6: A: 440.00 Hz
Digit 7: B: 493.88 Hz
Digit 8: C5: 523.25 Hz
Digit 9: D5: 587.33 Hz
Digit 0: E5: 659.25 Hz
```
[Answer]
# Python 2, 182 bytes
```
x=p=6637
while~-p:x=p/2*x/p+2*10**999;p-=2
s="MThd\0\0\0\6\0\1\0\1\342\4MTrk\0\0\13\301\0\220"
for i in`x`:s+="JHGECA@><L\260"[~ord(i)%29]+'{<'
open('p.mid','w').write(s+"\0\377/\0")
```
``x`` will produce `31415926...20198L`. The trailing `L` is used to produce the final channel message byte, via the mapping `~ord(i)%29`.
Outputs a single track Type 1 Midi file, named `p.mid` to the current working directory.
```
0000: 4d 54 68 64 00 00 00 06 MThd.... # Midi header, 6 bytes to follow
0008: 00 01 00 01 .... # Type 1, 1 track
000c: e2 04 â. # (-)30 ticks per beat, 4 beats per second
000e: 4d 54 72 6b 00 00 0b c1 MTrk...Á # Track header, 3009 bytes to follow
0016: 00 90 40 7b ..@{ # Wait 0 ticks, play E4 (3), 97% volume
001a: 3c 3c 7b <<{ # Wait 60 ticks, play C4 (1), 97% volume
001d: 3c 41 7b <A{ # Wait 60 ticks, play F4 (4), 97% volume
0020: 3c 3c 7b <<{ # Wait 60 ticks, play C4 (1), 97% volume
0023: 3c 43 7b <C{ # Wait 60 ticks, play G4 (5), 97% volume
...
0bcf: 3c b0 7b 3c <°{< # Wait 60 ticks, all notes off
0bd3: 00 ff 2f 00 .ÿ/. # End of track marker
```
[Answer]
# Mathematica, ~~107~~ 87 bytes
*Thanks to Martin Ender for saving 20 bytes!*
```
"t.au"~Export~Sound[SoundNote[⌊12Mod[#,10,1]/7⌋-1,.5]&/@#&@@RealDigits[Pi,10,1000]]
```
`#&@@RealDigits[Pi,10,1000]` gives the list of the first 1000 digits of π. `SoundNote[⌊12Mod[#,10,1]/7⌋-1` produces the correct pitch number (where 0 is middle C by default) from a digit. Then `SoundNote[...,.5]&/@` turns that pitch name into a sound object of duration 1/2 second, which `Sound` gathers into an actual audio snippet. Finally `"t.au"~Export~` exports to a Unix Audio Format file, mostly because the extension is the shortest supported one, but also because we get to make the filename a [slap in the face to π](https://www.tauday.com/tau-manifesto)!
Previous submission:
```
"t.au"~Export~Sound[StringSplit["E5 C D E F G A B C5 D5"][[#+1]]~SoundNote~.5&/@#&@@RealDigits[Pi,10,1000]]
```
[Answer]
# [Scratch](https://scratch.mit.edu/), 530 bytes
*Inspired by [BookOwl's answer](https://codegolf.stackexchange.com/a/107609).*
[Online Demonstration](https://phosphorus.github.io/app.html?id=141539239&turbo=false&full-screen=false). Playback will begin immediately, press `space` to stop and reset. Click the cat to start again.
**Edit:** golfed down slightly. I found some golfing tips on the [official wiki](https://wiki.scratch.mit.edu/wiki/Block_Plugin/Syntax#Shortening_Source_Code).
```
when gf clicked
set[c v]to[4e3
repeat(c
add[2e3]to[f v
end
repeat(250
set[b v]to(c
set[h v]to((d)mod(1e4
change[c v]by(-16
repeat(b
set[d v]to(((d)*(b))+((1e4)*(item(b)of[f v
set[g v]to(((2)*(b))-(1
replace item(b)of[f v]with((d)mod(g
set[d v]to(((d)-((d)mod(g)))/(g
change[b v]by(-1
end
change[h v]by(((d)-((d)mod(1e4)))/(1e4
repeat(4
add((h)mod(10))to[a v
set[h v]to(((h)-((h)mod(10)))/(10
end
repeat(4
say(item(last v)of[a v
play note((round((((item(last v)of[a v])-(1))mod(10))*(1.78)))+(60))for(0.5)beats
delete(last v)of[a v
```
**Graphical:**

Uses the Rabinowitz Wagon spigot to produce 4 digits at a time.
[Answer]
# R, 450 bytes
```
N=261.63*(2^(1/12))^c(16,0,2,4,5,7,9,11,12,14);S=44100;s=unlist(sapply(el(strsplit(as(Rmpfr::Const("pi",1e5),"character"),""))[c(1,3:1001)],function(x)sin(0:(0.5*S-1)*pi*2*N[(x:1)[1]+1]/S)));c=32767*s/max(abs(s));a=file("p.wav","wb");v=writeChar;w=function(x,z)writeBin(as.integer(x),a,z,e="little");v("RIFF",a,4,NULL);w(36+S*10,4);v("WAVEfmt ",a,8,NULL);w(16,4);w(c(1,1),2);w(S*1:2,4);w(c(2,16),2);v("data",a,4,NULL);w(2*length(s),4);w(c,2);close(a)
```
Uses package `Rmpfr` to get the correct precision on pi digits. Outputs a `.wav` file.
Indented, with new lines and comments:
```
N=261.63*(2^(1/12))^c(16,0,2,4,5,7,9,11,12,14) # Frequency of each notes
S=44100 #Sampling rate
s=unlist(sapply(el(strsplit(
as(Rmpfr::Const("pi",1e5),"character"), #get pi correct digits as a character string
""))[c(1,3:1001)], #Grabs first 1000 digits
function(x)sin(0:(0.5*S-1)*pi*2*N[(x:1)[1]+1]/S))) #Wave function
c=32767*s/max(abs(s)) #Normalize to range [-32767;32767] as per wav 16-bit standard
a=file("p.wav","wb")
v=writeChar
w=function(x,z)writeBin(as.integer(x),a,z,e="little")
v("RIFF",a,4,NULL) #ChunkID
w(36+S*10,4) #Chunksize
v("WAVEfmt ",a,8,NULL) #Format, followed by SubChunk1ID
w(16,4) #SubChunk1Size
w(c(1,1),2) #AudioFormat & NumChannels
w(S*1:2,4) #SampleRate & ByteRate
w(c(2,16),2) #BlockAlign & BitsPerSample
v("data",a,4,NULL) #SubChunk2ID
w(2*length(s),4) #Subchunk2Size
w(c,2) #Actual data
close(a)
```
[Answer]
## C (gcc) 572 bytes
```
p(float f){i;char b[10000];p=3.14;for(i= 0;i<5000;i++){b[i]=35*sin(f*(2*p*i)/10000);putchar(b[i]);}} f(){i;FILE *f;char p[1001];float n[10];n[0]= 261.63;for(i=1;i<=6;i++){if(i==3)n[i]=349.23;else n[i]=1.12231*n[i-1];}for(i=7;i<=9;i++)n[i]=2*n[i-7];f=popen("pi 1000","r");fgets(p,sizeof(p)-1,f);for(i=0;i<999;i++){switch(p[i]){case'1':p(n[0]);break;case'2':p(n[1]);break;case'3':p(n[2]);break;case'4':p(n[3]);break;case'5':p(n[4]);break;case'6':p(n[5]);break;case'7':p(n[6]);break;case'8':p(n[7]);break;case'9':p(n[8]);break;case'0':p(n[9]);break;default:p(n[0]);break;}}}
```
Ungolfed version:
```
void play(float freq)
{
char buffer[10000];
float pi=3.14;
for(int i = 0; i<5000; i++)
{
buffer[i] = 35*sin(freq*(2*pi*i)/10000 );
putchar(buffer[i]);
}
}
void f()
{
FILE *fp;
char pi[1001];
float note[10];
note[0]= 261.63;
for(int i=1;i<=6;i++)
{
if(i==3)
note[i]=349.23;
else
note[i]=1.12231*note[i-1];
}
for(int i=7;i<=9;i++)
note[i]=2*note[i-7];
fp=popen("pi 1000","r" );
fgets(pi, sizeof(pi)-1, fp);
for(int i=0;i<1001;i++)
{
switch(pi[i])
{
case '1': play(note[0]);break;
case '2': play(note[1]);break;
case '3': play(note[2]);break;
case '4': play(note[3]);break;
case '5': play(note[4]);break;
case '6': play(note[5]);break;
case '7': play(note[6]);break;
case '8': play(note[7]);break;
case '9': play(note[8]);break;
case '0': play(note[9]);break;
default : play(note[0]);break;
}
}
}
```
Explanation:
* `play(float freq)` routine takes in the frequency as a parameter of the note (hardcoded) you want to play and stores a sine wave in a buffer.
* In the function `f()`, i stored the frequencies corresponding to notes ranging from C4 to E5 in a `notes` array.
* Store the `pi` value followed by 1000 digits in a buffer.In order to do this, I installed the `pi` package on my machine, and used `popen` to read the output of `pi 1000` and store it in a `char` buffer.
* Using a `for` loop and `switch` I called the `play()` function to produce notes that correspond to every single digit in the `pi` buffer. ,
Usage: `./binary_name.o | aplay` on modern Linux distributions, on older distributions you would redirect it to `/dev/audio`
] |
[Question]
[
Write program, which verifies [Erdős–Straus conjecture](http://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93Straus_conjecture).
Program should take as input one integer`n` (`3 <= n <= 1 000 000`) and print triple of integers satisfying identity `4/n = 1/x + 1/y + 1/z`, `0 < x < y < z`.
Shortest code wins.
**Some examples:**
```
3 => {1, 4, 12}
4 => {2, 3, 6}
5 => {2, 4, 20}
1009 => {253, 85096, 1974822872}
999983 => {249996, 249991750069, 62495875102311369754692}
1000000 => {500000, 750000, 1500000}
```
Note that your program may print other results for these numbers because there are multiple solutions.
[Answer]
### Ruby, 119 106 characters
```
f=->s,c,a{m=s.to_i;c<2?m<s||(p a+[m];exit):(1+m...c*s).map{|k|f[s/(1-s/k),c-1,a+[k]]}}
f[gets.to_r/4,3,[]]
```
The code uses minimal bounds for each variable, e.g. `n/4<x<3n/4`, similarly for `y`. Even the last example returns instantaneous (try [here](http://ideone.com/JabsGX)).
Examples:
```
> 12
[4, 13, 156]
> 123
[31, 3814, 14542782]
> 1234
[309, 190654, 36348757062]
> 40881241801
[10220310451, 139272994276206121600, 22828913614743204775214996005450198400]
```
[Answer]
# Mathematica 62
This plain-vanilla solution works fine--most of the time.
```
f@n_ := FindInstance[4/n == 1/x + 1/y + 1/z && 0 < x < y < z, {x, y, z}, Integers]
```
**Examples and Timings (in secs)**
```
AbsoluteTiming[f[63]]
AbsoluteTiming[f[123]]
AbsoluteTiming[f[1003]]
AbsoluteTiming[f[3003]]
AbsoluteTiming[f[999999]]
AbsoluteTiming[f[1000000]]
```
>
> {0.313671, {{x -> 16, y -> 1009, z -> 1017072}}}
>
> {0.213965, {{x -> 31, y -> 3814, z -> 14542782}}}
>
> {0.212016, {{x -> 251, y -> 251754, z -> 63379824762}}}
>
> {0.431834, {{x -> 751, y -> 2255254, z -> 5086168349262}}}
>
> {1.500332, {{x -> 250000, y -> 249999750052, z -> 1201920673328124750000}}}
>
> {1.126821, {{x -> 375000, y -> 1125000, z -> 2250000}}}
>
>
>
---
But it does not constitute a complete solution. There are a some numbers that it cannot solve for. For example,
```
AbsoluteTiming[f[30037]]
AbsoluteTiming[f[130037]]
```
>
> {2.066699, FindInstance[4/30037 == 1/x + 1/y + 1/z && 0 < x < y < z, {x, y, z}, Integers]}
>
> {1.981802,
> FindInstance[4/130037 == 1/x + 1/y + 1/z && 0 < x < y < z, {x, y, z},
> Integers]}
>
>
>
[Answer]
# C#
*Disclamer: this is not a serious answer*
This just bruteforces all the possibilities from 1 to 1<<30. It's huge, it's slow, I don't even know if it works correctly, but it follows the specifications quite literally, as it checks the condition every single time, so that's nice.
I haven't tested this because ideone has a 5 second time limit for programs and therefore this won't finish executing.
*(In case anyone was wondering: this is a whopping **308 bytes** long)*
```
static double[]f(double n)
{
for(double x=1;x<1<<30;x++)
{
for(double y=1;y<1<<30;y++)
{
for(double z=1;z<1<<30;z++)
{
if(4/n==1/x+1/y+1/z)
return new[]{x,y,z};
}
}
}
return null;
}
```
*Update: fixed it so it actually works*
[Answer]
# [Python 2](https://docs.python.org/2/), 171 bytes
```
from sympy import*
def f(n):
for d in xrange(1,n*n):
for p in divisors(4*d+n*n):
q=(4*d+n*n)/p;x=(n+p)/4;y=(n+q)/4
if (n+p)%4+(n+q)%4+n*x*y%d<1:return x,y,n*x*y/d
```
[Try it online!](https://tio.run/##PY9LDoMwDET3nMIbJAiWgEI/QDlJ1UWlkDYLnBDSipyeJpFabzyeZ2ls7exL0WHfhVEzrG7WDuSslbEs4ZMAkVHeJyCUAQ6SYDMPek5ZjcQiiEQHwuVHrsqsWct48aOwjP@51MM2ZlTovGwHF9TiVViSAqKftkV0fSe2MZfya92byb6ND0aH0Sz5HjIpZN4abPGIdVV12Pm6NEGHwvOpqw/dPR4B2kiyQBjf2b8 "Python 2 – Try It Online")
The first answer fast enough to be exhaustively tested. This is able to find solutions for all 3 ≤ *n* ≤ 1000000 in about 24 minutes *total*, for an average of about 1.4 milliseconds each.
### How it works
Rewrite 4/*n* = 1/*x* + 1/*y* + 1/*z* as *z* = *n*·*x*·*y*/*d*, where *d* = 4·*x*·*y* − *n*·*x* − *n*·*y*. Then we can factor 4·*d* + *n*2 = (4·*x* − *n*)·(4·*y* − *n*), which gives us a much faster way to search for *x* and *y* as long as *d* is small. Given *x* < *y* < *z*, we can at least prove *d* < 3·*n*2/4 (hence the bound on the outer loop), although in practice it tends to be much smaller—95% of the time, we can use *d* = 1, 2, or 3. The worst case is *n* = 769129, for which the smallest *d* is 1754 (this case takes about 1 second).
[Answer]
## Mathematica, 99 bytes
```
f[n_]:=(x=1;(w=While)[1>0,y=1;w[y<=x,z=1;w[z<=y,If[4/n==1/x+1/y+1/z,Return@{x,y,z}];++z];++y];++x])
```
It's fairly naive brute force, so it doesn't really scale well. I'm definitely going to get to a million (so feel free to consider this invalid for the time being). `n = 100` takes half a second, but `n = 300` already takes 12 seconds.
[Answer]
# [Golflua](http://mniip.com/misc/conv/golflua/) 75
Reads `n` from prompt (after invocation in terminal), but basically iterates as [Calvin's Hobbies](https://codegolf.stackexchange.com/a/34860/11376) solution does:
```
n=I.r()z=1@1~@y=1,z-1~@x=1,y-1?4*x*y*z==n*(y*z+x*z+x*y)w(n,x,y,z)~$$$z=z+1$
```
An ungolfed Lua version of the above is
```
n=io.read()
z=1
while 1 do
for y=1,z-1 do
for x=1,y-1 do
if 4*x*y*z==n*(y*z+x*z+x*y) then
print(n,x,y,z)
return
end
end
end
z=z+1
end
```
Examples:
```
n=6 --> 3 4 12
n=12 --> 6 10 15
n=100 --> 60 75 100
n=1600 --> 1176 1200 1225
```
[Answer]
# Python, 117
```
n=input();r=range;z=0
while 1:
z+=1
for y in r(z):
for x in r(y):
if 4*x*y*z==n*(y*z+x*z+x*y):print x,y,z;exit()
```
Example:
```
16 --> 10 12 15
```
Nothing too special.
[Answer]
# C# - 134
Well, I posted an answer here before, but it wasn't really that serious. As it so happens, I'm very often very bored, so I golfed it a little bit.
It calculates all the examples *technically* correctly (I haven't tried the last two because, again, ideone inforces a 5 second time limit) but the first ones yield the correct result (not necessarily the result you calculated, but a correct one). It strangely outputs the number out of order (I have no clue why) and it gives `10, 5, 2` for `5` (which is a valid answer according to wikipedia).
134 bytes for now, I could probably golf it up a bit more.
```
float[]f(float n){float x=1,y,z;for(;x<1<<30;x++)for(y=1;y<x;y++)for(z=1;z<y;z++)if(4/n==1/x+1/y+1/z)return new[]{x,y,z};return null;}
```
[Answer]
### Haskell - 150 characters
`main = getLine >>= \n -> (return $ head $ [(x,y,z) | x <- [1..y], y <- [1..z], z <- [1..], (4/n') == (1/x) + (1/y) + (1/z)])
where n' = read n`
This ought to work, but I've not compiled it yet. It's almost certainly very very slow. It checks every possible triplet of valid integers, and should stop when it sees a set that works.
] |
[Question]
[
The task is simple: write a program that branches differently in x86 (32-bit) and x86-64 (64-bit) using only printable visible ASCII characters 0x21...0x7e (space and del are not allowed) in the machine code.
* Conditional assembly is not allowed.
* Using API calls in not allowed.
* Using kernel-mode (ring 0) code is not allowed.
* The code must run without causing exceptions in both IA-32 and x86-64 in Linux or in some other protected mode OS.
* The functioning must not depend on command line parameters.
* All instructions must be encoded in machine code using only ASCII characters in the range 0x21...0x7e (33...126 decimal). So eg. `cpuid` is out of limits (it's `0f a2`), unless you use self-modifying code.
* The same binary code must run in x86 and x86-64, but as file headers (ELF/ELF64/etc.) may be different, you may need to assemble and link it again. However, the binary code must not change.
* Solutions should work on all processors between i386...Core i7, but I'm interested also in more limited solutions.
* The code must branch in 32-bit x86 but not in x86-64, or vice versa, but using conditional jumps is not a requirement (indirect jump or call is also accepted). The branch target address must be such that there is space for some code, at least 2 bytes of space in which a short jump (`jmp rel8`) fits in.
The winning answer is the one that uses least bytes in the machine code. The bytes in the file header (ELF/ELF64 for example) are not counted, and any bytes of code after the branch (for testing purposes etc.) aren't counted neither.
Please present your answer as ASCII, as hexadecimal bytes and as commented code.
My solution, 39 bytes:
ASCII: `fhotfhatfhitfhutfhotfhatfhitfhut_H3<$t!`
hexadecimal: `66 68 6F 74 66 68 61 74 66 68 69 74 66 68 75 74 66 68 6F 74 66 68 61 74 66 68 69 74 66 68 75 74 5F 48 33 3C 24 74 21`.
Code:
```
; can be compiled eg. with yasm.
; yasm & ld:
; yasm -f elf64 -m amd64 -g dwarf2 x86_x86_64_branch.asm -o x86_x86_64_branch.o; ld x86_x86_64_branch.o -o x86_x86_64_branch
; yasm & gcc:
; yasm -f elf64 -m amd64 -g dwarf2 x86_x86_64_branch.asm -o x86_x86_64_branch.o; gcc -o x86_x86_64_branch x86_x86_64_branch.o
section .text
global main
extern printf
main:
push word 0x746f ; 66 68 6f 74 (x86, x86-64)
push word 0x7461 ; 66 68 61 74 (x86, x86-64)
push word 0x7469 ; 66 68 69 74 (x86, x86-64)
push word 0x7475 ; 66 68 75 74 (x86, x86-64)
push word 0x746f ; 66 68 6f 74 (x86, x86-64)
push word 0x7461 ; 66 68 61 74 (x86, x86-64)
push word 0x7469 ; 66 68 69 74 (x86, x86-64)
push word 0x7475 ; 66 68 75 74 (x86, x86-64)
db 0x5f ; x86: pop edi
; x86-64: pop rdi
db 0x48, 0x33, 0x3c, 0x24
; x86:
; 48 dec eax
; 33 3c 24 xor edi,[esp]
; x86-64:
; 48 33 3c 24 xor rdi,[rsp]
jz @bits_64 ; 0x74 0x21
; branch only if running in 64-bit mode.
; the code golf part ends here, 39 bytes so far.
; the rest is for testing only, and does not affect the answer.
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
jmp @bits_32
@bits_64:
db 0x55 ; push rbp
db 0x48, 0x89, 0xe5 ; mov rbp,rsp
db 0x48, 0x8d, 0x3c, 0x25 ; lea rdi,
dd printf_msg ; [printf_msg]
xor eax,eax
mov esi,64
call printf
db 0x5d ; pop rbp
NR_exit equ 60
xor edi,edi
mov eax,NR_exit ; number of syscall (60)
syscall
@bits_32:
lea edi,[printf_msg]
mov esi,32
call printf
mov eax,NR_exit
int 0x80
section .data
printf_msg: db "running in %d-bit system", 0x0a, 0
```
[Answer]
# 7 bytes
```
0000000: 6641 2521 2173 21 fA%!!s!
```
As 32 bit
```
00000000 6641 inc cx
00000002 2521217321 and eax,0x21732121
```
As 64 bit
```
00000000 6641252121 and ax,0x2121
00000005 7321 jnc 0x28
```
`and` clears the carry flag so the 64 bit version always jumps. For 64-bit the `6641` is the operand size override followed by `rex.b` so the operand size for the `and` comes out as 16 bit. On 32-bit the `6641` is a complete instruction so the `and` has no prefix and has a 32-bit operand size. This changes the number of immediate bytes consumed by the `and` giving two bytes of instructions that are only executed in 64-bit mode.
[Answer]
## 11 bytes
```
ascii: j6Xj3AX,3t!
hex: 6a 36 58 6a 33 41 58 2c 33 74 21
```
Uses the fact that in 32-bit, 0x41 is just `inc %ecx`, whereas in 64-bit it is the `rax` prefix that modifies the target register of the following `pop` instruction.
```
.globl _check64
_check64:
.byte 0x6a, 0x36 # push $0x36
.byte 0x58 # pop %rax
.byte 0x6a, 0x33 # push $0x33
# this is either "inc %ecx; pop %eax" in 32-bit, or "pop %r8" in 64-bit.
# so in 32-bit it sets eax to 0x33, in 64-bit it leaves rax unchanged at 0x36.
.byte 0x41 # 32: "inc %ecx", 64: "rax prefix"
.byte 0x58 # 32: "pop %eax", 64: "pop %r8"
.byte 0x2c, 0x33 # sub $0x33,%al
.byte 0x74, 0x21 # je (branches if 32 bit)
mov $1,%eax
ret
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
mov $0,%eax
ret
```
Wrote this on OSX, your assembler might be different.
Call it with this:
```
#include <stdio.h>
extern int check64(void);
int main(int argc, char *argv[]) {
if (check64()) {
printf("64-bit\n");
} else {
printf("32-bit\n");
}
return 0;
}
```
[Answer]
## 7 bytes
Not relying on 66 prefix.
```
$$@$Au!
```
32-bit:
```
00000000 24 24 and al,24h
00000002 40 inc eax
00000003 24 41 and al,41h
00000005 75 21 jne 00000028h
```
AL will have bit 0 set after the INC, the second AND will preserve it, the branch will be taken.
64-bit:
```
00000000 24 24 and al,24h
00000002 40 24 41 and al,41h
00000005 75 21 jne 00000028h
```
AL will have bit 0 clear after the first AND, the branch will not be taken.
[Answer]
If only C9h were printable...
32-bit:
```
00000000 33 C9 xor ecx, ecx
00000002 63 C9 arpl ecx, ecx
00000004 74 21 je 00000027h
```
The ARPL will clear the Z flag, causing the branch to be taken.
64-bit:
```
00000000 33 C9 xor ecx, ecx
00000002 63 C9 movsxd ecx, ecx
00000004 74 21 je 00000027h
```
The XOR will set the Z flag, the MOVSXD will not change it, the branch will not be taken.
] |
[Question]
[
As one of the less popular languages, it's difficult to find literature on the avant garde of postscript hackery. So what discoveries have the golfers here made to exploit the stack model (or other features) to overcome Postscript's inherent verbosity?
[Answer]
When generating graphical output and console output does not matter, use `=` instead of `pop`.
[Answer]
## Replace hexstrings with ASCII85
Probably old news, but I just learned it. :)
You can do it using the postscript interpreter interactively with an encoding filter and cut-and-paste. But I'm going to show how to use `dc` to do it "by hand".
So, here's a hex string. We split it into 4-byte chunks.
```
95 20 6e d8 d0 59 49 35 50 74 ba c5 08 2d
```
Firing up dc, we input these as 32-bit (unsigned) big-endian-byte-order numbers. Then *mod*-off base-85 digits (there should be 5 until you get to 0).
```
0> dc
16i
95206ED8
Ai
d85%n85/
82
d85%n85/
83
d85%n85/
82
d85%n85/
78
d85%n85/
47
d85%n85/
0
```
Padding the last chunk with `00 00`, yields (decimal), omitting the same number of bytes that we padded.
```
47 78 82 83 82 66 81 72 79 83 25 72 82 25 69 2 53 30 [2 53]
```
Add 33 to shift into the printable range of ASCII and poof! ASCII85.
>
> 80 111 115 116 115 99 114 105 112 116 58 105 115 58 102 35 86 63
>
> which decodes to:
> Postscript:is:f#V?
>
> %%%Oops! should say 'fun'! I screwed up somewhere. :)
>
>
>
Wrap it in `<~` ... `~>`, and Level-2 Postscript can access 8-bit data, cheaper than hex.
[Answer]
Here's a quickie: wrap multiple definitions in `[...>>begin` to eliminate the keyword `def` (nb. `[` is the same as `<<`).
```
def def
[>>begin
```
So remember: **more than ~~three~~ two ... *flock together*!** ;)
[Answer]
While most postscript operators are syntactically identifiers (and therefore must be space- (or otherwise-) delimited), the names `[`, `]`, `<<`, and `>>` are self-delimiting and scanner will detect them without intervening space. For the same reason, you cannot refer to these names with the usual `/literal` syntax (eg. `/[` is two tokens: an empty literal name equivalent to `()cvn cvlit`, and the executable name `[` equivalent to `([)cvn cvx exec`).
In order to redefine these names, which cannot be mentioned by name, we can use strings which are implicitly converted to names when used as keys in a dictionary (convenient!).
This example illustrates abusing these operators to perform arithmetic.
```
%!
([)0 def
(])1 def
(<<){add}def
(>>){mul}def
]]<<]]]<<<<>> =
%1 1 add 1 1 1 add add mul = %prints 6
```
Also `<<` and `[` (and `mark`) all mean the same thing.
---
My own postscript interpreter, [xpost](http://code.google.com/p/xpost/), also makes the right-curly brace available with some restrictions. [discussion](https://groups.google.com/d/topic/comp.lang.postscript/hV5Ie0jR45c/discussion)
[Answer]
## Embedded Decoder
A Postscript program has a unique(?) ability to read it's own program text as data. This is normally used by the `image` operator which receives a *data-acquisition-procedure* as input, and this procedure often uses `currentfile` followed by `readline`, `readstring`, or `readhexstring`. But seen another way, `image` is just another looping operator, so any loop can *read-ahead*. An example is the line-printer emulator from the Green Book.
Using the `token` operator invokes the scanner on a file or string, pulling off a number or space- (or otherwise-: see other answer) -delimited name.
A simple PS interpreter in PS:
```
{currentfile token not {exit} if dup type /arraytype ne {exec} if }loop
```
---
## Binary Operator String Decoder
Since I can't seem to get *raw* binary tokens to work for me (see other answer), I've made use of the "embedded decoding" idea to exploit the binary token mechanism to pack code into 8-bit strings, and then manipulate and parse the commands from the string *on the fly*.
```
/.{
<920> % two-byte binary-encoded name template with 0x92 prefix
dup 1 4 3 roll put % insert number into string
cvx exec % and execute it
}def
/${
//. %the /. procedure body defined above
73 . %"forall" (by code number)
}def
```
The `.` procedure takes a number from the stack and inserts it as the second byte in a two-byte string, the first byte being the prefix-byte for a binary token, specifying an executable system name. We save a byte in the hexstring by using a rule of the scanner that an odd number of nibbles in the hexstring is padded with an extra 0 nibble, so 3 hex nibbles produces a 2-byte string. The string is then marked *executable* and called with `exec` which invokes the scanner, produces the desired executable system name, and then loads the name and executes the operator. The `$` does this on each byte of a string on the stack, using the `.` procedure *twice*, once as the loop body, and then to execute the looping operator `forall` by number.
More compactly, these procedures look like this:
```
/.{<920>dup 1 4 3 roll put cvx exec}def/${//. 73 .}def
%123457890123456789012345678901234567890123456789012345
% 1 2 3 4 5
```
So, 55 chars buys binary token strings. Or, for 6 (maybe 7, if you terminate it with a space) chars, you can load the [G library](https://github.com/luser-dr00g/G) with `(G)run` which defines `.` and `$` as above (+ a few others to extend the range of ascii-reachable codes).
Further illustrated in my [crossword puzzle answer](https://codegolf.stackexchange.com/a/3877/2381).
[Answer]
# Factor-out repeated uses of long operator names
If you're already using a `<<>>begin` dictionary, there is a constant overhead of `/?{}` 4 characters per redefinition. So an operator of length *n* repeated *N* times will yield a character-count change of
(4 + *n*) - (*N* \* (*n* - 1)).
Setting this formula equal to 0 gives the equation of the *break-even* point. From this we can solve for each variable in terms of the other, yielding
*n* = - (*N* - 4) / (1 - *N*) and
*N* = (4 + *n*) / (*n* - 1) .
No we can answer questions like, "For how many uses of 'print' is it worthwhile to abbreviate?" *n* = 5, so *N* = 9/4. Take the ceiling, since you can't effectively call print 1/4 times. So, 3. 3 uses. And indeed,
```
print print print
/P{print}p p p
```
(assuming you've already paid the overhead of `<<>>begin` to activate the definition, of course).
Of course, binary tokens makes this kind of moot, giving you the first 255 names from the system name table as 2-bytes: 0x92, 0x??. And binary tokens are also self-delimiting, requiring no whitespace before or after, since the high-bit of the first byte is outside of the ascii range.
[Answer]
# Binary Tokens
For the ultimate *zip-up* of a PostScript program that final frontier is *binary tokens* which allows you to remove long operator names completely, at the cost of no longer having an ASCII-clean program.
So starting with a compacted block of postscript code
```
[/T[70{R 0 rlineto}48{}49{}43{A rotate}45{A neg rotate}91{currentdict
end[/.[currentpoint matrix currentmatrix]cvx>>begin begin}93{. setmatrix
moveto currentdict end end begin}>>/S{dup B eq{T begin exch{load exec}forall
end}{exch{load exch 1 add S}forall}ifelse 1 sub }>>begin moveto 0 S stroke
```
We look up all the names in the back of the [PLRM](http://partners.adobe.com/public/developer/en/ps/PLRM.pdf) (Appendix F, pp. 795-797)
```
appearance
in
vim dec meaning
<92> 146 'executable system name' binary token prefix
^A 1 add
^M 13 begin
^^ 30 currentdict
' 39 currentmatrix
( 40 currentpoint
2 50 cvx
8 56 dup
9 57 end
= 61 eq !)
> 62 exch
? 63 exec
I 73 forall
U 85 ifelse
d 100 load
h 104 matrix
k 107 moveto
n 110 neg
<85> 133 rlineto
<88> 136 rotate
§ 167 stroke
© 169 sub
```
And then type them in prefixed by a `146` (decimal) byte. [vim help for entering arbitrary bytes](http://vim.wikia.com/wiki/Entering_special_characters#By_character_value)
Then in vim, the condensed file can be typed directly, so:
>
> [/T[70{R 0`^V`146`^V`133}48{}49{}43{A`^V`146`^V`136}
> 45{A`^V`146`^V`110`^V`146`^V`136}
> 91{`^V`146`^V`30`^V`146`^V`57
> [/.[`^V`146`^V`40`^V`146`^V`104
> `^V`146`^V`39]`^V`146`^V`50>>
> `^V`146`^V`13`^V`146`^V`13}93{.
> `^V`146`^V`156
> `^V`146`^V`107`^V`146`^V`30
> `^V`146`^V`57`^V`146`^V`57
> `^V`146`^V`13}>>/S{`^V`146`^V`56
> B`^V`146`^V`61{T`^V`146`^V`13
> `^V`146`^V`62{`^V`146`^V`100
> `^V`146`^V`63}`^V`146`^V`73
> `^V`146`^V`57}{`^V`146`^V`62{
> `^V`146`^V`100`^V`146`^V`62
>
>
>
... you have to enter a space here to terminate the `^V`-62 and start the 1, but you can back up and delete it later ...
>
> 1`^V`146`^V`1S}`^V`146`^V`73}
> `^V`146`^V`85
>
>
>
... have to enter a space here to terminate the `^V`-85 and start the 1, but you can back up and delete it later ...
>
> 1`^V`146`^V`169}>>`^V`146`^V`13
> `^V`146`^V`107
>
>
>
... 3rd digit of 3-digit code terminates the byte-entry so the following `0` here is normal, conveniently ...
>
> 0 S`^V`146`^V`167
>
>
>
Which will look like this on screen (in vim):
```
[/T[70{R 0<92><85>}48{}49{}43{A<92><88>}45{A<92>n<92><88>}
91{<92>^^<92>9[/.[<92>(<92>h<92>']<92>2>>
<92>^M<92>^M}93{.<92><9c><92>k<92>^^<92>9<92>9<92>^M}
>>/S{<92>8B<92>={T<92>^M<92>>{<92>d<92>?}<92>I<92>9}{<92>>
{<92>d<92>>1<92>^AS}<92>I}<92>U1<92>©}>><92>^M
<92>k0 S<92>§
```
This one can often be omitted entirely if the aim is just to show a picture. Ghostscript paints most things to the screen without needing `showpage`.
```
¡ 161 showpage
```
[*This actually isn't working. Ghostscript's giving me `undefined` and `syntaxerror` for these tokens. Maybe there's some **mode** I need to enable.*]
[Answer]
# Change negative rolls to positive
Negative rolls can [always be changed to positive rolls](https://stackoverflow.com/questions/15997536/how-do-you-keep-the-roll-operator-straight/).
```
3 -1 roll
3 2 roll
5 -2 roll
5 3 roll
```
[Answer]
## Use my G library
<https://github.com/luser-dr00g/G>
It's a text file. No extension, for the shortest possible syntax to load it.
It permits this [203-char Sierpinksi Triangle program](https://codegolf.stackexchange.com/a/6604/2381)
```
[48(0-1+0+1-0)49(11)43(+)45(-)/s{dup
0 eq{exch{[48{1 0 rlineto}49 1 index
43{240 rotate}45{120 rotate}>>exch
get exec}forall}{exch{load
exch 1 sub s}forall}ifelse 1 add}>>begin
9 9 moveto(0-1-1)9 s fill
```
to be rewritten in 151 bytes as
```
3(G)run $
{A - B + A + B - A}
{B B}
{A - B - B}7{[ex{du w{(>K?\2u)$}if}fora]}rep
cvx[/A{3 0 rl}/B 1 in/-{120 rot}/+{-120 rot}>>b
100 200(k?B9)$ showp
```
[workfile with comments](https://github.com/luser-dr00g/G/blob/master/siertriG.ps)
Using the abbreviated system names feature, `1(G)run` completely removes the burden of long operator names. An operator name need only be long enough to distinguish it from the others.
So
* `add` becomes `ad`
* `mul` becomes `mu`
* `index` becomes `i`
* *etc, etc.*
Use the [PLRM](http://partners.adobe.com/public/developer/en/ps/PLRM.pdf) Appendix F for the standard table of operator names.
And the feature of Operator Strings is available even if the abbreviated names is not selected. The bare library has a "base-level" selected by adding simply `(G)run` with no further decorations.
The base level includes a new function `.` which accepts the integer code for an operator (the same Appendix F mentioned above) and executes it.
The new function `$` iterates through a string and calls `.` upon each one. So the ascii code directly selects the operator by number.
A new function `@` lets you reach down to the bottom of the table in Appendix F by treating the space character (Ascii 0x20) as 0.
A new function `#` lets you reach further up into the table by first adding 95 (0x5F) so the space char 0x20 is treated as 127 (0x7F), the very next code after the last printable ascii character `~` 126 (0x7E).
Two new functions `!` lets you access a deeply nested structure of arrays and/or dicts with an *index array* of indices/keys, rather than tedious expressions of many `get` (and `put`) operators.
`(G)run` 7 chars buys the base-level.
`1(G)run` 8 chars buys that AND abbreviated system names.
`3(G)run $` 9 chars immediately begins an *implicit-procedure block* scanning sources lines until the next blank line, and defining the first line as a procedure called `A`, the next line is defined as a procedure called `B`, etc. This should remove most of the `def`s needed for defining lots of stuff, without needing to wrap them in a dictionary, nor even explicitly giving them names.
[Answer]
# Error handling with `stopped`
For example, suppose `f` takes an argument from the stack and you want to apply `f` until the stack is empty.
`{f}loop`
will give a stack underflow when the stack becomes empty. So you could use
`{count 0 gt{f}if}loop`
but a shorter solution is:
`{{f}loop}stopped`
(Note that this leaves `true` on the stack.)
[Answer]
# Hex colors in a string
`(AZm){255 div}forall setrgbcolor` selects the HTML color `#415a6b`, because `A` is hex `41`, etc, so `(AZm)` is the same as `<415a6b>`.
So if you have a bunch of different colors to use, you can put them on the stack ready to apply `setrgbcolor` for only 3 extra bytes per color. For example, this puts 5 colors `#616263`, `#646566`, ..., `#6d6e6f` (as 15 numbers between 0 and 1) on the stack:
`(abcdefghijklmno){255 div}forall`
In general you might have to use unprintable characters in the string.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/7346/edit).
Closed 7 years ago.
[Improve this question](/posts/7346/edit)
## Challenge
Create a GUI Keyboard with as few characters as possible.
## Example
Because this was an assignment in one of my courses, I can't show the source code. However, here is a screen shot of my keyboard.

In this example, my keys were of type `JButton` and I used a Midi Synthesizer to produce the sound (with the default ADSR envelope values).
## Rules
* You **are allowed** to use standard external libraries.
* Be creative with your sound. You can use 8-bit, a sitar, etc.
* For simplicities sake, you may have five keys; black and white, from C to E (the first five keys on my keyboard).
* Most importantly... showcase your work!
**NOTICE**: Depending on what language you choose to work with, this may be a rather large task.
This is my first question on SE Code Golf. If anything is unclear, please ask for further details.
---
**EDIT**: The due date for this challenge will be 9/22/12. If you post an answer after this date, I will look over it regardless (and possibly +1 it).
[Answer]
# Mathematica 319 259 255
---
Edit:
Keys now depress (as buttons) when clicked.
---
[Answer]
## Web page (840/796 characters)
>>> **[Start playing](http://jsbin.com/iponek/4)** (Internet Explorer is not supported for multiple reasons; Google Chrome and Opera work best.)
I probably could make this a bit shorter, yet it is a good start. The lower score is after replacing all occurrences of ` ` with the character itself and removing the keyword `new`, the latter change breaking Google Chrome compatibility.
```
<style>table{border-collapse:collapse;border-width:1 0;border-style:solid;font-size:64;line-height:2}td{border-style:solid;border-width:0 1}</style><table><td colspan=3 title=0> <td bgcolor=black colspan=2 title=1> <td colspan=2 title=2> <td bgcolor=black colspan=2 title=3> <td colspan=3 title=4> <tr><td colspan=4 title=0> <td colspan=4 title=2> <td colspan=4 title=4> </table><script>for(A=[y=5];y--;){for(s=x=64e3;x--;)s+="~ "[x*(268+17*y)>>13&1];A[y]=new Audio("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA"+btoa(s))}setInterval("for(y=5;y--;)with(A[y])volume=volume&&Math.exp(-currentTime)",99);onmousedown=function(e){if(z=e.target.title)with(A[z])play(currentTime=0,volume=1)};onmouseup=function(e){if(z=e.target.title)with(A[z])pause(volume=0)}</script>
```
Save this code as a text file with a name ending in .htm or .html and open it in Chrome or Opera (Safari might also work), or just open the solution's [JSBin page](http://jsbin.com/iponek/4) to start playing. I reused the WAV file header from my solution to the [Twinkle Twinkle Little Star](https://codegolf.stackexchange.com/questions/272/twinkle-twinkle-little-star) code golf problem.
An important feature is that the sound diminishes as time passes. To observe this behavior, try holding down a key for a few seconds and listening to what happens.
Here is a more readable version of the code:
```
<style>
table {
border-collapse: collapse;
border-width: 1 0;
border-style: solid;
font-size: 64;
line-height: 2;
}
td {
border-style: solid;
border-width: 0 1;
}
</style>
<table>
<td colspan=3 title=0>
<td bgcolor=black colspan=2 title=1>
<td colspan=2 title=2>
<td bgcolor=black colspan=2 title=3>
<td colspan=3 title=4>
<tr>
<td colspan=4 title=0>
<td colspan=4 title=2>
<td colspan=4 title=4>
</table>
<script>
for (A = [y = 5]; y--;) {
for (s = x = 64e3; x--;)
s += "~ "[x * (268 + 17 * y) >> 13 & 1];
A[y] = new Audio("data:audio/wav;base64,UklGRiXuAgBXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQHuAgCA" + btoa(s));
}
setInterval(function() {
for (y = 5; y--;)
with (A[y])
volume = volume && Math.exp(-currentTime);
}, 99);
onmousedown = function(e) {
if (z = e.target.title)
with (A[z])
play(currentTime = 0, volume = 1);
};
onmouseup = function(e) {
if (z = e.target.title)
with (A[z])
pause(volume = 0);
};
</script>
```
[Answer]
## Groovy: 577 (703 with whitespaces)
The first 5 notes. Others could be added easily, it's somewhat dynamic.
Damn swing. Probably with a swing lib it would be better.

Plays through JFugue.
On github: <https://github.com/wpiasecki/glissando/blob/master/src/br/glissando/Piano.groovy>
On groovy 2.0.2
```
import java.awt.event.*
class Note { def n; boolean s; def p() { new org.jfugue.Player().with {play n;close()}} }
notes=['C','C#','D','D#','E'].inject([]){ l,n -> l<< Note[n:n,s:n=~/#/]}
h=300
l=0
w=60
x=0
new groovy.swing.SwingBuilder().edt {
frame size:[notes.size()*30+30,h],
show:true,
defaultCloseOperation:javax.swing.JFrame.EXIT_ON_CLOSE,
{ l = layeredPane() }
notes.each { n ->
C=java.awt.Color
s=n.s
p=panel bounds:(s ? [x-15,0,w-30,h-100] : [x,0,w,h]),
background: s ? C.BLACK : C.WHITE,
border: lineBorder(1, color: C.BLACK)
p.addMouseListener({ if(it.id==MouseEvent.MOUSE_CLICKED)n.p() }as MouseListener)
if(!s)x+=w
l.add p,s?0:1
}
}
```
[Answer]
## R - 491 characters
I'm a little late but I just saw this post yesterday.
Works on a Mac, uses [playRWave](http://www.informatics.indiana.edu/donbyrd/teach/RTools+Docs/tuneRPlaybackOnMacsNEW.html) and packages `tuneR` and `splancs`.
```
a=array
x=c(7,2)
y=c(5,2)
z=c(1,1,3,3)
par(mar=rep(0,4))
plot(NA,xli=c(0,9),yli=c(0,3))
N=list(a(c(0,3,3,2,2,0,0,0,0,z,0),x),a(c(3,6,6,5,5,4,4,3,3,0,0,z,1,1,0),c(9,2)),a(c(6,6,7,7,9,9,6,0,z,0,0),x),a(c(2,4,4,2,2,z,1),y),a(c(5,7,7,5,5,z,1),y))
c=c(NA,NA,NA,1,1)
for(i in 1:5){polygon(N[[i]],c=c[i])}
h=c(261.63,293.66,329.63,277.18,311.13)
library(tuneR)
setWavPlayer("~/Library/Audio/playRwave")
repeat{P=data.frame(locator(1));play(sine(h[sapply(N,function(x)splancs::inout(P,x))],bit=16))}
```

Ungolfed:
```
par(mar=rep(0,4))
plot(NA,xlim=c(0,9),ylim=c(0,3)) #Create empty plot: due to fuzzy matching of arguments, xlim can be reduced to xli
N=list(array(c(0,3,3,2,2,0,0,0,0,1,1,3,3,0),dim=c(7,2)), #C polygon
array(c(3,6,6,5,5,4,4,3,3,0,0,1,1,3,3,1,1,0),dim=c(9,2)), #D polygon
array(c(6,6,7,7,9,9,6,0,1,1,3,3,0,0),dim=c(7,2)), #E polygon
array(c(2,4,4,2,2,1,1,3,3,1),dim=(5,2)), #Db polygon
array(c(5,7,7,5,5,1,1,3,3,1),dim=(5,2))) #Eb polygon
c=c(NA,NA,NA,1,1) #Colors: by default 1 is "black"
for(i in 1:5){polygon(N[[i]],color=c[i])}
h=c(261.63,293.66,329.63,277.18,311.13) #Notes frequency in hertz: C4, D4, E4, Db4 and Eb4
library(tuneR)
setWavPlayer("~/Library/Audio/playRwave") #This can be change to other wav player I think
repeat{
P=data.frame(locator(1)) #Grab coordinates of selected point
H=h[sapply(N,function(x)splancs::inout(P,x))] #In which polygon does the selected point belong to, then map it to its ferquency
s=sine(H,bit=16) #By default create a 1sec note at the given frequency with 44100 sampling rate
play(s)
}
```
] |
[Question]
[
After having implemented [QuickSort in BrainF\*\*\*](https://codegolf.stackexchange.com/questions/2445/implement-quicksort-in-brainf), I realized it probably wasn't that quick. Operations that are O(1) in normal languages (like array indexing) are significantly longer in BF. Most of the rules for what makes an efficient sort can be thrown out the window when you are coding in a [Turing tarpit.](http://en.wikipedia.org/wiki/Turing_tarpit)
So here is a challenge to implement the "Fastest BrainF\*\*\* Sort Routine Ever". I will time all entries using the interpreter below. The intepreter uses a 16K tape of unsigned characters. Both the tape and the cells wrap when advanced/incremented past the limits. Reading the EOF puts a 0 in the current cell. The measured time includes both the time to parse the source file and the time to process all input files. Fastest code wins.
The test vector will be a set of Ascii files designed to test sorting edge cases, including
* An already sorted list: "ordered"
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
* A reverse sorted list: "reverse"
```
~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!
```
* A file consisting of many copies of a few unique values: "onlynine"
```
ibbkninbkrauickabcufrfckbfikfbbakninfaafafbikuccbariauaibiraacbfkfnbbibknkbfankbbunfruarrnrrrbrniaanfbruiicbuiniakuuiubbknanncbuanbcbcfifuiffbcbckikkfcufkkbbakankffikkkbnfnbncbacbfnaauurfrncuckkrfnufkribnfbcfbkbcrkriukncfrcnuirccbbcuaaifiannarcrnfrbarbiuk
```
* A completely random ascii file: "random"
```
'fQ`0R0gssT)70O>tP[2{9' 0.HMyTjW7-!SyJQ3]gsccR'UDrnOEK~ca 'KnqrgA3i4dRR8g.'JbjR;D67sVOPllHe,&VG"HDY_'Wi"ra?n.5nWrQ6Mac;&}~T_AepeUk{:Fwl%0`FI8#h]J/Cty-;qluRwk|S U$^|mI|D0\^- csLp~`VM;cPgIT\m\(jOdRQu#a,aGI?TeyY^*"][E-/S"KdWEQ,P<)$:e[_.`V0:fpI zL"GMhao$C4?*x
```
* A random file over the range 1..255: "wholerange"
```
öè—@œ™S±ü¼ÓuǯŠf΀n‚ZÊ,ˆÖÄCítÚDý^öhfF†¬I÷xxÖ÷GààuÈ©ÈÑdàu.y×€ôã…ìcÑ–:*‰˜IP¥©9Ä¢¬]Š\3*\®ªZP!YFõ®ÊÖžáîÓ¹PŸ—wNì/S=Ìœ'g°Ì²¬½ÕQ¹ÀpbWÓ³
»y »ïløó„9k–ƒ~ÕfnšÂt|Srvì^%ÛÀâû¯WWDs‰sç2e£+PÆ@½ã”^$f˜¦Kí•òâ¨÷ žøÇÖ¼$NƒRMÉE‹G´QO¨©l¬k¦Ó
```
Each input file has at most 255 bytes.
Here is the interpreter. It's written for console-mode Windows, but should be easy to port: just replace `read_time()` and `sysTime_to_ms()` with platform-specific equivalents.
Usage: `bftime program.bf infile1 [infile2 ...]`
```
#include <windows.h>
#include <stdio.h>
#define MS_PER_SEC 1000.0f
#define MAXSIZE (0x4000)
#define MAXMASK (MAXSIZE-1)
typedef __int64 sysTime_t;
typedef unsigned char Uint8;
typedef unsigned short Uint16;
typedef struct instruction_t {
Uint8 inst;
Uint16 pair;
} Instruction;
Instruction prog[MAXSIZE] = {0};
Uint8 data[MAXSIZE] = {0};
const Uint8 FEND = EOF;
sysTime_t read_time() {
__int64 counts;
QueryPerformanceCounter((LARGE_INTEGER*)&counts);
return counts;
}
float sysTime_to_ms(sysTime_t timeIn) {
__int64 countsPerSec;
QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
return (float)timeIn * MS_PER_SEC / (float)countsPerSec;
}
int main(int argc, char* argv[])
{
FILE* fp;
Uint8 c;
Uint16 i = 0;
Uint16 stack = 0;
sysTime_t start_time;
sysTime_t elapsed=0,delta;
if (argc<3) exit(printf("Error: Not Enough Arguments\n"));
fp = fopen(argv[1],"r");
if (!fp) exit(printf("Error: Can't Open program File %s\n",argv[1]));
start_time=read_time();
while (FEND != (c = fgetc(fp)) && i <MAXSIZE) {
switch (c) {
case '+': case '-': case ',': case '.': case '>': case '<':
prog[++i].inst = c;
break;
case '[':
prog[++i].inst = c;
prog[i].pair=stack;
stack = i;
break;
case ']':
if (!stack) exit(printf("Unbalanced ']' at %d\n",i));
prog[++i].inst = c;
prog[i].pair=stack;
stack = prog[stack].pair;
prog[prog[i].pair].pair=i;
break;
}
}
if (stack) exit(printf("Unbalanced '[' at %d\n",stack));
elapsed = delta = read_time()-start_time;
printf("Parse Time: %f ms\n", sysTime_to_ms(delta));
for (stack=2;stack<argc;stack++) {
Instruction *ip = prog;
fp = fopen(argv[stack],"r");
if (!fp) exit(printf("Can't Open input File %s\n",argv[stack]));
printf("Processing %s:\n", argv[stack]);
memset(data,i=0,sizeof(data));
start_time=read_time();
//Run the program
while (delta) {
switch ((++ip)->inst) {
case '+': data[i]++; break;
case '-': data[i]--; break;
case ',': c=getc(fp);data[i]=(FEND==c)?0:c; break;
case '.': putchar(data[i]); break;
case '>': i=(i+1)&MAXMASK; break;
case '<': i=(i-1)&MAXMASK; break;
case '[': if (!data[i]) ip = prog+ip->pair; break;
case ']': if (data[i]) ip = prog+ip->pair; break;
case 0: delta=0; break;
}
}
delta = read_time()-start_time;
elapsed+=delta;
printf("\nProcessing Time: %f ms\n", sysTime_to_ms(delta));
}
printf("\nTotal Time for %d files: %f ms\n", argc-2, sysTime_to_ms(elapsed));
}
```
---
**Results So Far**
Here's the average time of 5 runs of the complete set of vectors:
```
Author Program Average Time Best Set Worst Set
AShelly Quicksort 3224.4 ms reverse (158.6) onlynine (1622.4)
K.Randall Counting 3162.9 ms reverse (320.6) onlynine (920.1)
AShelly Coinsort 517.6 ms reverse (54.0) onlynine (178.5)
K.Randall CountingV2 267.8 ms reverse (41.6) random (70.5)
AShelly Strandsort 242.3 ms reverse (35.2) random (81.0)
```
[Answer]
```
>>+>,[->+>,]<[<[<<]<[.<[<<]<]>>[+>->]<<]
```
I don't remember whose idea this algorithm was. Maybe Bertram Felgenhauer's? It came from discussions around Brainfuck Golf contest #2, over a decade ago.
This is the fastest one yet on the sample inputs.
It's also not limited to inputs of length <256, but can handle arbitrarily long inputs.
Both these things were also true of Albert's answers, below. The nice thing about this one is that the running time is O(N) in the input length. Yes, this thing actually runs in linear time. It already ate a constant factor of 255 as a snack.
[Answer]
Here's a sort that is at least 6x faster than my quicksort. It's an algorithm that would make little sense in a traditional language, since it's O(N\*m) where m is the maximum input value. After collecting the input, it passes through the array, counting cells > 0 and then decrementing each one. It then adds 1 to the first `count` cells in the result vector. It repeats the passes until the count is 0.
BF:
```
Get Input
>,[>>+>,]
Count values GT 0 and decrement each
<[<[<<<+>>>-]<[-<<+>>>]>[<]<<]
While count: add 1 to results
<[[[<<+>>-]<+<-]
Seek back to end of input
>[>>]>>>[>>>]
Repeat counting step
<<<[<[<<<+>>>-]<[-<<+>>>]>[<]<<]<]
Seek to far end of results and print in reverse order
<[<<]>>[.>>]
```
C equivalent algorithm:
```
uchar A[MAX]={0}; uchar R[MAX]={0}; int count,i,n=0;
while (A[n++]=getchar()) ;
do {
count = 0;
for (i=0; i<n; i++) count += (A[i]) ? (A[i]-->0) : 0;
for (i=0; i<count; i++) R[i]++;
} while (count>0);
for (i=0; R[i]; i++) ;
for (i--; i>=0; i--) putchar(R[i]);
```
---
Here's one that's 2x as fast. It's based loosely on ["spaghetti sort"](https://codegolf.stackexchange.com/a/4231/152): it lays down a string of 1s as long as each input. The value in each cell represents the number of strands at least that long. (So [3,2,1,2] becomes `|4|0|3|0|1|0|0|`). Then it starts 'measuring' the strands and prints out the length every time it finds the end of one.
```
>,[ [-[>>+<<-]>+>] <[<<]>,] build strand of 1s for each input
+>[>+<-]>[ while there are strands
>[>+<<->-] do any strands end here?
<[<<.>>-] print length of all that do
<<[>>+<<-]>>+>>] shift right 1; inc length
```
Raw:
```
>,[[-[>>+<<-]>+>]<[<<]>,]+>[>+<-]>[>[>+<<->-]<[<<.>>-]<<[>>+<<-]>>+>>]
```
[Answer]
A simple counting sort implementation. Each bucket is 3 cells wide, containing the current input, a marker, and the count of the number of times the counter appears in the input.
```
process input
,[
while input is not zero
[
decrement input
-
copy input over to next bucket
[->>>+<<<]
mark next bucket as not the first
>>>>+<
repeat until input is zero
]
increment count for this bucket
>>+
rewind using markers
<[-<<<]<
process next input
,]
generate output
>+[>[<-.+>-]<[->>>+<<<]>>>+]
```
without comments:
```
,[[-[->>>+<<<]>>>>+<]>>+<[-<<<]<,]>+[>[<-.+>-]<[->>>+<<<]>>>+]
```
[Answer]
```
>,[>+>,]+[<[<-<]>>[<[>>]>[<->[>>]<.<[<<]]>>]<<<<<+]
```
[Answer]
```
>>+>,[>+>,]<[[<-<]>+>+[>]>[[-<<[[>>+<<-]<]>>]>-.+[>]>]<<]
```
] |
[Question]
[
A [basis](https://en.wikipedia.org/wiki/Basis_(linear_algebra)) of a vector space \$V\$ is a set of vectors \$B\$ such that every vector \$\vec v \in V\$ can be uniquely written as a linear combination of the vectors in \$B\$. In other words, let \$B = \{\vec b\_1, \dots, \vec b\_n\}\$ be a basis of some vector space \$V\$. For every possible \$\vec v \in V\$, we can say that
$$\vec v = \lambda\_1 \vec b\_1 + \lambda\_2 \vec b\_2 + \cdots + \lambda\_n \vec b\_n$$
for some **unique** real numbers \$\lambda\_1, \lambda\_2, \dots, \lambda\_n\$. Note that this requires the vectors in \$B\$ to be [linearly independent](https://en.wikipedia.org/wiki/Linear_independence) (i.e., you cannot write a vector in \$B\$ as a linear combination of other vectors in \$B\$).
For example, let \$V = \mathbb R^2\$ i.e. the set of all 2 dimensional vectors. We can see that \$B = \left\{ \begin{pmatrix} 1 \\ 0 \end{pmatrix}, \begin{pmatrix} 0 \\ 1 \end{pmatrix} \right\}\$ is a basis of \$V\$, as any 2 dimensional vector \$\vec v = \begin{pmatrix} x \\ y \end{pmatrix}\$ can be written as
$$\vec v = \begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \end{pmatrix}x + \begin{pmatrix} 0 \\ 1 \end{pmatrix}y$$
Furthermore, examine \$B = \left\{ \begin{pmatrix} 1 \\ 1 \end{pmatrix}, \begin{pmatrix} -1 \\ 2 \end{pmatrix} \right\}\$. As the two vectors are linearly independent, they must form a basis of \$\mathbb R^2\$, and so we can write any 2-dimensional vector as a combination of the two. For example,
$$\begin{pmatrix} 2 \\ -10 \end{pmatrix} = -2\begin{pmatrix} 1 \\ 1 \end{pmatrix} + -4\begin{pmatrix} -1 \\ 2 \end{pmatrix}$$
However, note that if we have \$B = \left\{ \begin{pmatrix} 1 \\ 0 \\ 1 \end{pmatrix}, \begin{pmatrix} 0 \\ 1 \\ 2 \end{pmatrix} \right\}\$, then this does not form a basis for all 3 dimensional vectors. There exists no such \$\lambda\_1, \lambda\_2\$ such that
$$\begin{pmatrix} 4 \\ 6 \\ 10 \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \\ 1 \end{pmatrix}\lambda\_1 + \begin{pmatrix} 0 \\ 1 \\ 2 \end{pmatrix}\lambda\_2$$
and so \$B\$ is not a basis for \$\begin{pmatrix} 4 \\ 6 \\ 10 \end{pmatrix}\$.
---
You are to take a vector \$\vec v \in \mathbb Z^m\$ of \$m\$ integers, and a list of \$n\$ vectors \$B = \{\vec b\_1, \dots, \vec b\_n\}\$. You should then output two distinct consistent values to indicate whether or not \$B\$ forms a basis for \$\vec v\$ (more precisely, whether \$B\$ forms a basis for some space containing \$\vec v\$). That is, whether or not there exists a unique set of numbers \$\lambda\_1, \lambda\_2, \dots, \lambda\_n\$ such that
$$\vec v = \lambda\_1 \vec b\_1 + \lambda\_2 \vec b\_2 + \cdots + \lambda\_n \vec b\_n$$
You may assume that \$\vec b\_i \in \mathbb Z^m\$ for all vectors \$b\_i \in B\$ - that is, they all have the same number of elements as \$\vec v\$, and they are all integer vectors.
You may take the inputs in any [reasonable, convenient format and method](https://codegolf.meta.stackexchange.com/q/2447/66833), including a list of lists of \$B\$, or a list of numbers for \$\vec v\$ etc. The output may be any two distinct, consistent values to indicate whether or not \$B\$ is a basis. You may freely choose these values.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
## Test cases
```
B
v
Output (λ1, λ2, ..., λn or reason)
[[8, 1, 2], [-7, -8, -9], [-1, 9, -5]]
[12, 36, -4]
True (1, -1, 3)
[[-9, -3]]
[3, 1]
True (-1/3)
[[1, 0, 1], [0, 1, 2]]
[1, -1, -1]
True (1, -1)
[[1, 0, 1], [0, 1, 2]]
[4, 6, 10]
False (shown above)
[[7, -2], [-10, -6], [-4, 9]]
[1, -21]
False (too many unknowns, an infinite number of solutions exist)
[[-1, 8, 1, 6, 3], [8, -6, -5, -10, 6], [-8, -3, -3, -4, 5], [-6, -6, 0, 3, 9], [2, 2, 0, -1, -3]]
[1, 1, 1, 1, 1]
False ([-6, -6, 0, 3, 9] and [2, 2, 0, -1, -3] are linearly dependent, so any way of writing the sum is not unique)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~43~~ ~~41~~ 39 bytes
```
@(B,v)(r=rank(B))-rows(B)|r-rank([B;v])
```
Anonymous function that inputs the set of vectors as a matrix **B** with each vector in a row, and **v** as a row vector. The output is `true` (displayed as `1`) if `B` is not a basis for `v`, and `false` (displayed as `0`) if it is.
[Try it online!](https://tio.run/##fVBBCoMwELz3FXs0sCuaaFoJQvEb4kFKvRQq2GIv/budTSy9FWKYncyMk8yX57het4layvN8O2cdryZb2mW837LOGFnm1wPgvUik@i6sg9mmrD8xlUw2kByZBJM0wKAawHpg6ktLzpNUgzlAL8o75R2ciYO6wBDijrDo4pgifyQVk8dUDIZUckw1SijEA@C4@SbZPUYjU2M4XVAsXotyMqpPObd/yKhDkvjYACTuZ1lXsVd0@19@C0/zAQ)
### How it works
The set of vectors defined by the rows of **B** is a basis for **v** if and only if the rank of the matrix **B** equals its number of rows (i.e. the rows of **B** are linearly independent) *and* the rank of the extended matrix with `v` as last row is the same (i.e. **v** is in the linear span of the rows of **B**).
To save bytes, the code checks if *either* of those conditions is *not* satisfied; that is, if the rank of **B** minus its number of rows is nonzero *or* if the rank of **B** minus that of the extended matrix is nonzero.
[Answer]
# JavaScript (ES6), 218 bytes
Expects `(matrix)(vector)`. Returns \$0\$ or \$1\$.
```
m=>v=>!(g=m=>m.reduce(o=>m.some((r,y)=>r.some((_,x)=>m[y+w]&&(D=m=>+m||m.reduce((s,[v],i)=>v*D(m.map(([,...r])=>r).filter(_=>i--))-s,0))(m.slice(y,y-~w).map(r=>r.slice(x,x-~w)))/r[x+w]))*++w||o,w=0)-w)(m)&!~g([...m,v])
```
[Try it online!](https://tio.run/##lVDNbsIwDL7vKboLiqmTtQ2wcUhPvEVUIQQFdWooSll/pIpX75yUMWniMqmR7K/fj@3PXbOr97a4XPm5OuTjUY1GpY1KX9lJUWWEzQ9f@5xVrq4rkzNmsQeV2nu3xY46o/uwzWYztnGq0AzDQ8lq1E2GBbGa@YYZYXYXxjQKIWzmjEAci/KaW7ZVacE5AK8xAiBmXRZk0GPPby14nfXBHu6wczDAm9UdhQPMw7AdhgpbFQFvyQBmr7cT05RksMlg3FfnuipzUVYndmRaf2AQY5BkGGj@jgGnnq99R/CammWWAdNxgoFcUbugkJe/JtwRpSdK8ntGIbfI/SLn6B7pfUno3z80Cwxokjh6JnErTMvEJOErX5Jg/UhLnka5IaZTkLV0KncIt/DSTUdek5VD5f2R7dKDq4lKJOmSCKJrJR7wy8mf8N@PZhi/AQ "JavaScript (Node.js) – Try It Online")
### How?
The method is the same as the one [used by Luis](https://codegolf.stackexchange.com/a/237984/58563).
To compute the rank of a matrix, we look for the largest sub-matrix of size \$n\times n\$ whose determinant is not equal to \$0\$. This is most probably not the shortest way of doing it.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 93 bytes
```
f=B=>1/B[0][p=B.find(t=>t[0]),1]?!!p&&f(B.map(q=>q.map((v,i)=>v*p[0]-q[0]*p[i]).slice(1))):!p
```
[Try it online!](https://tio.run/##hVDRboMwDHznK8JLlUwJI6Gl7aYwid9AeUAUqkwMwkD8PnMSxJi0bhJB9vnss@@9nMux@tRmYl1/q5dGwpfLjD/nRawKI/Oo0d0NTzKbACCUq7cwNIdDg/PoozR4kNngAjxTTWQ2PxngsQF@EGlForHVVY05IeQlNEvVd2Pf1lHb33GDiwCh4kIRO8PjFHGhqIUgZABfKUpSjwhAIGUneEcVKEJeg19mWU7iO1gC8x4zQSK2BMe1kd1gUxcu@6f5uG9O9708ftzrTo3tGZs8s3Kpu5eJP2StRRdvjaWLbcAK2JN/FvhqWeIW/j443S2RrN77CmRQPPlldhYuXw "JavaScript (Node.js) – Try It Online")
For testcase `[[8, 1, 2], [-7, -8, -9], [-1, 9, -5]], [12, 36, -4]` it input as `f([[8, -7, -1, 12], [1, -8, 9, 36], [2, -9, -5, -4]])`. Extra 47 bytes may be needed if we have to input as matrix B and vector V as two parameters.
This function simply reduce the array using Gaussian elimination.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 46 bytes
```
f(a,b)=#a==matrank(a)&&#matintersect(a,Mat(b))
```
[Try it online!](https://tio.run/##fU9BasMwEPzKkkCQYAW2lbg1xv1BXyB02ISkhLhBuL7k4q87s5bT3gqSmNmdmV0lGa7uK83zxQgfbbeVrvuWcZD7zYjd7bYg1/t4Hn7OpxGSTxnN0dpZUuofRsh9UBogANwo2dBJ@t5cmMRaphDCO1PJVLXk3pgcmGuAUWoAD3GCqKzY1@z2cYpgOiI47fo4aYZHQm4F2AqwdnmRmu285Ll/RXumGrRYNbqL7lRC42oA9JvftOoVpbn5AzD7VrGrdW/OVnVqza8XKYc2S@plCxTx3Yr1FOue/jXn72BctPMT "Pari/GP – Try It Online")
Takes a matrix and a column vector as input.
[Answer]
# [R](https://www.r-project.org/), 61 bytes
Or **[R](https://www.r-project.org/)>=4.1, 54 bytes** by replacing the word `function` with `\`.
```
function(B,v,`+`=Matrix::rankMatrix)+B-nrow(B)|+rbind(B,v)-+B
```
[Try it online!](https://tio.run/##jVDNCsIwDL77FD02LIW1dVMHXnb35gOok8EQOyjz5@C71yytOj0JTZuG7yeJD@06tBfXDF3vZI1X3GW79WY/@O5eVX7vTjGHrFbO9zdZwyPzh84dRzCorA6tPDNENnKJQqMwKNSCgn5qRUGl8SkALeIWUDRSE8aWVJwDzCYCjLeA@gW0pPgNIbWcbeJtAM1bNZqp/xlzFNSFzgHElLGIQ2giKO6SJph2TyXzYzIax/GJYDlnapF0yrQQm4IkiwQpuTPLWzJ88jQIbaKYmH4OQHgC "R – Try It Online")
Port of [Luis Mendo's answer](https://codegolf.stackexchange.com/a/237984/55372).
[Answer]
# [Wolfram Mathematica](https://www.wolfram.com/mathematica/), ~~51~~ 41 bytes
```
Tr[1^#]&@@Solve[i=0;s@++i&/@#.#==#2]===i&
```
-10 (!) bytes due to @att
[Try it online!](https://tio.run/##jVDLCsIwELz7FQuFXky0SWy1SCCfIOitVCgiGvABWryUfnudTX2fhAQys7MzuzlW9X57rGq/qbqd7VaXQq2jMnZueT7ctoW3yfzqhkMfj100iqyNdGmt9XG3uPhT7XZF08wEKUG6FdTIqSAJLPOAQOcAactIaUEmA5y05eDdLVlhgsLAqC3powiDhEkUk0dKsEJLuH@pJ4IQq5JvMU/az6wglll4Qpq/EvSPPUf2u8LOsIo35Y1SngUuvQmz5nFhOCCiNBSyXg6h4RxQ@BIdiLCOeUa/Dyag7g4)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes
```
⊞θηW∧θ⌈Φ§θ⁰κ≔EΦθλEκ⁻×μι×§§θ⁰ν§κ⌕§θ⁰ιθ⁼θ⟦Eη⁰
```
[Try it online!](https://tio.run/##XY49C8IwEIZ3f8WNF0jBby1OHRQcCh3cSoagxRym0Tat9t/HS6WLByE87/vex9Xo9vrUNoSi9wYbCUYcZh9DtgLM3C0quR6o7ms8ke2qFrPu7G7VEJ25kPAQXJB5T3eHuX5NMbatiM0vfPBHrvd4obryWEsgdn4wTfub6vhNErefiE/5i5AYS0LDFxctuQ6PTa@tj4Ey7jUxqIQ4hFCW5V7CQsJSsZnsJCTMSToSyynDRkVaLCWstoxrpULytl8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @tsh's JavaScript answer.
```
⊞θη
```
Append the vector to the basis.
```
W∧θ⌈Φ§θ⁰κ
```
Repeat until the basis becomes degenerate...
```
≔EΦθλEκ⁻×μι×§§θ⁰ν§κ⌕§θ⁰ιθ
```
... perform Gaussian elimination on the basis, dropping the first row.
```
⁼θ⟦Eη⁰
```
Check whether the result is a zero vector.
] |
[Question]
[
## Background
**K** functions have a feature called **projection**, which is essentially partial application of values to a function. The syntax for projections is a natural extension of the regular function call syntax:
```
f[1;2;3] / call a ternary function f with three arguments 1, 2, 3
f[1;2;] / the third argument is missing,
/ so it evaluates to a unary derived function instead
f[1;2;][3] / calling the derived function with 3 calls f with 1, 2, 3
/ so this is equivalent to calling f[1;2;3]
```
Projections can supply any number of arguments and missing slots, and omit trailing semicolons. The function is evaluated only when all missing slots are filled and the number of arguments is at least the function's arity. For the sake of this challenge, let's assume the arity of `f` is *infinity*, i.e. it is never actually evaluated.
The right side shows how ngn/k prettyprints projections. You can freely experiment with [ngn/k online interpreter](https://ngn.bitbucket.io/k/#eJyFjlEKwjAQRP89jdM2qfqOMuSjVaNHKBTvrkSEWmLdj2XnzQ5MPs0eGDlz4Urmxj1Nj102Su9tmsXl9lsY6GrIhF/YkS3L/bZLSZd6YjkV4k/jKncR3d/8+s+BSM+BI9onS6hBLXrVVEAxPQGQ6lxH).
```
f[1] / -> f[1]
f[1;2] / -> f[1;2]
f[;2] / -> f[;2]
f[;2][1] / -> f[1;2]
```
A projection also decides the minimum number of arguments `f` will be actually called with. For example, `f[1;]` specifies that the first arg is `1` and the second arg will come later. It is different from `f[1]`, and the two are formatted differently.
```
f[1] / -> f[1]
f[1;] / -> f[1;]
```
You can create projections out of projections too, which is the main subject of this challenge. Given an existing projection `P` and the next projection `Q`, the following happens:
* For each existing empty slot in `P`, each (filled or empty) slot in `Q` is sequentially matched from left to right, replacing the corresponding empty slot in `P`.
* If `Q` is exhausted first, the remaining slots in `P` are untouched.
* If `P` is exhausted first, the remaining slots in `Q` are added to the end.
```
f[;;1;;] / a projection with five slots, 3rd one filled with 1
f[;;1;;][2] / -> f[2;;1;;]
/ 2 fills the first empty slot
f[;;1;;][2;3;4] / -> f[2;3;1;4;]
/ 2, 3, 4 fills the first three empty slots
/ (1st, 2nd, 4th argument slot respectively)
f[;;1;;][2;;4] / -> f[2;;1;4;]
/ the second empty slot (2nd arg slot) remains empty
f[;;1;;][2;;4;;6] / -> f[2;;1;4;;6]
/ Q specifies five slots, but P has only four empty slots
/ so the 6 is added as an additional (6th overall) slot
```
## Challenge
Given a series of projections applied to `f`, simplify it to a single projection as described above.
The input is given as a string which represents the function `f` followed by one or more projections, where each projection specifies one or more (filled or empty) slots. You may further assume that
* the substring `[]` does not appear in the input (it means something slightly different),
* each filled slot (specified argument) contains a single integer between 1 and 9 inclusive, and
* the entire input does not have any spaces.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
All the examples are replicated here, and a "stress test" is presented at the bottom.
**Basic tests**
```
f[1] -> f[1]
f[1;] -> f[1;]
f[1;2] -> f[1;2]
f[;2] -> f[;2]
f[;2][1] -> f[1;2]
f[1;2;3] -> f[1;2;3]
f[1;2;] -> f[1;2;]
f[1;2;][3] -> f[1;2;3]
f[;;1;;] -> f[;;1;;]
f[;;1;;][2] -> f[2;;1;;]
f[;;1;;][2;3;4] -> f[2;3;1;4;]
f[;;1;;][2;;4] -> f[2;;1;4;]
f[;;1;;][2;;4;;6] -> f[2;;1;4;;6]
```
**Stress tests (input)**
```
f[;1]
f[;1][;2]
f[;1][;2][3]
f[;1][;2][3][;;;4]
f[;1][;2][3][;;;4][;5]
f[;1][;2][3][;;;4][;5][6;]
f[;1][;2][3][;;;4][;5][6;][7]
f[;1][;2][3][;;;4][;5][6;][7;;]
f[1;;;;;;;;;;;;;]
f[1;;;;;;;;;;;;;][2][3]
f[1;;;;;;;;;;;;;][2][3][;;;;;4;;;;;;;;]
f[1;;;;;;;;;;;;;][2][3][;;;;;4;;;;;;;;][5;6;7;8;9;1][2;3;4;5][6;7]
```
**Stress tests (output)**
```
f[;1]
f[;1;2]
f[3;1;2]
f[3;1;2;;;;4]
f[3;1;2;;5;;4]
f[3;1;2;6;5;;4]
f[3;1;2;6;5;7;4]
f[3;1;2;6;5;7;4;;]
f[1;;;;;;;;;;;;;]
f[1;2;3;;;;;;;;;;;]
f[1;2;3;;;;;;4;;;;;;;;]
f[1;2;3;5;6;7;8;9;4;1;2;3;4;5;6;7;]
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~37 34~~ 32 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ñgí⌡²☼☺≈AU▀≤L♠╫$U∩─.ù·○╓╥ò±E♦τèZ
```
[Run and debug it](https://staxlang.xyz/#p=a567a1f5fd0f01f74155dff34c06d72455efc42e97fa09d6d295f14504e78a5a&i=f%5B%3B1%5D%0Af%5B%3B1%5D%5B%3B2%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%5B%3B5%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%5B%3B5%5D%5B6%3B%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%5B%3B5%5D%5B6%3B%5D%5B7%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%5B%3B5%5D%5B6%3B%5D%5B7%3B%3B%5D%0Af%5B1%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%5D%0Af%5B1%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%5D%5B2%5D%5B3%5D%0Af%5B1%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%5D%5B2%5D%5B3%5D%5B%3B%3B%3B%3B%3B4%3B%3B%3B%3B%3B%3B%3B%3B%5D%0Af%5B1%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%5D%5B2%5D%5B3%5D%5B%3B%3B%3B%3B%3B4%3B%3B%3B%3B%3B%3B%3B%3B%5D%5B5%3B6%3B7%3B8%3B9%3B1%5D%5B2%3B3%3B4%3B5%5D%5B6%3B7%5D&m=2)
-2 reducing splitting code
## Explanation
```
2t1T.][/ {';/m{s{c{c{B}z?}?ms+k';*:}'fs+
2t1T.][/ get all argument bodies
{';/m split all on semicolons
{s{c{c{B}z?}?ms+k reduce by:
s swap with prev
{c{c{B}z?}?m map elements in prev to:
c{ }? if non-empty, leave elem as is
c{B}z? else remove first element of next and push
(pushes [] if empty)
s+ append the rest elements
';* join with semicolons
:} put in square brackets
'fs+ prepend 'f'
```
# [Stax](https://github.com/tomtheisen/stax), 37 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ö☺τσj↔₧♂√V{▐9,=☺|╢Δ‼$≥ä₧ÿºÉ/♂y╩▲S╞♫┘{
```
[Run and debug it](https://staxlang.xyz/#p=9901e7e56a1d9e0bfb567bde392c3d017cb6ff1324f2849e98a7902f0b79ca1e53c60ed97b&i=f%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%5B%3B5%5D%5B6%3B%5D%5B7%3B%3B%5D%0Af%5B%3B1%5D%0Af%5B%3B1%5D%5B%3B2%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%5B%3B5%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%5B%3B5%5D%5B6%3B%5D%0Af%5B%3B1%5D%5B%3B2%5D%5B3%5D%5B%3B%3B%3B4%5D%5B%3B5%5D%5B6%3B%5D%5B7%5D%0Af%5B1%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%5D%0Af%5B1%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%5D%5B2%5D%5B3%5D%0Af%5B1%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%5D%5B2%5D%5B3%5D%5B%3B%3B%3B%3B%3B4%3B%3B%3B%3B%3B%3B%3B%3B%5D%0Af%5B1%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%5D%5B2%5D%5B3%5D%5B%3B%3B%3B%3B%3B4%3B%3B%3B%3B%3B%3B%3B%3B%5D%5B5%3B6%3B7%3B8%3B9%3B1%5D%5B2%3B3%3B4%3B5%5D%5B6%3B7%5D&m=2)
uses an assign at index builtin, slightly longer.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 46 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¦¤¡¨ε¦';¡}Å»U0ìD_OXg-(©di®Å0«}0X.;}θ';ý0K"f[ÿ]
```
05AB1E is not the right language for this challenge.. :/
[Try it online](https://tio.run/##yy9OTMpM/f//0LJDSw4tPLTi3NZDy9StDy2sPdx6aHeoweE1LvH@EenFuodWpmQeWne41eDQ6lqDCD3r2nM71K0P7zXwVkqLPrw/9v//tGhrw9hoa6PYaGMgZW1tAiRNY6PNrGOjza2tYwE) or [verify all test cases](https://tio.run/##pZPLSsNAFIb3eYowLrqpkmujPUgR60YX4kIoDEFqm0pBqDRVFMyyPoBvUJBSUdwpghRhsi8@gy8SJxdnJhdMpVkk@b/zn3NmMicDt33ad4LbKwntXV84nZHTrcuocVOV0E5ndNk@r8tyqNe@5k0kf9/dy8gNyJQ8kAmZLV7JtAJk4vlj8nGs@M/Nk8PWmbtOHrt98uKPFfLkKa0N8BbvFfDnygHqYf/TDhCZ7W9LaHcwHNKOUb@jKnlrBD2s2lGT8EWiN2ASYq1xoIWEA6aFGjGjD9AFRkVCRcgYznsBVGDmWDCK2Qq0XAR0MHhUp9RIx8VwURSgljFQEFrYHkFNtPgpfj9OTPmG9HyEduOLiOIQkQITBjNjNP9w4hqk3bVSO7byGVZZCkBhEiQHKl78XFM078PimJV7MxOzjB9HwsivjOUb/66BTbp5CzZhC9R0QR4wQF2pbDzTfBCK6ieW1XvQA7aWaRQy/qPjCAnDlDLaPw).
**Explanation:**
Step 1: Transform the input to something more usable: [Try it online](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0PLDi05tPDQinNbDy1Ttz60sPa/zv@0aMNYLiBhDSGNQBSchMkZWRvDGHA6GixkbW1obY1gRBshs62NrU1Q@Bhca2szsIghlIRZDWFBrYBzgDqhJqAJRVub4hKONrPGJxVtjl/WGuphZIBFBOJvTMFoY5zi0WCOCX5DsaiLNrU2sza3trC2tDYkTxMkYiBBRoFuYACZI5JHNFAIGJnA8AQA).
```
¦ # Remove the leading "f" from the (implicit) input-string
¤ # Get its last character "]" (without popping)
¡ # Split it on this "]"
¨ # Remove the trailing empty item
ε # Map over each inner string
¦ # Remove the leading character (the "[")
';¡ '# Split it on ";"
} # Close the map
```
We now have a list of lists of digits and empty strings.
Step 2: Reduce this list of lists according to the challenge: [Try it online](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0PLDi05tPDQinNbDy1Ttz60sPZw66HdoQaH17jE@0ekF@seWpmSeWjd4VaDQ6trDSL0rGvP7fiv8z8t2jCWC0hYQ0gjEAUnYXJG1sYwBpyOBgtZWxtaWyMY0UbIbGtjaxMUPgbX2toMLGIIJWFWQ1hQK@AcoE6oCWhC0damuISjzazxSUWb45e1hnoYGWARgfgbUzDaGKd4NJhjgt9QLOqiTa3NrM2tLawtrQ3J0wSJGEiQUaAbGEDmiOQRDRQCRiYwPAE).
```
Å» # Cumulative left-reduce (which unfortunately keeps track of steps):
U # Pop and store the current list in variable `X`
0ì # Prepend a 0 before each item in the result-string
# (so all empty strings become 0s)
D_O # Get the amount of 0s in this list (duplicate; ==0; sum)
Xg # Push the length of the current list `X`
s- # Subtract the amount of 0s from this length
© # Store it in variable `®` (without popping)
di } # Pop, and if this value is >= 0:
®Å0 # Push a list with `®` amount of 0s
« # And append this to the result-list
0X.; # Then replace each zero ("0","00","000",etc.) in this list one by
# one with the values from list `X`
}θ # And after the cumulative left-reduce, pop and keep the last list
```
Step 3: Format this resulting list to a format similar as the input:
```
';ý '# Join the list with ";" delimiter
0K # Remove all 0s from the string
"f[ÿ] "# Push string "f[ÿ]", where `ÿ` is automatically replaced with the
# string
# (after which the result is output implicitly)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 126 bytes
```
lambda s,D=[]:f'f[{";".join([D:=[j or next(i,"")for j in D]+[*i]for k in s[2:-1].split("][")if(i:=iter(k.split(";")))]*0+D)}]'
```
[Try it online!](https://tio.run/##lVJLb6MwED43v8KhB9spqRogSZeRK1VKe93L3rwcIAXVKQvIuGqrqr89tXk4oUTbXQ4w32tGY1O9qcey8K8ruc/Y730e/0keYlS7G8ajMMMZf3fAudyVoiB8EzK@Q6VERfqqiHAdh2Ya7ZAo0Ca64DMRGfxkcM29cL6ILusqF4o4EXeoyIgImVCpJE89Dw6lNJpdXWzoR4T3Sr6Fk7OXR5Gn6Jd8TjU4i90EMd2yelaEdjmM5jcIU61utZaR2JRxXadSoYSxrUbnlRSFIrGL5zfYTegkfd2mlUJ3P@/vpCylbt1ZdLYt8G2eI5XWqkaVafYwxTZ22zQXZfEljBmeBd6hRSNPEULYlWklSUJdPGXY1UdJ3hsmph8Uu5ixzrGldJ/xRWRWMt@JfkGPoIWexZ4hLLbwkG8p/QH/QOm6I484S/GRE2ABvbWtLcn72d5IAB8CK/qaDIbykXpKBFgNdY2No18NFh082r8/kJa0i/hjQU@y8xsZGuKEh8Ny6Fv@xchXMDCvvnXz9Siw/i4BcCoD3RUeP/YmB@TYxr0v1/4vdt6AYDTLxoP/bsGXeps1XMMPs33zC7VbrwfdD64AWibouOgT "Python 3.8 (pre-release) – Try It Online")
Ungolfed:
```
def f(s):
D=[]
for k in s[2:-1].split(']['):
i = iter(k.split(';')) # next projection
D = [j or next(i,'') for j in D] # replace empty slots with arguments from i
D += [*i] # add the rest of i
return 'f['+';'.join(D)+']'
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~65~~ 59 bytes
```
{"f[",|x,|y/{.![a*+\a:~#'x;x],(1+!#y)!y}/y\'-1_'1_z\}."];["
```
Thanks to ngn for cutting 4 bytes [here](https://chat.stackexchange.com/transcript/90748?m=59140875#59140875) and [here](https://chat.stackexchange.com/transcript/message/59149637#59149637).
[Try it online!](https://ngn.bitbucket.io/k#eJydkt1ugzAMhe/7FJBOol1Zq0CAjfMoBrXcIE2bNKnqBYzSZx8/CUlapqFxg/352I6dlGnDSmL+tfKv9aHZu1Q877Iiva29ClXub/jOXddbt24Pdea98KPHj99Zu2c5iK1Wl7R5ovp2TkvHcSqcvj6wOZXF+ycq1Dhv83Z1oa4Bz1k+/qQPCaBJoFCgmEIWmWpp2pkIJ9qbmmtsUZrTAxwyQZomJ3maYDaGEELFw46JR4UW/BYHYkvSu1IkpwY3iF6QubSRqwHD+VjXVR1nUGD052WEyJJGf2gphqmPFyVQcp+TLEnCQ6ukX5y+bPNTd26zWSUF9htZmkGDI+47ThXEv6pQ1I2W4BVv/SaGxzZuIDEbaJHASIRkOfsB/CEGOA==)
# K (k9 2021.09.01), 54 bytes
```
{"f[",|x,|y/{!?(?x*+\x!:~#'x),?+\y!1}/y\'1_z\x_}."];["
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ”[Ṗ€ṣ€”;VṆ€k$ḟ0;ɗ"Ẏɗ/j”;ḟ0Ø[j”f;
```
A monadic Link that accepts a list of characters and yields a list of characters.
**[Try it online!](https://tio.run/##hVA7EoIwEO09hmOv/HXePZxxdiilQC5g51BoZ6k2joUtpYVoScUxwkViEgIiIqbYfZ/d7CbhMorWnLP0WmzOxNJDESeSxIngmLN0K@BqxO6XCfLjkD32@XEcSk9K2YkkDsDZ85btROmC84AMfyACymjKVMfKM2FVoM6kJMAA3oDMJoYF@4N/UcBViqFjNbpEekRNRKe@oSURnF8yueizyOt3oR/cPB0KVct26qSI/be/XUcOXHiYYiYXVN9ZLub5Lw "Jelly – Try It Online")**
### How?
```
ṣ”[Ṗ€ṣ€”;VṆ€k$ḟ0;ɗ"Ẏɗ/j”;ḟ0Ø[j”f; - Link: list of characters, S
ṣ”[ - split (S) at '['
Ṗ€ - pop (i.e. remove ']' from) each
ṣ€”; - split each at ';'
V - evaluate as Jelly code
-> list of projections with zeros at empty slots
/ - reduce by:
ɗ - last three links as a dyad, f(P, Q):
$ - last two links as a monad, f(P):
Ṇ€ - logical NOT each
k - partition (P) after truthy indices (of that)
-> P split after each empty slot
" - zip (across [t in that] and [q in Q]) with:
ɗ - last three links as a dyad, f(t, q):
0 - zero
ḟ - (t) filter discard (zeros)
; - concatenate (q)
Ẏ - tighten (to a flat list)
j”; - join with ';'
ḟ0 - filter discard zeros
Ø[j - "[]" join (that)
”f; - 'f' concatenate (that)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 92 bytes
```
v=>v.match(/(?<=[[;])\d*|\[/g).map(g=n=>1/n?o[++i]?g(n):o[i]=n:i=-1,o=[])&&`f[${o.join`;`}]`
```
[Try it online!](https://tio.run/##hVLJboMwEL3zFT5UxG4aEFnbTA2nfsUECUSAOiI2AsQlzbdTAyHK1tSH8XtvVi@7sA7LqBB5NZFqGzcJ4U3N3drah1X0TW3qfXJE8Nlm@/qzQTtl2pPTlEvuOrb0FI7HwvdSKtlaofC5XAs@cd4UR5@ZZpDgy0FZOyVkAMHRD5oqLqsoLOOScBIYCTp@a6C303Y728E3hdkAzjtqqY0CBzqxBzi9xDCD@RW/owDLvkzXSduheY9wdk106qnEjYSw@EvGJTxz4eq5F05HvlwPFByGfahjR@b/5t/G4QKWsIJ3@GgH7O6zH0wPHRjnl7SqQuwps8o8ExUdbeSIWYkqvkL9gTLCXXIwCImULFUWW5lKtWiaJKEZY2AcGTS/ "JavaScript (Node.js) – Try It Online")
-1 byte by Arnauld.
[Answer]
# Scala, 183 bytes
```
_.drop(2).init split "\\]\\["map(_ split ";")reduce{(p,q)=>val(b,a)=((q,q take 0)/:p){case((q,p),x)=>if(q.size<1|x!="")(q,p:+x)else(q drop 1,p++q.take(1))}
a++b}mkString("f[",";","]")
```
[Try it in Scastie!](https://scastie.scala-lang.org/suKGW44ATTGflXHoxfsdRQ)
A pretty horrible solution, but I'll work on it later. Explanation coming soon.
```
_ //The input
.drop(2) //Drop the "f["
.init //Drop the "]" at the very end
split "\\]\\[" //Split the projections up
map(_ split ";") //Split each projection into its parts
reduce{ (p, q) => //Reduce the projections by this function, which does the real work
val(b,a)=((q,q take 0)/:p){case((q,p),x)=>if(q.size<1|x!="")(q,p:+x)else(q drop 1,p++q.take(1))}
a++b}mkString("f[",";","]")
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 131 bytes
```
(f.(\d;)*(;(\d;)*)*)(;[^]]*].(?<-3>;)*(?(3)^))(\d);?
$1$6$5
}`\[\]
}`(f(.(\d|((?=;)))(?=[];]))*);?(].(?<-4>;)*)([^]]+)?
$1$#6$*;$6
```
[Try it online!](https://tio.run/##hVDLCsIwELz3N8xht2Khr1QZaz5km6KgBS8exKN@e036QqTWBGY2M7vDkvvlcb2d2paaiKozOCT07C5BamtDG5HZb9KDNw2lXDO7FoYJVKy0yoPXsZLKBo6pIR/zJDIl2PWZUiwsuzAY6oMyH8Tko9fcZay0CqF02zYS28ABekw8TTh6CdKxmFg6CfGA41BfTebwEADZnCTIf8misWRJsexiWPXzzCgyLjurS/fI/s5/90kOjQJb7PyC7vuc1y1W2Dc "Retina 0.8.2 – Try It Online") Explanation: Uses .NET balancing groups to shuffle arguments into slots. The first two lines shuffle arguments from the second application into free slots in the first. The middle two lines delete an empty application resulting from the first two lines. The last two lines append trailing arguments or slots from the second application to the first, however the test assumes that there are no arguments left to shuffle or empty applications, which is why an extra loop is needed.
] |
[Question]
[
*Inspired by [this Stack Overflow question](https://stackoverflow.com/q/52657041/2586922)*.
## The challenge
### Input
An array of square matrices containing non-negative integers.
### Output
A square matrix built from the input matrices as follows.
Let \$N \times N\$ be the size of each input matrix, and \$P\$ the number of input matrices.
For clarity, consider the following example input matrices (\$N=2\$, \$P=3\$):
```
3 5
4 10
6 8
12 11
2 0
9 1
```
1. Start with the first input matrix.
2. Shift the second input matrix *N*−1 steps down and *N*−1 steps right, so that its upper-left entry coincides with the lower-right entry of the previous one.
3. Imagine the second, shifted matrix as if it were stacked on top of the first. Sum the two values at the coincident entry. Write the other values, and fill the remaining entries with `0` to get a \$(2N-1)\times(2N-1)\$ matrix. With the example input, the result so far is
```
3 5 0
4 16 8
0 12 11
```
4. For each remaining input matrix, stagger it so that its upper-left coincides with the lower-right of the accumulated result matrix so far. In the example, including the third input matrix gives
```
3 5 0 0
4 16 8 0
0 12 13 0
0 0 9 1
```
5. The ouput is the \$((N−1)P+1)\times((N−1)P+1)\$ matrix obtained after including the last input matrix.
## Additional rules and clarifications
* \$N\$ and \$P\$ are positive integers.
* You can optionally take \$N\$ and \$P\$ as additional inputs.
* Input and output can be taken by [any reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Their format is flexible as usual.
* Programs or functions are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
* Shortest code in bytes wins.
## Test cases:
In each case, input matrices are shown first, then the output.
1. \$N=2\$, \$P=3\$:
```
3 5
4 10
6 8
12 11
2 0
9 1
3 5 0 0
4 16 8 0
0 12 13 0
0 0 9 1
```
2. \$N=2\$, \$P=1\$:
```
3 5
4 10
3 5
4 10
```
3. \$N=1\$, \$P=4\$:
```
4
7
23
5
39
```
4. \$N=3\$, \$P=2\$:
```
11 11 8
6 8 12
11 0 4
4 1 13
9 19 11
13 4 2
11 11 8 0 0
6 8 12 0 0
11 0 8 1 13
0 0 9 19 11
0 0 13 4 2
```
5. \$N=2\$, \$P=4\$:
```
14 13
10 0
13 20
21 3
9 22
0 8
17 3
19 16
14 13 0 0 0
10 13 20 0 0
0 21 12 22 0
0 0 0 25 3
0 0 0 19 16
```
[Answer]
# [R](https://www.r-project.org/), ~~88~~ 81 bytes
```
function(A,N,P,o=0*diag(P*(N-1)+1)){for(i in 1:P)o[x,x]=o[x<-1:N+i-1,x]+A[[i]];o}
```
[Try it online!](https://tio.run/##XYnBCoJAFEV/xeV7egd8Y0WZLvwBcS8uxJh4YA6YgRB9@2QQLdrcwzl3Di4qTHCPaVjUT1ShRgNfpvFF@ys1MdVGOBHmp/MzaaRTJHnDvl2xduWGwkheJ2pk86RqW@26s38FR6PeF7r1y6wrDZRhhz0kZVhYxq8fIBZHiPwfFiek@ObPZhze "R – Try It Online")
Takes a `list` of matrices, `A`, `N`, and `P`.
Builds the requisite matrix of zeros `o` and adds elementwise the contents of `A` to the appropriate submatrices in `o`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 12 bytes
```
⁹ṖŻ€ƒZƲ⁺+µ@/
```
[Try it online!](https://tio.run/##bU49DsIgGN09BaNGEoH@2c3NO0gYXZpewLEu7g6ewsnEJtXEocbeQy6C3wOqiwmEx/vez1dt63rnnG26d3d63e3@PBw3w8U2t3l/XS3c80DUmm5lm0ff9q1z0wnTWiecZYYznXImhQHSOWdLAKmIk4EjKABKogxR/7yRTYOjiMYkvNl3LiViYwe66Kt8H5GCs@hHKJ1kbC39MpBRLQ3VLzAddVJgTW@HSvmVFcXEJShD@SqB@qArMIUXBbkPnX0A "Jelly – Try It Online")
### How it works
```
⁹ṖŻ€ƒZƲ⁺+µ@/ Main link. Argument: A (array of matrices)
µ Begin a monadic chain.
@/ Reduce A by the previous chain, with swapped arguments.
Dyadic chain. Arguments: M, N (matrices)
Ʋ Combine the links to the left into a monadic chain with arg. M.
⁹ Set the return value to N.
Ṗ Pop; remove its last row.
Z Zip; yield M transposed.
ƒ Fold popped N, using the link to the left as folding function and
transposed M as initial value.
Ż€ Prepend a zero to each row of the left argument.
The right argument is ignored.
⁺ Duplicate the chain created by Ʋ.
+ Add M to the result.
```
[Answer]
# JavaScript (ES6), 102 bytes
Takes input as `(n,p,a)`.
```
(n,p,a)=>[...Array(--n*p+1)].map((_,y,r)=>r.map((_,x)=>a.map((a,i)=>s+=(a[y-i*n]||0)[x-i*n]|0,s=0)|s))
```
[Try it online!](https://tio.run/##bY/NasMwEITvfRIpGQut5Pz44EKfQ4gi0qS4pLaRQ4nB7@6uJHpJc1oNO5r59iv8hOkUu/FW9cPHeb20q@gxIsj21Sml3mIMs6iqfjNuSXr1HUYh3jEjsiH@yTuLUERAx2LatiK4ueo2vV8WLd29PDWmVstlknI9Df00XM/qOnyKizCwcM5Z7DxcDdKep9vjyIMMiLI20DwasPJSvjxG0GPEfxOhTqY6xx1KqM1j98xuYZKdiAkyCxOBTIIiaJQY7gLZAtYkVN5a7jHPKTMA1eULaZRT@YdJxxlC4WlgUo/m2rw/IPu5YJ9z118 "JavaScript (Node.js) – Try It Online")
### How?
Redimensioning matrices filled with a default constant (\$0\$ in that case) is neither very easy nor very short in JS, so we just build a square matrix with the correct width \$w\$ right away:
$$w=(n-1)\times p+1$$
For each cell at \$(x,y)\$, we compute:
$$s\_{x,y}=\sum\_{i=0}^{p-1}{a\_i(x-i\times (n-1),y-i\times (n-1))}$$
where undefined cells are replaced with zeros.
[Answer]
# [Python 2](https://docs.python.org/2/), 124 bytes
```
def f(m,N,P):w=~-N*P+1;a=[w*[0]for _ in' '*w];g=0;exec"x=g/N/N*~-N;a[x+g/N%N][x+g%N]+=m[x][g/N%N][g%N];g+=1;"*P*N*N;return a
```
[Try it online!](https://tio.run/##ZZBBboMwEEX3OcUoEgLMtMGGJE0srmCxt6wKNUCpFBNRKuimV6djQ1ddfc/4P/8ZP77H996KZbnVDTTRHRWW8XUqfp4UKxMuq0JPTKem6Qd4hc6GELLJyLZIZT3Xb/u5aA/qoBj5ZaXnhKpAGXcgSYq7no3eeq4j26Tgcs9KppiSQz1@DRaqxb0@1p8jBUCktc7waFDnyFNDqk/4QsIFcu5rgSnJBakyKDCL8R9lEAQC325yj51XOPNy9B6OkG8eTmDmYlJcU3mGwuUIjityQSFIU5rG35/R@2mO019gHl93AG6doZ/cNk3E3GK@DfAYOjsC/eHzR9/ZKAzELYQArCes8xMW7zbj8gs "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Z€Ż€’}¡"Jµ⁺S
```
[Try it online!](https://tio.run/##y0rNyan8/z/qUdOao7uBxKOGmbWHFip5Hdr6qHFX8P/D7e7//0dHRxvrKJjG6ihEm@goKBgaxAKZXArR0WY6ChYgUUMjHQVDQ6AoSBDINgAJWoKUxsZyxQIA "Jelly – Try It Online")
```
Z€Ż€’}¡"Jµ⁺S
µ Everything before this as a monad.
⁺ Do it twice
Z€ Zip €ach of the matrices
J 1..P
" Pair the matrices with their corresponding integer in [1..P] then apply the
following dyad:
Ż€ Prepend 0 to each of the rows
¡ Repeat this:
’} (right argument - 1) number of times
Doing everything before µ twice adds the appropriate number of rows and
columns to each matrix. Finally:
S Sum the matrices.
```
**[12 bytes](https://tio.run/##y0rNyan8/9/rUcNMg4e7uq0fbVynFPWoac2hrY8adwX/P9zu/v9/NJdCdLSxjoJprI5CtImOgoKhQSyQCRI101GwAIkaGukoGBoCRUGCQLYBSNASpDQ2lisWAA)**
```
J’0ẋ;Ɱ"Z€µ⁺S
```
If extra zeroes were allowed `ZŻ€‘ɼ¡)⁺S` is a cool 9 byte solution. [TIO](https://tio.run/##y0rNyan8/z/q6O5HTWseNcw4uefQQs1HjbuC/x9ud///Pzo62lhHwTRWRyHaREdBwdAgFsjkUoiONtNRsACJGhrpKBgaAkVBgkC2AUjQEqQ0NpYrFgA).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
µ;€0Zð⁺0ṁ+ṚU$}ṚU+⁸µ/
```
[Try it online!](https://tio.run/##y0rNyan8///QVutHTWsMog5veNS4y@DhzkbthztnharUgkjtR407Dm3V/3908sOdix817ju07dC2h7u3PNyx6dDOY@1hx7qAOlWA@HD7//@GJgoKhsZchgYKCgoGXFyGxgoKRgZcRoZArjEXl4IlkGvEpQCStQDKmoOFDYGihmYA "Jelly – Try It Online")
Bah, Jelly has an attitude today...
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 37 bytes
```
{i:0{Y#i-1aM:0RLyAL_i+:yZG#@aALa}Mai}
```
A function that takes a list of lists of lists. [Try it online!](https://tio.run/##bY6xCsMgFEV3v@JCxhLwqWkbp2TqEqF0ax9SHN2yhpBvt0pMpm6Xw7v3vDnOKa3RyvXdxJaCs/I1LeP0jRe7fB7NEMYpbC7ELTnBAsys0XkBgA1I@hKZr7jvjBSIKlSQO@yRkRf/2pWaWrkdVV1Dd54Q5eVDk30gVZUEiWMgr4L0qe3LN/uVhoEqaz6l9vkD "Pip – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 124 bytes
```
def f(A,N,P):M=N-1;R=G(M*P+1);return[[sum(A[k][i-k*M][j-k*M]for k in G(P)if j<N+k*M>i>=k*M<=j)for j in R]for i in R]
G=range
```
[Try it online!](https://tio.run/##JY2xCoMwFEX3fkXGRCP0pV1ajeDkpIjrI0OhxibSKKkO/fo0WrhwLpcDd/mur9mJEJ6DJppWvOUduzeyzSDvZU2bpEuB5X5YN@8QP9ubVjgpNNmUNArtAT17MhHjSE07ZjSxRZvGvTSljCikZbthd6M/ZPOvp1r6hxuHsHjj1nhPEBG4UBwv/Koi8MbhHAnAQai4EBHDQvgB "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
≦⊖θE⊕×θηE⊕×θηΣEEη×θξ∧¬∨∨‹ιν›ι⁺θν∨‹λν›λ⁺θν§§§ζξ⁻ιν⁻λν
```
[Try it online!](https://tio.run/##hY1Na8MwDIbv/RWiJwc0iJOyD3oqDEbLuhW2m8khJGYxOErrOKPsz3tySALdZcZGyM/zSlVTuqorbQjH8rzre/NF4llXTreavK4RLsl2dXKGvGBB7GlB4tO0uhcXhCZJEA6doX@Uj6EdjfgahAVeI9xRLd46L95dvK@674VBICYvTpdeu9ie7DAmKImR2bO3nr31xuF@T7W@ir/1Jy5HOBoapnVLZ@c0/6xhzXUbgspwBRt@Sim5QZB5wQ2AkilCWowNkxwhSyeSSYR8Jk8Msglw4nFJPERpGsWSvC/4hLtv@ws "Charcoal – Try It Online") Link is to verbose version of code and includes two bytes for somewhat usable formatting. I started off with a version that padded all the arrays and then summed them but I was able to golf this version to be shorter instead. Explanation:
```
≦⊖θ
```
Decrement the input value \$N\$.
```
E⊕×θηE⊕×θη
```
Compute the size of the result \$(N-1)P+1\$ and map over the implicit range twice thus producing a result matrix which is implcitly printed.
```
ΣEEη×θξ
```
Map over the implicit range over the input value \$P\$ and multiply each element by \$N-1\$. Then, map over the resulting range and sum the final result.
```
∧¬∨∨‹ιν›ι⁺θν∨‹λν›λ⁺θν
```
Check that neither of the indices are out of range.
```
§§§ζξ⁻ιν⁻λν
```
Offset into the original input to fetch the desired value.
] |
[Question]
[
*[Geobitsian language](https://chat.stackexchange.com/transcript/message/30147329#30147329)* is a new perversion of English where a word is broken into segments that each must start with a different letter. Then every time one of those starting letters appears in another string, it is replaced with its entire corresponding segment, maintaining capitalization.
This process is called *Geobitsizing*.
For example the word "[Geobits](https://codegolf.stackexchange.com/users/14215/geobits)" could be broken into `geo bits`, and the nonsense poem
```
Algy met a Bear
A Bear met Algy
The Bear was bulgy
The bulge was Algy
```
would be Geobitsized with it as
```
Algeoy met a Bitsear
A Bitsear met Algeoy
The Bitsear was bitsulgeoy
The bitsulgeoe was Algeoy
```
because every `g` becomes `geo`, every `G` (though there are none) becomes `Geo`, every `b` becomes `bits`, and every `B` becomes `Bits`.
Note that each substitution is performed with respect to the original string, not any intermediate step. e.g. if `geo` had been `gbo` instead, the `b`'s created would not replaced with `bits`.
# Challenge
Write a program or function that can generate Geobitsian language.
Take in a single-line string made of lowercase letters (a-z) and spaces. This will be the word used as the Geobitsizing argument, with the spaces separating the segments. You can assume:
* Segments will not be empty. So spaces will not neighbor each other nor be at the start or end of the string.
* Each segment starts with a different letter. Thus there cannot be more than 26.
For example, some valid segmented strings you must support are `geo bits`, `butt ner`, `alex`, and `do o r k nob` (single letter segments have no effect but are valid). But `geo` , `butt ner`, `Alex`, and `do o r k n ob` are invalid.
Your program or function also needs to take in another arbitrary string to apply the Geobitsizing to, and print or return the resulting Geobitsian language.
* You can assume this string only contains newlines and [printable ASCII.](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters)
* Remember that letter cases must be preserved from the input to the output.
Here are some more examples using `no pro gr am m ing` as the Geobitsizing argument:
`[empty string]` → `[empty string]`
`i` → `ing`
`I` → `Ing`
`Mmmm, mmm... MmmmMMM: m&m!` → `Mmmm, mmm... MmmmMMM: m&m!` (no change)
`People think bananas are great, don't you?` → `Proeoprole thingnok bamnoamnoams amre grreamt, dono't you?`
```
Pet a Puppy
Google Wikipedia
```
↓
```
Proet am Prouproproy
Groogrle Wingkingproedingam
```
Note that the results should be identical no matter how the argument is arranged, e.g. `ing pro m no am gr` should yield the same results as above.
**The shortest code in bytes wins.**
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṣ⁶;Œu1¦€$;©ZḢiЀị®
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmj4oG2O8WSdTHCpuKCrCQ7wqla4biiacOQ4oKs4buLwq4&input=&args=bm8gcHJvIGdyIGFtIG0gaW5n+UGV0IGEgUHVwcHkKR29vZ2xlIFdpa2lwZWRpYQ)
### Alternative version, 15 bytes
Jelly's title case function had a bug; it didn't capitalize the first word. That has been fixed, so the following works now.
```
ṣ⁶;Œt$;©ZḢiЀị®
```
This code does the same as in the competing version, except that `Œt` (title case) replaces the conditional uppercasing achieved by `Œu1¦€`.
### How it works
```
ṣ⁶;Œu1¦€$;©ZḢiЀị® Main link. Left argument: w (words). Right argument: s (string)
ṣ⁶ Split w at spaces.
$ Combine the two links to the left into a monadic chain.
€ Map over the words.
Œu1¦ Uppercase the item at index 1.
; Append the result to the unmodified words.
; Append all characters in s to the list of words.
© Copy the result to the register.
Z Zip/transpose, grouping the first chars into the first list.
Ḣ Head; extract the list of first characters.
iЀ Find the first index of each character in s.
ị® Select the characters/strings from the list in the register
that are at those indices.
```
[Answer]
# Python 3, 71 bytes
```
lambda w,s:s.translate({ord(t[0]):t for t in(w+' '+w.title()).split()})
```
Test it on [Ideone](http://ideone.com/mnTwxL).
### How it works
In Python *3*, the built-in `str.translate` takes a string and a dictionary, and replaces each character in the string whose code point is a key of that dictionary with the corresponding value, which may be a string, an integer or **None** (equivalent to the empty string).
Converting the string of words **w** to title case (i.e., capitalizing the first letter of each word) and appending it to the result of `w+' '` creates a string of space separated words with lower- and uppercase version (first letter). Without a second argument, `str.split` splits at whitespace, so `(w+' '+w.title()).split()` creates the *list* of all words.
Finally, the dictionary comprehension `{ord(t[0]):t for t in...}` turns each word **t** into a dictionary entry with key `ord(t[0])` (code point of the first letter) and value **t**, so `str.translate` will perform the intended substitutions.
[Answer]
## Python, ~~126~~ ~~99~~ ~~95~~ 81 bytes
Alot thanks to Dennis:
```
lambda G,S,j=''.join:j(s+j(g[1:]for g in G.split()if g[0]==s.lower())for s in S)
```
Edit1: don't need to append to a temporary
Edit2: `S` may contain uppercase...
Edit3: don't duplicate G
Edit4: compressed a little bit more and shoved it into one line
Edit5: using unnamed lambda and `j=join' '`
[Answer]
# Pyth, 19 bytes
```
.rzsC_hMBsm,rd0rd3c
```
[Try it online!](http://pyth.herokuapp.com/?code=.rzsC_hMBsm%2Crd0rd3c&input=%22no+pro+gr+am+m+ing%22%0APeople+think+bananas+are+great%2C+don%27t+you%3F&debug=0)
[Answer]
# Vim, 46 keystrokes
Ugly, and Hacky.
```
A <esc>:s/\<\w/:%s\/\0\\c\/\\0/g<cr>:s/ /eg<C-v><Cr>/g<cr>dgg@"
```
[Answer]
## [Retina](https://github.com/mbuettner/retina), 36 bytes
Byte count assumes ISO 8859-1 encoding.
```
i`(?<=^.*\b\2(\w+)[^·]*?(\w))
$1
A1`
```
[Try it online!](http://retina.tryitonline.net/#code=aWAoPzw9Xi4qXGJcMihcdyspW17Ct10qPyhcdykpCiQxCkExYA&input=bm8gcHJvIGdyIGFtIG0gaW5nClBldCBhIFB1cHB5Ckdvb2dsZSBXaWtpcGVkaWE)
[Answer]
# Pyth, ~~18~~ 16
```
MsXGhMJcjdrBH3)J
```
[Try it here](http://pyth.herokuapp.com/?code=MsXGhMJcjdrBH3%29J%0Ag%22Algy+met+a+Bear%0AA+Bear+met+Algy%0AThe+Bear+was+bulgy%0AThe+bulge+was+Algy%22+%22geo+bits%22&debug=0)
Defines a function `g` that performs the geobitsising. As a program this would be a bit shorter if the second string is single line, but multiline input isn't worth it:
```
sXwhMJcjdrBz3)J
```
The general idea here was to title case the geobitsian string and append that to the original string. Then split that on spaces and for each string, take the first letter and map it to the string it represents. That way `X` will turn the first letter of each word into the full word.
[Answer]
# Python 2, ~~83~~ 78 bytes
```
lambda w,s:''.join(c+w[(' '+w).find(' '+c.lower()):].split()[0][1:]for c in s)
```
Test it on [Ideone](http://ideone.com/3f4cof).
### How it works
We iterate over all characters **c** in the string **s**.
We prepend a space to the string of words **w**, then search for a occurrence of lowercased **c**, preceded by a space.
* If such an occurrence exists, `find` will return the index of the space in the string `' '+w`, which matches the index of **c** in **w**.
`w[...:]` thus returns the tail of **w**, starting from the word with first letter **c**. `split()` splits the tail at spaces, `[0]` selects the first chunk (the word) and `[1:]` removes its first letter.
After prepending **c** to the previous result, we obtain the correctly cased word that starts with **c**.
* If no word begins with **c**, `find` will return **-1**.
Thus, `w[...:]` yields the last character of **w**, `split()` wraps it in an array, `[0]` undoes the wrapping, and `[1:]` removes the only character from the string.
After prepending **c**, we obtain the singleton string whose character is **c**, so the whole operation is a no-op.
Finally, `''.join` concatenates all resulting strings, returning the Geobitsized version of **s**.
[Answer]
# Julia, ~~72~~ 68 bytes
```
w%s=prod(c->"$c"join((W=w|>split)[find(t->t[1]==c|' ',W)])[2:end],s)
```
[Try it online!](http://julia.tryitonline.net/#code=dyVzPXByb2QoYy0-IiRjImpvaW4oKFc9d3w-c3BsaXQpW2ZpbmQodC0-dFsxXT09Y3wnICcsVyldKVsyOmVuZF0scykKCnByaW50KCJubyBwcm8gZ3IgYW0gbSBpbmciJSJQZXQgYSBQdXBweVxuR29vZ2xlIFdpa2lwZWRpYSIp&input=)
[Answer]
## CJam, 19 bytes
```
lq\S/_32af.^+_:c\er
```
[Test it here.](http://cjam.aditsu.net/#code=lq%5CS%2F_32af.%5E%2B_%3Ac%5Cer&input=no%20pro%20gr%20am%20m%20ing%0APet%20a%20Puppy%0AGoogle%20Wikipedia)
### Explanation
```
l e# Read first line of input (list of words).
q\ e# Read remaining input and swap with first line.
S/ e# Split around spaces.
_ e# Duplicate.
32af.^ e# Convert the first letter of each word to upper case by taking
e# the element-wise XOR with the list [32].
+ e# Append the upper-cased words to the original ones.
_:c e# Duplicate and convert each word to its first character.
\ e# Swap characters with words.
er e# Transliteration, replacing each character with the corresponding word.
```
[Answer]
# JavaScript ES6, ~~67~~ ~~63~~ 70 bytes
```
g=>s=>s.replace(/\S/g,l=>l+(g.match(`\\b\\${l}(\\S+)`,'i')||[,""])[1])
```
Test this on Firefox. bugs are making this longer than I'd like
## Explanation
```
function(gbarg, str) {
return str.replace(/\S/g, function(chr) { // Replace non-whitespace w/...
return chr + (
gbarg.match(`\\b\\${l}(\\S+)`,'i') // That word in the gbstr
||[,""])[1] // if not in gbstr, use blank str
});
}
```
[Answer]
# Ruby, ~~65~~ ~~60~~ 58 bytes
```
->w,s{s.gsub(/\w/){|c|w=~/\b#{c}(\w+)/i;c+($1||c)[1..-1]}}
```
[Try it online!](https://repl.it/CZWG/2)
] |
[Question]
[
## Introduction
The two most common trigonometric functions, `sine` and `cosine` (or `sin` and `cos` for short), can be extended to be matrix-valued functions. One way to compute the matrix-valued analogs is as follows:
Consider these two important trigonometric identities:
$$
e^{i x} = \cos(x) + i \sin(x) \\
\sin^2(x) + \cos^2(x) = 1
$$
Using these identities, we can derive the following equations for `sin` and `cos`:
$$
\sin(x) = \frac{e^{i x} - e^{-i x}}{2 i} \\
\cos(x) = \frac{e^{i x} + e^{-i x}}{2}
$$
The [matrix exponential](https://en.wikipedia.org/wiki/Matrix_exponential) exists for all square matrices and is given by:
$$
e^A = \sum\_{k = 0}^\infty \frac{1}{k!} A^k
$$
where **A0** is the identity matrix **I** with the same dimensions as **A**. Using the matrix exponential, these two trigonometric functions (and thus all the other trigonometric functions) can be evaluated as functions of matrices.
## The Challenge
Given a square matrix **A**, output the values of `sin(A)` and `cos(A)`.
## Rules
* Input and output may be in any convenient, reasonable format (2D array, your language's matrix format, etc.).
* You may write a single program, two independent programs, a single function, or two functions. If you choose to write two functions, code may be shared between them (such as imports and helper functions).
* The input matrix's values will always be integers.
* Your solution may have accuracy issues as the result of floating-point imprecision. If your language had magical infinite-precision values, then your solution should work perfectly (ignoring the fact that it would require infinite time and/or memory). However, since those magical infinite-precision values don't exist, inaccuracies caused by limited precision are acceptable. This rule is in place to avoid complications resulting from requiring a specific amount of precision in the output.
* Builtins which compute trigonometric functions for matrix arguments (including hyperbolic trig functions) are not allowed. Other matrix builtins (such as multiplication, exponentiation, diagonalization, decomposition, and the matrix exponential) are allowed.
## Test Cases
Format: `A -> sin(A), cos(A)`
```
[[0]] -> [[0]], [[1]]
[[0, 2], [3, 5]] -> [[-0.761177343863758, 0.160587281888277], [0.240880922832416, -0.359709139143065]], [[0.600283445979886, 0.119962280223493], [0.179943420335240, 0.900189146538619]]
[[1, 0, 1], [0, 0, 0], [0, 1, 0]] -> [[0.841470984807897, -0.158529015192103, 0.841470984807897], [0, 0, 0], [0, 1, 0]], [[0.540302305868140, -0.459697694131860, -0.459697694131860], [0, 1, 0], [0, 0, 1]]
[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] -> [[0.841470984807897, 0, 0, 0, 0], [0, 0.841470984807897, 0, 0, 0], [0, 0, 0.841470984807897, 0, 0], [0, 0, 0, 0.841470984807897, 0], [0, 0, 0, 0, 0.841470984807897]], [[0.540302305868140, 0, 0, 0, 0], [0, 0.540302305868140, 0, 0, 0], [0, 0, 0.540302305868140, 0, 0], [0, 0, 0, 0.540302305868140, 0], [0, 0, 0, 0, 0.540302305868140]]
[[-3, 2, -6], [3, 0, 4], [4, -2, 7]] -> [[-0.374786510963954, 0.135652884035570, -1.35191037980742], [1.14843105375406, 0.773644542790111, 1.21625749577185], [1.21625749577185, -0.135652884035570, 2.19338136461532]], [[4.13614256031450, -1.91289828483056, 5.50873853927692], [-2.63939111203107, 1.49675144828342, -3.59584025444636], [-3.59584025444636, 1.91289828483056, -4.96843623340878]]
```
## Further Reading
[This excellent question](https://math.stackexchange.com/questions/80324/sina-where-a-is-a-matrix) over at Math.SE includes some alternate derivations of the matrix-valued analogs of trigonometric functions.
[Answer]
# Julia, ~~33~~ 19 bytes
```
A->reim(expm(A*im))
```
This is a function that accepts a 2-dimensional array of floats and returns a tuple of such arrays correponding to the cosine and sine, respectively. Note that this is the reverse of the order given in the test cases, in which sine is listed first.
For a real-valued matrix *A*, we have
[](https://i.stack.imgur.com/tYHRo.gif)
and
[](https://i.stack.imgur.com/CvWDx.gif)
That is, the sine and cosine of *A* correspond to the imaginary and real parts of the matrix exponential *e**iA*. See *Functions of Matrices* (Higham, 2008).
[Try it online!](http://julia.tryitonline.net/#code=Zj1BLT5yZWltKGV4cG0oQSppbSkpCgpmb3IgdGVzdCBpbiAocmVzaGFwZShbMC5dLCAxLCAxKSwKICAgICAgICAgICAgIFswLiAyLjsgMy4gNS5dLAogICAgICAgICAgICAgWzEuIDAuIDEuOyAwLiAwLiAwLjsgMC4gMS4gMC5dLAogICAgICAgICAgICAgWzEuIDAuIDAuIDAuIDAuOyAwLiAxLiAwLiAwLiAwLjsgMC4gMC4gMS4gMC4gMC47IDAuIDAuIDAuIDEuIDAuOyAwLiAwLiAwLiAwLiAxLl0sCiAgICAgICAgICAgICBbLTMuIDIuIC02LjsgMy4gMC4gNC47IDQuIC0yLiA3Ll0pCiAgICBwcmludGxuKGYodGVzdCkpCmVuZA&input=) (includes all test cases)
Saved 14 bytes thanks to Dennis!
[Answer]
# Mathematica, 27 bytes
```
{Im@#,Re@#}&@MatrixExp[I#]&
```
Based on @[Rainer P.](https://codegolf.stackexchange.com/users/48165/rainer-p)'s solution.
Takes the square matrix `A` as an argument and outputs a list containing `{sin(A), cos(A)}`.
The input is formatted with `N` to get a numerical value instead of a long exact formula and `Column` to display the results of `sin(A)` and `cos(A)` as separate matrices instead of a nested list.
[](https://i.stack.imgur.com/mwipn.png)
Calculating the values separately requires **38** bytes
```
{(#2-#)I,+##}/2&@@MatrixExp/@{I#,-I#}&
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~23~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
³æ*÷!
®Ḥ‘©r0Ç€s2_@/µÐL
```
[Try it online!](http://jelly.tryitonline.net/#code=wrPDpirDtyEKwq7huKTigJjCqXIww4figqxzMl9AL8K1w5BM&input=&args=W1swLCAyXSwgWzMsIDVdXQ)
### Background
This approach directly computes the Taylor series for *sine* and *cosine*, i.e.,

It increases the number of initial terms of both series until the result no longer changes, so its accuracy is only limited by the precision of the floating point type.
### How it works
```
®Ḥ‘©r0Ç€s2_@/µÐL Main link, Argument: A (matrix)
µÐL Loop; apply the chain until the results are no longer unique.
Return the last unique result.
® Yield the value of the register (initially zero).
Ḥ Unhalve/double it.
‘© Increment and copy the result (n) to the register.
r0 Range; yield [n, ..., 0].
Ç€ Apply the helper link to each k in the range.
s2 Split the results into chunks of length 2. Since n is always
odd, this yields [[Ç(n), Ç(n-1)], ..., [Ç(1), Ç(0)]].
_@/ Reduce the columns of the result by swapped subtraction,
yielding [Ç(1) - Ç(3) + ... Ç(n), Ç(0) - Ç(2) + ... Ç(n - 1)].
³æ*÷! Helper link. Argument: k (integer)
³ Yield the first command-line argument (A).
æ* Elevate A to the k-th power.
! Yield the factorial of k.
÷ Divide the left result by the right one.
```
[Answer]
# C++, 305 bytes
```
#include<cmath>
#include<iostream>
#include<vector>
int x,i=0, j;void p(std::vector<double> v){int x=sqrt(v.size());for(i=0;i<x;i++){for(j=0;j<x;j++) std::cout << v[x] << " ";std::cout << "\n";}}int main(){std::vector<double> s, c;while(std::cin >> x){s.push_back(sin(x));c.push_back(cos(x));}p(s);p(c);}
```
Input is a list of numbers that are a perfect square on stdin. Output is a pretty printed 2d array on stdout
[Answer]
# Matlab, 37 bytes
```
@(A){imag(expm(i*A));real(expm(i*A))}
```
[Answer]
# Matlab, ~~138 121 52~~ 50 bytes
Since matrix exponentiation is allowed, (what I didnt notice first, d'oh) I do not need to define my helper funciton anymore, and the whole thing can be trivially solved:
```
A=input('')*i;a=expm(A);b=expm(-A);[(b-a)*i,a+b]/2
```
The input should be a matrix e.g. `[1,2;4,5]` or alternatively `[[1,2];[3,4]]`
An unexpected thing (in hindsight not so unexpected) is that the cosine and sine matrix still satisfy
```
I = sin(A)^2+cos(A)^2
```
[Answer]
# Julia 0.4, 28 bytes
```
A->imag({E=expm(im*A),im*E})
```
Input is a matrix of floats, output is an array of matrices. [Try it online!](http://julia.tryitonline.net/#code=ZiA9IEEtPmltYWcoe0U9ZXhwbShpbSpBKSxpbSpFfSkKCmRpc3BsYXkoZihmbG9hdChyZXNoYXBlKFswXSwgMSwgMSkpKSkKcHJpbnQoIlxuXG4iKQpkaXNwbGF5KGYoZmxvYXQoWzAgMjsgMyA1XSkpKQpwcmludCgiXG5cbiIpCmRpc3BsYXkoZihmbG9hdChbMSAwIDE7IDAgMCAwOyAwIDEgMF0pKSkKcHJpbnQoIlxuXG4iKQpkaXNwbGF5KGYoZmxvYXQoWzEgMCAwIDAgMDsgMCAxIDAgMCAwOyAwIDAgMSAwIDA7IDAgMCAwIDEgMDsgMCAwIDAgMCAxXSkpKQpwcmludCgiXG5cbiIpCmRpc3BsYXkoZihmbG9hdChbLTMgMiAtNjsgMyAwIDQ7IDQgLTIgN10pKSk&input=)
[Answer]
## Sage, 44 bytes
```
lambda A:map(exp(I*A).apply_map,(imag,real))
```
[Try it online](http://sagecell.sagemath.org/?z=eJxLs81JzE1KSVRwtMpNLNBIrSjQ8NRy1NRLLCjIqYwHCuloZOYmpusUpSbmaGrycvFypWnkJpYUZVZoREcb6igY6CgYxuooRBuAmQZQJkgiNlZTEwBd6xob&lang=sage).
This anonymous function returns a list of 2 matrices corresponding to `sin(A)` and `cos(A)`, respectively. `exp(I*A)` computes the matrix exponential for `I*A` (`A` with all elements multiplied by the imaginary unit), and `matrix.apply_map(f)` returns a matrix where `f` has been applied to all of its elements. By applying `imag` and `real` (the functions for getting the imaginary and real parts of a scalar value) to the matrices, we get the values of `sin(A)` and `cos(A)`, thanks to Euler's famous identity (referenced in the challenge text).
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 8+9=17 bytes
[cosine](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=aeRl4H5lK70=&in=KDAgMiwzIDUp)
```
iäeà~e+½
```
[sine](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=aeR-ZeBlLb1p&in=KDAgMiwzIDUp):
```
iä~eàe-½i
```
Takes a matrix as input, also works for complex inputs
## Explanation
implements the equations
\$ \sin(x)= i\*\frac{e^{-ix}-e^{ix}}{2}\$
\$ \cos(x)= \frac{e^{ix}+e^{-ix}}{2}\$
```
i ; i times the implicit input
ä ; duplicate
~ ; negate
e ; exponential
à ; swap
e ; exponential
- ; subtract
½ ; half
i ; times i
; implicit output
```
] |
[Question]
[
# Input description
A string (for best results, all characters should be printable and be the same width).
# Output description
A character star following the pattern:
```
0 0 0
1 1 1
222
0123210
222
1 1 1
0 0 0
```
where `0`, `1` ... are subsequent characters of the string. The output does not necessarily have to be one string - printing the star char by char into the console is fine.
# Example
```
>> star('overflow')
>>
o o o
v v v
e e e
r r r
f f f
l l l
ooo
overflowolfrevo
ooo
l l l
f f f
r r r
e e e
v v v
o o o
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~13~~ 10 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
⤢:⁸/n!n↔┼┼
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyOTIyJXVGRjFBJXUyMDc4JXVGRjBGJXVGRjRFJXVGRjAxJXVGRjRFJXUyMTk0JXUyNTNDJXUyNTND,i=b3ZlcmZsb3c_,v=8)
## Explanation
```
⤢:⁸/n!n↔++
⤢ join input with newlines
: duplicate it
⁸ push the input again
/ make a diagonal out of it
n overlap the two
! transpose that result
n overlap with the first duplicated one
↔ mirror it horizontally
++ quad-palindromize without changing characters
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
gI¨„+×.ΛDg;Iθsǝ
```
[Try it online.](https://tio.run/##ASgA1/9vc2FiaWX//2dJwqjigJ4rw5cuzptEZztJzrhzx53//292ZXJmbG93)
**Explanation:**
```
g # Push the length of the (implicit) input-string
I # Push the input-string again
¨ # Remove its last character
„+× # Push string "+×"
.Λ # Use the modifiable Canvas builtin with these three arguments
D # Create a copy of the resulting string
g # Pop and push its length
; # Halve it
Iθ # Push the input, and only leave its last character
s # Swap so the length/2 is at the top of the stack
ǝ # Insert the character at that (floored) index into the Canvas-string
# (after which the result is output implicitly)
```
The Canvas Builtin uses three arguments to draw a shape:
* Character/string to draw: the input minus its last character in this case
* Length of the lines we'll draw: the length of the input in this case
* The direction to draw in: the `"+×"`, which translates to directions `[0,4,4,0,2,6,6,2,1,5,5,1,3,7,7,3]`, where each digit represents a certain direction:
```
7 0 1
↖ ↑ ↗
6 ← X → 2
↙ ↓ ↘
5 4 3
```
So the `+×`/`[0,4,4,0,2,6,6,2,1,5,5,1,3,7,7,3]` in this case translates to the directions \$[↑,↓,↓,↑,→,←,←,→,↗,↙,↙,↗,↘,↖,↖,↘]\$.
Here a step-by-step explanation of how it draws for example input `abcd` with these steps (with the other two Canvas arguments being `4` and `"abc"`):
Step 1: Draw 4 characters (`"abca"`) in direction `0↑`:
```
a
c
b
a
```
Step 2: Draw 4-1 characters (`"bca"`) in direction `4↓`:
```
a
b
c
a
```
Step 3: Draw 4-1 characters (`"bca"`) in direction `4↓`:
```
a
b
c
a
b
c
a
```
Step 4: Draw 4-1 characters (`"bca"`) in direction `0↑`:
```
a
b
c
a
c
b
a
```
Step 5: Draw 4-1 characters (`"bca"`) in direction `2→`:
```
a
b
c
abca
c
b
a
```
Etc., resulting in:
```
a a a
b b b
ccc
abcacba
ccc
b b b
a a a
```
After which we replace the middle `a` with the last character of the input-string with `Dg;Iθsǝ`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~7~~ 4 bytes
```
P*⮌S
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@3NKcks6AoM69Ew8oxJ0dHISi1LLWoOFXDM6@gtCS4BCiTrqGpqWn9/38@UCItJ7/8v25ZDgA "Charcoal – Try It Online") (Link to the verbose version.)
[Answer]
## Pyth, 37 bytes
```
jKm:*;t*2lz[dtlzt_d)*3@zdtlz)pzt_zj_K
```
[Try it here!](http://pyth.herokuapp.com/?code=jKm%3A*%3Bt*2lz%5Bdtlzt_d%29*3%40zdtlz%29pzt_zj_K&input=overflow&debug=0)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~74~~ ~~49~~ 45 [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")
```
{⍵@(⌈x÷2)∘⍉∘(⌽⍵@(2/¨⍳x))⍣2⊢''⍴⍨2⍴x←≢⍵}(⊢,1↓⌽)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71YHjUc9HRWHtxtpPuqY8ai3E0gCRfaCZYz0D6141Lu5QlPzUe9io0ddi9TVH/VuedS7wghIVTxqm/CocxFQYa0GUErH8FHbZKBGzf9pIInevkddzY961wAVHlpv/Kht4qO@qcFBzkAyxMMz@H@agnp@WWpRWk5@uToA "APL (Dyalog Unicode) – Try It Online")
-11 thanks to ovs
Explanation:
```
{⍵@(⌈x÷2)∘⍉∘(⌽⍵@(2/¨⍳x))⍣2⊢''⍴⍨2⍴x←≢⍵}(⊢,1↓⌽)
(⊢,1↓⌽) ⍝ turn "abc" into "abcba"
{ x←≢⍵} ⍝ x is the length of that string (passed as an argument)
''⍴⍨2⍴ ⍝ Generate a blank string of x times x
⍣2⊢ ⍝ Do twice:
⍵@(⌈x÷2)∘⍉∘(⌽⍵@(2/¨⍳x)) ⍝ Update our blank string with our argument (the mirrored string):
⍵@(2/¨⍳x) ⍝ Add our element horizontally, replace with our (mirrored) argument
(⌽ ) ⍝ Rotate vertically
⍉∘ ⍝ Transpose (double rotate, vertical and horizontal)
⍵@(⌈x÷2)∘ ⍝ Add our argument vertically to the string
```
Since we're doing these transposes twice, we'll have rotated our image on all four quadrants.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~155~~ 99 bytes
```
param($a)($r=0..($l=$a.length-2)|%{" "*$_+(,$a[$_]*3-join" "*($l-$_))})
$a+-join$a[$l..0]
$r[$l..0]
```
[Try it online!](https://tio.run/##LY1BCsIwEADv@4oQVklaE4qe8xIpYZHUKmtTVrGH2rfHVrwNw8CMeUry7BOzu2RJBTsV1FxGEnoYJGtQQuO9QQ5IntNwffXuaD@7WStdYazNAemMsa1O7p5vw2bX2GG0drGAVP/01rD3TQsofyoLAOzXn87vJB3nSZcv "PowerShell Core – Try It Online")
56 bytes saved thanks to [@mazzy](https://codegolf.stackexchange.com/users/80745/mazzy)!
## Explanation
```
# Build an array containing the top of the star
($r=0..($l=$a.length-2)|%{" "*$_+(,$a[$_]*3-join" "*($l-$_))})
# Prints the middle line
$a+-join$a[$l..0]
# Prints the array with the top of the star reversed
$r[$l..0]
```
[Answer]
## Perl, ~~97~~ 93 + 2 = 95 bytes
```
$i=y///c-2;push@a,map{$"x$j++.$_.($"x$i--.$_)x2}/.(?!$)/g;say for@a,s/.$//r.reverse,reverse@a
```
Requires `-nlE` flags:
```
$ perl -nlE'$i=y///c-2;push@a,map{$"x$j++.$_.($"x$i--.$_)x2}/.(?!$)/g;say for@a,s/.$//r.reverse,reverse@a' <<< 'overflow'
o o o
v v v
e e e
r r r
f f f
l l l
ooo
overflowolfrevo
ooo
l l l
f f f
r r r
e e e
v v v
o o o
```
Ungolfed:
```
$i=y///c-2;
push @a, map{
$" x $j++ .
$_ .
($" x $i-- . $_)x2
} /.(?!$)/g;
say for @a, s/.$//r.reverse, reverse@a
```
[Answer]
## Seriously, 57 bytes
```
╩╜#dXΣR;╝;lr;R3Z`i' *;(;;))@(((@)' *;)kΣ`M;R@k`'
j`Mi╛╜+@
```
Yes, that newline is supposed to be there. Yes, Seriously still sucks at string manipulation. Hexdump (reversible with `xxd -r`):
```
00000000: cabd 2364 58e4 523b bc3b 6c72 3b52 335a ..#dX.R;.;lr;R3Z
00000010: 6069 2720 2a3b 283b 3b29 2940 2828 2840 `i' *;(;;))@(((@
00000020: 2927 202a 3b29 6be4 604d 3b52 406b 6027 )' *;)k.`M;R@k`'
00000030: 0a6a 604d 69be bd2b 40 .j`Mi..+@
```
I'll update this with an explanation once I finish writing it up. It's kinda long.
[Answer]
## ES6, 153 bytes
```
s=>[...a=(t=[...s.slice(0,-1)]).map((c,i)=>(a=Array(t.length).fill` `,a[i]=c,a.join``+c+a.reverse().join``)),s+t.reverse().join``,...a.reverse()].join`\n`
```
Ungolfed:
```
function star(s) {
r = [];
h = s.length - 1;
for (i = 0; i < h; i++) {
a = [...' '.repeat(h)];
a[i] = s[i];
a = a.concat(s[i]).concat(a.reverse());
r.push(a.join(''));
}
return r.concat(s + [...s.slice(0,h)].reverse().join('')).concat(r.reverse()).join("\n");
}
```
Alternative solution, also 153 bytes:
```
s=>[...a=(t=[...s].reverse().slice(1)).map((c,i)=>(a=Array(l+l+1).fill` `,a[i]=a[l]=a[l+l-i]=c,a.join``),l=t.length),s+t.join``,...a.reverse()].join`\n`
```
Ungolfed:
```
function star(s) {
r = [];
h = s.length - 1;
for (i = 0; i < h; i++) {
a = [...' '.repeat(h + h + 1)];
a[i] = s[i];
a[h] = s[i];
a[h + h - i] = s[i];
r.push(a.join(''));
}
return r.concat(s + [...s].reverse().slice(1).join('')).concat(r.reverse()).join("\n");
}
```
Note: The `\n` inside `s is a literal newline character.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 22 bytes
```
Ṫƛ¥n꘍⁰L‹↲$+&›;$Jvømøm⁋
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%AA%C6%9B%C2%A5n%EA%98%8D%E2%81%B0L%E2%80%B9%E2%86%B2%24%2B%26%E2%80%BA%3B%24Jv%C3%B8m%C3%B8m%E2%81%8B&inputs=Hello&header=&footer=)
```
Ṫ # String[:-1]
ƛ ; # Map...
¥n꘍ # Prepend (register) spaces
⁰L‹↲ # Justify to the left by correct spacing
$+ # Append the correct letter
&› # Increment the register
$J # Append the input value
vøm # Palindromise each
øm # Palindromise
⁋ # Join by newlines
```
[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)
```
¬ÔËiDúEÃhU Ômê û ê
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=rNTLaUT6RcNoVSDUbeog%2byDq&input=Im92ZXJmbG93Ig)
```
¬ÔËiDúEÃhU Ômê û ê :Implicit input of string U > "1234"
¬ :Split > ["1","2","3","4"]
Ô :Reverse > ["4","3","2","1"]
Ë :Map each D at 0-based index E
i : Prepend
DúE : D right-padded with spaces to length E > ["4","3","2 ","1 "]
à :End map > ["44","33","2 2","1 1"]
hU :Replace the first element with U > ["1234","33","2 2","1 1"]
Ô :Reverse > ["1 1","2 2","33","1234"]
m :Map
ê : Palindromise > ["1 1 1","2 2 2","333","1234321"]
û :Centre pad each with spaces to the length of the longest > ["1 1 1"," 2 2 2 "," 333 ","1234321"]
ê :Palidromise > ["1 1 1"," 2 2 2 "," 333 ","1234321"," 333 "," 2 2 2 ","1 1 1"]
:Implicit output joined with newlines
```
[Answer]
# Python 3, 123 bytes
```
def f(s):n=len(s);o=[((s[i]+" "*(n-i-2))*2+s[i]).center(2*n)for i in range(n-1)];print("\n".join(o+[s+s[-2::-1]]+o[::-1]))
```
[Answer]
# [Haskell](https://www.haskell.org/), 72 bytes
```
f(h:t)|_:s<-' '<$t,d<-s++h#s=(h:d)#zipWith(#)d(f t)
f x=[x]
s#t=s:t++[s]
```
[Try it online!](https://tio.run/##DclBCsMgEADAe16xxEAUmw@I/qA99dBDCEFqtkpNIt0thNK/2851oqfnknOtKKNh9Z0N2aGH3nZ8CnYgraMg97@gxCeVW@IohQoSgVWDcLjxmBoS7Miw1iNNdfVpAwerL5cZypuv/Dpv0AFCe9/D8tgztvUH "Haskell – Try It Online")
Defines `f :: String -> [String]`.
[Answer]
# [J](http://jsoftware.com/), 39 38 bytes
```
(' ',|.){~[:(>.*=+.*e.,)"0/~|@i:&.<:@#
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NdQV1HVq9DSr66KtNOz0tGy19bRS9XQ0lQz062ocMq3U9GysHJT/a3KlJmfkK6QpqOeXpRap/wcA "J – Try It Online")
Consider `over`:
First imagine a table of coordinates like:
```
┌───┬───┬───┬───┬───┬───┬───┐
│4 4│4 3│4 2│4 1│4 2│4 3│4 4│
├───┼───┼───┼───┼───┼───┼───┤
│3 4│3 3│3 2│3 1│3 2│3 3│3 4│
├───┼───┼───┼───┼───┼───┼───┤
│2 4│2 3│2 2│2 1│2 2│2 3│2 4│
├───┼───┼───┼───┼───┼───┼───┤
│1 4│1 3│1 2│1 1│1 2│1 3│1 4│
├───┼───┼───┼───┼───┼───┼───┤
│2 4│2 3│2 2│2 1│2 2│2 3│2 4│
├───┼───┼───┼───┼───┼───┼───┤
│3 4│3 3│3 2│3 1│3 2│3 3│3 4│
├───┼───┼───┼───┼───┼───┼───┤
│4 4│4 3│4 2│4 1│4 2│4 3│4 4│
└───┴───┴───┴───┴───┴───┴───┘
```
For each element, ask "Are they equal or does either equal one" `=+.*e.,`? The answer will be 1 if true, 0 otherwise. Multiply that answer by the max of the two numbers `>.*`:
```
4 0 0 4 0 0 4
0 3 0 3 0 3 0
0 0 2 2 2 0 0
4 3 2 1 2 3 4
0 0 2 2 2 0 0
0 3 0 3 0 3 0
4 0 0 4 0 0 4
```
Now just index into the original input, reversed, with a space prepended `(' ',|.){~`:
```
o o o
v v v
eee
overevo
eee
v v v
o o o
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~49~~ 47 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{(⊢⍪1↓⊖)(⊢,0 1↓⌽)⍵@(2/¨⍳a)⊢⍵@a⊢⍉⍵@a⊢''⍴⍨2/a←≢⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q9Z41LXoUe8qw0dtkx91TdMEcXUMFMDcnr2aj3q3OmgY6R9a8ah3c6ImWOlWh0Qw3Qljqqs/6t3yqHeFkX7io7YJjzpBamoB&f=Ky5JLFJQzy9LLUrLyS9XBwA&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=star)
A dfn submission which takes the string as right argument.
-2 borrowing from Ven's answer.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 111 bytes
```
def f(s):l=len(s);r=range(1-l,l);[print("".join([" ",s[~max(i,-i,j,-j)]][i*j**3==j*i**3]for i in r))for j in r]
```
[Try it online!](https://tio.run/##HcbNCgIhEADgV5E5jaJB7CVafBLxsJDWDKYyu/Rz6dVt6/R9/b3dWp1OXca4pKwyrvpcfEl1zyxelnpNeHTFFj2HLlQ3BDhwo4oBFNg1fO7LC8k6smwd6xgDGTZm8p4N7cbcRJGiqkTr3/n/ODJCeyTJpT1Bjy8 "Python 3.8 (pre-release) – Try It Online")
## How it works :
* `s[~max(i,-i,j,-j)]` with `j` the number of the line and `i` the number of the column create this pattern
```
aaaaaaa
abbbbba
abcccba
abcdcba
abcccba
abbbbba
aaaaaaa
```
* The condition `i*j**3==j*i**3` is True exactly if `i = 0` or `j = 0` or `i = ±j` with j the line and i the column. This create this shape:
```
X X X
X X X
XXX
XXXXXXX
XXX
X X X
X X X
```
* `[" ", <char> ][ <condition> ]` will print the char if the condition is true and will print `" "` otherwise. The result is then :
```
a a a
b b b
ccc
abcdcba
ccc
b b b
a a a
```
* `"".join(... for i in r)` will concatenate the previous values to form a line
* `[print(...)for j in r]` will print the line for each line
] |
[Question]
[
Implement a function `divide(int a, int b, int c)` that prints the base 10 value of `a/b`. without using any floating point math nor `BigInteger`/`BigDecimal` or equivalent libraries whatsoever. At least `c` accurate characters within the set of `0123456789.` must be printed, except for the (possible) exception in point 4 below.
1. `a` and `b` may be any 32 bit integers. **Update:** If, for golfing purposes, you would like to have input be 64 bit primitives that is okay, but you do not need to support the whole 64 bit range of data.
2. You do not need to check that `c` is positive (though hopefully your program does not crash) if it's not.
3. The minimum supported upper bound for `c` is `500`. It is okay if your program does not support values of `c` above `500`, but it is also okay if it does.
4. For numbers that divide evenly, it is your choice whether to print extra zeroes (based on the value of `c`) or nothing.
5. You do not need to be able to use the function to do any further tasks with the quotient, the only goal is printing.
6. For numbers between `-1` and `1`, it is your choice whether to print a leading `0`. However, this is the only scenario where printing a leading zero is acceptable, and you may only print one such zero.
7. You may use any rounding / floor / ceil logic you prefer for the last decimal place.
8. For a negative answer, you must print a leading `-`. This does not count towards `c`. However, it is your choice if you wish to print , `+`, or nothing for a positive answer.
9. Integer division and integer modulus are both allowed. However, keep in mind that you are restricted to primitives, unless you choose to implement your own `BigInteger`/`BigDecimal` library which counts against your code length.
10. You do not need to handle `b` being `0`, though you can if you want. Your program may enter an infinite loop, or crash, if `b=0`, and you will not be penalized.
11. Slight rule change per comment. To make sure the playing field is level, while `a` and `b` are guaranteed to be 32 bit integers, you may use 64 bit long integers. If your chosen language goes beyond 64 bit integers as a primitive, you may not at any point use that functionality (pretend it is capped at 64 bits).
12. Another point that is unclear (it shouldn't change any of the current valid answers, though): while `c` may be interpreted as either the number of printed characters or the number of spaces after the decimal, your program must use `c` somehow in a relevant way to decide how many characters to print. In other words, `divide(2,3,2)` should be much shorter output than `divide(2,3,500)`; it is not okay to print 500 characters without regard to `c`.
13. I actually don't care about the name of the function. `d` is okay for golfing purposes.
### Input
Both a function call and reading from `stdin` are accepted. If you read from `stdin`, any character not in the set `[-0123456789]` is considered an argument delimiter.
### Output
Characters to `stdout` as described above.
### Example
for `divide(2,3,5)`, all of the following are acceptable outputs:
```
0.666
0.667
.6666
.6667
0.666
0.667
.6666
.6667
+0.666
+0.667
+.6666
+.6667
```
Another example: for `divide(371,3,5)` the following are all acceptable outputs:
```
123.6
123.7
123.6
123.7
+123.6
+123.7
123.66666
123.66667
123.66666
123.66667
+123.66666
+123.66667
```
And for `divide(371,-3,5)` the following are are all acceptable:
```
-123.6
-123.7
-123.66666
-123.66667
```
[Answer]
# C, ~~98~~ ~~95~~ 89
```
d(a,b,c){if(a>0^b>0)a=-a,printf("-");for(printf("%d.",a/b);c--;putchar(a/b+48))a=a%b*10;}
```
prints `c` digits after the `.`
example output:
```
d(2,3,5);
0.66666
d(-2,3,5);
-0.66666
d(24352345,31412,500);
775.25611231376543995925124156373360499172290844263338851394371577740990704189481726728638736788488475741754743410161721635043932255189099707118298739335285878008404431427479943970457150133706863618999108620909206672609193938622182605373742518782630841716541449127721889723672481854068508850120972876607665860180822615560932127849229593785814338469374761237743537501591748376416656055010823888959633261174073602444925506175983700496625493441996689163377053355405577486310963962816757926906914554947153953
d(-77,12346463,500);
-0.00000623660395693892250760399962321192717298873369644407471192356871761572524859953818352673150196943043525906974329409159530142357369879940514137530724386409289850866600418273638369142644334656816288195250736992448768525852302801215214430238036593962173620088603513411087855687900251270343579371679160258286118056645048869461642577311412993340683886551152342172814999729072204727783171585254821563066280601982932277851559592411203111368818745903178910429650985873444078680671541315111866451144752954
```
should work for -2147483647<=a<=2147483647, same for b. handling the `-` was a pain.
online version: [ideone](http://ideone.com/F0DfHD)
[Answer]
# Java, 92/128
```
void d(long a,int b,int c){if(a<0^b<0){a=-a;p('-');}for(p(a/b+".");c>0;c--)p((a=a%b*10)/b);}<T>void p(T x){System.out.print(x);}
```
I had to improvise so that `a` or `b` could be -2147483648 as positive 32-bit integers only count towards 2147483647, that's why `a` became a `long`. There could be a better way of handling negative results, but I know none (`double`s would probably get [this](https://codegolf.stackexchange.com/revisions/22161/8) to work for `abs(a) < abs(b)` as they have `-0` but only [ones' complement](http://en.wikipedia.org/wiki/Ones%27_complement) would keep the precision).
Why two byte numbers? I needed 92 bytes for the calculation and 36 for the print-helper (`System.out.print` sucks; generally Java isn't that golfy).
```
public class Div {
void d(long a, int b, int c) {
if (a < 0 ^ b < 0) {
a = -a;
p('-');
}
for (p(a / b + "."); c > 0; c--) {
p((a = a % b * 10) / b);
}
}
<T> void p(T x) {
System.out.print(x);
}
public static void main(String[] args) {
final Div div = new Div();
div.d(12345, 234, 20);
div.p('\n');
div.d(-12345, 234, 20);
div.p('\n');
div.d(234, 234, 20);
div.p('\n');
div.d(-234, 234, 20);
div.p('\n');
div.d(234, 12345, 20);
div.p('\n');
div.d(234, -12345, 20);
div.p('\n');
div.d(-234, 12345, 20);
div.p('\n');
div.d(-234, -12345, 20);
div.p('\n');
div.d(-2147483648, 2147483647, 20);
div.p('\n');
div.d(2147483647, -2147483648, 20);
div.p('\n');
}
}
```
The method basically exercises what most of us learned at school to generate the requested decimal digits.
[Answer]
## PHP, 108
```
function d($a,$b,$c){$a*$b<0&&$a*=-print'-';for($p='.';$c--;$a.=0,print$i.$p,$p='')$a-=$b*$i=($a-$a%$b)/$b;}
```
It works by simply outputting the quotient of `a` / `b` during a loop of `c` steps, `a` becoming the remainder multiplied by 10 at each iteration.
[DEMO](http://sandbox.onlinephpfunctions.com/code/31bcb7dff0073ec9a78e564ea73e62456a4c2cf1)
[Answer]
## Python 111
```
f=lambda a,b,c:'-'[a*b>=0:]+'%s'%reduce(lambda(d,r),c:(d%c*10,r+`d/c`+'.'[r!='':],),[abs(b)]*c,(abs(a),''))[-1]
```
This solution does not violates any of the stated rules.
[Answer]
# C: 72 characters
```
d(a,b,c){for(printf("%d.",a/b);c--;putchar((a=abs(a)%b*10)/abs(b)+48));}
```
It almost entirely does what it is supposed to do. However it will as some of the other answers here give wonky values or fail for `d(-2147483648,b,c)` and `d(a,-2147483648,c)` since the absolute value of -2147483648 is out of bounds for a 32-bit word.
[Answer]
# Perl, no arithmetic, 274 bytes
This is Euclidean *long* division, likely to consume an unusual amount of memory. The closest it gets to math on floating-point numbers is in using bit operations to parse them.
```
sub di{($v,$i,$d,$e)=(0,@_);($s,$c,$j)=$i=~s/-//g;$s^=$d=~s/-//g;
$i=~s/\.(\d+)/$j=$1,""/e;$d=~s/\.(\d+)/$c=$1,""/e;
$z=0.x+length($c|$j);$i.=$j|$z;$d.=$c|$z;
($e,$m,$z,$t)=(1.x$e,0.x$i,0.x$d,"-"x($s&1));
for(;$e;$t.="."x!$v,$v=chop$e){$t.=$m=~s/$z//g||0;$m="$m"x10}
print"$t\n"}
```
---
Examples:
```
di(-355,113,238);
di(1.13,355,239);
di(27942,19175,239);
di(1,-90.09,238);
di("--10.0","----9.801",239);
di(".01",".200",239);
```
Output:
```
-3.141592920353982300884955752212389380530973451327433628318
584070796460176991150442477876106194690265486725663716814159
292035398230088495575221238938053097345132743362831858407079
646017699115044247787610619469026548672566371681415929203539
0.0031830985915492957746478873239436619718309859154929577464
788732394366197183098591549295774647887323943661971830985915
492957746478873239436619718309859154929577464788732394366197
183098591549295774647887323943661971830985915492957746478873
1.4572099087353324641460234680573663624511082138200782268578
878748370273794002607561929595827900912646675358539765319426
336375488917861799217731421121251629726205997392438070404172
099087353324641460234680573663624511082138200782268578878748
-0.011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011
1.0203040506070809101112131415161718192021222324252627282930
313233343536373839404142434445464748495051525354555657585960
616263646566676869707172737475767778798081828384858687888990
919293949596979900010203040506070809101112131415161718192021
0.0500000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
```
[Answer]
### Ruby, 178
```
def d(a,b,c)
n=(a<0)^(b<0)
a=-a if n
m=a/b-b/a
l=m.to_s.size-1
g=(a*10**(10+c)/b).to_s
f=m<0?"."+"0"*(l-1)+g[0..c-l-1] : g[0..l]+"."+g[l+1..c-2]
p n ? "-"+f : f
end
```
[Online version](http://ideone.com/fvmcfb) for testing.
The trick is to multiply *a* with a pretty high number, so the result is just an integer multiple of the floating point operation. Then the point and the zeros have to be inserted at the right place in the resulting string.
[Answer]
# python 92 bytes:
```
def d(a,b,c):c-=len(str(a/b))+1;e=10**c;a*=e;a/=b;a=str(a);x=len(a)-c;return a[:x]+'.'+a[x:]
```
i think some more golfing is possible.....
[Answer]
## C 83
```
d(a,b,c){printf("%d.",a/b);for(a=abs(a),b=abs(b);c--&&(a=a%b*10);)putchar(a/b+48);}
```
Same Idea that I used in my python implementation
] |
[Question]
[
Your task – should you choose to accept it – is to build a program that parses and evaluates a string (from left to right and of arbitrary length) of tokens that give directions – either left or right. Here are the four possible tokens and their meanings:
```
> go right one single step
< go left one single step
-> go right the total amount of single steps that you've gone right, plus one,
before you previously encountered this token and reset this counter to zero
<- go left the total amount of single steps that you've gone left, plus one,
before you previously encountered this token and reset this counter to zero
```
There's a catch though – the tokens of directions your program should be able to parse will be presented in this form:
```
<<->-><<->->>->>->
```
... in other words, they are concatenated, and it is your program's task to figure out the correct precedence of directions and amount of steps to take (by looking ahead). The order of precedence is as follows (from highest to lowest precedence):
1. `->`
2. `<-`
3. `>`
4. `<`
If you encounter `<-` when no steps to the left had previously been made since either the start or since the last reset, take one single step to the left. Same rule applies to `->`, but then for going to the right.
**Your program should start at 0 and its result should be a signed integer representing the final end position.**
You may expect the input to always be valid (so, nothing like `<--->>--<`, for instance).
Example input:
```
><->><-<-><-<>>->
```
Steps in this example:
```
step | token | amount | end position
------+-------+--------+--------------
1. | > | +1 | 1
2. | < | -1 | 0
3. | -> | +2 | 2
4. | > | +1 | 3
5. | <- | -2 | 1
6. | < | -1 | 0
7. | -> | +2 | 2
8. | <- | -2 | 0
9. | < | -1 | -1
10. | > | +1 | 0
11. | > | +1 | 1
12. | -> | +3 | 4
```
For clarification: the output of the program should only be the final end position as a signed integer. The table above is just there to illustrate the steps my example took. No need to output such a table, table row, or even just the steps' end positions. Only the final end position, as a signed integer, is required.
Shortest code, after one week, wins.
[Answer]
# GolfScript, 46 chars
```
'->'/')'*.'<-'-.')'/);+,\'>)'-.'<-'/);\'-'-+,-
```
This is one of the most linear GolfScript programs I've ever written — there's not a single loop, conditional or variable assignment in it. Everything is done using string manipulation:
* First, I replace every occurrence of `->` by `)`. Since the input is guaranteed to be valid, this ensures that any remaining occurrence of `-` must be a part of `<-`.
* Next, I make two copies of the string. From the first copy, I remove the characters `<` and `-`, leaving only `>` and `)`. I then duplicate the result, remove all the `)`s and every `>` following the last `)` from the second copy, concatenate them and count the characters. Thus, in effect, I'm counting:
+ +1 for each `)`,
+ +1 for each `>` after the last `)`, and
+ +2 for each `>` before the last `)`.
* Next, I do the same for the other copy, except this time counting `<` and `<-` instead of `>` and `)`, and removing the `-`s before the final character count. Thus, I count:
+ +1 for each `<-`,
+ +1 for each `<` after the last `<-`, and
+ +2 for each `<` before the last `<-`.
* Finally, I subtract the second count from the first one, and output the result.
[Answer]
# Python 2.7 - 154 147 134 128 bytes
```
l=r=p=0
exec"exec raw_input('%s->','p+=r+1;r=0%s<-','p-=l+1;l=0%s>','r+=1;p+=1%s<','l+=1;p-=1;')"%((";').replace('",)*4)
print p
```
*Serious changes have been made to the way this program works. I've removed the old explanation, which can still be found in this answer's edit history.*
This one's gross.
It works pretty much the same way as other answers for this question, replacing the characters in the input with valid statements in that language and executing them. There's one major difference, though: `replace` is a long word. Screw that.
@ProgrammerDan in chat came up with the idea of using a tuple with the string `;').replace('` in it 4 times, to use the pre-`str.format()` method of formatting text. Four instances of `%s` are in the string on the second line, each one taking its value from the associated element of the tuple at the end. Since they're all the same, each `%s` is replaced with `;').replace('`. When you perform the operations, you get this string:
```
exec raw_input(';').replace('->','p+=r+1;r=0;').replace('<-','p-=l+1;l=0;').replace('>','r+=1;p+=1;').replace('<','l+=1;p-=1;')
```
This is now valid python code that can be executed with `exec`. That's right, baby: *Nested `exec`s let me use string operations on code that needs to perform string operations on code*. Someone please kill me.
The rest of it is pretty straightforward: Each command is replaced with code that keeps track of three variables: The current position, the number of rights since the last `->`, and the same for lefts and `<-`. The whole thing is run and the position is printed.
You'll notice that I do `raw_input(';')`, using ';' as a prompt, rather than `raw_input()` which has no prompt. This saves characters in an unintuitive way: If I did `raw_input()`, I'd have to have the tuple filled with `).replace('`, and every instance of `%s` would have ';\'' before it *except the first one*. Having a prompt creates more redundancy so I can save more characters overall.
[Answer]
# Perl, 134 131 ... 99 95 bytes
```
sub f{$p+=$d;$&=~/-/?($p+=$s,$s=0):($s+=$d)}$_=<>;$d=1;s/-?>/f/eg;$s=0;$d=-1;s/<-?/f/eg;print$p
```
Takes input as a single line on stdin, eg:
```
ski@anito:~$ perl -le 'sub f{$p+=$d;$&=~/-/?($p+=$s,$s=0):($s+=$d)}$_=<>;$d=1;s/-?>/f/eg;$s=0;$d=-1;s/<-?/f/eg;print$p'
><->><-<-><-<>>->
4
```
or:
```
ski@anito:~$ echo "><->><-<-><-<>>->" | perl -le 'sub f{$p+=$d;$&=~/-/?($p+=$s,$s=0):($s+=$d)}$_=<>;$d=1;s/-?>/f/eg;$s=0;$d=-1;s/<-?/f/eg;print$p'
4
```
I split the instructions into the "right" operators (">" and "->") and "left" operators ("<" and "<-"). The advantages of this are that it's easier to exploit the parallelism between left and right operators, and we don't have to do anything fancy to tokenize the string. Each "direction" is dealt with as a substitution operation where we adjust the running total by the number of steps taken in that direction, ignoring the reverse direction which is taken care of by the other substitution operation. Here's a less-golfed ancestor of this code as a sort of documentation:
```
sub f {
$dir=shift;
if($1 =~ /-/) {
$pos+=$side+$dir;
$side=0;
} else {
$pos+=$dir;
$side+=$dir;
}
}
$_=<>;
s/(-?>)/f(1)/eg;
$side=0;
s/(<-?)/f(-1)/eg;
print $pos
```
In a prior iteration of this code, the substitutions were all done in one pass. This had the advantage of keeping a direct mapping between $p/$pos and the position that would be returned at any given point in time, but took more bytes of code.
If you want to use() 5.10.0, you can s/print/say/ to shave another 2 characters off the count, but that's not really my style.
[Answer]
## Perl, 88 77 bytes
```
$_=<>;print s/->/F/g+2*s/>(?=.*F)//g+s/>//g-(s/<-/B/g+2*s/<(?=.*B)//g+s/<//g)
```
Input is expected via STDIN, for example:
```
echo '><->><-<-><-<>>->'|perl -e '$_=<>;print s/->/F/g+2*s/>(?=.*F)//g+s/>//g-(s/<-/B/g+2*s/<(?=.*B)//g+s/<//g)'
4
```
## Update
There is no need to convert the string to a summation, because `s//` is already counting. :-)
## First version
```
$_=<>;s/->/+1/g;s/>(?=.*1)/+2/g;s/>/+1/g;s/<-/-1/g;s/<(?=.*-)/-2/g;s/</-1/g;print eval
```
Input is expected via STDIN, example:
```
echo '><->><-<-><-<>>->'|perl -e '$_=<>;s/->/+1/g;s/>(?=.*1)/+2/g;s/>/+1/g;s/<-/-1/g;s/<(?=.*-)/-2/g;s/</-1/g;print eval'
4
```
## Explanation:
The idea is to convert the direction string into a summation so that the result is output by a simple `print eval`.
`>` before any `->` takes two steps, one at once and the other at the next `->`. It does not matter, which of the `->` while it follows at least one of them. The internal counter is reset after the next `->`, thus `>` does not cause further steps, the maximum is two steps. Then `->` adds one step for itself and so do any remaining `>` after the last `->`.
The same holds for the backwards direction with negative instead of positive step counts.
E.g.: `><->><-<-><-<>>->`
`s/->/+1/`: Start with forward direction, because `->` has highest precedence.
E.g.: `><**+1**><-<**+1**<-<>>**+1**`
`s/>(?=.*1)/+2/g`: The look-ahead pattern assures that only the `>` before any `->` are converted.
E.g.: `**+2**<+1**+2**<-<+1<-<**+2+2**+1`
`s/>/+1/g`: Now the remaining `>` are covered.
E.g.: `+2<+1+2<-<+1<-<+2+2+1`
`s/<-/-1/g`: Analog the backwards direction.
E.g.: `+2<+1+2**-1**<+1**-1**<+2+2+1`
`s/<(?=.*-)/-2/g`: In the look-ahead pattern the full `-1` of the former `<-` is not needed, because there are no `-` of the direction symbols left.
E.g.: `+2**-2**+1+2-1**-2**+1-1<+2+2+1`
`s/</-1/g`: The remaining `<` after the last `<-` are converted.
E.g.: `+2-2+1+2-1-2+1-1**-1**+2+2+1`
`print eval`: Calculate and output the result.
E.g.: **`4`**
[Answer]
## Ruby, 141 bytes
```
l=1;r=1;o=0
gets.gsub('->',?R).gsub('<-',?L).chars{|c|case c
when'<';o-=1;l+=1
when'>';o+=1;r+=1
when'L';o-=l;l=1
when'R';o+=r;r=1
end}
$><<o
```
Ungolfed:
```
parsed = gets.gsub('->', 'R')
.gsub('<-', 'L')
countL = 1
countR = 1
result = 0
parsed.each_char do |c|
case c
when '<'
result -= 1
countL += 1
when '>'
result += 1
countR += 1
when 'L'
result -= countL
countL = 1
when 'R'
result += countR
countR = 1
end
end
puts result
```
[Answer]
## D - 243
**Golfed**:
```
import std.regex,std.stdio;void main(string[]a){int s,c,v;auto t=a[1].matchAll("->|<-(?!>)|>|<".regex);foreach(m;t){auto r=m.hit;if(r=="->"){s+=c+1;c=0;}else if(r=="<-"){s-=v+1;v=0;}else if(r==">"){++s;++c;}else if(r=="<"){--s;++v;}}s.write;}}
```
**Un-golfed**:
```
import std.regex, std.stdio;
void main( string[] a )
{
int s, c, v;
auto t = a[1].matchAll( "->|<-(?!>)|>|<".regex );
foreach( m; t )
{
auto r = m.hit;
if( r == "->" )
{
s += c + 1;
c = 0;
}
else if( r == "<-" )
{
s -= v + 1;
v = 0;
}
else if( r == ">" )
{
++s;
++c;
}
else if( r == "<" )
{
--s;
++v;
}
}
s.write;
}
```
[Answer]
# C, ~~148~~ ~~141~~ 140
140:
```
r,l,o;main(char *x,char **v){for(x=v[1];*x;x++)(*x^45)?(*x^60)?(r++,o++):(*(x+1)==45)?(x++,o-=l+2,l=0):(o--,l++):(o+=r+1,r=0,x++);return o;}
```
141:
```
r,l,o;main(char *x,char **v){for(x=v[1];*x;x++)(*x^45)?(*x^60)?(r++,o++):(*(x+1)==45)?(x++,o=o-l-2,l=0):(o--,l++):(o+=r+1,r=0,x++);return o;}
```
148:
```
r,l,o;main(char *x,char **v){for(x=v[1];*x;x++){if(*x^45){if(*x^60)r++,o++;else{o--,l++;if(*(x+1)==45)x++,o-=l,l=0;}}else o+=r+1,r=0,x++;}return o;}
```
With whitespace:
```
r,l,o;
main(char *x,char **v)
{
for(x=v[1];*x;x++)
(*x^45) ?
(*x^60) ?
(r++,o++)
:
(*(x+1)==45) ?
(x++,o-=l+2,l=0)
:(o--,l++)
:(o+=r+1,r=0,x++);
return o;
}
```
Probably a lot more room to golf this. I mostly gave up on trying to manipulate 4 variables in ternaries that captured lvalues (it kept coming out longer and getting later), but not a bad first pass. Pretty straight-forward array pass. Takes input as a command-line argument, outputs via the return value.
You'll need the `-std=c99` flag to compile it with gcc.
**EDIT:**
Yep, it's late - missed some obvious stuff.
[Answer]
# JavaScript, 136
```
z=0;l=r=1;c=["--z;++l;",/</g,"++z;++r;",/>/g,"z-=l;l=1;",/<-/g,"z+=r;r=1;",/->/g];for(a=8;a--;s=s.replace(c[a--],c[a]));eval(s);alert(z)
```
Unminified:
```
s="><->><-<-><-<>>->";
z=0;
l=r=1;
c=[
"--z;++l;", /</g,
"++z;++r;", />/g,
"z-=l;l=1;", /<-/g,
"z+=r;r=1;", /->/g
];
for(a=8;a--;s=s.replace(c[a--],c[a]));
eval(s);
alert(z) // Output (4)
```
## How it works
Given a string input as `s` like so:
```
s="><->><-<-><-<>>->";
```
It uses a Regex to replace each command with a set of instructions which modify `z` (the end position), `l` (stored left movements) and `r` stored right movements. Each Regex is performed in order of precedence.
For the input above this converts `s` to:
```
"++z;++r;--z;++l;z+=r;r=1;++z;++r;z-=l;l=1;--z;++l;z+=r;r=1;z-=l;l=1;--z;++l;++z;++r;++z;++r;z+=r;r=1;"
```
Pretty, ain't it.
Finally we `eval(s)` to perform the instructions and alert `z` which contains the end position.
[Answer]
## Javascript (116, ~~122~~, ~~130~~)
116:
```
for(l=r=p=i=0;c='<>-0'.indexOf(a.replace(/->/g,0)[i++])+1;p--)c-4?c-3?c-2?l++:(r++,p+=2):(p-=l-2,l=0):(p+=r+2,r=0);p
```
122:
```
for(l=r=p=i=0,a=a.replace(/->/g,0);c='<>-0'.indexOf(a[i])+1;i++,p--)c-4?c-3?c-2?l++:(r++,p+=2):(p-=l-2,l=0):(p+=r+2,r=0);p
```
130:
```
for(l=r=p=i=0;c='<>-'.indexOf(a[i])+1;i++,p--)c-3?c-1?(r++,p+=2):a[i+1]=='-'?a[i+2]=='>'?l++:(p-=l,l=0,i++):l++:(p+=r+2,r=0,i++);p
```
[Answer]
## JavaScript [217 bytes]
```
prompt(x=l=r=0,z='replace',f='$1 $2 ')[z](/(>.*?)(->)/g,f)[z](/(<.*?)(<-)/g,f)[z](/(<|>)(<|>)/g,f)[z](/<-?|-?>/g,function(c){c=='>'&&(x++,r++),c=='<'&&(x--,l++),c=='->'&&(x+=++r,r*=0),c=='<-'&&(x-=++l,l*=0)}),alert(x)
```
Probably it may be shortened a bit more...
[Answer]
# PHP, 284 282
No regex.
```
$i=fgets(STDIN);$c=$a=0;$s=str_split($i);while($c<count($s)){switch($s[$c]){case"<":if($s[$c+1]=="-"){if($s[$c+2]==">"){$c+=3;$a+=$rr;$rr=0;$ll++;}else{$c+=2;$a+=-($ll+1);$ll=0;}}else{$c++;$a--;$ll++;}break;case">":$c++;$a++;$rr++;break;case"-":$c+=2;$a+=$rr+1;$rr=0;break;}}echo$a;
```
**Ungolfed:**
```
$i=fgets(STDIN);
$c=$a=0;
$s=str_split($i);
while($c<count($s)){
switch($s[$c]){
case "<":
if($s[$c+1]=="-"){
if($s[$c+2]==">"){
$c+=3;$a+=$rr;$rr=0;$ll++;
}
else{
$c+=2;$a+=-($ll+1);$ll=0;
}
}
else{
$c++;$a--;$ll++;
}
break;
case ">":
$c++;$a++;$rr++;
break;
case "-":
$c+=2;$a+=$rr+1;$rr=0;
break;
}
}
echo $a;
```
[Answer]
## Another perl solution, 113 chars
There are already two answers that beat this, it's just for giggles. It uses an approach based on Ilmari's observation about the value of tokens:
```
$_=<>;chomp;s/->/#/g;s/<-/%/g;s/>(?=.*#)/?/g;s/<(?=.*%)/;/g;s/#/>/g;s/%/</g;$t+=ord for split//;print$t-61*length
```
Exploded a bit:
```
$_=<>;
chomp;
s/->/#/g;
s/<-/%/g;
s/>(?=.*#)/?/g;
s/<(?=.*%)/;/g;
s/#/>/g;
s/%/</g;
$t+=ord for split//;
print$t-61*length
```
] |
[Question]
[
Your function or program should take a year as input and return (or print) the date (in the Gregorian calendar) of that years Easter (not the Eastern Orthodox Easter). The date returned should be formatted according to ISO 8601, but with support for years greater than 9999 (such as *312013-04-05* or *20010130*), and it only needs to work with years greater than or equal to **1583** (the year of the adoption of the Gregorian calendar), and years less than or equal to **5701583** (as that is when the sequence of Easter dates starts to repeat itself).
Examples:
```
e(5701583) = 5701583-04-10
e(2013) = 2013-03-31
e(1583) = 1583-04-10
e(3029) = 30290322
e(1789) = 17890412
e(1725) = 17250401
```
The use of built-in functions for returning the date of easter is boring and therefore disallowed. Shortest answer (in characters) wins.
*Resources:*
* *<http://en.wikipedia.org/wiki/Computus#Algorithms>*
* *<http://web.archive.org/web/20150227133210/http://www.merlyn.demon.co.uk/estralgs.txt>*
[Answer]
## GolfScript (85 chars)
```
~:^100/.)3*4/.@8*13+25/-^19%.19*15+@+30%.@11/+29/23--.@-^.4/++7%97--^[[email protected]](/cdn-cgi/l/email-protection)/100*\31%)+
```
Sample usage:
```
$ golfscript.rb codegolf11132.gs <<<2013
20130331
```
Note that this uses a different algorithm to most of the current answers. To be specific, I've adapted the algorithm attributed to Lichtenberg in the resource linked by [Sean Cheshire](https://codegolf.stackexchange.com/users/5011/sean-cheshire) in a comment on the question.
The original algorithm, assuming sensible types (i.e. not JavaScript's numbers) and with an adaptation to give month\*31+day (using day offset of 0) is
```
K = Y/100
M = 15 + (3*K+3)/4 - (8*K+13)/25
S = 2 - (3*K+3)/4
A = Y%19
D = (19*A+M) % 30
R = (D + A/11)/29
OG = 21 + D - R
SZ = 7 - (Y + Y/4 + S) % 7
OE = 7 - (OG-SZ) % 7
return OG + OE + 92
```
I extracted a common subexpression and did some other optimisations to reduce to
```
K = y/100
k = (3*K+3)/4
A = y%19
D = (19*A+15+k-(8*K+13)/25)%30
G = 23+D-(D+A/11)/29
return 97+G-(G+y+y/4-k)%7
```
This approach has slightly more arithmetic operations than the other one (Al Petrofsky's 20-op algorithm), but it has smaller constants; GolfScript doesn't need to worry about the extra parentheses because it's stack-based, and since each intermediate value in my optimised layout is used precisely twice it fits nicely with GolfScript's limitation of easy access to the top three items on the stack.
[Answer]
# Python 2 - 125 120 119 chars
This is [Fors's answer](https://codegolf.stackexchange.com/a/11146/2621) shamelessly ported to Python.
```
y=input()
a=y/100*1483-y/400*2225+2613
b=(y%19*3510+a/25*319)/330%29
b=148-b-(y*5/4+a-b)%7
print(y*100+b/31)*100+b%31+1
```
**Edit**: Changed last line from `print"%d-0%d-%02d"%(y,b/31,b%31+1)` to save 5 characters. I would have loved to represent `10000` as `1e4`, but that would produce floating point necessitating a call to `int`.
**Edit2**:
Thanks to Peter Taylor for showing how to get rid of that `10000` and save 1 character.
[Answer]
# PHP 154
**150** chars if I switch to YYYYMMDD instead of YYYY-MM-DD.
```
<?$y=$argv[1];$a=$y/100|0;$b=$a>>2;$c=($y%19*351-~($b+$a*29.32+13.54)*31.9)/33%29|0;$d=56-$c-~($a-$b+$c-24-$y/.8)%7;echo$d>31?"$y-04-".($d-31):"$y-03-$d";
```
With Line Breaks:
```
<?
$y = $argv[1];
$a = $y / 100 |0;
$b = $a >> 2;
$c = ($y % 19 * 351 - ~($b + $a * 29.32 + 13.54) * 31.9) / 33 % 29 |0;
$d = 56 - $c - ~($a - $b + $c - 24 - $y / .8) % 7;
echo $d > 31 ? "$y-04-".($d - 31) : "$y-03-$d";
```
Useage: `php easter.php 1997`
Output: `1997-03-30`
Useage: `php easter.php 2001`
Output: `2001-04-15`
[Answer]
# dc: 106 characters
```
?[0n]smdndsy100/1483*ly400/2225*-2613+dsa25/319*ly19%3510*+330/29%sb148lb-5ly*4/la+lb-7%-d31/0nn31%1+d9>mp
```
Usage:
```
> dc -e "?[0n]smdndsy100/1483*ly400/2225*-2613+dsa25/319*ly19%3510*+330/29%sb148lb-5ly*4/la+lb-7%-d31/0nn31%1+d9>mp"
1725
17250401
>
```
This should be able to be shortened by using 'd' and 'r' instead of all the loads and stores.
[Answer]
# C: 151 148 characters
```
y;a;b;main(){scanf("%d",&y);a=y/100*1483-y/400*2225+2613;b=(y%19*3510+a/25*319)/330%29;b=148-b-(y*5/4+a-b)%7;printf("%d-0%d-%02d\n",y,b/31,b%31+1);}
```
And the same code, but better formatted:
```
#include <stdio.h>
int y, a, b;
int main() {
scanf("%d", &y);
a = y/100*1483 - y/400*2225 + 2613;
b = (y%19*3510 + a/25*319)/330%29;
b = 148 - b - (y*5/4 + a - b)%7;
printf("%d-0%d-%02d\n", y, b/31, b%31 + 1);
}
```
There are frightfully many algorithms for calculating the date of Easter, but only a few of them are well suited for code golfing.
[Answer]
# Javascript 162 156 145
```
function e(y){alert(y+"0"+((d=56-(c=(y%19*351-~((b=(a=y/100|0)>>2)+a*29.32+13.54)*31.9)/33%29|0)-~(a-b+c-24-y/.8)%7)>(f=31)?4:3)+(d-f>0&d-f<10?0:"")+(d>f?d-f:d))}
```
Inspired by @jdstankosky's PHP solution...
Provides YYYYMMDD result...
Now narrowed down to:
```
alert((y=prompt())+0+((d=56-(c=(y%19*351-~((b=(a=y/100|0)>>2)+a*29.32+13.54)*31.9)/33%29|0)-~(a-b+c-24-y/.8)%7)>(f=31)?4:3)+(d-f>0&d-f<10?0:"")+(d>f?d-f:d))
```
Now asks for input... reduced literal string of "0" to 0 and let loose typing work to my advantage! :)
Reduced further to take ES6 into account...
`e=y=>y+"0"+((d=56-(c=(y%19*351-31.9*~((b=(a=y/100|0)>>2)+29.32*a+13.54))/33%29|0)-~(a-b+c-24-y/.8)%7)>(f=31)?4:3)+(d-f>0&d-f<10?0:"")+(d>f?d-f:d)`
[Answer]
## APL 132
This algorithm calculates the number of days Easter lies relative to the beginning of March. The date is returned in the YYYYMMDD format as allowed in the question:
```
E y
(a b)←⌊((3 8×⌊y÷100)+¯5 13)÷4 25
c←7|y+(⌊y÷4)-a-e←⌊d-((19×d←30|(227-(11×c)-a-b))+c←19|y)÷543
+/(10*4 2 0)×y,(3+i>31),(61⍴⍳31)[i←e+28-c]
```
Taking the original test cases:
```
E 2013
20130331
E 1583
15830410
E 3029
30290322
E 1789
17890412
```
[Answer]
# Javascript 134 Characters
Using a slightly modified Al Petrofsky's 20-op algorithm to allow a simpler conversion into the year-month-date format.
This provides additional 14 characters shorter code from the answer provided by [WallyWest](https://codegolf.stackexchange.com/users/8555/wallywest)
## The Original Al Petrofsky's Code:
```
a =Y/100|0,
b =a>>2,
c =(Y%19*351-~(b+a*29.32+13.54)*31.9)/33%29|0,
d =56-c-~(a-b+c-24-Y/.8)%7;
```
Last line changed to:
```
d =148-c-~(a-b+c-24-Y/.8)%7;
```
## 1. 138 Characters With the format YYYY-MM-DD
```
e=y=>(c=(y%19*351-31.9*~((b=(a=y/100|0)>>2)+29.32*a+13.54))/33%29|0,d=148-c-~(a-b+c-24-y/.8)%7,y+'-0'+(d/31|0)+"-"+((o=d%31+1)>9?o:'0'+o))
console.log(e(2021));
console.log(e(2022));
console.log(e(5701583));
console.log(e(2013));
console.log(e(1583));
console.log(e(3029));
console.log(e(1789));
console.log(e(1725));
```
## 2. 134 Characters With the format YYYYMMDD
```
e=y=>(c=(y%19*351-31.9*~((b=(a=y/100|0)>>2)+29.32*a+13.54))/33%29|0,d=148-c-~(a-b+c-24-y/.8)%7,y+'0'+(d/31|0)+((d=d%31+1)>9?d:'0'+d))
console.log(e(2021));
console.log(e(2022));
console.log(e(5701583));
console.log(e(2013));
console.log(e(1583));
console.log(e(3029));
console.log(e(1789));
console.log(e(1725));
```
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 179 bytes
```
READ*,I
J=I/100*2967-I/400*8875+7961
K=MOD(MOD(I,19)*6060+(MOD(MOD(J/25,59),30)+23)*319-1,9570)/330
L=K+28-MOD(I*5/4+J+K,7)
WRITE(*,'(I7,I0.2,I0.2)')I,(L-1)/31+3,MOD(L-1,31)+1
END
```
[Try it online!](https://tio.run/##NYvBDoIwEETv/RG67dbutpbSAwcTOBRQE2Li2QveNCH@PwLGw0zeTPKm9/yZHy/znH6wLGN7ahRm0dXZMpFyqYwm2@OKVRWDjqlk0dfnayO3ZOQEqqSStPx/nXUBQwL0BNp5UJ6TYUwhEljvSQx1r11ldl8Fe9Sd7jGCuI/51kqFhcwRMx3cXlBARjkYXmXWHjdtXegZNIv20iyLI66@ "Fortran (GFortran) – Try It Online")
Uses the "Emended Gregorian Easter" algorithm (Al Petrofsky) from the second resource link. Strangely, it fails for year 5701583 (and, apparently, only for this year), predicting the Easter as one week earlier. Prints the date in `YYYYYYYMMDD` format, with some leading spaces if the year has less then seven digits.
] |
[Question]
[
**Closed**. This question is [opinion-based](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it can be answered with facts and citations by [editing this post](/posts/197/edit).
Closed 6 years ago.
[Improve this question](/posts/197/edit)
Can you recommend any freely available books about code golfing in general and especially in Java and C++?
[Answer]
There are at least two books about golfing:
* "Short Coding" by Ozy (only available in Japanese I think, search for it on [www.amazon.co.jp](http://www.amazon.co.jp))
* The Perlgolf History book, available [here](http://terje2.frox25.no-ip.org/).
Other recommended reading:
* Andrew Savige's (eyepopslikeamosquito) articles on golf, accessible from his node on [perlmonks](http://www.perlmonks.org/?node_id=176576)
* The language specific forums over on [codegolf.com](http://codegolf.com/boards/board)
* The solutions to finished challenges on [golf.shinh.org](http://golf.shinh.org/all.rb) (look for "post-mortem").
[Answer]
[Mark Byers](https://stackoverflow.com/users/61974/mark-byers) maintains a [golfing tips](https://sites.google.com/site/codegolfingtips/Home) site. It's not a book per se, but, you may find some gems there!
[Answer]
When it comes to golfing in Java, it's not to be recommended.
Actually, I would go so far as to say (paraphrasing E. W. Dijkstra) that it cripples the mind, and therefore should be regarded as a criminal offense.
If you insist on doing codegolf in Java, all the basic stuff you need is found in java.util.Scanner (parsing input), java.math.BigInteger, and java.lang.String. In addition, the syntax for regexes and print formatting will come in handy.
[Answer]
"the zen of optimization" by Michael Abrash has a few sections on optimizing assembly code for size. I remember there was a chapter where he squeezed every spare byte out of a ridiculously small sort function.
] |
[Question]
[
What is the **shortest sequence** of moves that, from the solved state of the cube, creates a pattern that meets the following criteria:
* 6 colors on each face
* at most 2 facelets of the same color
* no adjacent facelets of the same color
EDIT: I made up the name of the pattern. I asked [this question](https://math.stackexchange.com/q/2971036/560881) in 2018 on Mathematics Stack Exchange and forgot about it. Thanks to [uhoh](https://math.stackexchange.com/users/284619/uhoh) for suggesting Code Golf. Who knows when I would have discovered this awesome community!
---
\* In the Rubik's world, an algorithm is a sequence of moves, like: L, R, U, D, F, B etc.
[Answer]
# Seven Face Turns
```
U D2 F2 B2 R L U'
```
With yellow (Y) at the top, red (R) at the front and green (G) at the right (with their opposites white (W), orange (O), and blue (B) respectively) that produces the net:
```
O R G
W Y W
B O R
W R Y O G B W O Y R B G
G B R Y R W B G O Y O W
O G B W G Y R B G W B Y
O Y B
R W O
G Y R
```
Here is Python code that finds this solution.
**[Try it online!](https://tio.run/##nVhtb9s2EP6uX8EpGCotbhrJclIIy7A0ibEArT0kTr8YhkDbVKxWEl2KSuoN@@3ZkZQtUaIbb/6QWtTdc3cP761eb/iK5v33a/byEjOaoSXmeJHioiAFSrI1Zbw@sizrCH2iTwTFZb7gCc0L5OSUI74iKE8WpICvFDGCl2heyuMNWlL5@gudu9aSxOjBKTjmxA0tBB9GeMlyNJUP4iNfTk9n07Nwho7rx/Bs1msJ@XDar4W82bQfdoQCXcg3CvU7JwNdLTCqebrQoCE0A65EtMMDow0DDccPB1r050bjTYo8I0WSx3MtfA/EmtCBmdmz8L2mFnr1Y38P0yYSfU2tRdegTdfdoXT5WuRtugbmu9J90ZQ8o5Kvc@wbOe7ryIGuE3SoM9iR1zDQlNrX5IcmfnX2rg9jz0SNnn5BM2c8Y/r5upLXUvKNSn2dm76Rz0BH9lvIgRF5oCsFLaVBQ2nL1odD2PK7yWVsBCZ69HRr0zMw0tO6iCZbg04mnRvbXTv7jF3Bb1ViO93AeZ2tj4ewFbTy@LQFHJjz@FSPzOu6c2ZKQFMe6wRpMJ4RJuhcVDtDPc3/gTH32vd01mDvCI1wBtOUxnIQZvr8xHN47qE4YTA8cc6TRUoXX5@TgiDMaJkvEc0JWlCWE4beoofhHQACTi7@JAzR9ZoWSf6IYgzzFzkddWFTCfEtjgtA1x8@WsPLq5t7dIFsQIVn2xpF4ij68/L2TpynJHekjIvevUO@ZX0af76Jhg@jq8nteCQkpuQJp07sopgyFKMkR1Iewr4bTy6FVHQ7ur69upyMJaJj2z1k@@LPG9vdCYlXvFynpHY/@lZixgkrJHT3uAfGlskCc3gLZkleZoQB/Y7BcE/cDOMXnuta1hBim8g476PJOJo83I2EY/LgBDDJd8d@sN2ei9CR4n5FYbVB5VrsNsUmywhnG@RgNk84w2zjWvc3V@PR9SuY14CJtJOh7Uoj/JlWRoqOFeHA9vZ60h28/AI3nXMI5X788fPNdXQPAd@Iy5gmM/QLei8ZSwQrDOePxKmv0d1W8xbEEVkTeT2ZPZGvV7d6h35GWlr8dFEJt14A8u@7TdFxLfmv3BYVqFAKwSmuTFCoFSgAdaKceiR5JKojKsi3kuRAh7Mka76qvEpiJB/Rb@g03JWgiFVTEnHvQ4K899xat0IV/GjSLpjwdLFtBIW417hO9w7DHa2mpViwp5mavvVmJwJ4vx6GInZMmv5rmvIDnu5u22y6twfYfQX5B@@7r0RGRQWnayCwr70lqfkOLi5@dAmmmvtPRguyH9zQI36I7WtvZXJglYkS0WAIRGSNgciuCU7DHeYsNHK7SUi6bKX7MZqKInPUTQoEqPJuiEp1OtvVGo/kuGqxrhSeBMGN5mLtKk04rGnoldjoOtnJtsZbFSfA9UEyzWS@zZwnt9l/nipf1wx6hF7PRq@lnPMGvTn5QpOqIKdCUKEDU4bZoAS2rooGMdv1lE6wYn5Il5IiWmGWwjEYai5Gzbvv9IaahyMk6pGJgZzSEqyVMP3F/6Tn0OBhmi0fiYRJCa9ErGYbqQyofUMGB6sOrDE60RWNQwyJ0LC87QZgL39buVHZKmpHVhjiF7tDAcuLwQecbxwsanQuY8Y9@AIu/ZWsnYZbvZaP9ZakTmC5ct2DvJYxS@@kZzhNK6cKq9XKC8KbLogCkV9g2P7aWGkOsjqiKCdkKWbyYkUWX9UGh78nWZmBzprwRK1xIBAn1baldjn7j22C2CjhqCAkg6VF/CwCfsLBM2GkmRDy1xcIKSXVZlj9@nIFWxwsPEJE5iRYEk0HtsmMLsu06S0Ag29OpaFIqMM/gVWthEnoivHmN00bCagOJqwkVdJnGJK94k2NU@jQ8ul5laREndW4qhxjuyCYLVZiRcUc/S2FLv6x3f83wbvTWyvFfW3N7fbT17tKR2XOCP5q7R8hipTjLSvbz4LCWp@X9U0pHMsC76Moh/qKIlFJdhQJiqPIVrCKb@vl5V8 "Python 3.8 – Try It Online")**
```
from dataclasses import dataclass
# Move functions (not the nicest to read but they do the job)
def U(state):
return [
state[0][6:] + state[0][:6],
state[2][:3] + state[1][3:],
state[4][:3] + state[2][3:],
state[3],
state[5][:3] + state[4][3:],
state[1][:3] + state[5][3:],
]
def F(state):
return [
state[0][:4] + state[5][2:5] + state[0][7:],
state[1][6:] + state[1][:6],
state[0][6:7] + state[2][1:6] + state[0][4:6],
state[2][6:8] + state[2][:1] + state[3][3:],
state[4],
state[5][:2] + state[3][:3] + state[5][5:],
]
def R(state):
return [
state[0][:2] + state[1][2:5] + state[0][5:],
state[1][:2] + state[3][2:5] + state[1][5:],
state[2][6:] + state[2][:6],
state[3][:2] + state[4][6:] + state[4][:1] + state[3][5:],
state[0][4:5] + state[4][1:6] + state[0][2:4],
state[5],
]
def D(state):
return [
state[0],
state[1][:4] + state[5][4:7] + state[1][7:],
state[2][:4] + state[1][4:7] + state[2][7:],
state[3][6:] + state[3][:6],
state[4][:4] + state[2][4:7] + state[4][7:],
state[5][:4] + state[4][4:7] + state[5][7:],
]
def B(state):
return [
state[2][2:5] + state[0][3:],
state[1],
state[2][:2] + state[3][4:7] + state[2][5:],
state[3][:4] + state[5][6:] + state[5][:1] + state[3][7:],
state[4][6:] + state[4][:6],
state[0][2:3] + state[5][1:6] + state[0][:2],
]
def L(state):
return [
state[4][4:5] + state[0][1:6] + state[4][2:4],
state[0][:1] + state[1][1:6] + state[0][6:],
state[2],
state[1][:1] + state[3][1:6] + state[1][6:],
state[4][:2] + state[3][6:] + state[3][:1] + state[4][5:],
state[5][6:] + state[5][:6],
]
# Names of the move functions above, first anticlockwise around one corner - UFR
# then their opposing faces (clockwise around the opposite corner) - DBL
FACES = "UFRDBL"
N_FACE_PAIRS = len(FACES) // 2
MOVE_FUNCTIONS = [eval(f) for f in FACES]
ROTATION_INDICATORS = ("", "2", "'")
ROTATIONS = tuple(clockwise_quarters for clockwise_quarters, indicator in enumerate(ROTATION_INDICATORS, start=1))
FIRST_FACES_TO_TURN = (FACES.index("U"),) # one choice up to symmetry (arbitrary)
SECOND_FACES_TO_TURN = (FACES.index("D"), FACES.index("F")) # two choices up to symmetry (one opposite, one adjacent)
SOLVED_STATE = [[i] * 8 for i in range(len(FACES))]
def adjacent(face_1, face_2):
return face_1 % N_FACE_PAIRS != face_2 % N_FACE_PAIRS
@dataclass()
class Move:
face: int
rotation: int
def gen_move_sequences(depth):
if depth > 0:
for move_sequence in gen_move_sequences(depth - 1):
if len(move_sequence) > 1:
faces = (f for f in range(len(FACES))
if f != move_sequence[-1].face
and (f != move_sequence[-2].face
or adjacent(move_sequence[-1].face, move_sequence[-2].face)
)
)
turn_stop = 3
elif len(move_sequence) == 1:
faces = SECOND_FACES_TO_TURN
turn_stop = 3
else:
faces = FIRST_FACES_TO_TURN
turn_stop = 2
for face in faces:
for turn in ROTATIONS[:turn_stop]:
yield move_sequence + [Move(face, turn)]
else:
yield []
def get_state(move_sequence):
v = SOLVED_STATE
for m in move_sequence:
for i in range(m.rotation):
v = MOVE_FUNCTIONS[m.face](v)
return v
def print_move_sequence(move_sequence):
print(' '.join(FACES[move.face] + ROTATION_INDICATORS[move.rotation - 1] for move in move_sequence))
def is_harlequin(state):
for face in range(len(FACES)):
# centre colour must not be an edge facelet colour
if face in state[face][1::2]:
return False
# adjacent non-centre facelets must not have the same colour
if any(a == b for a, b in zip(state[face], state[face][1:] + state[face][:1])):
return False
# face must have all colours
if len(set(state[face] + [face])) < len(FACES):
return False
# No need to check the maximum repetitions to find the first "Harlequin" it seems, but if it were:
# from collections import Counter # move to top of module
# if max(Counter(state + [face]).values()) > 2:
# return False
return True
def main():
depth = 1
while depth:
print(f"searching at {depth=}")
for move_sequence in gen_move_sequences(depth):
if is_harlequin(get_state(move_sequence)):
print_move_sequence(move_sequence)
break
else:
depth += 1
continue
break
if __name__ == "__main__":
main()
```
[Answer]
While I was was sieving through hundreds of patterns, using Herbert Kociemba's [Cube Explorer](http://kociemba.org/cube.htm), I stumbled upon a pattern, shown in the animation\* below, that can be generated by a 15-move algorithm. But I don't know if this is the shortest algorithm which generates a harlequin pattern.
[](https://i.stack.imgur.com/xR5h4.gif)
D' F L2 D F U2 B U' R' L F B L2 D L'
---
**UPDATE – I found another one!**
F R B D B F2 R2 U2 L' F' L D2 B R2 U
Today I decided to systematically search for the shortest harlequin algorithm using Kociemba's program. I started by manually counting the number of harlequin search patterns to be used in the Pattern Editor. There are 7 ways to arrange the first 2 facelets of the 1st color (excluding rotation symmetry):
[](https://i.stack.imgur.com/cGZ58.jpg)
For patterns 1 and 5 there are only 13 ways to arrange the next 2 facelets of the 2nd color:
[](https://i.stack.imgur.com/tUGRr.jpg)
For patterns 2, 6 and 7 there are 15 ways to arrange the 2nd color facelet pair. For patterns 3 and 4 there are 14 ways.
So, there are 99 ways in which the first 4 facelets can be arranged.
For pattern 1 I counted 80 ways in which the 3rd color facelet pair can be placed. Because the colors of the search pattern only tell the program the structure of the pattern and not the actual colors to be searched, it doesn't matter how we color the last 3 facelets as long as each has a unique color. So there are 80 search patterns that begin with pattern 1. Pattern 2 is the starting point for 110 search patterns. Pattern 3 generates 94 search patterns. But I ran into a roadblock. Some search patterns produce 7 results, some 164 and some... OVER 9000!!
[](https://i.stack.imgur.com/sEB7d.jpg)
I had to stop the program after letting it run for more than 24 hours. It was still searching for patterns.
Obviously, it is unfeasible to manually search for the shortest harlequin generator. I hope someone will find a better way to answer this question. I understand that the number of harlequin patterns may be so large that it renders such patterns as... not so special to worth the effort of investigating. I don't know enough math to go any further.
I am still interested in a mathematical solution to this puzzle.
---
\* GIF created using [Rubik's Cube Explorer](http://iamthecu.be/) and [VirtualDub](http://www.virtualdub.org/).
] |
[Question]
[
# Barbrack
Your task is to write a program or function that takes a non-negative integer (in decimal or any other convenient base for your language), and output a number in the numbering system **Barbrack**.
## What's that?
Barbrack is a numbering system I made up that can represent non-negative integers. Zero is represented with an empty string or an underscore, one is represented with [], and all other positive integers can be represented with a **brack**.
A **brack** is delimited with brackets [] and works as follows (with an example of 84):
1. Take your number a and find its prime factorization. In this case, the prime factorization of 84 is 22\*31(\*50)\*71.
2. Find the indices of these primes, where the index of 2 is 1. In this case, the index of 3 is 2, since it's the prime right after 2; and the index of 7 is 4, since it's the fourth prime.
3. Take the exponents of each prime, and put them in brackets in increasing order of the size of the prime, with consecutive exponents being separated by bars (|). So the general format is [exponent of 2|exponent of 3|exponent of 5…]—in this case, [2|1|0|1]. **Minimize the number of cells!**
4. Recursively calculate the exponents in Barbrack, remembering that 0 is the empty string and 1 is []. So [2|1|0|1] => [[1]|[]||[]] => [[[]]|[]||[]].
5. Output the final result.
## Test inputs
```
0 -> (nothing)
1 -> []
2 -> [[]]
5 -> [||[]]
27 -> [|[|[]]]
45 -> [|[[]]|[]]
54 -> [[]|[|[]]]
84 -> [[[]]|[]||[]]
65535 -> [|[]|[]||||[](48 bars)[]]
65536 -> [[[[[]]]]]
```
(sidenote: (48 bars) means 48 consecutive bars in the actual output)
## Rules
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* No input in Barbrack! This isn't a cat challenge!
* You may replace [] with any other paired delimeter, like () or {}. However, the vertical bars need to be actual vertical bars.
* Whitespace is not allowed within the number, but is allowed outside of it (for example, a trailing newline).
* The program should be able to fully parse any number given infinite time and memory.
## Scoring
Scores are counted by minimum bytes on a per-language basis.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ÆE߀j”|Ø[jxẸ
```
[Try it online!](https://tio.run/##y0rNyan8//9wm@vh@Y@a1mQ9aphbc3hGdFbFw107/ls/apijoGunABS0PtzOdbgdqCLy/38DHUMdIx1THRNTHQsTHTNTU2NTMGkGAA "Jelly – Try It Online")
A monadic link that takes an integer as its argument and returns a string.
## Explanation
```
ÆE߀j”|Ø[jxẸ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌­
ÆE # ‎⁡Prime exponents
߀ # ‎⁢Current (main) link for each member of the list of exponents
j”| # ‎⁣Join with the bar character
Ø[j # ‎⁤Wrap in square brackets
xẸ # ‎⁢⁡Repeat once if original argument was non-zero else repeat zero times (effectively preserves current value if argument was non-zero else returns empty list)
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
## Conversion back from barbrack
## [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ṖḊṣ”|߀ÆẸµ0¹?
```
[Try it online!](https://tio.run/##y0rNyan8///hzmkPd3Q93Ln4UcPcmsPzHzWtOdz2cNeOQ1sNDu20/3@4zRUslgWWnRGdVQGU47J@1DBHQddOAShofbgdmWd4ZP@xTSpch9uBeiL//zfQMdQx0jHVMTHVsTDRMTM1NTYFk2YA "Jelly – Try It Online")
A monadic link that takes a string and returns an integer. The TIO link converts to barbrack and then back.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
λ[∆Ǐvx\|jøB|¤
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwizrtb4oiGx492eFxcfGrDuEJ8wqQiLCIiLCIxXG4yXG41XG40NVxuODQiXQ==)
```
λ # Define a recursive lambda
[ # If the input is nonzero
x # Recurse on
v # Each of
∆Ǐ # The prime exponents of n
\|j # Join by |
√∏B # And wrap in []
[ |¤ # Else, if it's zero, return the empty string.
```
[Answer]
# [Python](https://www.python.org), 113 bytes
```
def f(n):
P=i=2;r=''
while w:=n>1:
while n%i<1:n//=i;w+=1
r+=P%i*'|'+f(w-1);P*=i*i*2;i+=1
return'[%s]'%r*n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9NDoIwFIT3nuJtSEspwaIlBizxCOyNO2l4iXlixYBBTuKGjd7J2_i_mWQyk_ky13t9bqo9jePt1Nhw8ThsSwuWk59OoDBo4swZxibQVrgroU0N5eoV_Tx5uFQpRZHBrA2MegUuMIWHgl1YYHkbKj8rhEGBIs7w03Blc3LE1t5xwzwn6Ade2b2DDpBgKpWMpZZzLRdzmWg90x9N3tzaITXcsr5Lcz1AmENveecPzP_u_I88AQ)
[Answer]
# JavaScript (ES6), 96 bytes
```
f=(n,q=1)=>n?q>n?"]":["|["[(g=d=>q%d--?g(d):q<3|-d)(q++)]]+f((g=_=>n%q?0:1+g(n/=q))())+f(n,q):""
```
[Try it online!](https://tio.run/##bcxBCoMwEAXQfY8REGZI02o1UkKjBxEpYjRYJOnU0pV3T7Mt6WI27/8/j@EzbONreb6F82YKYdbgjqQL1I1rKR7rmerY3rEOrDa6ocwI0VowqOhW7sIgEOfY93yG2LjHXUZtrgpuwZ01IQJizOJXVIyF0bvNr9Np9RZmyBEPv1IkcklEJlKldK0SqqUs5V@tEcMX "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 196 bytes
```
n#f|n`mod`f==0=1+(n`div`f)#f|0<1=0
p 1=[]
p n=(:)<*>p.div n$until((<1).mod n)(+1)2
f 0=""
f 1="[]"
f n='[':concat(init$filter(\n->mod(product[1..n-1]^2)n>0)[2..maximum.p$n]>>=(:["|"]).f.(n#))++"]"
```
[Try it online!](https://tio.run/##HU7dasMgGL3vU4gN1K@xollTRom@wZ7AORKSyqTxS@jM2EXf3bndnHPg/HA@h6/7bZ5zxr1/Yh@XqfdaS61qhv0UvnsPxZCd0nK3EqWtK4SaXaE7mlWUBMFqwxRmxjoFogwQBFYraHaeSE1pIaWpdX8C9cEeruOC45BYwJAqH@Z0e7B3PJlSZetjmbYxWSUEnpT7aACNBNsIEYefELco1gqdMeWApU/qQHjBcA9Q19TRHIeARJM4rG@kbAVMwgOxkive8JafW/565pe2fWn/8eJy/gU "Haskell – Try It Online")
[Answer]
# Python3, 227 bytes
```
R=range
def f(n):
if n<2:return'[]'*n
d,K={},{}
while n>1:
for i in R(2,n+1):
if(i==2 or all(i%j for j in R(2,i))):
K[i]=1
if 0==n%i:n//=i;d[i]=d.get(i,0)+1;break
return'['+'|'.join(f(d.get(i,0))for i in K)+']'
```
[Try it online!](https://tio.run/##XY7BjoIwFEX3/Yq3MW2FqEUxBqf@ADu3hgWGVh9DHqRhMpk4fjtWDdq4Ozf35L7X/fXnlpabzg3DXruSToZVxoIVJDMGaIG@ksyZ/scRPxR8SgyqONeXa3y5Mvg9Y2OAdsq7YFsHCEiwF0lMkboPgJ8QqHUCviybRuCkfoj1KKKUTxHyAxZaPdDfXWhNE8xoPte4re5VNTuZXmC8kJHaHp0pvxmMn/GI//NZ3SIJK96ifP2Uy4gXfOgcUu8VX7GRVcBJwGnAqzBsVkFYp@ky/chrKYcb)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~99~~ ~~87~~ 80 bytes
```
⊞υNWυ«≔∨⊟υωι¿⁼ι⁺ωιι«≔⟦⟧θ≔²ηW⊖ι«⊞θ⌕X⁰⮌↨ιη⁰≧÷Xη§θ±¹ι⊞θ|≦⊕ηW¬⌊﹪η…²η≦⊕η»⊞υ]FΦ⮌θλ⊞υκ[
```
[Try it online!](https://tio.run/##fZGxasMwEIZn@ymEpxOokJYOhU4paSBDUpM1ZFDji31UlmNZigutn92V5LhDhwoksHT@/u@kUyXNqZFqHHPXVeAE2@iLsztXv6MBzp/TviKFDBxnX2my7DoqNbwZyJuL3xOs95N8WUJnBq@tk6oDEixXroM@HHHOckPaQqxC1WEAzaTDUbA2HMwbD4JV8fuWu8KTwRq1xcITokSSRNdWsDXpwpv0XnUh2B6vaDqEF@kXChzu5RY84pKtvEwReyorCxttV3SlAr1rBFSCLe1GF/gZyDsspUW4jwiaCHNq9p39QXrar@XsPzewayxsSVPtatg2hVNNiNpLXeLUbBjsX9SQ3sL982THKfzcGAZrUtarz4233lWF@77VfsTK6fazQ/xvSIdxfHoc767qBw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υN
```
Start by processing the input integer.
```
Wυ«
```
Repeat until there are no more values to be processed.
```
≔∨⊟υωι
```
Get the next value, or the empty string if it is zero.
```
¿⁼ι⁺ωιι«
```
If the next value is a string then print it, otherwise:
```
≔⟦⟧θ
```
Start collecting prime powers.
```
≔²η
```
Start at the first prime.
```
W⊖ι«
```
Repeat until the integer is reduced to `1`.
```
⊞θ⌕X⁰⮌↨ιη⁰
```
Add the multiplicity of this prime factor to the list of prime powers.
```
≧÷Xη§θ±¹ι
```
Divide the integer by the power of the prime to the multiplicity.
```
⊞θ|
```
Add a separator to the list of prime powers.
```
≦⊕ηW¬⌊﹪η…²η≦⊕η
```
Find the next prime by brute force.
```
»⊞υ]
```
Push a `]` for later output.
```
FΦ⮌θλ⊞υκ
```
Push each prime power in reverse order, but without the leading separator.
```
[
```
Print `[`. Subsequent passes through the loop will then process the prime powers, separators and `]`.
[Answer]
# [J](https://www.jsoftware.com), 34 bytes
```
*#1|.'][',1}.&;'|'(,$:)&.>_&q: ::$
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtxU0lL2bBGTz02Wl3HsFZPzVq9Rl1DR8VKU03PLl6t0ErBykoFqlJLkys1OSNfQcNazS4NKK0JNMtQwUjBVMHEVMHCRMHM1NTYFEyaQXQsWAChAQ)
`_&q: ::$` Get the prime exponents. If that errors (0), get an empty array instead.
`'|'(,$:)&.>` For each exponent, call the entire function recursively and prepend a bar to the result.
`1}.&;` Join into a single string and remove the first bar.
`1|.'][',` Wrap in brackets by prepending both, then rotating one to the back.
`*#` Replicate by sign of input. This makes sure 0 returns an empty string.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"D!i„[]×ëÓ®δ.V'|ý'[ì']«"©.V
```
As usual, 05AB1E isn't the best when it comes to recursive challenges. And since there isn't a way to interpret or convert a list `[]` to a string `"[]"`, it becomes even longer..
[Try it online](https://tio.run/##ATIAzf9vc2FiaWX//yJEIWnigJ5bXcOXw6vDk8KuzrQuVid8w70nW8OsJ13CqyLCqS5W//84NA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/JRfFzEcN86JjD08/vPrw5EPrzm3RC1OvObxXPfrwGvXYQ6uVDq3UC/uv8z/aQMdQx0jHVMfIXMfEVMfURMfCRMfM1NTYFEyaxf7X1c3L181JrKoEAA).
Here an alternative that's 1 byte longer:
```
Δ.γd}εÐdi!i„[]×ëÓ'|ý…[ÿ]}}}J
```
[Try it online](https://tio.run/##ATUAyv9vc2FiaWX//86ULs6zZH3OtcOQZGkhaeKAnltdw5fDq8OTJ3zDveKAplvDv119fX1K//84NA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1P0zm1OqT239fCElEzFzEcN86JjD08/vPrwZPWaw3sfNSyLPrw/tra21ut/rc7/aAMdQx0jHVMdI3MdE1MdUxMdCxMdM1NTY1MwaRb7X1c3L183J7GqEgA).
**Explanation:**
```
"..." # Define the recursive string below
© # Store this string in variable `®` (without popping)
.V # Pop and execute it as 05AB1E code
# (after which the result is output implicitly)
D # Duplicate the current integer
!i # Pop the copy, and if it's 0 or 1:
„[]× # Repeat "[]" 0 or 1 times as string
ë # Else (it's >=2):
Ó # Get a list of exponents of its prime factorization
δ # Map over each integer:
® .V # Do a recursive call
'|√Ω '# Join the list with "|"-delimiter
'[ì']« # Prepend "[" and append "]"
```
```
Δ # Loop until the result no longer changes,
# using the implicit input in the first iteration:
.γ } # Adjacent group-by the string by:
d # Check whether it's a digit
ε # Map over each group:
Ð # Triplicate the current string
di # If it's a number:
!i„[]×ëÓ'|ý '# Similar as above
…[ÿ] # Prepend "[" and append "]"
} # Close the inner if-else statements
} # Close the outer if-statement
} # Close the map
J # Join this mapped list of groups back together to a single string
# (after which the result is output implicitly)
```
[Answer]
# [Scala](http://www.scala-lang.org/), 335 bytes
Port of [@Ajax1234's Python answer](https://codegolf.stackexchange.com/a/265603/110802) in Scala.
\$ \color{red}{\text{But the scala code fails on same cases. Any help would be appreciated.}} \$
---
335 bytes, it can be golfed much more.
Golfed version. [Try it online!](https://tio.run/##ZZBBS8MwGIbv/RWxMEjcjFtlO7TLQMGD1OFBPJUysiadn0vTkqaKdP3tNe0usgUC@R7e8D58dcYV78v9l8ws2nLQqPUQEjJHhRswN4c6RI/G8N/k3RrQh5SE6EODRWxMIlQ5apXGOZ4TckEWVyS4Iqvl8mE10q6HoiqNRfUgRRsLimaltqZU9MlIfqzpzhvUcqzDF21JeFZiLTiyDoiRtjHaT1L/Vkff3CDBtrxKXHTmborJCGP2CrVN/hHdFEx7P5@gJHbvzYK0@6GP75Vs89JgWN8FyJZDkAxlwFhwOuEANdpJIiDUpbhSGCa7G@b20MYMwjCOBrGmmLj8nLTudc8gEkzQphLcSoFhJuhB2jfzrGrppjmZLkg0lnfD8fzEn8ZUOGHQmaUFr1z5JseX3wihxfG8DuyffDL1U7/ru/4P)
```
import scala.util.control.Breaks._
def f(n:Int):String={if(n<2)return"[]"*n;var d=Map[Int,Int]();var K=List[Int]();var num=n
while(num>1){breakable{for(i<-2 to num){if(i==2||(2 until i).forall(i%_!=0)){K=i::K;if(num%i==0){num/=i;d=d.updated(i,d.getOrElse(i,0)+1);break}}}}}
"["+K.distinct.map(i=>f(d.getOrElse(i,0))).mkString("|")+"]"}
```
Ungolfed version. [Try it online!](https://tio.run/##ZVLLTsMwELznK4ZISDYUA0VwiGglkDiggjggTlGF3MYpBseJHAeEaL@9bJxS@jjFO@uZ2R2nnkojl0tdVKXzqNtKNF4bMS2td6URt07Jj1q8RlE5eVdTj0epLX4iIFM5CiqYdLM6wY1z8jt99k7b2ZgneLHaYxBuAhWh3liWszPOd5DzPaS/h1xdXl5cBXQRraxzZhPcW09WnenaTOdgFtfoczjlG2cRp@MYR7BR6H9Kh4xuP8oqJYFeqzJmfN0bUe9B1z7dwW1TUGcl8vWmjSIfwoY45ytrYNLmJSdGsT8kLx2YxvUJ@vBlq/J/uxtWYzCg5nwO1kdjKX5oLognjaHmIV5xMAAlt8FDGFMjSTDaAMPuNNMhgujZNgVhh1PibYFtGJloqkx6lTHdo2Km/JO7M7VqS1I5ph23OGHPDWQR7Z7W34646HKL05jERiKjgLWdelHIqg1gSA@6Z8u5KD6612XxPG7HiMdx@AsWy@Uv)
```
import scala.util.control.Breaks._
object Main {
def main(args: Array[String]): Unit = {
println(f(0))
println(f(1))
println(f(2))
println(f(65536))
}
def f(n: Int): String = {
if (n < 2) return "[]" * n
var d = Map[Int, Int]()
var K = List[Int]()
var num = n
while (num > 1) {
breakable({
for (i <- 2 to num) {
if (i == 2 || (2 until i).forall(i % _ != 0)) {
K = i :: K
if (num % i == 0) {
num /= i
d = d.updated(i, d.getOrElse(i, 0) + 1)
break
}
}
}
})
}
"[" + K.distinct.map(i => f(d.getOrElse(i, 0))).mkString("|") + "]"
}
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 109 bytes
```
require"prime"
f=->n{n<1?"":"[#{n<2?"":Prime.each((q=n.prime_division)[-1][0]).map{|x|f[q.to_h[x]||0]}*?|}]"}
```
[Try it online!](https://tio.run/##lVDLboMwELz7K6zlAlWxgMZpVZXkF3q3rIimoFgivGmNsL@d2jzCuXvYnZmd3ZW26b@GaWrSuhdNClUj7imgLPZPxVh8hGeAd2COgZGFn7ZN0uR6c906Lshsv3yLH9GKsvCYH3IWcI/ck2pUUmWsJl15uTHJlQq4fjorzUFPEGAb/gmjcEOMo@iBGeeIPphSlkevD86swNGB7ooRZhc97Ds239uuLbZl4ZHSF7qOL6pa839i23RcD9gTJoC0VS46FxB488NG1ZS/CmH53KRtn3exoZvHTIKH8NaYi1IAxh1L@0GB8BBn5JrkuSuN0/y96DA4o9TmrDMOGpsUr6MaAdLTHw "Ruby – Try It Online")
```
f=->n{ _f_ takes an integer _n_ and
n<1?"" returns "" if _n_ == 0
:"[#{...}]" else returns a string enclosed in brackets composed of:
n<2?"" empty string if _n_ == 1
:Prime.each( else we take all primes up to
(q=n.prime_division)[-1][0])
maximum factor( saving factorization in _q_ )
.map{|x| and map them by:
f[...] calling _f_ recursively with
q.to_h[x] hash made from factorization( gives us powers )
||0 for primes not in factorization _q_ default _nil_ is converted to 0
}*?| finally join with `|`
```
] |
[Question]
[
## Background
Adám and I were once discussing [a way to properly extend some features in Dyalog APL](https://chat.stackexchange.com/transcript/message/54813110#54813110). I came up with the following extension to Take, a function that takes some front or back elements (and an analogous extension to Drop). We agreed that it was a good idea, but it was incredibly hard to come up with a piece of code that imitates the behavior.
While the original proposal operates on multi-dimensional arrays, this challenge's scope is limited to 1D arrays of numbers. Whenever I mention "array", it implies a 1D array.
## The Take function `↑`
`↑` takes two arguments. One is the array `A` (of length `L`), and the other is a single integer `N` (which can be 0, positive, or negative).
The behavior depends on the value of `N`:
* If `0 ≤ N ≤ L`, `↑` takes first `N` elements of `A` from the start.
* If `-L ≤ N < 0`, `↑` takes last `-N` elements of `A` from the end.
* If `N > L` or `N < -L`, `↑` performs "overtake", appending (for positive `N`) or prepending (for negative `N`) zeros until the array's length becomes `abs(N)`.
It can be thought of applying a Boolean mask to an infinitely zero-padded version of `A`:
```
For all cases, A = [1, 2, 3, 4, 5]
For N = 3: (positive simple take)
A : ... 0 0 1 2 3 4 5 0 0 ...
Mask : ... 0 0 1 1 1 0 0 0 0 ... # Fill 1s from the start of the array
Result: 1 2 3 # Elements at 0 mask are removed from the array
For N = -4: (negative simple take)
A : ... 0 0 1 2 3 4 5 0 0 ...
Mask : ... 0 0 0 1 1 1 1 0 0 ... # Fill 1s from the end of the array
Result: 2 3 4 5
For N = 7: (positive overtake)
A : ... 0 0 1 2 3 4 5 0 0 0 ...
Mask : ... 0 0 1 1 1 1 1 1 1 0 ... # The mask overflows the input array
Result: 1 2 3 4 5 0 0
For N = -8: (negative overtake)
A : ... 0 0 0 0 1 2 3 4 5 0 0 ...
Mask : ... 0 1 1 1 1 1 1 1 1 0 0 ... # The mask is filled from the end,
# overflowing through the start
Result: 0 0 0 1 2 3 4 5
```
## The proposed extension ("Multi-Take")
The extension allows `N` to be an array of integers `[N1, N2, N3, ..., Nn]`. It conceptually generates all the masks to apply to `A` using each of `Ni`, and combines all of them by logical OR. Then the mask is applied to `A` in the same sense as above, giving the resulting array (which may have some contiguous middle elements removed, or have padding in both directions).
Because the [identity element for OR is 0](https://en.wikipedia.org/wiki/Identity_element#Examples), empty `N` gives all-zero mask, resulting in an empty array (which is equivalent to giving a single zero as `N`).
```
For all cases, A = [1, 2, 3, 4, 5]
For N = [1, -2]: (removing a contiguous region)
A : 1 2 3 4 5
Mask (1) : 1 0 0 0 0 # Taking from start
Mask (-2): 0 0 0 1 1 # Taking from end
OR : 1 0 0 1 1
Result : 1 4 5 # [1, 4, 5]
For N = [8, -7]: (padding in both direction)
A : 1 2 3 4 5
Mask (8) : 0 0 1 1 1 1 1 1 1 1 # Overtaking from start
Mask (-7): 1 1 1 1 1 1 1 0 0 0 # Overtaking from end
OR : 1 1 1 1 1 1 1 1 1 1
Result : 0 0 1 2 3 4 5 0 0 0 # [0, 0, 1, 2, 3, 4, 5, 0, 0, 0]
For N = [2, 4, 7]: (for multiple values of same sign, some are simply shadowed)
A : 1 2 3 4 5
Mask (2) : 1 1 0 0 0 0 0
Mask (4) : 1 1 1 1 0 0 0
Mask (7) : 1 1 1 1 1 1 1
OR : 1 1 1 1 1 1 1 # Same as simply N = 7 or [7]
Result : 1 2 3 4 5 0 0 # [1, 2, 3, 4, 5, 0, 0]
For N = []: (empty N gives empty result)
A : 1 2 3 4 5
Mask : (None) # No mask to apply
OR : 0 0 0 0 0 # Identity element of OR
Result: (Empty) # []
```
## Challenge
Implement the extension, i.e. a program or function that takes an array of numbers `A` and an array of take amounts `N`, and outputs the modified array using the mechanism described above.
The "array" can be any sequential container type in your language of choice.
You can assume the elements of `A` are given in any common number type in your language of choice (or, if you're doing string I/O, represented in the most natural format for your language). Your program should be able to handle empty `A` and `A` containing zeros or duplicate elements.
You may assume `A` contains only integers even if your program accepts floating-point numbers as input.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
# These test cases all share A = 1 2 3 4 5
# Should work for any 5-element array A' = a b c d e
# giving the output's 1 2 3 4 5 substituted with a b c d e respectively,
# even if A' contains duplicates or zeros
N = (empty)
Output = (empty)
N = 3
Output = 1 2 3
N = 0
Output = (empty)
N = -4
Output = 2 3 4 5
N = 7
Output = 1 2 3 4 5 0 0
N = -8
Output = 0 0 0 1 2 3 4 5
N = 0 0 0 0 0
Output = (empty)
N = 0 4 2 3
Output = 1 2 3 4
N = -2 -1 0 -7
Output = 0 0 1 2 3 4 5
N = 0 2 -2 1 -1
Output = 1 2 4 5
N = -7 -5 -3 -1 1 3 5 7
Output = 0 0 1 2 3 4 5 0 0
-------------------------
# Noteworthy edge cases
A = 1 4 3 4 5
N = 0 2 -2
Output = 1 4 4 5
A = 1 2 0 4 5
N = 7 -8
Output = 0 0 0 1 2 0 4 5 0 0
-------------------------
# These test cases share A = (empty)
N = (empty)
Output = (empty)
N = 0 0 0 0 0
Output = (empty)
N = 3 1 4
Output = 0 0 0 0
N = -3 -1 -4
Output = 0 0 0 0
N = 3 1 -4 -1 5
Output = 0 0 0 0 0 0 0 0 0 (9 zeros)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~58~~ 50 bytes
```
{{2⊃{⍵[⍒⍴¨⍵]}(⍺,⍵)A⍺(⍵,⍺↓⍨≢A)}/((⌈/,⌊/)0,⍵)↑¨⊂A←⎕}
```
[Try it online!](https://tio.run/##jZGxasMwFEV3f4W22JBiWbJxVtOlXZtspUOgpEugXYvx0oJpTRSSlP5ApwwFL82S0Z/yfsS9UtN4ScxDSNyHju4V702f5hf3z9P540Pb5rmi6jUns7slsyHz02yh7wqfzH4IFWQQKHYo9lR@kNnS@1cWFKHv0@ItHNKiCgPpUCrXeF29ZFSuaPlZtDMrzBIBZL6td63B4Gp8c4lzcnU9bmcCCpwUTa2E8v6qSMRCYyeHeiAGntehGvDoiEq3TqLIPWLqvKPmQJIDNXXMwVKe14j1r0MDJA@O7TUvXqHNtr1NnfK8lRtiZJ/xElKgCbZ2SRHQRLCyusF2qrcrZzCN0Lgf@f9dN9oeL0AOTk6hvw "APL (Dyalog Unicode) – Try It Online")
What better way to implement this than in APL itself? That being said, some of the logic is nontrivial.
Anonymous function that takes `N` as the right argument and `A` in standard input.
*-2 bytes thanks to @Bubbler*
*-1 byte thanks to @Adám*
### Explanation
Even though APL has the take function built-in, combining them requires a bit more work.
Firstly, as @Jonah noted, only the elements of `N` with the largest absolute value matter to the final result since all elements with smaller absolute value correspond to subarrays of those formed from higher absolute value. Aka, only the largest positive number and the most-negative negative number matter. We obtain those right off the bat with `(⌈/,⌊/)0,⍵`, where `⍵` is N. This produces a pair of the smallest number and the highest number in `0` appended to N. Appending `0` is important because it guarantees that the two numbers obtained are respectively non-positive and non-negative.
The convenient part is `↑¨⊂A←⎕`, where we use APL's built-in take (`↑`) to obtain two arrays, one (call it `m`) counting backwards from the end, and one forwards from the start (call it `M`).
Here, it gets interesting. For non-trivial `A`, there are several cases to consider:
```
A = 1 2 3 4 5
1. M ⊆ m:
m: 0 0 1 2 3 4 5
M: 1 2 3
union: m
2. m ⊆ M:
m: 3 4 5
M: 1 2 3 4 5 0 0 0
union: M
3. Both m and M have 0s:
m: 0 0 1 2 3 4 5
M: 1 2 3 4 5 0 0 0
union: m,(the zeros of M)
4. Neither m nor M have 0s, but they overlap:
m: 3 4 5
M: 1 2 3 4
union: A
5. M and m do not overlap:
m: 4 5
M; 1 2
union: M,m
```
There are different ways to define the unions of the two arrays. For example, the union for case 3 could instead be `(the zeros of m),M`, but that is less useful for golfing due to precedence. Importantly, case 1 could analogously be defined as `m,(the zeros of M)` (same as case 3) since `M` has no zeros in case 1.
For cases 1 to 4, the union desired is the longest one out of `A`,`M`, and `m,(the zeros of M)`. For example, in the example for case 2 , `M` has length 8, which is longer than the other two possibilities: `A` has length 5, and `m,(the zeros of M)` has length 6. This holds true for all four of these cases, so all we have to do is compute all 3 possibile unions, then take the longest one.
This evidently does not hold true for case 5. `A` always has more elements than the desired union, so it would always be selected over `M,m`. This is only one conditional, so it is not particularly difficult to add in a quick check. However, `M,m` is the longest in cases 1 to 4, so we can instead take the second-longest out of `A`,`M`, `m,(the zeros of M)`, and `M,m`.
```
{{2⊃{⍵[⍒⍴¨⍵]}(⍺,⍵)A⍺(⍵,⍺↓⍨≢A)}/((⌈/,⌊/)0,⍵)↑¨⊂A←⎕}
{...}/(⌈/,⌊/)0,⍵}↑¨⊂A←⎕ ⍝ Compute m and M as discussed,
⍝ then pass m as ⍺ and M as ⍵ to the following:
2⊃{⍵[⍒⍴¨⍵]} ⍝ Get the second-longest of:
⍺,⍵ ⍝ m,M
A ⍝ A
⍺ ⍝ M
⍵,⍺↓⍨≢A ⍝ m,(the zeros of M)
```
[Answer]
# JavaScript (ES6), ~~103 97~~ 96 bytes
Expects `(A)(N)`.
```
a=>b=>Object.keys(g=x=>x&&g(g[x<0?a.length+x++:--x]=x),b.map(g)).sort((a,b)=>a-b).map(i=>~~a[i])
```
[Try it online!](https://tio.run/##hZFNbsMgEEb3PUgE8gzyD5arqtAj9ACWF@A6xKlrotiq6CZXd3FadVHFGbGCeTw@Zo7m00ztuT/NOPq3btmrxShtlX61x66dxXv3NTGngtJht3PM1eE5fTFi6EY3H5KQJE@IoVGBgxUf5sQc52Ly55kxA5YrbdDya6FX@nIxdd/wpfXj5IdODN6xPaszyKEACWXDWd1w/nCvXlBASgEoKaIiFY9kCvhdNCjXLfliDphFH1a0MKI5ZJEnpRVgCVis6iwel3DbLv/bN8TpXwPhZoc25kv16zr2GFBu1H4@gPLOVZQrErPx5Rs "JavaScript (Node.js) – Try It Online")
### How?
When it's called with \$x>0\$, the helper function \$g\$ creates a key in its own underlying object for each value in the range:
$$[x - 1, x - 2, ..., 0]$$
When it's called with \$x<0\$, it does the same thing with the range:
$$[L + x, L + x + 1, ..., L - 1]$$
where \$L\$ is the length of the input array \$a\$.
When it's called with \$x=0\$, it does nothing.
```
g = x => // x = input
x && // stop the recursion if x = 0
g( // otherwise, do a recursive call:
g[ // create a new key in g:
x < 0 ? // if x is negative:
a.length + x++ // use a.length + x and post-increment x
: // else:
--x // use x, pre-decremented
] = x // the value associated to this key doesn't matter,
// so we just use the argument for the next call
) // end of recursive call
```
We sort all keys created by invoking \$g(x),x\in b\$ in ascending order and map the resulting indices to the values of \$a\$, forcing \$0\$'s when they are out of range.
```
a => b =>
Object.keys(
g = …,
b.map(g)
)
.sort((a, b) => a - b)
.map(i => ~~a[i])
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~113~~ 103 bytes
```
def f(A,N):k=len(A);N+=0,;return[+(-1<i<k)and A[i]for i in sorted({*range(max(N)),*range(k+min(N),k)})]
```
[Try it online!](https://tio.run/##dZLRboMgFIbvfQrSK5iHRBTj0tYlvoAvYLgwEzfiig3apMuyZ3fQdoluAFfn4@eHA//5c34fdbYsnexRjyuoyX4oP6TGFTnUcZnAwcj5YnQTY8qO6jiQVneoapToR4MUUhpNo5llh7@eTKvfJD61V1wTAo9yiE9KWwAD@SZieW0nOaESNRGyAzcMUsiAQy6gEQQ8NPPjxI8p9/MiIH8OuMNjhpa5qwKeKVBm99IitNkKUmBWFTAogOZAM2fDLM1h48T/OG1Nkt@GYd3b5nX9/bmntsfxDblfgvJ/MsrdQu64iCKXBZsdl4bbB@9v4rNRerZBWhX1utiVLzu4h26NSbT8AA "Python 3 – Try It Online")
Bit naive of an approach, but it works pretty well.
*-10 bytes thanks to @ovs*
### Explanation
We generate the sets of all indices of `m` and `M`, 0-indexed relative to the start of `A`. A simple union of these two sets combines the two masks.
```
def f(A,N):
k=len(A);
N+=0,; # Append 0 to ensure that the min/max functions never error
[
+(-1<i<len(A))and A[i] # try to get the i-th element of A
for i in sorted({ # sort the indices to appear in proper order
# generate the indices
# 0-indexed starting at the first element of A
*range(max(N)), # the set of all indices of M¸union:
*range(k+min(N),k) # the set of all indices of m
})
]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
⊞η⁰E⁻±⌊ηLθ0IΦθ∨‹κ⌈η›⁻⊕κLθ⌊ηE⁻⌈ηLθ0
```
[Try it online!](https://tio.run/##bU7LCsIwELz7FYunLWyhvlDwKChCq72XHkJdmtA22iQV/z4SBCvqnGZgXpUUprqK1vt8sBIlQRJtJ7lR2mEmbpgpPVg8cS0cB6G6oUMZRQQp69pJ7AOfJtPoHdsJ63CvWscGe4KzwZStxYYgE48xfzAsguW1cNSV4Y614ws2X@0fswG/98bef7e8L4oZwZxgQbAkWJUExYYgXpelj@/tEw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞η⁰
```
Much like the other answers, a `0` is pushed to the take list, so that the maximum is at least `0` and the minimum is at most `0`.
```
E⁻±⌊ηLθ0
```
Print `0`s for each element taken before the first.
```
IΦθ∨‹κ⌈η›⁻⊕κLθ⌊η
```
Print those elements which fall in either the positive or negative range.
```
E⁻⌈ηLθ0
```
Print `0`s for each element taken after the last.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~28~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εݨyd≠iIg+<]˜êεIg‹yd*iyèë¾
```
Inputs in the order \$N,A\$.
[Try it online](https://tio.run/##AUMAvP9vc2FiaWX//861w53CqHlk4omgaUlnKzxdy5zDqs61SWfigLl5ZCppecOow6vCvv//WzgsLTddClsxLDIsMyw0LDVd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCqNL/c1sPzz20ojLlUeeCzIh0bZvY03MOrzq3NSL9UcPOyhStzIjKwysOrz6077@SXpjO/@jo6FidaEMdIx1jHRMd01ggJ9oYQ8QAQ0TXBEPIHFORBaZJOlCIRcYExMc0xEhH1xCoQ9ccixagnJGOIVABpjZzHV1THV1jkGZDoLipDi79YGETZI/owB1uABcEYgwPQEILaLwJjAOxT9cEWVLXBCRmChaKBQA).
**Explanation:**
```
ε # Map each value `y` in the (implicit) input-list `N` to:
Ý # Push a list in the range [0,`y`]
¨ # Remove the last value to make the range [0,`y`)
yd≠i # If `y` is negative:
Ig+ # Add the input-length of `A` to each value
< # And decrease each value by 1
] # Close the if-statement and map
˜ # Flatten the list of indices
ê # Sort and uniquify these indices
ε # Map each index `y` to:
Ig‹ # Check if `y` is smaller than the input-length of `A`
yd # Check if `y` is non-negative (>= 0)
*i # If both are truthy:
yè # Index `y` into the (implicit) input-list `A`
ë # Else:
¾ # Push a 0 instead
# (after which the resulting list is output implicitly)
```
[Answer]
# [Clojure](https://clojure.org/), 90 bytes
```
#(for[j(sort(set(for[i %2 x(range(Math/abs i))](if(< i 0)(+(count %)i x)x))))](get % j 0))
```
[Try it online!](https://tio.run/##dU/RasMwDHzPVxyMgswwTZyE9GG/0C8wfshau3ModuekkL/P5CyDwDYbGenuLJ0u9zg8k13oah3c8kIuJj3QGNNEo53W0uOgMFPqw83SuZ8@jv37CC@EIe/oDR6loFe6xGeYcBAes5iFyPTNMoCBebGIgq5xtJ/QPbSuoFCjQWsMCmwnMGGga46SQzb8dDk5ZQTbXfMm/8@UgqwYld0Kc6VQMZSpDrKFrLOg4mEtOmMMD6NH8mG6B5BDj8BOiz3E3prN209L81uiUG4SHnNaBbv1/thq779mQ3m5b3PrnhmSTS655z82ly8 "Clojure – Try It Online")
Takes input in the order: data, indices
### Ungolfed
```
#(for [j
(->
; for each i in indices generate a range from 0 to abs(i)
(for [i %2 x (range (Math/abs i))]
; for negative indices add the offset = length(data) + i
(if (< i 0) (+ (count %) i x) x))
set ; keep unique values
sort)] ; sort in ascending order
; for each j, get the jth item in data, or 0 if out of bounds
(get % j 0))
```
] |
[Question]
[
Shorter version of [Skyscrapers Challenge](https://www.conceptispuzzles.com/index.aspx?uri=puzzle/skyscrapers/techniques)
### Task
Given an array of building heights and a positive integer `k`, find all the permutations(without duplicates) of the heights such that exactly `k` buildings are visible.
Any building will hide all shorter or equal height buildings behind it.
Any format for input and output is valid.
Input array will never be empty.
In case it is not possible to see exactly as many buildings, output anything that cannot be an answer but no error.
### Examples:
(Length of output is shown for very long outputs,but your output should be all possible permutations)
```
input:[1,2,3,4,5],2
output: 50
input:[5,5,5,5,5,5,5,5],2
output: []
input:[1,2,2],2
output:[(1,2,2)]
Seeing from the left, exactly 2 buildings are visible.
input:[1,7,4],2
output:[(4, 7, 1), (1, 7, 4), (4, 1, 7)]
input:[1,2,3,4,5,6,7,8,9],4
output:67284
input:[34,55,11,22],1
output:[(55, 34, 11, 22), (55, 22, 34, 11), (55, 34, 22, 11), (55, 11, 34, 22), (55, 22, 11, 34), (55, 11, 22, 34)]
input:[3,4,1,2,3],2
output:31
```
**This is code-golf so shortest code wins**
*Optional: If possible, can you add something like `if length is greater than 20: print length else print answer`. In the footer, not in the code.*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
œÙʒη€àÙgQ
```
[Try it online](https://tio.run/##ATEAzv9vc2FiaWX//8WTw5nKks634oKsw6DDmWdR/31EZ8KpMjDigLppwq7/WzEsNyw0XQoy) or [verify (almost) all test cases](https://tio.run/##yy9OTMpM/W/u5ulir6SQmJeioGTv6RIKZD9qmwRk/z86@fDMU5PObX/UtObwgsMz0yMC/9e6pB9aaWTwqGFX5qF1tTr/ow11jHSMdUx0TGO5jLiijXRMdQyBPGMwz1QHBUJVAHWAWYY65jomYJYxUDtQH1ACKGMI5ANNAJsLlAUA) (test case `[1,2,3,4,5,6,7,8,9],4` times out).
Footer of the TIO does what OP asked at the bottom:
>
> *Optional: If possible, can you add something like `if length is greater than 20: print length else print answer`. In the footer, not in the code.*
>
>
>
**Explanation:**
```
œ # Permutations of the (implicit) input-list
# i.e. [1,2,2] → [[1,2,2],[1,2,2],[2,1,2],[2,2,1],[2,1,2],[2,2,1]]
Ù # Only leave the unique permutations
# i.e. [[1,2,2],[1,2,2],[2,1,2],[2,2,1],[2,1,2],[2,2,1]]
# → [[1,2,2],[2,1,2],[2,2,1]]
ʒ # Filter it by:
η # Push the prefixes of the current permutation
# i.e. [1,2,2] → [[1],[1,2],[1,2,2]]
ۈ # Calculate the maximum of each permutation
# i.e. [[1],[1,2],[1,2,2]] → [1,2,2]
Ù # Only leave the unique maximums
# i.e. [1,2,2] → [1,2]
g # And take the length
# i.e. [1,2] → 2
Q # And only leave those equal to the second (implicit) input
# i.e. 2 and 2 → 1 (truthy)
```
[Answer]
## Haskell, 73 bytes
```
import Data.List
f n=filter((n==).length.nub.scanl1 max).nub.permutations
```
[Try it online!](https://tio.run/##fY4xDoMwDEV3TuGhA0hWpABRp2wdewPEkLahRA0GJUbq7VNKpaoM1H@x9b6/3Zv4sN6n5IZpDAwnw0acXeSsA9Kd82xDnpPWhfCW7twLmi8iXg15CYN5Fus82TDMbNiNFNNgHIGG25gBTMERwwE@u0vTQQmNFEK1P/RbK1W40b5RYonlP3zEegdLaKoalUK5hGwytp9WWOP7TNWmFw "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 10 bytes
```
Œ!Q»\QL=ʋƇ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMXAQ7tjAn1sT3Ufa///3/h/tKGOiY557H8jAA "Jelly – Try It Online")
*-2 bytes by [@Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)*
This is a dyadic function taking the building heights and `k` in that order.
```
Œ! All permutations of first input
Œ!Q Unique permutations of first input
»\ Running maximum
Q Unique values
L Length of this array
= Equals k
ʋ Create a monad from these 4 links
»\QL=ʋ "Are exactly k buildings visible in arrangement x?"
Ƈ Filter if f(x)
Œ!Q»\QL=ʋƇ All distinct perms of first input with k visible buildings.
```
[Answer]
# Pyth, ~~18~~ 16 bytes
```
fqvzl{meSd._T{.p
```
Try it [here](http://pyth.herokuapp.com/?code=fqvzl%7BmeSd._T%7B.p&input=%5B1%2C7%2C4%5D%0A2&test_suite=1&test_suite_input=%5B1%2C2%2C3%2C4%2C5%5D%0A2%0A%0A%5B5%2C5%2C5%2C5%2C5%2C5%2C5%2C5%5D%0A2%0A%0A%5B1%2C2%2C2%5D%0A2%0A%0A%5B1%2C7%2C4%5D%0A2%0A%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%5D%0A4%0A%0A%5B34%2C55%2C11%2C22%5D%0A1%0A%0A%5B3%2C4%2C1%2C2%2C3%5D%0A2&debug=0&input_size=3).
Note that the online version of the Pyth interpreter throws a memory error on the largest test case.
```
f Filter lambda T:
q Are second input and # visible buildings equal?
v z The second input value
l { The number of unique elements in
m the maximums
e S d ...
._ T of prefixes of T
{ .p over unique permutations of (implicit first input)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~81~~ 63 bytes
*-18 bytes thanks to nwellnhof!*
```
{;*.permutations.unique(:with(*eqv*)).grep:{$_==set [\max] @_}}
```
[Try it online!](https://tio.run/##XYxdC4IwFIbv@xWDIrZxEOZXpQj9DxPZxaxBMz9mJeJvX7MuTDl3z3OetxLNPTSqR/sCJcgMMXUq0ahOcy0fZet0paw7gaOX1DdMRf2khDjXRlTRsMuTpBUapRfF3xk65@NoWt6jArsEpwxc8MCHICPxZsYBLG4pp8ZdowP4E9r@mP8/DaG1RzjNCbPasyYAZr9WW1PzbS02Hw "Perl 6 – Try It Online")
Anonymous code block that takes input curried, e.g. `f(n)(list)`. That `.unique(:with(*eqv*))` is annoyingly long though `:(`
### Explanation:
```
{; } # Anonymous code block
*.permutations.unique(:with(*eqv*)) # From all distinct permutations
.grep:{ } # Filter where
set [\max] @_ # Visible buildings
$_== # Equals num
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
á f_åÔâ Ê¥V
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=4SBmX+XU4iDKpVY=&input=WzEsNyw0XSwyCi1R)
For the longer outputs, adding `} l` to the end will output the length instead. The online interpreter times out for the `[1,2,3,4,5,6,7,8,9],4` test case, regardless of outputting the length or the list.
Explanation:
```
á :Get all permutations
f_ :Keep only ones where:
åÔ : Get the cumulative maximums (i.e. the visible buildings)
â Ê : Count the number of unique items
¥V : True if it's the requested number
```
[Answer]
# JavaScript (ES6), ~~108~~ 107 bytes
Takes input as `(k)(array)`. Prints the results with `alert()`.
```
k=>P=(a,p=[],n=k,h=0)=>a.map((v,i)=>P(a.filter(_=>i--),[...p,v],n-(v>h),v>h?v:h))+a||n||P[p]||alert(P[p]=p)
```
[Try it online!](https://tio.run/##ZZFLa8MwEITv@RU6FCzRtYjz6CNFDj700kMb6FEVjXDtWLErG8sxlDi/3V07lL4QiNmZbweB9rrVLq5N1fi2fEv6VPS5CDeCaqiEVGBFDpmYMhFq/q4rSlswOGyo5qkpmqSmryI0vs9Acs4raHHFp22YMcBr3a4yxi5119mu28hKdZ0ukrqhgxYV6@@klAHMYA4LWCqYKSBSLuHX@bIHbvY9XMPiZzI2wBXaN3CrhgyDOXpLCDBHMDhbyI38sKwmPC3rex1nlEoNJFeMiJAcJ4RERBCpUIwPxsENScSrg8uoYxikNGdUDyourSuLhBfljm41shfHh@enR@6a2tidST8QO2H7mOQn4vshiogXid012YnUiTsUDbZu/7ZF3BUmTugUSDBlfF8aS70X67H/4LmMhAiSNfHwN5AjK@J5bHJi/Sc "JavaScript (Node.js) – Try It Online")
### Commented
```
k => // k = target number of visible buildings
P = ( // P = recursive function taking:
a, // a[] = list of building heights
p = [], // p[] = current permutation
n = k, // n = counter initialized to k
h = 0 // h = height of the highest building so far
) => //
a.map((v, i) => // for each value v at position i in a[]:
P( // do a recursive call:
a.filter(_ => i--), // using a copy of a[] without the i-th element
[...p, v], // append v to p[]
n - (v > h), // decrement n if v is greater than h
v > h ? v : h // update h to max(h, v)
) // end of recursive call
) // end of map()
+ a || // unless a[] was not empty,
n || // or n is not equal to 0,
P[p] || // or p[] was already printed,
alert(P[p] = p) // print p[] and store it in P
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
fȯ=⁰Lü≤uP
```
[Try it online!](https://tio.run/##yygtzv7/P@3EettHjRt8Du951LmkNOD///9G/6MNdYx0jHVMdExjAQ "Husk – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~114~~ 113 bytes
```
lambda a,n:{p for p in permutations(a)if-~sum(p[i]>max(p[:i])for i in range(1,len(p)))==n}
from itertools import*
```
[Try it online!](https://tio.run/##ZZDdSsQwEIXv@xQDe5PICCZNt@tCfZHai4itBpof0iwooq9eM1vrdpXczJz55swh4T29eifnoXmcR22fnjVodMePAIOPEMA4CH20p6ST8W5impvh9ms6WRZa0z1Y/ZaLo@k44YbwqN1LzwSOvWOBc9407rMYordgUh@T9@MExgYf080conEJiBxYK1BiiQqrDiXnxa66K4oFyMMKrx4hxQ7aboPQvlwH7Nzx63mN6neuEGoEwREySqWiMqvUXfb@ZsN9djngfYeKMsK@lge1OVJmpkKR@RxFLKeyACU5Z2sp6QwpUq7qqlBH6kWhjUXdbi3qllm8/qWmxOfkPz8KpSjmbw "Python 2 – Try It Online")
-1 byte, thanks to ovs
---
# [Python 3](https://docs.python.org/3/), 113 bytes
```
lambda a,n:{p for p in permutations(a)if sum(v>max(p[:p.index(v)]+(v-1,))for v in{*p})==n}
from itertools import*
```
[Try it online!](https://tio.run/##ZZDNboMwEITvfoqVcrHTbVUMhDQSfRHKgSqgWsI/AgelivLs1Auhoal88X6emR3Zffsva@KxyT/GttKfxwoqNIeLg8Z24EAZcHWnT77yypqeV0I10J80H951deauOLgXZY71mQ@ifOLDc4RCkHUI1svWXUWemytrOqtB@brz1rY9KO1s57ej65TxwNva8IYXEUqMMcG0RCmEYJv0lbGbJDyn@OdMIraBolyLKEP@PvFpFA@KDJO7IkHIECKBEMR0TegaKE0r52NH3IWcPb6VmExdYZfJfbJeFAdVilFwhELRbV0gEFN6iJeSVhGRcqELoYnonZBjpmvXTNeaOet/c2o9tV9@F@KIjT8 "Python 3 – Try It Online")
[Answer]
# J, ~~43~~ 38 bytes
*-5 bytes after incorporating an optimization from Kevin's O5AB13 answer*
```
(]#~[=([:#@~.>./\)"1@])[:~.i.@!@#@]A.]
```
[Try it online!](https://tio.run/##TU9dT4MwFH3vrziOJVCF60AQbYKpmvhkfPAVeSBLceiyurXEGBP@OhZGFtP05t7z0dP7MSzIb1AI@AixgnA3Ijy@Pj8NQeX1ZRGUwpM93dHlG1/EsuKl6KkleSY9Wd1TNXD28kBQ@67etvYHuoFR1jC1R0EIVijwS3IpI@o5zgn4hzCm1huNbIQ8JGgQu3qFFNmRcfYMS/g@RyQmQXY6YyrspjXQnf3qrMFOu3H3PltDMT6WnJzTNHMpcsShg3KXFQpXXMvdErPSwUfldZ7cpNPv0om4QEu3bNrYhakDrDIW69oog3prNL714ZOI2PAH "J – Try It Online")
## ungolfed
```
(] #~ [ = ([: #@~. >./\)"1@]) ([: ~. i.@!@#@] A. ])
```
## explanation
we're merely listing all possible perms `i.@!@#@] A. ]`, taking uniq items thereof with `~.`, then filtering those by the number of visible building, which must equal the left input.
the key logic is in the parenthetical verb which calcs the number of visible buildings:
```
([: #@~. >./\)
```
Here we use a max scan `>./\` to keep a tally of the tallest building seen so far. Then we just take the unique elements of the max scan, and that's the number of visible buildings.
] |
[Question]
[
Consider this spiral
```
###########
#
# #######
# # #
# # ### #
# # # # #
# # # # #
# # # #
# ##### #
# #
#########
```
Starting in the centre:
* The first line (upwards) has 3 characters.
* The second line has the same number of characters (3)
* Next, we add two chars (5) for the next two sides.
* This pattern continues, two sides the same length then increase the length by 2.
I want to generate this spiral for N lines.
* Write in any language.
* The input/argument, etc. is the number of lines in your spiral.
* Each line starts with the ending character of the previous line in the direction 90 degrees clockwise of the previous line.
* I don't care how much whitespace is before or after each line, as long as the elements of the spiral line up.
* Output text to draw the spiral with any non-whitespace character you choose.
* Attempt to do this in the smallest number of bytes.
Test cases (using a hash as output):
N = 1
```
#
#
#
```
N = 2
```
###
#
#
```
N = 3
```
###
# #
# #
#
#
```
N = 10
```
###########
#
# #######
# # #
# # ### #
# # # # #
# # # # #
# # # #
# ##### #
# #
#########
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 11 bytes
### Code:
Thanks to *Emigna* for saving two bytes!
```
LDÈ-Ì'#3Ý·Λ
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/fx@Vwh@7hHnVl48NzD20/N/v/f0MDAA "05AB1E – Try It Online")
### Explanation
The lengths of each individual edge on the spiral starts with length **3** and gradually increases every two steps by two:
$$
3, 3, 5, 5, 7, 7, 9,\dots
$$
For a spiral with \$n\$ edges, we just need to trim this list to size \$n\$. This is done with the following piece of code:
```
L # Create a list from [1 .. input]
DÈ # Duplicate and check for each number if even
- # Subtract that from the first list
Ì # Add 2
```
This basically gives us the desired list of lengths.
```
'# # Push the '#' character
0246S # Push the array [0, 2, 4, 6]
Λ # Write to canvas
```
The canvas works as a function that pops three parameters (where the rightmost parameter is popped first): **<length(s)>**, **<char(s)>**, **<direction(s)>**. The directions parameter is in this case a list of numbers. The numbers that correspond to the directions are:
$$
\left[\begin{array}{r}
7 & 0 & 1 \\
6 & \circ & 2 \\
5 & 4 & 3
\end{array}\right]
$$
In this case, **[0, 2, 4, 6]** corresponds to the directions list `[↑, →, ↓, ←]`. The canvas iterates over each length retrieved from the list of lengths, uses the '#' character and cyclically iterates over the directions list.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~176~~ ~~170~~ ~~165~~ ~~161~~ 157 bytes
```
g=lambda a,r:r and g(map(''.join,zip(*a))[::-1],r-1)or a
R=['#']
n=1
exec"R=g([' '+l for l in g(R,n)][:-1]+[(n+2)*'#'],3*n);n+=1;"*input()
print'\n'.join(R)
```
[Try it online!](https://tio.run/##PU87T8MwEJ57v8IKg@3ERTjlmSpjWZEitpDBTdzUkF6sUyoofz7YlLKcP52/1/nTtB8xn9uxsyUlSTL35WAO284wo6ggZrBjvTgYLzi/fh8dqm/nRWqkrItiqRtFSy3HwIOqrPkVbwBLDfbLtklV9qLmjPFsYLtAGZjD4FUplE0dtVktMMtlGmVqlaJcY1bqdZI69MdJSPDkcOJveE4WlZxDQ3Ah4HPvBste6WgLWEx0CnPxy2YuoBjP4kmXbXhdsIbw01o/sc3L84ZopCjbkjUfAMA5h1jTxZpksLdCK61l4Pw7n8FOOPmHo2rWkMMKbuEO7uEBHuEJ9M38Aw "Python 2 – Try It Online")
Repeatedly: Uses `g` to rotate the `n`th iteration of the spiral into a 'canonical' position (similar to N=3 or N=7), adds a new segment by adding 2 spaces at the left of each existing row, then replacing the last row with all `'#'`s (resulting in a position comparable to N=4 or N=8), and finally using `g` again to rotate it back to the correct position. Lather, rinse, repeat.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal/wiki), ~~16~~ ~~15~~ 14 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page)
```
↶FN«¶×#⁺³⊗÷ι²↷
```
-2 bytes thanks to *@Neil*.
[Try it online (verbose)](https://tio.run/##S85ILErOT8z5/z8gsyy/xCc1rURD05rLLb9IwzOvoLTErzQ3KbVIQ1OzmktBIaAoM69EQykmTwmoBMYNycxNLdZQUlbScUxJ0TDWcckvTcpJTQFqL0lNTy1yySzLTEnVyNQx0gQCsDaQRUGZ6Rlgm2r//zc0@K9blgMA) or [Try it online (pure)](https://tio.run/##AS8A0P9jaGFyY29hbP//4oa277ym77yuwqvCtsOXI@KBusKz4oqXw7fOucKy4oa3//8xMA).
**Explanation:**
Printing direction is to the right by default, and we want to start upwards, so we start by rotating 45 degrees counterclockwise:
```
PivotLeft();
↶
```
Then loop `i` in the range `[0, input)`:
```
For(InputNumber()){ ... }
FN« ...
```
Print a new-line to mimic the effect of moving back one position:
```
Print("\n");
¶
```
Print "#" `x` amount of times in the current direction:
```
Print(Times("#", ... ));
×# ...
```
Where `x` is: `3 + i // 2 * 2`:
```
Add(3,Doubled(IntegerDivide(i,2))
⁺³⊗÷ι²
```
And then rotate 45 degrees clockwise for the next iteration of the loop:
```
PivotRight();
↷
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~179~~ 178 bytes
thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -1 byte.
```
n=input()
S,H=' #'
m=[S*n]*(n%2-~n)
x=n/4*2
y=0--n/4*2
k=2
m[y]=S*x+H+S*n
M=[1,0,-1,0]*n
exec'exec k/2*2*"x+=M[~k];y+=M[k];m[y]=m[y][:x]+H+m[y][x+1:];";k+=1;'*n
print'\n'.join(m)
```
[Try it online!](https://tio.run/##JYyxCoMwFEX3fIVYSjQx1YROhre7ODmmmYpQG3xKsZAs/noa7XLuefDuXcP2WlDFiDDh@t2KkgxVBzS7UDKDGRhaVuBViR1L4gHrO1MkQCPEXx0oMptgYWCedzz9kx6MrJpKJNh0jn580gOZqxVTLPccerM7q8MhKc/@AdN6m0ZO9Vy2VufacZCapp31M@FGH0hv72XCYi5jlM0P "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 179 bytes
In this approach formulas are used for `x` and `y` deltas instead of a lookup list.
```
n=input()
S,H=' #'
m=[S*n]*(n%2-~n)
x=n/4*2
y=0--n/4*2
k=2
m[y]=S*x+H+S*n
exec'exec k/2*2*"x+=k%-2+k%4/3*2;y-=(k%2or k%4)-1;m[y]=m[y][:x]+H+m[y][x+1:];";k+=1;'*n
print'\n'.join(m)
```
[Try it online!](https://tio.run/##JYyxCoMwFEX3fIVYJDFpqr46Gd7u7mgzFaE2@BSxEJf@ehrtcjhcLmfZt9dMEALhSMtnEznrri3y5MLZhH0nyUpBGegv5cwjFbUEtmOp9V8dApv63WInvWpV/LPBD09@IHEFSJCpV@gyDcpldXGXYHaNwmUwr0lccl2ZM3Cgb7yNlVO9qhprUuMUVobH7rKOtPEH8dt7HklMeQhV@QM "Python 2 – Try It Online")
[Answer]
## JavaScript (ES6), 185 bytes
Sure this can be golfed more, maybe with currying, but here's my very humble attempt. Line breaks added for readability except penultimate character
```
r=(a,n=1)=>n?r(a.reduce((_,c)=>c).map((_,i)=>a.map(e=>e[i])).reverse(),n-1):a,
s=n=>n?r(s(n-1)).map((r,i)=>[...r,w,w].map(x=>i?x:'#')):[[w=' ']],
d=n=>r(s(n),1-i).map(r=>r.join``).join`
`
```
Usage: `d(10)` returns a string as per the N=10 challenge example.
Defines a function `r(a,n)` to rotate an array `a` by `n` turns; a function `s(n)` to generate a 2-dimensional array representing a spiral of size `n` by recursively rotating and adding spacing and lines (not rotated back to starting position); and a function `d(n)` to draw a spiral of size `n`, rotated consistently as per the challenge, and rendered as a returned string.
This was a really fun challenge :¬)
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~20~~ 16 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
H:2%!-├#×;↶n}╶├⟳
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JUY4JXVGRjFCJXVGRjVCJXVGRjFBJXVGRjEyJXVGRjA1JXVGRjAxJXVGRjBEJXUyNTFDJTIzJUQ3JXVGRjFCJXUyMUI2JXVGRjExJXVGRjExJXUyNTRCJXVGRjVEJXUyNTc2JXUyNTFDJXUyN0Yz,i=MTA_,v=8)
## Explanation
```
ø;{:2%!-├#×;↶11╋}╶├⟳
ø push an empty art object
; swap with the input
{ } for i in 1 to n:
{: } duplicate i
{ 2% } mod 2
{ ! } negate
{ - } subtract that from i
{ ├ } add 2
{ #× } repeat '#' that many times
{ ; } swap with previous iteration
{ ↶ } turn 90 degrees anticlockwise
{ 11╋} overlap at (1,1)
╶├⟳ rotate 90 degrees n+2 times
```
] |
[Question]
[
Given a string `l`, find all palindromic substrings `p` of `l` (including duplicates and single character strings). Next, rearrange all sub-strings in `p` into a valid palindrome (there may be multiple correct answers). If it is not possible to rearrange `p` into a single palindrome, your program may have undefined behavior (error, stack-overflow, exiting, hanging/untimely murder of John Dvorak, etc...)
---
# Examples
## Valid Test Cases
```
l = anaa
p = ['a', 'n', 'a', 'a', 'aa', 'ana']
result = anaaaaana or aanaaanaa or aaananaaa
l = 1213235
p = ['1', '2', '1', '3', '2', '3', '5', '121', '323']
result = 1213235323121
l = racecar
p = ['r', 'a', 'c', 'e', 'c', 'a', 'r', 'cec', 'aceca', 'racecar']
result = racecarcecaacecracecar (there are others)
l = 11233
p = ['1', '11', '1', '2', '3', '33', '3']
result = 113323311 or 331121133
l = abbccdd
p = ['a', 'b', 'bb', 'b', 'c', 'cc', 'c', 'd', 'dd', 'd']
result = bbccddaddccbb or ccbbddaddbbcc or (etc...)
l = a
p = ['a']
result = a
```
## Invalid Test Cases (Not Possible)
```
l = 123456789
p = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
result = <not possible, behavior undefined>
l = hjjkl
p = ['h', 'j', 'jj', 'j', 'k', 'l']
result = <not possible, behavior undefined>
l = xjmjj
p = ['x', 'j', 'jmj', 'm', 'j', 'jj', 'j']
result = <not possible, behavior undefined>
```
---
# Rules
* If the input word is a palindrome itself, it will always be valid as input.
* Only one substring should be returned, which one you choose is arbitrary as long as it's valid.
* If the input has no viable output, your code may have undefined behavior.
* Inputs will only contain ASCII-Printable characters between `0x20-0x7E`.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count is the winner.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
{s.↔}ᶠpc.↔
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7pY71HblNqH2xYUJINY//8rAWVTkxOLlP5HAQA "Brachylog – Try It Online")
Fails (i.e. prints `false.`) if not possible.
### Explanation
```
{ }ᶠ Find all…
s. …substrings of the input…
.↔ …which are their own reverse
p Take a permutation of this list of palindromes
c. The output is the concatenation of this permutation
.↔ The output is its own reverse
```
[Answer]
# [Coconut](http://coconut-lang.org/), 140 bytes
```
s->p(map(''.join,permutations(p(v for k in n(s)for v in n(k[::-1])))))[0]
from itertools import*
n=scan$((+))
p=list..filter$(x->x==x[::-1])
```
[Try it online!](https://tio.run/##LYxBCoMwEADvviKHQjZtlfYqxI9YDyGobNXdsInioX9PlXZuA8N49kxryqN95Vg2ARYXQOvqzUj30MuyJpeQKUKATQ0salJIiiCaU7afTG1dl8/OnLSPrhiEF4Wpl8Q8R4VLYEnXgmz0ji4AN2OKYGeMqaoGnI/wAnvZ7Nbu/1PW4nzvnWj1aVQQpCMdc9t9AQ "Coconut – Try It Online")
[Answer]
# JavaScript (ES6), 193 bytes
*"Look Ma, no permutation built-in!"* (So yes ... it's long ...)
Returns an empty array if there's no solution.
```
f=(s,a=[].concat(...[...s].map((_,i,a)=>a.map((_,j)=>s.slice(i,j+1)))).filter(P=s=>[...s].reverse().join``==s&&s),m=S=[])=>S=a.map((_,i)=>f(s,b=[...a],[...m,b.splice(i,1)]))>''?S:P(m.join``)||S
```
### Demo
```
f=(s,a=[].concat(...[...s].map((_,i,a)=>a.map((_,j)=>s.slice(i,j+1)))).filter(P=s=>[...s].reverse().join``==s&&s),m=S=[])=>S=a.map((_,i)=>f(s,b=[...a],[...m,b.splice(i,1)]))>''?S:P(m.join``)||S
console.log(f('anaa'))
console.log(f('1213235'))
console.log(f('hjjkl'))
console.log(f('a'))
```
### How?
Let's split the code into smaller parts.
We define **P()**, a function that returns **s** if **s** is a palindrome, or **false** otherwise.
```
P = s => [...s].reverse().join`` == s && s
```
We compute all substrings of the input string **s**. Using **P()**, we isolate the non-empty palindromes and store them in the array **a**.
```
a = [].concat(...[...s].map((_, i, a) => a.map((_, j) => s.slice(i, j + 1)))).filter(P)
```
The main recursive function **f()** takes **a** as input and compute all its permutations. It updates **S** whenever the permutation itself is a palindrome (once joined), and eventually returns the final value of **S**.
```
f = ( // given:
a, // a[] = input array
m = S = [] // m[] = current permutation of a[]
) => // and S initialized to []
S = a.map((_, i) => // for each element at position i in a[]:
f( // do a recursive call with:
b = [...a], // b[] = copy of a[] without the i-th element
[...m, b.splice(i, 1)] // the element extracted from a[] added to m[]
) // end of recursive call
) > '' ? // if a[] was not empty:
S // let S unchanged
: // else:
P(m.join``) || S // update S to m.join('') if it's a palindrome
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ŒḂÐf
ẆÇŒ!F€ÇḢ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7mg5PSON6uKvtcPvRSYpuj5rWHG5/uGPR////ow11FIDICEjGAgA "Jelly – Try It Online")
Prints `0` in the invalid case.
[Answer]
# [Stax](https://staxlang.xyz/#c=%C3%A7%C2%BB%C2%AC%E2%96%BA%C3%96%E2%88%9Ej%E2%88%9E%3A%C3%86%E2%95%98%CF%84%CE%B4&i=%22a%22%0A%0A%22anaa%22%0A%0A%221213235%22%0A%0A%22abbccdd%22%0A%0A%22racecar%22%0A%0A%2211233%22&a=1&m=1), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
绬►Ö∞j∞:Æ╘τδ
```
[Run test cases](https://staxlang.xyz/#c=%C3%A7%C2%BB%C2%AC%E2%96%BA%C3%96%E2%88%9Ej%E2%88%9E%3A%C3%86%E2%95%98%CF%84%CE%B4&i=%22a%22%0A%0A%22anaa%22%0A%0A%221213235%22%0A%0A%22abbccdd%22%0A%0A%22racecar%22%0A%0A%2211233%22&a=1&m=1) (It takes about 10 seconds on my current machine)
This is the corresponding ascii representation of the same program.
```
:e{cr=fw|Nc$cr=!
```
It's not quite *pure* brute-force, but it's just as small as the brute-force implementation I wrote. That one crashed my browser after about 10 minutes. Anyway, here's how it works.
```
:e Get all contiguous substrings
{cr=f Keep only those that are palindromes
w Run the rest of the program repeatedly while a truth value is produced.
|N Get the next permutation.
c$ Copy and flatten the permutation.
cr=! Test if it's palindrome. If not, repeat.
The last permutation produced will be implicitly printed.
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~131~~ ~~123~~ 120 bytes
```
->s{m=->t{t==t.reverse}
(1..z=s.size).flat_map{|l|(0..z-l).map{|i|s[i,l]}}.select(&m).permutation.map(&:join).detect &m}
```
[Try it online!](https://tio.run/##XVL9bpswEP@fp7CQEoGUWAOara1E9iAIVYftqGbGibDptoY8e@azgdAhYd/vy@aw@6H5ez@V9/3RXLtyf7RXW5aW9uJD9EbcoiSj9LM01MhPkdKTAvvWweU6qjH55pS9SqnHcjSV3Kn6dqNGKMFssu1SehF9N1iw8qzRlmxf27PUKeXCOgvZdrd7FRFSxaAB4h3xT0Du0UjF4FHQY18hjut655NZnhV5cfDhBbnXVRgI1SHwS6gHJhj0U2hCOC6FF2cFB6xWCjykhxA@8YFXcVRWxlV8UuBrBsdHj1leFNPvQVS4Xoos9OfmHJnFDE3DGOdTbwEA54w1DQaaBmtANhAoeAdaA4E1BCMSQYJgDATW80bLxvMBhjNcnVDxdPj@4/nF6ZWWaubf2/aXmrta8X/arm2/8FFNBbB3ws9klPoy2B35ACX5G2jz293T0eV6YQZlSUlOlbfUjnOTIfHmxZDySDb5kyHJxqQx2ZBqWiakqNTm4i7kf8s6mqmBi59JsKV1JDSP7v8A "Ruby – Try It Online")
A lambda accepting a string and returning a string. Returns `nil` when no solution exists.
-5 bytes: Replace `select{|t|l[t]}` with `select(&l)`
-3 bytes: Replace `map{..}.flatten` with `flat_map{...}`
-1 bytes: Loop over substring length and substring start, instead of over substring start and substring end
-2 bytes: Declare `z` at first use instead of beforehand
```
->s{
l=->t{t==t.reverse} # Lambda to test for palindromes
(1..z=s.size).flat_map{|l| # For each substring length
(0..z-l).map{|i| # For each substring start index
s[i,l] # Take the substring
}
} # flat_map flattens the list of lists of substrings
.select(&l) # Filter to include only palindromic substrings
.permutation # Take all orderings of substrings
.map(&:join) # Flatten each substring ordering into a string
.detect &l # Find the first palindrome
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes
```
ŒʒÂQ}œJʒÂQ}¤
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6KRTkw43BdYenewFYRxa8v9/YlJiIgA "05AB1E – Try It Online")
-1 byte thanks to Magic Octopus Urn and Emigna.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
h_I#sM.p_I#.:
```
[Try it online!](https://tio.run/##K6gsyfj/PyPeU7nYV68ASOlZ/f8fbaijAERGQDIWAA "Pyth – Try It Online")
-1 byte thanks to Mr. Xcoder
[Answer]
# [Python 3](https://docs.python.org/3/), 167 bytes
```
lambda a:g(sum(k,[])for k in permutations(g(a[i:j+1]for i in range(len(a))for j in range(i,len(a)))))[0]
g=lambda k:[e for e in k if e==e[::-1]]
from itertools import*
```
[Try it online!](https://tio.run/##RU1LDsIgFNz3FG8JWhOrOxJOgiwwPvC15RNKF54ewTRxMpnFfDLpU94x3KuVj7oa/3wZMMKxbfdsGZXmNmZYgAIkzH4vplAMG3PMKBLzedI9p55nExyyFQMz/Lea/y6Nh9@grnpw8rhahELoZezl9mMBpUQlxGXSerA5eqCCucS4bkA@xVxONWUKhVmmphEab0015/UL "Python 3 – Try It Online")
-2 bytes thanks to Mr. Xcoder
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 19 bytes
Hampered by Japt not (yet) being able to get *all* substrings of a string (and partly by my current levels of exhaustion!).
Outputs `undefined` if there's no solution.
```
Êõ@ãX fêQÃc á m¬æêQ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=yvVA41ggZupRw2Mg4SBtrObqUQ==&input=ImFuYWEi)
---
## Explanation
```
:Implicit input of string U
Ê :Length of U
õ :Range [1,Ê]
@ Ã :Pass each X through a function
ãX : Substrings of U of length X
f : Filter
êQ : Is it a palindrome?
c :Flatten
á :Permutations
m :Map
¬ : Join to a string
æêQ :Get first element that is a palindrome
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
ḟS=↔mΣPfS=↔Q
```
[Try it online!](https://tio.run/##yygtzv7//@GO@cG2j9qm5J5bHJAGZgX@//9fqSgxOTU5sUgJAA "Husk – Try It Online")
## Explanation
```
ḟS=↔mΣPfS=↔Q Implicit input, a string.
Q List of substrings.
f Keep those
S=↔ that are palindromic (equal to their reversal).
P Permutations of this list.
mΣ Flatten each.
ḟ Find an element
S=↔ that is palindromic.
```
[Answer]
# [J](http://jsoftware.com/), 53 bytes
```
[:{:@(#~b"1)@(i.@!@#;@A.])@(#~(0<#*b=.]-:|.)&>)@,<\\.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62qrRw0lOuSlAw1HTQy9RwUHZStHRz1YjVBohoGNspaSbZ6sbpWNXqaanaaDjo2MTF6/zW5FLhSkzPyFdIU1BPzEhPV4byixOTU5MQihEBGVlZ2DoJraGhkbKzO9R8A "J – Try It Online")
] |
[Question]
[
Who doesn't absolutely love permutations, right? I know, they are amazing––so much fun!
Well, why not take this fun and make it *funner*?
Here's the challenge:
Given an input in the exact form: `nPr`, where `n` is the pool taken from and `r` is the number of selections from that pool (and `n` and `r` are integers), output/return the exact number of permutations. For those of you that are a bit rusty with the terminology: [Permutation, def. 2a](http://dictionary.reference.com/browse/permutation).
However, this is where the challenge comes into play (makes it not too easy):
>
> You may not use any built in library, framework, or method for your permutation function. You may not use a factorial method, permutation method, or anything of the sort; you must write everything yourself.
>
>
>
If further clarification is needed, please, do not hesitate to tell me in the comments and I will promptly act accordingly.
Here is an I/O example:
Sample function is `permute(String) -> int`
Input:
```
permute("3P2")
```
Output:
```
6
```
This is code-golf, so shortest code wins!
[Answer]
# CJam, ~~15~~ 14 bytes
```
r~\;~\),>UXt:*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r~%5C%3B~%5C)%2C%3EUXt%3A*&input=10P4).
### How it works
```
r e# Read a token ("nPr") from STDIN.
~ e# Evaluate. This pushes the numbers n, Pi and r on the stack.
\; e# Discard Pi.
~ e# Take the bitwise NOT of r. Pushes -(r+1).
\) e# Increment n.
, e# Turn n+1 into [0 ... n].
> e# Keep only the last r+1 elements.
UXt e# Replace the first element with 1.
e# This avoid dealing with the egde case nP0 separately.
:* e# Compute their product.
```
[Answer]
# Perl, 27 bytes
```
#!perl -pl61
$\*=$`-$%++for/P/..$'}{
```
Counting the shebang as 4, input is taken from stdin.
---
**Sample Usage**
```
$ echo 3P2 | perl npr.pl
6
$ echo 7P4 | perl npr.pl
840
```
[Answer]
# Haskell, ~~71~~ 66 bytes
```
p s|(u,_:x)<-span(/='P')s,(n,k)<-(read u,read x)=product[n-k+1..n]
```
Pretty straightforward stuff: split at the 'P' then take the product between (n-k+1) and n.
Thanks to nimi for their idea to use pattern guards rather than a `where` clause, it shaved off 5 bytes.
[Answer]
## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), ~~13~~ ~~25~~ 19 bytes
Thanks to **Sp3000** for suggesting this!
```
1nnd3&1N.[d1-]x$*N.
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=1nnd3%261N%2E%5Bd1-%5Dx%24*N.&input=27P0)
### Explanation
```
1 Push 1
n Take integer from input (say, n)
n Take integer from input (say, k); ignores non-numeric characters in the way
d3&1N. Output 1 if k is 0
[ ] Loop k times
d1- Duplicate top of stack and subtract 1
x Dump top of stack
$* Multiply all of it together
N. Output as integer
```
This uses the same algorithm as Alex's: `n P k` = `n(n-1)(n-2)...(n-k+1)`.
[Answer]
# Julia, ~~63~~ ~~58~~ 48 bytes
```
s->((n,r)=map(parse,split(s,"P"));prod(n-r+1:n))
```
This creates an unnamed function that accepts a string and returns an integer. To call it, give it a name, e.g. `f=s->...`.
Ungolfed:
```
function f(s::AbstractString)
# Get the pool and number of selections as integers
n, r = map(parse, split(s, "P"))
# Return the product of each number between n-r+1 and n
return prod(n-r+1:n)
end
```
This uses the fact that the number of permutations is *n*(*n*-1)(*n*-2)...(*n*-*k*+1).
Saved 10 bytes thanks to Glen O!
[Answer]
# Bash + Linux utils, 33
```
jot -s\* ${1#*P} $[${1/P/-}+1]|bc
```
`jot` produces the sequence of `r` integers starting at `n-r+1`, and separates them with `*`. This expression is piped to `bc` for arithmetic evaluation.
[Answer]
# MATLAB, 54 bytes
```
[n,r]=strread(input(''),'%dP%d');disp(prod((n-r+1):n))
```
Tried to make it smaller, but one of the things MATLAB is really bad at is getting inputs. It takes 32 characters just to get the two numbers from the input string!
Fairly self explanatory code. Get the input in the form `%dP%d` where %d is an integer. Split that into `n` and `r`. Then display the product of every integer in the range `n-r+1` to `n`. Interestingly this works even for `xP0` giving the correct answer of 1. This is because in MATLAB the `prod()` function returns 1 if you try and do the product of an empty array. Whenever `r` is zero, the range will be an empty array, so bingo we get 1.
---
This also works perfectly with **Octave** as well. You can try it online [here](http://octave-online.net/).
[Answer]
# Javascript, 59 57 bytes
```
s=>(f=(n,k)=>k?(n- --k)*f(n,k):1,f.apply(f,s.split('P')))
```
[Answer]
## Java(594 - bytes)
```
import java.util.*;import java.lang.*;public class Perm {private String a;private static int[] nr=new int[2];private static int sum=1;Scanner in=new Scanner(System.in);public String input(){a=in.nextLine();return a;}public void converter(String a){this.a=a;String b=a.substring(0,1);String c=a.substring(2);nr[0]=Integer.parseInt(b);nr[1]=Integer.parseInt(c);}public int param(){for(int counter=0; counter < nr[1]; counter++){sum=sum*nr[0]--;}return sum;}public static void main(String args[]){Perm a;a=new Perm();String k=a.input();a.converter(k);int ans=a.param();System.out.println(ans);}}
```
[Answer]
# J, 23 bytes
```
^!._1/@(".;._1)@('P'&,)
```
An anonymous function. Example:
```
f =. ^!._1/@(".;._1)@('P'&,)
f '10P4'
5040
```
Explanation:
```
( ;._1)@('P'&,) Split over 'P', and on each slice,
". read a number.
@ Then,
^!._1/ fold (/) with the built-in "stope function" (^!.k) for k=1.
```
The [stope function](http://www.jsoftware.com/jwiki/Vocabulary/hat#stope) I used might border on counting as a built-in... It rests somewhere between the generality of the multiplication operator and the specificity of the factorial operator.
[Answer]
# APL, 23
```
{{×/⍵↑⍳-⍺}/-⍎¨⍵⊂⍨⍵≠'P'}
```
Takes the string as argument. Explanation:
```
⍵⊂⍨⍵≠'P' ⍝ Split by 'P'.
-⍎¨ ⍝ Convert to numbers and negate making a vector (−n −r)
{ }/ ⍝ Reduce it by a defined function, which
⍳-⍺ ⍝ makes a vector of numbers from 1 to n (⍺)
⍵↑ ⍝ takes r last elements (⍵←−r)
×/ ⍝ and multiplies them together.
```
[Answer]
## Python 2, 66
```
def f(s):a,b=map(int,s.split('P'));P=1;exec"P*=a;a-=1;"*b;print P
```
Pretty straightforward. Processes the number input as `a,b`. Keeps a running product as `P`, which is multiplied by the first `b` terms of `a, a-1, a-2, ...`.
[Answer]
## TI-BASIC, 52 bytes
```
Ans→Str1
expr(sub(Ans,1,⁻1+inString(Ans,"P→P ;n
1
If expr(Str1 ;If n^2*r ≠ 0
prod(randIntNoRep(P,P+1-expr(Str1)/P²
Ans
```
TI-BASIC has a "product of a list" function, so getting around the restriction on builtins isn't too hard. However, TI-BASIC doesn't support empty lists—so we need to
To extract the two numbers, I extract the first number as a substring. This is *expensive*; it takes up the whole second line. To keep from needing to do this again for the second number, I set the variable P to that number, and evaluate the whole string using `expr(`, then divide by P².
Finally, I take a random permutation of the list between the two numbers (taking care to add one to the second number) and take the product.
[Answer]
## [Ouroboros](https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros), ~~47~~ 45 bytes
Some of this is pretty ugly--I'd imagine it could be golfed further.
```
Sr.r-1(
)s.!+S1+.@@.@\<!@@*Ys.!+*S.!!4*.(sn1(
```
Each line of code in Ouroboros represents a snake eating its tail.
### Snake 1
`S` switches to the shared stack. `r.r` reads one number, duplicates it, and reads another. (Nonnumeric characters like `P` are skipped.) `-` subtracts the two. If the input was `7P2`, we now have `7`, `5` on the shared stack. Finally, `1(` eats the final character of the snake. Since this is the character that the instruction pointer is on, the snake dies.
### Snake 2
`)s` does nothing the first time through. `.!+` duplicates the top of snake 2's stack, checks if it's zero, and if so adds 1. On the first iteration, the stack is empty and treated as if it contained infinite zeros, so this pushes `1`; on later iterations, the stack contains a nonzero value and this has no effect.
Next, `S` switches to the shared stack, where we have the number `n` and a counter for calculating the product. `1+` increments the counter. `.@@.@\<!` duplicates both numbers and pushes 1 if `n` is still greater than or equal to the counter, 0 otherwise. `@@*Y` then multiplies the counter by this quantity and yanks a copy onto snake 2's stack.
`s.!+` switches back to snake 2's stack and uses the same code as earlier to convert the top number to 1 if it was 0 and keep it the same otherwise. Then `*` multiplies the result by the partial product that was sitting on this stack.
We now go back to the shared stack (`S`), duplicate the counter-or-zero (`.`), and negate it twice (`!!`) to turn a nonzero counter into a 1. `4*.(` multiplies this by 4, duplicates, and eats that many characters from the end of the snake.
* If we haven't reached the halting condition, we've got a 4 on the stack. The four characters after the `(` are eaten, and control loops around to the beginning of the code. Here `)` regurgitates four characters, `s` switches back to snake 2's stack, and execution continues.
* If the counter has passed `n`, we've got a 0 on the stack, and nothing is eaten. `sn` switches to snake 2's stack and outputs the top value as a number; then `1(` eats the last character and dies.
The result is that the product `(r+1)*(r+2)*...*n` is calculated and output.
### Try it out
```
// Define Stack class
function Stack() {
this.stack = [];
this.length = 0;
}
Stack.prototype.push = function(item) {
this.stack.push(item);
this.length++;
}
Stack.prototype.pop = function() {
var result = 0;
if (this.length > 0) {
result = this.stack.pop();
this.length--;
}
return result;
}
Stack.prototype.top = function() {
var result = 0;
if (this.length > 0) {
result = this.stack[this.length - 1];
}
return result;
}
Stack.prototype.toString = function() {
return "" + this.stack;
}
// Define Snake class
function Snake(code) {
this.code = code;
this.length = this.code.length;
this.ip = 0;
this.ownStack = new Stack();
this.currStack = this.ownStack;
this.alive = true;
this.wait = 0;
this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
if (!this.alive) {
return null;
}
if (this.wait > 0) {
this.wait--;
return null;
}
var instruction = this.code.charAt(this.ip);
var output = null;
console.log("Executing instruction " + instruction);
if (this.partialString !== null) {
// We're in the middle of a double-quoted string
if (instruction == '"') {
// Close the string and push its character codes in reverse order
for (var i = this.partialString.length - 1; i >= 0; i--) {
this.currStack.push(this.partialString.charCodeAt(i));
}
this.partialString = null;
} else {
this.partialString += instruction;
}
} else if (instruction == '"') {
this.partialString = "";
} else if ("0" <= instruction && instruction <= "9") {
if (this.partialNumber !== null) {
this.partialNumber = this.partialNumber + instruction; // NB: concatenation!
} else {
this.partialNumber = instruction;
}
next = this.code.charAt((this.ip + 1) % this.length);
if (next < "0" || "9" < next) {
// Next instruction is non-numeric, so end number and push it
this.currStack.push(+this.partialNumber);
this.partialNumber = null;
}
} else if ("a" <= instruction && instruction <= "f") {
// a-f push numbers 10 through 15
var value = instruction.charCodeAt(0) - 87;
this.currStack.push(value);
} else if (instruction == "$") {
// Toggle the current stack
if (this.currStack === this.ownStack) {
this.currStack = this.program.sharedStack;
} else {
this.currStack = this.ownStack;
}
} else if (instruction == "s") {
this.currStack = this.ownStack;
} else if (instruction == "S") {
this.currStack = this.program.sharedStack;
} else if (instruction == "l") {
this.currStack.push(this.ownStack.length);
} else if (instruction == "L") {
this.currStack.push(this.program.sharedStack.length);
} else if (instruction == ".") {
var item = this.currStack.pop();
this.currStack.push(item);
this.currStack.push(item);
} else if (instruction == "m") {
var item = this.ownStack.pop();
this.program.sharedStack.push(item);
} else if (instruction == "M") {
var item = this.program.sharedStack.pop();
this.ownStack.push(item);
} else if (instruction == "y") {
var item = this.ownStack.top();
this.program.sharedStack.push(item);
} else if (instruction == "Y") {
var item = this.program.sharedStack.top();
this.ownStack.push(item);
} else if (instruction == "\\") {
var top = this.currStack.pop();
var next = this.currStack.pop()
this.currStack.push(top);
this.currStack.push(next);
} else if (instruction == "@") {
var c = this.currStack.pop();
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(c);
this.currStack.push(a);
this.currStack.push(b);
} else if (instruction == ";") {
this.currStack.pop();
} else if (instruction == "+") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a + b);
} else if (instruction == "-") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a - b);
} else if (instruction == "*") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a * b);
} else if (instruction == "/") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a / b);
} else if (instruction == "%") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a % b);
} else if (instruction == "_") {
this.currStack.push(-this.currStack.pop());
} else if (instruction == "I") {
var value = this.currStack.pop();
if (value < 0) {
this.currStack.push(Math.ceil(value));
} else {
this.currStack.push(Math.floor(value));
}
} else if (instruction == ">") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a > b));
} else if (instruction == "<") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a < b));
} else if (instruction == "=") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a == b));
} else if (instruction == "!") {
this.currStack.push(+ !this.currStack.pop());
} else if (instruction == "?") {
this.currStack.push(Math.random());
} else if (instruction == "n") {
output = "" + this.currStack.pop();
} else if (instruction == "o") {
output = String.fromCharCode(this.currStack.pop());
} else if (instruction == "r") {
var input = this.program.io.getNumber();
this.currStack.push(input);
} else if (instruction == "i") {
var input = this.program.io.getChar();
this.currStack.push(input);
} else if (instruction == "(") {
this.length -= Math.floor(this.currStack.pop());
this.length = Math.max(this.length, 0);
} else if (instruction == ")") {
this.length += Math.floor(this.currStack.pop());
this.length = Math.min(this.length, this.code.length);
} else if (instruction == "w") {
this.wait = this.currStack.pop();
}
// Any unrecognized character is a no-op
if (this.ip >= this.length) {
// We've swallowed the IP, so this snake dies
this.alive = false;
this.program.snakesLiving--;
} else {
// Increment IP and loop if appropriate
this.ip = (this.ip + 1) % this.length;
}
return output;
}
Snake.prototype.getHighlightedCode = function() {
var result = "";
for (var i = 0; i < this.code.length; i++) {
if (i == this.length) {
result += '<span class="swallowedCode">';
}
if (i == this.ip) {
if (this.wait > 0) {
result += '<span class="nextActiveToken">';
} else {
result += '<span class="activeToken">';
}
result += escapeEntities(this.code.charAt(i)) + '</span>';
} else {
result += escapeEntities(this.code.charAt(i));
}
}
if (this.length < this.code.length) {
result += '</span>';
}
return result;
}
// Define Program class
function Program(source, speed, io) {
this.sharedStack = new Stack();
this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
var snake = new Snake(snakeCode);
snake.program = this;
snake.sharedStack = this.sharedStack;
return snake;
}.bind(this));
this.snakesLiving = this.snakes.length;
this.io = io;
this.speed = speed || 10;
this.halting = false;
}
Program.prototype.run = function() {
this.step();
if (this.snakesLiving) {
this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
}
}
Program.prototype.step = function() {
for (var s = 0; s < this.snakes.length; s++) {
var output = this.snakes[s].step();
if (output) {
this.io.print(output);
}
}
this.io.displaySource(this.snakes.map(function (snake) {
return snake.getHighlightedCode();
}).join("<br>"));
}
Program.prototype.halt = function() {
window.clearTimeout(this.timeout);
}
var ioFunctions = {
print: function (item) {
var stdout = document.getElementById('stdout');
stdout.value += "" + item;
},
getChar: function () {
if (inputData) {
var inputChar = inputData[0];
inputData = inputData.slice(1);
result = inputChar.charCodeAt(0);
} else {
result = -1;
}
var stdinDisplay = document.getElementById('stdin-display');
stdinDisplay.innerHTML = escapeEntities(inputData);
return result;
},
getNumber: function () {
while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
inputData = inputData.slice(1);
}
if (inputData) {
var inputNumber = inputData.match(/\d+/)[0];
inputData = inputData.slice(inputNumber.length);
result = +inputNumber;
} else {
result = -1;
}
var stdinDisplay = document.getElementById('stdin-display');
stdinDisplay.innerHTML = escapeEntities(inputData);
return result;
},
displaySource: function (formattedCode) {
var sourceDisplay = document.getElementById('source-display');
sourceDisplay.innerHTML = formattedCode;
}
};
var program = null;
var inputData = null;
function showEditor() {
var source = document.getElementById('source'),
sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
stdin = document.getElementById('stdin'),
stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
source.style.display = "block";
stdin.style.display = "block";
sourceDisplayWrapper.style.display = "none";
stdinDisplayWrapper.style.display = "none";
source.focus();
}
function hideEditor() {
var source = document.getElementById('source'),
sourceDisplay = document.getElementById('source-display'),
sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
stdin = document.getElementById('stdin'),
stdinDisplay = document.getElementById('stdin-display'),
stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
source.style.display = "none";
stdin.style.display = "none";
sourceDisplayWrapper.style.display = "block";
stdinDisplayWrapper.style.display = "block";
var sourceHeight = getComputedStyle(source).height,
stdinHeight = getComputedStyle(stdin).height;
sourceDisplayWrapper.style.minHeight = sourceHeight;
sourceDisplayWrapper.style.maxHeight = sourceHeight;
stdinDisplayWrapper.style.minHeight = stdinHeight;
stdinDisplayWrapper.style.maxHeight = stdinHeight;
sourceDisplay.textContent = source.value;
stdinDisplay.textContent = stdin.value;
}
function escapeEntities(input) {
return input.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function resetProgram() {
var stdout = document.getElementById('stdout');
stdout.value = null;
if (program !== null) {
program.halt();
}
program = null;
inputData = null;
showEditor();
}
function initProgram() {
var source = document.getElementById('source'),
stepsPerSecond = document.getElementById('steps-per-second'),
stdin = document.getElementById('stdin');
program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
hideEditor();
inputData = stdin.value;
}
function runBtnClick() {
if (program === null || program.snakesLiving == 0) {
resetProgram();
initProgram();
} else {
program.halt();
var stepsPerSecond = document.getElementById('steps-per-second');
program.speed = +stepsPerSecond.innerHTML;
}
program.run();
}
function stepBtnClick() {
if (program === null) {
initProgram();
} else {
program.halt();
}
program.step();
}
function sourceDisplayClick() {
resetProgram();
}
function stdinDisplayClick() {
resetProgram();
}
```
```
.container {
width: 100%;
}
.so-box {
font-family:'Helvetica Neue', Arial, sans-serif;
font-weight: bold;
color: #fff;
text-align: center;
padding: .3em .7em;
font-size: 1em;
line-height: 1.1;
border: 1px solid #c47b07;
-webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
background: #f88912;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
display: inline-block;
border-radius: 6px;
float: left;
margin-right: 25px;
cursor: pointer;
}
.option {
padding: 10px 20px;
margin-right: 25px;
float: left;
}
h1 {
text-align: center;
font-family: Georgia, 'Times New Roman', serif;
}
a {
text-decoration: none;
}
input, textarea {
box-sizing: border-box;
}
textarea {
display: block;
white-space: pre;
overflow: auto;
height: 50px;
width: 100%;
max-width: 100%;
min-height: 25px;
}
span[contenteditable] {
padding: 2px 6px;
background: #cc7801;
color: #fff;
}
#stdout-container, #stdin-container {
height: auto;
padding: 6px 0;
}
#reset {
float: right;
}
#source-display-wrapper , #stdin-display-wrapper{
display: none;
width: 100%;
height: 100%;
overflow: auto;
border: 1px solid black;
box-sizing: border-box;
}
#source-display , #stdin-display{
font-family: monospace;
white-space: pre;
padding: 2px;
}
.activeToken {
background: #f93;
}
.nextActiveToken {
background: #bbb;
}
.swallowedCode{
color: #999;
}
.clearfix:after {
content:".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
display: inline-block;
}
* html .clearfix {
height: 1%;
}
.clearfix {
display: block;
}
```
```
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
<textarea id="source" placeholder="Enter your program here" wrap="off">Sr.r-s1(
)s.!+S1+.@@.@\<!@@*Ys.!+*S.!!4*.(sn1(</textarea>
<div id="source-display-wrapper" onclick="sourceDisplayClick()"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
<textarea id="stdin" placeholder="Input" wrap="off">3P2</textarea>
<div id="stdin-display-wrapper" onclick="stdinDisplayClick()"><div id="stdin-display"></div></div></div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
<span id="steps-per-second" contenteditable>20</span></div></div>
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
FöΠ↑↔ḣmrx'P
```
[Try it online!](https://tio.run/##AR8A4P9odXNr//9Gw7bOoOKGkeKGlOG4o21yeCdQ////M1Ay "Husk – Try It Online")
**How?**
```
x'P # split input on the character 'P'
mr # and map each of the 2 strings to a value;
Fö # now, fold over these 2 values by calculating
Π # the product of
↑ # the first r elements (where r = second value) of
ḣ # the series 1..n (where n = first value)
↔ # reversed
```
] |
[Question]
[
The Great Pyramid of Giza, the largest pyramid in Egypt, is not only the oldest of the Seven Wonders of the Ancient World, but it is also the **only** one to remain largely intact. The Egyptian Pyramids can take up to 20 years to build and are so big that Al-Aziz Uthman, son of the great Saladin who crushed the Crusaders, had to give up demolishing the Great pyramids of Giza because it was deemed **too great a task**. The Egyptian pyramids were mostly built as tombs for the country's Pharaohs and their consorts during the Old and Middle Kingdom periods (c. 2686–1690 BCE), and as of 2008, 138 Egyptian pyramids have been discovered.
The task is to create a program which inputs a sequence of distances separated by a space, and produces 10×10 text pyramids separated by those distances. A distance of 1 is equal to two characters.
A text pyramid will look like this:
```
/\
/--\
/----\
/------\
/--------\
/----------\
/------------\
/--------------\
/----------------\
/------------------\
```
**If the input consists of only a line break, then one pyramid will be produced, as above**. For each pyramid, pyramids to the left are displayed as if they were in front.
## Example I
Input:
```
4 3 1
```
Output:
```
/\ /\ /\/\
/--\ /--\ /--\-\
/----\ /----\/----\-\
/------\/------\-----\-\
/--------\-------\-----\-\
/----------\-------\-----\-\
/------------\-------\-----\-\
/--------------\-------\-----\-\
/----------------\-------\-----\-\
/------------------\-------\-----\-\
```
## Example II
Input:
```
0 9
```
Output:
```
/\ /\
/--\ /--\
/----\ /----\
/------\ /------\
/--------\ /--------\
/----------\ /----------\
/------------\ /------------\
/--------------\ /--------------\
/----------------\/----------------\
/------------------\-----------------\
```
## Example III
Input:
```
11
```
Output:
```
/\ /\
/--\ /--\
/----\ /----\
/------\ /------\
/--------\ /--------\
/----------\ /----------\
/------------\ /------------\
/--------------\ /--------------\
/----------------\ /----------------\
/------------------\ /------------------\
```
The application to fulfill these requirements in the fewest amount of characters is the winner.
Reference: Wikipedia.org
[Answer]
## Windows PowerShell, 122 ~~132~~ ~~133~~ ~~139~~
```
$d=@(-split$input)-gt0
0..9|%{' '*(9-($x=$_))+($a="/$('--'*$_)\")+-join($d|%{' '*(($_-$x-1)*($x-lt$_))
$a[(-2*$_)..-1]})}
```
[Test script](http://svn.lando.us/joey/Public/SO/CG2705/test.ps1).
Random input also makes for nice images:

[Answer]
## Golfscript, 70 characters
```
~]0-:|;10,{:§9\-" "*"/""-"§2**+"\\"+:&|{.§>{§-(2*" "*1$}{-2*&>}if}%n}%
```
Direct port of my [Ruby solution](https://codegolf.stackexchange.com/questions/2705/egyptian-pyramids/2715#2715), so I'm sure it's possible to shorten this by quite a few characters.
[Answer]
## Haskell, 148 characters
```
r=replicate
p d=map(\k->foldr(\n i->r(9-k)' '++'/':r(2*k)'-'++"\\"++drop(11+k)(r(2*n)' '++i))""$d++[0])[0..9]
main=interact$unlines.p.map read.words
```
I'm quite unsatisfied with this! It just feels way too long. Ideas?
[Answer]
## Python, 123 characters
```
N=[10]+map(int,raw_input().split())
for y in range(10):print''.join((2*n*' '+'/'+2*y*'-'+'\ ')[-2*n-1:-1]for n in N)[9-y:]
```
[Answer]
## Ruby 1.9, 116 characters
```
d=gets.split-[?0]
10.times{|i|puts [?\s*(9-i),l=?/+?-*2*i+?\\,d.map{|r|i<(r=r.to_i)??\s*2*(r+~i)+l :l[-2*r,99]}]*""}
```
[Answer]
## Perl, 130 126 132 chars
```
$_=<>;$s=" "x9;map{$k.="/\\"." "x($_-1)if$_}split;$_="$s$k/\\$s\n";for$i(0..9){print;s%\\-%-\\%g;s%\\/%-\\%g;s%\\ %-\\%g;s% /%/-%g}
```
Slightly shorter version which takes input as command-line arguments rather than from stdin:
```
$s=" "x9;map{$k.="/\\"." "x($_-1)if$_}@ARGV;$_="$s$k/\\$s\n";for$i(0..9){print;s%\\-%-\\%g;s%\\/%-\\%g;s%\\ %-\\%g;s% /%/-%g}
```
Can't believe no-one did a regex solution yet. Perl is a long way from being my best language, so this can probably lose a lot more. I'd be interested to see a sed implementation, if someone's up for the challenge.
(Thanks, @mbx, for 4 chars).
[Answer]
## JavaScript, 396 bytes
```
function p(a){for(u=0;u<10;u++){t[u+a][9-u]="/";for(k=9-u+1+a;k<10+u+a;k++)t[k][u]="-";
t[10+u+a][u]="\\"}}function _(a){t=[];for(i=0;i<50;i++){t[i]=[];for(j=0;j<10;j++)t[i][j]=" "
}var a=a.split(" "),b=a.reduce(function(a,b){return a-0+(b-0)})*2;for(i=a.length-1;i>=0;
i--)p(b),b-=a[i]*2-0;p(0);a="";for(j=0;j<10;j++){b="";for(i=0;i<50;i++)b+=t[i][j];
a+=b.replace(/\s+$/,"")+(j<9?"\n":"")}return a}
```
I'm not going to win with JavaScript, but there is a JavaScript entry now :)
Usage: `_("1 2 3")` etc.
[Answer]
## Ruby (112)
Slightly shorter than Ventero's Ruby solution, with a different approach. I just started learning Ruby, so this can probably be reduced quite a bit.
```
s=' '*9+r='/\\';gets.split.map{|i|s+=' '*2*(i.to_i-1)+r}
10.times{puts s;s.gsub!' /','/-';s.gsub!(/\\.?/,'-\\')}
```
[Answer]
# Powershell, ~~105~~ 98 bytes, the strictest reading of the spec
*-7 bytes from migimaru's [answer](https://codegolf.stackexchange.com/a/3430/80745).*
```
($a=' '+-join(,5+$args-gt0|%{' '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}
```
Test script:
```
$f = {
($a=' '+-join(,5+$args-gt0|%{' '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}
}
@(
,(@"
/\
/--\
/----\
/------\
/--------\
/----------\
/------------\
/--------------\
/----------------\
/------------------\
"@)
,(@"
/\ /\ /\/\
/--\ /--\ /--\-\
/----\ /----\/----\-\
/------\/------\-----\-\
/--------\-------\-----\-\
/----------\-------\-----\-\
/------------\-------\-----\-\
/--------------\-------\-----\-\
/----------------\-------\-----\-\
/------------------\-------\-----\-\
"@, 4,3,1)
,(@"
/\ /\
/--\ /--\
/----\ /----\
/------\ /------\
/--------\ /--------\
/----------\ /----------\
/------------\ /------------\
/--------------\ /--------------\
/----------------\/----------------\
/------------------\-----------------\
"@, 0,9)
,(@"
/\ /\
/--\ /--\
/----\ /----\
/------\ /------\
/--------\ /--------\
/----------\ /----------\
/------------\ /------------\
/--------------\ /--------------\
/----------------\ /----------------\
/------------------\ /------------------\
"@, 11)
) | % {
$expected, $a = $_
$result = &$f @a
($result-join"`n")-eq$expected
$result
}
```
Output:
```
True
/\
/--\
/----\
/------\
/--------\
/----------\
/------------\
/--------------\
/----------------\
/------------------\
True
/\ /\ /\/\
/--\ /--\ /--\-\
/----\ /----\/----\-\
/------\/------\-----\-\
/--------\-------\-----\-\
/----------\-------\-----\-\
/------------\-------\-----\-\
/--------------\-------\-----\-\
/----------------\-------\-----\-\
/------------------\-------\-----\-\
True
/\ /\
/--\ /--\
/----\ /----\
/------\ /------\
/--------\ /--------\
/----------\ /----------\
/------------\ /------------\
/--------------\ /--------------\
/----------------\/----------------\
/------------------\-----------------\
True
/\ /\
/--\ /--\
/----\ /----\
/------\ /------\
/--------\ /--------\
/----------\ /----------\
/------------\ /------------\
/--------------\ /--------------\
/----------------\ /----------------\
/------------------\ /------------------\
```
# Powershell, ~~101~~ 94, fun with one leading whitespace
```
($a=-join(,6+$args-gt0|%{' '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}
```
[Answer]
I couldn't get the C#3 version any shorter than this. I don't know the character count exactly, but I suspect that I have lost. :-(
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace PyramidRenderer
{
/// <summary>
/// Generates ASCII-art pyramids at user-specified horizontal locations to
/// the standard output stream.
/// </summary>
public class Program
{
/// <summary>
/// Generates one or more ASCII-art pyramids at the locations specified and
/// sends them to the standard output stream.
/// </summary>
/// <param name="args">The command-line arguments. These should be non-negative
/// integers that specify the horizontal distance of each additional pyramid from the
/// preceeding pyramid. Whether or not any distances are suppplied, a pyramid
/// is rendered at the starting location.</param>
public static void Main(string[] args)
{
try
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
int[] pyramidDistances = ParsePyramidLocationsFromCommandLine(args).ToArray();
PyramidCollection pyramids = new PyramidCollection(pyramidDistances);
pyramids.RenderToText(Console.Out);
}
catch (ArgumentException ex)
{
Console.Error.WriteLine(ex.Message);
}
}
/// <summary>
/// Handler for the unhandled exception. This just displays the error message to
/// the standard error stream.
/// </summary>
/// <param name="sender">Required but unnecessary sender object for the event handler.</param>
/// <param name="e">The object that represents the exception.</param>
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Debug.Assert(e.ExceptionObject != null);
string exceptionText;
Exception ex = e.ExceptionObject as Exception;
if (ex == null)
exceptionText = e.ExceptionObject.ToString();
else
exceptionText = ex.Message;
Console.Error.WriteLine(exceptionText);
}
/// <summary>
/// Takes the command-line arguments and converts them to a sequence of
/// non-negative integers.
/// </summary>
/// <param name="args">The command-line arguments as supplied to Main.</param>
/// <returns>A sequence of integers that represent the user’s distance selections.</returns>
/// <exception cref="ArgumentException">An invalid argument was supplied.</exception>
private static IEnumerable<int> ParsePyramidLocationsFromCommandLine(string[] args)
{
Debug.Assert(args != null);
foreach (string arg in args)
{
int result;
if (int.TryParse(arg, out result))
{
if (result < 0)
throw new ArgumentException(string.Format("Invalid distance specified: {0}", arg));
yield return result;
}
else
{
throw new ArgumentException(string.Format("Invalid option: {0}", arg));
}
}
}
}
/// <summary>
/// Represents a single pyramid to be rendered.
/// </summary>
internal class Pyramid
{
/// <summary>
/// The height of the pyramids in text rows. The width of each pyramid will be
/// twice the height.
/// </summary>
internal const int Height = 10;
/// <summary>
/// The length in characters of the horizontal unit distance in which the user
/// specifies the pyramid distances.
/// </summary>
internal const int PyramidUnits = 2;
/// <summary>
/// The character to output as the background of the pyramids.
/// </summary>
private const char backgroundChar = ' ';
/// <summary>
/// The character to output as the left edge of the pyramids.
/// </summary>
private const char leftEdgeChar = '/';
/// <summary>
/// The character to output within each pyramid, between the edges.
/// </summary>
private const char brickChar = '-';
/// <summary>
/// The character to output as the right edge of the pyramids.
/// </summary>
private const char rightEdgeChar = '\\';
/// <summary>
/// The absolute horizonal location of the pyramid’s bottom left corner as
/// specified in PyramidUnits.
/// </summary>
private int position;
/// <summary>
/// Constructs a new pyramid object at the specified location.
/// </summary>
/// <param name="position">The absolute horizonal location of the pyramid’s bottom
/// left corner in PyramidUnits.</param>
internal Pyramid(int position)
{
Debug.Assert(position >= 0);
this.position = position;
}
/// <summary>
/// Renders a single row the pyramid to the supplied text stream starting at
/// the indicated location.
/// </summary>
/// <param name="textWriter">The output stream to which the pyramid is to
/// be rendered.</param>
/// <param name="row">The row of the pyramid to render. Zero is the top row,
/// and Height - 1 is the bottom row.</param>
/// <param name="startingPosition">The text character position—indexed at zero—at
/// which the rendering is to begin. If non-zero, this identifies the column one
/// past the ending location of the previous pyramid.</param>
/// <returns>The horizontal location (in characters) at which the next item
/// may be rendered.</returns>
internal int RenderRow(TextWriter textWriter, int row, int startingPosition)
{
Debug.Assert(textWriter != null);
Debug.Assert(row >= 0);
Debug.Assert(startingPosition >= 0);
int leftBoundary = Height - 1 - row + position * PyramidUnits;
int rightBoundary = Height + row + position * PyramidUnits;
startingPosition = RenderField(textWriter, backgroundChar, startingPosition, leftBoundary);
startingPosition = RenderField(textWriter, leftEdgeChar, startingPosition, leftBoundary + 1);
startingPosition = RenderField(textWriter, brickChar, startingPosition, rightBoundary);
startingPosition = RenderField(textWriter, rightEdgeChar, startingPosition, rightBoundary + 1);
return startingPosition;
}
/// <summary>
/// Outputs a sequence of repeated characters from the indicated starting position to
/// just before the ending position, unless the starting position is already equal to
/// or greater than the ending position.
/// </summary>
/// <param name="textWriter">The output stream to which the field is to be rendered.</param>
/// <param name="character">The character to be repeated in the output.</param>
/// <param name="startingPosition">The location at which rendering may begin in
/// characters indexed at zero.</param>
/// <param name="endingPosition">The location one past the location at which rendering
/// is to end.</param>
/// <returns>The position at which the next field may begin.</returns>
private static int RenderField(TextWriter textWriter, char character, int startingPosition, int endingPosition)
{
Debug.Assert(textWriter != null);
Debug.Assert(startingPosition >= 0);
Debug.Assert(endingPosition >= 0);
int charCount = endingPosition - startingPosition;
if (charCount <= 0)
return startingPosition;
textWriter.Write(new string(character, charCount));
return endingPosition;
}
}
/// <summary>
/// A collection of pyramids to be displayed.
/// </summary>
internal class PyramidCollection
{
/// <summary>
/// A left-to-right ordered list of the pyramids that the user has
/// requested to be rendered.
/// </summary>
List<Pyramid> allPyramids = new List<Pyramid>();
/// <summary>
/// Constructs a new pyramid collection.
/// </summary>
/// <param name="distances">The distances of each non-leftmost pyramid (in PyramidUnits) after
/// the previous pyramid. The total number of pyramids will be one greater than the length of
/// the distances array.</param>
internal PyramidCollection(int[] distances)
{
Debug.Assert(distances != null);
int nextPosition = 0;
allPyramids.Add(new Pyramid(nextPosition));
foreach (int nextDistance in distances)
{
Debug.Assert(nextDistance >= 0);
try
{
checked
{
nextPosition += nextDistance;
int endLocation = nextPosition * Pyramid.PyramidUnits + Pyramid.Height * 2;
}
}
catch (OverflowException)
{
// Ignore any pyramids specified beyond the integer maximum distance.
break;
}
allPyramids.Add(new Pyramid(nextPosition));
}
}
/// <summary>
/// Outputs ASCII-art images of the pyramids in this collection to the
/// provided output stream.
/// </summary>
/// <param name="textWriter">The output stream to which the pyramids
/// are to be rendered.</param>
internal void RenderToText(TextWriter textWriter)
{
Debug.Assert(textWriter != null);
for (int row = 0; row < Pyramid.Height; row++)
{
int startingPosition = 0;
foreach (Pyramid pyramid in allPyramids)
{
startingPosition = pyramid.RenderRow(textWriter, row, startingPosition);
}
textWriter.WriteLine();
}
}
}
}
```
] |
[Question]
[
*This is not a duplicate of [this challenge](https://codegolf.stackexchange.com/q/71476/9288).*
Here by an *array*, I mean a nested list that is "not ragged", i.e., it is either a list of elements, or a list of arrays of the same shape. For example, this is an array of shape `(2,3)`:
```
[[1, 2, 3], [4, 5, 6]]
```
The *depth* (or *rank*) of an array is the length of its shape. The depth of the array above is `2`.
But we can see every ragged-list as an array, where every element of the array is a either an atom (e.g., an integer) or a ragged-list. For example, the following ragged-list can be seen as an array of shape `(2,3)`:
```
[[1, 2, [3]], [4, [5], [6, [7]]]]
```
The six elements of this array are `1`, `2`, `[3]`, `4`, `[5]`, `[6, [7]]`. As an array, its depth is `2`.
So we can define the ***array depth*** of a ragged list to be its maximum depth as an array.
Or more formally:
* If a ragged list has length \$a\$, we say it is an array of shape \$(a)\$.
* If every element of a ragged list is an array of shape \$(a\_1,\dots,a\_n)\$, and the length of the ragged list is \$a\_0\$, then we say it is an array of shape \$(a\_0,a\_1,\dots,a\_n)\$. (So it is also an array of shape \$(a\_0,a\_1,\dots,a\_{n-1})\$.)
* The ***array depth*** of a ragged list is the maximum length of its shape when we see it as an array.
## Task
Given a non-empty ragged list of positive integers, output its array depth. You may assume that the input does not contain any empty list.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Testcases
```
[1] -> 1
[1, 2, 3] -> 1
[[1, 2, 3]] -> 2
[3, [3, [3], 3], 3] -> 1
[[[[1], 2], [3, [4]]]] -> 3
[[1, 2, 3], [4, 5, 6]] -> 2
[[1, 2, [3]], [4, [5], [6, [7]]]] -> 2
[[1, 2], [3, 4, 5], [6, 7, 8, 9]] -> 1
[[[1, 2]], [[3, 4], [5, 6]]] -> 1
[[1, [2]], [[[3]], [[[4]]]]] -> 2
[[[1], [2]], [[3, 4], [5, 6]]] -> 2
[[[[[[[3]]]]]]] -> 7
```
[Answer]
# JavaScript (ES6), 54 bytes
```
f=a=>a.some(n=>+n.length!=a[0].length)?1:f(a.flat())+1
```
A quite simple approach: check if all elements are the same length, increment a counter if they are and repeat with the list flattened by one level, then return the counter.
-3 bytes thanks to tsh. -1 more thanks to l4m2.
```
f=a=>a.some(n=>+n.length!=a[0].length)?1:f(a.flat())+1
console.log(f([[[[1,2],[3,4]]]]))
console.log(f([[[[[[3, []]]]]]]))
console.log(f([[1, 2], [3, 4, 5], [6, 7, 8, 9]]))
console.log(f([[[1, 2]], [[3, 4], [5, 6]]]))
```
[Answer]
# [Python](https://www.python.org)/NumPy, 23 bytes
Thx @pxeger for clarifying the legalese.
```
from numpy import*
ndim
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBfisIwEMbxNacY-5TIuNBWrS644DlCHoRVDDR_qKnSs-xLX9wr7Fn0NDZN2m1gYOabX76Z5OfXNu5idNs-andebv_OlVGga2UbkMqayi2I_pYqdJ-H-0WWJ0g_CUg0sAd1tPR0O5Yota0dZR9XW0pHE1h-QcIYAVtJ7ai3oJKhYcGofc3mPBWeSglPETKEfCjHuhcywnOEEMKrU7JjuzoTEVgJES7lExevI6wRNqNh7HWGscvXPtl0UQwWAxa9vUVkCoQtwk78b9FzvtuTPgnjpi_ikYhDeVh2HNWfXIhRLEj4qjc)
#### Not entirely legal [Python](https://www.python.org)/NumPy 22 bytes
```
from numpy import ndim
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZBNasMwEIXpVqd4zUqCScF2E6eBFnoOoUWgCRFYPzhySs7SjTftEXqX9jS1LNm1YGDmzac3I318-Vs4O9v3n104rXffp9YZ2M74G7Txrg2wb9qk5s_r-1k3RxR7Bk0OzzAHz4_XQ0Pa-i5w8XDxjQ58hfULVkIw-FbbwKMF14KcSEb97929LFSkCiYLQkmopnKuR6FksiKkUFFdkgM71KXKwKNS6VK1cIk6YUPYzoa5NxjmrtzEZDtEPVlMWPaOFpmpCTvCk_rfYuRidyRjksYtXyQzkYfKtOw8ajyVUrNYs_RVfw)
Builtin (in case you haven't noticed).
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 22 bytes
```
l<itr(K**l$rH lp)<pM[]
```
Takes input as a free monad of lists (`Free List a`).
## Explanation
Our strategy here is to calculate the "shape" of the array first and then derive its depth from that. We represent a shape as a list of sizes.
We are going to use a recursive strategy. Our base case is a terminal element which has shape `[]` and our inductive case is a list. If we have the shape of every element of a list then we know its shape is longest common prefix of all their shapes and add its own length to the front.
With that `itr x<pM y` will let us do this recursion. We already said `y` was `[]` so that's easy. Now we just need the other function.
`lp` gets the longest common prefix of two lists so `rH lp` gets the longest common prefix of a list of lists. We add `K**l` to put its own length on the front.
So our result is
```
itr(K**l$rH lp)<pM[]
```
which gets the shape of a array. But we need the *depth* so we add an extra `l<` to get the length of the shape.
## Reflections
* On my dev branch I've already made a alias for `(**)K`. This would have come in use on this challenge here as well. It would have saved 2 bytes `l<itr(l*:*rH lp)<pM[]`
* This is not the first time I've used `itr` and `pM` together in this way. When we only care about the shape of a free it's very useful to first replace all the elements and then iterate. This should have it's own name. It would have saved ~~3~~ 4 bytes: `l<shp(K**l$rH lp)i` (an extra byte is saved because `[]` can be replaced with `i` to save a byte whereas in the original `i` and `[]` are the same length)
[Answer]
# [R](https://www.r-project.org/), 78 bytes
```
f=function(r)sum(1,if(all(Map(is.list,r))&!sd(lengths(c(r,r))))f(unlist(r,F)))
```
[Try it online!](https://tio.run/##jZHBDoIwDIbvPkWNiWmTagIo6EGP3nwGQwSUBNFscPDpkeHACQpcaFb@fvv/VRS@EP7zFISP7Lorol2Up@csvqcoSOY3tDiO0E8SPPoPjOUyiWXGgmg@lQEmYXrJrhLPKFSPKMI8VYryfCiPJhurvkUEM1jswZp0/zHYDE6P4lumdXZX5zB8V1IDI9jGLaXcphZnpTJqhDNgrx5hWDO4fW6NMe3WGK7qum64unqGkT6iEUAZMTAew4ZhS6NepELVww2wbuh8w2uragvUSvz5vN96IGOzql/o/x7twfV3DZp2vEnxAg "R – Try It Online")
[Answer]
# Python3, 107 bytes:
```
f=lambda x,c=0:int in[*map(type,x)]or any(len(i)!=(c:=c or len(x[0])) for i in x)or min(1+f(i,c)for i in x)
```
[Try it online!](https://tio.run/##dZJNbsMgEIXX9Smm2RhaGsVx89NI9Ai9AEUVdbBKYmNkUOWc3gUbu95kgTTz5s03A8Lc3E@j86Np@76klai/zwI6UtDNSWkHSrOnWhjkbkaSDvOmBaFvqJIaKfxIUXGiBXgxCB3bcIyh9KnyjdBhH9VKo@y5RIoUeFHpLV2tVizj8PIOWcIyAlsC@ZTO@SBsE5YTGA8P6tLpvT7f8mh45XxsyheUoBPYEdjPwFjzwFhluxDs/TlMiMkW2QERPQcCRwJv/H@LwReqgzME47jljVh0xKFsXHYeNVyE3acMHja2z40H/4yJqk3TOhDWJfMbl6pyskUfjZYE7NqaSjmUfuoU41PycCFXoKAmOZBSnDwIa6UHlcij1r4iW1F9yV9RoQvGlPofga7Yb3Uhdzw8MW1wpU5aZ8EE4NmT@z8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes
```
W⁼⌊EθL⁺⟦⟧κ∨⌈EθL⁺⟦⟧κω«≔⟦⟧ζFθFκ⊞ζλ≔ζθ⊞υω»I⊕Lυ
```
[Try it online!](https://tio.run/##jU09D4IwFJzhV7zxNamDnwuTMQ4mEtkJQ4MVGkqRlorB@NtrS/gB3nDvXe5yV9ZMlx2Tzo21kBzw3FsmDaZCida2mLIn9hSuXFVDjZm0BvOCQkM8KNy0D7z/CI6e4RNHR2NEpWZnIkkcPToN2BOYb0Mgs6bGiYIM5hL2sg9y9mzoSuJvnGmhBjwxM@BFlZq3XA38jsu@DbOJc7nH2o/lmyJwvqWwC8@ewqHwcKuX/AE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W⁼⌊EθL⁺⟦⟧κ∨⌈EθL⁺⟦⟧κω«
```
Convert any numbers in the array to empty lists by vectorised adding them to the empty list (this leaves arrays unchanged). Compare their minimum and maximum length, unless the maximum length is `0` i.e. if the array only contains integers. Repeat while all arrays have the same length.
```
≔⟦⟧ζFθFκ⊞ζλ≔ζθ
```
Flatten the array.
```
⊞υω
```
Keep track of the number of loops.
```
»I⊕Lυ
```
Output the final depth.
33 bytes using the newer version of Charcoal on ATO:
```
W⁼⌊EθL⁺⟦⟧κ∨⌈EθL⁺⟦⟧κω«≔Σθθ⊞υω»I⊕Lυ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jY69CsIwFIXn9ilCpyukQ_1D6CTiIFgsOIYOscY2mEbbJFYQn8TFQUHwiXwbE6i7Z_i4XM45995eeUmb_EDF_f40ehdOPu-25IIhmNeGCgUJl7wyFST0CDVGSyYLXUIqjAKSYbTvWWG0aqzh_IextUQX35sqxQsJaxuo7bruxb6XGlWCcZ7Yv_ppw6WGGVUaFjJvWMWkZlvoeo2rix9qk6vf4xEJwpMIMApC7kisInuZ9DNHMsBo6IYRRuPMKsi65Bc "Charcoal – Attempt This Online") Link is to verbose version of code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Seems long!
```
¬RẎƬṖẈ€E€i0oLƲ
```
A monadic Link accepting a list that yields the "array-depth".
**[Try it online!](https://tio.run/##y0rNyan8///QmqCHu/qOrXm4c9rDXR2Pmta4AnGmQb7PsU3/D7cD2f//R0cbxnLpRBvqKBjpKBiDmHA2iGOsowDBsSARmAqQJqCiWKikSWxsLIpOkJiOgqmOghmyONAQqEy0KYhhBsTmyFqh5oG0QuXNdRQsdBQsIUqiLUBqQDJgVSAGxAqYAdFQWahF0RCHQfSCHByNWzcYGMdCAFcsAA "Jelly – Try It Online")**
### How?
Uses the same intuition as [emanresu A's JavaScript answer](https://codegolf.stackexchange.com/a/241157/53748)
```
¬RẎƬṖẈ€E€i0oLƲ - Link: list, A
¬ - logical NOT - converts all integers to zeros
R - range (vectorises) - converts all zeros to empty lists
Ƭ - collect up inputs while distinct, applying:
Ẏ - tighten
Ṗ - pop - remove the final one
Ẉ€ - lenth of each for each
E€ - all-equal for each
Ʋ - last four links as a monad, f(that):
i0 - first 1-indexed index of a zero (or zero)
oL - logical OR with the length
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
SмΔ¼D€gË≠i¾q}€`}¾<
```
Inspired by [*@emanresuA*'s JavaScript answer](https://codegolf.stackexchange.com/a/241157/52210).
[Try it online](https://tio.run/##yy9OTMpM/f8/@MKec1MO7XF51LQm/XD3o84FmYf2FdYCeQm1h/bZ/P8fHR1tqKNgFBuroxAdbayjYAJimOoomMXGxgIA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f/gC3vOTTm0x@VR05r0w92POhdkHtqno3doa2EtUCQmofbQPpv/ID4XSBtXeUZmTqpCUWpiikJmHldKPpeCgn5@QYk@xHQohWahjYIKWG1e6v9ow1iuaEMdBSMdBWMgC84Eso11FCA4FiQAlQeqADKNYqFyJrGxscjaQEI6CqY6CmZIwkAToBLRpiCGGRCbI2mEGgbSCJU211Gw0FGwBKuAKAFJgBWBGBDzodqjoZJQW6IhboLojEVIY@oFA@PYWLhy3DbFcgEA).
I initially had [this 13-byter](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/9NzLuw5N8XlUdOa9MPdh/YC6YTaQ/ts/uvoHdr6PzraMFZHIdpQR8FIR8EYxISzQRxjGI6FyEJUQDQZwRSYxMbGougEiekomOoomCGLR0OMBMpEm4IYZkBsjqwVah5IK1TeXEfBQkfBEqIEogbMBKkCMSBWwAyIhspCLYqGOAyqNxYhj0U3GBjHxiI04LYtNhYA), but unfortunately it fails for test cases like `[[[1,2]],[[3,4],[5,6]]]`.
**Explanation:**
```
Sм # Convert all integers to an empty string:
S # Convert the (implicit) input-list to a flattened list of digits
м # Remove all those digits from each inner-most integer/string of
# the (implicit) input-list
Δ # Loop until the list no longer changes:
¼ # Increase the counter variable by 1 (starts at 0)
D # Duplicate the current list
€g # Get the length of each inner item
Ë≠i # If they are NOT all the same length:
¾ # Push the counter variable
q # And stop the program
# (after which this is output implicitly as result)
} # Close the if-statement
€` # Flatten one level down
}¾ # After the loop: push the counter variable
< # Decrease it by 1 (because the last two iterations were the same
# for the loop to stop)
# (after which this is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~75~~...... 54 bytes
```
f=->a{a.map(&:size).uniq.one?&&a.flatten!(1)?1+f[a]:1}
```
[Try it online!](https://tio.run/##fZDdCoJAEIXve4qJQJTGpdVSC6oHGfZiCwXB7P@iome3Wd3CyroY9uec@c7sHs6rS1Vlc3@hb1ps9M51Zsf8mnriXOZ7sS3TpeNokRX6dErLviu9pRxmpNVM3qsdZGKti8IlqbwB@AuQvdYdQoAQGuVTemlPMWiJIUJTyjh@EZjBWqCseazUCxZ2JRkPwgQh6gy1Pg61TpqYTcQVt9BfLTbfoK0/RkgQpqp76rrHOOsus2lG@vVLZN12MGoe2jlO/SH0l/7upwbbBsYV0Qg5mB/GDA5DYkbES4wJn6bqAQ "Ruby – Try It Online")
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 5 bytes
```
Uˡ{Ťj
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FstDTy-sProka0lxUnIxVGzBLUaOaMNYrmhDHQUjHQVjIAvOBLKNdRQgOBYkAJUHqgAyjWKhciaxsbHI2kBCOgqmOgpmSMJAE6AS0aYghhkQmyNphBoG0giVNtdRsNBRsASrgCgBSYAVgRgQ86Hao6GSUFuiIW6C6IxFSGPqBQPjWAiAhAgA)
```
Uˡ{Ťj
U Wrap the input in a singleton list
ˡ{ Loop until failure, and return the number of iterations:
Ť Transpose; fails if it is not a rectangular 2D array
j Join
```
] |
[Question]
[
There are 31 positive integers that cannot be expressed as the sum of 1 or more distinct positive squares:
```
2, 3, 6, 7, 8, 11, 12, 15, 18, 19, 22, 23, 24, 27, 28, 31, 32, 33, 43, 44, 47, 48, 60, 67, 72, 76, 92, 96, 108, 112, 128
```
There are 2788 positive integers that cannot be expressed as the sum of 1 or more distinct positive cubes:
```
2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 66, 67, 68, 69, 70, 71, 74, 75, 76, ...
```
It has been proven that this sequence is finite for all powers, and the largest term in each sequence is part of the [Anti-Waring numbers](https://cs.uwaterloo.ca/journals/JIS/VOL20/Prier/prier3.html), specifically \$N(k,1)-1\$, for a power \$k\$.
You are to take a positive integer \$n > 1\$ as input, and output *all* positive integers that **cannot** be expressed as the sum of 1 or more distinct positive integers to the power of \$n\$. You may output the integers in any clear and consistent format (as digits, unary, Church numerals etc.) and you may use any clear and consistent separator between the numbers (newlines, spaces, as a list, etc.).
Your program *must* terminate, through error or natural termination, in finite time; iterating over all integers and outputting those that cannot be expressed in such a form is not an acceptable method.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
2 -> 2, 3, 6, 7, 8, 11, 12, 15, 18, 19, 22, 23, 24, 27, 28, 31, 32, 33, 43, 44, 47, 48, 60, 67, 72, 76, 92, 96, 108, 112, 128
3 -> 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, ...
4 -> 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, ...
5 -> 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, ...
6 -> 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 66, 67, 68, 69, 70, 71, 72, 73, ...
7 -> 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, ...
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 26 bytes [SBCS](https://github.com/abrudz/SBCS)
```
⊢{z~∊(⊢,+)\⍺*⍨z←⍳!⍵}!×2*×⍨
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9S1qLqq7lFHl8ajrkU62poxj3p3aT3qXVH1qG3Co97Nio96t9YqHp5upHV4OlAUAA&f=S3/UNqG6qu5RR5fGo65FOtqaMY96d2k96l1RBZR41Lv5Ue/WWi4jhXQFQwMA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
This only works theoretically in multiple ways. The upper bound used (factorial of `c = n! * 2^(n^2)`is way too high to be accurately computed in floats, it would take forever to accurately compute it as a bigint, and it would quickly go out of memory trying to compute its range and all subset sums of *that*. As a minimal evidence of correctness, the function `g` in the link instead takes an explicit `limit` on its right and `n` on its left, and computes all numbers up to `limit` that are non-sums of distinct n-th powers.
### Deriving a correct and simple upper bound
[A001661](http://oeis.org/A001661) contains a formula for the upper bound of the last term for each n. I was able to simplify it in many steps (and greatly overshoot the bound in the process) to just 7 bytes of APL:
```
d*2^(n-1)*(c*2^n + (2/3)*d*(4^n - 1) + 2*d - 2)^n + c*d
where c = n!*2^(n^2) and d = 2^(n^2 + 2*n)*c^(n-1) - 1
= d*(c + 2^(n-1)*(c*2^n + (2/3)*d*(4^n + 2) - 2)^n)
= d*(2*c + (2*c*2^n + (4/3)*d*(4^n + 2) - 4)^n)/2
by 2c<n^n*(2^n)^n = (n*2^n)^n
and a^n+b^n<(a+b)^n
= d*(n*2^n + 2*c*2^n + (4/3)*d*(4^n+2)-4)^n/2
by n*2^n + 2*c*2^n < c*(2^(n+1)+1) < 2^(n^2+2*n)*c <= d + 1
<= d*(d + 1 + (4/3)*d*(4^n+2)-4)^n/2
= d*(d*(4^(n+1)/3+11/3)-3)^n/2
by 4^(n+1)/3+11/3 < c
and 2^(n^2 + 2*n) = 2^(n^2)*4^n <= 2^(n^2)*n!*64/6
which gives d < c^n*64/6
< c^n*64/6 * (c^n*64/6 * c)^n/2
= c^(n^2+2n) * (32/3)^(n+1)/2
by (32/3)^(n+1)/2 < c^2
(for n=2 = 16384/27 < 607)
(for n=3 < 6475)
< c^(n^2+2n+2)
< c!
The APL formula for `c!`: !!×2*×⍨
```
### The code
```
⊢{z~∊(⊢,+)\⍺*⍨z←⍳!⍵}!×2*×⍨ Monadic train. ⍵←n
!×2*×⍨ c = n!*2^(n^2)
⊢{ } Pass to a dyadic dfn, ⍺←n, ⍵←above
z←⍳!⍵ z ← 1..c!
⍺*⍨ Raise each to the power of n
∊(⊢,+)\ Compute all sums of distinct powers
z~ Remove them from z
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~80 ... 72~~ 71 bytes
```
->n,*w{*r=0;a=1;1while w!=w|=[*(z=a**n)..(a+=1)**n]-r|=r.map{|y|y+z};w}
```
[Try it online!](https://tio.run/##JcbRCkAwFADQd1/B21wsw9u6fmTtYYoopJVus/n2IU/n2HNwccJY9XsJ5MFiLQ0KKWhe1jGlDCmgAnahAdhzzpkpUOTvdWUDWr6ZwwcXXHHdku54pJNqdPLR/nQ6Pg "Ruby – Try It Online")
### Explanation:
The algorithm stops when no new numbers are found between `(x-1)^n` and `x^n`. When that range is covered, then by just adding `x^n` we can cover the range up to `2*x^n`. I assume that's enough to reach `(x+1)^n` (but alas, I can't prove it, sorry)
[Answer]
# [Python 2](https://docs.python.org/2/), 97 bytes
```
n=input()
q=x=1
w=0
a=n**n<<n*n
while q<a**a:
if w**n<q:w+=1;x|=x<<w**n
if~x>>q&1:print q
q+=1
```
[Try it online!](https://tio.run/##FcoxDoMwDEDR3afwhKhZGsbU5i4ZiohUuTFKlVRCXD2Q9b@f/nn76tyaStT0y@MDTKo4KPKEIEqkzEoKZYufNxoHouAB44qlm/kyiXvVQypzL53Ouiw2OJ/2qBkN0O6ntfkC "Python 2 – Try It Online")
Uses \$\left(n^n2^{n^2}\right)^{n^n2^{n^2}}\$ as an upper bound (Derived from Bubbler's upper bound with \$n^n\ge n!\$). Calculating this takes so much time that there won't be any output for \$n>4\$ on TIO.
---
Here is an alternative approach that doesn't rely on an upper bound but rather terminates when no new number was found in \$\left(w^n, (w+1)^n\right]\$ for some integer \$w\$.
I'm not sure if this is valid, but the highest numbers from \$n=2\$ to \$n=6\$ (see below) match up with the paper linked in the challenge, and I think [the Ruby answer](https://codegolf.stackexchange.com/a/235098/64121) works in a similar way.
```
def f(n):
w=f=q=1;x=3
while f:
w+=1;x|=x<<w**n;f=0
while w**n^q:f|=x>>q&1<1!=print(q);q+=1
```
[Try it online!](https://tio.run/##HctBCoAgFATQfaewTahtkmiTfo/SKj8FYf4INOjupi3nzUx47u30Y86rQ4bci7lhERAIlE4wlrDth2NYmMW@4gvJmCil1whD1X9QYaEZS2stdcqoFsK1@5uT0FSOGfkk8gc "Python 3 – Try It Online")
Here is a more optimized version of the same algorithm that only prints the last integer: [Try it online!](https://tio.run/##LZDNaoRAEITvPkVBYBl3NeAKuxD0Egghh5DL3oOa0RnUns04okLIq5vWyaF/iuqvDn1fnDKUruuXrNEICp8CYEaOlKfmOXF9cyWsJ6U7iZsd5XbFGidvAC2f6H3z0PEI2uWMn5xblv3bJdsiyTIdt3ESxry1Jx@ha8wHtnOUPh6w0o2WIH7ng/CXTISPpXafnaTGKcF6fQDlF4yDHOCMQT9WCr3sjV1QG4vb20eEcnSYjG0HdKYqum4JNuqKyhaDYnDSTuF9h16sZcoQ@gXDMjjZezc9vz4HwZZI0ARbUCPFOcJl/9ndanKCov2J4foH "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
²2*×!!ŒṗQƑƇfƑƇɗÐḟ²€
```
[Try it online!](https://tio.run/##y0rNyan8///QJiOtw9MVFY9OerhzeuCxicfa00DEyemHJzzcMf/QpkdNa/7jkeMyNTjc/v@/EQA "Jelly – Try It Online")
A monadic link taking an integer `n` as its argument and returning a list of integers. Implements @Bubbler’s method for determining the upper bound, so be sure to upvote that one too! While this answer would end in a finite time, it would be a very very long time even for n=2, and requires a huge amount of RAM (enough to generate integer partitions of \$3072!\$). I’ve therefore included a footer on TIO which demonstrates that the rest of the code works for integers up to 50.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 202 bytes, (Compact™)
```
g=lambda x:x<2or x*g(~-x);from itertools import*
def f(n,q=2):
while q<g(g(n)*2**n**n):k=[x**n for x in range(1,q)];q not in[sum(h)for l in range(1,-~len(k))for h in combinations(k,l)]and print(q);q+=1
```
[Try it online!](https://tio.run/##TYwxbsMwEAR7v@LKO0YurDSBZL3EcEFbJEWIvBMpBqEbf12RUgXYYrEz2OVVJuHPryVvmxuCjo9RQ@3qtZUMVTl8nyv1NksEX0wuImEFHxfJRZ1GY8EiN2loqTvBz@SDgXR16JBJtUrxHurm4Vb3Ava4BM@QNTuDlybRvU/AUvbxtn5HnOhwwn/n/A6GcaY/Mh3kKfHhWRcvvOLcBLprHmHJngsm6tPHcNkstrT9Ag "Python 3.8 (pre-release) – Try It Online")
Hmph, the damn upper limit is too big. Won't work for \$n>2\$ because of the big factorial calculation
-1 thanks to @cairdcoinheringaahing
# [Python 3 (PyPy)](http://pypy.org/), 283 bytes, (Performance™)
```
g=lambda x:x<2or x*g(~-x);from itertools import*
def f(n,q=2):
c=g(n)*2**n**2;d=2**(n*n+2*n)*c**~-n-1
while q<d*2**~-n*(c*2**n+.6*d*~-4**n+2*d-2)**n+c*d:k=[x**n for x in range(1,-~int(q**(1/n)))];q not in[sum(h)for l in range(1,-~len(k))for h in combinations(k,l)]and print(q);q+=1
```
[Try it online!](https://tio.run/##VY47coQwEETzPcWEmgHZhdblAFYn2dqARXxUiBEfuQwJV8eCzFlXd7@ZHrfQeb7LcRu342i1K4e3KWHN14fyM6zUil2uWDSzH8CGeg7euwXsMPo50M3UDTSC00krzG9Q6VYwkiJiIlUYHZVg4kRRtCuiXbLMbvDbWVfD9DBnNXokqgtKPr7JROOLLsZIhaeqyOS9fq5RQ3OuAsswl9zWIkvlbjmIKT7KPhkRX8UE7EOsPJefQXR4Eu4/4WoWPV5JdyaVH96Wy2A9L6JPHb5KNjDO12UspkRnRyPuePwB "Python 3 (PyPy) – Try It Online")
Probably terminates more than billion times faster compared to the above version.
Optimizations:
* Uses the full formula to calculate the upper bound from [A001661](http://oeis.org/A001661), the generated upperbound is still big, but not as big as one by the Compact version
* To check if number can be represented in nth powers of 1 or more integers, previous version checks in the range of 1 to the number, but this checks until the nth root of the number, which speeds up the check dramatically.
It works for \$n>2\$ too!
] |
[Question]
[
# Background
[Wuxings](https://en.wikipedia.org/wiki/Wuxing_(Chinese_philosophy))(五行) are the five "elements" in Chinese philosophy. They are **Fire**(火), **Water**(水), **Wood**(木), **Metal**(金), and **Soil**(土). You can find them on East Asian calendar, where some days (Tuesday through Saturday) are named by the Wuxings.
Some Korean names are given according to Wuxings, so that father's name will have a positive effect to his children. Let's simulate that.
# Positive actions
* **Fire** fertilizes **Soil**.
* **Soil** incubates **Metal**.
* **Metal** is a container for **Water**.
* **Water** nourishes **Wood**.
* **Wood** fuels **Fire**.
# Negative actions
These are irrelevent to this challenge, but I'm showing them anyway.
* **Fire** melts **Metal**.
* **Metal** chops **Wood**.
* **Wood** penetrates **Soil**.
* **Soil** blocks **Water**.
* **Water** extinguishes **Fire**.
# Ideographs
Some ideographs have a Wuxing as its radical. Here, only the **CJK Ideographs**(U+4E00–U+9FFF), a Unicode block, will be considered as of Unicode 1.0.1.
* 火(U+706B)–爩(U+7229) have **Fire** as the radical.
* 水(U+6C34)–灪(U+706A) have **Water** as the radical.
* 木(U+6728)–欟(U+6B1F) have **Wood** as the radical.
* 金(U+91D1)–钄(U+9484) have **Metal** as the radical.
* 土(U+571F)–壪(U+58EA) have **Soil** as the radical.
* All other characters fall in *don't care* situation.
# Notes
* Some characters, in Unicode's own dictionary, disagree with the categorization above. For example, 泵(U+6CF5) actually doesn't have Water as its radical, but rather "石". For another example, 渠(U+6E20) has ambiguous radical, Water or Wood. Such characters also fall in *don't care* situation.
* After Unicode 1.0.1, Unicode added more characters that has a Wuxing as their radical to the block and other blocks. For example, 龦(U+9FA6) also has Fire as its radical. This detail shall be ignored in this challenge, and such characters also fall in *don't care* situation.
# Objective
Given an ideograph having a Wuxing \$W\$ as its radical, output **any** ideograph whose radical will be positively acted by \$W\$.
# Examples
Given 溒(U+6E92), it has Water as its radical, so output any ideograph having Wood as its radical, since Water nourishes Wood. For example, 杜(U+675C).
Given 坽(U+577D), it has Soil as its radical, so output any ideograph having Metal as its radical, since Soil incubates Metal. For example, 鉺(U+927A).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 39 bytes
I/O: Unicode codepoints as integers.
```
n=>Buffer("99944,777I")[n/543%62&15]<<9
```
[Try it online!](https://tio.run/##bY5Rb4IwFIXf@RU3xtk2IgNEKhmQyKbJHvZklj0QMhsBx8Jag8yYEH47azHDF196b893zs35Zmd22lfFsZ5xkWZdHnQ8CKPfPM8qPPI8z3F0SunriMT8ceHMH1x7Yi0S3/e6FQQQawAxoK0oSqQDmJcFtTa6msv1ChL9ij@ESK/YpfZSYTeyNjfM6qxCvfw8d9SkpntLb4oqu6alHPXYtr0Bv2U1K/u0Z71Y/XSWDiRa8qRpe8HPsiaHIASMMIIprIy84CnG8acOPwWXD7skRBk4hIGSYDKRux8oQmIzkSFEEDGOLF3LJCXysLwiqjXbf9071KhmgzQ4@T8DkL1OosyMUhzw7n06brhRi21dFfyALZe0MG5UdczlOgtBOXL5uW9ShLQ7WQugJVpLuj8 "JavaScript (Node.js) – Try It Online")
## How?
### Step 1
We first look for some divisor \$d\$ such that the following element sets \$S\_k\$ are disjoint:
$$S\_k=\left\{\left\lfloor\dfrac{n}{d}\right\rfloor,\:C\_{min}(k)\le n\le C\_{max}(k)\right\}$$
where \$C\_{min}(k)\$ and \$C\_{max}(k)\$ are the codepoint bounds of the \$k\$-th element.
Because the Unicode range of **Water** (U+6C34 to U+706A) is immediately followed by the Unicode range of **Fire** (U+706B to U+7229), there are not many possible options for \$d\$: it must be a proper divisor of \$28779\$ (0x706B), i.e. \$d\in\{1, 3, 53, 159, 181, 543, 9593\}\$. The best value in there that actually works is \$d=543\$.
### Step 2
We then look for some modulo chain that takes \$n\$ as input and turns it into an index corresponding to the counterpart element, using \$n/543\$. Instead of rounding the result towards zero, we force the last operation to a bitwise AND rather than a modulo.
A quick brute-force search leads to:
$$f(n)=((n/543)\bmod 62)\operatorname{and}15$$
### Step 3
Finally, we look for some multiplier \$m\$ such that there exists some \$q\_k\$ for each \$k\$ that satisfies:
$$C\_{min}(k)\le q\_k\times m\le C\_{max}(k)$$
One possible golf-friendly value is \$m=512\$, leading to the following table:
```
element | hexa range | q | q*512 | as hexa
---------+-----------------+----+-------+---------
Soil | 0x571F - 0x58EA | 44 | 22528 | 0x5800
Wood | 0x6728 - 0x6B1F | 52 | 26624 | 0x6800
Water | 0x6C34 - 0x706A | 55 | 28160 | 0x6E00
Fire | 0x706B - 0x7229 | 57 | 29184 | 0x7200
Metal | 0x91D1 - 0x9484 | 73 | 37376 | 0x9200
```
The values of \$q\$ are encoded as the ASCII codes of `,479I`.
[Answer]
# [Haskell](https://www.haskell.org/), 51 bytes
```
w x="金火林土水"!!sum[1|c<-"朧氳灪釐",x>c]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v1yhwlbpZfvE542rn82b/nTO/GcbtigpKhaX5kYb1iTb6Co9m7P82YbNzxtXvWyfoKRTYZcc@z83MTPPNiWfS0GhoLQkuKRIIbpcQf3ZrknqOgpABtAM9dj/AA "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“Ọ{ƊɠṪƲ‘ɓ:Ḣ<Sịɗ‘×Ḣ
```
A monadic Link accepting an ordinal which yields an ordinal as below:
```
Input Output
Fire (28779 火 - 29225 爩) 22444 垬 (Soil)
Soil (22303 土 - 22762 壪) 37467 鉛 (Metal)
Metal (37329 金 - 38020 钄) 27874 波 (Water)
Water (27700 水 - 28778 灪) 26426 机 (Wood)
Wood (26408 木 - 27423 欟) 28960 焠 (Fire)
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHu3uqj3WdXPBw56pjmx41zDg52erhjkU2wQ93d5@cDuQfng7k/v//38jI3MwIAA "Jelly – Try It Online")** Or see [all valid cases](https://github.com/DennisMitchell/jelly).
### How?
Integer dividing by \$181\$:
1. keeps the ranges distinct
2. reduces all values to less than \$256\$
3. has more than one result for each range
4. has a single result greater than \$181\$
This allows us to place all our magic numbers into a single list of code-page indices, using these for the integer division, the category identification, a lookup of the new category, and a final multiplication:
```
“Ọ{ƊɠṪƲ‘ɓ:Ḣ<Sịɗ‘×Ḣ - Link: ordinal, n e.g. n = 27700 (木 - minimal Water)
“Ọ{ƊɠṪƲ‘ - code-page indices (call this M) [181,123,145,159,206,153]
ɓ - new dyadic chain - f(n,M):
: - integer divide [27700//181, 27700//123,...]
Ḣ - head (call this x) 27700//181 = 153
ɗ - last three links as a dyad - f(x, M):
< - (x) less than? (M) [1, 0, 0, 1, 1, 0]
S - sum 3
ị - index into (M) 145
‘ - increment 146
× - multiply (M) [146×181, 146×123, ...]
Ḣ - head 146×181 = 26426 (机 - a Wood)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ 25 bytes
```
℅×⊘φ℅§6-L888 :::6÷℅S⁵⁴³
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMZyE9MLkkt0gjJzE0t1vBIzClLTdFI09RR8C9KycxLzNFwLPHMS0mt0FBSsLAy01VQUPBRUNJR8Mwrccksy0xJ1fDNzCst1oCp9swrKC0JLgEanq6hCTTFGIgNDS0tNcHA@v//Z1sX/NctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Takes the ordinal of the input, integer divides by 543, cyclically indexes into the lookup table, takes the ordinal of that character, multiplies by 500, and converts back to Unicode.
I tried to reduce the size of the lookup table but although subtracting `3` and dividing by `654` allowed me to reduce it by 2 bytes it cost 3 bytes to subtract `3`, so it didn't help.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~99~~ 91 bytes
```
lambda c:{k:v for v,r in zip("水土木火金","钅爪火欠士")for k in range(ord(r))}[c]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHZqjrbqkwhLb9IoUynSCEzT6Eqs0BD6dmGLU/nzH82Z8XzxtUv2ycq6Si9nNT6vGMVkPtszYKni1craYK0ZIM0FCXmpadq5BelaBRpatZGJ8f@LyjKzCvRSAOLZeYVlJZoaALB/2e7JgEA "Python 3.8 (pre-release) – Try It Online")
-8 bytes thanks to @ovs
Input as an integer representing a unicode codepoint, output as a length-1 string.
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 40 bytes
```
lambda n:b"MMMFF<JJJc"[n//543%62&15]*378
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHPKknJ19fXzc3Gy8srWSk6T1/f1MRY1cxIzdA0VsvY3OJ/QVFmXolGckaRRppGflGKRmZeQWmJhiYI/H@2axIA "Python 3.8 (pre-release) – Try It Online")
Shameless copy of @Arnauld's answer
] |
[Question]
[
# Introduction
Logic gates! Everyone knows them, everyone loves them (unless you're starting to learn them). Take two booleans, compare them, get a single boolean in return. `AND`, `NAND`, `OR`, `NOR`, `XOR`, `XNOR`. Fun! But, what if you only had the inputs and output, but *not* the operator?
[](https://i.stack.imgur.com/UAhJq.png)
# Challenge
Given a three digit number, `xyz`, where `x` and `y` are inputs to the unknown gate(s) and `z` is the output, list all the possible gates. The output order doesn't matter but it must be all caps and separated by a space. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins!
# Example Inputs and Outputs
Inputs:
>
> 001
>
>
> 101
>
>
> 111
>
>
>
Outputs:
>
> NAND NOR XNOR
>
>
> NAND OR XOR
>
>
> AND OR XNOR
>
>
>
[Answer]
# JavaScript (ES6), ~~58~~ 56 bytes
```
n=>`25AND 41OR X37OR`.replace(/\d+/g,m=>m>>n%6&1?'':'N')
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7ByNTRz0XBxNA/SCHC2Nw/KEGvKLUgJzE5VUM/JkVbP10n19Yu184uT9VMzdBeXd1K3U9d839yfl5xfk6qXk5@ukaahoKCgaYmF7qYIaaYIRZ1hpjqDA0MsIhhUYfFPEOQef8B "JavaScript (Node.js) – Try It Online")
### How?
Given the input \$n\$, we compute \$n\bmod 6\$ to get an index into 3 small lookup bit masks.
It's worth noting that all operations are commutative, i.e. \$(X \operatorname{op} Y)=(Y \operatorname{op} X)\$ even when \$X=\lnot Y\$. So the collisions between `011` and `101` and between `010` and `100` are actually very welcome.
```
n (decimal) | n mod 6 | NAND | NOR | XNOR
-------------+---------+------+-----+------
011 or 101 | 5 | 0 | 1 | 1
010 or 100 | 4 | 1 | 0 | 0
111 | 3 | 1 | 1 | 0
110 | 2 | 0 | 0 | 1
001 | 1 | 0 | 0 | 0
000 | 0 | 1 | 1 | 1
| | |
| | +--> 0b100101 = 37
| +--------> 0b101001 = 41
+--------------> 0b011001 = 25
```
We look for the bit masks in the string `"25AND 41OR X37OR"` and replace them with either `"N"` or an empty string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes
```
V€Ḅ“n|ḃ’b⁹¤æ»ị“N“”ż“AND “OR X“OR”
```
[Try it online!](https://tio.run/##y0rNyan8/z/sUdOahztaHjXMyat5uKP5UcPMpEeNOw8tObzs0O6Hu7uB4n5A/Khh7tE9QNrRz0UBSPkHKUSAKaD4////lQwNDJUA "Jelly – Try It Online")
## Explanation
```
V€Ḅ“n|ḃ’b⁹¤æ»ị“N“”ż“AND “OR X“OR” Main Link
€ For each character
V evaluate it (into 0 or 1)
Ḅ convert the input string to binary
“n|ḃ’b⁹¤ [106, 86, 150]:
“n|ḃ’ 6968982
b in base
⁹ 256
æ» Right shift each number by the input (those three numbers encode whether or not the N needs to be present)
ị and index into
“N“” ["N", ""] (odd = N, even = "", since Jelly lists wrap)
ż interleave it with
“AND “OR X“OR” "AND ", "OR X", "OR"
Final result is [N]AND [N]OR X[N]OR
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~98~~ ~~88~~ 78 bytes
```
lambda s:'%sAND %sOR X%sOR'%(*[eval(s[0]+o+s[1]+'!='+s[2])*'N'for o in'&|^'],)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSl212NHPRUG12D9IIQJEqqtqaEWnliXmaBRHG8Rq52sXRxvGaqsr2qoDWUaxmlrqfupp@UUK@QqZeepqNXHqsTqa/wuKMvNKNNI01A0NDdU1Nf8DKQA "Python 3 – Try It Online")
*Thanks to ovs for -20 bytes*
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
Nθ⭆vAND jOR XiOR⎇‹ι_ι×NΣ§◧⍘℅ι01⁸θ
```
[Try it online!](https://tio.run/##JYwxD4IwFIR3f0XT6ZFgQjcTJowLCVICDG7mCU@tgQptIfrra9VLLnfDfdfd0XRPHLzP9bS4chkvZGCO0k1llHbQuBC3I07A16w8sIes2UnJmsesJaPRvKEga0HFjJ95FLNQWjWSBV6GTbOMkLlc9/SCCvuCrg72aOl/C9L0SuMAKoA8EV9@FzxHP6Xei0T47Tp8AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The lowercase letters' ASCII codes encode the binary patterns for where the `N`s appear. This algorithm actually depends on the input being an integer and the output being in upper case. Although the input is taken in base 10, the cyclic indexing means that the values are equivalent to base 2.
```
Nθ Input the 3-digit number
vAND jOR XiOR Literal string `vAND jOR XiOR`
⭆ Map over characters and join
ι Current character
‹ Is less than
_ Literal `_`
⎇ If true then
ι Current character else
N Literal `N`
× Repeated by
Σ Extract decimal value of
ι Current character
℅ ASCII code
⍘ 01 Converted to base 2
◧ ⁸ Left padded to length 8
§ Cyclically indexed by
θ Input number
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 72 59 bytes
```
lambda n:f'{n%15%2*"N"}AND {n*3%17%2*"N"}OR X{n%9%2*"N"}OR'
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHPKk29Ok/V0FTVSEvJT6nW0c9FoTpPy1jV0Bwq4h@kEAFUYQnnqv9Pyy9SqFDIzFMw0DHUMQQSIBJIGQBpMNfQiktBoaAoM69EA2h8hZWBca2Crp1CdZpGhWatuuZ/AA)
Expects input as a decimal number.
*-13 bytes thanks to ovs' modular dark magic*
I squinted at the numbers very hard until I found these three formulae ovs chained all the modulos:
* `n&1!=n//110` <=> "the last digit is 1 and n is not 111; or n == 110"
* `n%2!=(n>2)` <=> "the last digit is 0 and n is nonzero; or n == 001"
* `n%9%2` <=> "the number of 1 in the digits of n is odd"
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 53 bytes
```
%"%sAND %sOR X%sOR"[*\Nn&=vz1/z110*\Nn%z2>z2*\N%%z9 2
```
[Try it online!](https://tio.run/##K6gsyfj/X1VJtdjRz0VBtdg/SCECRCpFa8X45anZllUZ6lcZGhqAeKpVRnZVRkCWqmqVpYLR//8GBoYA "Pyth – Try It Online")
Port of [a previous version of Stef's Python 3.8 answer](https://codegolf.stackexchange.com/a/211818/91569).
# [Pyth](https://github.com/isaacg1/pyth), ~~64~~ 61 bytes
-3 bytes by using string formatting.
```
A,shzs@z1=Tsez%"%sAND %sOR X%sOR"[?x&GHT\Nk?x|GHT\Nk?xxGHT\Nk
```
[Try it online!](https://tio.run/##K6gsyfj/31GnOKOq2KHK0DakOLVKVUm12NHPRUG12D9IIQJEKkXbV6i5e4TE@GXbV9TAGBUQxv//BgaGAA "Pyth – Try It Online")
First time golfing in Pyth!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
’n€ƒxš¯š¯’4ôuεI`Š…*+~Nè.VQi'Nõ.;]ðý
```
[Try it online](https://tio.run/##yy9OTMpM/f//UcPMvEdNa45Nqji68NB6EAaKmBzeUnpuq2fC0QWPGpZpadf5HV6hFxaYqe53eKuedezhDYf3/v9vYGAIAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWY0v9HDTPzHjWtOTap4ujCQ@tBGChicnhL6bmtkQlHFzxqWKalXed3eIVeWGCmut/hrXrWsYc3HN77X0kvTOd/tJKBgaGSjpIhhDQ0VIoFAA).
**Explanation:**
```
’n€ƒxš¯š¯’ # Push dictionary string "nandxnornor"
4ô # Split it into parts of size 4: ["nand","xnor","nor"]
u # Uppercase each string: ["NAND","XNOR","NOR"]
ε # Map over each string:
I # Push the input
` # Pop and push its digits separated to the stack
Š # Triple-swap the values on the stack: a,b,c → c,a,b
…*+~ # Push string "*+~"
Nè # Index the map-index into this string
.V # Execute it as 05AB1E code:
# *: Multiply the top two values on the stack
# +: Add the top two values on the stack
# ~: Bitwise-OR the top two values on the stack
Qi # If this is equal to the third value that was on the stack:
'Nõ.; '# Remove the first "N" in the string
] # Close the if-statement and map
ðý # And join the list with space delimiter
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’n€ƒxš¯š¯’` is `"nandxnornor"`.
The `’n€ƒxš¯š¯’4ôu` could alternatively also have been `.•UNœTǨ₆~•#` for the same byte-count.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~78~~ 73 bytes
Saved 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
f(n){n=1<<n%6;printf("NAND %sOR X%sOR"+!(n&38),"N"+!(n&22),"N"+!(n&26));}
```
[Try it online!](https://tio.run/##TVDBCoJAEL37FdNCsauGrkFEa4egrgadgpII0/DQKOlBEr/ddt212sMw773ZeY9J5o8k6fuMImtxw8MQp0tRvnKsM0qibbSDaXU4wklV4kwozhYr5pJI90Hw1y8ZE10vf8LzliNlVmuBfIqo06q@4jmGDbTcBe6rwnknhgnPhn1Tpkm9Bm0ZKUdZiGsIhTUckVLB9qxhQVa8gCqfHO9pI018YdoQqvydFhnVCZhnoG2wAMcZJhnotGNilFtM6kGPxVdWt/qh8VYXJIbtrK7/AA "C (gcc) – Try It Online")
Inputs a three digit decimal number representing the two boolean arguments and the result of a boolean operator and outputs all possible operators to `stdout`.
Uses that super-handy lookup table from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/211769/9481).
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 143 bytes
```
void A(int a){for(int i=-1;i++<5;)if((7+21*((a+2)/4)>>i&1)==a%2)System.out.print(new String[]{"AND","OR","XOR","NAND","NOR","XNOR"}[5-i]+" ");}
```
[Try it online! (More details inside)](https://tio.run/##tVZbb9s2FH6Wf8WZgLaSZckidbHdJN4K7GUPS4G2wAKkaUHbdMzWljxJbpJefnt3DinZ8iXYim2JTUkUz@X7Pp5DfxCfhJ@vZfZh9vF7Z72ZLNUUpktRlvC7UBl86XSsucrEEspKVPhOz67gAjJ5Zx4c9wwX1ab1qk@5msEK3zqvq0Jlt9c3IIrb0tX@rHlegKOyChT6Cc/wcn4BA7x6Hq2wLOv1Q1nJVZBvqmCN9pXjKBiPgcNTYC54YOO/B2aSHU02z8/BxtzQ3Sp44Shze@h5mTn6xbdOp98/mRoMt5nRilMefjg7DKl9rYL7lm0PdiZ0TyvPTgd17LeZ7/tvM7tegfnj97sm/oVGINwviMaAufDZGWI4T85cNXecgcdZ13GEx91@7I7H6ilzLy7EE@4exSGZGw2/2C8uf7V79stXOFzp8dLMXJopuny7Tnx149nE/bfvHavf7VjQhZfVQhYglhXMN9m0UnkGYr0ucjFdyPI5Lel3LJ19abLv0TjR49TsilNoSFJCpPPEl5hkNOjFvMf5t2vhTW4acFNXr7X@BmCNx4xXO1Q16EOARpwT6pAfMsQP3b18hYZBuZmUOpJDOFwnDuKu8gPeVV3l9po5VEZ5zG3mXRMJ@n24U9UCY8CmRB8gYKnKqqOV7/erQmLl4bRERuFWVPJZCSYarvsocflElBKiFLLNaoJaOCuVqdVmBfkcohgmcio2uACf7Cvb7aFxXsgZiBJERtTKYp0v0e8M8PqQ5SsllrVkG@c3fH9LAh/IRmnb25c2VDkIY6IxNK@CKjca2Bok2GI3g7IJ72JyVu@AWY6dRp7cBIz5w67oCi9KumI81oSqp1NUnz0i/i5MLclwxHxFvHcdlvBBmhoVfBaNkiEbdFU/jl2fpymPo0ivU/2Ie8MwTsJ4oB957I@GSRKlQUSyRilVu1ZJA78/vb3r5nNqg@@mw7MzlxhVc5ipWfaswi6MeiCpqA7KiepsC8LUOJaASwXueXUV/JMi@MEqf6wIDnMwGfz8L2I9t23DpaHyoe5zepvN5PSIq0My@iwMPfEER7xr80Jz/ws1pjq7pgdiC4QyX26o@9GEnvxlLQqxwvL09XuVrTdVDyIU@FZVTa2eT8Z40uoC5uf9ybjdLz833f5R@Eftfouau0Y8WnWqgzrZeMw9HJj7lN1sSyrT5uy/YyzdMoZKJkgFtkAPfIqABNLZjGS90A2PGlSZr3SjEsslpD@1mhMdK835UvYgL2aSetjkAUr1WRLBeOws1wsxkfgzBc0f8Oh5gycTdUsB04XIprRMlTDNN0u0lHRMLZWpslwfYuu8pC7YKIlxZLmWU0Xutm10AIo84tpSUb8yQvbgbqGwP@O7PMPVrJa5ENpzhfGB445BigCIKEDOAOgLlzQSX50wBMAPoDnUd7tHPVwAG3VCdjR/YHABfNhh7LSjsOUtGmipLYCvfyxknavUxwzc5cVH5GBe5CuYYA8qHogqLMcG7AKPkPrFJ7HcyNL0eHkvphVyUC0KKYGhi2qxKY2fMAwZ5oV@8IIPQQfM31Jmt2j7FYB@qWmhtMi0GyibEjN8h/wgdrTHZft7Q/65MTeODG4DcMIeEoVnnYO/t/iQbjjW3sCl1HFTaJD2vU16GSxroVDEMHyPA3sPfWB0i6kwfLpDoLp@5Qw3LqRwjQr2tI49ErIH9L2kgXS8QXpHGBYDgsVG3qh737LSq/R646RlNSCjeASWLux7PP3hDbWWRV4gA1ghGfIgMH0DAh@JHsIyzeV8rqZKZlVJoEIT0IQwaV5uc6wzwIBxDFECPAUrxsPNRLx/x427tp@WWZP41iv6iXTmCNqKBv4W7h4ptcGWM7TCuBgdc7B4WpM0aHI@tNvlnGgrhlZJ6hNNtdkus60i7RRjrQgKEo9aVnur6qjtFJkmCENaLPZqs@Ge/DuQLSE5I3AxQ2TMS7r3NbP7vA5bG@Iw@2YbRcC53hEsIoaa@C0FdtJctnTlWhKOaLmfHNpdHvGz5TakpDW3oV/HY/wRvC07jMQTimpx7g3Izo/JNggCdBDtOdjfSw1hCfmgeuGJAeozvvMQP@KhnUJKrEdDvZkYMy7SnYvkuGhbMFooUG9CEQWaN58uJB5VWUFFSGfTQnySECTPysZ7esTR1W5T7O2JWO@JtPbO6NqB2svgGObVYY4GZmJqpvES77kZnnCzc2bc6GrVfA891mDl3Pjp9r//BQ "Java (OpenJDK 8) – Try It Online")
Input is a single 3 digit number, interpreted as binary. Example input: "A(0b101);"
Explanation:
```
(...)
if((7+21*((a+2)/4)>>i&1)==a%2)
7+21*( ) // The shortest interpolation equation (see bottom of tio.) I could find, for the "x" values of
// 0, 1, 2, representing 00_, 01_ / 10_, 11_ respectively.
(a+2)/4 // The sum of the second and third bit, found this equation with brute force,
// alternative: (a|1)/3, needs parentheses because of bit operation order.
>>i&1 // The bit at i, delete all bits except the first to compare it with:
)==a%2) // The first digit of a. (like "number % 10", except for binary)
```
And, [I'm pretty sure you can print the answer when asked to return it.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
] |
[Question]
[
We have a challenge [to output your own score](https://codegolf.stackexchange.com/questions/160646/output-your-score), but it seems like all the answers there just hardcode the output and that's *boring*1. So lets have a new challenge. Your program must output its own length in bytes followed by the string `" bytes"`, but in order to prevent hardcoded solutions if we reduce its size by removing *any* one byte, the new program must also output it's new byte count, still followed by `" bytes"`. Output does not need to be case sensitive. You may also choose to output a trailing newline.
Your answers will be scored in bytes with fewer bytes being better.
---
1: I actually like some of the answers there.
[Answer]
# [Backhand](https://github.com/GuyJoKing/Backhand), ~~40 36~~ 29 bytes
```
vv""sseettyybb
""jjHHOO]
```
[Try it online!](https://tio.run/##S0pMzs5IzEv5/7@sTEmpuDg1taSksjIpSUFBBgiUlLKyPDz8/WP//wcA "Backhand – Try It Online") [Verification!](https://tio.run/##fZCxbsIwEIbn5Bk6XCMh24IGoW6RWGChS3kAFCGTOMS02JbtgPL06RlCwtA2ky93/3/3/ab1tVbvXdfJs9HWg3Zx/3Kti2Nj9dHyMyxDmTpfSpVawUvK4vjQerHWjfLY/RaK9rOpUIUuBSXcFVISxtBEKk/JCuehCIKMzGBQP/q9HI1LUYFt1L7/M3SyOLpKX4M2uI2EJehDroQBd1BhN6rSq5VejF6RFb6xCrFSc5NVibkjw1wbPz/w4qvmqpyv@sf@Q3lhDcqETU0LYUvCBmbdBNrfjntQfmoo0OgoAiSOs5g7J0KyQYo5ektH9im5BeFIiFpc1jW36E@wrLQFCVKBDWb0KWAWgpAV9OVO5vC6hIc8xHA/JZmUQCeOZcmEytk4zWYgVLkkBOOJ/gTaZTKfDqLpIsvZ4HzDiqJ/wN4WT2hBNrCNd8Td5ZIk6CG8b9vDAeAFvyQ5nTab7Tb/AQ "Python 3 – Try It Online")
When in doubt, double up on everything. This uses Backhand's ability to move more than one step at a time to implement the redundancy. The unprintables all have the byte value 28.
## Explanation:
### Non-irradiated program:
```
v Reduce step count to 2
" Start string literal
s e t y b Push the " bytes" part of the output
" Push 28 twice and end the string literal
j Jump to the 28th position (0 indexed)
] Increment the 28 to 29
O Print the 29
H Halt and output the entire stack
```
### Irradiated program:
If any character is deleted, every character after that is shifted down.
```
vv"sseettyybb
v " s e t y b The same instructions are still executed
```
However, instead of jumping to the `]`, it instead reflects off the end of the program and lands on the `O` instead.
```
v 28th character (0 indexed)
vv""sseettyybb ""jjHHOO]
v""sseettyybb ""jjHHOO]OOHHjj"".....
^ 28th character, reflecting off the end of the code
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 47 bytes
```
>>yyLL @"setyb 64"/
"47 bytes"@"setyb 64"L\
```
[Try it online!](https://tio.run/##KyrNy0z@/9/OrrLSx0cBBByUilNLKpMUzEyU9LmUTMwVkipLUouVkIR9Yv7/BwA "Runic Enchantments – Try It Online")
Which is more or less a port of my [Geiger Counter](https://codegolf.stackexchange.com/a/173051/47990) answer, but with different output (which is, itself, a port of a Klein answer).
`>>yyLL` is required for Runic to generate (at least) one IP, merge two IPS, and reflect back to the left, so that all variations result in a single left-moving IP. Could be replaced by `yy<<` but it doesn't save any bytes.
The reflectors on the right force the IP to the lower left string, so the removal of top right one of them allows the IP into the top right string. Removing a byte anywhere else along the top line adjusts the top reflector to sit above the L (allowing the program into the lower right). The removal of a byte along the bottom adjusts that reflector (or removes it) so that the last character gets implicitly filled with a space, which allows the IP to bounce off both sides of the top right reflector and into the top right string.
The excess spaces are disappointing, though. But all attempts to reduce them have resulted in either larger programs, same size programs, or programs that are not 100% radiation proof. Both the Klein and ><> answers here use features not available in Runic.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~43~~ 39 bytes
```
||vn-{"' bytes"-10/
o>o<"38 bytes"[0/0
```
[Try it online!](https://tio.run/##S8sszvj/v6amLE@3WkldIamyJLVYSdfQQJ9LId8u30bJ2AIqFm2gb/D/PwA "><> – Try It Online") [Verification!](https://tio.run/##fZDRbsIgFIavy1OckRggaqvxZmnmLub9XsCYpWupJZlAgGqa@e4dVGy92HZDOJzz/5zv151rlNz0fS9OWhkHyqJ4s51FSBt1NMUJtqFMrauETA0vKsoQ@uwc36lWOt/94pLG2ZTLUlWcksKWQhDGvImQjpI3Pw9lEORkAaP63o9yb1zxGkwrP@LL2MlRchGuAaX9byR84n3IhTAoLNS@m9TpxQjHJ6/EcNca6bFSPchqrG/IkCntslrYZjhS3UFwxGzkU20g@22RO9G7grIp5JEHID/OUGEtDykGqc/MGTpxzskAbUmIlZ93TWG8P/FlrQwIEBJMMKMPYbIALWqI5V4c4GkLd3lAvq2CZxXQmWE5nlGxmKbZAristoT4KJI/gfa5OMxH0XydH9joPGAlyT9gy/UDWpCNbNMeqL9ez3L5jeMgXq5XGQL1ql7w5jm@7VfZ6gc "Python 3 – Try It Online")
In the un-irradiated program, we add `0` to the `'` (39), and in the irradiated program we skip the 0 and add `-1` to it instead. If something is removed from the top row, we shift to the bottom row instead and just output `38 bytes`.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 71 bytes
```
//.........||.>e;s;@..\;t;y;b<>}F"+!P0;/|/F!P0$@;<...t;ye;bs/.........)
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/19fXw8Gamr07FKti60d9PRirEusK62TbOxq3ZS0FQMMrPVr9N2AtIqDtQ1QJVAy1TqpGKFV8/9/AA "Hexagony – Try It Online") [Verification!](https://tio.run/##fZBBb6NADIXP8CtctNEwSnZo1Rs0VbWVelz13kYVBBNG2s4gz9AUKfvbU09KoIfdcgHj9579uRt8a8318XjUr50lD9bF45cbXBx3ZHdUvsI6lMr5WhtFWNapjONq8Hhve@O5@wdNOmoVmq2tMRWl22otpOQQbXwqfrEetsGQixVM7nN/tHNwjQ1Qb17GP1Mnj6O99i3YjqeJMIRzxF5IKB003I0atSftcc6KCH1PhrFUd7I1CfXVAJntfNbie7mzZsh4PFLHUiRFFYTkRE6ctg@E/1roTPbbwrYtzQ4DGMtlXDqH4ZrByrfzlM68S3GCdyKcF9/u25I4X3DZWAIN2gCFsPTLUWWA1w2M5ZPewMUazvaA/rlKsqghXZDMk0WqV7NargBNvRaCTxL9F@gp15vlZFpe5Rs5JZ@wougbsJ9XX9CCbWKb94iPWabOz@GgbrFwxZ1Sz4UvhqK6uf37kCwvHi@L7JA98PvHXXHDSm5iUbnZKj8A "Python 3 – Try It Online")
I spent way too long trying to get this into a size 5 hexagon, but I had to settle for a subpar size 6 instead `:(`.
### Expanded:
```
/ / . . . .
. . . . . | |
. > e ; s ; @ .
. \ ; t ; y ; b <
> } F " + ! P 0 ; /
| / F ! P 0 $ @ ; < .
. . t ; y e ; b s /
. . . . . . . . .
) . . . . . . .
. . . . . . .
. . . . . .
```
I initially made this with the `)` one row lower, *but* it turns out that's exactly where the divide between size 5 and size 6 hexagons are. This means when a byte is removed, the size all shifts down and ruins the pathways. I'm definitely sure that a size 5 is possible.
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) 000, 41 bytes
```
<<@"setyb "$"4"+"0"/
..@"setyb 04"(....<1
```
[Try it online!](https://tio.run/##y85Jzcz7/9/GxkGpOLWkMklBSUXJRElbyUBJn0tPDyZoYKKkoQcENob///83MDD4r@sIAA "Klein – Try It Online") [JoKing's Verifier](https://tio.run/##fZBNbsMgEIXX5hRT1AiQE@KoWVmJ1Db7XiCNKsfGMWoCFuBGPr0LqX9aqS0LxDDz3sw3desqrR66rpOXWhsH2qL@ZVuLUG30yWQX2IaQW1dIxY3ICsoQOrZO7HSjnM@ehaJ9LRcq14WgJLO5lIQxbyKVo@TZ10MeBCmZw6ge8r3cGxeiBNOot/5nzKQoukpXga59NxKaeB9yJQwyC6XPRiW/GunE5BUZ4RqjPBavb7IS1zdkWOraLd/PQqqvm9ctBEtIkgQWT5iNnLoJhL8NNJC9aMirTJ1EAPPlDGXWirDNIPW7c4ZOvDG5wdtXRcKCxceuyozvQHxYagMSpAIT7Oi3tbKAL0vow708wN0WBnmA/xoGzwqgM8NSPKNyPlWzOQhVbAnxS4n@RNqn8hCPoniVHtjofAOLon/QFqsfcEE40k2ToG6zecRWuPYI@B6vcYwTvEScD5/JGlPuz2b1CQ "Python 3 – Try It Online")
I think this answer is similar to [JoKing's ><> answer](https://codegolf.stackexchange.com/a/173031/56656), but I don't read ><> so I can't be sure.
There are 4 different types of byte removals here
1. **A byte is removed from the first line before `/`.** In this case the slash is effectively moved left one space, deflecting it onto the bottom line and preventing the modified part of the code from being executed. This causes us to run the code `("40 bytes"@`, which outputs `40 bytes`.
2. **The first `/` is removed from the first line.** In this case we run the code `"0"+"4"$" bytes"@`, which is a convoluted way or printing `40 bytes`.
3. **The newline is removed.** This makes us start from the end of the second line and the resulting code (with noops removed) is `1("40 bytes"@`, which just prints `40 bytes`.
4. **A byte from the last line is removed.** This causes the `1` at the end of the first line to be moved left and prevents it from being added to the stack when the pointed is deflected by `/`. The code `"0"+` for that reason pushes `0` instead of `1`, the rest of the code turns the `0` into `40 bytes`.
# [Klein](https://github.com/Wheatwizard/Klein) 001, 41 bytes
```
\("40 bytes"@......1
..@"setyb "$"4"+"0"/
```
[Try it online!](https://tio.run/##y85Jzcz7/z9GQ8nEQCGpsiS1WMlBDwwMufT0HJSKU0sqkxSUVJRMlLSVDJT0////b2Bg@F/XEQA "Klein – Try It Online") [JoKing's Verifier](https://tio.run/##fZDRboIwFIav6VOcNTNtg1bIvCIxcfN@L@DMglCkmbakLTM8PWsRcUu2cUE4nPP/53x/07laq6e@7@W50caBtmj8sp1FqDH6aPIzrEPJrSul4kbkJWUIHTontrpVzndPQtFxlgtV6FJQkttCSsKYN5HKUfLi56EIgozMYVLf@qPcG5eiAtOq9/HP1MlQdJGuBt34bSQs8T7kQhjkFirfjSp@MdKJu1dkhGuN8li8GWQVbgZkWOrGLT9OQqrrmzcdBEtIkhQWz5hNnLoNhL8ddCN71VDUuTqKAObHGcqtFSHNIPXZOUPvvDEZ4O2bIiFg8bmtc@M3EF9W2oAEqcAEO/otVhbwZQVjuZN7eFjDTR7gr8fgWQl0ZliGZ1TO79NsDkKVa0J8KNGfSLtM7uNJFKfZnk3OA1gU/YO2SH/ABeFEd78E9W8Ur5LrHN7w4UkR5xtshesOgB/xCsc4wcsv "Python 3 – Try It Online")
Here's an answer using a different topology. It's the same size but I think there is room for improvement.
] |
[Question]
[
# Challenge :
Check if the given number forms a `number staircase` or not
---
# Input :
A integer (greater than 0 and not decimal). NOTE : You can take input as string , array of digits.
---
# Output :
a truthy / falsy value depending on whether the number forms a staircase or not
---
# Number staircase :
A *number staircase* is an integer that , when read from left to right :
* Starts with 1
* which may be followed by 2
* which may be followed by 3
* and so on till `n`
* then the number descends starting at n - 1
* then n - 2
* then n - 3
* and so on till it reaches 1
## Note :
The *may be* part is used to indicate that if length > is greater than 1. If it is the order must be followed as is. i.e : 12321
---
# Example :
```
12321 ---> true
12345654321 ---> true
9 ---> false
1 ---> true
2 ---> false
123421 ---> false
112312318901323 ---> false
123456789101110987654321 ---> true
```
---
# Note :
The input given will always be an integer greater than 0 and will not be a decimal. Your output must be a `truthy or falsy` value depending on the input
---
# Restrictions :
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes (for each programming language ) wins.
---
[Answer]
# [R](https://www.r-project.org/), 97 bytes
```
function(n)"if"(n>1,{while({T=T+1;x=paste(c(1:T,T:2-1),collapse="");nchar(x)<nchar(n)})0;x==n},T)
```
[Try it online!](https://tio.run/##JYtbCoMwEEX/u4qSrxkaIZP61nQV2YAEg4KMopYK4tpTbX8O98C5c/D3Ogr@zW7tRwZG0XsB/CK5f7p@aGG3xj6o2szULGsLDqi00pY6IpRuHIZmWlojBFbsumaGDev/YDxQnTfDh7QYPBDePOgLpJ/6Z8UFcWqcpFlekCIiVeRZmsRnITB8AQ "R – Try It Online")
Takes `n` as a `character` or an `integer`; using `character` will give correct results for integers that can't be held precisely as a 64-bit `double`.
Generates staircase numbers until it finds one at least as long as `n` is, then tests for equality.
Equivalent to:
```
function(n)
if(n > 1){
T <- T + 1
x <- paste(c(1:T,T:2-1),collapse="")
while(nchar(x) < nchar(n)){
T <- T + 1
x <- paste(c(1:T,T:2-1),collapse="")
}
return(x == n)
} else
return(TRUE)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ŒḄ€Vċ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7Wh41rQk70v3//39DI2MTUzNzC0tDA0NDQwNLC3MzUxNjI0MA "Jelly – Try It Online")
Warning: Very slow (fast for `1` and `121`)! Prepend `DL` to make it faster.
[Answer]
# JavaScript (ES6), ~~62~~ 57 bytes
*Saved 2 bytes thanks to @l4m2*
Returns a boolean.
```
f=(s,k=1)=>(m=s.match(`^${k}(.*)${k}$`))?f(m[1],k+1):s==k
```
[Try it online!](https://tio.run/##ndBbC4IwFMDx9z6FiA9bmXq8L1h9kCgc5rrMSzjrJfrsS8GHQi1oHNjTjz/nXNidybQ@X5tlWR0ypThF0hQUMF2jgkqrYE16QsneeIgnsua4@40E4w1HxRZ2plgAXklKhUqrUlZ5ZuXVEXGkg@u5oGOsjT3b1pr6ls2Gxg/CwB@VE4ZMNXrDWS6HoR9oLOT@FWo3mjzDJGpVNzFxwHO9T/2tFIRRTMABAIfE0dsh@5XUCw "JavaScript (Node.js) – Try It Online")
### How?
Starting with **k = 1**, we look for **k** at the beginning and at the end of the string, and recursively iterate the process on the remaining middle sub-string with **k + 1**. The recursion stops as soon as there's no match anymore. The input is a staircase number if the last sub-string is equal to **k**.
**Example for s = "1234321":**
```
k | s | match | s == k
---+-----------+-----------+--------
1 | "1234321" | 1(23432)1 | no
2 | "2343" | 2(343)2 | no
3 | "343" | 3(4)3 | no
4 | "4" | null | yes
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~55~~ 54 bytes
-1 byte thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni?tab=profile)!
```
f x=elem x[read$[1..z]++[z-1,z-2..1]>>=show|z<-[1..x]]
```
[Try it online!](https://tio.run/##FYyxCsMgFAB/5Q0dWlKFZ9JNs3TuF4gUoS@NVE2IQkX67zYZjhsObrbpQ963NkFR5ClA0RvZ10kj59V0na4Mr5UJztGMo0rz8v1VyY5cjGnBuggKgl0fTzivm4sZOEw7x@Wy27tICZSU8KZ8X2KmmFND0Q@3oRf4Bw "Haskell – Try It Online")
[Answer]
# Pyth, ~~13~~ 12 bytes
```
/mjk+Sd_Stdl
```
Saved a byte thanks to RK.
[Try it here](http://pyth.herokuapp.com/?code=%2Fmjk%2BSd_Stdl&input=%22123456789101110987654321%22&debug=0)
### Explanation
```
/mjk+Sd_Stdl
m lQ For each d up to the length of the (implicit) input...
+Sd_Std ... get the list [1, 2, ..., d, d-1, ..., 1]...
jk ... concatenated.
/ Count how many times the input appears.
```
If you really want the input as an integer, you can use `}Qmsjk+Sd_Std` instead, but this is horrifyingly slow.
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
f=lambda s,n=1,t='1',u='':t+':'>s>t<s*f(s,n+1,t+`n+1`,`n`+u)or s==t+u
```
[Try it online!](https://tio.run/##TU7RCoMwDHyeX5EXia4dmKrTyuq31DFkwlbF1od9fVcnyiAkd7njuOnjnqMR3vfq1b3vjw4sN4q4U0jIF4XYOIYNtrZ1N3vukyCzIDMdjubaaLak4wxWKccW368QBgNJdEISuQghGyrKa1nsXG7f3xaHYzcHvE4tM8pF/hdQ1ZIyIspkXR1paROdpnkwDjAWhYVLC7FFiCFUhdA3Tf0X "Python 2 – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~138~~ ~~107~~ 102 bytes
```
bool t(List<int>s)=>s.Select((j,i)=>s[0]==1&&s.Last()==1&&(i==0||j+1==s[i-1]||j-1==s[i-1])).All(x=>x);
```
[Try it online!](https://tio.run/##nZA9D4IwEIZ3f0Un08ZCKKBIsCTGlc3BgTAo6VDStInXRBLxt2PBSBzB4e7yJPe@91GDV4Ps@5sxCllcSLAHqW0OhOfgn4UStcW4oXLgMqg4Z@s1@MUVLCYjYMl50HXNhnEOpfRY5cCbgBD/qBRued6SrD8ZDUYJ/3KXVhRSC2yxFg80zUVPxGhIIxcMvQjJVvMlMd3SnYt4qTxdMGl@a7h8f7f1As1H9c17mtLA1eH26K/PJaMHcyZsyKnD5Pehg2n/Bg "C# (Visual C# Interactive Compiler) – Try It Online")
Explanation:
```
bool t(List<int>s)=>
s.Select((j,i) => //iterate over each item and store the return value
s[0]==1&&s.Last()==1 //does the sequence start and end with 1?
&& //AND
(i==0 //is it the first item?
|| //OR
j+1==s[i-1] //is the item 1 greater than the previous?
|| //OR
j-1==s[i-1]) //is the item 1 smaller than the previous?
).All(x=>x); //did all pass the criteria?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
```
L€L€ûJså
```
Warning: EXTREMELY SLOW! Add `g` to the start to speed it up.
[Try it online!](https://tio.run/##MzBNTDJM/f8/3edR0xoQPrzbq/jw0v//DY2MjQwB "05AB1E – Try It Online")
Explanation:
```
L 1..input
€L for each element, map to 1..element
€û palindromize each element
J join each element from a list to a string
så is the input in that list?
```
Old Explanation:
```
F For [0 .. input] map over
NL Push 1..i
û Palindromize
J Join
¹ First input
Q Equal?
} end loop
O Sum.
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fzc/n8G6vQzsDa/3//zc0MgQA "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
```
lambda s,r=range:s in[''.join(map(str,r(1,k+2)+r(k,0,-1)))for k in r(len(s))]
```
[Try it online!](https://tio.run/##Vco7EsIgEADQ3lPQsTtBhyV/Z3IStcAxUSQhzELj6dHWV7/4ya89mLJM17La7f6wIime2IbnfE7ChYuUp/fuAmw2QsqsGEj5ymDF4JVWR0LEZWfhf1kwrHOAhHgrkV3IYgFJpm7arh9G0kSkx6Hv2qY2JPHwfySWLw "Python 2 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç╗☻W╧ΩÆΘαφ←≤─♣
```
[Run and debug it](http://stax.tomtheisen.com/#p=80bb0257cfea92e9e0ed1bf3c405&i=12321)
Very slow for bigger numbers.
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), ~~57~~ ~~55~~ 46 bytes
```
{GenerateFirst[N@Join@Bounce@1&`:,`>=:`#&_]=_}
```
[Try it online!](https://tio.run/##NUtNC4IwGL73KwaFpx18p6YTDCko6CAduo3hhr6WlylunaLfvkwJHni@tXO6eaLvSF749wUNTtrhuZ@sE1V5HXpTHoeXabCEQOVUHYpcbYNaFvXHV4itFbtxbB5yc5t64@5o3UlbtKKjRACLGFAyU5zsk3gxfPaUsDVd2ln8kPEQIhb952nGIQSAkGfp@pXSfwE "Attache – Try It Online") Ah, that's much more elegant.
With `Generate` (49 bytes):
```
{g@Generate[{g@_>=#_2}&_]=_}g:=N@Join@Bounce@1&`:
```
## Explanation
```
{GenerateFirst[N@Join@Bounce@1&`:,`>=:`#&_]=_}
{ } anonymous lambda, argument: _
GenerateFirst[ , ] find the first element satisfying...
N@Join@Bounce@1&`: this generation function
`>=:`#&_ and this condition
=_ is it equal to the input?
```
The generation function simply creates the `N`th staircase number. Then, this search terminates once ``>=:`#&_` is satisfied. Expanded, this is:
```
`>=:`#&_
(`>= : `#) & _ NB. remember _ is the input
NB. also, f:g is f[...Map[g, args]]
{ #_1 >= #_2 } & _
{ Size[_1] >= Size[_2] } & _
{ Size[_1] >= Size[the original input] }
[n] -> { Size[n] >= Size[input] }
```
So, this terminates once the length of the generation function's output is at least that of the inputs. Thus, this generates the smallest staircase number at least as long as the input number. Thus, if the input is a staircase number, the result will be the same staircase number, and otherwise the next longest staircase number. As such, a simple check with equality to the original input is sufficient for determining whether or not it was a staircase number.
## Attache, 55 bytes
```
0&{If[#_2>#g[_],$[_+1,_2],_2=g!_]}g:=N@Join@Bounce@1&`:
```
[Try it online!](https://tio.run/##NUs9D4IwFNz9FTUQFjv0FRBKgiE66UAc3JqmECyVBYitk/G31woxucu7j3ettW33UK5HRelI9D73PJD0EGguBQ653AGWVHiWeivFRxdlXV2mYayO02vsVAVRU7haqbvh4Tx3Wmyuz2G0N2XsqTXK8B4jDjSmgJE/SbpPk8Uw7zGia7q0XvyQMwIxjf/vWc6AAABhebZuhXBf "Attache – Try It Online") With plan ol' recursion.
[Answer]
# [J](http://jsoftware.com/), 40 bytes
```
1#.[:(<-:"_1<@([:;>:<@":@-|@i:)@<:@#\)":
```
[Try it online!](https://tio.run/##ZYzBCoJAFEX3fsVjXIxCIz7HSX1N8SBw1aqtQkQ4VAQt2hT079OAYJGLC4fLvefqRSYdrAkkLCAHClEZbPe71mOcdZRYReKAlpOOVhuyLIjVmy@UsiWO@1SQTyOIhtP5Dg5wguIHdWmWptT/VVU3mCOGqcYSTYgOjJg3dTXun@NBtsfbY3jJ732iYJpbZwIHgQvtPw "J – Try It Online")
I'm not quite happy with this soluiton - a lot of `@` and boxing `<` .
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 109 bytes
```
N =INPUT
X =L ='1'
C R =LT(SIZE(L R),SIZE(N)) X R :F(O)
X =X + 1
L =L X :(C)
O OUTPUT =IDENT(L R,N) 1
END
```
[Try it online!](https://tio.run/##HYyxCoAgFADn51e8LR@1CE2CUxkI8gwzkMbmqKH/x8zthrt77@d8rrEUYDSO1z0JyGg8mk51YoJYOcnNHVZ6jDQ0YiLMGEEvMlDzM/aoBPi/zKDlRCJA2FP91e1sOf35wFQty3Mp6gM "SNOBOL4 (CSNOBOL4) – Try It Online")
Curiously, replacing `'1'` in the second line with `1` causes the program to fail on the input of `1`.
[Answer]
# [K](https://github.com/kevinlawler/kona), 36 bytes
```
{|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}
```
Takes a string such as "12321" as a parameter.
This function is written as a long chain of function applications, as in `f g h x`, so read the commented versions from the bottom, going up.
`{x+1}` is `lambda x: x+1`, x is a default param name. Check out <https://pastebin.com/cRwXJn7Z> or the interpreter's help for operator meanings.
We generate the staircase number with `n` in the middle by `{,/$(1+!x),1+1_|!x}`:
```
{,/ / join all the chars
$ / tostring each number
(1+!x) / take the range [0..x-1]; add 1 to each
, / concat
(1+1_|!x)} / take the range [0..x-1]; reverse it; drop 1; add 1 to each
```
The whole function `{|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}`:
```
{|/ / any_is_true
($x)~/: / match the string with each of the generated staircases
{,/$(1+!x),1+1_|!x}' / make staircase number of each of the numbers
/ (note: the x in the inner lambda shadows the outer x)
1+!#x} / take the range [1..length of the string, inclusive]
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~64~~ ~~60~~ 58 bytes
-6 thanks to @BMO!
```
elem.show<*>(`take`[[1..n]++[n-1,n-2..1]>>=show|n<-[1..]])
```
[Try it online!](https://tio.run/##HYtNDoMgGESvQkwXWn4iqF0Jl@iSkMgCoxE/m4IpC@9OSzeTmbw3iw2b8z7nWTrvdhaW4zPeVT1Fu7lJa84YGIw1UE6ACsa4UUoW64KRFmxMk3e7ApLodcZnfN9O8Cu4oIuFEsYVkgpVGJddzyg1V/pdW8IJF534Zz88hr70ruXG5C8 "Haskell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-lp`, 49 bytes
```
$i++while s/^$i//;$i-=2;$i--while s/^$i//;$_||=$i
```
[Try it online!](https://tio.run/##XYtLDsIgFEXnrKKJzBqER6GfNCzBLWhMRH0JUlJoOunaRawzJyc59@QGOzudM8W6Xp/obBX5mSLnI0Vm5Jfsb79sm6GYSzKLv9n7eLg6N62xSjYm9I/qtbiEoVysTzPamEE2SrddP4AAADH0XatVI4GU8KPaXZCBFOy@D@8pJJx8zOykjwJEZi58AA "Perl 5 – Try It Online")
`0` = truthy, anything else = falsy
[Answer]
# Java 10, 142 bytes
```
s->{int n=1,l,f=1;try{for(;;s=s.substring(l=(n+++"").length(),s.length()-l))if(!s.matches(n+".*"+n)&!s.equals(n+""))f=0;}finally{return f>0;}}
```
[Try it online.](https://tio.run/##lZCxbsIwEIZ3nuKaobIbMHGAQhqFsVtZYKs6mOBAqOPQ2KGKojx7egTUoQupdJZ85//O/3dHcRaj4@6zjZUwBt5EqusBQKqtLBIRS1hdUoBtnispNMRkbYtU78HQEB8aPBjGCpvGsAINEbRmtKxxAOiID9UwiXhoi6pO8oKEoYkMM@XWdEOIioh2XddxKFNS7@2B0KH5vY4UpWlCHgzLhI0P0qDYYU@Oq@kjFuVXKVRXcyhNIi9sklQLpaq6kLYsNCRLrDVtePV4KrcKPd6snvN0BxnS3njePwS9kl5WABlyaPndJaQjBRiPYVOU9lC9dOm6MlZmLC8tO@EEqzTJmGYxcTj6Ce9p/InfUzedPc@m/1HPFwH3OOdesJj/aUWGV1yavMvg9/gt6Omon3VUXmIReHziT3p13ETNoGl/AA)
**Explanation:**
```
s->{ // Method with String parameter and boolean return-type
int n=1, // Stair integer, starting at 1
l, // Length integer to reduce bytes
f=1; // Result-flag, starting at 1
try{for(;; // Loop until an error occurs
s=s.substring(l=(n+++"").length(),s.length()-l))
// After every iteration: remove `n` from the sides of the String
if(!s.matches(n+".*"+n)
// If the current String with the current `n` isn't a stair
&!s.equals(n+""))
// And they are also not equal (for the middle)
f=0; // Set the flag to 0
}finally{ // After the error (StringOutOfBoundsException) occurred:
return f>0;}} // Return whether the flag is still 1
```
[Answer]
# Japt, 11 bytes
Takes input as a string.
```
Êõõ mê m¬øU
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=yvX1IG3qIG2s+FU=&input=IjEyMzQ1Njc4OTEwMTExMDk4NzY1NDMyMSI=)
---
## Explanation
```
:Implicit input of string U
Ê :Length of U
õ :Range [1,Ê]
õ :Range [1,el] for each element
mê :Map & palidromise
m¬ :Map & join
øU :Contains U?
```
---
## Alternative, ~~10~~ 9 bytes
This solution, which can take input as a string or an integer, will return an array of numbers for truthy or, eventually, throw an error for falsey, if it doesn't cripple your browser before that. Use with caution.
```
@¥Xê q}aõ
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=QKVY6iBxfWH1&input=IjEyMzQ1Njc4OTEwMTExMDk4NzY1NDMyMSI=)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~45~~ 43 bytes
```
$
;1
+`^(.+)(.*)\1;\1$
$2;$.(_$1*
^(.+);\1$
```
[Try it online!](https://tio.run/##LUtJCoAwELvPO0ZoFUozdWnpA/yEaD148OJB/H@1KoQkZDm3az9W5EqNKTNFUJNmZRqtTK0nxAlMLJGNWhg1vVUJc4Y4AT3cdn3XFh8IJG9SikcLfLBw4v7h4AMsABv88L1u "Retina – Try It Online") Link includes test cases. Edit: Saved 2 bytes thanks to @Leo. Explanation:
```
$
;1
```
Initialise `n` to `1`.
```
+`^(.+)(.*)\1;\1$
```
While `s` begins and ends with `n`:
```
$2;$.(_$1*
```
Delete `n` from the ends of `s` and increment `n`.
```
^(.+);\1$
```
Test whether `n` is left.
[Answer]
# [Regex (PCRE)](http://php.net/manual/en/reference.pcre.pattern.syntax.php), 92 bytes
```
^(1|\d(?=1|9)|[2-79](?=8)|[2-68](?=7)|[2-57](?=6)|[2346](?=5)|[235](?=4)|[24](?=3)|3(?=2))+$
```
[Try it online!](https://regex101.com/r/F9j2El/5)
I'm open to any suggestions to improve this.
[Answer]
Thanks to following users:
```
@Nooneishere
@LyricLy
@JoKing
```
# [Python 2](https://docs.python.org/2/), 147 bytes
```
g=s=input()
f=1
o='1'==s[0]
while`f`==s[0]:s=s[len(`f`):];f+=1
f-=2
o&=`f`==s[0]
while s and`f`==s[0]:s=s[len(`f`):];f-=1
o&=f==0
o|=g=='1'
print o
```
[Try it online!](https://tio.run/##dY1NCoMwGET33ymyMkoRTPytZU5SBAs1GpAkNJZS6N3TiNBdV8MM7zHuvS3WyBBmeGjjnluakYIgCy444K/FQK9Fr9OoxqP2PsY6mTQuWT9c1CniKockm@BHHRLz7Gbu/9V8f0qggILsBzP2V3IPbTZmQ@BCllXdtN25a5u6KqXgXw "Python 2 – Try It Online")
] |
[Question]
[
So, here's a map of, let's say, a dungeon...
```
##########
# #####
# #####
##########
##########
##########
##########
#### ##
#### ##
##########
```
Let's say that the hero is in Room A (at the top left) and their goal (a prince in distress?) is in Room B (to the bottom right). Our map does not allow the hero to progress to their goal.
We need to add a passageway...
```
##########
# #####
# #####
####.#####
####.#####
####.#####
####.#####
#### ##
#### ##
##########
```
There, much better!
---
## Rules
* A program or function which accepts a dungeon map (made up of hashes and spaces, with rows separated by new line characters).
* It will output a map with dots added to denote passages in all spaces which are on a direct path between the space characters.
* It will not change the line length, or number of lines.
* Passages are all in a direct line from spaces to spaces.
+ Passages can not turn around corners
+ They will not be between spaces and the edge of the map.
* Use any language.
* Attempt to perform the conversion in the fewest bytes.
* If no passageways can be drawn, return the map, unchanged.
* The map should always have hashes around all edges (You do not need to handle spaces at the edge).
* Input maps are always rectangular, each row should be the same width.
## Test cases
```
#### ####
# # => # #
# # # #
#### ####
########## ##########
# ##### # #####
# ##### # #####
########## ####.#####
########## => ####.#####
########## ####.#####
########## ####.#####
#### ## #### ##
#### ## #### ##
########## ##########
########## ##########
# ##### # #####
# ##### # #####
########## ##########
########## => ##########
########## ##########
########## ##########
###### ## ###### ##
###### ## ###### ##
########## ##########
########## ##########
# ##### # #####
# ##### # #####
########## ####.#####
########## => ####.#####
#### ### #### ###
########## ######.###
###### ## ###### ##
###### ## ###### ##
########## ##########
########## ##########
# ##### # #####
# ##### # #####
########## ##..######
########## => ##..######
########## ##..######
########## ##..######
## ####### ## .######
## ###### ## ######
########## ##########
########## ##########
# ##### # #####
# ##### # #####
########## #.########
########## => #.########
########## #.########
####### # #.##### #
####### # #.##### #
# ##### # # ..... #
########## ##########
########## ##########
# ##### # #####
# ##### # #####
########## #.########
##### ### => #.### ###
##### ### #.### ###
####### # #.##### #
####### # #.##### #
# ##### # # ..... #
########## ##########
########## ##########
## # ## #
########## ##......##
########## ##......##
########## => ##......##
########## ##......##
########## ##......##
########## ##......##
# ## # ##
########## ##########
########## ##########
#### #### #### ####
####### ## ####..# ##
###### ### ####.. ###
# ### ## # => # ... .. #
# ## ### # # .. ... #
### ###### ### ..####
## ####### ## #..####
#### #### #### ####
########## ##########
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
ỴḲaLḊṖƊ¦”.KƊ€Z$⁺Y
```
[Try it online!](https://tio.run/##y0rNyan8///h7i0Pd2xK9Hm4o@vhzmnHug4te9QwV8/7WNejpjVRKo8ad0X@//9fXV1dGQ64lBWAAJOJpAAEwOIYTDAHhamALgoEQPsA "Jelly – Try It Online")
Tricky -1 thanks to [user202729](https://codegolf.stackexchange.com/users/69850/user202729).
Explanation:
```
ỴḲaLḊṖƊ¦”.KƊ€Z$⁺Y Arguments: S
Ỵ Split S on newlines
ḲaLḊṖƊ¦”.KƊ€Z$ Monadic link
ḲaLḊṖƊ¦”.KƊ€ Map over left argument
ḲaLḊṖƊ¦”.KƊ Monadic link
Ḳ Split on spaces
aLḊṖƊ¦”. Dyadic link with right argument '.'
aLḊṖƊ¦ Apply at specific indices
a Logical AND (vectorizes)
LḊṖƊ Monadic link
L Length
Ḋ Range [2..n]
Ṗ Remove last element
K Join with spaces
Z Zip
⁺ Previous link
Y Join with newlines
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p0`, 56 bytes
```
#!/usr/bin/perl -p0
/
/;$n="(.{@+})*";s%#%/ #*\G#+ |(?= )$n\G$n /s?".":$&%eg
```
[Try it online!](https://tio.run/##K0gtyjH9/1@fS99aJc9WSUOv2kG7VlNLybpYVVlVX0FZK8ZdWVuhRsPeVkFTJS/GXSVPQb/YXklPyUpFTTU1/f9/ZTjgUlYAAkwmkgIQAItjMMEcFKYCuihI7b/8gpLM/Lzi/7oFBv91fU31DA30DAE "Perl 5 – Try It Online")
[Answer]
# APL+WIN, 87 bytes
Prompts for character matrix:
```
n←(' '=m←⎕)⋄c←(∨⍀n)+⊖∨⍀⊖n⋄r←(∨\n)+⌽∨\⌽n⋄((,c>1)/,m)←'.'⋄((,r>1)/,m)←'.'⋄((,n)/,m)←' '⋄m
```
[Answer]
## **[Haskell](https://www.haskell.org/), 209 165 162 bytes.**
```
import Data.List
t=transpose
k=concat
j a=(foldr1 max<$>)<$>t<$>t[a,f<$>a,t$f<$>t a]
f b|(e:g:d@(h:_:_))<-group b=k[f$e++g,'.'<$h,drop(length h)$f$k d]|1>0=' '<$b
```
[Try it online!](https://tio.run/##7VbJasMwEL37KwbHEIu4obmaOBTaY3rq0ZigxPISb8KaQA/5d1eustDWSmoSKAkdGI@YJz2PHtKghIqM5XnTpAWvaoQXinQ8TwUa6GFNS8ErwYzMW1XliqKxBurZUZWH9QQK@j61ZkQ6tu5TJ5KROmi1EYEGRgTLrc3c2A2f7MRduAtCpg9xXW04LL3Mjyw2GsXOcDycWokT1hW3c1bGmEBCrMjKIAy2k9mjNwQ5YdkgE/hMBRPggW/Azo6j1syBNNP5lgP4Xa5de0gFR9QH@DlTWQevZO6J6Nmujqgi@iE7tk5l7kWXdv/9kdvSRfH963I5AnoEzrLdhy6a/qlB4Mya9j/73GX6DHajP@4mPZF90bd0bvTd5FSfuf65ufC87O@sript9@vUUgHdO1FgBxv07zNnqv6qi6G@BU1L@XYqKH9dgK0C3@Ab1vOSfCZgDXZaIqsFl87AN80ADu8uQpoP "Haskell – Try It Online")
Not the most efficient way of doing it in Haskell I'm sure. It's got too many parentheses for my liking but I'm not sure how to remove any more.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~173~~ 148 bytes
```
m=input().split('\n')
exec"m=zip(*[[c*(c!='#')or'#.'[(' 'in r[i:])*(' 'in r[:i])]for i,c in enumerate(r)]for r in m]);"*2
for r in m:print''.join(r)
```
[Try it online!](https://tio.run/##xVLLbsMgELz7K7b4sIAqH3KrK3@J40NFiEpVAyJEavPzDob4kdqqqiZV94BmZ4ed5WE//avRm06YnawcIaRrK6Xt0VNWHOy78hS3GlkmP6QgbXVSlvK6FpyKhwpzZMZhXmBNEVBpcLUqG8bHrFQNa/bGgXoUEBipj610L15Sl3jXs23DngnfZBNRWqe0RyzejNJB28U8C@PFQaCflj91JA@x1TnAtIYgWSykiIVQWsFzzQ9x2r7EKf7QuLdbx3cyTqp/MF7HMMew1NzfePw@I4YFf4Px/Hqvr/qXxtENvohuxEPL742HF5mmnn2QS6MEh9OkNGpg/Y0XPXvjMw "Python 2 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 95 bytes
```
+`(?<=(.)*)#(?=.*¶(?>(?<-1>.)*)[ .])
.
+`\.(?=(.)*)(?<*)¶.*)
#
(\S+)
$.1$*.
```
[Try it online!](https://tio.run/##ZYq7DYAwDER7T2EUCjsRluiBDEEJSFBQ0FAgZmMAFgtOCsTnVXfvbpv3ZZ1CcCP5qiZhy4Z8LfY8yDfqirKJskMZGATc2Ivu6ahrFv3reB5iGQwg9a1jBMylzK1gCOYGDCr/@DhEkv/FVF4Rv1a5AA "Retina 0.8.2 – Try It Online") Explanation:
```
+`(?<=(.)*)#(?=.*¶(?>(?<-1>.)*)[ .])
.
```
This looks for `#` signs that are above spaces or `.`s and turns them into dots until there are none left. The lookbehind finds the `#`'s column and then the lookahead skips to the next line and atomically to the same column below so that the space or `.` can only match if it's exactly below the `#`.
```
+`\.(?=(.)*)(?<*)¶.*)
#
```
This looks for `.`s that are not below spaces or `.`s and turns them back into `#`s until there are none left. The lookahead finds the `.`'s column and then the lookbehind skips to the previous line and atomically to the same column above in much the same way so that the space or `.` can only match if it's exactly above the `#`. A negative lookbehind is used so that this also works for `.`s in the top row.
```
(\S+)
$.1$*.
```
(Note trailing space on both lines) This simply looks for all runs of non-whitespace characters between spaces and ensures that they are all `.`s.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 104 bytes
```
->s{2.times{s=((0...s=~/\n/).map{|i|s.lines.map{|b|b[i]}*""}*"\n").gsub(/ [#.]+(?= )/){$&.tr(?#,?.)}};s}
```
[Try it online!](https://tio.run/##dY3PDoIwDIfvPEUDxmz@6YxXmZz06gMAB5eAWSILoXAwY776FGa42aTJ97Vpf92gXr6Wfn8me8ReNxVZkowdEJHkWxRGcGzurR31SPjUpqKgalS5Lt0mjr9dmJjjgwbFBOQJlluWSeCC29Ua@45lyS5D7tyJnG@HnqDO0/Ryu0bJUjMCLDjZgjBPIRAEDBb9tuEM/j@bcEos/Qc "Ruby – Try It Online")
Well, it's not great, but at least it's convoluted. I'm sure it can be improved.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╛XA╟φkôα`æbπ┐w↨╙j≥☺
```
[Run and debug it](https://staxlang.xyz/#p=be5841c7ed6b93e0609162e3bf7717d36af201&i=%23%23%23%23%0A%23++%23%0A%23++%23%0A%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23++++%23%23%0A%23%23%23%23++++%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23++%23%23%0A%23%23%23%23%23%23++%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23+++%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23++%23%23%0A%23%23%23%23%23%23++%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23+%23%23%23%23%23%23%23%0A%23%23++%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23++%23%0A%23%23%23%23%23%23%23++%23%0A%23+%23%23%23%23%23++%23%0A%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23++++%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23++%23%23%23%0A%23%23%23%23%23++%23%23%23%0A%23%23%23%23%23%23%23++%23%0A%23%23%23%23%23%23%23++%23%0A%23+%23%23%23%23%23++%23%0A%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23+++++++%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%23+++++++%23%23%0A%23%23%23%23%23%23%23%23%23%23%0A%0A%23%23%23%23%23%23%23%23%23%23%0A%23%23%23%23++%23%23%23%23%0A%23%23%23%23%23%23%23+%23%23%0A%23%23%23%23%23%23+%23%23%23%0A%23+%23%23%23+%23%23+%23%0A%23+%23%23+%23%23%23+%23%0A%23%23%23+%23%23%23%23%23%23%0A%23%23+%23%23%23%23%23%23%23%0A%23%23%23%23++%23%23%23%23%0A%23%23%23%23%23%23%23%23%23%23&m=1)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org),205 193 190 186 181 175 172 bytes
```
r=>r.split`
`.map(x=>[...x]).map((R,y,r)=>R.map((c,x)=>{for(D=2;c<"#"&&D--;){for(;(T=(r[y+=D]||0)[x+=!D])>" ";);for(;r[y-=D][x-=!D]>c;)T?r[y][x]=".":0}})&&R.join``).join`
`
```
[Try it online!](https://tio.run/##xVZdb4IwFH3vr@hoQmiUG7PHsbIXfoHxjZBg2Fw0TgyaBTP97ay2fBQoiE6z@2DPvb3tuae0N67m3/NdlCy3e3sTv39kC5YlzE1gt10v9yEK4Wu@tVLm@gCQBlS41nR8GCeUuVPpRuOUOz@LOLE89uxErwYxTNOzbYeKoGPNmJX4hxHzguNxQv10xJ68gLoGNhzqiBQ@bfNpP7XPU27k0Nkbj/FAwAwwXianEzXNKazi5SYMqRxRmEXxZhevP2Adf1oLKyTcEMG4@OEWUsb0cYTqq5FIk3bO45ktqCQMgXJlE0orC7vICFfAfsamYozvr/lMrIPXab4f4301y5THaO78ohUN/IdmHcQKxK2EoZoByGCIoZ/xgmZSLCsWKccn65IISyg9REqldc3NzXSa60lcCS5hzsibKj47AgpPMkrVgrGEWkak6X/KKQm75T21YLFXv2CFEYSR26GWEfUqHnStlddUe8rKQeH8DtSjw681VAlQ0TRgvrcCsdDeZPyz4C74OMFd8FbBte9Ujnm9qNGImnm5hGIOQB3zCpR4xx7tvwpVgyC66qoT0@bJqoonD6Kzd49Va6jvkf0C "JavaScript (Node.js) – Try It Online")
### Commented
```
f=r=>r.split`
` -> //getting as string with lines
.map(x=>[...x]) //to 2d string array
.map((R,y,r)=> //r - the new 2d string array
R.map((c,x)=>{ //
for(D=2;c<"#"&&D--;) //instead of using if joining c==" " with the loop,D=1/0
{for(; //
(T=(r[y+=D]||0)[x+=!D])>" ";); //0[num] = undefined. checking for a path - consisting of # or .(or not consisting of space or undefined), we dont need temp (X,Y) because in the next loop we will return to our original position regardless of the correctness of the path
for(;T&&r[y-=D][x-=!D]>c;) //again instead of if(T) combine with loop. if T is not undefined it will be a space because the array can return .#(space). and we then go back to the source(x,y)
//remeber that c==" "
r[y][x]="." //and just putting . where weve been
}})&&R.join`` //instead of return r as string at the end , we know that we cant change a row at a smaller index(due to D-0/1) so we can return R.join`` already
).join`
`
```
] |
[Question]
[
## Self-limiting lists
Consider a nonempty list **L** containing nonnegative integers.
A *run* in **L** is a contiguous sublist of equal elements, which cannot be made longer.
For example, the runs of **[0,0,1,1,3,3,3,2,1,1]** are **[0,0], [1,1], [3,3,3], [2], [1,1]**.
The list **L** is *self-limiting* if for each integer **N ≥ 1**, the number of occurrences of **N** is less than or equal to the number of runs of **N-1**.
The above list is not self-limiting, because there are 4 occurrences of **1**, but only one run of **0**s.
Here's an example of a self-limiting list: **[0,0,3,4,1,0,2,1,1,0,2,1,0,0,0,1,0]**.
It has
* 5 runs of **0** and 5 occurrences of **1**,
* 4 runs of **1** and 2 occurrences of **2**,
* 2 runs of **2** and 1 occurrence of **3**,
* 1 run of **3** and 1 occurrence of **4**,
* 1 run of **4** and no occurrences of **5**,
* no occurrences of other integers.
## The task
Your task is to decide whether a list is self-limiting.
More explicitly, your input shall be a nonempty list of nonnegative integers.
If the list is self-limiting, your output shall be truthy; otherwise, it shall be falsy.
Input and output can be in any reasonable format.
The lowest byte count in each programming language is the winner.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test cases
Truthy instances:
```
[0]
[1,0]
[0,1,1,0,2]
[3,1,1,0,0,2,0,0]
[5,0,4,1,3,0,2,2,0,1,1,1,0]
[0,0,1,1,0,0,1,1,0,0,2,2,0,0]
[6,0,0,0,2,2,1,0,5,0,3,4,0,1,1,1]
[5,0,1,0,0,0,0,4,0,3,1,1,1,2,2,0,0,0,0,0]
[4,5,1,3,2,0,5,2,0,3,0,1,0,1,0,0,0,1,0,0,1,0,3,4,4,0,2,6,0,2,6]
[0,4,1,3,10,6,0,1,3,7,9,5,5,0,7,4,2,2,5,0,1,3,8,8,11,0,0,6,2,1,1,2,0,4]
```
Falsy instances:
```
[2]
[1,1,0]
[0,0,1,1,1,0,0,2]
[0,1,0,1,1,2,2,3,0,0,4,6]
[1,1,2,1,2,0,2,0,3,0,0,2,2,1,2,3,2,0,1,1,1,0,0,3,3,0]
[3,4,1,0,0,0,5,5,0,2,2,0,0,0,0,0,2,0,1,1,0,4,3,5,4,3]
[1,0,0,0,2,5,3,1,1,0,3,3,1,3,5,4,0,4,0,0,2,0,2,1,1,5,0,0,2,4,4,0,2,0,1,4,4,2,3,3,5,3,4,0,2,0,5]
[4,3,1,0,0,4,6,6,1,0,1,2,1,3,0,1,0,2,0,3,4,0,2,1,1,3,0,2,2,2,0,5,5,0,5,2,5,5,0,4,3,2,3,1,1,3,5,1,4,1,6,2,6,2,4,0,4,0,4,5,3,3,0,0,6,1,0,0,0,6,2,1,0,1,2,6,2,4]
[5,1,1,1,0,2,0,6,1,0,2,1,2,2,5,3,1,0,0,0,3,2,3,0,1,1,0,1,0,1,1,2,0,6,4,1,2,1,1,6,4,1,2,2,4,0,1,2,2,1,3,0,1,2,0,0,0,2,0,2,2,0,1,0,0,1,3,0,0,0,6,2,0,1,0,1,2,1,1,1,0,4,0,0,5,2,0,0,0,4,1,2,2,2,2,0,5,3,2,4,5,0,5]
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 29 bytes
```
{bag(.grep(?*)X-1)⊆.squish}
```
[Try it online!](https://tio.run/##bVPNSsNAEL73KUIRaSXK7uxuqhTx5hN4EEKQCm0VKtaEHop49eBj@iJx5zdRZGGzO7Mz833fTPbrdlf1L8fidFNc9@@Pq@3sYtuu97Obs/n9uZ9/f31edG@H5@7po@9Wx2Ja37WHdTNdTvC2mZ08zIvNazupXVNOal/Sx5U@L1cCXoJc8hV3NKV8iNkYyIhmz4842FnEEGmxFRnYhE7MFXI2yaHpvTxz5ApSQPLwwqcxxyMOoExATzlYE3jbsUqkyhXvjJaJeEdWPC7Kq5wLQSyyE0sm8Vzm5TlhRfA9lYwNqzmtb1e77j9xgcX9o5Boo4o7oxiEeKVhIJWUoMoHQn3IFtDPbYumAbP5JZ6FYZ2Q/XmXCRB3KrXzgU78iPvhBA36k9xVXEwbSbhAMcHsiTsWBFfmlxfzBpkmbySjFdApA2OSCF4S7CBAA80Csq6ox2BwI8EI0jilWMkEen3Ns6dagj0GaUsy6E7KqoRD8zAmCiFvZ5ABhxFRGDVCfyIngzYAdCOBtF3Oht3JjwgjgQJVI5maZf8D "Perl 6 – Try It Online")
Very nice challenge for Perl 6. Uses the subset operator on [Bags](https://docs.perl6.org/type/Bag) (integer-weighted sets). Explanation:
```
{
bag( # Create bag of
.grep(?*) # non-zero elements,
X- 1 # decremented by one.
)
⊆ # Subset test.
.squish # "squish" removes repeated elements in each run.
# The result is implicitly converted to a bag
# counting the number of runs.
}
```
[Answer]
# JavaScript (ES6), ~~92~~ 89 bytes
```
a=>a.map(n=>g(~n,n!=p&&g(p=n)),c=[j=0],p=g=n=>c[n]=-~c[n])&&!c.some((n,i)=>i-j++|n<c[~j])
```
[Try it online!](https://tio.run/##fVTbTgIxEH33L3jB3VhIr4smlke/wLfNPmxWQAh2N6ImJoZfx850WpZYTJNSOrcz50x31361h@59O3zMXP@yOq3tqbXLdv7WDoWzy01xdMxN7DCdborBurJkna13ljdssBvrPbraNXZ2hJ9yOp1080P/tioKx7alXW5nu7u7H/fY1cddU5663h36/Wq@7zfFbf38/vnx@t3cljfj@3VR86b8cydY7pYz4RdnMmNTZPNW2DMext9r76PQB7xEiMlW4infOe@1zBXagwf4QiXla1GFK1gERXH0VISGqoSVidQ@O/QgsY7EyJAr5hNpBwwacVVhz3YaOBEcneC4YA8@NUBceCMAMmS590uE/BX2KhCBhrw3l3I/tftDTm2ZVft/FYj/KxPBE2@K2Kyu1JCEN7IWFZPE57mWAnt2ynTiOVB0oVfKAiiUt/s9P93kbVicW4WnEBMmghNWsBv6H/WEKhrFURij0r3Jzowi1J4bvwJnkt6CSIzoVC@@EZn6NIjWUGeScCucRuCkwimTCb1GVIpmJXZc0QsR0Tv7NqIOMsVKUtikTjihiHyf5wBiNPUn0lnSe5SjvuVItfhF4DTqZ7x8xFfUlqfXx@mrIkd8KaxmSI3TLw "JavaScript (Node.js) – Try It Online")
### How?
The array **c[ ]** is used to store both the number of runs and the number of integer occurrences. Runs are stored at non-negative indices and integer occurrences are stored at 1's-complement indices (**c[-1]** = number of **0**'s, **c[-2]** = number of **1**'s, etc.).
Negative indices are actually saved as *properties* of the underlying array object and **.some()** does not iterate over them.
```
a => // given the input array a[]
a.map(n => // for each value n in a[]:
g( // update c[]:
~n, // increment c[~n] (# of integer occurrences)
n != p && g(p = n) // if n != p, set p to n and increment c[n] (# of runs)
), // end of c[] update
c = [j = 0], // start with c = [0] and j = 0 (used later)
p = // initialize p to a non-numeric value
g = n => c[n] = -~c[n] // g = helper function to increment c[n]
) // end of map()
&& !c.some((n, i) => // for each value n at position i in c[]:
i - j++ | // make sure that i == j++
n < c[~j] // and n is greater than or equal to c[~j]
) // end of some()
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~49~~ ~~48~~ 44 bytes
```
#!/usr/bin/perl -p
$z[$_+1]+=!/^$o$/;$z[$o=$_]--}{$_="@z"!~/.-/
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lKlolXtswVttWUT9OJV9F3xokkm@rEh@rq1tbrRJvq@RQpaRYp6@nq///vwGXCZchlzGXoQGXGZcBmGnOZcllCoQGQJYJlxEQmkJlLIDQ0BDIASk2AgoZAkmQCf/yC0oy8/OK/@sWAAA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
œ-ŒgḢ€‘ƊS¬
```
[Try it online!](https://tio.run/##ZVO7TQRBDM2p4gpYJI89swcVUADhakOEhK4BMnQJEiEkxMRXwMWgow@ukcX/WYRWGs348/ye7X242@0el@X0dnl6vf85fpz3h/PT@/fL7edh@XqW1/5wsyzTNME8XGw2Uxn8AkPhDwa0J/mTDXKasfG1spnULI5iYQEBmdWzV/mjmswobsEjRnScXqR4IKiTvIxj2WfBlTGEDyoaarClB0TJUypVrT7aGaxNUgG1y3U7XDOaENmyU8o291zxVwxyVBFFi9ZZsKYJo6n/euLd6L2GlEQudOzJ6LghKFqGLrUjkvhjZDVVG/s/DctEqUXs5zN3wAPaEHMnvVmYTQGckfibv6OhAly1VaQ5lPYWcyLnxjr5M/3ou1RSas0SsWOYapoSbM4fnSrpBojyUSeLSbgqEfJhhcjRd69EdGxd9BQzHH1ALcmDF45G9jFKTnVJJe/oy40rqbgaR/xE4OvVKcKqRTE0yCUH/xFx1SLSatqoeZ5/AQ "Jelly – Try It Online")
### How it works
```
œ-ŒgḢ€‘ƊS¬ Main link. Argument: A (array)
Ɗ Drei; group the three links to the left into a monadic chain.
Œg Group consecutive, identical elements of A into subarrays.
Ḣ€ Head each; pop the first element of each run.
‘ Increment the extracted integers.
The resulting array contains n repeated once for each run of (n-1)'s.
œ- Perform multiset subtraction, removing one occurrence of n for each
run of (n-1)'s.
S Take the sum. If only 0's remain, the sum will be 0.
¬ Take the logical NOT, mapping 0 to 1 and positive integers to 0.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
ŒgḢ€ċЀṀḶ$<ċЀṀR$$Ẹ
```
[Try it online!](https://tio.run/##XVM7TsRADO05x5ZTOPZMFiROQbvaEiGhvQAdoqGgQRyBmhottAsHCRcJY/vZCWik@cS/956d2@vD4W6ev19upuPrz8Pb19PpuR/Tx/10fN9cLs@rzWb6PM6nx/6c592OChUptQz95L7HSbb6uS9nO9viHk76EDw0htze@kXTiX3k4v4ZTBmxRGbsiLIMCA3gkCPSBzoyk6AA8vhS19rjFQdbJjZXD17Rw65VqlUefXe0TmQg@6rXbbnouRTEthu1ZIPlvK/BE45QUktWTcSu3z8RQD9EpWQh4DZGGCNZcAiFGOyWbKJ270xNmg74jz4ZpnWk2/uOJsPcSjRX7OZOLjkBjdob3qGfpq2mjViM5PfmTRHg6vz6ct6MgRmSZM0CMUicTJrBa8DOACrWbmU9Whs54VaDIehNUBwxZEN4@3gN@ROEM6MtLaETyoaES/M0poLQkHfGDPOKKK8aEf8JYZYWgLQSKNpFOc@Ef41XAolVM5n2@18 "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
ŒgḢ€ċ’}<ċ
çЀx⁸ẸṆ
```
[Try it online!](https://tio.run/##y0rNyan8///opPSHOxY9alpzpPtRw8xamyPdXIeXH54AFKh41Ljj4a4dD3e2/f//P9pUxxAMDXSMgNgMyjIEYiMdUx1jMB8EjYF8YyANUWsIZUH0mIBZID6MbQSkDaAsQ6g@I6hJRmBsBDXFACpvADbJCG62EdxdJmA5U7h@mA0QM0zBLjMB0kB2LAA "Jelly – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 94 bytes
```
lambda a:all(sum(1for x,y in zip(a,a[1:]+[-1])if x==j!=y)>=a.count(j+1)for j in range(max(a)))
```
[Try it online!](https://tio.run/##VVPbbsIwDH2Gr@jeUtFNuZYNqfuKvbFqyjYYRaVUHWywn2e246SgSCH15fgc2/Tnw2bfmcu6er20fvf@6TO/8G0rvo87odb7ITsV56zpsr@mF77wS7WoZ8t7VefNOjtV1fauOufPlX/42B@7g9jOVI5JW0wZfPe1Ejt/Ej7P88vvpmlX2ctwXC2mk6Z7yyoI6o8HkU8n/dBA9lqsfnwrwIfxS1lPl6rAWxYKjiw0vA2/4QtvsDj4tWAzZEOrCjGUKVP8mBczS/oOFvQhkgEsRmBsxVGSPIbRGSUciLSQjRw04WiKDLkxX6Uba1iqW4abmAYNSpIRn/PiCaCQwhycWNCx5xGOCnglcVdU0QKOpq7dqmfd3EmZ@BtWVXKOZpzIPnZGs64Ry6CfpmGTvkD1pi8pC6sY8MMdpspeV8R5GnqFmNBpyVzQ7/g79g1RLTXFUI5JdkezMMwKtMEJmjXviEoKbcKPu6OTDkfsHDPXzNPQlFFzSdPTia0lFoZnEhWWvFkqRtNOxT7qFKt5Ii4xl1w19m@cG@ZY1qPSW/Pe6iud@moK8Z8heYVGfvKqP3FWMm2x5H@XvuqPoWrUpfof "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 21 bytes
```
x o e@ó¥ mÌè¥X ¨Uè¥XÄ
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=eCBvIGVA86UgbczopVggqFXopVjE&input=WzAsMCwzLDQsMSwwLDIsMSwxLDAsMiwxLDAsMCwwLDEsMF0=)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~13~~ 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
Dennis [found a much better algorithm](https://codegolf.stackexchange.com/a/160001/527). I've shamelessly ported it to stax.
```
ä╨²@┬↕OR♣
```
[Run and debug it online](https://staxlang.xyz/#p=84d0fd40c2124f5205&i=[0]%0A[1,0]%0A[0,1,1,0,2]%0A[3,1,1,0,0,2,0,0]%0A[5,0,4,1,3,0,2,2,0,1,1,1,0]%0A[0,0,1,1,0,0,1,1,0,0,2,2,0,0]%0A[6,0,0,0,2,2,1,0,5,0,3,4,0,1,1,1]%0A[5,0,1,0,0,0,0,4,0,3,1,1,1,2,2,0,0,0,0,0]%0A[4,5,1,3,2,0,5,2,0,3,0,1,0,1,0,0,0,1,0,0,1,0,3,4,4,0,2,6,0,2,6]%0A[0,4,1,3,10,6,0,1,3,7,9,5,5,0,7,4,2,2,5,0,1,3,8,8,11,0,0,6,2,1,1,2,0,4]%0A[2]%0A[1,1,0]%0A[0,0,1,1,1,0,0,2]%0A[0,1,0,1,1,2,2,3,0,0,4,6]%0A[1,1,2,1,2,0,2,0,3,0,0,2,2,1,2,3,2,0,1,1,1,0,0,3,3,0]%0A[3,4,1,0,0,0,5,5,0,2,2,0,0,0,0,0,2,0,1,1,0,4,3,5,4,3]%0A[1,0,0,0,2,5,3,1,1,0,3,3,1,3,5,4,0,4,0,0,2,0,2,1,1,5,0,0,2,4,4,0,2,0,1,4,4,2,3,3,5,3,4,0,2,0,5]%0A[4,3,1,0,0,4,6,6,1,0,1,2,1,3,0,1,0,2,0,3,4,0,2,1,1,3,0,2,2,2,0,5,5,0,5,2,5,5,0,4,3,2,3,1,1,3,5,1,4,1,6,2,6,2,4,0,4,0,4,5,3,3,0,0,6,1,0,0,0,6,2,1,0,1,2,6,2,4]%0A[5,1,1,1,0,2,0,6,1,0,2,1,2,2,5,3,1,0,0,0,3,2,3,0,1,1,0,1,0,1,1,2,0,6,4,1,2,1,1,6,4,1,2,2,4,0,1,2,2,1,3,0,1,2,0,0,0,2,0,2,2,0,1,0,0,1,3,0,0,0,6,2,0,1,0,1,2,1,1,1,0,4,0,0,5,2,0,0,0,4,1,2,2,2,2,0,5,3,2,4,5,0,5]%0A&a=1&m=2)
Unpacked, ungolfed, and commented, this is what it looks like.
```
c copy input
:g get run elements
{^m increment each
|- multiset-subtract from original input
|M! get maximum from result, and apply logical not
```
[Run this one](https://staxlang.xyz/#c=c%09copy+input%0A%3Ag%09get+run+elements%0A%7B%5Em%09increment+each%0A%7C-%09multiset-subtract+from+original+input%0A%7CM%21%09get+maximum+from+result,+and+apply+logical+not&i=[0]%0A[1,0]%0A[0,1,1,0,2]%0A[3,1,1,0,0,2,0,0]%0A[5,0,4,1,3,0,2,2,0,1,1,1,0]%0A[0,0,1,1,0,0,1,1,0,0,2,2,0,0]%0A[6,0,0,0,2,2,1,0,5,0,3,4,0,1,1,1]%0A[5,0,1,0,0,0,0,4,0,3,1,1,1,2,2,0,0,0,0,0]%0A[4,5,1,3,2,0,5,2,0,3,0,1,0,1,0,0,0,1,0,0,1,0,3,4,4,0,2,6,0,2,6]%0A[0,4,1,3,10,6,0,1,3,7,9,5,5,0,7,4,2,2,5,0,1,3,8,8,11,0,0,6,2,1,1,2,0,4]%0A[2]%0A[1,1,0]%0A[0,0,1,1,1,0,0,2]%0A[0,1,0,1,1,2,2,3,0,0,4,6]%0A[1,1,2,1,2,0,2,0,3,0,0,2,2,1,2,3,2,0,1,1,1,0,0,3,3,0]%0A[3,4,1,0,0,0,5,5,0,2,2,0,0,0,0,0,2,0,1,1,0,4,3,5,4,3]%0A[1,0,0,0,2,5,3,1,1,0,3,3,1,3,5,4,0,4,0,0,2,0,2,1,1,5,0,0,2,4,4,0,2,0,1,4,4,2,3,3,5,3,4,0,2,0,5]%0A[4,3,1,0,0,4,6,6,1,0,1,2,1,3,0,1,0,2,0,3,4,0,2,1,1,3,0,2,2,2,0,5,5,0,5,2,5,5,0,4,3,2,3,1,1,3,5,1,4,1,6,2,6,2,4,0,4,0,4,5,3,3,0,0,6,1,0,0,0,6,2,1,0,1,2,6,2,4]%0A[5,1,1,1,0,2,0,6,1,0,2,1,2,2,5,3,1,0,0,0,3,2,3,0,1,1,0,1,0,1,1,2,0,6,4,1,2,1,1,6,4,1,2,2,4,0,1,2,2,1,3,0,1,2,0,0,0,2,0,2,2,0,1,0,0,1,3,0,0,0,6,2,0,1,0,1,2,1,1,1,0,4,0,0,5,2,0,0,0,4,1,2,2,2,2,0,5,3,2,4,5,0,5]%0A&a=1&m=2)
**Old Answer:**
```
║Ä|╤#╫∩▼cëózü
```
[Run and debug it](https://staxlang.xyz/#p=ba8e7cd123d7ef1f6389a27a81&i=[0]%0A[1,0]%0A[0,1,1,0,2]%0A[3,1,1,0,0,2,0,0]%0A[5,0,4,1,3,0,2,2,0,1,1,1,0]%0A[0,0,1,1,0,0,1,1,0,0,2,2,0,0]%0A[6,0,0,0,2,2,1,0,5,0,3,4,0,1,1,1]%0A[5,0,1,0,0,0,0,4,0,3,1,1,1,2,2,0,0,0,0,0]%0A[4,5,1,3,2,0,5,2,0,3,0,1,0,1,0,0,0,1,0,0,1,0,3,4,4,0,2,6,0,2,6]%0A[0,4,1,3,10,6,0,1,3,7,9,5,5,0,7,4,2,2,5,0,1,3,8,8,11,0,0,6,2,1,1,2,0,4]%0A[2]%0A[1,1,0]%0A[0,0,1,1,1,0,0,2]%0A[0,1,0,1,1,2,2,3,0,0,4,6]%0A[1,1,2,1,2,0,2,0,3,0,0,2,2,1,2,3,2,0,1,1,1,0,0,3,3,0]%0A[3,4,1,0,0,0,5,5,0,2,2,0,0,0,0,0,2,0,1,1,0,4,3,5,4,3]%0A[1,0,0,0,2,5,3,1,1,0,3,3,1,3,5,4,0,4,0,0,2,0,2,1,1,5,0,0,2,4,4,0,2,0,1,4,4,2,3,3,5,3,4,0,2,0,5]%0A[4,3,1,0,0,4,6,6,1,0,1,2,1,3,0,1,0,2,0,3,4,0,2,1,1,3,0,2,2,2,0,5,5,0,5,2,5,5,0,4,3,2,3,1,1,3,5,1,4,1,6,2,6,2,4,0,4,0,4,5,3,3,0,0,6,1,0,0,0,6,2,1,0,1,2,6,2,4]%0A[5,1,1,1,0,2,0,6,1,0,2,1,2,2,5,3,1,0,0,0,3,2,3,0,1,1,0,1,0,1,1,2,0,6,4,1,2,1,1,6,4,1,2,2,4,0,1,2,2,1,3,0,1,2,0,0,0,2,0,2,2,0,1,0,0,1,3,0,0,0,6,2,0,1,0,1,2,1,1,1,0,4,0,0,5,2,0,0,0,4,1,2,2,2,2,0,5,3,2,4,5,0,5]%0A&a=1&m=2)
It iterates over the input and checks the conditions:
* Is the element `> 0`?
* Is `occurrences(element) >= runs(element - 1)`?
If either of these conditions are true for an element, then that element is compliant. Iff all elements are compliant, the result is `1`.
Here's the unpacked, ungolfed, commented representation of the same program.
```
O push 1 under the input
F iterate over the input using the rest of program
|c skip this iteration of the value is 0
x# number of occurrences of this value in input (a)
x:g _v# number of runs of (current-1) in input (b)
>! not (a > b); this will be truthy iff this element is compliant
* multiply with running result
```
[Run this one](https://staxlang.xyz/#c=O++++++++%09push+1+under+the+input%0AF++++++++%09iterate+over+the+input+using+the+rest+of+program%0A++%7Cc+++++%09skip+this+iteration+of+the+value+is+0%0A++x%23+++++%09number+of+occurrences+of+this+value+in+input+%28a%29%0A++x%3Ag+_v%23%09number+of+runs+of+%28current-1%29+in+input+%28b%29%0A++%3E%21+++++%09not+%28a+%3E+b%29%3B+this+will+be+truthy+iff+this+element+is+compliant%0A++*++++++%09multiply+with+running+result&i=[0]%0A[1,0]%0A[0,1,1,0,2]%0A[3,1,1,0,0,2,0,0]%0A[5,0,4,1,3,0,2,2,0,1,1,1,0]%0A[0,0,1,1,0,0,1,1,0,0,2,2,0,0]%0A[6,0,0,0,2,2,1,0,5,0,3,4,0,1,1,1]%0A[5,0,1,0,0,0,0,4,0,3,1,1,1,2,2,0,0,0,0,0]%0A[4,5,1,3,2,0,5,2,0,3,0,1,0,1,0,0,0,1,0,0,1,0,3,4,4,0,2,6,0,2,6]%0A[0,4,1,3,10,6,0,1,3,7,9,5,5,0,7,4,2,2,5,0,1,3,8,8,11,0,0,6,2,1,1,2,0,4]%0A[2]%0A[1,1,0]%0A[0,0,1,1,1,0,0,2]%0A[0,1,0,1,1,2,2,3,0,0,4,6]%0A[1,1,2,1,2,0,2,0,3,0,0,2,2,1,2,3,2,0,1,1,1,0,0,3,3,0]%0A[3,4,1,0,0,0,5,5,0,2,2,0,0,0,0,0,2,0,1,1,0,4,3,5,4,3]%0A[1,0,0,0,2,5,3,1,1,0,3,3,1,3,5,4,0,4,0,0,2,0,2,1,1,5,0,0,2,4,4,0,2,0,1,4,4,2,3,3,5,3,4,0,2,0,5]%0A[4,3,1,0,0,4,6,6,1,0,1,2,1,3,0,1,0,2,0,3,4,0,2,1,1,3,0,2,2,2,0,5,5,0,5,2,5,5,0,4,3,2,3,1,1,3,5,1,4,1,6,2,6,2,4,0,4,0,4,5,3,3,0,0,6,1,0,0,0,6,2,1,0,1,2,6,2,4]%0A[5,1,1,1,0,2,0,6,1,0,2,1,2,2,5,3,1,0,0,0,3,2,3,0,1,1,0,1,0,1,1,2,0,6,4,1,2,1,1,6,4,1,2,2,4,0,1,2,2,1,3,0,1,2,0,0,0,2,0,2,2,0,1,0,0,1,3,0,0,0,6,2,0,1,0,1,2,1,1,1,0,4,0,0,5,2,0,0,0,4,1,2,2,2,2,0,5,3,2,4,5,0,5]%0A&a=1&m=2)
[Answer]
## Haskell, 80 bytes
```
import Data.List
o#l=[1|x<-l,x==o]
f x=and[(i-1)#(head<$>group x)>=i#x|i<-x,i>0]
```
[Try it online!](https://tio.run/##dVTBbsIwDL3zFZHgAFKZEicpm0Q57bg/QBwqAaNaoQg6qQf@vYsdJy20U6Qoje3n52enp/z@cyjLti3O1@pWi8@8zt@@ins9qaZltlWPZr0skybLqt3kKJosv@y382KpFtP56ZDv17PN9636vYpmscmKafMo1ssmKTZy157z4iIysa8mQlxvxaUWM3EUW7l7/lbJ641MlFsygZd7zffOgvuL1bo74@ya7OihvP8AXUacDm8MMSWbt6IfZtAuByOP5FccIclLMwNG9@slyjhU5AyEDxTlcQKWijvmNsQn9fugMl@/kuSAx1Xy4WCR2soZkYhly7tbymOnVJ@i7AYxn2Fh0LD/RWU5RxoqoxSaBUpHcIFpBCGC@MASdTk02gcDYqJsvuon6SMCZtfO7vbhMLKnTcK4aTp5f99YyRzRbvk7tAYzGNJaU4yO93bQes1snRZueY2AR1hFFUzMFUYbYn2WmFquCJizpqFCLVIaFojMDTHS3PZQbcoDroL3YLSD7hDjgLtpYxWSGQSNu55jjOHaVDwDPyXo1Qy9ToVHLHliO66yp1Xop4wPSPKPAHpaacpmfRfaPw "Haskell – Try It Online")
] |
[Question]
[
# Challenge
Given a string describing a cutting rule and another string, cut parts out of the second string using the rule described by the first string.
Both strings will consist of letters `a-z` or `A-Z`, whichever one you choose (they don't have to be represented the same way). The way the second string is to be modified is described below:
# Algorithm
Take the first string and imagine filling in the gaps between non-adjacent (increasing) letters with `=`; for example, `abcfg` => `abc==fg`. Then, line up the two strings and return all characters from the first string that aren't above an equal sign. For example, given `abcfg` and `qrstuvw` as inputs:
```
qrstuvw - Modify
abc==fg - Modifier
qrs--vw -> qrsvw
```
If the modifier is shorter after filling with equal signs, all trailing characters in the second string should be included. If the modifier is longer, the trailing characters are ignored.
The modifier isn't guaranteed to be sorted.
# Test Cases
```
abcfg, qrstuvw -> qrsvw
abqrs, qwertyuiopasdfghjklzxcvbnm -> qwjklzxcvbnm
za, qr -> qr
azazaz, qwertyuioplkjhgfdsazxcvbnmnbvcxzasdfghjklpoiuytrewq -> qmn
```
Reference Implementation (used to generate test cases) -> [TIO](https://tio.run/##ZY/bagMhFEWf41fsCgFtTSH0LZB@Rd9CHpwZzZhMHOMlc/n5qZY0FIog@@g6nHXcFNvefixLozQ0kwIV35FVjT0ofT/3xrKQrmw2rvwd6J7iFaz3DZs4NihhLGHLoXuPUWCCsXjw8rDdHfmRCzDOOd7yw2Z7JCuvYvL2OWH611tnlqLM6pRlFS9aMBojXrLYnnJChtZ0Cl8@qexbvLOysS5Fxt@D60xkVCCDK@eNzcU6CKwDNp/5pljjZ1fxuzPnyyKrWp8Ebj7EdB@IrHLK5aB8nJLpnQyNPrXnSzeP9b2yVzLLQhM5l/OX7C7n9qSbIB@kre71OD/7XW/SFL0abt8)
# Rules
* Standard Loopholes Apply
* You may take input as two strings, two lists of characters, a matrix of characters, etc. (any other reasonable format is acceptable)
* You may output as a string or a list of characters (or some other standard format for strings)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes in each language is declared the winner for its language. No answer will be accepted.
* Either string may be empty.
Happy Golfing!
*Inspired by Kevin Cruijssen's recent two challenges, "There, I fixed it (with [tape](https://codegolf.stackexchange.com/q/157240/41024)/[rope](https://codegolf.stackexchange.com/q/157600/41024))"*
[Answer]
# JavaScript (ES6), ~~81~~ 80 bytes
Takes input in currying syntax `(modify)(modifier)`.
```
s=>g=([c,...a],d=i=0,x=s[k=parseInt(c,36),i+=c?d&&(k-d+26)%26:1])=>x?x+g(a,k):''
```
[Try it online!](https://tio.run/##dY69boMwAIT3PgVLY1sY0iYSQySTOc8QZTD@i4HYxAab8PIkaasWtapuvLvvrqaBeuZ012fGcjFLMntSKgKPDOd5Tk@YE03e8Ej8sSEddV4cTA8Z3hYI65SwPV@tYJPxdFOg102xez8hUo77MVWQ4gbtAJiZNd62Im@tghKCq/P9ECJAENCKSQUQStbrJCuThxPiy@94FK6/Ddp21HOpznXTTiMLlbl8Eh6lBSH@2H9A7lmY6HLv/7G2qc9Kck@/aKYKbJy@L3RWD7feiXj9eDE9tQBfzHwH "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // outer function, taking the string s to modify
g = ( // recursive inner function g(), taking:
[c, ...a], // c = current modifier character; a[] = remaining characters
d = i = 0, // d = code of previous modifier character; i = pointer in s
x = s[ // x = i-th character of s
k = parseInt(c, 36), // k = code of the current modifier character in [10..35]
i += c ? // update i; if c is defined:
d && // if d = 0, let i unchanged
(k - d + 26) % 26 // otherwise, add the difference between k and d (mod 26)
: // else:
1 // just pick the next character by adding 1
] // end of character lookup in s
) => //
x ? // if x is defined:
x + g(a, k) // append x and do a recursive call to g()
: // else:
'' // stop recursion
```
[Answer]
# [Python 3](https://docs.python.org/3/), 99 bytes
```
lambda a,b:[x for x,y in zip(a,''.join(d+(ord(c)+~ord(d))%26*'='for c,d in zip(b[1:],b))+a)if'='<y]
```
[Try it online!](https://tio.run/##ZY/NboMwEITvPMVeKtvFqpRW6gGFJ6Ec1hiDCbEdY34PeXWK0zaXag8rzc432nFraK352FX@tfd4FRIBuciKBZT1sPAVtIFNO4qckLfOakNlSq2XtGLpPW7J2Mv75yvJSSQqLv8IUZyykgvGUmRaHffzWu6hHsIAORQJACU3P4RxmgknKCrVEMZ/5Ln2YR21dThI1bTdpd@WahLmSjgc1gN7WjFKG/5H@0vXNkoO@IsaMVXL9gx0Vo9r8PV8e2RucQhLyiSJNZCDiD0e72ZHsvPaBKpoPDC2fwM "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 17 bytes
```
ćsv¹Ç¥Nè<yú«}SðÊÏ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//SHtx2aGdh9sPLfU7vMKm8vCuQ6trgw9vONx1uP///8QqEOQqLE8tKqkszcwvyMnOykhPSylOrKpILkvKy83LTyQAKvABAA "05AB1E – Try It Online")
---
Calculates the ASCII distance between each char, prepending that many spaces if it's positive. Negative distance results in appending 0 spaces, as per the spec. After that, I push all characters at the same indices in string 2 as the spaces in the first manipulated string.
---
```
Input: [azaz,qwertyuiopasdfghjklzxcvbnm]
--------------------------------------------------------------------------------
ćs # Remove head, swap | [a, zaz]
v # Iterate... | ............
¹Ç¥ # Push deltas between each char of string 1 | [a,[25,-25,25,-25]]
Nè # Push delta at index... | [a, 25]
< # Decrement (for 1-indexed answer) | [a, 24]
y # Push current char in iteration... | [a, 24, z]
ú # Append b spaces to a... | [a, '(spaces)z']
« # Concat | [a(spaces)z]
} # End loop. | [a(spaces)za(spaces)z]
SðÊ # Split, push 1 for non-space elements. | [Long array of 1/0]
Ï # Push chars from 2 that aren't spaces in 1. | ['qmn']
```
---
90% sure I can lose another 2-3 bytes by not using spaces, but pushing the char at index N. Still working on this variant at the moment... What my "better idea" ended up as:
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
Ç¥ε1‚Z}ηO0¸ìʒ²g‹}è
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cPuhpee2Gj5qmBVVe267v8GhHYfXnJp0aFP6o4adtYdX/P@fWIUMuQrLU4tKKksz8wtysrMy0tNSihOrKpLLkvJy8/ITkQAA "05AB1E – Try It Online")
I feel like I'm missing something, if you see improvements on `ε1‚Z}`, `ʒ²g‹}` or `0¸ì` lmk...
`Ç¥ε1‚Z}ηO0¸ìè` was 13, but it wraps when `n > |input_2|` to `input_2[n%|input_2|]`...
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç«|¢Äα•è@╟╣i`vF
```
[Run and debug it](https://staxlang.xyz/#p=80ae7c9b8ee0078a40c7b969607646&i=%22qrstuvw%22+%22abcfg%22%0A%22qwertyuiopasdfghjklzxcvbnm%22+%22abqrs%22%0A%22qr%22+%22za%22%0A%22qwertyuioplkjhgfdsazxcvbnmnbvcxzasdfghjklpoiuytrewq%22+%22azazaz%22%0A&a=1&m=2)
This is the ascii representation.
```
:-Z+{v0|Mt|cB]pFp
```
1. Get pairwise differences.
2. Prepend a zero.
3. Foreach difference, repeat
4. Subtract 1, and take maximum with zero.
5. Remove that many characters from the beginning of string.
6. Stop if the string is empty.
4. Print the rest of the string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
OI’R¬⁸żFḣL}aḟ0
```
A dyadic link accepting the modifier as a list of characters on the left and the list of characters to modify on the right returning a lists of characters.
**[Try it online!](https://tio.run/##y0rNyan8/9/f81HDzKBDax417ji6x@3hjsU@tYkPd8w3@P//f2IVCP4vLE8tKqkszcwvyMnOykhPSylOrKpILkvKy81LKkuuqEosTklLz8jKzinIzyytLClKLS8EAA "Jelly – Try It Online")**
### How?
```
OI’R¬⁸żFḣL}aḟ0 - Link list of characters Modifier, list of characters InStr
- e.g. ['a','c','g','a'], ['n','m','l','k','j']
O - ordinals of Modifier [97,99,103,97]
I - incremental differences [2,4,-6]
’ - decrement [1,3,-7]
R - range [[1],[1,2,3],[]]
¬ - NOT (vectorises) [[0],[0,0,0],[]]
⁸ - chain's left argument, Modifier
ż - zip together [['a',[0]],['c',[0,0,0]],['g',[]],['a']]
F - flatten ['a',0,'c',0,0,0,'g','a']
L} - length of right (InStr) 5
ḣ - head to index ['a',0,'c',0,0] (if shorter or equal, no effect)
a - AND with InStr (vectorises) ['n',0,'l',0,0]
ḟ0 - filter out zeros ['n','l']
```
[Answer]
# JavaScript (ES6), 79 bytes
```
f=([t,...T],s,z=T[0])=>z&&s?s[0]+f(T,s.slice(t>z||(parseInt(t+z,36)-370)%37)):s
```
Uses the same algorithm for calculating distance between letters as my [last answer](https://codegolf.stackexchange.com/a/157405/42260).
**Test cases:**
```
f=([t,...T],s,z=T[0])=>z&&s?s[0]+f(T,s.slice(t>z||(parseInt(t+z,36)-370)%37)):s
console.log(f('abcfg','qrstuvw')) // -> qrsvw
console.log(f('abqrs','qwertyuiopasdfghjklzxcvbnm')) // -> qwjklzxcvbnm
console.log(f('za','qr')) // -> qr
console.log(f('azazaz','qwertyuioplkjhgfdsazxcvbnmnbvcxzasdfghjklpoiuytrewq')) // -> qmn
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~35~~ ~~34~~ 32 bytes
```
{⍵∩⍨⊃¨↓∘⍵¨+\0,1⌈(-2-/⎕ucs⍺),=⍨⍵}
```
[Try it online!](https://tio.run/##VYxNTsMwEIX3PUV3A6JRC0skbsLGcerUjRuntpM0QV2BqvAThISQWLMKB@iGZY8yFwnjtiCQJevTvPc@lqkgqpjSccAVs1byHp/fpMbNy6QX9N9gu8XmE9sOH253HW5esXmn2647u56MzvGpOQkugjGNcm6x/TodXfluu133vfvZ338YQhKIMVUuIxBMKiCk0ODjHegE1gNgIRcxDGFprMuLEoZuz0Q@I/JZOTWuyqXOmI1EPJsnql7xIkwXh3r55zCAmu11R5PX1P7986hkPotFZNlxloYFX9W/9kzLvHJmWi4PlkUK3w "APL (Dyalog Classic) – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~27~~ ~~24~~ 25 bytes
```
{y[+\0,1|1_-':x,!#y]^" "}
```
[Try it online!](https://tio.run/##VY3JDoIwFEX3fgVWEyGCkS39DXaIUoYyFyhTC@KvI5NG8zb35uacFyvEJ@OItZ4b59tVVp/qQzlpTN4fuHkHAhhGXeuPBn9RDQsXgUEri6FoYRQmkEEOqWQOO90QAbId7AMIClpWddMCaYlTMLd5avPcerTidZjlqHSxH0Rx0jGnsUm6EO1PX8EOLdLV95F18/3ZkjgKfOyWaKOJ3Tis@/7Is7DmFfXaYhGlBJjjGw "K (ngn/k) – Try It Online")
```
{y[+\0,1|1_-':x,!#y]^" "}
{ } function with x and y as arguments
#y the length of y
!#y 0 1 2 ... (#y)-1
x, x concatenated with
-': differences between pairs
1_ rm extra leading item
1| max between 1 and
0, prepend 0
+\ partial sums
y[ ] index y with that
^" " rm spaces due to out-of-bounds indexing
```
[Answer]
# [Haskell](https://www.haskell.org/), 49 bytes
```
(x:r)#(y:n:s)=x:drop(length[y..n]-2)r#(n:s)
r#_=r
```
[Try it online!](https://tio.run/##TYvNCoMwEITvPsWCPUSoHnoU7Iu0UjYaNRpX3cTfl7daSilz@Zj5pkLbKGP2XSwxB75YY4ptkCxxzl0vjKLSVY81iigNbwH74lw99l8J7y1qggQ0OcWYObjASEaTshBBiz0I8XzgVabhXfoYHOXccW5P@Fg7yqwoYWDrxmn2UB4Ew6zYraPuerR5UVZ1Y7YlmyS13oaH6@F25s8zTV2VRW7x65GcsmX7vftOj6tjNQ9v "Haskell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 45 bytes
```
s/./v0.$;x(ord($')-1-ord$&)/eg;$_|=<>;s/\W//g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX0@/zEBPxbpCI78oRUNFXVPXUBfIUlHT1E9Nt1aJr7G1sbMu1o8J19dP//8/MSk5LZ2rsKi4pLSs/F9@QUlmfl7xf92cgv@6vqZ6hgZ6hgA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~68~~ 64 bytes
```
->m,z,i=1{z[i,[0,m[i].ord+~m[i-1].ord].max]&&='';m[i+=1]?redo:z}
```
[Try it online!](https://tio.run/##VZDNcoMgFEb3PgXDIlmEOHXbju2DOCxQQDEBDOIfSfrqlih02mEGznfhHgbMUC4rz9fzp0QOiTy7u0Kg4g3JQuBUG3r69nTONsapJDM@HPLj8cNXT3mGvwyj@t09126wPYBSU8EFMzDZc2@NUHVMtbYR2dyxyjIKkyIBoICkrHgNEYA309thnAJ6wCgc8HGrTszYZRC6Iz3lddNerm6uxlLJffdPDq2O7LYwR6F7jf/G66Vtak57EgyqHKvZ/d7TaTEs1rDptrVJBXGCU0aqBlANHgK1SD@8/PXEsAARoY3A/Qe3OCadMEXXHw "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 28 bytes
```
⭆η×ιI§⁺⭆θ⁺×0∧μ⊖⁻℅λ℅§θ⊖μ1⭆η1κ
```
[Try it online!](https://tio.run/##VY7NCsIwEITvPsWS0xZW0LOnohcPxYK@QExiG0yi@Wn17WNtLdi9zDJ8M4xoeRAPbnKug3YJz2mQpuJPbAku2qqImmDPY8IyHZ1Ub6xNF/84TzA6E8w2jKB0Ei3BQYmgrHJJSay0G5hTkNpxg6YgmP@51i8DtpiOgG3ZVxbLft59RHY586u4NSsfYur6V1735gM "Charcoal – Try It Online") Link is to verbose version of code. Based on my answer to There, I fixed it with tape. Explanation:
```
⭆θ⁺×0∧μ⊖⁻℅λ℅§θ⊖μ1 Fix it with tape, but map to 1s and 0s
⁺ ⭆η1 Append extra 1s just in case
⭆η Map over the second string
§ κ Get the character from the fixed string
I Cast to integer
×ι Repeat the current character that many times
Implicitly print
```
~~Note: This should be 28 bytes, but `And` is broken at time of writing.~~
[Answer]
# Java 8, 117 bytes
```
a->b->{for(int i=0,j;++i<a.length;b=j>0&b.length()>=i+j?b.substring(0,i)+b.substring(i+j):b)j=a[i]+~a[i-1];return b;}
```
**Explanation:**
[Try it online.](https://tio.run/##jZA7b8IwFIV3foXFUMVKYtG1IamqSt06MaIM1yYPG@MEPwIJon89NSWtutAiS9e@vkfH37GADuKmLZTYbEcmwRj0DlydZggZC5YzJLyCOMslKZ1iljeKvE2HJatBr/PoT83Kaq6qCF33LEMMpWiEOKNxdiobHXBlEU8XkUjCkC@ByEJVtk5oKrLFA53aAGcpD8UzJcZR82UVLCKOw98XXoCfKBYprHkefvgaP@aJLqzTCtHkPCYzn6t1VPpcU7yu4Ru085GDK@A6R4Av8RFa9cYWO9I4S1o/slIFjEDbyj6YA2VlNSe2efVf8KI19AHG38O9NtZ1hznGyR1GXn3T6FBo2zvetGA2ZVWLrRyOrKNqd5f3ALcJ74MbLut/OrkVdVVuDEx0inbsOPwwtw13vdXFYT@9ep6dx08)
```
a->b->{ // Method with char-array + String parameters and String return
for(int i=0,j;++i<a.length;
// Loop `i` in range [1; length_of_array)
b= // After every iteration: change the String-input to:
j>0 // If `j` is larger than 0,
&b.length()>=i+j? // and the length of `b` is larger or equal to `i+j`:
b.substring(0,i) // Take the substring [0; i)
+b.substring(i+j)// + the substring [i+j; end_of_string]
: // Else:
b) // Leave `b` the same
j=a[i]+~a[i-1]; // Set `j` to the difference between two adjacent chars - 1
return b;} // Return the modified input-String
```
] |
[Question]
[
Given two lists of dice rolls for a battle in Risk, your program or function must output how many troops each player loses.
## Background
You do not have to read this, for it is merely background. Skip to "Task" subheading to continue unabated.
In the game of [Risk](https://en.wikipedia.org/wiki/Risk_(game)), one player can attack another player (in fact, this is necessary to win). The outcome of a battle is determined by the roll of dice. Every battle occurs as a succession of sub-battles in which each player can lose up to `2` of their army pieces.
In a sub-battle, the defender and attacker each roll several dice whose number may vary based on circumstances irrelevant to this challenge. The highest-valued die of the attacker is compared to the highest-valued die of the defender. If the attacker's die is higher than the defender's die, the defender loses one piece. Otherwise, the attacker loses one piece.
Then, if both players have at least two dice, the second-highest valued dice of the two players are compared. Again, if the attacker's die is higher than the defender's die, the defender loses one piece. Otherwise, the attacker loses one piece.
(Defender wins ties. If both defender and attacker roll a `4`, then the attacker loses a piece.)
[](https://i.stack.imgur.com/YdCicm.png)
In this sub-battle from the Wikipedia article, the attacker's dice are red and the defender's dice are white. The highest of the attacker's dice is `4` and the highest of the defender's is `3`. Since the attacker was higher, the defender loses a piece. The second-highest are `3` for the attacker and `2` for the defender. Since the attacker was again higher, the defender loses another piece. Thus in this sub-battle, the attacker loses no pieces and the defender loses `2` pieces.
Note that the third-highest pieces are not compared. This is because the defender has no more than two dice on a single sub-battle, so there are no third-highest pieces to compare ever.
## Task
Given the unsorted dice rolls (integers in the range 1 to 6 inclusive) of both the attacker and the defender of a sub-battle of Risk in any convenient form, output the number of army pieces each player loses. The output may be in any convenient form, as long as it has different outputs to indicate the five possibilities. You must indicate what those different outputs are in your question.
The output is determined as follows: Start with `def=0` and `atk=0`. If the greatest value of the list of dice rolls of the attacker is greater than the greatest value of the list of dice rolls of the defender, then increment `def`. Otherwise, increment `atk`.
If both lists of dice rolls have length at least `2`, then: if the second-greatest value of the list of dice rolls of the attacker is greater than the second-greatest value of the list, then increment `def` and otherwise increment `atk`.
Finally, the program or function must output a unique identifier for each of the following 5 output possibilities:
```
╔═══╦═══╗
║atk║def║
╠═══╬═══╣
║ 1 ║ 0 ║
║ 0 ║ 1 ║
║ 2 ║ 0 ║
║ 1 ║ 1 ║
║ 0 ║ 2 ║
╚═══╩═══╝
```
## Example
Defender: `[3, 2]`
Attacker: `[2, 4, 1]`
Max of defender is `3` and max of attacker is `4`. `4>3`, so `def=1`
Second of defender is `2` and second of attacker is `2`. `Not(2>2)`, so `atk=1`. The output could then be `[1,1]`.
## Test Cases
```
Defender
Attacker
Output (as [def,atk])
-----
[1]
[1]
[0,1]
-----
[6,6]
[1,1,1]
[0,2]
-----
[1,2]
[5,2,3]
[2,0]
-----
[5]
[3,4]
[0,1]
-----
[4]
[4,5]
[1,0]
-----
[1,3]
[1,2,3]
[1,1]
-----
[4]
[4,5,6]
[1,0]
-----
[4,5]
[6,2]
[1,1]
-----
[5]
[6,1,3]
[1,0]
-----
[5,5]
[4,4,1]
[0,2]
-----
[2,5]
[2,2]
[0,2]
-----
[6,6]
[4,4,3]
[0,2]
-----
[2,1]
[4,3]
[2,0]
-----
[4]
[1,5]
[1,0]
-----
[1]
[5,2]
[1,0]
-----
[6,2]
[4]
[0,1]
-----
[4,2]
[2,5,5]
[2,0]
-----
[2]
[6,6,2]
[1,0]
-----
[6]
[2,6]
[0,1]
-----
[3,1]
[1]
[0,1]
-----
[6,2]
[3,5,2]
[1,1]
-----
[4,2]
[1,1]
[0,2]
-----
[4,3]
[5,4,1]
[2,0]
-----
[5,6]
[1,2]
[0,2]
-----
[3,2]
[4,4]
[2,0]
-----
[2]
[6,3,4]
[1,0]
-----
[1,4]
[6,2,4]
[2,0]
-----
[4,2]
[2,5,4]
[2,0]
-----
[5]
[6,2,1]
[1,0]
-----
[3]
[2,5,4]
[1,0]
-----
[5,4]
[2]
[0,1]
-----
[6,3]
[2,6,5]
[1,1]
-----
[3,1]
[4]
[1,0]
-----
[4]
[6,6,5]
[1,0]
-----
[6,3]
[4,2]
[0,2]
-----
[1,6]
[5,4]
[1,1]
-----
[3,6]
[4,4]
[1,1]
-----
[5,4]
[5,1,1]
[0,2]
-----
[6,3]
[5,4]
[1,1]
-----
[2,6]
[1,2]
[0,2]
-----
[4,2]
[3,5,5]
[2,0]
-----
[1]
[1,2,1]
[1,0]
-----
[4,5]
[1,6]
[1,1]
-----
[1]
[3,5,1]
[1,0]
-----
[6,2]
[6,2]
[0,2]
```
## Sample implementation
Python 2 or 3
```
def risk(atk_rolls,def_rolls):
# set the rolls in descending order, e.g. [5,3,2]
atk_rolls = sorted(atk_rolls,reverse = True)
def_rolls = sorted(def_rolls,reverse = True)
# minimum length.
minlen = min(len(atk_rolls),len(def_rolls))
atk_lost = 0
def_lost = 0
# compare the highest-valued rolls
if atk_rolls[0]>def_rolls[0]:
def_lost += 1
else:
atk_lost += 1
if minlen == 2:
# compare the second-highest-valued rolls
if atk_rolls[1] > def_rolls[1]:
def_lost += 1
else:
atk_lost += 1
return [def_lost, atk_lost]
```
## Specifications
* The input may be taken as any form that clearly encodes **only** the defender's rolls and the attacker's rolls.
* The output may be in any form that provides a unique output for each of the five possibilities listed above.
* The defender's rolls are a list of `1` or `2` integers in the set `[1,2,3,4,5,6]`. The attacker's rolls are a list of `1` to `3` integers in the set `[1,2,3,4,5,6]`.
* Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code **in each language** wins! Do **not** let answers in golfing languages discourage you from posting answers in other languages.
[Answer]
# NAND gates, 237
[](https://i.stack.imgur.com/s0DbK.png)
Created with [Logisim](http://www.cburch.com/logisim/)
Inputs are 3-bit unsigned binary, entered on the left. Outputs (2 bits) are on the right.
It is too large to fit on the screen and Logisim can't zoom, so the image is black-and-white. Sorry :(
Works for all test cases.
There is likely a better way to do this using some memory circuit, allowing large sections to be reused.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
NṢ€>/Ṡḟ-o-S
```
A monadic link taking a list of `Defender, Attacker` rolls (each as lists), returning an integer between `-2` and `2` inclusive (defender losses - attacker losses):
```
result : [def, atk]
-2 : [ 0, 2]
-1 : [ 0, 1]
0 : [ 1, 1]
1 : [ 1, 0]
2 : [ 2, 0]
```
**[Try it online!](https://tio.run/##ASoA1f9qZWxsef//TuG5ouKCrD4v4bmg4bifLW8tU////1sxLDJdLFs1LDIsM10 "Jelly – Try It Online")** or see a [test suite](https://tio.run/##XVG7TsRADOzvK@4DHHHe3WyDdCUlDeUqxRU06CRqugMhpaCjogCBqBEtRJQREr@x@ZHg@JEsNN61xh6Pxxfn@/3VOJ7m7nW4edse5e4lfz5Xl9XZ2Lf56y4hbBpIjuMGHEekiBRXfft9n7uH3N2u@HM8HB7X1XY9HJ5@3nd9SwXEuhuuP06IlZ5xTClxe0MhRYhCBZIjD6jBgee8puAh8D9QCFBrnec@q1OM2DiDqS8Sl3FEQGNkLEDQiY5zp7WiZ0K9osj5MgVNgejUrkm1quQ/sWqd4@mmJTImKj2UPjje1BiFxVwJvG09a67VNac8TjQX88wzhCBOwH91ofDGKa//i3GvbShY1K1E@3KXOCNSGVQbslJj9OZuwV/Pt4@2pTpf7hhmfxb3cdYt90b1FbWydJb9b34B "Jelly – Try It Online") (which maps the results to the OP format).
### How?
```
NṢ€>/Ṡḟ-o-S - Link: list [list Def, list Atk]
N - negate all the rolls
Ṣ€ - sort €ach of the lists of -1*rolls (max rolls are to the left now)
/ - reduce by:
> - is greater than? (when len(Atk) > len(Def) leaves trailing negatives)
Ṡ - sign (maps all negatives to -1; zeros and ones of comparison unchanged)
- - literal -1
ḟ - filter discard (remove the -1s)
- - literal -1
o - logical or, vectorises (replaces the zeros with minus ones)
S - sum
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
M#eI¬¤z>Ö>
```
[Try it online!](https://tio.run/##yygtzv7/31c51fPQmkNLquwOT7P7//9/tImOcez/aFMdEx3DWAA "Husk – Try It Online")
Input as two separate lists of rolls, output as in the op.
### Explanation
`¤z>Ö>` sorts each list in descending order and then zips them comparing corresponding elements (and truncating the longer list).
`M#eI¬` creates a 2-element list (`e`) with counts (`#`) of truthy values (through identity `I`) and falsy values (through logical negation `¬`)
[Answer]
# [Retina](https://github.com/m-ender/retina), 82 bytes
```
%O^`.
((.)+).*(¶(?<-2>.)+)(?(2)(?!)).*
$1$3
O$`.
$.%`
\d
$*1D
(1+)D1*\1
1+D
A
O`.
```
[Try it online!](https://tio.run/##K0otycxL/P9f1T8uQY9LQ0NPU1tTT0vj0DYNextdIzsQV8NewwhIKGoCJbhUDFWMufxVgGpV9FQTuGJSuFS0DF24NAy1NV0MtWIMubgMtV24HLn8E/T@/zcyNuEyNAMA "Retina – Try It Online") First line of input is attacker's dice, second is defender's dice. Returns (on separate lines) `AA`, `AD`, `DD`, `A` or `D` as appropriate.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ 75 bytes
```
x=0
k=map(sorted,input())
while all(k):x+=cmp(*map(list.pop,k))or 1
print-x
```
[Try it online!](https://tio.run/##VVHLboMwELz7K7gB7baqn4dI/EVvUQ8RQQqCgEWISr@e2rMGWiGj3fXs7Mza/8y3cVBrPV6bKs/zdak@RFfdL754jNPcXKkd/HMuylJ839q@yS59X3TlaXmt6rsvXiKwbx/zux89dWU5TpkUfmqH@W1ZA1/q@pyezUlkWbM0dRZnrWf5ReGIsyMXIwpfyCSpkFlSpENmQ6zJhMiEyJAFQgPPiFQPHAL3FPhU6nQkmQV1QwYTFDIFFM@ONxo3EtnGK3ke6wE6aoMaRIEJCIVZPNehHtVoOhwq@GAW7mW3Bl5sUmbTJhS6FSvb@XkPkgx7pP86zO5ZgUv/raOHHXDdQTcr3LbrUpUxBiokFDGL3na1M9r0Zm5zgR0eHszue9ujTOr4pST2JBPm2FT8/wI "Python 2 – Try It Online")
Output is defender losses - attacker losses
[Answer]
# [MATL](https://github.com/lmendo/MATL), 23 bytes
```
oH2$S1&Y)Y&t1M>t~b,Y&sD
```
[Try it online!](https://tio.run/##y00syfn/P9/DSCXYUC1SM1KtxNDXrqQuSSdSrdjl///qaDMdIx2jWOtoUx3j2FoA "MATL – Try It Online")
Not sure why defenders are allowed more dice than attackers, but maybe I am not that well versed in Risk. The core program is just `>t~,sD`, all the other bytes are there to allow for different input lengths, with a bit of sorting thrown in. Input is attacker followed by defender, output is attacker losses followed by defender losses.
```
o % Convert input to numeric array, padding with zeroes
H2$S % Sort row-wise (specified to prevent 1v1 sorting)
1&Y) % Split attacker/defender
Y&t % Logical and to filter out excess dice. Duplicate for 'do twice' later.
1M> % Get throws again, decide who won
t~ % And the inverse to decide who lost
b, % Bubble filter to the top. Do twice:
Y& % Apply filter
sD % Sum of losses. Display.
```
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 97 83 78 bytes
```
d=>a=>{for(u=v=0;d.sort()>[]&a.sort()>[];)a.pop()>d.pop()?u++:v++
return[u,v]}
```
[Try it online!](https://tio.run/##fc/fCoIwFAbwe5/Cq3DspM5/F8nsQcSLoRaVOTnTQUTPbmpgkiGD7TB@fB/nKrRQOV6adq@aS1HiXda38tFrgSaavC94InjyPEm0Oq65Gxe2kthaJEmznfjOMRF2I5thLj7vsaP0oCk1sGw7rNMOdPbqc1krWZV2Jc8WWinLyHSR2HQcM3WBZcYPiSCaEAxnAb0VZMPfAEPwwJ@hB@4KhiPzIdisDUYUQDgj9ieJjU1T86KSbaSNuyzy@jc "JavaScript (SpiderMonkey) – Try It Online")
-4 bytes and fixed thanks to @ovs and @Craig Ayre
-1 byte thanks to @Shaggy
[Answer]
# [Perl 5](https://www.perl.org/), 66 + 1 (-a) = 67 bytes
```
@A=sort split/ /,<>;$b+=@A?pop@A>$_?-1:1:0for reverse sort@F;say$b
```
[Try it online!](https://tio.run/##FcuxCsIwEADQ3a84SjaNTSpdGtMmi5t/IEgLEQIld1yC4M974tsfJd5HkRB9RW5Qac@th/50nZ3ajj7EhZBCnNVz0Xayk3khA6d34prgX8LN1fWjNnHEubTuUTqn2BsnA1wOA9gvUstYquj7eDbWiF5/ "Perl 5 – Try It Online")
**Input:**
Two lines. First line is defender (player 1), second is attacker (player 2). Individual rolls separated by spaces.
**Output:**
Indicates effective change in defender's strength vs. attacker.
```
Output Attacker Defender
2 0 2 Defender wins both
1 0 1 Defender wins the only roll
0 1 1 Attacker wins first, defender wins second
-1 1 0 Attacker wins the only roll
-2 2 0 Attacker wins both rolls
```
[Answer]
# [R](https://www.r-project.org/), 46 bytes
```
function(x,y)s(s(y,T)[1:2]>s(x,T)[1:2])
s=sort
```
[Try it online!](https://tio.run/##XY8xC4MwEIV3f4XgksANXmIcBAuF7l26iYOogSJoMRHqr09zTYrSKXfvu/dytzpdO73NvX0uM3vDzg0zbIcHb7AS7cV4LdY8MbVZVuuy26jHeRjXJLta2/UTVffNvjabss6kzTBq6OzkHZohIM@aHLD1Tc9KKDn0pHr9C0QACIKAAgGSgICcgAJZFUdAAUWlfIuBkk2GvGjDY6485rwJ6G9xGgkK/mwxT4GiPO//208EQM9ZjvfQvDwBUaHfQMY73Ac "R – Try It Online")
All this does is three sorts and one comparison... plus extracting the first two elements in the middle.
Input is two vectors of dice rolls.
Output encoded as follows:
```
╔═══╦═══╗
║atk║def║
╠═══╬═══╣
║ 1 ║ 0 ║ TRUE
║ 0 ║ 1 ║ FALSE
║ 2 ║ 0 ║ TRUE TRUE
║ 1 ║ 1 ║ FALSE TRUE
║ 0 ║ 2 ║ FALSE FALSE
╚═══╩═══╝
```
Works because extraction in R does not recycle its argument, but pads the result with `NA` to get to the requested length.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
0,0‘⁸Ṁ€</¤¦‘⁸ḟ"Ṁ€⁺</¤¦⁸L€Ṃ>1¤¡
```
[Try it online!](https://tio.run/##y0rNyan8/99Ax@BRw4xHjTse7mx41LTGRv/QkkPLoCI75itBRB817oJKNO7wAfIf7myyMwTyF/7//z862lBHwThWRwFEG4GYsQA "Jelly – Try It Online")
*Veeeeeeeery* ungolfed! >\_<
Outputs values exactly as in test cases.
] |
[Question]
[
Given an input number `n` from `1` to `26` (or `0` to `25`), output the alphabet reading left-to-right up to and including that corresponding letter, with `a=1, b=2, c=3, ...`. The twist is the letters must also be repeated vertically corresponding to their position in the alphabet. Odd numbers (when `1`-indexed) should be balanced across the horizontal line, while even numbers should alternate between favoring the top or bottom (you can choose which direction to go first). If you're 0-indexing, then swap odd/even in the previous sentence.
Worded another way -- if the alphabetical value of a letter `?` is `#`, then there should be `#` copies of that letter in the output, all of them in the `#`th column. These letters should be evenly balanced above and below the horizontal line that has the `a`. If the letters cannot be balanced evenly, then alternate having the "extra" letter above and below that line.
Here are the first six outputs (`n = 1,2,3,4,5,6`, 1-indexed, choosing to alternate to the bottom first), separated by newlines, so you can see the pattern. Comments explaining the pattern start with `#`.
```
a # On a line by itself
ab
b # The "extra" letter is below the horizontal
c
abc # The 'c' splits evenly
bc
d # Because the 'b' was below, the extra 'd' must be above
cd
abcd
bcd
de
cde
abcde # The 'e' balances
bcde
e
def
cdef
abcdef
bcdef
ef
f # Since the 'd' was above, the extra 'f' must be below
```
(skip a few to `n=26`)
```
xyz
wxyz
tuvwxyz
stuvwxyz
pqrstuvwxyz
opqrstuvwxyz
lmnopqrstuvwxyz
klmnopqrstuvwxyz
hijklmnopqrstuvwxyz
ghijklmnopqrstuvwxyz
defghijklmnopqrstuvwxyz
cdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
efghijklmnopqrstuvwxyz
fghijklmnopqrstuvwxyz
ijklmnopqrstuvwxyz
jklmnopqrstuvwxyz
mnopqrstuvwxyz
nopqrstuvwxyz
qrstuvwxyz
rstuvwxyz
uvwxyz
vwxyz
yz
z
```
### Rules
* You can choose to output in uppercase or lowercase, but it must be consistent.
* The output cannot have extraneous whitespace, except for an optional trailing newline.
* Either a full program or a function are acceptable.
* The input number can be taken via [any suitable format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# Python 2, ~~101~~ 99 bytes
```
r=range(input())
for x in sorted(r,key=lambda x:x*-(x&2)):print bytearray([97+i,32][i<x]for i in r)
```
xsot saved two bytes by realizing `x*-(x&2)` suffices as a sorting key — the bottom half of the resulting image is unaffected due to `sorted` guaranteeing a stable sort.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 26 bytes
A perfect score for a challenge about alphabet.
```
j_C.e<u_G/k2.[.|1Q*hkbdQ<G
```
[Try it online!](http://pyth.herokuapp.com/?code=j_C.e%3Cu_G%2Fk2.%5B.%7C1Q%2ahkbdQ%3CG&test_suite=1&test_suite_input=5%0A26&debug=0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḷ&2’×ḶỤØaḣ⁸¤ṫW€UGU
```
Port of my Python answer. [Try it online.](http://jelly.tryitonline.net/#code=JjLigJnDlwrhuLbDh8Oe4oCYw5hh4bijwrPCpOG5q1figqxVR1U&input=&args=MTk)
EDIT: Dennis saved two bytes by using `Ụ` (grade up) instead of `Þ` (sort by)!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
RØaxŒgz⁶W€;ṚL‘$¡¥/Ṛ⁸H¤¡j⁷
```
[Try it online!](http://jelly.tryitonline.net/#code=UsOYYXjFkmd64oG2V-KCrDvhuZpM4oCYJMKhwqUv4bma4oG4SMKkwqFq4oG3&input=&args=MjY) or [verify all test cases](http://jelly.tryitonline.net/#code=UsOYYXjFkmd64oG2V-KCrDvhuZpM4oCYJMKhwqUv4bma4oG4SMKkwqFq4oG3CsOH4oKsauKAnMK2wrY&input=&args=MSwgMiwgMywgNCwgNSwgNiwgMjY).
[Answer]
## JavaScript (ES6), ~~127~~ 126 bytes
```
n=>[...Array(n).keys()].sort((a,b)=>a*~-(a&2)-b*~-(b&2)).map(i=>` `.repeat(i)+`abcdefghijklmnopqrstuvwxyz`.slice(i,n)).join`\n`
```
Uses @Lynn's sort trick. Writing out the whole alphabet was two bytes cheaper than calculating it. Edit: Saved 1 byte thanks to @ETHproductions because I forgot to note that `\n` actually represents the literal newline character. (I don't like putting literal newlines in my answer when the line is so long.)
] |
[Question]
[
### Introduction
A [pentagonal number](https://en.wikipedia.org/wiki/Pentagonal_number) ([A000326](https://oeis.org/A000326)) is generated by the formula **Pn= 0.5×(3n2-n)**. Or you can just count the amount of dots used:
[](https://i.stack.imgur.com/XaINR.gif)
You can use the formula, or the gif above to find the first few pentagonal numbers:
```
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, 176, 210, 247, 287, 330, 376, 425, 477, etc...
```
Next, we need to compute the sum of **x** consecutive numbers.
For example, if **x = 4**, we need to look at Pn + Pn+1 + Pn+2 + Pn+3 (which consists of **4** terms). If the sum of the pentagonal numbers also is a pentagonal number, we will call this a ***pentagonal pentagon number***.
For **x = 4**, the smallest pentagonal pentagon number is `330`, which is made of **4** consecutive pentagonal numbers: `51, 70, 92, 117`. So, when the input is `4`, your program of function should output `330`.
---
### Task
* When given an integer greater than 1, output the smallest pentagonal pentagon number.
* You may provide a function or a program.
* **Note:** There are no solutions for e.g. **x = 3**. This means that if a number **cannot be made** from the first 10000 pentagonal numbers, you must stop computing and output whatever fits best for you.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
---
### Test cases:
```
Input: 2
Output: 1926 (which comes from 925, 1001)
Input: 3
Output: ?
Input: 4
Output: 330 (which comes from 51, 70, 92, 117)
Input: 5
Output: 44290 (which comes from 8400, 8626, 8855, 9087, 9322)
Input: 6
Output: 651 (which comes from 51, 70, 92, 117, 145, 176)
Input: 7
Output: 287 (which comes from 5, 12, 22, 35, 51, 70, 92)
Input: 8
Output: ?
Input: 9
Output: 12105 (which comes from 1001, 1080, 1162, 1247, 1335, 1426, 1520, 1617, 1717)
Input: 10
Output: ?
```
Also bigger numbers can be given:
```
Input: 37
Output: 32782
Input: 55
Output: 71349465
Input: 71
Output: 24565290
```
[Answer]
## CJam, 29 bytes
```
6e5{)_3*(*2/}%_A4#<riew::+&1<
```
[Try it online.](http://cjam.tryitonline.net/#code=NmU1eylfMyooKjIvfSVfQTQjPHJpZXc6OismMTw&input=NzE)
Takes a couple of seconds to run.
### Explanation
First, we need to check how many pentagonal numbers we need to consider as potential sums. The sum of the first 10,000 pentagonal numbers is `500050000000`. The first pentagonal number greater than that is the 577,380th.
```
6e5 e# 600,000 (a short number that's a bit bigger than we need).
{ e# Map this block onto every number from 0 to 599,999...
) e# Increment.
_3*(*2/ e# Apply the pentagonal number formula given in the challenge.
}%
_ e# Make a copy.
A4#< e# Truncate to the first 10,000 elements.
ri e# Read input and convert to integer.
ew e# Get sublists of that length.
::+ e# Sum each sublist.
& e# Set intersection with all 600k pentagonal numbers computed earlier.
1< e# Truncate to the first result.
```
I used a slightly modified program to find the largest inputs which yield a non-empty solution. These are all the solutions for inputs greater than 9,000:
```
9919 -> 496458299155
9577 -> 446991927537
9499 -> 455533474060
9241 -> 401702906276
9017 -> 429351677617
```
[Answer]
# Lua, 142 Bytes
```
p={}o={}n=...for i=1,10^4 do p[i]=(3*i^2-i)/2o[p[i]]=1 end for i=0,10^4-n do s=0 for j=1,n do s=s+p[i+j]end if(o[s])then print(s)break end end
```
**Ungolfed**
```
p={}o={}n=tonumber(...)
for i=1,10^4 do
p[i]=(3*i^2-i)/2o[p[i]]=1
end
for i=0,10^4-n do
s=0
for j=1,n do
s=s+p[i+j]
end
if(o[s])then
print(s)
break
end
end
```
Yay for inverting tables!
*Update 142 Bytes:* Saved 10 bytes by removing superfluous 'tonumber' function call.
[Answer]
## Haskell, 109 bytes
```
p=map(\n->div(3*n^2-n)2)[1..10^7]
(%)=(sum.).take
x#l|length l<x=0|elem(x%l)p=x%l|1<2=x#tail l
(#take(10^4)p)
```
Returns `0` if there's no pentagonal pentagon number.
Usage example (takes some time to finish): `map (#take(10^4)p) [1..10]` -> `[1,1926,0,330,44290,651,287,0,12105,0]`.
It's more or less a direct implementation of the definition: if the sum of the first `x` elements is in the list, output it, else re-try with the tail of the list. Start with the first 10,000 pentagonal numbers, stop and return `0` if the list has less than `x` elements.
[Answer]
# PARI/GP, 71 bytes
I like the `ispolygonal` function in PARI/GP.
```
x->[p|p<-vector(10^4,i,sum(n=i,i+x-1,(3*n^2-n)/2)),ispolygonal(p,5)][1]
```
[Answer]
# Python 3, 144 bytes
```
R,P=range,list(map(lambda n:(3*n*n-n)/2,R(1,10001)))
def F(X):
for a in R(0,len(P)-X):
S=sum(P[a:a+X])
if(1+(1+24*S)**.5)%6==0:print(S);break
```
This reverses the definition of a pentagonal number; if P(n) = (3n^2-n)/2, then a given P will be a pentagonal number iff (1+sqrt(24\*P+1))/6 is an integer. (Technically, it should also look at (1-sqrt(24\*P+1))/6, but that should always be negative.) Also uses spaces and tabs as two different indentation levels, as suggested [here](https://codegolf.stackexchange.com/a/58/47796). This doesn't output anything if it can't find a pentagonal pentagonal number; I trust that's OK?
I strongly believe that someone more clever than I am could find a way to shorten this even more, probably around the for loop.
[Answer]
# LabVIEW, 39 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
No gif of it running this time.
Math node in loop creates an array of all the numbers. Take Sub-array, add elements, search for that number, if found take index and stop loop.
An invalid input puts out the highest pentagonal number.
[](https://i.stack.imgur.com/tzeAY.gif)
[Answer]
# R, ~~114~~ 100 bytes
```
k=.5*(3*(t=1:1e6)^2-t);z=1;for(i in 1:(1e4-(n=scan()-1)))z[i]=sum(k[i:(i+n)]);cat(intersect(k,z)[1])
```
ungolfed (kinda)
```
k=.5*(3*(t=1:1e6)^2-t) # map all pentagon numbers up to 1e6
z=1 # create a vector
for(i in 1:(1e4-(n=scan()-1))){ # from 1 to 10.000 - n loop
z[i]=sum(k[i:(i+n)])} # get the sum of all pentagon numbers i:(i+n)
cat(intersect(k,z)[1]) # see which sums is a pentagon number itself, plot the first
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
×24‘½‘%6¬Oị
15ȷ7RÇṫ³R$zȷ.5ZSÇḢ
```
This code works with [this version of Jelly](https://github.com/DennisMitchell/jelly/tree/e27683dee67e6a23f0651e839a4a4bf96322fe91) and is equivalent to the following binary code:
```
0000000: 94 32 34 b2 90 b2 25 36 87 4f b1 0a 31 35 a0 .24...%6.O..15.
000000f: 37 52 92 ad 8b 52 24 7a a0 2e 35 5a 53 92 a6 7R...R$z..5ZS..
```
It is by far to slow and memory hungry for the online interpreter, since it checks the first 150,000,000 for pentagonality (149,995,000 happens to be the 10,000th pentagonal number).
By shortening the range to something more sensible, you can [Try it online!](http://jelly.tryitonline.net/#code=w5cyNOKAmMK94oCYJTbCrE_hu4sKMTXItzRSw4fhuavCs1Ikesi3LjVaU8OH4bii&input=&args=Mzc) for small enough inputs.
### Idea
A known result about pentagonal numbers is that **x** is pentagonal if and only if **sqrt(24x + 1) - 1** is divisible by **6**.
Rather than computing the first 10,000 pentagonal numbers, we define a helper link that removes non-pentagonal numbers from a given array. Why? Because the latest version of Jelly that predates this challenge has no sane way to intersect lists...
### Code
```
×24‘½‘%6¬Oị Define the aforementioned helper link. Left argument: a (list)
×24 Multiply each list item by 24.
‘ Increment each product.
½ Apply square root to each result.
’ Decrement each square root.
%6 Compute all remainders of division by 6.
¬ Apply logical NOT.
O Get the indices of ones.
ị Hook; get the elements of a at those indices.
15ȷ7RÇṫ³R$zȷ.5ZSÇḢ Define the main link. Input: x
15ȷ7R Yields [1, ..., 1.5e8].
Ç Apply the helper link; keep only pentagonal numbers.
³R$ Yield r = [1, ..., x].
ṫ Remove the first y-1 pentagonal numbers for each y in r.
zȷ.5 Transpose the resulting array, padding with sqrt(10).
Z Transpose once more. The shifted lists have now been padded.
This makes sure incomplete sums (i.e., of less than x
pentagonal numbers) will not be integers.
S Compute all sums.
Ç Apply the helper link once more.
Ḣ Select the first match, if any.
```
---
# Jelly, 21 bytes (non-competing)
```
ȷ6Rµ²×3_¹Hµḣȷ4ṡ³ZSf¹Ḣ
```
The latest version of Jelly has two new features (overlapping slices and and list filtering / intersection) and a bug fix, which allows a much lower byte count.
This code works fine on my desktop computer, but it's a tad to slow for TIO's time limit. To [Try it online!](http://jelly.tryitonline.net/#code=yLc1UsK1wrLDlzNfwrlIwrXhuKPItzThuaHCs1pTZsK54bii&input=&args=Mzc) (for sufficiently small inputs), we have to reduce the initial range once again.
### How it works
```
ȷ6Rµ²×3_¹Hµḣȷ4ṡ³ZSf¹Ḣ Input: x
ȷ6R Yield [1, ..., 1,000,000].
µ Begin a new, monadic chain.
² Square each number in the range.
×3 Multiply the squares by 3.
_¹ Subtract the numbers from the range.
H Halve each difference.
This yields the first 1,000,000 pentagonal numbers.
µ Begin a new, monadic chain.
ḣȷ4 Keep only the first 10,000 pentagonal numbers.
ṡ³ Yield all overlapping slices of length x.
ZS Transpose and sum. This computes the sum of each slice.
f¹ Filter; intersect with the long list of pentagonal numbers.
Ḣ Select the first match, if any.
```
[Answer]
# Mathematica 85 bytes
```
n=577380;Intersection[#(3#-1)/2&/@Range@n,Table[#((#-1)^2+x(3#-4+3x))/2,{x,n}]][[1]]&
```
perfoms a quick search up to **P104**.
[Answer]
# Axiom, 157 bytes
```
p(n)==(3*n*n-n)quo 2;f(x)==(a:=0;for i in 1..x repeat a:=a+p(i);for j in 1..10000 repeat(p(floor((1+sqrt(1.+24*a))/6)::INT)=a=>return a;a:=a+p(j+x)-p(j));-1)
```
ungolfed and results
```
h(x:PI):INT==
a:=0;for i in 1..x repeat a:=a+p(i) -- sum(p(i),i=1..x)
for j in 1..10000 repeat
p(floor((1+sqrt(1.+24*a))/6)::INT)=a=>return a
a:=a+p(j+x)-p(j)
-1
(5) -> [[i,f(i)] for i in 1..10]
(5)
[[1,1], [2,1926], [3,- 1], [4,330], [5,44290], [6,651], [7,287], [8,- 1],
[9,12105], [10,- 1]]
Type: List List Integer
```
esplenation:
We can find n using the result "a", see below
```
a=(3*n^2-n)/2 => 3*n^2-n-2*a=0 => n=floor((1+sqrt(1.+24*a))/6)::INT
```
[use 1+sqrt(...) because n>0]
This above means that if exist one n0 such that
```
p(n0)=a
```
than
```
n0=floor((1+sqrt(1.+24*a))/6)::INT
```
Afher that we have to prove that p(n0)=a for to be sure (because it is not always so)
But the main trick would be doing the sum
```
a:=sum(p(i),i=1..x) [x elements sum]
```
only at the start, and find the next x elements sum simply using
```
a=a+p(x+1)-p(1)=sum(p(i), i=2..x+1)
```
and so on for the other sums (using above in the statement a:=a+p(j+x)-p(j) ).
This means it is not necessary one number x element sum inside the loop...
..
[Answer]
# [Python 2](https://docs.python.org/2/), ~~128~~ 124 bytes
```
X=input();N=S=0
while all(S-(3*n*n-n)/2for n in range(S)):N+=1;S=sum(3*(n+N)**2-n-N>>1for n in range(X));N<1e4or 0/0
print S
```
[Try it online!](https://tio.run/##XY6xDoIwFEX39xVNp7akAQpKBMvC3qULKzFVmuCDIET9@lrj5nhvTs69y3sbZ1Sh05TS0GuPy74x3hhtdQbP0U@ODNPErGSFQIESeaqu80qQeCTrgDfHLOe1SXTeWP3Y75FjmBguhJIoTdvmf3jPo/6cuzLWWZrBsnrciA3xQONe7kJ/q139DaSjQUEJBzhCBScoqg8 "Python 2 – Try It Online")
[Answer]
# Javascript 93 bytes
```
p=i=>i>0&&3*i*i-i>>1
f=(x,i=1,t=0)=>i<1e4?(24*(t+=p(i)-p(i-x))+1)**.5%6==5&i>x?t:f(x,i+1,t):0
console.log(f(4))
console.log(f(5))
console.log(f(6))
console.log(f(7))
console.log(f(8))
console.log(f(9919)==496458299155)
console.log(f(9577)==446991927537)
console.log(f(9499)==455533474060)
console.log(f(9241)==401702906276)
console.log(f(9017)==429351677617)
console.log(f(9))
console.log(f(10))
```
] |
[Question]
[
# Church Subtraction
Lambda calculus has always been a fascination of mine and the emergent behaviors of passing functions into each other is delightfully complex. [Church numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals) are representations of natural numbers contructed from the repeated application of a function (normally the unary addition of a constant). For example, the number zero returns x and "ignores" the input function, one is `f(x)`, two is `f(f(x))` and so on:
```
ident = lambda x: x
zero = lambda f: ident
succ = lambda n: lambda f: lambda x: f(n(f)(x))
one = succ(zero)
add1 = lambda x: x + 1
to_int = lambda f: f(add1)(0)
print(to_int(one))
>>> 1
```
From this we can easily see that addition is accomplished by applying the first function to x then applying the second function to x:
```
add = lambda m: lambda n: lambda f: lambda x: n(f)(m(f)(x))
print(to_int(add(one)(two)))
>>> 3
```
Addition is relatively easy to understand. However, to a newcomer it might be inconceivable to think of what subtraction looks like in a Church encoded number system. What could it possibly mean to un-apply a function?
# Challenge
Implement the subtraction function in a Church encoded numeral system. Where subtraction performs the [monus operation](https://en.wikipedia.org/wiki/Monus) and unapplies a function `n` times if the result will be greater than zero or zero otherwise. This is code-golf so shortest code wins.
# Input
Two Church numerals that have been encoded in your choice of language. The input can be positional or curried. To prove these are true Church numerals they will have to take in any function and apply them repeatedly (`add1` is given in the examples but it could be `add25`, `mult7`, or any other unary function.)
# Output
A Church numeral. It should be noted that if `m < n` then `m - n` is always the same as the identity function.
Examples:
```
minus(two)(one) = one
minus(one)(two) = zero
...
```
also acceptable:
```
minus(two, one) = one
minus(one, two) = zero
```
Credit:
This [github gist](https://gist.github.com/vivekhaldar/2438498) for giving me a python implementation of Church Numerals.
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
```
(r%s)f x=s(x:)(iterate f x)!!r(+1)0
```
[Try it online!](https://tio.run/##TYzRCoMgGIXvfYoTLFBmoGtXg54kuhCXS1YSWtDTz1lI2913zvn@f1Dh3Y9jjNSXgRlsTaDbg1G79F4tPVLDisLTq2Qi6mH1eoDbWzT4c4rCkdXl3afNI6xaQ5CnNQZTumlwChfQkoHmNP3QMUImZXd59tYtyWyPB1JAcBx4h8xU45bpdpJE3ZGqQisFr7nkgosufrQZ1SvESs/zFw "Haskell – Try It Online")
Say that `r` and `s` are the church encodings of `m` and `n`. We want `r%s` to apply `f` `m-n` times to some initial value `x`. We first generate the infinite list
```
iterate f x = [x, f x, f (f x), f (f (f x)), ...]
```
then use `s(x:)` to prepend `n` copies of `x`, that is, shift each value `n` indices right:
```
s(x:)(iterate f x) = [x, x, x, ..., x, f x, f (f x), f (f (f x)), ...]
```
We then compute `m` directly as `r(+1)0`, and take the `m`'th element of that list as `!!r(+1)0`. An indexing-free solution could instead do `head$r tail$...`, that is drop the first element `m` times and then take the first element, but the indexing syntax is much shorter.
Note that the [classic solution](https://stackoverflow.com/questions/6595749/subtraction-of-church-numerals-in-haskell) doesn't work in Haskell without extensions because its strong typing can't represent the predecessor operation.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~82~~ 80 bytes
```
eval('!u:!v:v(!n:!f:!x:n(!g:!h:h(g(f)))(!u:x)(!u:u))(u)'.replace('!','lambda '))
```
[Try it online!](https://tio.run/##hVLbTuswEHz3V6zFkewVh4qCxIMlPqHnBwAhkzgXqVlHSRzC@fmyNmlCi1BfovXszs544vZjqDzdHXaPzwc32r1WMhg5mlFLMrIwcjKkZWlkZSpd6gIRNU9M6Rv4EFBtOtfubeaYq/6qvW3ecgsK8XAFgW5Kvy9cvtlsRNu5HB5hHiBzrIqlmgyQnutyQSsDi/YMJQdLHVBcwW5dHRbqaGDUUTcaFTxV@A4G1w81ldCGrvW966O3/67z64ITR5PoQ5ZdNF5oYot6QtbJKDQroTY1WMohrtGxpeubLSKwlSgrhCfH06kdARTDuz8C3ONz1bk4ksj3KPp6Op4eWM7m33JtzMWE2WazeGXydmXH@8I1bMXgX2saTiIpdJxFfcustovdr6EUsGZPvC7hMeg3l9nQuxR4EUhKGVf2Q3e28pvutfqjUCuFcXL09M@FxhL9TmCjT9ML6qeXc0cpMFwx1v2BrQonrWg@/i3y79D7xqXnApmdH8qpzi5de@bjee8LnpM5fAI "Python 2 – Try It Online")
2 bytes thx to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) noting an un-needed pair of parens.
Anonymous function that implements minus.
Mostly this is just compressing the definition found at the Wikipedia page; not like I truly understand the code yet. But interesting!
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
```
lambda r,s:s(lambda r:lambda f:lambda x:r(lambda(_,x):(x,f(x)))((x,x))[0])(r)
```
[Try it online!](https://tio.run/##Zc7BDoMgDAbgO0/BzXb2ILoTiU/izOJwRBNlirqwp3e4yEy2C3yl@UuH19w8TLqO@WXtqv5WV9zSJCcIhdyhA5y0exOu5FCCIw0OEcHL30VSIlhcp0UpnvNvysWCMdUsVjXHs5H8bz7pXMv7s@og0hCdDI955KLtRF8hW8zvFOtX2r5DSJCxutX66PVkZEjACDt6pF3Gb87YYFsz82KLgkgoQeIfn0kEZpQGpgcFZViubw "Python 2 – Try It Online")
We do Church decrement by tracking the previous value for each iteration and outputting that at the end. 39% of the code length is `"lambda"`'s...
[Answer]
# [C++ (clang)](http://clang.llvm.org/), 112 bytes
```
#define L(x,y)[&](auto x){return y;}
auto m=L(u,L(v,v(L(n,L(f,L(x,n(L(g,L(h,h(g(f)))))(L(u,x))(L(u,u))))))(u)));
```
[Try it online!](https://tio.run/##bVHLTsMwEDw3X2EZCa3VINprmyIhrj0gcQSEguM0lhq7cmwIoH57WT/yQCKXxLPjmdkJP51u@LFUh8uVVPzoKkEKqTtrRNneZROGiFSHuyyTypK2lAoY@blcVaKWSpA99PkXe75@hdJZTXr2Y4R1RpGv7TkLULvbg8v38JF/wB4UftW5v6XwdMCvJm/gADXzD3hqn96ORcy/t5fF7S150q0gD40zvCHKtcKUxy5bBBdZCYy3C3l6tk3otzA6gYEwDjrHeRhMeWpQmAL6YDrwNK64C2zwWiNuP/WAIwXhzOdL0cqqklZqlbh4DFZt/nd9NGsnx0HjEdu2WDipneJepZtk1sOCy/WYBOE6wbQGuuyXlNEpp36TqZcaN/QaDFZsPo//d07BTJ2tNps4AdrTWSMnMwjyPNK4drYoohNwVhR0Q2gAkkDAXhTNV3HL8RYpCkKfsETRddp0G@SgTXAY646nWHI6YPn/6Nyn1pNKXK8xwv9AXCpIpKuDjp/@m@jdmpLPxCK/TTdiNjbHUTYYzMHREMHz5Rc "C++ (clang) – Try It Online")
This is by far the most incomprehensible C++ code I've ever written. That said, I think that ungolfing this code will only make it worse.
[Answer]
# [Underload](https://github.com/catseye/stringie), 37 bytes
```
(~(((!())~):*^(~!:(:)~*(*)*)~^^!)~^^)
```
[Try it online!](https://tio.run/##jY2xCsMwDER3f4W9nTTFNAlFv5HdUEi30kIg0Em/7tpVHdrQQnWg4XRPt17n83K5neacoQACiJSEEzQIhJTBxKQphbooF5OrSH0ZHD1NzkOqZS5iV72EewHgiCfnxP56G3R/QtIS1oYYP8ANPnyFX8d@Yyz7I9pkTWP/1tT05Mdh9yA/AA "Underload – Try It Online")
The inner `(((!())~):*^(~!:(:)~*(*)*)~^^!)` is the `pred` function, implemented via pairs:
```
( ( start pred function )!
(
(!())~ ( push zero below argument )!
):*^ ( do that twice )!
( ( start pair-increasing function )!
~! ( remove second argument)!
: ( duplicate first argument )!
(:)~*(*)* ( increment first return value )!
)
~^^ ( run pair-increasing function n times )
! ( remove first in returned pair )!
)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~87~~ ~~85~~ ~~81~~ ~~76~~ 74 bytes
```
f=>g=>h=>x=>f(([x,[g,a]])=>[g(x),a])([x,g(a=>[x=>x,a])(f(a=>[h,a])())])[0]
```
[Try it online!](https://tio.run/##NY3BDsIgEETv/ZLd2Jo2xovJ4ocQDgQL1DRgSjX8PV1Q9zT7Zmf2qT86mW157UOIj7kkKpaEI@FJZBIWQOZeul4rhSSkg4yssVIHmgkf5UZsW33TiArlqIrx7814ClzU6sL9SyAMEydqKCPecreEnWx9V@tO7I3YmRhSXOfzGh2wDwl@4SviX16Qpxw "JavaScript (Node.js) – Try It Online") Not going to win any awards, but I thought I'd try a different approach.
`a=>[h,a]` is a stage that applies `h`, while `a=>[x=>x,a]` is a stage that doesn't apply `h`. We apply the first function `f` times and the second function `g` times. We then apply the inverse function `([f,[g,a]])=>[g(x),a]` `f` times. This skips over the `g` second stages and performs `f-g` first stages as desired. It then remains to extract the final value.
The tuples can of course be converted to lambda functions which results in the following expression:
```
f=>g=>h=>x=>f(e=>e(x=>d=>d(g=>a=>e=>e(g(x))(a))))(e=>e(x)(g(a=>e=>e(x=>x)(a))(f(a=>e=>e(h)(a))())))(x=>a=>x)
```
[Answer]
# [R](https://www.r-project.org/), 86 bytes
```
eval(parse(t=gsub("!(.)","function(\\1)","!u!vv(!n!f!xn(!g!hh(g(f)))(!ux)(!uu))(u)")))
```
[Try it online!](https://tio.run/##jVFBTsQwDLznFXZPtmARuXCCn6y0Kt2kG2mboCYuFZ8vcYGuKoTEJRqPx6OxMy5DiJLh@bC4qb3SWztmR@Wlz/JKDdIDN/eNl9iVkCIdj1ZrFJwmwoge50jY4@VCPXlmJpRZH6lQuKnM8uHGVO1hM/F8wzPDbLJ03U4R@U@1J6UqYtNFGXZjgSF4fdWQtE0BDmCZwV2zA01iUnQ6tEqUYFPe08bULpv2fN75DvyvaGuw4SddNbE7F10V7sCakk4hll8nIZ1geuRvgdZfSzzVY67A1lW29vpvN36T8vIJ "R – Try It Online")
R port of [@ChasBrown’s Python answer](https://codegolf.stackexchange.com/a/190767/42248) so be sure to upvote that one too.
[Answer]
# [J](http://jsoftware.com/), 56 bytes
```
c=:3 :0
t=.^:y
5!:1<'t'
)
m=.2 :'c 0>.(>:u 5!:0->:v 5!:0)0'
```
[Try it online!](https://tio.run/##hY1BTsMwEEX3PsVng2NVjZyk2YxwJDhAN7BGsswICyVN5dopPX1Imy4gWbCa0Z8373@NozNUgbSIJn@ni6gfqHiSUQolOpOXIOmgmzxrKGG66W1Dw21RWo77lxzP8NweOSD24G92KTIsPjmkwwecT8F5HFLHwbbC2baFIUxayAGzUQpx9bz6/ozobcSZ4e3AiCHxwnAS7HyPzKFSuNkagl6F2eaxVL/y3T3fEIq57Y1P8S6Tcp4VDLIJrhW661OpVhXFAtmtEb1A6v@RQv9hxh8 "J – Try It Online")
Note: *-3 bytes off TIO count for `m=.`*
Higher order functions in J are achieved using adverbs and conjunctions. Here a church numeral is the gerund form of the adverb formed by combining the "power of" conjunction (which repeatedly applies a verb) and an integer. The following verb `c` (for "create") uses J's [Atomic Representation](https://www.jsoftware.com/help/dictionary/dx005.htm) to transform an integer into such a gerund:
```
c=:3 :0
t=.^:y
5!:1<'t'
)
```
Our "minus" operator (which is a conjunction) subtracts the right gerund church numeral from the left. It does not, however, assume any particular implementation of church numerals, including the one from our `c` verb. Instead, it relies on the general definition and turns each gerund church numeral back into an adverb by inverting it with `5!:0`, and then applying that adverb to the increment verb `>:`, and then applying *that* to 0.
It then subtracts and takes the maximum with 0, and applies `c` to get the final result: a new gerund church numeral.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~55~~ ~~48~~ ~~47~~ 39 bytes (33 characters)
```
#2[(fx#[g#@g@f&][x&][#&])&]@#&
```
[Try it online!](https://tio.run/##bY5NCsIwEEb3PcVAIGhpwR9wI4GAa8GFuzBIjKktNBHaFArSS3gDT@gR6ii2grj4ZjHD@944HXLrdCiM7uvmGCptAoieLdQke9zuLYWp82vKs8w4qpbCOE45Ssb7SQwnmxXewiZvKpODb5ytdFlDPI2MnAnGga@N9AfBZGyUT@eEI48iIoOtwz9uVxU@yL0@llYRgiojLSZw9QnMElh1@MWHn4uL/0WHE3U4TF5FnyYQAoza6lZRm0vHPRnc27DsRtmyw/4J "Wolfram Language (Mathematica) – Try It Online")
The symbol is 0xF4A1, a special Mathematica code point that denotes a rightward arrow for `\[Function]`. [See here](https://codegolf.stackexchange.com/a/141021/87058) for more explanations. This is what the code looks like in the Mathematica front end:
[](https://i.stack.imgur.com/NQtMQ.png)
We can do it in [40 bytes / 32 characters](https://tio.run/##bY5LCsIwEIb3PcVAIGip4APcSCDgWnDhLgwSY2oLZoQ2hYL0Et7AE3qEOooPEBf/LGb4/m@CjYUPNpbO9nWzi5V1EVQvpoZul2vOaTlkDjyFPuhcomk5QiJqIftBCnufl@RhWTSVK4Ca4Ct7rCEdJk6PlZAgF07TVgmdOkOjCcMok4TJ6Ov4j1tXJUW9sbujN4ygyVmKGZwpg3EG8w6/@Pvp8kS/6PvEHQGzR9GrCZQCZ1a2NdwWRp89G8LTMOs@slmH/R0), which may be shorter depending on the measurement scheme: `#2[n⟼f⟼x⟼n[g⟼#@g@f&][x&][#&]]@#&`
The un-golfed version is a literal translation of the [classical definition of pred](https://en.wikipedia.org/wiki/Church_encoding#Derivation_of_predecessor_function):
```
pred = n \[Function] f \[Function] x \[Function] n[g \[Function] h \[Function] h[g[f]]][u \[Function] x][u \[Function] u];
subtract[m_, n_] := n[pred][m]
```
which looks like this in the Mathematica front end:
[](https://i.stack.imgur.com/a81Fa.png)
This subtraction function works with the Church numerals defined with
```
c@0=#& &;c@n_=#@*c[n-1][#]&
```
(un-golfed: `c[0] = Identity &; c[n_] = Function[a, a@*c[n-1][a]]`)
so that we have
```
Table[c[n][f][x], {n, 0, 6}]
(* {x, f[x], f[f[x]], f[f[f[x]]], f[f[f[f[x]]]], f[f[f[f[f[x]]]]], f[f[f[f[f[f[x]]]]]]} *)
```
and
```
subtract[c[7],c[5]][f][x]
(* f[f[x]] *)
```
] |
[Question]
[
# Introduction
Recently, me and a couple of my friends decided to play some cards, and one of them suggested the game 'Irish Snap', which was the inspiration for this challenge. However, I later learnt that the game has a lot of different rules that you can play with, some of which are listed [here](https://en.m.wikipedia.org/wiki/Slapjack#Irish_Snap). The rules that are in this challenge aren't currently listed on that page, hence the name, 'Variant Rules'
# The Challenge
Given an array of 3 cards, output a truthy or falsey value depending on if they make a valid snap in a game of Irish snap.
# Input
The input will be an array of 3 numbers, ranging from 1-13 inclusive, with 1 representing an ace, 11 representing a jack, 12 representing a queen and 13 representing a king. The input can be in any order of top, middle, bottom.
# Rules
The 4 different criteria for if cards make an Irish snap are:
* The top and middle cards are the same
* The top and middle cards have a difference of one
* The top and bottom cards are the same
* The top and bottom cards have a difference of one
If any of these criteria are met, you must output a truthy value. As well as this, for the two criteria that require the cards to have a difference of one, it 'wraps around', meaning that an ace and a king are considered to have a difference of one, and vice versa.
# Test Cases
```
Input (Bottom, Middle, Top) -> Output
1 13 7 -> False
1 4 13 -> True
9 3 6 -> False
8 9 7 -> True
2 6 5 -> True
12 5 11 -> True
10 4 8 -> False
12 13 7 -> False
9 7 10 -> True
7 3 1 -> False
4 2 3 -> True
```
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
lambda x,y,z:{x-y,x-z}&{0,1,12,-1,-12}
```
[Try it online!](https://tio.run/##bY7LCsIwEEX3fsWsJIFbyKRqquCfuGmRolCbUrrog357nLa4MAqzOvcxtxm6h6/TUF5vocpfxT2nHgPGy9QnA/pknPeTAYMtEpazc2jaZ92p2ndUKgdOwVrvNlh4X6lSCaMDSPhH2NwnkCjn2O6EgTId8yNIEvaHM4NEYxv3Z9tbE2HpXxYt/qjIgNw66DvA6073ZyevWIc3 "Python 3 – Try It Online")
Returns a non-empty set (truthy) if valid, empty set (falsey) if not. Takes input in order top-middle-bottom, but can be rearranged for same code size.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 16 bytes
```
3>(*-(*|*)+1)%13
```
[Try it online!](https://tio.run/##XY3NCoJQFIT39ylmU3g1seMtfxKtVQ8Q7aqF0DUCtVBaRPbsdizSaDnzfcxcdZV7bXHHOEPcqsQwbcNsTGmRHJFqI5FdKhj5udS1xEMArK5KxCgWJ2d/tJyIuzq9Y5kZzW4zOTCV4tkSSMGHnWCd5rUWhFnXcN5WNy1CKHgDDRB@5Dd0Gc37RC4HoiFPeSr4WXb/rroplr6@z1fU0xc "Perl 6 – Try It Online")
Anonymous whatever lambda that takes input as `top, middle, bottom` and returns a Junction that evaluates to True or False
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes
```
α12%ß!
```
[Try it online!](https://tio.run/##yy9OTMpM/W9o4Jbw/9xGQyPVw/MV/@v8j4421FEwNI7VUTCP5QJzTGLBAkCOpY4CSMIMxLbQUbCEKTICiekomII1GIEYQB2GYJ4BRL8FTAphsiWIBgoYgDjmEJMNYwE)
Takes inputs as `[middle, bottom], top`.
```
α # absolute difference
12% # mod 12
ß # minimum
! # factorial
```
Only 1 is truthy in 05AB1E. 0! and 1! are both 1, while no other number has a factorial of 1.
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
1 e.2>12||@-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRVS9YzsDI1qahx0/2typSZn5ANlbRUMFQyNFdIUzCEihmARE6CAoTFCjaUCSIkZQokFUAhFj5GCGVDAFMkQIwVTkCmGSDYZgA22UEASMsKw3VLBHKTPAEmVOdh6w/8A "J – Try It Online")
Taking bottom middle as left arg, top as right arg.
# original answer taking input as one list
# [J](http://jsoftware.com/), 24 bytes
```
1 e.2>#:@3 5(12||@-/)@#]
```
[Try it online!](https://tio.run/##ZY2xCsJAEAV7v2IwRQyYmL3zkngQORCsrOytJEFs/IH8@7mixR0W2wyz855x3ZQzo6dkS4vXqxtO18s5ClNjjoUPFrcRsyyh3lWhuMVqNd0fLzVHZgSx9F8iP7JXljoHLF2qDIqyH0OHyyIGh0i21Gp4IEPmb13DHzO1ep2X@AY "J – Try It Online")
* `#:@3 5` The numbers 3 and 5 in binary are `0 1 1` and `1 0 1` which are the masks for the middle/top and bottom/top cards respectively
* `(12||@-/)@#` We filter the input with those masks, take the abs value of the
resulting differences, then the remainder when divided by 12 (for the ace-king case)
* `1 e.2>` are either of the resulting numbers less than 2, ie, 0 or 1?
[Answer]
# JavaScript (ES6), 29 bytes
Takes input as `([bottom, middle])(top)`.
The output is inverted.
```
a=>c=>a.every(n=>(n-c)/2%6|0)
```
[Try it online!](https://tio.run/##fdDNCoJAFAXgfU9xN@FcSHM0/xbjsidoZy6GaYxCZkJLCHr3aUYICrXt/eCcw73ygfeiu9zuvtInaRpmOCsFK3kgB9k9iWIlUb7AbbROXyEaoVWvWxm0@ky8as/bXtYerr7PDamAboDGNRLIcIrFBmDEdIo0tLhzmM9g9C82@8RSiz/qHVV16B5LS8c@Gs9E5haLpT47BlKHyfxSSFwsXXhA5jBENG8 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~37~~ 30 bytes
*Saved 1 byte thanks to @Grimy*
Takes input as `([bottom, middle])(top)`.
```
a=>c=>a.some(n=>(n-=c)*n%72<2)
```
[Try it online!](https://tio.run/##jdDLDoIwEAXQvV8xG0NreBXklViWfoE7ZNHUYjTYGlB/v1KMEYMQt5MzvXd6Zg/W8uZ0vTlSHYSuqGY05zRnbqsuAkmaI@lQjldymQSbAGuuZKtq4dbqiKxiy@pWlBZeDMcVKoDYQMISI0gwBs@DHo5UZgP0Kp5RxO/U2qh0TgV/JSbvRDJUX8zay2LX3KfO6quQ8LVu3AilHcoGTX6iri7EBkXTyNwEkYkjMy@ZT0wM8j9IPwE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
›²⌊﹪↔⁻E²NN¹²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO9KDWxJLVIw0hHwTczLzO3NFfDNz@lNCdfwzGpWAMoVAokEwtA8p55BaUlfqW5SUDlmprofKCAoRGQ0rT@/99QwUTB0Pi/blkOAA "Charcoal – Try It Online") Port of @Grimy's answer. Takes input as three separate values bottom, middle, top, and outputs using Charcoal's default Boolean format of `-` for true, nothing for false. Explanation:
```
² Literal 2
› Is greater than
⌊ Minimum of
↔ Absolute value of (vectorised)
E²N First two numeric inputs as a list ([bottom, middle])
⁻ Minus (vectorised)
N Third input (top)
﹪ Modulo (vectorised)
¹² Literal 12
```
[Answer]
# [Perl 5](https://www.perl.org/) `-ap`, 31 bytes
```
$t=<>}{$\|=abs($t-$_)%12<2for@F
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lxNbGrrZaJabGNjGpWEOlRFclXlPV0MjGKC2/yMHt/38TBSMuQ@N/@QUlmfl5xf91fU31DAwN/usmFgAA "Perl 5 – Try It Online")
### Input:
```
bottom middle
top
```
Actually, the order of the middle and bottom doesn't matter.
### Output:
`0` for false; `1` for true
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~12~~ 11 bytes
Takes input as `[bottom, top, middle]` or `[middle, top, bottom]` (both work).
Outputs `[]` (Falsy in Pyth) if there's no valid snap, a non-empty array otherwise.
```
f>2%.aT12.+
```
[Try it online!](https://tio.run/##K6gsyfj/P83OSFUvMcTQSE/7//9oQyMdcx3TWAA "Pyth – Try It Online")
If a consistent truthy/falsy value is required, add `.A` in front for +2 bytes. Then output will be `True` or `False`.
## Explanation
```
f # Filter on lambda T:
>2 # 2 >
.aT # abs(T)
% 12 # % 12
.+ # the list of deltas (difference between consecutive elements)
.A (if required)# Any truthy values in the above list?
```
Edit: -1 with a different approach
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ạ%12ṠƑ
```
[Try it online!](https://tio.run/##y0rNyan8///hroWqhkYPdy44NvH////RJjoKRrH/jQE "Jelly – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 47 43 bytes
```
f(b,m,t){return(1<<t-m|1<<t-b)&0x80101003;}
```
[Try it online!](https://tio.run/##Tc7NboMwDAfwM36KvzIVESmdcOkHLXS77Ql23AVCukaCbIKgTer67CygHaZYim39bFmv37WeHqzT7dgYlINv7Mfj9Wm6JLXqlJe33vixdwmXpV93P8tXyzj9zlMOL82K@2SdR1dZl0jcKJqrWqFT8AVFX1fbmmTQlbskYtVgiTcnFOKA4qBiL3E@I5MURZ99mP4HT1gNC/5bqDDftaQSzxCv/WgEThAvVTsYIQu6TwzOcCDGNiR0RIY95TiG1gZ77Ig32IGZOA0in8vFBwBO6RA80y8 "C (gcc) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
d_aV <2
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZF9hViA8Mg&input=WzEsMTNdCjc)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
I%12ỊẸ
```
[Try it online!](https://tio.run/##y0rNyan8/99T1dDo4e6uh7t2/P//31DH0FjHBAA "Jelly – Try It Online")
A monadic link taking the list of `[middle, top, bottom]` as its argument and returning `1` for snap and `0` for no snap.
[Answer]
# T-SQL 2008, 40 bytes
```
PRINT 1/-~abs((@-@2)%12/2*((@-@3)%12/2))
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1095920/irish-snap-variant-rules)**
[Answer]
# [R], 23 bytes
takes input as a=c(bottom,top,middle):
`any(abs(diff(a))%%12<2)`
] |
[Question]
[
# Input
A single integer \$1 \leq x \leq 10^{15}\$.
# Output
The maximum number of distinct positive integers that have the product \$x\$.
# Examples
Input: 1099511627776. Output: 9. One possible optimal list of factors is: (1, 2, 4, 8, 16, 32, 64, 128, 4096).
Input: 127381. Output 4. One possible optimal list of factors is: (1, 17, 59, 127).
Related to this [old question](https://codegolf.stackexchange.com/questions/104707/list-all-multiplicative-partitions-of-n?rq=1).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes
```
Max[Length/@Cases[Subsets@Divisors@#,{a__}/;1a==#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zexItonNS@9JEPfwTmxOLU4Org0qTi1pNjBJbMsszi/qNhBWac6MT6@Vt/aMNHWVjk2Vu1/QFFmXomCQ3q0oZG5sYVh7P//AA "Wolfram Language (Mathematica) – Try It Online")
*4-bytes saved thanks to @attinat*
Here is also a **153 bytes** version that calculates `1099511627776` and `10^15`
```
Max[Length/@Table[s=RandomSample@Flatten[Table@@@FactorInteger[#]];Last@Select[Times@@@TakeList[s,#]&/@IntegerPartitions@Length@s,DuplicateFreeQ],5!]]+1&
```
[Try it online!](https://tio.run/##LY7RCoIwFEB/pRB6STADlQjhPoQQGFj5NvZws8scbTO2G/T3S6rnc@AcizySRdYDRlXHE75FS07xmEGPN0Mi1Bd098le0T4NQWOQmZz4QgBocODJHx2TIi8SKfctBoYrGRpY9NpSmK0eH9TqwCKkiVxl8Pc79KxZTy7ALwohPbyeZp5hajzRWabFUsp1voqd144XoES@2e2KPC@3VVWVMsYP "Wolfram Language (Mathematica) – Try It Online")
The result for `10^15` is **12**
>
> {1, 2, 4, 5, 10, 16, 25, 40, 50, 100, 125, 250}
>
>
>
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes
```
(c=n=#;If[i∣n,n/=i,--c]~Do~{i,n};c)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPZNs9W2dozLTrzUcfiPJ08fdtMHV3d5Ng6l/y66kydvFrrZE21/wFFmXkl0cq6dmkOyrFq@g5c1YY6ZjqG5jqmZjqWhjqGQMrQyBJEGBsBuUbmxhaGtf//AwA "Wolfram Language (Mathematica) – Try It Online")
Greedy algorithm. Times out on TIO on larger inputs such as `1099511627776`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
Very inefficient. Will time out on TIO for numbers with a large amount of divisors.
```
ÑæʒPQ}€gZ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MTDy05NCgisfdS0Jj3q/38jA0tLU0NDMyNzIAAA "05AB1E – Try It Online")
**Explanation**
```
Ñ # push a list of divisors of the input
æ # push the powerset of that list
ʒPQ} # filter, keep only the lists whose product is the input
€g # get the length of each
Z # take the maximum
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes
```
{$!=$_;+grep {$!%%$_&&($!/=$_)},1..$_}
```
[Try it online!](https://tio.run/##DchLCoAgEADQ/ZxigkmKwrSiD@FZpIVG0A9bhXh2c/neY9wxxPNDZlFFT5kivVSbMw8m5DlpxgrKmtRlqCXnpEO0t8Pi2C/zlugB8V0/5MxCiLIdu0mCFEJAL@YBUvw "Perl 6 – Try It Online")
Takes the greedy approach to selecting divisors.
[Answer]
# Javascript (ES6), 39 bytes
```
f=(n,i=0)=>n%++i?n>i&&f(n,i):1+f(n/i,i)
```
There's probably a few bytes that can be saved here and there. Just uses the greedy algorithm for the factors.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ŒPP=³ƊƇẈṀ
```
[Try it online!](https://tio.run/##AR0A4v9qZWxsef//xZJQUD3Cs8aKxofhuojhuYD///8xNQ "Jelly – Try It Online")
-1 byte thanks to someone
-2 bytes thanks to ErikTheOutgolfer
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 13 bytes
```
â à f_×¶UÃmÊn
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4iDgIGZf17ZVw23Kbg&input=Nzg)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
f;?⟨⊇×⟩l
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmZiBXA8hJs7Z/NH/Fo672w9MfzV9ZrqSpoPRwV2ftw60T/qNK5fz/H22mY6FjaKRjaKpjaKZjZKJjZK5jbKZjbK5jYqRjYqljZqJjYahjaaBjaADERhY6pmDa3NjCMBYA "Brachylog – Try It Online")
(The naive approach, `{~×≠l}ᶠ⌉`, generates an infinite number of solutions with extra 1s before eliminating them with `≠`, and thus fails to actually terminate. It's not a problem, though, since it's for the same byte count!)
Takes input through the input variable and output through the output variable. The header on TIO contains a copy of most of the code for the sake of showing you what the factor list is, but this works perfectly fine without it. Since `⊇` gives larger sublists first, this predicate essentially does the same thing as most other answers, but without explicitly generating and filtering the complete powerset of the factors, thanks to backtracking.
```
The output
l is the length of
⊇ a sublist (the largest satisfying these constraints)
f of the factors of
the input
; ⟨ ⟩ which
× with its elements multiplied together
? is the input.
```
[Answer]
# [Scala](https://www.scala-lang.org/), 77 bytes
```
def f(n:Long)={var(m,c,i)=(n,1,2L);while(i<=m){if(m%i==0){m/=i;c+=1};i+=1};c}
```
[Try it online!](https://tio.run/##HY49D4IwFEV3f8VbTNqISjFQ@ejgjpOjcaiV4jO0mEI0hvDbK7Dc4Z6bk9sp2Ujf3l@V6uEs0cLgH5UGTWxWtramYvhIR0ygAqSC2IAFUUnz7xObimAhDB1QE7NGIUI6mL3AXG0EG3NcUo2LzUxiIl3dZXByTv6ul96hrW8UBOjWzQiKLcwLCu8J9Y0leq53fbvcoKvRexYnnkX8cGSehWkaM5ZEnPPkDw "Scala – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~10~~ 9 bytes
```
Π=
dz↑⁇(l
```
[Try it online!](https://tio.run/##S0/MTPz//9wCW66UqkdtEx81tmvk/P9vaGRubGEIAA "Gaia – Try It Online")
Follows the same "algorithm" as seen elsewhere -- filter the divisor powerset for the longest with product equal to the number and return its length.
```
| helper function
Π= | is prod(list)==n (implicit)?
|
| main function; implicitly takes n
dz | divisor powerset (in decreasing order of size)
↑⁇ | filter by helper function
(l | take the first element and take the length (implicitly output)
```
[Answer]
# [Clam](https://github.com/dylanrenwick/Clam), 15 bytes
```
p}_`nq#:;qQ@s~Q
```
TIO link coming soon (when dennis pulls)
Basically a port of @Emigna's 05AB1E solution.
## Explanation
```
- Implicit Q = first input
p - Print...
} - The last element of...
_ - Sorted...
`nq - Lengths of... (map q => q.len)
@s - Items in powerset of
~Q - Proper divisors of Q
# - Where... (filter)
;q - Product of subset
: - Equals...
Q - Q
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 54 bytes
```
int f(int n,int i=0)=>n%++i<1?1+f(n/i,i):n>i?f(n,i):0;
```
Uses the same approach as @vrugtehagel's and @JoKing's answers.
[Try it online!](https://tio.run/##Sy7WTS7O/P8/M69EIU0DRObpgMhMWwNNW7s8VW3tTBtDe0PtNI08/UydTE2rPLtMeyAHxDSw/h9QBFSskaZhaGRubGGoqWn9HwA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 34 bytes
Obviously times out on that massive number, but will eventually time out if given enough time on another machine.
```
->n{(1..n).count{|e|n%e<1?n/=e:p}}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9cur1rDUE8vT1MvOb80r6S6JrUmTzXVxtA@T9821aqgtvZ/gUJatEq8Xkl@fGasQnlGZk6qQnpqSfF/Q1MzLkMjc2MLQwA "Ruby – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
▲mLfo=¹ΠṖḊ
```
[Try it online!](https://tio.run/##ASEA3v9odXNr///ilrJtTGZvPcK5zqDhuZbhuIr///8xMjczODE "Husk – Try It Online") A port of [Emigna's answer](https://codegolf.stackexchange.com/a/185063).
] |
[Question]
[
Your task is to fill the bucket with numbers upto a given input.
### Rules
Numbers occupy the leftmost position then rightmost, then leftmost and so on.
After overflow, the numbers start to gather around the bucket in a similar manner. They occupy position diagonally.
The examples should make it clear what the expected output is (Some rules are mentioned in the examples).
For more then 10, use the rightmost digit
### Examples:
```
The bucket:
| | or | |
| | | |
| | | |
| | | |
|------| |______|
input:1 (You can start from either 0 or 1)
output:
| | (There can be whitespace to the left even if there is no overflow
| | but the bucket must not be distorted.)
| |
|1 |
|------|
input:6
output:
| |
| |
| |
|135642|
|------|
input:8
output:
| |
| |
|7 8|
|135642|
|------|
input:23
output:
|913 20|
|357864|
|791208|
|135642|
|------|
input:27
output:
|913420|
|357864|
|791208|
|135642|
75|------|6
input:30
output:
|913420|
|357864|
|791208|
9|135642|0
75|------|68
input:40
output:
|913420|
|357864|
5|791208|6
939|135642|040
7175|------|6828
input:54 (Maximum input for start=1)
3|913420|4
13|357864|42
915|791208|620
7939|135642|0408
57175|------|68286
```
This is **code-golf** so shortest code wins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~145~~ 143 bytes
A hard-coded pattern (see [**here**](https://codegolf.stackexchange.com/a/177385/58563) for more maths).
1-indexed.
```
n=>` g|EGIJHF|h
e]|?ACDB@|^f
c[U|9;=><:|V\\d
aYSO|357864|PTZb
_WQMK|------|LNRX\``.replace(/[3-h]/g,c=>(x=Buffer(c)[0])<n+51?x%10:' ')
```
[Try it online!](https://tio.run/##HcdbT4MwGIDhe35FL2bWxsJgwDa3lel0np3nI6CtXQsaUhamZsk@fzsSn6v3/RQ/YiWrj@WXbcqFqjWrDYs4amQwOzo5PT6E3GpOpTDZ2z@Y7sKrbl7G97AzYtF4CA9JsrCQeL69BD/sD3oBXN29vFtvj9cXZ2D/g/P5zVPCuVOpZSGkwp3Yt/O0k1HJIrxm02@tVYUlid2UjM126E3WW547bKM2qUexR3t0QLs@7fap79LApWGQWo4uq5mQOTaIRUiWZlUWyinKDPM5a23Mb2JaG40NaYITUv8B "JavaScript (Node.js) – Try It Online")
*Saved 2 bytes thanks to @tsh*
[Answer]
# JavaScript (ES6), ~~144 ... 139~~ 137 bytes
A mathematical approach (see [**here**](https://codegolf.stackexchange.com/a/177369/58563) for less maths).
0-indexed.
```
n=>(y=4,g=x=>~y?(X=x>8?17-x:x,k=X<y?g:X<5?24-(z=4+y-X)*~z+y*2:y*6+X*2-18,~X?X^5?k<0?'-':(k+=x>8)<n?k%10:' ':'|':`
`)+g(~X?-~x:!y--):'')()
```
[Try it online!](https://tio.run/##FcxNb4IwGADgu78CE5e29K2BWpR0vPS0685N9hEIE7Zh2kWXpdXJX2fz/uT5bH/aU3f8@PoWzr/t5x5nhzWNqGDAgPUUDbUY6tLkOxF0gBFtFc2gbVUYqQQ9o@JRWJZOZx5TqWO65TaVIi9hssa@FmasMkME0XTkt4hVzox3eaZJQjT5JbpZNIwP9F@LKehlFIJpQhhl8/1TDlsoQW5A7mCTgcqgUC@Lde@PD233Tl2CddJ5d/KH/frgB9o84urirs9udempY9eGsfkP "JavaScript (Node.js) – Try It Online")
### How?
The output is built character by character, with \$y\$ decreasing from \$4\$ to \$0\$ and \$x\$ increasing from \$0\$ to \$18\$ on each row.
We define:
$$X=\begin{cases}x&\text{if }x\le 8\\17-x&\text{if }x>8\end{cases}$$
By writing the full values rather than just the unit digits, we get the following table:
```
x | 0 1 2 3 4 5 6 7 8 | 9 10 11 12 13 14 15 16 17 18
X | 0 1 2 3 4 5 6 7 8 | 8 7 6 5 4 3 2 1 0 -1
---+----------------------------+-------------------------------
4 | .. .. .. .. 52 || 18 20 22 | 23 21 19 || 53 .. .. .. .. \n
3 | .. .. .. 50 42 || 12 14 16 | 17 15 13 || 43 51 .. .. .. \n
2 | .. .. 48 40 34 || 6 8 10 | 11 9 7 || 35 41 49 .. .. \n
1 | .. 46 38 32 28 || 0 2 4 | 5 3 1 || 29 33 39 47 .. \n
0 | 44 36 30 26 24 || -- -- -- | -- -- -- || 25 27 31 37 45 \n
```
This table is essentially symmetric across the y-axis, except that the values on the left side are even and the values on the right side are their odd counterparts.
We define:
$$k=\begin{cases}24+(4+y-X)(5+y-X)+2y&\text{if }X<5\\6y+2X-18&\text{if }X>5\end{cases}$$
$$k'=\begin{cases}k&\text{if }x\le 8\\k+1&\text{if }x>8\end{cases}$$
And for each cell, we append:
* a linefeed if \$X=-1\$
* a pipe if \$X=5\$
* a hyphen if \$k<0\$
* a space if \$X<y\$ or \$k'>n\$ (where \$n\$ is the input)
* \$k' \bmod 10\$ otherwise
### Commented
```
n => ( // main function taking n
y = 4, // start with y = 4
g = x => // g = recursive function taking x
~y ? // if y is not equal to -1:
( X = x > 8 ? 17 - x : x, // compute X
k = X < y ? // if X is less than y:
g // set k to a non-numeric value
: // else:
X < 5 ? // if X is less than 5:
24 - (z = 4 + y - X) * ~z // apply the 'side numbers' formula
+ y * 2 //
: // else:
y * 6 + X * 2 - 18, // apply the 'middle numbers' formula
~X ? // if X is not equal to -1:
X ^ 5 ? // if X is not equal to 5:
k < 0 ? // if k is less than 0:
'-' // append a hyphen
: // else:
(k += x > 8) < n ? // update k to k'; if it's less than n:
k % 10 // append the unit digit of k'
: // else:
' ' // append a space
: // else (X = 5):
'|' // append a pipe
: // else (X = -1):
`\n` // append a linefeed
) //
+ g(~X ? -~x : !y--) // update x and y, and do a recursive call
: // else (y = -1):
'' // stop recursion
)() // initial call to g with x undefined
```
[Answer]
# [Python 2](https://docs.python.org/2/), 170 bytes
```
I=input()
s=" u|SUWXVT|v\n sk|MOQRPN|lt\n qic|GIKLJH|djr\n oga]|ACEFDB|^bhp\nme_[Y|------|Z\`fn"
i=1
exec"s=s.replace(chr(64+i),[`i%10`,' '][i>I]);i+=1;"*55
print s
```
[Try it online!](https://tio.run/##HchrD4FQHIDx932K1mYVMRne2LG5y/1@q4gcOuQ4OjG2/3dP/N49D/uE3p3moshAhLJnqKgCR5IYe8J0vlwtZvCyaJz8Cv3heDIagB/@xoO40DK6vU4bjpcgPvfz3oZKrdGsV2F78JhFb3hnriH9BxvLOVFJIEgX8Bu7Ekc8E2Dm712suF6gFPMpomqmQxJ61tFkUbZNUjZstURSSC9JyUJBYAGhocijSM99AQ "Python 2 – Try It Online")
[Answer]
# Java 10, 168 bytes
```
n->" g|EGIJHF|h\n e]|?ACDB@|^f\n c[U|9;=><:|V\\d\n aYSO|357864|PTZb\n_WQMK|------|LNRX`".chars().forEach(c->System.out.print(c<46|c==124?(char)c:c<n+51?c%10:" "))
```
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/177369/52210) (so also 1-indexed, and outputting `-` as bottom). If you like this answer, make sure to upvote him as well!
[Try it online.](https://tio.run/##jZJbb4JAEIXf/RUTkiZLGojIRasCvWmv2gu9i23XERSrqwE0abr@drpYnvrEPkwyZ7@dPSeZGd1QZTb@ynBOkwR6NGI/FYCIpUEcUgygn7cAm2U0BiRCBya3hLStiJKkNI0Q@sDAhowpjpSzE945u7g87/Kpz0QbDLl7dHJ6fMjfw1zAwSM/aNlOu8mffH8sJPrq3XDdrDcsg98@vI189vF817viyu7w6/79y6ek4pTGCZHVcBl3KE4JKo73naTBQl2uU3UVC28E24bF0ba1muGS/IGMTWyzfVNzcU@rNiWQZDlr5d5X69FceC8i7PItRHripWLSZDAEKv9FZyoSbZcZ4P@Hc0Ykn0nFbU5apclGabKml0frpVG9Who1yqOmUazHNvsF)
**Explanation:**
```
n-> // Method with integer parameter and no return-type
" g|EGIJHF|h\n e]|?ACDB@|^f\n c[U|9;=><:|V\\d\n aYSO|357864|PTZb\n_WQMK|------|LNRX`"
// String containing the bucket and magic string
.chars().forEach(c-> // Loop over the characters (as integers)
System.out.print( // Print:
c<46|c==124? // If the character is "\n", " ", "-", or "|":
(char)c // Output the character as is
:c<n+51? // Else-if the character value is smaller than the input + 51:
c%10 // Output a digit: the character value modulo-9
: // Else:
" ")) // Output a space
```
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 130 bytes
```
00 C0 20 9B B7 A9 C0 65 65 85 FB A2 00 BD 2B C0 F0 1A 10 12 C5 FB 90 04 A9 20
D0 0A 69 70 C9 3A 90 04 E9 0A B0 F8 20 D2 FF E8 D0 E1 60 20 20 20 20 F5 7D D3
D5 D7 D8 D6 D4 7D F6 0D 20 20 20 F3 EB 7D CD CF D1 D2 D0 CE 7D EC F4 0D 20 20
F1 E9 E3 7D C7 C9 CB CC CA C8 7D E4 EA F2 0D 20 EF E7 E1 DD 7D C1 C3 C5 C6 C4
C2 7D DE E2 E8 F0 0D ED E5 DF DB D9 7D 2D 2D 2D 2D 2D 2D 7D DA DC E0 E6 EE 00
```
This uses a modified version of the "preformatted" approach of some other answers. It contains a full string of the bucket, but the digits are replaced by values starting from `0xC1`, while any characters for direct printing are in the range `0x01`-`0x7f`.
The C64 charset doesn't include a pipe (`|`) character, it's therefore replaced with the similar-looking [PETSCII](https://en.wikipedia.org/wiki/PETSCII) character `0x7d`.
### [Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22bucket.prg%22:%22data:;base64,AMAgm7epwGVlhfuiAL0rwPAaEBLF+5AEqSDQCmlwyTqQBOkKsPgg0v/o0OFgICAgIPV909XX2NbUffYNICAg8+t9zc/R0tDOfez0DSAg8enjfcfJy8zKyH3k6vINIO/n4d19wcPFxsTCfd7i6PAN7eXf29l9LS0tLS0tfdrc4ObuAA==%22%7D,%22vice%22:%7B%22-autostart%22:%22bucket.prg%22%7D%7D)
Usage: `SYS49152,[n]` (1-indexed, e.g. `SYS49152,54` for the full output)
**Commented disassembly**:
```
00 C0 .WORD $C000 ; load address
.C:c000 20 9B B7 JSR $B79B ; get unsigned byte from commandline
.C:c003 A9 C0 LDA #$C0 ; add #$C0 (+ carry = #$C1) ...
.C:c005 65 65 ADC $65 ; ... to parameter
.C:c007 85 FB STA $FB ; and store in $FB
.C:c009 A2 00 LDX #$00 ; loop index
.C:c00b .loop:
.C:c00b BD 2B C0 LDA .bucket,X ; loop over encoded string
.C:c00e F0 1A BEQ .done ; null-terminator -> done
.C:c010 10 12 BPL .out ; positive (bit 7 clear) -> output
.C:c012 C5 FB CMP $FB ; compare with parameter+#$C1
.C:c014 90 04 BCC .digit ; smaller -> convert to digit
.C:c016 A9 20 LDA #$20 ; otherwise load space character
.C:c018 D0 0A BNE .out ; and output
.C:c01a .digit:
.C:c01a 69 70 ADC #$70 ; add offset to '0' (#$30)
.C:c01c .check:
.C:c01c C9 3A CMP #$3A ; greater than '9' (#$39) ?
.C:c01e 90 04 BCC .out ; no -> to output
.C:c020 E9 0A SBC #$0A ; otherwise subtract 10 (#$a)
.C:c022 B0 F8 BCS .check ; and check again
.C:c024 .out:
.C:c024 20 D2 FF JSR $FFD2 ; output character
.C:c027 E8 INX ; next index
.C:c028 D0 E1 BNE .loop ; and repeat loop
.C:c02a .done:
.C:c02a 60 RTS ; exit ....
.C:c02b .bucket:
.C:c02b 20 20 20 [...] ; "encoded" string for bucket
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 64 bytes
```
Nθ³↑⁵‖M←F²«‖J⁻³ι±¹F⊘⁺θ¬ι«↖I﹪⁺⊗κ⊕ιχM§”)⊟E≡≦⌈▷⊖ü∕”κ§”)⊟&hXτtD(λM”κ
```
[Try it online!](https://tio.run/##PY3BasMwEETP9leInFaggmzHl/RU2kNd6hBK@wGOvW5FZclRJFMo@XZ3rTSGZdlZ3sy0X41rbaPnuTJj8PswHNHBid@nB6eMh2K9dh@jYCXJN@w1tr5WzlkHu1fsPX176xjknP2myT8A9E1ewjC@W6iVCWcoBFNcsD1@Nh4h4wsQfc@NnrCDgyboRID1oDiPYcnavhQJ9ticPdS2C9pe@ScbjprM35RcmdbhgMaTpgDBMsljS1LbCeHBV6bDH9hIWdymzJe9lXRJuRFsiVm5LJO3KTOZR0Nkr@SSfEkv81xu57tJ/wE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the number.
```
³↑⁵‖M←
```
Draw half of the bucket and then mirror it to complete the bucket.
```
F²«
```
Loop for each side of the bucket.
```
‖J⁻³ι±¹
```
Reflect the bucket so that we can draw in a consistent direction on both loops, and jump to the position of the first digit on that side of the bucket.
```
F⊘⁺θ¬ι«
```
Loop over the number of digits on that side of the bucket.
```
↖I﹪⁺⊗κ⊕ιχ
```
Print the next digit and move the cursor up and left.
```
M§”)⊟E≡≦⌈▷⊖ü∕”κ§”)⊟&hXτtD(λM”κ
```
Adjust the cursor position by reading the offsets from two compressed strings, `003003003005203004000500` (horizontal offsets) and `11011011011510200300040000` (vertical offsets). These offsets take the above cursor movement into account which conveniently means that they never have to be negative.
] |
[Question]
[
# Task
Encode a string that entirely consists of uppercase alphabets (`A-Z`) using only zeros and ones, using your own favorite scheme. But the rule isn't that simple!
# Rules
1. Your program/function must correctly handle any valid input string of **length 8**.
2. The results must have the same length for all inputs.
3. The results must be distinct for distinct inputs.
4. The results must be as short as possible.
5. The results must be zero-one balanced (have number of ones **similar** to that of zeros). They don't have to be equal (i.e. perfectly balanced), but your score will be penalized for that.
You don't have to provide a program/function that decodes your encoding.
# Input and Output
* You can decide to accept any set of 26 distinct **printable ASCII characters** instead of `A-Z`.
* You can decide to output any pair of distinct **printable ASCII characters** instead of `0` and `1`.
* You are **not allowed to output an integer** instead of a bit string, since it may have leading zeros and it's unclear if you actually met the rule 2.
* If you decide to deviate from the default (`A-Z` input and `01` output), you must specify the input/output character sets in your submission.
# Scoring
* Base score: Code size, or 1 if your program happens to be empty.
* Penalties
+ Penalty for length: multiply `1.5 ** (encoded length - 42)`
+ There is no bonus for being shorter; 42 is the minimal length for a perfectly balanced encoding of 8-length strings with alphabet size 26.
+ Penalty for being unbalanced: multiply `2 ** max(abs(ones - zeros) for every valid input of length 8)`, where `ones` and `zeros` are the counts of 1 and 0 in each output, respectively.
+ Your submission must either show a worst-case example (input/output) or theoretical explanation on the penalty value.
* The lowest score wins.
# Example Submission
## Hypothetical esolang, 0 Bytes, Score 74733.8906
Here is a hypothetical esolang, where an empty program prints out all the ASCII codes of input's characters in binary.
```
```
For example, if you give `AAAAAAAA` as input, the program will print `1000001` 8 times in a row, i.e. `10000011000001100000110000011000001100000110000011000001`.
The input alphabet is chosen to be `CEFGIJKLMNQRSTUVXYZabcdefh`. This way, all of the chars are converted to seven digits in binary, and the zero-one counts differ only by one per char (they all have three 1's and four 0's or vice versa when converted to binary).
The output length is always 56, and the worst-case unbalance occurs on the inputs like `CCCCCCCC`, where zeros appear 8 more times than ones.
Therefore, the score of this submission is `1.5 ** (56 - 42) * 2 ** 8 == 74733.8906`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 bytes, 0 penalty, Score 11
This program uses `[0-9A-P]` for input and `[01]` for output.
```
ö■▄←·ï↨≡⌐╠H
```
[Run and debug it online](https://staxlang.xyz/#c=%C3%B6%E2%96%A0%E2%96%84%E2%86%90%C2%B7%C3%AF%E2%86%A8%E2%89%A1%E2%8C%90%E2%95%A0H&i=%2200000000%22%0A%2200000001%22%0A%220000000P%22%0A%2200000010%22%0A%220000ABCD%22%0A%22PPPPPPPP%22&m=2) - click the run button to start. The first four test cases run in milliseconds. The fifth in seconds. The sixth in millenia.
The corresponding ascii representation of this program is this.
```
A$21*,26|bD|N
```
It leans heavily on the `|N` instruction, which gets the subsequent permutation of an array.
```
A$21* "10" repeated 21 times
,26|b get input and decode it as a base 26 number
D|N ... that many times get the next lexicographic permutation
```
All outputs are permutations of the initial string. It has 21 zeroes and 21 ones. Therefore, all outputs are 42 characters, and perfectly balanced.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
2Ḷx21Œ!Q
O_65ḅ26ị¢
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//MuG4tngyMcWSIVEKT182NeG4hTI24buLwqL///9HSFFJRktTQQ "Jelly – Try It Online")
-1 byte thanks to caird coinheringaahing
might remember to re-add the explanation since it was restructured for golfing
[Answer]
## Pyth, ~~20~~ ~~19~~ 14 bytes, Max Diff: 0, Length: 64, Score: ~~149636.5528~~ ~~142154.7251~~ 104745.5869
```
sm@S.{.p*`T4xG
```
[Try it online!](https://tio.run/##K6gsyfj/vzjXIVivWq9AKyHEpML9/3@ljMz0/Jy01CIlAA)
Uses the lower case alphabet (`[a-z]`) instead of uppercase. Can use uppercase by replacing `G` with `rG1`, at the cost of 2 bytes.
I could have translated [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino)['s Python 3 answer](https://codegolf.stackexchange.com/questions/157238/balanced-zero-one-encoding/157245#157245) for a better score, but frankly, I want an answer that actually works.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~779~~ 645 bytes, Max(Diff) = 0, Length = 48, Score = 7346.95
```
def f(s):
a,b=0,""
for i in s:a=a*26+ord(i)-65
a+=56*252**4
for i in range(5):b=bin((int("4lnk28t9vtqgfrpfda9uyfrjhcjwjvno6aec2nwegi0g4mnublc05dher8fjm4s5gh55lu87a4itmc74t6tozcsfdbxkg82frwljy0wam1jht98g2j0bma021v5d48pwq0fklv0n1ltrxft1fpk5gt5mx5fj4p2mjqqpvcylt1xayxf1iwdmyoxgfvl7oui1oo6147bm9rqpqut9ns8hhjc77t3pqy48otovrsm1t4mmleumspkuef66ma1vi0l4mtkwaeeizuvvds9fro3vhc0mrn6ox17rdpk7xw747qf28934u5jci5q1qj81i7dyf7rf0x7hb19xm93xhxsgh4w8ifs6fhynsddbo9j938ewfvhjlbpiz50n5hanmno6c89blyx50e89z7vjq2ho2r2u2wwyu4q18kv4fi1nhmfbgjbnkdayr5kblaped4fo5u97bi9a67d89irxa0r9cinmnohfgjmh5fhkcr33",36)>>a%252*10)&1023)[2:].rjust(10,"0")+b;a/=252
return b[2:]
```
[Try it online!](https://tio.run/##TZLNjtsgAITveQrLUqs4u20Bg4FUWamv0aoHsI0BG7Ax/svLp1lpVe0cR5/mMPrGI@ng0ePRtCpT57m4njLxKm/gNc9PmQoxM5nx2XwVN3FB1UuIzdkU3yryxF5upLoggi4X/AmNwnftmRRXeZPGn8/Gp3OOB98jlviapk7FUTWCL4eKVtd2s6sPlWhr5Le2M6DDzi9yqAFpdBuZsg7PpNOEDAujApvkaopTlcK9nlUj975jSMVtsAfYhINWJ846ZIF0AiC4kgazcZuA6ocVeDikuKsE1diTLhG3E2XxiJydpnGtjyHBXRy7gmZr3BH2Tq0DDYuBIVQQU@l4nMZpSdzPTGtbU5rKcTowCymscXYwYeeGdnHz2C@tqion4GrAgF3qN9G25r6sazNzFUO56hq46KuwQxqbsaf7RjGdFGK8xAuxtSETnCyDhjaHolGBnWoJ@e54uet97jTemFFzpfTh56aRgVtesnZTq7aDHM2dAE@08O55b824HI6dgJbxO13thHRAES1o244FT5D1K1YGeu2U7Kz0fSOOSHo5iLFtsApk4VQaLiraMG7iLkDktXmf1qqzThOl@zqWZf5aVsXbm/jyrgUExVcIUFn8Qde/36Nd5nSGT7FAXrzIn@LH7QmdstimJfpMvkOPMT51eXqY//pIXpz@d78/khePfw "Python 2 – Try It Online")
The magic number
`4lnk28t9vtqgfrpfda9uyfrjhcjwjvno6aec2nwegi0g4mnublc05dher8fjm4s5gh55lu87a4itmc74t6tozcsfdbxkg82frwljy0wam1jht98g2j0bma021v5d48pwq0fklv0n1ltrxft1fpk5gt5mx5fj4p2mjqqpvcylt1xayxf1iwdmyoxgfvl7oui1oo6147bm9rqpqut9ns8hhjc77t3pqy48otovrsm1t4mmleumspkuef66ma1vi0l4mtkwaeeizuvvds9fro3vhc0mrn6ox17rdpk7xw747qf28934u5jci5q1qj81i7dyf7rf0x7hb19xm93xhxsgh4w8ifs6fhynsddbo9j938ewfvhjlbpiz50n5hanmno6c89blyx50e89z7vjq2ho2r2u2wwyu4q18kv4fi1nhmfbgjbnkdayr5kblaped4fo5u97bi9a67d89irxa0r9cinmnohfgjmh5fhkcr33` (in base 36), or its decimal equivalent `382136276621246556626597379364678993894472503063952720559883124988542417847157286833446006767955087631166943136913765901237281892296575754126024183763829277879554548743231384272055945084065681774297483130020386641869860456147616177702938121538230311395513497506285733567467605871232294046704309941152721616618474501854355102646152223338484615876165254236449912858255665248186687952137487016925761633237335983620006273901509768720506129789443353730706676483647298576692613113269388239830925662977837917272690235355742330377154505179476767457756888107428475384947712227312747517748632498691058764154580934614231152483398774630508576533263098942260213967880819240793990219283490212843120923539516962682466148372296338428497778127570401190309339992457562121354271`, encodes all 252 permutations of 5 `0`s and 5 `1`s.
The algorithm first converts `A-Z` into `0-25` and treat it as a base-26 number, then add `56*252**4`.
Then, the number is converted to a 5-digit base-252 number, and substitute with the corresponding permutation of 5 `0`s and 5 `1`s.
After that, delete the first 2 bits, which is guaranteed to be `01`. Then we have encoded the string to a 48-bit string, which consists of exactly 24 `0`s and 24 `1`s.
[Answer]
## JavaScript (ES8), score 22186.623779296875
```
f=
s=>s.replace(/./g,(c,i)=>(i%2*127^c.charCodeAt()).toString(2).padStart(7,0))
```
```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
For even length input, always outputs 3.5\* of zeros and ones, so it only pays the 1.5 \*\* 14 penalty. Supported characters: `'+-.3569:<GKMNSUVYZ\cefijlqrtx`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
42ɠO%ḅ26ịœcH$ạ‘Ṭ
```
Uses `+,-./0123456789:;<=>?@ABCD` for input and returns a list of ones and zeroes.
This attempts to build a list of 538,257,874,440 combinations in memory, so you'll need a large amount of RAM to run it as is...
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//MTjJoE8lKzI0JOG4hTI24buLxZNjSCThuqHigJjhuaz//0RBRA "Jelly – Try It Online") (testable; input length 3, output length 18)
### How it works
```
42ɠO%ḅ26ịœcH$ạ‘Ṭ Main link. No arguments.
42 Set the argument and the return value to 42.
ɠ Read one line from STDIN.
O Ordinal; map ['+', ..., 'D'] to [43, ..., 69].
% Take the code points modulo 42, mapping [43, ..., 69] to
[1, ..., 26].
ḅ26 Convert the result from base 26 to integer.
$ Combine the two links to the left into a monadic chain.
H Halve; yield 21.
œc Generate all 21-combinations of [1, ..., 42].
There are 538,257,874,440 of these combinations. The first
269,128,937,220 begin with a 1.
ị Retrieve the combination at the index to the left.
[26, 26, 26, 26, 26, 26, 26, 26] in bijective base 26 equals
217,180,147,158 in decimal, so the retrieved combination will
begin with a 1.
‘ Increment; yield 43.
ạ Absolute difference; map [1, ..., 42] to [42, ..., 1].
The combination now begins with a 42.
Ṭ Untruth; turn the combination into a Boolean list, with 1's
at the specified indices and 0's elsewhere.
Since the maximum of the combination is 42, this list will have
exactly 42 items, 21 of which will be 1's.
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~985~~ 135 bytes, Max Diff 0, Length 42, score 135
```
lambda s:C(int(s,26),21,20)
B=lambda x,y:y<1or-~x*B(x+1,y-1)//y
def C(n,o,z):p=B(o,z);x=n>=p;return z+1and[x]+C(n-p*x,o-x,z-1+x)or[1]*o
```
[Try it online!](https://tio.run/##Tc8xT8MwEAXgPb/iNvsSh9YuFJRiJBKgbHQPGYzSiCBqW3YqORn46wFDQbzpk@5JT2fH4dXo1dzJ5/ldHV5aBb6oaK8H6plYIxOciSUmpTxdAxuL8Zobl3@EtKQh42zMOS4WY9LuO6ioZoZNWFhZ0ohNkPpG2o3bD0enYcq40m0dmuyrmds0MJMHNuU8C2hczZvUzJ1x4KHXUJPlKYTBr3k0F6vzi/XlVfRtWd3dP2wfo3c/efrnHWmKBBRI6KjHBKyLzxFy9mZ6Tf3gvp8NiBB3Q9xV@NfzxwNVKKXgOH8C "Python 3 – Try It Online")
Courtesy of Bubbler
Ungolfed code:
```
import math
def binomial(x, y):
return math.factorial(x) // math.factorial(y) // math.factorial(x - y)
def string_to_int(input_str):
result = 0
for i in range(0,8):
result += (ord(input_str[i])-65)%26 * pow(26,i)
return result
def counting_function(target, ones, zeros):
if zeros > 0:
position = binomial(ones+zeros-1,zeros-1)
else:
position = 1
if target > position:
if ones > 0:
print("1", end='')
ones -= 1
counting_function(target-position,ones,zeros)
else:
if zeros > 0:
print("0", end='')
zeros -= 1
counting_function(target,ones,zeros)
elif ones > 0:
print("1", end='')
ones -= 1
counting_function(target,ones,zeros)
input_str = input("Input string (A-Z): ")
input_int = string_to_int(input_str)+1
target = input_int
ones = 21
zeros = 21
counting_function(target, ones, zeros)
print("")
```
Since other approaches seem quite inefficient, I've tried to make a time-optimal one. It is clealy O(N) in N bits of encoding, which is big-O optimal.
Hint: try to think of Pascal's triangle for this one ([this diagram](https://en.wikipedia.org/wiki/Pascal%27s_triangle#/media/File:Pascal%27s_triangle_pathways.svg) reveals it)
Sample outputs:
```
Input: AAAAAAAA
Output: 000000000000000000000111111111111111111111
```
```
Input: ZZZZZZZZ
Output: 011001000000011010011000111010110110111110
```
Execution time: < 0.013 s (roughly constant for all inputs)
[Answer]
# [Perl 5](https://www.perl.org/), 55 bytes, max diff 0, length 42, score ~~56~~ 55
This works but will take a long but doable time (`ZZZZZZZZ` took 2.5 days on my computer). Memory is no problem.
Uses `A-Z` as input and `1` and `A` as encoding characters. They are always perfectly balanced. Skips the first `26^7 = 8031810176` balanced combinations representing string shorter than 8 characters, but that's OK since there are `538257874440` available and I use `208827064575` and `208827064575 + 8031810176 < 538257874440`.
However it actually "counts" up to to the target combination which will take very long. That's why in the TIO link I only used a too short input string (which are also supported) to demonstrate that the output is correct. Will work up to a bit more than `AAAAAA` before TIO times out.`ZZZZZZZZ` should be about `26^3 = 17576` times slower.
```
#!/usr/bin/perl -ap
$_=1x21 .($i=A)x21;s/(A*)(1*)1A/$2$1A1/ until"@F"eq$i++
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2igZ2D9XyXe1rDCyFBBT0Ml09ZRE8i0LtbXcNTS1DDU0jR01FcxUjF0NNRXKM0rycxRcnBTSi1UydTW/v/f0cnZxfVffkFJZn5e8X/dgkQA "Perl 5 – Try It Online")
The decoder is almost the same:
```
#!/usr/bin/perl -ap
$_=1x21 .($\=A)x21;s/(A*)(1*)1A/$2$1A1/,$\++until"@F"eq$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2igZ2D9XyXe1rDCyFBBT0MlxtZRE8i0LtbXcNTS1DDU0jR01FcxUjF0NNTXUYnR1i7NK8nMUXJwU0otVImvrf7/3xAIHCHIEcGGsBxRwL/8gpLM/Lzi/7oFiQA "Perl 5 – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 75 bytes, Max Diff 0, Length 42, score 75
```
0i:0(?v'A'-$dd+*+!
.")1+.\1+:0$:2%:}:@-2,@+$bl"
[ab+-?\$:?vv~3
~~]>n<v$-1<>
```
[Try it online!](https://tio.run/##S8sszvj/3yDTykDDvkzdUV1XJSVFW0tbkUtPSdNQWy/GUNvKQMXKSNWq1spB10jHQVslKUeJKzoxSVvXPkbFyr6srM6Yq64u1i7PpkxF19DG7v9/RygAAA "><> – Try It Online")
Fair warning, this will take a very *very* ***very*** long time to complete even for the trivial `AAAAAAAA` case. Runs through each binary representations of a counter until the (base 26 representation of the input)'th binary number with 21 `1`s is reached. If you want to test the program somewhat you can replace the `ab+` on the third line with `1` which will return the nth binary number with just a single `1`, [Try it online!](https://tio.run/##S8sszvj/3yDTykDDvkzdUV1XJSVFW0tbkUtPSdNQWy/GUNvKQMXKSNWq1spB10jHQVslKUeJK9pQQUHXPkbFyr6srM6Yq64u1i7PpkxF19DG7v9/RwiIAgA "><> – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes, Max Diff 0, Length 42, Score 112
```
lambda s:sorted({*permutations("01"*21)})[int(s,26)]
from itertools import*
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqji/qCQ1RaNaqyC1KLe0JLEkMz@vWEPJwFBJy8hQs1YzOjOvRKNYx8hMM5YrrSg/VyGzJLWoJD8/p1ghM7cAqFnrf0ERSE2aRmZeQWmJhqam5n83DxcXT38vNwA "Python 3 – Try It Online")
This only works in theory because of memory constraints. There are `538257874440` distinct balanced zero-one strings of length 42 and `208827064575` possible inputs, so some of the possible outputs will not be used.
-37 bytes thanks to @recursive
[Answer]
# C++, 146 Bytes, 42 maxlength, 0 unbalance, score 146
```
#include<algorithm>
long long i,s;int f(char*I,char*O){for(O[i=42]=s=0;i--;i<8?s=s*26+I[i]:0)O[i]=i%2|48;for(;s--;)std::next_permutation(O,O+42);}
```
Works for any continious 26 char, but warning it runs an unacceptable time
] |
[Question]
[
**Motivation**: Sometimes you need to know where you are in a string. You want to be able to look at any part of a string and know exactly where you are, as far as possible.
**Challenge**: write a program to output a **tape measure string** of a given length. A **tape measure string** self describes its length-so-far as often as possible along it's own length.
**Rules**:
1. Your program must take one positive integer parameter, for the total length of the tape measure string
2. For each contiguous string of digits in the output, these digits must accurately report the length of the output so far - **inclusive**!
1. Lengths are measured from the start of the string to the **end** of each number
3. As many length numbers as possible should be included in the string
4. Avoid ambiguity. Separators/delimiters can be used to avoid numbers being juxtaposed, i.e. `12` says twelve not one, two.
5. The string must always accurately report its total length at its end, with no trailing separators
6. You may need multiple separators to keep the lengths accurate, e.g. here's an example tape measure string of length 4: `1--4`
**Non prescriptive/exhaustive examples:**
* tape measure string of length 1: `1`
* tape measure string of length 2: `-2`
* tape measure string of length 3: `1-3`
* tape measure string of length 4: `1--4` or `-2-4` (both report lengths as often as possible, i.e. twice, and end with the correct total length)
* tape measure string of length 10: `1-3-5-7-10`
* tape measure string of length 11: `1-3-5-7--11` or `1-3-5--8-11` or `1-3--6-8-11` or `1--4-6-8-11` or `-2-4-6-8-11` (all have as many length numbers as possible, and finish with the total string length)
[Answer]
# Python, ~~50~~ ~~48~~ ~~47~~ 46 bytes
```
f=lambda x:x*"1"if x<2else f(x-len(`-x`))+`-x`
```
# Explanation
Pretty simple recursive lambda solution
Our base cases are 1 and 0 which are covered by `"1"*x` otherwise we get the string of `-x` with ``-x`` and prepend the result of calling the function on `len(`-x`)` less.
[Answer]
# Mathematica, ~~67~~ 57 bytes
*Thanks to Martin Ender for jettisoning 10 bytes!*
```
""["1"][[#]]/._@__:>#0[#-1-IntegerLength@#]<>ToString@-#&
```
Unnamed function taking a nonnegative integer argument and returning a string. Pretty much the obvious recursive algorithm: make sure the string ends with the input number preceded by a `"-"`, and then call the function again using `#0`.
But there's golfy fun to be had in implementing the algorithm. `""["1"][[#]]` denotes the `#`th argument of the expression `""["1"]`: the 0th argument is the head `""` and the 1st argument is visibly `"1"`, which provides the base cases of the recursion. If `#` exceeds 1, then `""["1"][[#]]` throws an error message and remains as an unevaluated function. But then `/._@__:>` is a rule that takes any unevaluated function and transforms it into the expression that comes next, which is the recursive call to the original function.
Original submission:
```
If[#<2,""["1"][[#]],#0[#-1-IntegerLength@#]<>"-"<>IntegerString@#]&
```
[Answer]
## JavaScript (ES6), 49 bytes
```
f=(n,s='',t=''+-n)=>n>1?f(n-t.length,t+s):n?n+s:s
```
```
<input type=number oninput=o.value=f(this.value)><br><textarea id=o></textarea>
```
[Answer]
# Pyth, 23 bytes
```
L?<b2*"1"b+y-bl+""_bs_b
```
Blatantly stole the recursive solution from [Wheat wizard's](https://codegolf.stackexchange.com/a/106847/47650) answer. Also, I believe this is not golfed properly.
[Try it here!](http://pyth.herokuapp.com/?code=L%3F%3Cb2%2A%221%22b%2By-bl%2B%22%22_bs_b%0Ay1%0Ay2%0Ay3%0Ay4%0Ay11%0Ay0&debug=0)
[Answer]
# [Perl 6](http://perl6.org/), 43 bytes
```
{[R~](-$_,{$_+.comb}...^*>-1).&{S/^\-1/1/}}
```
Explanation:
```
{ } # A lambda.
... # Generate a sequence...
-$_ # starting from the negated lambda argument,
,{ } # continuing iteratively using the formula:
$_+.comb # Last element plus length of last element.
*>-1 # until we hit 0 or higher,
^ end-point not inclusive.
[R~]( ) # Reverse and concatenate the number sequence.
.&{ } # Apply to this the transformation:
S/^\-1/1/ # Remove the sign from a leading "-1".
```
So for example for input 10, it generates the sequence `(-10, -7, -5, -3, -1)`, and from that the string `-1-3-5-7-10`, and from that the final string `1-3-5-7-10`.
[Try it online](https://tio.run/#z43T1).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 68 bytes
```
f(n){int*j;n<2?j="1"+!n:printf(f(n-asprintf(&j,"%d",-n)));return j;}
```
[Try it online!](https://tio.run/##LYzBDsIgEETv/Qok0bBSkuKxtPFbGhSzJK4NpaeGb8dtdW7z3mS8eXlfa1AEG1K@RkfD7R5HaaU@UT8nhkGxNtPyL5fYyvNDtoYAwKVnXhOJ6EplK94TkoKtEZzwSWpnOFqHg@06h1rDoX6DPfOaF/5HvjpYaUr9Ag "C (gcc) – Try It Online")
Borrows [@Wheat Wizard's recursive solution.](https://codegolf.stackexchange.com/a/106847/80050)
] |
[Question]
[
# Introduction
Time is confusing. Sixty seconds to a minute, sixty minutes to an hour, twenty-four hours to a day (and not to mention that pesky am/pm!).
There's no room for such silliness nowadays, so we've decided to adopt the only sensible alternative: decimal days! That is to say, each day is considered 1 whole unit, and anything shorter is written as a decimal fraction of that day. So, for example: "12:00:00" would be written as "0.5", and "01:23:45" might be written as "0.058159".
Because it will take time to get used to the new system, you are tasked with writing a program that can convert between them in both directions.
# Challenge
Write a program in the language of your choice, that given a modern time in the ISO-8601 format of "hh:mm:ss", will return the equivalent decimal fraction unit. Likewise, given a decimal fraction, the program should return the time in the modern format initially specified.
You can make the following assumptions:
* The modern time input and output can range from "00:00:00" to "24:00:00"
* The decimal time input and output can range from "0" to "1", and should be able to accept/output up to at least 5 decimal places (such as "0.12345"). More precision is acceptable
* The program should be able to know which conversion direction to perform based on input
* You cannot use time related functions/libraries
The winner will be determined by the shortest code that accomplishes the criteria. They will be selected in at least 7 decimal day units, or if/when there have been enough submissions.
# Examples
Here's a(n intentionally) poorly written piece of JavaScript code to be used as an example:
```
function decimalDay(hms) {
var x, h, m, s;
if (typeof hms === 'string' && hms.indexOf(':') > -1) {
x = hms.split(':');
return (x[0] * 3600 + x[1] * 60 + x[2] * 1) / 86400;
}
h = Math.floor(hms * 24) % 24;
m = Math.floor(hms * 1440) % 60;
s = Math.floor(hms * 86400) % 60;
return (h > 9 ? '' : '0') + h + ':' + (m > 9 ? '' : '0') + m + ':' + (s > 9 ? '' : '0') + s;
}
decimalDay('02:57:46'); // 0.12344907407407407
decimalDay('23:42:12'); // 0.9876388888888888
decimalDay(0.5); // 12:00:00
decimalDay(0.05816); // 01:23:45
```
[Answer]
# CJam, ~~58 56~~ 42 bytes
I am sure this is too long and can be golfed a lot. But here goes for starters:
```
86400q':/:d_,({60bd\/}{~*i60b{s2Ue[}%':*}?
```
[Try it online here](http://cjam.aditsu.net/#code=86400q'%3A%2F%3Ad_%2C(%7B60bd%5C%2F%7D%7B~*i60b%7Bs2Ue%5B%7D%25'%3A*%7D%3F&input=0.9998842592592593)
[Answer]
# Python 2, ~~159~~ ~~150~~ 141 + 2 = 143 Bytes
Straightforward solution, can probably be much shorter. Will work on it.
*Added two bytes to account for input needing to be enclosed in "s. Also, Sp3000 pointed out an issue with eval() interpreting octals, and showed a way to shorten formatting, use map() and remove one print.*
```
n=input();i=float;d=864e2
if':'in n:a,b,c=map(i,n.split(':'));o=a/24+b/1440+c/d
else:n=i(n);o=(':%02d'*3%(n*24,n*1440%60,n*d%60))[1:]
print o
```
[Check it out on ideone here.](http://ideone.com/WVPBAO)
[Answer]
# Javascript (*ES6*), 116 110 bytes
```
f=x=>x[0]?([h,m,s]=x.split(':'),+s+m*60+h*3600)/86400:[24,60,60].map(y=>('0'+~~(x*=y)%60).slice(-2)).join(':')
// for snippet demo:
i=prompt();
i=i==+i?+i:i; // convert decimal string to number type
alert(f(i))
```
**Commented:**
```
f=x=>
x[0] ? // if x is a string (has a defined property at '0')
([h, m, s] = x.split(':'), // split into hours, minutes, seconds
+s + m*60 + h*3600) // calculate number of seconds
/ 86400 // divide by seconds in a day
: // else
[24, 60, 60]. // array of hours, minutes, seconds
map(y=> // map each with function
('0' + // prepend with string zero
~~(x *= y) // multiply x by y and floor it
% 60 // get remainder
).slice(-2) // get last 2 digits
).join(':') // join resulting array with colons
```
[Answer]
## Python 3: 143 Bytes
```
i,k,l,m=input(),60,86400,float
if'.'in i:i=m(i)*l;m=(3*':%02d'%(i/k/k,i/k%k,i%k))[1:]
else:a,b,c=map(m,i.split(':'));m=(a*k*k+b*k+c)/l
print(m)
```
Same byte count as the python 2 solution but it seems we took different approaches to the maths.
[Answer]
# Julia, ~~152~~ ~~143~~ 142 bytes
Well, I updated my approach to be less "Julian," as they say, for the sake of golfing. For a better (though less concise) approach, see the revision history.
```
x->(t=[3600,60,1];d=86400;typeof(x)<:String?dot(int(split(x,":")),t)/d:(x*=d;o="";for i=t q,x=x÷i,x%i;o*=lpad(int(q),2,0)*":"end;o[1:end-1]))
```
This creates an unnamed function that accepts a string or a 64-bit floating point number and returns a 64-bit floating point number or string, respectively. To call it, give it a name, e.g. `f=x->...`.
Ungolfed + explanation:
```
function f(x)
# Construct a vector of the number of seconds in an hour,
# minute, and second
t = [3600, 60, 1]
# Store the number of seconds in 24 hours
d = 86400
# Does the type of x inherit from the type String?
if typeof(x) <: String
# Compute the total number of observed seconds as the
# dot product of the time split into a vector with the
# number of seconds in an hour, minute, and second
s = dot(int(split(x, ":")), t)
# Get the proportion of the day by dividing this by
# the number of seconds in 24 hours
s / d
else
# Convert x to the number of observed seconds
x *= d
# Initialize an output string
o = ""
# Loop over the number of seconds in each time unit
for i in t
# Set q to be the quotient and x to be the remainder
# from x divided by i
q, x = divrem(x, i)
# Append q to o, padded with zeroes as necessary
o *= lpad(int(q), 2, 0) * ":"
end
# o has a trailing :, so return everything up to that
o[1:end-1]
end
end
```
Examples:
```
julia> f("23:42:12")
0.9876388888888888
julia> f(0.9876388888888888)
"23:42:12"
julia> f(f("23:42:12"))
"23:42:12"
```
[Answer]
# C, 137 bytes
Full C program. Takes input on stdin and outputs on stdout.
```
main(c){float a,b;scanf("%f:%f:%d",&a,&b,&c)<3?c=a*86400,printf("%02d:%02d:%02d",c/3600,c/60%60,c%60):printf("%f",a/24+b/1440+c/86400.);}
```
Ungolfed and commented:
```
int main() {
// b is float to save a . on 1440
float a,b;
// c is int to implicitly cast floats
int c;
// If the input is hh:mm:ss it gets splitted into a, b, c
// Three arguments are filled, so ret = 3
// If the input is a float, it gets stored in a
// scanf stops at the first semicolon and only fills a, so ret = 1
int ret = scanf("%f:%f:%d", &a, &b, &c);
if(ret < 3) {
// Got a float, convert to time
// c = number of seconds from 00:00:00
c = a * 86400;
printf("%02d:%02d:%02d", c/3600, c/60 % 60, c%60);
}
else {
// a = hh, b = mm, c = ss
// In one day there are:
// 24 hours
// 1440 minutes
// 86400 seconds
printf("%f", a/24 + b/1440 + c/86400.);
}
}
```
[Answer]
# J, 85 bytes
Results:
T '12:00:00'
0.5
T 0.5
12 0 0
T '12:34:56'
0.524259
T 0.524259
12 34 56
```
T=:3 :'a=.86400 if.1=#y do.>.(24 60 60#:y*a)else.a%~+/3600 60 1*".y#~#:192 24 3 end.'
```
Total 85
[Answer]
# Javascript, ~~194~~ ~~192~~ ~~190~~ 188 bytes
```
function(z){if(isNaN(z)){x=z.split(':');return x[0]/24+x[1]/1440+x[2]/86400}h=(z*24)|0;h%=24;m=(z*1440)|0;m%=60;s=(z*86400)|0;s%=60;return""+(h>9?'':0)+h+':'+(m>9?'':0)+m+':'+(s>9?'':0)+s}
```
[Answer]
# JavaScript ES6, ~~98~~ 130 bytes
```
s=>s==+s?'246060'.replace(/../g,l=>':'+('0'+~~(s*=+l)%60).slice(-2)).slice(1):s.split`:`.reduce((a,b)=>+b+(+a)*60)*1/864e2;f(0.5);
```
[Answer]
# C, ~~156~~ 152 bytes
I thought it is going to be easy for C. But still ended up quite large. :(
```
n,m=60;d(char*s){strchr(s,58)?printf("%f",(float)(atoi(s)*m*m+atoi(s+3)*m+atoi(s+6))/m/m/24):printf("%02d:%02d:%02d",(n=atof(s)*m*m*24)/m/m,n/m%m,n%m);}
```
Test Program:
```
#include <stdio.h>
#include <stdlib.h>
int n,m=60;
d(char*s)
{
strchr(s,':') ?
printf("%f",(float)(atoi(s)*m*m+atoi(s+3)*m+atoi(s+6))/m/m/24):
printf("%02d:%02d:%02d",(n=atof(s)*m*m*24)/m/m,n/m%m,n%m);
}
int main()
{
d("01:23:45");
printf("\n");
d("02:57:46");
printf("\n");
d("23:42:12");
printf("\n");
d("12:00:00");
printf("\n");
d("0.5");
printf("\n");
d("0.05816");
printf("\n");
d("0");
printf("\n");
d("1");
printf("\n");
return 0;
}
```
Output:
```
0.058160
0.123449
0.987639
0.500000
12:00:00
01:23:45
00:00:00
24:00:00
```
[Answer]
# PHP, ~~70~~ 69 bytes
```
<?=strpos($t=$argv[1],58)?strtotime($t)/86400:date("H:i:s",$t*86400);
```
takes input from command line argument, prints to STDOUT:
If input contains a colon, convert to unix time and divide by (seconds per day),
else multply numeric value with (seconds per day) and format unix time to `hh:mm:ss`.
[Answer]
# Perl, ~~109~~ ~~108~~ 101 + 6 (`-plaF:` flag) = 107 bytes
```
$_=$#F?($F[0]*60+$F[1]+$F[2]/60)/1440:sprintf"%02d:%02d:%02d",$h=$_*24,$m=($h-int$h)*60,($m-int$m)*60
```
Using:
```
perl -plaF: -e '$_=$#F?($F[0]*60+$F[1]+$F[2]/60)/1440:sprintf"%02d:%02d:%02d",$h=$_*24,$m=($h-int$h)*60,($m-int$m)*60' <<< 01:23:45
```
[Try it on Ideone.](http://ideone.com/6pWG2B)
[Answer]
# Excel, 178 bytes
```
=IF(LEFT(A1,2)="0.",TEXT(FLOOR(A1*24,1),"00")&":"&TEXT(MOD(FLOOR(A1*1440,1),60),"00")&":"&TEXT(MOD(FLOOR(A1*86400,1),60),"00"),((LEFT(A1,2)*60+MID(A1,4,2))*60+RIGHT(A1,2))/86400)
```
] |
[Question]
[
For those with a little linear algebra background, the challenge is as simple as this: determine the [eigenvalues and eigenvectors](http://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors) of a given complex 2x2 matrix. You may skip ahead to The Challenge for I/O details, etc. For those who need a little refresher on eigensystems, read on.
## Background
The [characteristic equation](http://en.wikipedia.org/wiki/Characteristic_polynomial) of a matrix \$A\$ is defined by
$$\det| A - λI | = 0$$
where \$λ\$ is a complex (scalar) parameter, \$I\$ is the identity matrix and \$\det|...|\$ is the [determinant](http://en.wikipedia.org/wiki/Determinant). The left-hand side evaluates to a polynomial in \$λ\$, the *characteristic polynomial*, which is quadratic in the case of 2x2 matrices. The solutions of this characteristic equation are the *eigenvalues* of \$A\$, which we will denote as \$λ\_1\$ and \$λ\_2\$.
Now the *eigenvectors* \$v\_i\$ of \$A\$ satisfy
$$Av\_i = λ\_iv\_i$$
For each \$λ\_i\$, this gives you a system of two equations in two unknowns (the components of \$v\_i\$), which can be solved quite easily. You will notice that the system is actually underspecified, and the magnitude of the eigenvectors are not determined by the equations. We will usually want the eigenvectors to be normalised, that is \$\sqrt{|x|^2 + |y|^2} = 1\$, where \$x\$ and \$y\$ are the vector components, \$|x|^2\$ is \$x\$ multiplied by its complex conjugate.
Note that the eigenvalues may be degenerate, i.e. \$λ\_1 = λ\_2\$. In this case, you may or may not be able to satisfy the single system of equations with two linearly independent eigenvectors.
## The Challenge
Given a 2x2 matrix with complex elements, determine its two (possibly identical) eigenvalues and a normalised eigenvector for each eigenvalue. The resulting numbers must be accurate to at least 3 (decimal) significant digits. You may assume that the real and imaginary parts of any matrix element is in the range \$[-1,1]\$.
You may write a function or a program, taking input via STDIN, command-line argument, prompt or function argument. You may output the result to STDOUT, a dialog box or as the function return value.
You may use any convenient (but unambiguous) string or list format for input and output. You can also choose between pairs of floats or complex types to represent the individual numbers.
You must not use built-in functions for solving eigensystems (like Mathematica's `Eigenvectors` or `Eigensystem`) or equation solvers.
This is code golf, so the shortest answer (in bytes) wins.
## Examples
Each example is three lines: the input, the eigenvalues and the corresponding eigenvectors in the same order. Note that the eigenvectors are only determined up to their phase, and that in the case of degenerate eigenvalues, the eigenvectors may actually be arbitrary (as in the first example).
```
[[1.0, 0.0], [0.0, 1.0]]
[1.0, 1.0]
[[1.0, 0.0], [0.0, 1.0]]
[[0.0, 0.4], [-0.1, -0.4]]
[-0.2, -0.2]
[[0.894427, -0.447214], [0.894427, -0.447214]]
[[0.3, 0.1], [0.4, -0.9]]
[-0.932456, 0.332456]
[[-0.0808731, 0.996724], [0.951158, 0.308703]]
[[0.5, -1.0], [0.8, -0.5]]
[0.74162i, - 0.74162i]
[[0.745356, 0.372678 - 0.552771i], [0.745356, 0.372678 + 0.552771i]]
[[-0.0539222 + 0.654836i, -0.016102 + 0.221334i], [0.739514 - 0.17735i, -0.0849216 + 0.77977i]]
[0.238781 + 0.984333i, -0.377625 + 0.450273i]
[[0.313668 + 0.322289i, 0.893164], [-0.236405 - 0.442194i, 0.865204]]
[[-0.703107 - 0.331792i, 0.286719 - 0.587305i], [-0.418476 + 0.396347i, -0.885934 + 0.50534i]]
[-1.13654 - 0.32678i, -0.4525 + 0.500329i]
[[0.833367, -0.248208 - 0.493855i], [-0.441133 - 0.408236i, 0.799215]]
[[-0.156312 + 0.788441i, 0.045056 - 0.579167i], [0.130741 - 0.97017i, 0.049183 - 0.590768i]]
[-0.181759 + 1.11738i, 0.0746298 - 0.919707i]
[[0.86955, -0.493846 + 0.000213145i], [0.318856 - 0.0181135i, 0.94763]]
```
[Answer]
# Python 2, 198 bytes
```
a,b,c,d=input()
H=(a+d)/2
D=(H*H-a*d+b*c)**.5
X,Y=H+D,H-D
p,q,r,s=[[1,0,0,1],[b,X-a,b,Y-a],[X-d,c,Y-d,c]][2*(c!=0)or(b!=0)]
A=abs
V=A(A(p)+A(q)*1j)
W=A(A(r)+A(s)*1j)
print[X,Y],[[p/V,q/V],[r/W,s/W]]
```
Input is a flat list of 4 complex numbers via STDIN, e.g.
```
[0.0+0j, 0.4+0j, -0.1+0j, -0.4+0j]
```
Note that Python uses `j` instead of `i` for complex numbers.
Output is two lists, the first containing the eigenvalues and the second containing the eigenvectors, e.g.
```
[(-0.2+0j), (-0.2+0j)]
[[(0.8944271909999159+0j), (-0.4472135954999579+0j)], [(0.8944271909999159+0j), (-0.4472135954999579+0j)]]
```
*(newline inserted for clarity)*
[Answer]
# MATLAB, 91
A standard technique to obtain a normalized vector and remove the useless degree of freedom is representing the elements of the vector as the cosine and sine of some angle.
I originally tried to code in Python, but its math handling proved to be too brain-damaged. Its math functions refused to accept complex values, and it does not understand that floating-point division by zero is OK.
```
function[]=f(a,b,c,d)
L=(a+d+[1,-1]*((a-d)^2+4*b*c)^.5)/2
t=atan((L-a)/b);v=[cos(t);sin(t)]
```
First the two eigenvalues are printed under the heading `L =`. Then two column vectors are printed under the corresponding values of L, under `v =`. The code may fail to give linearly independent vectors in cases where it is possible to do so (such a program normally would be considered broken), but Martin said it is not required.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 59 bytes
```
{a b c d←⍵⋄l,2 1∘.○¯3○b÷⍨a-⍨l←2÷⍨a+d(+,-).5*⍨(4×b×c)+×⍨a-d}
```
**Derivation of formula for eigenvalues:**
$$
det|A-\lambda I|=0
\\
det\left|\begin{pmatrix}
a & b \\
c & d
\end{pmatrix}-
\begin{pmatrix}
\lambda & 0 \\
0 & \lambda
\end{pmatrix}\right|=0
\\
det\left|\begin{pmatrix}
a-\lambda & b \\
c & d-\lambda
\end{pmatrix}\right|=0
\\
(a-\lambda)(d-\lambda)-bc=0
\\
\lambda^{2}-(a+d)\lambda+ad-bc=0
\\
\lambda=\frac{a+d\pm \sqrt{(a+d)^{2}-4(ad-bc)}}{2}
\\
\lambda=\frac{a+d\pm \sqrt{a^{2}+2ad+d^{2}-4ad+4bc}}{2}
\\
\lambda=\frac{a+d\pm \sqrt{a^{2}-2ad+d^{2}+4bc}}{2}
\\
\lambda=\frac{a+d\pm \sqrt{(a-d)^{2}+4bc}}{2}
$$
As for the eigenvectors... everything I tried myself was longer than the MATLAB answer that I don't really understand yet. May add another explanation here at some point.
The code is then a simple implementation of these formulae.
```
{a b c d←⍵⋄l,2 1∘.○¯3○b÷⍨a-⍨l←2÷⍨a+d(+,-).5*⍨(4×b×c)+×⍨a-d}
a b c d←⍵ ⍝ assign variable names
l←2÷⍨a+d(+,-).5*⍨(4×b×c)+×⍨a-d ⍝ formula for the eigenvalues
2 1∘.○¯3○b÷⍨a-⍨l ⍝ formula for the eigenvectors
l, ⍝ append eigenvalues
```
[Try it online!](https://tio.run/##JY7LSsNAFIb3PsXZtbXNMNdMshaKurS@wOQmhaEWI4iUrpQilhRdSNy4dyFkU3GfvMm8SDxJGPhnvo@fc8asrZc8Gnt748XW5PkybtuNgQhiSNzuzRW/bv9sZxyYe/kkrtzXlcCMmj9XfBsPw2KNDzhNxtOZNyHqFGksmzJqyngybcq@m2zbeT/y4F6fXPHjimM3bPfuDh@LqzPM6/OLBeA@yLC3QYHXHPAPvRx4NNqi@YJV@mCXqxTydG3uzH3aZsCA4mEnGSaRUFeEdSFREAEIgww7VvhCEXRCoagrSqgSIef8khJfyUD4g2Q@o53jnAkhgRItQsUkGqa1UEMpkCFnPjqtQ63/AQ "APL (Dyalog Classic) – Try It Online")
[Answer]
# Lua, ~~462~~ ~~455~~ ~~431~~ 427 bytes
There is no built-in complex math in Lua. No vector operations either. All had to be rolled by hand.
```
a,b,c,d,e,f,g,h=...x=math.sqrt z=print i=a-g j=b-h
k=(i^2-j^2)/2+2*(c*e-d*f)m=x(k^2+(i*j+2*(c*f+d*e))^2)n=x(m+k)o=x(m-k)i=(a+g+n)/2
j=(b+h+o)/2 k=(a+g-n)/2 l=(b+h-o)/2 z(i,j,k,l)q=c^2+d^2 r=e^2+f^2 s=q+r if s==0
then z(1,0,0,0,0,0,1,0)else if r==0 then m,n,o,p=c,d,c,d c,d=i-a,j-b e,f=k-a,l-b
u=x(q+c^2+d^2)v=x(q+e^2+f^2)else m,n=i-g,j-h o,p=k-g,l-h c,d=e,f
u=x(r+m^2+n^2)v=x(r+o^2+p^2)end z(m/u,n/u,o/v,p/v,c/u,d/u,e/v,f/v)end
```
Run from the command-line with the following arguments:
```
lua eigen.lua Re(a) Im(a) Re(b) Im(b) Re(c) Im(c) Re(d) Im(d)
```
Produces the following output:
```
Re(lambda1) Im(lambda1) Re(lambda2) Im(lambda2)
Re(v11) Im(v11) Re(v12) Im(v12) Re(v21) Im(v21) Re(v22) Im(v22)
```
...for a,b,c,d the 4 components of the input matrix, lambda1 and lambda2 the two eigenvalues, v11,v21 the first unit eigenvector, and v12,v22 the second unit eigenvector.
For example,
```
lua eigen.lua 1 0 1 0 1 0 0 0
```
...produces...
```
1.6180339887499 0 -0.61803398874989 0
0.85065080835204 0 -0.52573111211913 0 0.52573111211913 0 0.85065080835204 0
```
] |
[Question]
[
# Directions
Write a program that, given an input integer *n* (`n >= 0`), outputs the **smallest positive integer** *m* where:
* `n = a[1]^b[1] + a[2]^b[2] + a[3]^b[3] + ... + a[k]^b[k]`
* `a` and `b` are finite sequences of the same length
* all elements of `a` are less than `m`
* all elements of `b` are less than `m`
* all elements of `a` are **different** and integers `a[x] >= 0`
* all elements of `b` are **different** and integers `b[x] >= 0`
* `a[x]` and `b[x]` are not both 0 (since 0^0 is indeterminate)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
# Examples
```
In 0 -> Out 1
Possible Sum:
In 1 -> Out 2
Possible Sum: 1^0
In 2 -> Out 3
Possible Sum: 2^1
In 3 -> Out 3
Possible Sum: 2^1 + 1^0
In 6 -> Out 4
Possible Sum: 2^2 + 3^0 + 1^1
In 16 -> Out 5
Possible Sum: 2^4
In 17 -> Out 4
Possible Sum: 3^2 + 2^3
In 23 -> Out 6
Possible Sum: 5^1 + 3^0 + 2^4 + 1^3
In 24 -> Out 5
Possible Sum: 4^2 + 2^3
In 27 -> Out 4
Possible Sum: 3^3
In 330 -> Out 7
Possible Sum: 6^1 + 4^3 + 3^5 + 2^4 + 1^0
```
[Answer]
# Python, 120
```
f=lambda n,A,B:n*all(f(n-a**b,A-{a},B-{b})for a in A for b in B)
g=lambda n,m=1,M={0}:f(n,M-{0},M)and g(n,m+1,M|{m})or m
```
The function `f` is an auxiliary function that checks whether `n` can *not* be expressed as a sum of powers with distinct bases from `A` and exponents from `B`. It uses a natural recursive strategy: `n` must be nonzero, and we try every possible choice of base and and exponent and they all need to fail. We removing them from the allowed lists and decrease `n` by the corresponding amount.
The function `g` is the main function. It searches for an `m` that works. `M` is the set of allowed values up to `m-1`. We remove `0` from the allowed exponents to stop `0**0` (which Python evaluates to 1) from being used. This doesn't hurt anything Because `0**x` is a useless `0` for all other `x`.
[Answer]
# Python 2, 138 bytes
```
from itertools import*
S=lambda n,m=0,R=[]:m*any(n==sum(map(pow,*C))for k in R for C in product(*tee(permutations(R,k))))or S(n,m+1,R+[m])
```
*(Thanks to @Jakube for all the tips)*
I've never learnt so much about the `itertools` module as I have from this one question. The last case takes about a minute.
We start by searching from `m = 1` and incrementing until we get a solution. To check for a solution we iterate over:
* `k = 0 to m-1`, where `k` is the number of terms in the solution
* All possible combination of terms (by zipping together two permutations of subsets of `[0, 1, ... m-1]` with size `k`), then summing and checking if we have `n`
Note that we iterate `k` up to `m-1` — even though technically `m` terms are possible in total, there's always a solution with `m-1` terms as `0^0` is not allowed and `0^b` contributes nothing. This is actually important because `0^0` is treated as 1 by Python, which seems like a problem, but it turns out not to matter!
Here's why.
Suppose a solution found erroneously uses `0^0` as 1, e.g. `3^2 + 1^1 + 0^0 = 11`. Since we only generate up to `m-1` terms, there must be some `j` we are not using as a base (here `j = 2`). We can swap out the base 0 for `j` to get a valid solution, here `3^2 + 1^1 + 2^0 = 11`.
Had we iterated up to all `m` terms, then we might have gotten incorrect solutions like `m = 2` for `n = 2`, via `0^0 + 1^1 = 2`.
[Answer]
## GolfScript (90 84 bytes)
```
[0.,.]](~:T),(+{:x;{:|2,{:c)|=x),^{c[1$x]=:A^x^:-;[|~-+@A-?+@A+@]}%}/+~}%.[]*T&}?)\;
```
[Online demo](http://golfscript.apphb.com/?c=Oyc2JwoKWzAuLC5dXSh%2BOlQpLCgrezp4O3s6fDIsezpjKXw9eCksXntjWzEkeF09OkFeeF46LTtbfH4tK0BBLT8rQEErQF19JX0vK359JS5bXSpUJn0%2FKVw7)
### Dissection
```
[0.,.] # Base case: [sum As Bs] is [0 [] []]
](~:T # Collect it in an array of cases; fetch parameter, eval, store in T.
),(+ # Create array [1 2 ... T 0]. Putting 0 at the end means that it won't
# be reached except when T is 0, and nicely handles that special case.
{ # Loop over the values from that array...
:x; # ...assigning each in turn to x (and popping it from the stack)
{ # Stack holds array of [sum As Bs] cases; map them...
:| # Store [sum As Bs] in |
2,{:c # For c in [0 1]...
)|=x),^ # Get [0 1 ... x]^ either As or Bs, depending on c
{ # Map these legal new As or Bs respectively...
c[1$x]=:A # Work out which of that value or x is the new A
^x^:-; # And the other one is the new B
[ # Begin gathering in an array
|~ # Push sum As Bs to the stack
-+ # Add - to Bs to get Bs'
@A-?+ # Rotate sum to top and add A^- to get sum'
@A+ # Rotate As to top and add A to get As'
@ # Final rotation to put elements in the right order
] # Gather in array [sum' As' Bs']
}% # End map
}/ # End for
+~ # Push all the elements corresponding to x^B and A^x on to the stack
}% # End map, collecting the untouched [sum As Bs] and all the new
# [sum' As' Bs'] arrays into a new array of reached cases.
.[]*T& # Flatten a copy of that array and filter to values equal to T.
# This gives a truthy value iff we've found a way to make T.
}? # Loop until we get a truthy value, and push the corresponding x
)\; # Increment to get the value of m and discard the array of cases
```
The most elegant trick is the handling of the special case for `0`.
[Answer]
# Haskell, 143 130
```
import Data.List
p n=head$[1..]>>=(\m->[m|let x=permutations[0..m-1]>>=inits,a<-x,b<-x,sum(zipWith(\x y->x^y*signum(x+y))a b)==n])
```
Usage example: `p 23` -> `6`.
This is a simple brute force search. For every list `[0..0], [0..1], [0..2] ... [0..∞]` take all initial segments of the permutations (e.g. [0..2]: permutations: `[012], [102], [210], [120], [201], [021]`, initial segments for 1st permutation: `[0], [01], [012]`, 2nd: `[1], [10], [102]`, etc.). For every combination of 2 of those lists calculate the sum of powers. Stop when first one equals n.
[Answer]
## GolfScript (59 chars)
```
~:T),{),.0{2$0-{2${{4$2$^}2*@3$\?4$+f~}%\;~}%+\;\;}:f~T&}?)
```
[Online demo](http://golfscript.apphb.com/?c=Oyc2JwoKfjpUKSx7KSwuMHsyJDAtezIke3s0JDIkXn0yKkAzJFw%2FNCQrZn59JVw7fn0lK1w7XDt9OmZ%2BVCZ9Pyk%3D)
This uses recursion to enumerate the values achieveable for a given `m` and searches for the first `m` which works. It's lightly inspired by [xnor's answer](https://codegolf.stackexchange.com/a/44666/194) but quite different in implementation.
### Dissection
```
~:T # Evaluate input and store in T (for Target)
),{ # Search [0 1 ... T] for the first m which matches a predicate
),.0 # Push [0 ... m] to the stack twice and then 0
# Stack holds: possibleAs possibleBs sum
{ # Define the recursive function f
2$0-{ # Map over A in possibleAs (except 0)
2${ # Map over B in possibleBs (except 0)
{4$2$^}2* # Duplicate respective possibles and remove selected values
@3$\?4$+ # Compute sum' = sum + A^B
f # Recursive call gives an array [sums]
~ # Push the sums to the stack individually
}% # End map: this collects the sums into a combined array
\; # Pop A, leaving just the combined [sums] inside the map
~ # Repeat the trick: push to the stack individually
}% # End map, collecting into a combined array
# Stack now holds: possibleAs possibleBs sum [sums]
+ # Include the original sum in the array of reachable sums
\;\; # Pop possibleAs and possibleBs
}:f # End function definition
~ # Evaluate the function
T& # Test whether the sums contain T
}? # End search
) # Increment to get m
```
[Answer]
# Python: 166 characters
```
from itertools import*;p=permutations
f=lambda n,r=[0]:any(n==sum(map(lambda x,y:(x+y>0)*x**y,a,b))for j in r for a,b in product(p(r,j),p(r,j)))*1or 1+f(n,r+[len(r)])
```
## Explanation
The function `f` creates all possible integers, that can be expressed as sum of powers of of numbers in `r`. If starts with `r = [0]`. If any of those integers is equal to `n`, it returns the length of `r`, otherwise it call itself recursively with an extended `r`.
The computation of the all integers, that can be expressed as sum is done with two loops.
The first loop is the `for j in r`, which tells us the length of the expression (2^3 + 1^2 has length 2). The inner loop iterates over all combinations of permutations of `r` of length `j`. For each I calculate the sum of powers.
[Answer]
# JavaScript (ES6) 219 ~~224~~
Recursive function. Starting with m=1, I try all combinations of integer 1..m for bases and 0..m for exponents (0 base is useless given 0^0 == undefined).
If no solution found, increase m and try again.
Special case for input 0 (in my opinion that is an error in the specs anyway)
The C function recursively generates all combinations from an array of given length, so that
```
C(3, [1,2,3]) --> [[3,2,1], [3,1,2], [2,3,1], [2,1,3], [1,3,2], [1,2,3]]
```
The third level `every` is used to zip together the array a of bases and b of exponents (there is no `zip` function in JavaScript). Using `every` to stop early when there is a solution not using all elements in the two arrays.
```
F=(n,j=1,k=[],
C=(l,a,o=[],P=(l,a,i=l)=>{
for(l||o.push(a);i--;)
e=[...a],P(l-1,e.concat(e.splice(i,1)))
})=>P(l,a)||o
)=>n&&C(k.push(j++),k)[E='every'](a=>C(j,[0,...k])[E](b=>a[E](x=>t-=Math.pow(x,b.pop()),t=n)))
?F(n,j,k):j
```
**Test** In FireFox/FireBug console
```
;[0,1,2,3,6,16,17,23,24,27,330].map(x=>[x,F(x)])
```
*Output*
>
> [[0, 1], [1, 2], [2, 3], [3, 3], [6, 4], [16, 5], [17, 4], [23, 6], [24, 5], [27, 4], [330, 7]]
>
>
>
] |
[Question]
[
May be you know [the game of Set](http://www.setgame.com/set/daily_puzzle) (a wonderful game for kids btw) a card game with 81 cards, where each card has a figure on it with 4 different attributes (form , number, colour and fill). Each attribute has 3 different values:
```
form: wave, oval, diamond
colour: red, purple, and green
number: 1, 2, 3
fill: none, dashed, opaque.
```
12 cards are laid open on the table and now the challenge is to indicate sets. A set consists of three cards where every attribute value occurs 0, 1 or 3 times. having 2 cards with red figures, or opaque, or 1 number is no good. See the [supplied](http://www.setgame.com/set/daily_puzzle) link for a more visual explanation.
I do envision a code for a card where all attributes are encoded so
```
"WP2N"
```
stands for
```
2 Purple Waves with No fill
```

Together with for instance `OR1N` and `DG3N`
 and 
it is a set (3 different forms, 3 different colors, 3 different number, 1 fill).
Input is space delimited string of unique codes (randomly chosen out of 81 possible codes) representing cards.
```
"OR1N WP2N DG3N DR1D WG3S WG1N WR2D WP3N DR2O DR2D OG3O OR2D"
```
The solution must indicate all possible sets within the given collection. So
```
OR1N, WP2N, DG3N
```
must be part of the solution together with all other sets.
[Answer]
# Mathematica ~~93 92 93 82 76~~ 73
```
f={}⋃Select[StringSplit@#~Subsets~{3}, FreeQ[Tally/@(Characters@#^T),2]&]&
```
**The Logic**
`StringSplit@#~Subsets~{3}` produces a list of 3-card subsets. Each triple such as:
{{"D", "G", "3", "N"}, {"W", "G", "3", "S"}, {"O", "G", "3", "O"}}
or

is then transposed,

and `Tally/@(Characters@#^T)` tallies the number of distinct items in each row.
```
{3,1,1,3}
```
3 corresponds to "all different"; 1 corresponds to "all same".
`FreeQ[...,2]` determines whether 2 cards of the same type or in the triple.
If 2 is not among the tallies, then the three cards are a "set", according to Game of Set rules.
---
**Usage**
```
f["OR1N WP2N DG3N DR1D WG3S WG1N WR2D WP3N DR2O DR1D OG3O OR2D"]
```
>
> {{"DG3N", "WG3S", "OG3O"}, {"OR1N", "WP2N", "DG3N"}, {"WP2N", "DR1D",
> "OG3O"}}
>
>
>
[Answer]
## Ruby, ~~104~~ ~~98~~ ~~81~~ 80 characters
```
$*.combination(3).map{|c|puts c*?,if(0..3).all?{|i|c.map{|x|x[i]}.uniq.size!=2}}
```
Sample run (using your example data):
```
c:\a\ruby>set.rb OR1N WP2N DG3N DR1D WG3S WG1N WR2D WP3N DR2O DR1D OG3O OR2D
OR1N,WP2N,DG3N
WP2N,DR1D,OG3O
WP2N,DR1D,OG3O
DG3N,WG3S,OG3O
```
It outputs `WP2N,DR1D,OG3O` twice because you have two `DR1D`s in your sample data.
Explanation:
`$*.combination(3).map{|c|` - each combination of 3 cards
`puts c*?,if` - output the set, if...
`(0..3).all?{|i|` - if all of the numbers from 0 to 3 (the indeces of the properties in the string) evaluate to `true` when passed into this block
`c.map{|x|x[i]}` - take the `i`th index of each string
`.uniq.size!=2}` - if the amount of unique properties (form, color, etc.) is not 2 (so, 1 or 3)
[Answer]
# Mathematica 73
```
f = Select[StringSplit@#~Subsets~{3}, FreeQ[Tally /@ Thread@Characters@#, 2] &] &
```
**Usage**
```
f["OR1N WP2N DG3N DR1D WG3S WG1N WR2D WP3N DR2O DR1D OG3O OR2D"]
```
>
> {{"OR1N", "WP2N", "DG3N"}, {"WP2N", "DR1D", "OG3O"}, {"WP2N", "DR1D", "OG3O"}, {"DG3N", "WG3S", "OG3O"}}
>
>
>
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
ṇ₁⊇Ṫz{=|≠}ᵐz
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa7EVQOEYUoPd3XaP2rb8Kip6eG2BUDOw60THnUsf7hjG5BdC@T8f7iz/VFT46Ou9oc7V1VV29Y86lwAEq/6/z9ayT/I0E8hPMDIT8HF3RhIBBm6KIS7GwcDCZBEkBGQGwCWMPIHES4K/u7G/gr@QJaSjpJxcUGGglFKUaqCYX5BMZBIzwASRUCx4nQwF0iAZYtBEilArlEKWEl6qlIsAA "Brachylog – Try It Online")
Takes input through the input variable and [generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) the output through the output variable.
Second test case taken from a [recently closed duplicate](https://codegolf.stackexchange.com/questions/195023/play-the-card-game-set) in its encoding, since this solution doesn't really care what anything actually means.
```
The output variable is
⊇ a subsequence
Ṫ of length 3
ṇ₁ of the input split on spaces,
z z the columns of which
{ }ᵐ are all
| either
= the same element repeated,
≠ or entirely free of duplicates.
```
[Answer]
### GolfScript, 53 characters
```
" "/:w,,{:a,{:^,{a^]{w=}%.0\zip{.&,2=|}/!{.p}*;}/}/}/
```
Input must be provided on STDIN, [example online](http://golfscript.apphb.com/?c=OyJPUjFOIFdQMk4gREczTiBEUjFEIFdHM1MgV0cxTiBXUjJEIFdQM04gRFIyTyBEUjJEIE9HM08gT1IyRCIKCiIgIi86dywsezphLHs6Xix7YV5de3c9fSUuMFx6aXB7LiYsMj18fS8hey5wfSo7fS99L30vCg%3D%3D&run=true):
```
> OR1N WP2N DG3N DR1D WG3S WG1N WR2D WP3N DR2O DR2D OG3O OR2D
["OR1N" "DG3N" "WP2N"]
["WP2N" "OG3O" "DR1D"]
["DG3N" "OG3O" "WG3S"]
["WR2D" "OR2D" "DR2D"]
```
Commented code:
```
" "/:w # split the input at spaces and assign it to variable w
,, # create the array [0..n-1] (n being the length of w)
{:a,{:^,{ # three nested loops: a=0..n-1, ^=0..a-1, _=0..b-1
# (third loop has no variable assigned but just pushes on stack)
a^] # make an array [a,^,_] of the three loop variables
{w=}% # take the corresponding list items, i.e. [w[a],w[^],w[_]]
.0\ # push zero, add duplicate of the the array
zip # zip transposes the array, thus [OR1N WP2N DG3N] -> [OWD RPG 123 NNN]
{ # loop over those entries
.& # unique
,2= # length equals 2?
| # "or" with top of stack (two zero pushed before)
}/ # end of loop, on stack remains the results of the "or"s
!{.p}* # if no length of 2 is there, make a copy of the set and print it
; # discard stack item
}/}/}/ # closing the three nested loops
```
[Answer]
## javascript ~~323~~ 313
```
function a(b){d=h=[];c=e=f=0;for(i in b){for(j in b){for(k in b[i]){if(b[i][k]==b[j][k]){if(c+f<4)c++;else if(c==4){h+=b[j];if(h.length=3)return h}}else{for(l in d){for(m in d[l]){g=f;if(d[l][2]==i){if(d[l][3]==k)if(b[j][k]!=d[l][0]&&b[j][k]!=d[l][1])f++;}else{continue}}if(g==f)d[e++]=[b[i][k],b[j][k],j,k]}}}}}}
```
its a function that takes a array of objects, and returns a array of objects.
[DEMO fiddle](http://jsfiddle.net/mendelthecoder/uQeMy/3/) (with tidy-up).
[Answer]
## APL(IBM), 76
```
⍉¨x/⍨{{⍵≡1⌽⍵}⍵=1⌽⍵}¨x←⊃¨(∘.,/3⍴⊂⍪¨(' '≠y)⊂y←⍞)⌷⍨¨z/⍨∧/¨2</¨z←,⍳3⍴12
```
I don't have IBM APL, but I believe this will work.
**Sample run (Emulating IBM APL in Dyalog APL)**
```
OR1N WP2N DG3N DR1D WG3S WG1N WR2D WP3N DR2O DR1D OG3O OR2D
OR1N WP2N WP2N DG3N
WP2N DR1D DR1D WG3S
DG3N OG3O OG3O OG3O
```
[Answer]
## Sage, 71
If `C` is a string, say `"OR1N WP2N DG3N DR1D WG3S WG1N WR2D WP3N DR2O DR1D OG3O OR2D"`, execute
```
[c for c in Subsets(C.split(),3)if{1,3}>={len(set(x))for x in zip(*c)}]
```
to get `[{'DR1D', 'OG3O', 'WP2N'}, {'DR2D', 'WR2D', 'OR2D'}, {'WG3S', 'OG3O',
'DG3N'}, {'DG3N', 'WP2N', 'OR1N'}]`
And here's a very different approach using the interpretation that a Set is a projective line in `GF(3)^4`:
```
[c for c in Subsets(C.split(),3)if sum(matrix(3,map('WODRPG123N'.find,''.join(c))))%3==0]
```
I was a little annoyed that `D` was used twice... until I figured how to abuse that. But even better, I abuse the `find` method, too. `str.find` returns -1 if a letter isn't found. Since `-1 = 2 mod 3`, the letter `S` is handled appropriately because it doesn't occur in `'WODRPG123N'`.
[Answer]
# [Python 2](https://docs.python.org/2/), 99 bytes
```
lambda A:[a for a in combinations(A,3)if all(len(set(t))-2for t in zip(*a))]
from itertools import*
```
[Try it online!](https://tio.run/##HYqxCsIwFEV3v@LhlBQVmmyCQ6HQrSl16KAOqTb4IE1C8hb9@Zq4HO7lnPCht3diM5f7ZvU6vzQ055sG4yNoQAdPv87oNKF3iTUHydGAtpbZxbG0ECPOj6LUVOovBlZpzh87E/0KSEsk720CXIOPVG0hoiMwbK/GuodpED20ncwY6xamTl4zihhFvsNfCFXQguqkApXX/pSCRWKcbz8 "Python 2 – Try It Online")
] |
[Question]
[
Traditionally when you compare two strings you use lexicographical comparison. That can be described by the recursive algorithm:
$$
f(x, y)=
\left\{\begin{array}[rr] \\
\mathrm{EQ} & \mathrm{if}\,\mid x\mid=0\,\mathrm{and}\,\mid y\mid=0 \\
\mathrm{GT} & \mathrm{if}\,\mid x\mid>0\,\mathrm{and}\,\mid y\mid=0 \\
\mathrm{LT} & \mathrm{if}\,\mid x\mid=0\,\mathrm{and}\,\mid y\mid>0 \\
\mathrm{GT} & \mathrm{if}\,x\_0 > y\_0 \\
\mathrm{LT} & \mathrm{if}\,x\_0 < y\_0 \\
f(\mathrm{tail}(x),\mathrm{tail}(y)) & \mathrm{if}\,x\_0 = y\_0
\end{array}\right.
$$
This has many advantages, however it does have some drawbacks. In particular it doesn't work like we might want it with our base 10 numerals. For example `9` is "greater than" `852` with lexicographical comparison because its first digit is larger.
So for more human oriented sorting we can use a modified algorithm:
* Break each string into runs of consecutive digits (`0-9`) and individual non-digit characters. For example `abc29em3jdd` -> `a b c 29 e m 3 j d d`
* Compare each of the two broken strings with lexicographical comparison treating each piece as a single symbol. Compare two individual characters as normal. When comparing two runs of digits, consider the one which is longer to be greater, otherwise compare them lexicographically. When comparing a run of digits with a individual character treat the run of digits as if it were its first digit.
This produces some pretty nice results. `852` is greater than `9`, and `b15` is greater than `a16`.
## Task
Implement this human oriented comparison by taking two strings as input and outputting one of three distinct values. One if the two strings are equal, one if the first input is "greater" than the second and the last if the second input is "greater" than the first.
You can assume that the strings are finite and consist of only characters on the range of 32 to 127.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes.
## Test cases
```
"abc" "abx" => LT
"abx" "abc" => GT
"abx" "abx" => EQ
"ab" "abc" => LT
"ab" "ab10" => LT
"ab10c" "ab9x" => GT
"ab9x" "ab10c" => LT
"15x" "16b" => LT
"16b" "15x" => GT
"852" "9" => GT
"1,000" "9" => LT
"1.000" "9" => LT
"20.15.12" "20.19.12" => LT
"20.15.12" "6.99.99" => GT
"15k19" "15w12" => LT
"9w" "10" => LT
"10" "9w" => GT
"a123" "123a" => GT
"#123" "123#" => LT
"3-2" "3-1" => GT
"a000" "a0" => GT
"a001" "a0" => GT
"a000" "a1" => GT
"0xa" "0x10" => GT
"0_10" "0_4" => GT
"/" "*" => GT
```
[Answer]
# [C (GCC)](https://gcc.gnu.org), 230 178 176 bytes
edit: - bytes thank to c--, -6 thanks to pan
```
*p="1234567890";i,j;f(char*x,char*y){x[i=strcspn(x,p)]+y[j=strcspn(y,p)]?strncmp(x,y,i>j?j:i)?:i-j?:(i=strspn(x+=i,p))-strspn(y+=j,p)?:atoi(x)-atoi(y)?:f(x+i,y+i):strcmp(x,y);}
```
Returns positive for GT, negative for LT and 0 for EQ (same output as strcmp)
```
* p = "1234567890";
i, j;
f(char * x, char * y) {
x[i = strcspn(x, p)] + y[j = strcspn(y, p)] ? // find first digit in each string
strncmp(x, y, i > j ? j : i) ? : // return strcmp if strings are different before first digit
i - j? : // return longer string before the first digit
(i = strspn(x += i, p)) - strspn(y += j, p) ? : // return longer number
atoi(x) - atoi(y) ? : // return larger number if both have the same length
f(x + i, y + i) : // otherwise compare the string after the numbers
strcmp(x, y); // return strcmp if there are no digits
}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZLRToMwFIYT78ZTNDUmdBRSpuAAGVfGG29MvNuMYVVciWME0JWYPYk3u9m9r6NPY1vYZJGE5LTf_5__HJJ-7ujjC6Xb7e6tSszx99cwD6E9Or9w3MuxR2DAcBokOl3ExZBjVWr0wacsLKuClnmmc5yjB6OepgdSSxKJW0aXudBrzCZplPoMRT4z08jXVbdqNkIm3Mhs77URpuIe-XG1YjpHpqq1AInwMlwbDPlyThOMgk2z98_J6fuKPWnVc1npdJWVFZC7guHrosSgC4pFibQPbcAyQZY5CEGiK5MUAm2QF0JJdDiDZ-UMgraEEyBqBjHYe7HqvgIERADe3kPgKzBpwI0C8PoOisyNpolMbRmzTEdAzFZbwnhORZ4oXJoOkDeQ9sFjZ5-xYTY5gjZpJ3nHAR7f27shtqOw7c670FXRUvuDY2ckodf1YULIP2j1wBGxbMeyVYI8e_LcL7uW54mvo3prtU33N-1mwrqDCI8lI7wxtm9l_9Z_AQ)
Previous attempt:
```
int f(char*x,char*y){int c,i,j;for(;;){i=strcspn(x,"1234567890");j=strcspn(y,"1234567890");if(!*(x+i)&&!*(y+j)) return strcmp(x,y);if(c=strncmp(x,y,i>j?j:i))return c;if(c=atoi(x+=i)-atoi(y+=j))return c;for(;isdigit(*x);x++,y++);}}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~74~~ 72 bytes
*Saved 2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)! Bugfix thanks to [tsh]*
```
x=>y=>((a=(g=s=>b=s.replace(/\d+/g,n=>0+n.padStart(16)))(x))>g(y))-(a<b)
```
[Try it online!](https://tio.run/##ZZJNb@IwEIbv/AqL9mAvTrBhQRuxzq3qpZdqe2NR6yROym6URLFZUqH8duqPfG2RiDXzeN55x2j@8H9cxvWxUl5RJuKasmvDwg8WQsgZzJhkYcSkX4sq57GAy9/JYpnhgoVkUfgVT34pXitItwgh2CAUZvADIQ/ynxG6xmUhFXh6AQx4dDdz6aNJwZA@PJuU7Ga5UCDmUkid72cA7Oc8iudYn80cP70csCWNJZo//k/0@fDckb5kEFlAiSNda0pc86CZ9AqarnRU041hdBuNxMSOd8Ifm5Umgcttf4oJIY71Kv8rWRGfbnxqpCYMbHh7t/WDQP@mzTd/aWBHOE8kwdkgMhpat/P4Orpam4rVmg/sbmB3kz9n7RnftUdHrZudkymhN8TWjCrSaCd9UjIZnrzawcjr96FuqfNvXclhN3ObUNa1iJXehW41Un7MRWJ2Q5ekZQ0N3HMMIgzKkzqAMnXrg8BFG5nbWshTblqkkCMYoZ3mxxT2mBmdqwa932Jhilr9iVyK7s5Z@9VJvsPREXf9D8hJWrvQZS78vMzg2/2la9kudWgG83NRZOq9BRWXUorkDd08RDSVVogEAx6rE8/tq5y9G/SLBW8xuL9E7SDUWR/qq6xUGrhWrbFrr58 "JavaScript (Node.js) – Try It Online") Gives `-1` for `LT`, `0` for `EQ`, and `1` for `GT`. Call as `f(a)(b)`.
Assumes the strings' integers are [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding) (in this case, positive integers ≤ \$2^{53}-1\$, i.e., 16 decimal digits or less. This transforms both input strings by left padding such integers with spaces, prepending a zero, and using the native string comparison sort, which gives us the correct results. (This method, as opposed to padding with 0s, distinguishes `0` and `000`, as in such cases, the length of the string should be taken into consideration.)
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 27 bytes [SBCS](https://github.com/abrudz/SBCS)
```
(⍋>⍒)-⍤⌈⍥≢/↑¨¨'\d+|.'⎕S'&'¨
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=AS4A0f8o4o2LPuKNkikt4o2k4oyI4o2l4omiL@KGkcKowqgnXGQrfC4n4o6VUycmJ8Ko&f=XY5BDoAgDATvvsJbL4a0JBD7HDXh4gPg@bIUIpoQ6OxuW9JKx3kR7kJLste0mYb3sRoIdxK2MTqyWmjoECSAJZ5GEe3QQHvwldScjZlfcjN5dhKcIIxSUf706FTr6Stv0bYm96BmoH1Z2txMDw&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
Tacit function that returns `0 1`, `0 0`, `1 0` for `LT`, `EQ`, `GT`, respectively. Input `f x y`.
```
'\d+|.'⎕S'&'¨ split into numbers/others
-⍤ ↑¨¨ left-pad splits to
⌈⍥≢/ max length of inputs
(⍋>⍒) compare
```
[Answer]
# [Python](https://www.python.org), 95 bytes
-X bytes thanks to WheatWizzard and Conor O'Brian
```
def f(x):a,b=[[(len(i),i)for i in re.findall('\d+|.',y)]for y in x];return(a>b)-(a<b)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Xc1BCoJAGAXgvacYpoX_TypoLaKyK3QAlZjJGRqyGRlGUOgmbVxUd-o2aQZBq7f4eO_dnnXnTkb395lM80fjZLh6HUohiYQW1yzgaZZBJTQoDBRKY4kiShMrIql0yaoK_LycXyM_6LAYuRu5LTZWuMZqYDuOIbAtR09damPdUP3e7GurtAMJQBk_0oDQ4ZciovcDLuJkMRIXyfLPziZORvrkQNNs30_5Bg)
[Answer]
# [Raku](https://raku.org), 39 bytes
```
&[cmp]o*».&{[m:g/\d+|./».&{+$_//$_}]}
```
[Try it online!](https://tio.run/##Vc7BDoIwDAbgV2kI4SBmrCQszggvggsBFA9KIHgAgjyZN18Mu41ITHb4@q9t2l67h1jqEbwK4sVLy7pVze7zZt6U1sdbcL74LxaY2nezIHCzWc3LMx/BcbOUK6ABIKGCOIGpIs8OVE0Hp7woIS@GZK85EMuNa7qFJOSWyPWcXFvkYL5MG0YDoCgMRQFUah6iEKTJ9pzzlezHkDOMGIagIQl/oWBS0rPb7yhpaW9bZA/2IqRFfbJ8AQ "Perl 6 – Try It Online")
* `*».&{ ... }` is an anonymous function that maps its list-of-strings argument over the braced expression.
* `m:g/\d+|./` breaks a string up into a list of matches, each either a group of digits, or a single other character.
* `».&{ ... }` maps each of those lists over the braced expression.
* `+$_ // $_` tries to convert each match into a number with the `+` operator. If that fails, the defined-or operator `//` replaces the error with the original value.
* `[ ... ]` wraps each list in an `Array`.
* `&[cmp]` is a reference to the built-in `cmp` operator, which operates on arrays of heterogeneous data types just as specified in the problem statement. It returns one of the enumerated values `Less`, `Same`, or `More`.
* `o` composes those two functions together.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 49 bytes
```
\d+
$.&$*10$&
^
$%'¶
O`¶.*
^(.*)(¶\1)*(¶.*)*$
$#2
```
[Try it online!](https://tio.run/##RY1NTsMwEIXX864RtySGmhmnqbAEvQILWFZtnJQFqtRFhRSfLAfIxcKYRkLy8/fmx8@3r5/va5xX5UdL8@H8COPWxgqbNY4wq4dpxHs7jc7iWDpbldN4kMqWuVNZA1P4@bM9t/vXtzl2PcUuQaXsF@Z6KRXCyFdeDHkS0l@zhzSJZNdBRerx0ngKkCdmznR3enbSOPGUTVDz39m5EPRo0EWCRgw6DAPph6IvB0TxNakiisUVqDee6o0g5vTImbJQawGnSJw0gk8awqctnsn@Ag "Retina 0.8.2 – Try It Online") Takes newline-separated input and outputs `0`, `1` or `2` for `GT`, `LT` and `EQ` but link is to test suite that splits on tabs and translates the output to `>`, `<` or `=` for convenience. Explanation:
```
\d+
$.&$*10$&
```
Prefixes each run of digits with a run of `1`s of the same length and a `0`. This maintains lexicographical sort order when comparing numbers with non-numbers while making numbers sort by length and then lexicographically.
See below for the explanation of the rest of the program. Previous 44 byte version compared digit strings numerically rather than by length:
```
\d+
$*10
^
$%'¶
O`¶.*
^(.*)(¶\1)*(¶.*)*$
$#2
```
[Try it online!](https://tio.run/##RY1NCsIwEIXXmWuYYholZAItDqhXcKHLUtK/hQguRGhP1gP0YnFGC0Im35s3k5fX8L4/m5SZa1Sp6negLXqoQWfbZYZLXGZnoTbO5maZK8ytESe3GvQmpFvs4/l4Sk3bqaadgIvZrZR@bRkcK5cskkxo@podYDEpLFvgUqzhUARFgHvvvdD9GLzDwmFQIojF3ykdER8OeiBxxMhDGhV/iPxy/AA "Retina 0.8.2 – Try It Online") Takes newline-separated input and outputs `0`, `1` or `2` for `GT`, `LT` and `EQ` but link is to test suite that splits on tabs and translates the output to `>`, `<` or `=` for convenience. Explanation:
```
\d+
$*10
```
Replace all embedded runs of digits with a run of that number of `1`s followed by a `0`. This maintains lexicographical sort order when comparing numbers with non-numbers while making numbers sort numerically.
```
^
$%'¶
```
Make a copy of the first string.
```
O`¶.*
```
Sort the modified strings lexicographically.
```
^(.*)(¶\1)*(¶.*)*$
$#2
```
Count how many strings match the first string. If both strings were equal, then they will both match. If the first string was less than the second, then it will match and the other string will not. If the first string was greater than the second, then there will not be any additional matches.
I include the previous newline in the sort string as non-empty strings are easier to process in Retina, but note that the above rule works whether or not the copy is included in the sort; with the copy, the possible results are `EEE` (all equal), `FFS` (first sorts before second), `SFF` (first sorts after second), while without the copy, the third result is `FSF`, where the first two strings are still different.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÙΣ.γd}εÐdigs»]k
```
Input as a pair of strings. Outputs `[0,1]` for \$LT\$; `[1,0]` for \$GT\$; and `[0]` for \$EQ\$.
[Try it online](https://tio.run/##yy9OTMpM/f//8Mxzi/XObU6pPbf18ISUzPTiQ7tjs///j1ZSNjQyVtJRApLKSrEA) or [verify all test cases](https://tio.run/##XY6xTsMwEIZfJXIXQK65S0hUT1mKWFiQKpYoqhyKqqgDQyWSDpGYmBEbCwtj2RATA1K95yH6IqnPdqCtZNn/d//vu3tYqqK87x5XKQu2z68BS1dj1um39kO0X7Om/dYvs3K@3Pzki46J23G6@Sy3T@9XE72ek7i80WvzXE@ahgUn@veU8S7LmCruGDd3zXKe2Zfb2j713oFlAcETgmsj@6ysfcDlMSbGpHCU0HeqEY3i0JB0DgeAfxL7FILAWCCFSUqSR/VESGmOH7lAacdUPigrQrcy2r6V2xbDiJwwUpYHfzywHA2pdzREl3Y7KegJD8h6Lgm1MgC1HwlTOxSmFxbPjT5jeb4D).
**Explanation:**
```
Ù # Uniquify the (implicit) input-pair (for the EQ test cases)
Σ # Sort the pair by:
.γ # Adjacent group the substrings by:
d # Is it a (non-negative) number
}ε # After the adjacent-group-by: map over each part:
Ð # Triplicate the current part
di # Pop one, and if it's a (non-negative) number:
g # Pop another, and push its length
s # Swap so the number is before the length on the stack
» # Join the stack (the length & number) with newline delimiter
] # Close the if-statement, map, and sort-by
k # Get the indices of this sorted pair into the (implicit) input-pair
# (which is output implicitly as result)
```
[Answer]
# [Perl 5](https://www.perl.org/), 41 bytes
```
sub{s/\d+/$&+1e9.$&/ge for@_;pop cmp pop}
```
Returns -1 for GT, 0 for EQ and 1 for LT.
[Try it online!](https://tio.run/##jZJRb4IwEMef5VNcmioaC1KTGivR@bLsYcvMEt/QGEUwi0OYugxi/OysLag4ZRmB8L@7X@9/R4i87QdLgwSwD/1097U47FqTZbOFa03qcRPXWisP/HA7nNlRGIEbRCDex9TWRLLuoPnCRQTUJXSMMgn9AegvY31KNBk5qnTB3CL2VIpddXt8K2In6qbbtWkRoxYqw6iVLyE0j1HZbPw0XH7kbjfKLivQzqJsNlk6Yywu@yBd1j5j/ATdYpRYlpWv8Au7MjX/hbUtkzKTSmeludR/Yx2Tc3Gje7OxNeW5KWXfqlXBtKEdFBgkdRwTwIl4vDhqQB@GeGbnNcCrcC9SNezXIZhHeCYwhTcyJK87sieRPwtRQxgDB6ihitMMjLbvm72PqkZnJ6K4B1WjK1VyVsLdc/feUiRkKM5KNdkgolXkaOB9ZnYPoIdrHXqgv47GMHrWSaW4AlGUrR3THw "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ ~~20~~ 18 bytes
```
œ-œlLɗÐƤ€ØDoṚ$ż"¹Ġ
```
[Try it online!](https://tio.run/##y0rNyan8///oZN2jk3N8Tk4/POHYkkdNaw7PcMl/uHOWytE9Sod2Hlnw/3D70UkPd86weLi72x@IHzXMcQ8BEj4gwjXwUcNcHW@g8iwgT8HWTgHI14z8/z86WikxKVlJRwFIVSjF6nBFgxlgfjIaHy6PJg3hGhrA@IYGUAMt4TosK2CKoLoMTcEihmZJUL4Z2BiQMJhvYWoE4ltCZXUMDAyQ@XqofCMDPUNTPUOwFhDbEsTGkDHTs7QEIpgDsg0tIVaWwxRbloMFoB4xhNhQDvWDoZExWNbIOBEioowQUYaIGOuC7THWNYTqgboy0QDON0TjQ@Sh6g0qEkFcgwqYEwziIY4wiDeBCOiDeFpKsbEA "Jelly – Try It Online")
Takes a list of two inputs, and returns `[[1], [2]]` for LT, `[[1, 2]]` for EQ, and `[[2], [1]]` for GT. (The test footer converts these because my brain couldn't handle checking the test cases otherwise.)
A band-aid fix to a solution that otherwise always compares digits as greater than non-digits.
```
ÐƤ For every prefix (largest first) of
€ each of the inputs,
L get the length of
œ- the multiset difference of the suffix and
œl ɗ ØD the suffix with leading digits removed.
o Replace zeroes in either result with
Ṛ$ corresponding elements of the other result,
ż"¹ then zip each result with the corresponding input.
Ġ Group indices, sorted by value.
```
[Answer]
# [Tcl](http://tcl.tk/), 506 bytes
Modified from [@Kjetil S's answer](https://codegolf.stackexchange.com/a/257589/110802)
---
Golfed version, [try it online!](https://tio.run/##jVTBjpswEL3nK0aIPaUgHCnRsnvoqeqhVVeV9paiygGHRUuAGqN1hPzt6Qw2kC5RtRYi9ryZ98bMTFRaXi6NrFMoqlSKk6jU76o7HYRsoW@VNPgWCqRou1KB5z0CHYtMQ/QIx1oKnr7AiSt876XIhW4g4GUJQVGVRSXoNytS0UIQQP8rWxvwkTWxrK3iUsEeHTOhwbc0UWI1RJW9hxhCvGkIcQntkayocpC8ysVADT4lt8dEJPS@VQiAmcTR4uVuRllPH7mXIo6MQtfARGySkA7ztxg9KGhNYuajiVo9KVQnK/CtMwYPFTlCr@HsKoAiywr52t3qfBM9z9SjflqfGi4xA02wuYwlVKJV0K8AV88PKQyLHzS49f3ZjKAewXQEv94Ap8gvPycQFpFXtBPIoiXIotSCsV5qOtvkdRXJts6f7Q4Lzck2eV3R3m831hIDLED2KYqid@BMG/4H3EQh24ZsA7SJaXML3IVxjM@/mttXFtts39hmpjWubCVv2yLHJhpKiY0D2JQDQg2S19iDR1d2a30raKZ8QiwDrYDZdiPrmBetaDaPBR1ymc1jombSxJFSXTsPB/43iD9W8DN49asHD@D9eHqGp2@esUk1ncIAbEocePDugl2LRv0Ad8E97c7TDslEqkSGBjoiJ@28YY5JdLgoDJokmKzM6vIX)
```
proc increment_numbers {str} {set result ""; set idx 0; foreach match [regexp -all -inline -indices -- {\d+} $str] {set start [lindex $match 0]; set end [lindex $match 1]; append result [string range $str $idx [expr {$start - 1}]]; set num [string range $str $start $end]; append result [expr {$num + 1e9}].$num; set idx [expr {$end + 1}]}; append result [string range $str $idx end]; return $result}; proc f {x y} {set x [increment_numbers $x]; set y [increment_numbers $y]; return [string compare $x $y]}
```
Ungolfed version
```
proc increment_numbers {str} {
set result ""
set idx 0
foreach match [regexp -all -inline -indices -- {\d+} $str] {
set start [lindex $match 0]
set end [lindex $match 1]
append result [string range $str $idx [expr {$start - 1}]]
set num [string range $str $start $end]
append result [expr {$num + 1e9}].$num
set idx [expr {$end + 1}]
}
append result [string range $str $idx end]
return $result
}
proc f {x y} {
set x [increment_numbers $x]
set y [increment_numbers $y]
return [string compare $x $y]
}
foreach test {
{abc abx LT}
{abx abc GT}
{abx abx EQ}
{ab abc LT}
{ab ab10 LT}
{ab10c ab9x GT}
{ab9x ab10c LT}
{15x 16b LT}
{16b 15x GT}
{852 9 GT}
{1,000 9 LT}
{1.000 9 LT}
{20.15.12 20.19.12 LT}
{20.15.12 6.99.99 GT}
{15k19 15w12 LT}
} {
lassign $test x y exp
set got [f $x $y]
switch $got {
-1 {set got LT}
0 {set got EQ}
1 {set got GT}
}
set status [expr {$exp eq $got ? "ok" : "NOT OK"}]
puts [format "%-6s x: %-8s y: %-8s expected: %s got: %s" $status $x $y $exp $got]
}
```
] |
[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.
---
On the flight to Hawaii for vacation, I'm playing with a deck of cards numbered from 1 to \$n\$. Out of curiosity, I come up with a definition of "magic number" for a shuffled deck:
* The magic number of a shuffle is the minimum number of swaps needed to put the cards back into the sorted order of 1 to \$n\$.
Some examples:
* `[1, 2, 3, 4]` has magic number 0, since it is already sorted.
* `[4, 3, 2, 1]` has magic number 2, since I can swap (1, 4) and then (2, 3) to sort the cards.
* `[3, 1, 4, 2]` has magic number 3. There is no way I can sort the cards in fewer than 3 swaps.
**Task:** Given \$n\$ and the magic number \$k\$, output all permutations of \$n\$ whose magic number is \$k\$.
You may assume \$n \ge 1\$ and \$0 \le k < n\$. You may output the permutations in any order, but each permutation that satisfies the condition must appear exactly once. Each permutation may use numbers from 0 to \$n-1\$ instead of 1 to \$n\$.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
Trivia: The number of permutations for each \$(n, k)\$ is given as [A094638](http://oeis.org/A094638), which is closely related to Stirling numbers of the first kind [A008276](http://oeis.org/A008276).
## Test cases
```
n, k -> permutations
1, 0 -> [[1]]
2, 0 -> [[1, 2]]
2, 1 -> [[2, 1]]
3, 0 -> [[1, 2, 3]]
3, 1 -> [[1, 3, 2], [2, 1, 3], [3, 2, 1]]
3, 2 -> [[3, 1, 2], [2, 3, 1]]
4, 0 -> [[1, 2, 3, 4]]
4, 1 -> [[1, 2, 4, 3], [1, 3, 2, 4], [1, 4, 3, 2], [2, 1, 3, 4],
[3, 2, 1, 4], [4, 2, 3, 1],
4, 2 -> [[1, 3, 4, 2], [1, 4, 2, 3], [2, 1, 4, 3], [2, 3, 1, 4],
[2, 4, 3, 1], [3, 1, 2, 4], [3, 2, 4, 1], [3, 4, 1, 2],
[4, 1, 3, 2], [4, 2, 1, 3], [4, 3, 2, 1]]
4, 3 -> [[2, 3, 4, 1], [2, 4, 1, 3], [3, 1, 4, 2], [3, 4, 2, 1],
[4, 1, 2, 3], [4, 3, 1, 2]]
```
[Answer]
# [J](http://jsoftware.com/), 26 22 bytes
```
((=#"1-#@C.)#])!A.&i.]
```
[Try it online!](https://tio.run/##ZY0xC8IwFIT3/oprA6bBNDRpEBqoqAUncXAtbyoWdfH/TzFJiyIdDt4dd@97@TZ3mna5aznPCsUndA4cEjVcUKXQ3y5nX5YdK3TFDr0SjER@VJunIi@y7D4@3tDYBk1ocD0pVHsMg5ZoJAxJDEYiunjGKDiitAvI77xezU3crItNKNpf0SSOjU9nlP2j6RSYxdkFH9xcM0vTpi8xIPIf "J – Try It Online")
*-4 thanks to Bubbler!*
Generates all perms, converts to cycle representation, take sum of "length of each cycle - 1" (this gives number of swaps needed to sort), then filter to only those elements whose swap count matches the input requirement.
[Answer]
# [Python 3](https://docs.python.org/3/), 108 bytes
```
f=lambda n,k,*a:n and sum([f(n-1,k-1,v,*a[:i],n,*a[i+1:])for i,v in enumerate(a)],f(n-1,k,n,*a))or[a]*(k==0)
```
[Try it online!](https://tio.run/##RYzNCsIwEIRfZY/ZuoJFvAT6JCGHlaYaYqYltgWfPrYqeBgYvvmZXvN9xLnWoXtovvZKkCSNWpCip@eSjRsMjq2kTeuWOBu9YDfx0FrPw1goykoRFLDkUHQORtnLb/bpMo/FqW9M6roTVzeViNlAKAltPUnMtB9hvymKWzCt0OUL0x@CfX0D "Python 3 – Try It Online")
[Answer]
# [Python](https://www.python.org), 97 bytes
```
f=lambda n,k:[[]][n+k*k:]or[L[:j]+[n]+(2*L[j:])[1:n-j]for j in range(n)for L in f(n-1,k-(-~j<n))]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY87DsIwEAV7TuHSm8QSDimQBTfIDVZbGIFJbLKJrFDQcBGaNHAnboMiPiIpZ14xerdHd-mrlofhfu6dWj-t255ss9tbwVkwiETIaUiCoTZiicZTikypzJMSvSFAbVh5cm0UXtQsouXjQTKMohyFk6x0FpRUV79hAPqEqi7W3MvESZ0tARY_zOeo_7GYrsV8zae4Anj3vgdf)
### [Python](https://www.python.org), 134 bytes
```
def f(n,k,L=0):
z=range(n);L=[*(L or z)];n-=1;s=L[n]
for j in z:L[n]=L[j];L[j]=s;yield from([L][n-j:],f(n,k-(j<n),L))[k>0];L[j]=L[n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9BDoIwEEX3nGKWHVISUBeGWk_QGzRdmECVogMpuIADeAk3bPRO3kZQTGQzyXvJn5l_f9Zde6poGB7X1kbb1y3LLVhGvORKxpgG0Et_oGPOCIWSOmQKKg89GkGRTEQjlSYTgB2lg4KgTycxWmfENGQjuiI_Z2B9dWFaGU2RSw3_3IiY2xFyhajLfTwHpvz8jah9QS0LLdvwGDH4w2SJqyWuEb8rfsXe)
Enumerates the magic permutations. n is number of elements, k is magic number.
### How?
A modification of a textbook (I'd think) permutation enumerator: go from rightmost to leftmost position swapping each with any position to its left or not at all. All we are adding is fixing the number of swaps.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Lœʒāøœ€.œ€`.Δε˜Á2ô€ËP}P}€g<OQ
```
Port of [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/255244/52210), but without [cyclic permutation](https://en.wikipedia.org/wiki/Cyclic_permutation#:%7E:text=In%20mathematics%2C%20and%20in%20particular,all%20other%20elements%20of%20X.) builtin†.
Inputs in the order \$n,k\$.
[Try it online](https://tio.run/##yy9OTMpM/f/f5@jkU5OONB7ecXTyo6Y1emAyQe/clHNbT8853Gh0eAuQf7g7oDagFshIt/EP/P/fhMsIAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6H@fo5NPTTrSeHjH0cmPmtbogckEvXNTzm09Pedwo9HhLUD@4e6A2oBaICPdxj8i8H@tzv/oaEMdg1idaCMoaQgkjcFsYyjbCEiagEVMwCImUBHj2FgA).
**Equal bytes alternative actually performing swaps:**
```
ÝRεULœʒ©ãX.Æε®svy‡}D{Q}à].»K
```
Inputs also in the order \$k,n\$.
[Try it online](https://tio.run/##AUIAvf9vc2FiaWX//8OdUs61VUzFk8qSwqnDo1guw4bOtcKuc3Z5w4LigKF9RHtRfcOgXS7Cu0v//zIKNP8tLW5vLWxhenk) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCmNL/w3ODzm0NjfQ5OvnUpEMrDy@O0Dvcdm7roXXFZZWHmx41LKx1qQ6sPbwgVu/Qbu//SnphOv@jow10DGN1gKQRkDQEkwY6xmA2iDQCkwY6JmARE7AIiDQGkrH/dXXz8nVzEqsqAQ).
**Explanation:**
```
L # Push a list in the range [1, first (implicit) input n]
œ # Get a list of all its permutations
ʒ # Filter this list of permutations by:
āøœ€.œ€`.Δε˜Á2ô€ËP}P}
# Get the cyclic permutation of the current permutation-list†:
ā # Push a list in the range [1,length] (without popping): [1,n]
ø # Pair it together with each value in the current permutation
œ # Get all permutations of this list
€ # Map over each permutation:
.œ # Get all partitions
€` # Flatten it one level down
.Δ # Find the first partition of permutation of pairs of the current
# permutation-list that's truthy for:
ε # Map over each part of the partition:
˜ # Flatten the list of pairs
Á # Rotate it once towards the right
2ô # Split it back into parts
€Ë # Check if the values in each individual pair are the same
P # Check if this is truthy for all of them (thus it's a cycle)
}P # After the map: check if it's truthy for the entire partition
} # Close the find_first, resulting in the cyclic permutation
€g # Get the length of each inner cycle-list
< # Decrease each length by 1
O # Take the sum of those
Q # Check if it's equal to the second (implicit) input k
# (after which the filtered list of permutations is output implicitly)
```
```
Ý # Push a list in the range [0, first (implicit) input k]
R # Reverse it to [k,0]
ε # Map over each value:
U # Pop the current value, and store it in variable `X`
L # Push a list in the range [1, second (implicit) input n]
œ # Get all permutations of this list
ʒ # Filter it by:
© # Store the current list in variable `®` (without popping)
ã # Get all pairs of this list
# (with duplicates by using cartesian power of 2)
X.Æ # Get all X-sized combinations of these pairs
# (without duplicates by using combinations builtin)
ε # Map over each list of pairs:
® # Push permuted list `®`
s # Swap so the current list of pairs is at the top
v # For-each over each pair `y`:
y # Push the current pair `y`
 # Bifurcate it; short for Duplicate & Reverse copy
‡ # Transliterate it in the list, basically swapping the values
}D{Q # After the inner loop: check if the list is sorted
D # Duplicate the resulting list with performed swaps
{ # Sort the copy
Q # Check if both lists are the same
}à # After the inner map: check if any was truthy
] # Close both the filter and outer map
.» # Then left-reduce these lists by:
K # Removing lists
# (after which the reduced list of permutations is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes
```
⊞υ…N≔υθFN«≔⟦⟧υFθFLκF⁻⁻EλEκ§κ⎇⁼πλμ⎇⁼πμλπυθ⊞υμ≔⁺θυθ»Iυ
```
[Try it online!](https://tio.run/##bY89C8IwEIbn9lfceIE46dapiIOgUsRNHGKNbWmStvkQRfztMSntIt5wH9zD3fuWNdNlx4T3hTM1OgpHpiqOW9U7e3DyyjUSQrI0N6apVASGMN07DT8MvNNkgs4XCi5QyYgNBMa646qyNbZkmveNcmbOrEdBIZaWQm636safsT1xrZh@4WZwTBjsKQhCQf5byLAIN3oSIwqIUgnMvmQUNAksRPg5zEyWftJCN8rimhmLLtj1fgVLv3iILw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ…N
```
Start with the identity permutation as the only permutation with magic number `0`.
```
≔υθ
```
Also set this as the list of permutations seen so far.
```
FN«
```
Loop through the magic numbers.
```
≔⟦⟧υ
```
Start with no permutations for the next magic number.
```
FθFLκF
```
Loop through the swaps of the permutations seen so far (including the ones whose swaps we've already seen but that's code golf for you).
```
⁻⁻EλEκ§κ⎇⁼πλμ⎇⁼πμλπυθ
```
Generate the list of potential new permutations but remove any previously seen (including those already seen for this magic number).
```
⊞υμ
```
Append any new permutations for this magic number. (Or I could have just concatenated the lists I guess.)
```
≔⁺θυθ
```
Append all of the new permutations for this magic number to the list of those seen so far.
```
»Iυ
```
Output the permutations for the last magic number processed.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 48 bytes
```
f(n,k)=forperm(n,p,n-k-#permcycles(p)||print(p))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNw3SNPJ0sjVt0_KLClKLcoGcAp083WxdZRAvuTI5J7VYo0CzpqagKDOvBMjShOqzA2rQyFOwVTDUUTDRUQDxsoE8Ax2FPAVdkCBEQ56Cko6CkkK2gpKVkqa1AsgyhWxNmCkwVwAA)
A port of [@Jonah's J answer](https://codegolf.stackexchange.com/a/255244/9288).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 83 bytes
```
f=(n,k,a=[])=>n--?[f,...a].flatMap((v,i,[...b])=>f(b[b[0]=v,i]=n,k-!!i,b)):k?[]:[a]
```
[Try it online!](https://tio.run/##Nc6xCoMwGATgV1FwSDAJFjoZo3uh7dAxBIzWSBr5IypCEZ/dxqHTwccd3Eevem4nOy4U/Ls7DiMQEEe0kAqLEiitpCGMMa2YGfRy1yNCK7FEBmvOikGNbGSmRFAlwpbGsSUNxrmrpMqlVofxExq6JQJx4VCIK4c0xX90IuOuAO6CtR5mP3Rs8D2qkw12EiWb2yNahry9ng82L5OF3povMudPjPca8@MH "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒcżU$œcⱮŻ}y@ƒ€€R{Ṛḟ/Q
```
A dyadic Link that accepts \$n\$ on the left and \$k\$ on the right and yields a list of those permutations of \$[1,n]\$ which require a minimum of \$k\$ pairwise swaps to sort.
**[Try it online!](https://tio.run/##ATEAzv9qZWxsef//xZJjxbxVJMWTY@KxrsW7fXlAxpLigqzigqxSe@G5muG4ny9R////NP8z "Jelly – Try It Online")**
### How?
Starting with the sorted deck the code performs all possible (up to rearrangement) swap sequences of lengths \$j \leq k\$ then takes those reachable with exactly \$k\$ swaps and removes any that were reachable with less.
```
ŒcżU$œcⱮŻ}y@ƒ€€R{Ṛḟ/Q - Link: integer, n; integer, k
Œc - unordered pairs (n) (e.g. n=3 -> [[1,2],[1,3],[2,3]])
$ - last two links as a monad - f(x=that):
U - reverse each pair
ż - (x) zip with (that) -> P = [[[a,b],[b,a]],...])
} - with chain's right argument:
Ż - zero range (k) -> [0,1,2,...,k]
Ɱ - map (across j in that) with:
œc - (P) combinations (j) -> all (ordered) length j pair-tuples
{ - with chain's left argument:
R - range (n) -> [1,2,3,...n]
€ - for each (list of pair-tuples):
€ - for each pair-tuple:
ƒ - reduce (pair-tuple) starting with (range(n)) using:
@ - with swapped arguments:
y - translate (e.g. [3,1,2] y [[2,3],[3,2]] -> [2,1,3])
Ṛ - reverse
/ - reduce by:
ḟ - filter-discard
Q - deduplicate
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29 bytes
```
LsmmXd_kk.cSQ2b{-F_myF]SQdUhE
```
[Try it online!](https://tio.run/##K6gsyfj/36c4NzciJT47Wy85ONAoqVrXLT630i02ODAlNMP1/38TLmMA "Pyth – Try It Online")
### Explanation
```
L define y(b): applies every swap possible to every sequence in b
sm b for all d in b
m .cSQ2 for all pairs of unique elements in range(1,n+1), k
Xd_kk generate a sequence by swapping the elements of k in d
m UhE map d over range(k+1)
yF d apply y d times to
]SQ [range(1,n+1)]
_ reverse this
-F fold over subtraction (remove all states with fewer flips)
{ deduplicate
```
] |
[Question]
[
[Futoshiki](https://en.wikipedia.org/wiki/Futoshiki) is a logic puzzle where an \$n×n\$ Latin square must be completed based on given numbers and inequalities between adjacent cells. Each row and column must contain exactly one of each number from \$1\$ to \$n\$ while satisfying the inequalities.

In a solved Futoshiki puzzle any row (or column) forms a [linear extension](https://en.wikipedia.org/wiki/Linear_extension) of the poset induced by that row's inequalities. Counting linear extensions of posets of this kind is a [polynomial-time problem](https://math.stackexchange.com/a/4540334/357390), as opposed to #P-complete for [the general case](https://codegolf.stackexchange.com/q/46836).
Given the sequence of \$n\ge0\$ symbols between cells of an initially empty Futoshiki row of length \$n+1\$, each of which is one of \$<\$, \$>\$ or \$-\$ (nothing; no constraint), output the number of solutions of that row when considered in isolation. You may use any three distinct symbols for \$<,>,-\$, but your program must pass all test cases below in reasonable time.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
## Test cases
```
"" -> 1
">" -> 1
"<" -> 1
"-" -> 2
"<>" -> 2
">-" -> 3
"><>" -> 5
"---" -> 24
">->>" -> 10
"><><>" -> 61
"->->-<<>" -> 11340
">-<><--<>><" -> 4573800
"><>><><<<>><>" -> 26260625
">><<>><<>><<>>" -> 120686411
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 84 bytes
```
t["-"<>#<>"-"]&
t@s_:=t@s=Tr[t/@StringReplaceList[s,"->"|"<>"|"<-"|"--"->"-"]]~Max~1
```
[Try it online!](https://tio.run/##NYvBCsIwDIbvPkXJYKeF4VW6sAdQEPVWipSx6cAN2XIQ1L16Tbt6yJc/H/kHx/d2cNw3zneq8mwAQVOmSbbNN1zP110lrC6T4bI@89SPt1P7fLim3fczm7kAJPhIKQAFiMFI3S4H91q2/igdNplCUp3JrFW5Kmv1BigUUIAOwJjiTTHTeiCuFxIlm7wY1P@CWBSQTj/hTccVBcWcBr7@Bw "Wolfram Language (Mathematica) – Try It Online")
A fast solution using memoization. Finishes all test cases in a second.
Without memoization (`t@s=`) it would save 4 bytes, and the last three testcases would take 42 seconds, 4 minutes and 20 minutes respectively on my computer.
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
Count[Sign@*Differences/@Permutations@Range[0,Tr[1^#]],#]&
```
[Try it online!](https://tio.run/##LYvBDoMgEAV/hUDioYFY75aQ6AeY2huhDTFgOYgJ4Knx2@mK3mbezi46fc2ik5t0tuiRu3XzSY5u9uLWO2tNMH4ysRaDCcuWIFx9FE/tZyPv9BVk8yZKUaKqPAQHrwQxjqwcE9jc6WiiJBT9MMfHoaEIt4XYgazgZ1dKoQrVAjoMM8clK8FBxXlhfgpjpzHOr/XaYWEt8J7/ "Wolfram Language (Mathematica) – Try It Online")
Brute force. Cannot pass the last three testcases in reasonable time.
Takes input as a list, where `>`, `<`, `-` are represented by `1`, `-1`, `_` respectively.
[Answer]
# JavaScript (ES6), ~~110~~ 98 bytes
```
f=(s,m=t=0,j,p)=>s[~~j]?[...s,0].map((_,v)=>m>>++v&1|p*!eval(p+s[j]+v)||f(s,m|1<<v,j+1|0,v))|t:++t
```
[Try it online!](https://tio.run/##hY/dCoIwGIbPu4rqILb246bWQei6EJGQ0mhojiY7Gt26TSKxJvSdPu/7vHyyMIU@P26qI/f2UvZ9lQKNm7RLGZZYwVTo7PmU@TGjlGrMctoUCoATNg41QiBkNtyq7ao0RQ0U0pnMkYHWVoPG8iQxWCJumStA2x0Q6vpze9dtXdK6vYIKrNcQLj8XBEu@@OFiEpjjyR9Ovnno9ScDc1yQLx55fCJwfOftEzLlYewPiNEwPMBmFsYNF9j7LzoFSd6ZwcCjmPUv "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
s, // s = input string of length N
m = // m = bitmask of already used numbers
t = 0, // t = number of solutions
j, // j = pointer in s, initially undefined
p // p = previous number in the permutation
) => //
s[~~j] ? // if there's still something to process:
[...s, 0] // create an array of length N + 1
.map((_, v) => // for each value at position v in there:
m >> ++v & 1 | // increment v; abort if v was already used
p * !eval( // or p is defined and
p + s[j] + v // the expression p + s[j] + v
) || // is falsy once evaluated as JS code
f( // otherwise, do a recursive call:
s, // pass s unchanged
m | 1 << v, // update m to mark v as used
j + 1 // increment j
| 0, // or force it to 0 if it was undefined
v // set p = v
) // end of recursive call
) | t // end of map(); yield t
: // else:
++t // increment t
```
[Answer]
# [Python](https://www.python.org), 111 bytes
```
f=lambda s,t="",b=1:b and(s+t==""or(s<">">"<"!=t[-1:])*b*f(s[1:])*f(t[:-1])+f(s[1:],t+s[:1],b*-len(s)/~len(t)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9BboQgFIb3cwrKChSmog41RrxGF8YFdjQ1YdQIbdJNL9KNm_Y6Xc9t-lRMQ-D9-fne_-DrZ_pwr-OwLN9vruPZfeyU0bfmqpFlTmHMGiXyBunhSmzoFDjjTGyBS1gFflCu4iKvadAEHbHVJjviqpyLmobeYi60VS5q1gTctAOx9PFzrY5S6sc-d-OMDOoHNE5wE9H8hHo2IoVueiLtuzbMnO1kekcw4iXClAKg-vPcTka_tCTAXGHwprkfHIFW1pH-iF_uv3hrEyd4thfFIfgmYnDKQ5W7l4Dy5gU47sl0BUofFG2Mp-QaB3e88IYQSboSHBAOR7lPTS9PSRbtrWt3sZU9XcYykjHMA6v433tcHMlMpkLs__oD)
### [Python](https://www.python.org), 118 bytes
```
f=lambda s,t="",b=1:(s<">">"<"!=t[-1:]and(s+t==""or b*f(s[1:])*f(t[:-1])))+(s>""and f(s[1:],t+s[0],b*-len(s)/~len(t)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9BboMwEEX3OYXrlR3sFAOhCGFfowvEAhpQLDmAsBupm16kGzbtdbrObTqAUWXZ8_XnzR_562f8cNehn-fvd9fx7HHvpKlvzaVGljmJMWukyIktsIJT4CfpSi7yqu4vxAZOAjFMqDl2xJZgUxCuzLmoKKUBsQpjIJHvMhfYMqxYc-Sm7Ymlz59LdcD67a8dpBmkezSM0AlpfkCaDUiiWz2S9l4bZk52NNoRjLhCmFIApD5N7Wjqt5YcMZcYvHHSvSMwyjqi9_j58YvXMXGAz3hR7IKvIgJH7UptXgzKm2fguCeTBVA-KFwZT6VLHPR44Q0h4mQhOCAcHrVtTc4vcRZuo8t0sZYtPY3SMI1gH1jF_93iojDN0kSI7V9_)
### [Python](https://www.python.org), 123 bytes
```
f=lambda s,t="",b=1:(s[:1]!=">">"<"!=t[-1:]and(s+t==""or b*f(s[1:])*f(t[:-1])))+(s>""and f(s[1:],t+s[0],b*-len(s)/~len(t)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9BboQgFIb3cwqGFYwwFXWsMcI1ujAutKMpCaNGaJOmSS_SjZv2Ol3PbfpUTEPg_fnf937g62d8dy9DP8_fr67j2f2jk6a-NdcaWeYkxqyRIie2zEV1lFjBKvBRupKLvKr7K7GBk4ANE2pOHXBgUxCuzLmoKKUBsQpjIJHvMhfYMqxYc-Km7YmlD59LdcD6Jzx1kGaQ7tEwQiek-QFpNiCJbvVI2rfaMHO2o9GOYMQVwpQCIPV5akdTP7fkhLnE4I2T7h2BUdYRvcfP91-8jokDfMaLYhd8FRE4aldq82JQ3rwAxz2ZLIDyQeHKeCpd4qDHC28IEScLwQHhcKjt1uTyGGfhNrpMF2vZ0tMoDdMI7gOr-N9bXBSmWZoIsf3rDw)
### [Python](https://www.python.org), 165 bytes (@Steffan)
```
f=lambda s,b=1:s==""or sum((b:=b*(i-len(s))/~i)
*("<"<s[i]and">">s[i+1]and f(s[i+2:])*f(s[:i]))for i in range(len(s)-1))+(s<">"and f(s[1:]))+(s[-1]>"<"and f(s[:-1]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9BcoMgGIX3OQXDCoykYozNOMA1usi4wEZbZog6YjrTTS_STTbpdbrObfojOF2Ij8d73w_fP-Pn_D70t9v9Onfs-Lh30upLc9bIpY3klZMS42FC7nohpKlkkxDDbNsTR-nTl6GbhGCBhTuZWvdnrLACueV-gzridV7VNPGyMjWlHbAMMj2adP_WkkBinNItcQLqa49Dy3snxmsFE1a_gj2l8bIvnmY9bRgBlNFqg0w6IIkueiTth7ap3bnRmplgxBTClEJAmt3Ujla_tiTBTGLwxsn0M4Fq2hGz4m-PX7zU-AYuFoVYBVtEDo5alQreHlQ0D5BjMVn4gIqgbMnEVOlxcMZENDjfFz7BIMJgUWFqcXjeH7NQ9W2x_AK9zMuszGEeWOL_C7g8K49lwXl41x8)
### [Python](https://www.python.org), 174 bytes
```
f=lambda s,b=1:s==""or sum((b:=b*(i-len(s))/~i)
*((s[i]>"<")*(s[i+1]<">")and f(s[i+2:])*f(s[:i]))for i in range(len(s)-1))+((s[0]<">")and f(s[1:]))+((s[-1]>"<")and f(s[:-1]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY-xboMwFEX3fIXlyY_gFBNCI4T9Gx0qBtNAa8kBBKRSl_5Ilyzt2F_pnL_pMzaqOmCu7rv3PPvja3ibX_ruev28zC0_3r5bafW5PmkyxbUUxSQlpf1IpsuZsbqQdcQMt03HJoC7dwObiLHp0VSKlhQiJ7eiKqmioLsTaRcjLSqInCxMBdAizRDTkVF3zw3zLC4Ato6U_C8LrPoBF37HOinQAAi3fnBQ66D9gLwEig0xcU8kOeuBNa_axnY3DdbMjBKuCAXAgDS7sRmsfmpYRLmk6A2j6WaG1bhlZsVfbz90qYkN3i2IchV8ESk6alXKe3tUwTxgjodk5gIqgJIlE1K5w-GMl8EQYp-5BMcIx0P5rdnhfn9MfNW1y-Xn6XmaJ3mK-9Aq_z6PS5P8mGdC-Hf9Ag)
This will surely be outgolfed to oblivion but it finishes all test cases in a second on ato.
Takes "=" instead of "-" because it sits conveniently between "<" and ">" codepointwise.
Uses a divide-and-conquer-ish approach: take the first element recurse into the two leftover halves and multiply their counts with each other and the number of ways they can be merged which is some binomial coefficient.
[Answer]
# [Goruby](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby/9289#9289), ~~72~~ 50 bytes
-28 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus) and [G B](https://codegolf.stackexchange.com/users/18535/g-b).
I wasn't going to post this since it craps out on the last three test cases on ATO but it looks like I'll be in good company anyway, so here it is.
```
->s{[*0..s.sz].pe.ct{|a|s.a?{|t|1>t*=a.po-a[-1]}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVbNjts2EAZ69FPMejdrybFlyfvTYBFnkxSbtpcGSIAeargGJdO2Ev2BpDaxLedFesmhPfaBmqfpDCnJsuMEKbpYmORw5uNw5puh_vhT5P7q46fW36fwY0pzyASP8hmHPiyVyuTNYLAI1TL3nSCNB6Rhfvwo9Qcxk4qLwSKN5tPSzhF-K4iYlPDSf8MD1QJ4-lQrLJlcwgg22xbK7rnwU8l7cPbr3avnL1_f4U417UESRqgz43OIuVqms2kcShkmC4h70GU9OPdxG0ChUQN8DGPclzyaO9qDCUygKEYQMxUs0XpqwKQV22N3ohHCOYKcn4PBA5hOJU9m06ml6CAbNkWXiYUsym0A3_HDZIZgDr9nkdXORBpsCu2CPmbGFCvg7AN6ti-Ebdt2AhZF1tkHm849-9AA1Rv6KLuUbvXII8lLgYLbA_coDjbcgMwzLox6MmtVv43AlsFuVTE9jIdEnU6nBzGO5AnzI15tGn8E7gx-P91IR6VT6Sxk7lsDZ2Bv2pbTvbXb8BBe8QV_nzlcBizj1tm5vd0OtG3sLATPLGE7MhVqihSbpVCEVUxDA6mdIiU0V7ngJMms8xsZrrkNjx9DeHDD8jIm3WkiVU2S4AvkCHrfwI2gBxqNJUrWNFHAkhkIjo4lZnu64MpSZXBYKDn8wmJ-J0QqetDOkzAJVcgidH5W48HpJti2ezrEXFiefXCTJYaHIzTzfcHvQ6bCNPmG3JCGyYteprmYBgwdGoF1-8xxbn-zYTRClQbnYwdJzN9bxmwVV6TznDxTKYp11DfFukBkTGiik00dANlv_FrblKBNoQRec1cfCX-vIE8ijg3A2jtfK6IPtKqdrO30LnTprrWsjLfZCo_wVu9gaChP-iYELasC-qyCTFc5wqHDuJqw1lwhVNPMsARLFSR8JsJ7pmojLMSdeQleqlTnLC1G2fwJ0-nT5B1OApqcdEwGslxJaJ9u2JZHUdpDwvjbVEQzTZx9n-cWMcJzXWNZZi7GpCUFwXRehOv183y9bnXG4Sjpdi8f9L2rXvjQu5gURbLdoSFLmQTJVvr4Cn-WTt8tw8jEzgU9h1XIo4PYoV6eqDKyLuj5np7WNXF8JgRb1Sem0Wyqk1ZS10i15E0aJk3DFwyz-ANNv2hNvtQ10G5_fvjPicIOJWoAzoIlqDDmZBImgX707pI85oK40DR9jURLFrXlAGQWhaq1O5UZxpDU6nQadW3pK2O1UQMIdlzpwxHRg3BMWGKFlGeJzLBlwzxiSvGkGk-wmcQZQyaW4wmgg2mAPYiGie3QtTYFgZqipGcK2npKzp5uaGtr3hp6QKI0eFuVP7Gzvg3Vn8wjaqPM-aoZdveIBdxiDuWtkmLBGoBdEVX5N39lQnRzMJpYxlhhpRXe7q3VCbodeuJKmeaFsca6PnJCmT-VikYX0SrmNdEOUqvgqLhD4gfa1Y5uFHqkCG6bnNg76Tgl_1PyxzdlGCfYWsY3BPE_s0mZ_Fri6ls1_UfPMmp05VjvVfLqjnvlsYr9tPpg233J7J9GH0r64Rc8uC9q5gT3Tv1RQx2XvmuOedqs5_nor1zN-4_-GfafyM246zoOvlLriZNxJ1CbghXSYbf4NBXeE9UdMSdL-2zc9ybb7dZYfvqudQpPoI__Hs76NAMXZ4_1zGvpd5geKHpcx3j4eILdmDY9WiBWc7m_cqvVUO_1YKc9NMY9qHUuKsme3pXGQbWG5vCyNibVprrn7qEcgF17JVrD1tU6-yDexSXhnNaH7MDc5lrLKqvLq-8vHrkNu6ZSPRyR19e6Hl6718OrHUL_mMEXVrXzQ_f60fWl57UmrUbydP1o1knNUf0hn8F8XC4nRChDiY8fzfgv)
# [Ruby](https://www.ruby-lang.org/), ~~95~~ 67 bytes
-22 bytes thanks to Dingus and G B.
```
->s{[*0..s.size].permutation.count{|a|s.all?{|t|1>t*=a.pop-a[-1]}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZLNaoQwFIWhS5_igrvBhCT-1EW1iz6GSMk4ygw4KpO4mKpP0o2U9qHap2nUUWOZQiD33JzzJSF5_7zU-2v_kQVftcyQ__2CQtFEO4KxwOL0lsa4Si_nWnJ5KguclHUhm5a3AvM8f25a2dJQ7gKOq7JCPEI07rpuQv08GCaEgNSgqkJDBURVT2NFDZkK-ZpwkQoIIDIAotgCc1ikg1AsXW4VmRUb1yxY3WwKW7B47Lmz8bkjR9k0J3OW8GDV7ZRsKH9gHr3RtCwZPVsItZ2BYy6brDCi67E3pxz30faJltNNy3Snv1zLYx7xmLsS0L3AP2o5PCOe7zmUGrGhPR5OeXKEQwmtuJ73ZS5atU0FWXSTsZEWh-lL9P00_wI)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Pretty horrific brute force solution, exacerbated by me being so horribly out of practice!
Will crap out on inputs longer than 8 characters.
```
¬³ð á ®ã2 e@OxXqUgY
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=rLPwIOEgruMyIGVAT3hYcVVnWQ&input=Ii0%2bLT4tPDw%2bIg)
```
¬³ð á ®ã2 e@OxXqUgY :Implicit input of string U
¬ :Split
³ :Push 3 (value is irrelevant, we just need an extra element)
ð :0-based truthy indices (which is all of them as every element is a non-empty string, or 3)
á :Permutations
® :Map
ã2 : Sub-arrays of length 2
e : Does every pair return true
@ : When passed through the following function as X, at index Y
Ox : Eval as JavaScript
Xq : Join X with
UgY : Character in U at index Y
:Implicit output of sum of resulting array
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 87 bytes
```
≔⪫--Sθ≔⦃⦄η⊞υθFυ«§≔ηιEΦ⊖Lι∧⁻>§ικ⁻<§ι⊕κ⁺⁺…ικ-✂ι⁺²κF⁻§ηιυ⊞υκ»FLθFΦυ⁼⊕ιLκ§≔ηκ∨ΣE§ηκ§ηλ¹I§ηθ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZVFNSwMxEMVj-ytCThPIHvQktCyUqrBisdCjeFi3aTdsmv1IIkrpL_HSg6In_40Xf00n2S1dMZDA5L2ZN2_m7SvL0yYrU7Xffzi7ii5_z34mxsi1httSaqBRRDlJdOXswjZSr4ExTmo2Gnas7Y6THMO5Mzm4FlqVDQHHyHY4aFkTm-ileIGcE8nJLK3gRiorGrgSWSM2QluxhDuh1zYH6QUmegkzqZ0BGqP-MR-TCw930PgvlOhTMaQxz5wrJIZn-popMc3Lqq3CCY0ovgslM-G_AukiCOAZDQfBRavU7x9zHGPk6LdA6q513BmoEQ1x5xFJ17VLlYF-g75OlxAUyb9JFZzcN7BwG_AD6wPsZBtDFYye-57nuCEL09TYPr_2ft7NU2a6HX8-0OhZ0cfvOB6PT7cFDw) Link is to verbose version of code. Explanation: Port of @alephalpha's Mathematica answer. The number of solutions for any given string of inequalities is the sum of the numbers of solutions when the highest number is placed in any legal cell (i.e. not to the right of `>` or to the left of `<`). These numbers of solutions are equivalent to the numbers of solutions of a reduced string of inequalities where the cell and its inequalities have been replaced by a separator.
```
≔⪫--Sθ
```
Wrap the inequalities in `-`s. This makes the legal highest cells easier to identify.
```
≔⦃⦄η
```
Start collecting lists of reduced strings of inequalities.
```
⊞υθFυ«
```
Start a breadth-first search with the wrapped input string.
```
§≔ηιEΦ⊖Lι∧⁻>§ικ⁻<§ι⊕κ⁺⁺…ικ-✂ι⁺²κ
```
Get the possible reduced strings of inequalities for this string and save them in the dictionary.
```
F⁻§ηιυ⊞υκ
```
Add those strings that have not yet been seen to the search for further processing.
```
»FLθFΦυ⁼⊕ιLκ
```
Process the strings of inequalities in increasing order of length.
```
§≔ηκ∨ΣE§ηκ§ηλ¹
```
Update the dictionary with the total count for this string of inequalities.
```
I§ηθ
```
Output the total count for the wrapped input string.
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
≔⁺-Sθ⊞υ⟦⟧Fθ≔ΣEυEΦ⁻Eθνκ∧∨⁻ι<‹↨κ⁰μ∨⁻ι>›↨κ⁰μ⁺κ⟦μ⟧υILυ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9BasMwEEX3PYXQagQydBmIMaSFloJDDF4aL1RHcYRt2dZIuUw2WbQ0V-olcoaMmnQRxEjo_a_P1_Hc7JVrRtWfTt_B75LF72WFaFoLRR8QeMIl-7BT8KV3xrYghGSzWD4VAfcQJKtquuxGx2AW7P6yDAOs1RTleLyZ3msHa2MpMIJZMksxHc3KbmHzrxnJeMqJ5hoRXhRq6CR7JjDQPNiyaHt3WsXkRydtf9UJVEMtRAQhNqb-Hl4Vesi1bT3VJ235hZ8N3v_-U_Hk0PP6nGS00jS74Ss) Link is to verbose version of code. Brute force, so the last few test cases will time out on ATO. Explanation:
```
≔⁺-Sθ
```
Prepend a `-` to the input string as the first number is not constrained by any previous number.
```
⊞υ⟦⟧
```
Start with a list of no numbers found.
```
Fθ
```
Loop over each constraint.
```
≔ΣEυEΦ⁻Eθνκ∧∨⁻ι<‹↨κ⁰μ∨⁻ι>›↨κ⁰μ⁺κ⟦μ⟧υ
```
For each list so far find all the numbers that satisfy the next constraint and create a new list of lists.
```
ILυ
```
Output the number of lists found.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), Fast: 47 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) / Slow: 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
### Slow:
```
L‘Œ!IṠnẠ¥ƇV€L
```
A monadic Link that accepts a list of characters - `<->` represented as `-01` respectively and yields the solution count.
**[Try it online!](https://tio.run/##y0rNyan8/9/nUcOMo5MUPR/uXJD3cNeCQ0uPtYc9alrj8///fyVDXSBUAgA "Jelly – Try It Online")** Or see the, truncated [test-suite](https://tio.run/##y0rNyan8/9/nUcOMo5MUPR/uXJD3cNeCQ0uPtYc9alrj8/9RwxwbXTsgqWtg@KhhbiWQpaChBCSVNK0UgAJZOofbj23SfNS44@ieyP//o5WUdBSU7ECEDYjQBbPAfDsw2w7C0dWF8HTt7KCiQPFYAA "Jelly – Try It Online") (shows the Link input in parentheses).
##### How?
```
L‘Œ!IṠnẠ¥ƇV€L - Link: list of characters, A, from '-01' (equivalent to '<->' respectively):
L - length (of A)
‘ - increment
Œ! - all permutations of [1..that]
I - deltas (b-a for each neighbouring pair (a,b) in each list)
Ṡ - signs -> 1 if a<b; -1 if a>b
V€ - evaluate each (of A) as Jelly code -> '-': -1, '0' -> 0, '1' -> 1
¥Ƈ - keep those (of the delta lists) for which:
n - not equal? (vectorises)
Ạ - all?
L - length
```
---
### Fast:
```
ḅ3$Ɲ%6ỊTœP€⁸;ḊŻ$}¥/€Ñ€Sȯ1
i@‘ịɗ,Ç$;ɼ0ịƲe?®
Ø0jÇ
```
A monadic Link that accepts a list of integers - `<->` represented as `[2,0,1]` respectively and yields the solution count.
**[Try it online!](https://tio.run/##y0rNyan8///hjlZjlWNzVc0e7u4KOTo54FHTmkeNO6wf7ug6ulul9tBSfaDA4YlAIvjEekOuTIdHDTMe7u4@OV3ncLuK9ck9BkDOsU2p9ofWcR2eYZB1uP3/o8Z9djaZjzauA7L/K9nZ2dggsBIA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjlZjlWNzVc0e7u4KOTo54FHTmkeNO6wf7ug6ulul9tBSfaDA4YlAIvjEekOuTIdHDTMe7u4@OV3ncLuK9ck9BkDOsU2p9ofWcR2eYZB1uP3/o8Z9djaZjzauOzrp4c4ZjxrmKGgACU0rhUcNc7NUgNqObdIE2nB0T@T//9FKSjoKSnYgwgZE6IJZYL4dmG0H4ejqQni6dnZQUag4UETXBqYBKKoLJOxsoGpAymzAFFjADsyGYqVYAA "Jelly – Try It Online") (shows the Link input in parentheses).
##### How?
Implements the same algorithm as [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)'s [Mathematica answer](https://codegolf.stackexchange.com/a/252362/53748) - go show some love :)
No built-in cache so this implements one. It's not got particularly great performance because (a) Jelly has no dictionary or hash-map data type, (b) Jelly only has a single register, so I keep values alongside their corresponding keys so it must search through those too (they can never match as keys are lists while values are positive integers), and (c) I went with a golfy implementation which looks up the key twice.
Note: the main Link is the one at the bottom, `Ø0jÇ`.
```
ḅ3$Ɲ%6ỊTœP€⁸;ḊŻ$}¥/€Ñ€Sȯ1 - Link 1, calculate count: list of integers, A, from [0,1,2] (equivalent to '-><' respectively):
ḅ3$Ɲ - convert each neighbouring pair from base 3
%6 - modulo by six (vectorises)
Ị - insignificant? (effectively is that 0 or 1?)
T - truthy indices
-> starts of substrings equivalent to: '->', '<-', '<>', and '--'
i.e. possible surrounding chars of the highest value
œP€⁸ - partition (A) at each of those (discarding the index itself)
¥/€ - reduce each by:
$} - apply to the right hand one:
Ḋ - dequeue
Ż - prefix a zero (equivalent to a '-')
; - (left one) concatenate (that)
Ñ€ - call Link 2 (below) for each (if any)
S - sum
ȯ1 - logical OR with one
i@‘ịɗ,Ç$;ɼ0ịƲe?® - Link 2, get count: list of integers, A, from [0,1,2] (equivalent to '-><' respectively):
® - recall from the register
Our cache: initially zero, but becomes a list of inputs (lists)
and outputs (positive integers) with a zero prefix
e.g. [0, [2], 1, [2,2], 1, [1], 1, [1,2], 2, ...]
'<'=1 '<<'=1 '>'=1 '><'=2 ...
? - if...
e - ...condition: exists?
ɗ - ...then: last three links as a dyad - f(A, cache)
i@ - index (of A) in (the cache)
‘ - increment -> index of the pre-calculated value
ị - index into the cache -> pre-calculated value
Ʋ - ...else: last four links as a monad - f(A):
$ - last two links as a monad - f(A):
Ç - call Link 1 (above)
, - (A) paired with that
ɼ - apply to the register & yield:
; - (register) concatenate (that) -> adds the "key" A (a list) and value
0ị - 0 index into -> gets the value back out
Ø0jÇ - Link 3 (main Link): list of integers, A, from [0,1,2] (equivalent to '-><' respectively):
Ø0 - [0,0] (equivalent to "--")
j - join with A
Ç - call Link 2 (above)
```
---
### Also:
Fast version taking the characters as given in the question \$51\$ [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page):
```
*Ɲ%87%5ḂTœP€⁸;45;Ḋ}ʋ/€Ñ€Sȯ1
i@‘ịɗ,Ç$;ɼ0ịƲe?®
⁾--jOÇ
```
**[Try it online!](https://tio.run/##y0rNyan8/1/r2FxVC3NV04c7mkKOTg541LTmUeMOaxNT64c7umpPdesDBQ5PBBLBJ9YbcmU6PGqY8XB398npOofbVaxP7jEAco5tSrU/tI7rUeM@Xd0s/8Pt/4FyWUCelYJm5P//0UpKOgpKdiDCBkTogllgvh2YbQfh6OpCeLp2dlBRqDhQRNcGpgEoqgsk7GygakDKbMAUWMAOzIZipVgA "Jelly – Try It Online")**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) (non-competing*†*), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
*† Non-competing, because the challenge states* "your program must pass all test cases below in reasonable time"*, which this brute-force approach definitely doesn't do. (And yes, I know the challenge doesn't contain a [restricted-time](/questions/tagged/restricted-time "show questions tagged 'restricted-time'") tag, so it isn't a hard requirement.)*
```
Ćāœεü2I‚øε».V]PO
```
Uses `‹`/`›`/`1` for `<`/`>`/`−` respectively, and takes the input as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//SNuRxqOTz209vMfI81HDrMM7zm09tFsvLDbA////aKVHDbuUdIDkTjCJyo4FAA) or [verify some of the smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlUr/j7QdaTw6@dzWw3uMDq171DDr8I5zWw/t1guLDfD/r6QXpvM/OjpWRyFa6VHDLiUoYyeEYYjg6yBL7wJyDZE5aCoMwfJoagyhKjBMQmhGMSgWAA).
**Explanation:**
```
Ć # Enclose the (implicit) input-list; appending its own first item
ā # Push a list in the range [1,length] (without popping), which will
# be a list in the range [1, input-length + 1] due to the enclose
œ # Get all permutations of this list
ε # Map each permutation to:
ü2 # Create overlapping pairs of the integer-list
I‚ # Pair it with the input character-list
ø # Zip/transpose; swapping rows/columns
ε # Map over each pair of pair + character:
» # Join the inner pair by spaces, and then both items by newlines
# (e.g. [[1,2],"‹"] becomes "1 2\n‹")
.V # Evaluate and execute it as 05AB1E code
] # Close both maps
P # Get the product of each inner list
O # Sum the list to get the amount of truthy values
# (which is output implicitly as result)
```
[Answer]
# [Rust](https://www.rust-lang.org/) + itertools, 149 bytes
```
use itertools::*;|s|(1..(s.len()as i8+2)).permutations(s.len()+1).filter(|p|p.windows(2).zip(s).all(|(a,&c)|c==1||(a[1]-a[0]).signum()==c-1)).count()
```
[Try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=be415fc1bec6e36040962d4c9497c984)
Can be assigned to a variable of type `fn(&[i8]) -> usize`. It uses this mapping of characters to ints as input:
```
'>' 0
'<' 2
'-' 1
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 130 bytes
```
DgGHI!GR]1=Tgt^2tl.BGtH=bYVhG ab1FdUtHIv@.[\0tH.BNd=k-tHd Xb_1-/*s<>T.<.>Nktk^2tkhH.!k@b_1)))Rb;J.!hlzVcz)=/*Jegim!!xNdN2lN.!hlN;J
```
[Try it online!](https://tio.run/##FctBC4IwGIDhv@KOE/xMr25DJNr0sIOYFGXRWriYQdBHlH9@Ge/x4X1@0YWwHqWqiWyHjHcjnnKcoJKouNn3TkYXk23sFlX9LuFwXKGCSlvuE1Q22plzlqTxi4kOGAjt0S@7dwqILxejlLamaIC4ae6vM@Vp3NzG@4OQj7Y6n/RfdNGEELElIdgP "Pyth – Try It Online")
Uses input `<>` in place of `<>-`.
Okay, so... this is pretty bad. For one thing it's like 17 bytes longer than the current best python, and it's slower. Depending on what "reasonable" means it may not even meet the requirements. Alright, so why did I bother sharing it? Well because I think the algorithm is cool, and I'm really just amazed I got it to work. It uses a formula presented in this [OEIS](https://oeis.org/A060351), I'll give a brief explanation.
So first we can split the sequence along any `-` into some number of subsequences. Our base point for the final answer is then the number of permutations of the whole sequence divided by each subsequences, this is computed with simple factorials. Then all we need is the number of valid subsequence orders. This is where the OEIS formula comes into play, it basically comes down to a particular sum of sequences one less in length than itself. We multiply all of these by the base point and that's our answer.
] |
[Question]
[
There are times when a large number of people need to choose something. They all want to get the stuff they choose, obviously, but it's impossible to please everyone that way, so a usual compromise is to give people three choices and try to make sure that everyone gets one of their choices.
For instance, consider three people who want to choose their parts in a play. The play has three parts. Imagine that the parts are called Word, PowerPoint and Excel, and imagine that the choices are like this:
```
Person 1 chooses: (from first choice to third choice)
Word
PowerPoint
Excel
Person 2 chooses: (from first choice to third choice)
PowerPoint
Excel
Word
Person 3 chooses: (from first choice to third choice)
Excel
Word
PowerPoint
```
Here, it is easy to assign Word to person 1, PowerPoint to person 2 and Excel to person 3 and thus give everyone their first choice. However, it is not so easy if...
```
Person 1 chooses: (from first choice to third choice)
Word
Excel
PowerPoint
Person 2 chooses: (from first choice to third choice)
Word
PowerPoint
Excel
Person 3 chooses: (from first choice to third choice)
Excel
Word
PowerPoint
```
Since person 3 is the only person who wants Excel, person 3 automatically gets Excel.
Person 1 and person 2 both want Word, but there is only one Word, so suppose we assign Word to person 1. Then person 2 cannot get Word but his second choice, PowerPoint, has not been taken, so we can assign PowerPoint to person 2.
It gets even more complicated here:
```
Person 1 chooses: (from first choice to third choice)
Word
PowerPoint
Excel
Person 2 chooses: (from first choice to third choice)
Word
Excel
PowerPoint
Person 3 chooses: (from first choice to third choice)
Excel
Word
PowerPoint
```
Again, person 3 is the only one who wants Excel, so he gets it.
If we assign Word to person 1, then person 2 cannot get Word. But person 2 cannot get Excel either because person 3 got it! This means that person 2 is stuck with his third choice, PowerPoint. Obviously he is not very happy.
If we assign Word to person 2, on the other hand, person 1 can get his second choice, PowerPoint, and overall everyone is happier.
And that is the aim of this challenge: to make everyone as "happy" as possible.
## Challenge
Write a program or function that takes in a list of lists. Each sublist contains three positive integers. If the length of the big list is \$n\$, then the positive integers from 1 to \$n\$ will be present in the list (and no other integers will be there). For instance, above we had three people, so there were three possible choices. If there are twenty people, then in total there will be the integers from 1 to 20 present in the list.
Input may be taken in any reasonable format similar to the one above.
Your output should be a list of \$n\$ distinct positive integers corresponding to the integer assigned to each person. This list is, due to the input format above, a permutation of `1..n`. The output should be such that the people represented in the input are as "happy" as possible.
Output may be in any reasonable format similar to the one above.
Your code may do anything if it receives an empty list.
## Quantifying happiness for the purposes of this challenge
The "happiest" arrangement is the one where the following expression is minimal:
$$\sum^{4}\_{i=1} ix\_i$$
Here, \$x\_i\$ is the number of people who got their \$i\$-th choice. \$x\_4\$ is the number of people who got *none* of their choices.
This measure means that if many people get none of their choices, then the population as a whole will be *very* unhappy. On the other hand, if everyone gets their first choice, then the population will be very happy.
If there are multiple arrangements that have the same "happiness value", then you may output any number of them.
## Test cases
```
[[1,2,3],[2,3,1],[3,1,2]] -> [1,2,3] // first worked example above with 1=Word, 2=PowerPoint, 3=Excel
[[1,3,2],[1,2,3],[3,1,2]] -> [1,2,3] // second worked example
[[1,2,3],[1,3,2],[3,1,2]] -> [2,1,3] // third worked example
[[1,2,3],[1,2,4],[2,3,4],[2,4,3]] -> [1,2,3,4] // happiness measure 7; multiple answers possible
[[1,4,2],[1,4,2],[1,4,2],[2,3,4]] -> [1,2,4,3]
[[1,2,3],[2,3,5],[4,5,1],[5,1,2],[5,4,3]] -> [1,2,4,5,3]
[[1,2,3],[1,3,4],[1,4,5],[1,5,6],[1,6,7],[1,7,8],[2,3,8],[2,6,5]] -> [1, 3, 4, 5, 6, 7, 8, 2]
[[1,2,3],[2,3,4],[3,4,5],[4,5,1],[1,2,3]] -> [1,2,3,4,5]
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[4,5,6],[5,6,7]] -> [1, 2, 3, 6, 7, 4, 5]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, measured in bytes, wins.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 75 bytes
-2 bytes thanks to @att.
```
MinimalBy[Permutations[i=0;++i&/@#],tTr[Tr@*Position[0]/@(#-t)/. 0->4]]&
```
[Try it online!](https://tio.run/##fY/dCoIwGIbPu4oPBOlnptXUIBLpPPCgs7EDCaVBKtg6CNlNdAddYZdgW01WGR3tGe/z7f1WpPyQFSln@7TNYd1uWcmK9Li5kCSrizOXSVWeCFt7q8mE2W5sUcTv19uuJrs6HifViSmDeNSNh5bDR@4UPCfClNptUrOSEwucCHJiUQo2uPEAmqaZIZgjWAgEjToRzBSqUwZCoAHAU1qoq0ze/L7UJW/@X0kiNs0dYiUYH5vmH9iN9t9/Jb5CKfv6Z77e54VfVZ/7Y1Pla5QjgcYAQagxRLA0jR0GakyI9gE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python](https://www.python.org) SciPy, 120 bytes
```
def f(x):[[email protected]](/cdn-cgi/l/email-protection)*0+4;a[[*zip(range(len(x)))],x-1]=1,2,3;return linear_sum_assignment(a)[1]+1
from scipy.optimize import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZKxbtswEIaBToWe4uBJcs6yJUu2EUNFl-4ZCnQQhICxqZgoRRIkFct5kgJdvLTvlD5NSUlp4iKIBv4ij3ff_SR__lYne5DifP7V2nq2eer2tIY67KJrUnSfu_jrdHGVbUlZTh-ZCjUR9zTkVLgNUVRhN0uqIsEUl1tNbasFcCYo0bembW6JMexeNFTYkERlUl0lQa1lA2bH1CmWyrKGPVJgjZLaTkf-j2EKom3UCYgBoYJaauDABEjlyIso1pTsPciE0XUA7uNQAI8V0ZZZJkU4mc8nUbmo-iBD6cINUaFQMdGanNBP6APhyGOjOLPhBGafYOI89RlKM9e0y8M6ZOPa0N_5z4ePZdk7rrB0IyZO3YhpVfkaYwzmc6iZNhaOUn-ne6AdaRSnQO7kA4UjswdIim9S7xHS4kYeqb6RDoqwLL50O8oDT1m6qviP9jbF0J0U-_8wwUuPz1VeZ6fuf8i2B6bfTU4xG40Omrn1Vy24VV_mQJTy92GgocS0msJ6C03LLes9C-P8GVDSvYi7EZCN3i51KPkC8Ljg8sBzpxnm_cHnvSmvl335-EViMhrwnLzXHFe9rnDd6xo3I2DQldv3XBCWCBlCjrBCWCNs3KVVwfAi_gI)
Not fully builtin but leaves the heavy lifting to scipy.optimize.linear\_sum\_assignment. We just need to feed it in the right format (essentially one-hotting --- or rather three-hotting --- the input).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
◄oṁo%4←z€¹Pŀ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@j6S35D3c25quaPGqbUPWoac2hnQFHG/7//x8dHW2oY6RjHKsTDSR1DIE0kNQxigUygDLGQJYOXAWyDEQEpgKbjJGOCdRUCG0CFIeoMIGaikpDVCKbARIxBdImOqZgl5mCbQHRYLNiAQ "Husk – Try It Online")
```
P # calculate all permutations of
ŀ # the length of the input;
◄ # now output the element that minimizes:
o # combination of
z€¹ # zip 'get index' function over input (or 0 if not found)
ṁo%4← # then subtract 1 & modulo 4 (so not found becomes 3)
```
[Answer]
# [R](https://www.r-project.org), ~~137~~ 133 bytes
*Edit: -4 bytes thanks to pajonk and the new-to-me function `anyDuplicated()`*
```
\(l,n=length(l),q=expand.grid(rep(list(1:n),n)),p=q[!apply(q,1,anyDuplicated),])p[order(apply(p,1,\(x)sum(mapply(match,x,l,4))))[1],]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lVKxbtswEAU65iuu6BASODeQbCNBWmVq9mwdHA-MdJGIUCRNUrX8Af2KLu6QKcgHtV9TynSK1LETVMs9ksf3Ht_px0-3fhTey1q3pIP_PLrvwu3o7Nf3a6ZQF4p0HRqmOC4K6q3Q1cfayYo5skxJH1h2rjlqztEWi9l7Ya1asQVmKPTqS2eVLEWgiuOc25lxFTmWWmxsuWY9913L2rTVilA22KPCCY_fLJvjPJn5_e7hmcWkW7IMcxxzLFksmA0gFszjVfgAowt46oCTE7iVzgdYGndHFVAvWqsIxI35RrCUoYGs-BrdIeTFlVmSuzJSB4RxcdmXpI72io-jFD5zcVjcU2l0taO-n3TL9Zd9lzSP60QaGun-kzOPwW7j2oJJPNpxHI8G-ibORGryHloSvnMEp5-g7VSQm-S0jyl5sCYK3hwSnjwltAuSzL_Cg5VX_Q-XpgOY4DSNe7oJZwNePmToeoPxENiTyGaMpiWjCUqhjwPUFGIMqzgGXYPRcR4kHQwS6Z9dr1P9Aw)
**Ungolfed**
```
assignments=
function(l){
# get all combinations of n times 1..n, unfortunately with repeats that we don't want
p=expand.grid(rep(list(seq(l)),length(l)))
# now get rid of the combinations with duplicates
p=p[apply(p,1,function(x)sum(unique(x)|1)==length(l)),]
# calculate the happiness score of each person
# as the position of the match of each assigned value in each input list
# (or 4 if it isn't found)
e=apply(p,1,function(x)mapply(match,x,l,4))
# calculate total happiness score for each combination:
h=colSums(e)
# return the combination for which happiness score is minimal:
p[which.min(h),]
}
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 34 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{x⊃⍨⊃⍋(⍵+.⍳⊢)¨x←/⍨∘(≡∘∪⍨¨)⍨,⍳⍴⍨≢⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q6541NX8qHcFmOzWeNS7VVvvUe/mR12LNA@tqHjUNkEfJNkxQ@NR50Ig9ahjFZB/aIUmkNQBqevdApLvXATUWAsA&f=S1d41DZB4VHfVK9gfz@FR71LFNLAJFSEK11BPTraUMdIxzhWJxpI6hgCaSCpYxQbqw6TNQbydOCq0GUhojBVuGSNdEygNkBoE6A4QpUJ1AZUGqIa3SyQqCmQNtExBbvWFGwjiEY1E@EuE6iZpmDaVMcMTJvpmINpcx0LqKkQ2gyoLlYdAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) (Last cases uses more memory than allowed on [TryAPL](https://tryapl.org/).)
The cost function for a single arrangement can be computed in a very compact way with `+.⍳`, taking the preferences on the left and the arrangement on the right. Half of the code is just generating the permutations.
[Answer]
# [Python 3](https://docs.python.org/3/), 123 bytes
```
lambda*a:p({*sum(a,[])},*a)[1:]
p=lambda r,b,*a:min([[*b,i].index(i)+k,i,*j]for i in r for k,*j in[a and p(r-{i},*a)or[0]])
```
[Try it online!](https://tio.run/##fVLLbtswELz7K/YWSWWS2pbswoV6c6/NoUAPihBQ1jpiLZEEScUxgn67u6SUxgqKXDjkPmb2QX1yjZLL8z6/P7e8q2qe8I2OXhLbdxFnRRn/YQmPi/mmnOl8iADDKjJuOiGjokgqJsobIWt8jkT86cAES36Xe2VAgJBgwF8PZKNXwYHLGnRkrl9EIFam@FyW8fnYiBbhp@lxMwNw5uQBKEUzeGCgescgeYDcW3oXxTdWt4IwRBm0fevIuY8SfOJtREHx4NJGSBcNAXkenMQVszHnMsjf8XmH2sH2x/etMcoMRVQG@eFcFHO2YMuSFXSyOSGdbFGWcP0NRh/c3sJeGOvgqMwBa@LjnabGeKWeEI7CNTDPfylTM1jkd@qI5k6RNoNlviXpduZVlsTK/qn9X8XiTtEkpzKztxpfWS6zF3Qfsl0jzIfJC5aOjQ6Ykv2iBLJ6moZrLSRaCx1y2xuE9VfoaKwi9Cwt9WdBK2tFNQqkY29THCjfBLzcbDrwjDBlWRh8FpryOK3L@yeJ87EBr5MFzNgq4IqtA67Zl1FgwBXFvRIuA@HKx5Dcu/l8hOkoE5Inc/NkvpSwQtWhknhl4VFJyaFC6KUf6eld62nYYzoZweCfrGSkDUtB@oJ2p2gjxwYltJzempahJNQKrbxy8IiOVnQCtafvgMLArlFih/Yv "Python 3 – Try It Online")
Using builtins only.
As a one-liner:
# [Python 3](https://docs.python.org/3/), 125 bytes
```
def f(b,*a,r=0):s=r or{*sum(a,b)};return min([[*b,i].index(i)+k,i,*j]for i in s for k,*j in[a and f(*a,r=s-{i})or[0]])[r==0:]
```
[Try it online!](https://tio.run/##fVLJbtswEL37K@YWyZ0kXmS7cKDe3GtzKNCDIASUNY5Yy6RAUnGMIN/uDiklsYIiFz5ylvdmYXNylVbz87mkHeyiAscCTTqJ1zY1oM3L2LaHSGARv94Zcq1RcJAqyrJxgTK/kaqk50jG3/Yocfw332kDEqQCC/66Zxu/MgFClcweuO31i3yNtckmeR5nJk0n6/x8rGRN8Nu0tB4BOHPyAJzbIDwg6NYhjB8g9ZbWRfGNbWrJGKIM2bZ27GQFehJ1xEFx52qMVC7qAtI0OJkrxj7nMsjf6XlLjYPNr58bY7TpiigMif05y6Y4w3mOGZ84ZeQTZ3kO1z@g98HtLeyksQ6O2uypZD5xaLgxUegngqN0FUzTP9qUCLP0Xh/J3GvWRpinG5auR15lzqz4rvZ/FUtbzSMdyow@anxjucye8b3LdpU0XybPMOkb7TBh@0UJbPU0lWgaqchaOJCwrSFY3cGBxypDz8pyfxYaba0seoGk722IHeWHgJcbDQe@YExwEQa/CE15HNbl/YPEad@A11kEXOAy4BJXAVf4vRfocMlxb4TzQLj0MSz3aT5fYdLLhOTB3DyZLyWsUB9IK7qy8KiVElAQtMqP9PSp9STsMRmMoPMPVtLThqUQf0G71byRY0UKasHvhpehFZSarLpy8EiOV3QCvePvQNLAttJyS/Yf "Python 3 – Try It Online")
[Answer]
# Javascript, 178 bytes
```
// 178 Bytes
f=a=>(h=(m,i=a.map(_=>0),n=a.length)=>(g=_=>new Set(b=i.map((k,j)=>a[j][k])).size-n?(c=j=>j===!!j||(j<n&&++i[j]&&c(i.reduce((a,b)=>a+b)>m&&j+!(i[j]=0))))(0)&&g():b)()||h(m+1))(0)
// Example
const arr = [
[1, 2, 3],
[1, 3, 4],
[1, 4, 5],
[1, 5, 6],
[1, 6, 7],
[1, 7, 8],
[2, 3, 8],
[2, 6, 5],
];
console.log(f(arr));
```
## Explanation
```
f = a => (
h = ( // This function tries to find an assignment that happiness <= m
m, // Maximum allowed happiness
i=a.map(_=>0), // Assignments (by rank), i.e. [0,1,2] means P1 gets first choice, P2 gets second, P3 gets third.
n=a.length
) => (
g = _ => // This function will iterate through the possibilities of i until it finds a solution (or not)
new Set(b = i.map((k, j) => a[j][k])).size - n // Checks if assignments are unique
? (
c = j=> // This function finds the "next" i with maximum happiness m
j===!!j || ( // If j is a bool (i.e. not a number, then stop)
j < n && // If j >= n, then no more combinations
++i[j] && // Increment i[j] (otherwise, nop)
c(
i.reduce((a, b)=> a + b) > m && // If happiness score exceeds m ...
j + !(i[j] = 0) // Set i[j] to 0 and negate, so we call c(j + 1)
)
)
)(0) &&
g()
: b
)() ||
h(m+1) // If no assignment was found, try again with a more relaxed contraint
)(0) // Start with m = 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
āœΣδkÅ\®₄:O}н
```
-1 byte and corrected my limitations mistake thanks to *@DominicVanEssen*
[Try it online](https://tio.run/##yy9OTMpM/f//SOPRyecWn9uSfbg1xkTVv/bC3v//o6MNdUx0jGJ1MGgjHWMdk9hYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL6P8jjUcnn1scUXxuS/bh1hgTVf/aC3v/6/yPjo421DHSMY7ViQaSOoZAGkjqGMXG6iiApIyBTB24EhQpiBBMCVYpIx0TqMEQ2gQoDlViAjUYlYYoRTEFJGQKpE10TMHOMwVbBKKRTEO4xQRqmimYNtUxA9NmOuZg2lzHAmokhDYDqsOwzQTsHRMUWyHyGN7DR5tAbTcF2x4bCwA).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
œ # Pop and push a list of its permutations
Σ # Sort these permutation-lists by:
δ # Apply double-vectorized with the (implicit) input-list of lists
k # Get the first 0-based index of the value in the inner input-list
# (or -1 if it's not present)
Å\ # Pop the list of lists, and leave its main diagonal
4% # Modulo-4 to replace all -1s with 3s
O # Then sum the list together
}н # After the sort-by: pop and leave the first list (with lowest sum)
# (which is output implicitly as result)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes
```
żṖµ£⁰ƛ¥$vḟ;Þ/4%∑;h
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvOG5lsK1wqPigbDGm8KlJHbhuJ87w54vNCXiiJE7aCIsIiIsIltbMSw0LDJdLFsxLDQsMl0sWzEsNCwyXSxbMiwzLDRdXSJd) or [Verify (almost) all test cases](https://vyxal.pythonanywhere.com/#WyJQalQiLCLGm+KGkuKGkCIsIsW84bmWwrXCo+KGkMabwqUkduG4nzvDni80JeKIkTtoIiwiO1rGm2AgPT4gYGoiLCJbW1sxLDIsM10sWzIsMywxXSxbMywxLDJdXSwgW1sxLDMsMl0sWzEsMiwzXSxbMywxLDJdXSwgW1sxLDIsM10sWzEsMywyXSxbMywxLDJdXSwgW1sxLDIsM10sWzEsMiw0XSxbMiwzLDRdLFsyLDQsM11dLCBbWzEsNCwyXSxbMSw0LDJdLFsxLDQsMl0sWzIsMyw0XV0sIFtbMSwyLDNdLFsyLDMsNV0sWzQsNSwxXSxbNSwxLDJdLFs1LDQsM11dLCBbWzEsMiwzXSxbMiwzLDRdLFszLDQsNV0sWzQsNSwxXSxbMSwyLDNdXV0iXQ==) (the larger ones time out)
Port of 05AB1E. Probably a way to shorten `£⁰ƛ¥$vḟ;`, but idk.
## How?
```
żṖµ£⁰ƛ¥$vḟ;Þ/4%∑;h
ż # Inclusive length range [1, length]
Ṗ # All permutations
µ ; # Sorting lambda
£ # Store this item in the register
⁰ƛ ; # Mapping lambda over the input
¥$vḟ # Get the index of the current character in this list
Þ/ # Get the main diagonal of this list
4% # Modulo each by four to convert -1 to 3
∑ # Sum these
h # Get the first item of the sorted list
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~57~~ 46 bytes
```
≔Eθκη⊞υ⟦⟧Fη≔ΣEυE⁻ηκ⁺κ⟦μ⟧υ≔EυΣEι﹪⌕§θμλ⁴ηI§υ⌕η⌊η
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY_NqsIwEIX3PkVwleAI_nQhuCrCBReC4DJkUVs1wTS9No3cd7kbF4q-jyvfxtNWxUDmTJjzzUz-b6lOyrRI7Ol0CdW2P3ncY-_NzvFF8ssPxPaCmBbTzjJ4zQMxqfDYFiXjWrCXdRXyxo5yLQvjgue6ZZcW-R5crgQOsQD-awSYN26AF1mwBf8xLuNxNXfZ5q9eIgdncaO2RbNPaVzFZ4mvPka0akBMxgomR1tdA2J69uvUvz54ld3-0XbVoyelHNCQRookIkXQMUU0gCLSsNEx6kq16BM) Link is to verbose version of code. 0-indexed. Explanation:
```
≔Eθκη⊞υ⟦⟧Fη≔ΣEυE⁻ηκ⁺κ⟦μ⟧υ
```
Generate all the permutations of `[0..n)`. This is based on my answer to [1 to N column and row sums](https://codegolf.stackexchange.com/q/254768/) but tweaked to use the length of the input as `n`.
```
≔EυΣEι﹪⌕§θμλ⁴η
```
Calculate the unhappiness of each permutation.
```
I§υ⌕η⌊η
```
Output a permutation with the least unhappiness.
[Answer]
# [Python 3.8+](https://docs.python.org/3/), ~~172~~ ~~171~~ 165 bytes
-6 bytes thanks to [@jezza\_99](https://codegolf.stackexchange.com/users/110555/jezza-99)
## Golfed code
```
from itertools import*
def f(m):
L=len(m);H=s=5*L
for p in permutations(range(1,L+1)):
if(h:=sum((m[i]+[p[i]]).index(p[i])for i in range(L)))<H:H,s=h,p
return s
```
[Try it online!](https://tio.run/##Lc5LisMwDAbgfU6hpdWKQponmfE@i9wgZFGoPTHUD2QH2tNnnMxs9EnwSyh80upd1Qfed83egkmKk/evCMYGz@lSPJUGLSwOBUzypVxuv0YZZXOZCtCeIYBxEBTbLT2S8S4KfrgfJUqariUee2C0WAcZNyuEnc1ynUOuC96Me6q3OAY8Lpnj0t/yhIjf4zBSlCuFAliljR3EPbBxSWgxzyXdqVooW1F9WlNz2lB72lJ32lGfzel/25xbUMr8IlQENUFD0BJ0BD3BHXH/BQ)
[Answer]
# [Scala](http://www.scala-lang.org/), 378 bytes
378 bytes, it can be golfed more.
---
Golfed version. [Try it online!](https://tio.run/##ZZFPi9swEMXv@RRznGm1ZrO7yRYrCuytBbdlKT2FUFRHjlUk2VjK0mD82VNJ6R@2vsjjn9@8Nx75Whp56b7/UHWAj1I7GC/h3Ct43j3tRaV9iM/FQTXQoC0jfd59cGG/JzG@SAOVsIVR7hha/iIH9Mxq954Epsai0cZgRXhLbPWmIp5cejXYU1CoXX8K5dWMyr@2InOwMtTtWEuv4JM2YpvsMFbEM/smtk03jHpzk@WFdgddK1@ELgn5oHy4GhV9MkLNYi9bEu9Cq4bNzZ8hkpCms1bmAFmPmsoyiyYeE7D/p8UlhA4q@h1ClP@/FXgLJxe0SZ@s7FGLLdrk8zbWRGk29fNzg/mNCn@yXDfYbvKixnSKlnvRTxP302UBkLZk40WgHI6@hKdhkOfdlzBod4ybgq9OBxAwRiVAH2kwDpu8cMwMINdLBncM7on9B@8ZPMzgA4PVDK4YrGdwzeBxBh8ZvHsN73LQHK5TUGZEIMSrqa6JV7c4PCXdtJguvwA)
```
type Q[A]=List[A]
def f(m: Q[Q[Int]])={val L=m.length;var(s,minH)=(List.fill(L)(0),5*L);def permute(input:Q[Int]):Q[Q[Int]]=input match{case Nil=>List(Nil);case _=>for{i<-input.indices.toList;rest=input.patch(i,Nil,1);other<-permute(rest)}yield input(i)::other};for(p<-permute((1 to L).toList)){val h=(0 until L).map(i=>(m(i):+p(i)).indexOf(p(i))).sum;if(h<minH){minH=h;s=p}};s}
```
Ungolfed version. [Try it online!](https://tio.run/##ZVJNT9wwFLznV7yjDa7FArugFVsJTiCl7aHihBAyWWdj6o/Idqqian/71s8JaZZcnLzxvHljj0MltDgclGmdjxCw4l1UmlfORu80v/NS/Ar8pTiiVE5rWUXlLDddFK9a8lvvxftdV9fSF4V7fUvb8E0oC38LgK2soSZmDaUK8SkvDzY@P9MBwQI2mQrwW2goU2W4lnYXmxG8T@ASTqAcEA8hISjAa6U1KSk5o@OeURYb7ouMoINW@uRWEmXbLk4m05mv0QtAJoMRsWpGDKASQcJ3pWHzNfeS9E@Pd19wr3Z@0pXU4OZLL8mV3apKBh4dCkw4XoaYDPSsFgcTxXAYgwWd8FxspEe9j3Nh43/CHt6V1NtehygK63XfMjD2Rb/mD/ok7VSMLCA6KOngj9LxHBhFkwySM@hseitIMqIlCg9MTB51CqmmFA8p//yoSa4oD535uNYaSAM3OSU6uaIhtWYEMOL2k@WMF4N5TNakh0aE34U15Hf49DN6ZXeY7KNVcYyzTWjUltQkhzbI5v8Fg3MGF5R9Ai8YXM7ASwbLGbhksJqBKwZXM/CKwfUxeJ4HzcEVDspYCmCzOXLVT@zVknlK843si8PhHw)
```
import scala.util.control.Breaks._
import scala.collection.mutable.ArrayBuffer
object Main {
def f(m: List[List[Int]]): List[Int] = {
val L = m.length
val H = 5 * L
var s = List.fill(L)(0)
var minH = H
def permute(input: List[Int]): List[List[Int]] = {
input match {
case Nil => List(Nil)
case _ => for {
i <- input.indices.toList
rest = input.patch(i, Nil, 1)
other <- permute(rest)
} yield input(i) :: other
}
}
for (p <- permute((1 to L).toList)) {
val h = (0 until L).map(i => (m(i) :+ p(i)).indexOf(p(i))).sum
if (h < minH) {
minH = h
s = p
}
}
s
}
def main(args: Array[String]): Unit = {
println(f(List(
List(1, 2, 3),
List(1, 3, 4),
List(1, 4, 5),
List(1, 5, 6),
List(1, 6, 7),
List(1, 7, 8),
List(2, 3, 8),
List(2, 6, 5)
)) == List(1, 3, 4, 5, 6, 7, 8, 2))
}
}
```
] |
[Question]
[
**WARNING: This challenge may need 128 bit floats.1**
The task is to perform numerical integration. Consider the following three functions.
\$
f(x) = cx^{c - 1}e^{-x^c}
\$
\$
g\_1(x) = 0.5e^{-x}
\$
\$
g\_2(x) = 5 e^{-10 x}
\$
We will have that \$c \geq 0.2\$. Your code should be correct for any value between 0.2 and 1.0.
The task is to perform the integral:
\$
\int\_{0}^{\infty} f(x) \ln\left(\frac{f(x)}{g\_1(x)+g\_2(x)}\right) \mathrm{d}x.
\$
Your output should be correct to within plus or minus \$10^{-10}\$ percent of the correct answer.
**Input**
A single real number \$c\$.
**Output shown to 15 significant places**
```
c = 0.2. Output: 119.2233798550179
c = 0.3. Outout: 8.077346771987397
c = 0.4. Output: 2.07833944013377
c = 0.5. Output: 0.8034827042913205
c = 0.6. Output: 0.3961739639940003
c = 0.7. Output: 0.2585689391629249
c = 0.8. Output: 0.2287758419066705
c = 0.9. Output: 0.2480070283065089
c = 1.0. Output: 0.2908566108890576
```
**Timing**
Your code must complete on [TIO](https://tio.run/#) before it times out.
As is usual, this is a competition *per* language. In other words, Java coders should not be put off by the single character solution in a language they can't believe exists. You may use any language/library you choose.
**Questions and notes**
* Does this integral actually exist/converge?
Yes. It is the [Kullback Leibler](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) divergence between two probability distributions.
* Show me any code that can compute these integrals.
See this [Wolfram Alpha](https://bit.ly/36sy5jL) example.
* Why such high precision that we need 128 bit floats?
It is quite easy to solve the integral to low precision using simple ideas. However, to get high precision seems to need careful thought both about the integral itself but also the quadrature method that will be used. I felt this made the question more challenging and interesting.
1. For lots of languages this is easy. E.g Fortran has real128, gcc/clang have \_Float128 for C/C++, Python has Decimal (and many other options), Dyalog APL has 128 bit (decimal) floats, C# has the Decimal type, Haskell has rounded, PHP has decimal, MATLAB has the Multiprecision Computing Toolbox, Julia has BigFloat, Java has BigDecimal, JavaScript has big.js, Ruby has BigDecimal, R has Rmpfr, Perl has Math::BigFloat, SOGL has 200 digit decimal precision, etc. If your favourite golfing language doesn't, maybe consider adding it?
# Update
Alexey Burdin has shown that
\$
\int\_{0}^{\infty} f(x) \ln\left(\frac{f(x)}{g\_1(x)+g\_2(x)}\right) \mathrm{d}x = \int\limits\_0^1 \left(\ln c+\left(\ln \left(-\ln t\right)\right)\cdot\frac{c-1}{c}+ \ln t- \ln\left(0.5+5e^{-9x(t)}\right) +(-\ln{t})^{1/c}\right)dt\$
This potentially greatly simplifies the problem.
[Answer]
## python3, 3982 2183 1866 1821 1677, ~14s
```
from functools import*
#let's start with the comments. I'll exclude them from total count
#from functools I need only reduce
#I've been coding in python2 for 5 years so I'm used to built-in reduce much
#and it's very handy here
g=range
#just keep it in mind while reading) ranGe -> g
#and we're getting rid of classes in favor of functions, that gives
#us ~100 bytes more. It's how it was:
#class P:
#it's a Polynomial, self.c are coefficients and self.d is a divisor. So all polynomial computations are exact
#we need polynomials to implement https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss%E2%80%93Legendre_quadrature
# c=[0]
# d=1
#don't even know if these initial values are necessary
# def __init__(self,c,d=1):
# self.c=list(c)
# self.d=d
#n'th derivative
# def dn(self,n=1):
# c=self.c[:]
# for _ in g(n):
# c=[c[i]*i for i in g(1,len(c))]
# d=reduce(gcd,c,self.d)
#gcd is imported from math along with exp,log and gamma
# return P([i//d for i in c],self.d//d)
# def m(self,x):
#the value of poly at point x. __call__ may look better
# return sum((x**i)*self.c[i] for i in range(len(self.c)-1,-1,-1))/self.d
#the reverse order was for floats and really needed there for precision,
#but python3 have exact Fractions, so maybe it's to be golfed too
#Now let's convert this class to functions
#derivative=lambda c:reduce(lambda c,_:[c[i]*i for i in g(1,len(c))],g(n),c)
#the_gcd=lambda c,d:reduce(gcd,c,d)
#the_result=lambda c,d,m:([i//m for i in c],d//m)
#where c is now the derivative
#and combined:
v=lambda c,d,n=1:(lambda c:
(lambda c,d,m:([i//m for i in c],d//m))(c,d,reduce(gcd,c,d))
)\
(reduce(lambda c,_:[c[i]*i for i in g(1,len(c))],g(n),c))
#the computing of a plynomial's value:
m=lambda c,d,x:sum((x**i)*c[i] for i in g(len(c)-1,-1,-1))/d
d={}
#https://en.wikipedia.org/wiki/Combination written recursively with Pascal's triangle, with the dict d for speed
def c(n,k):
if (n,k) not in d:
d[(n,k)]=1 if k==0 or k==n or n==0 else c(n-1,k)+c(n-1,k-1)
return d[(n,k)]
#p=30
#it's the floating point precision for Decimal
#it was needed for computing the polynomial roots, you can see the raw version
#maybe I'll get rid of it if it's used in the only place
from math import*
from fractions import Fraction as F
n=61
l=v(sum(([c(n,i)*(-1)**(n-i),0] for i in g(n+1)),[]),
2**n*reduce(lambda x,y:x*y,g(1,n+1),1),n)
#Legendre polynomial of order n, pretty straightforward, -3bytes for space
#you can't see these bytes in the tio version, there is 1 line
d=v(*l)
#and the derivative for weights
#see we can use c and d now 'cause we don't need them more
c=2**100
#maybe the hardest-to-read part, the roots of l
#taking too long to compute (2-3 mins) so hard-stored
#b(b'GKSmRyJoJz...') is the 390-bytes byte array,
#representing the <0 roots (the function is odd, so -x and x are both roots and we have to store only half)
#30 13-byte(100-bit, for 10^{-30} precision) integers are stored in lsbf order of bytes
#and c is common multiplier for all computed roots' denominators
from base64 import b64decode as b
#extract numbers from base-64,
r=(lambda b:[sum(2**(n*8)*i for n,i in enumerate(b[j:j+13])) for j in g(0,391,13)])(b(b'GKSmRyJoJzZNd978D7hBJ/SAXF6k3Q+D7w9eWlMN1hwU7v+nhNcPP3k+PPY3ALm75/G0DwxkhnBW7vYeTLvhhw8XTAWijBbPeSIxclAPxUQBLJIlU0r8S8gODz6W/ntGb0p0WeUPww6bS5oF+R0NzuqOe20OpkOWAx5DBcFecEQODqjUMBgWzmCaCiGqpQ2xekr44w56Xl998jMNN0/S8UF6TE04eGm5DL0i6Wm5wA/nHOhgNgxOR3kgsJNHFpZQMKsLdK2AMa1xRv65pzQYCxSYft+TX736FBjQfQqY8CuipXP9Bxm/adwJEKYLfykKeTs/aG00CVuQ6lnO2j04CUVLhggLyUIxC/eIqRKid9IHdSe6aSQRS8hkmWoZB2rhfvNKb9bHP8KfWwb379JeWbyiuY/elZkFsIKVLmMYZwdEhs7TBAvB47snQ/UMwtDNCgRb9soEqlNzn6z8GT8DTfSlRAVDCG07FjtxAheAQ01VIxgWXpy6oQEELmiRzDIqr+ckI9EA'))
#and make fractions
#0 is in r for magically mistaken 391 for 390 )
#maybe +[0]+r[::-1] is 1 byte shorter (or longer?)
#but at least more readable )
#roots computation code is in the raw below
r=[F(i,c) for i in [-j for j in r]+r[-2::-1]]
#the weights
w=[2/((1-x**2)*(m(*d,x))**2) for x in r]
from decimal import*
D=Decimal
setcontext(Context(prec=30, rounding=ROUND_HALF_DOWN))
#that was float=
#it's only converting Fraction to Decimal. no built-in
f=lambda r:(lambda n,d:D(n)/D(d))(*str(r).split('/'))
#number of sub-intervals of (0,1)
d=2**8
s=input().strip()
c=D(s)
#the inverse of c, not the math.exp(1) ))
e=D(1)/c
#pretty straightforward, I is the integrator,
I=lambda h:sum(sum(f(v)*h(f(((x+1)/2+i)/d))/(2*d) for v,x in zip(w,r))
for i in range(d))
#the rest follows (at math:)
print(D(gamma(1/float(s)+1))+(c.ln())-I(lambda t:(D('0.5')+5*((-9*((-((t).ln()))**(e))).exp())).ln())-D('0.5772156649015328606065120900824')*(1-e)-1)
```
[Try it online!](https://tio.run/##VVRbk6I8EH1efgVvkyAOFxXBKh5U1PF@H8exrC0uEVAICCjo1vfb5wteZnZLpJNO@uR0kz7hJXECXPr62kWBT@9O2EyCwItp1w@DKGEoW410bCPqrHq6b1g6bbIWi1WhBp7znxFZ8Wtg43IcQQoi2qVdTJtb1iIOCEG@HiHrZCJgmxZLppB4H55vjN@1jblxt4z7A2EDgfUQBiaEW9YGGLJkRPl/M8pq8ckHIGMYFzJ5/N/R99iiwN4eCDmLstQ//1EW2tEmwOwB1qhf7o6@DWkcJHmYRXy/rM3Nt1UFmqwfVJWnCSyxOLc4nyMvRjkKwT7AwmNATqF@RSg5RQTogUHdKuzrifNd3HvNI91M3AA/a063Hw5aj@k2hVVJoDz1DG4JbnK@JEVATmAYcpgLWf6fZHGBZMhutpAVGQYz/5Y3Yy@1jLmweUXzjSx5MCTVOAPGg5SpkhiB5@/EDD1GUvnJypDKFjIDC@W0DCpSn5hGbZNTE3M6jAwfH46wzPkgfPJRpCcIGJt9bV8QSlsIbxv2d7o8W1IEVijBLQQGMF46/bk/u/SC3vVzZClVWas6jR43r3@0pUNpWtCqqYJW3nAkOOmyei5gZ2ROJqVDYTJZl@oDv1rhOryWZgcHN1bV8xotBmfHSeWPRX3l7hvGBM27menVJ9ly2hj0ut6Sj@S5bI@1q7TicNIx@JBfoeUkTSVjXgnahRk/up6OYyTy4/AwXtWzitYw28hsTcfacb8cNuzV1W/qTbdzDKdihg5RuZxWpA9PUeT9cDTiubm8bEuLFl9GHb@iDXhXWvmVtM7ht7Fjj@xsPCsd7Lg3emuHn9NhPx5YfbE@1IVsdpYq4XW6bmbz9S4pLD6qJand2E930@Nabp7c8GOiNDKf06201@qvB7vLoY8WMad3eL75fppKHh6Le77cXL4PHNseXJbdrMmh7nHWdy2l@2bNkaTPp7O57Bz8VfDZECNndx71DcV4m8j93So1SlWlh1bGxT2tOeR9Htpxt/8@8Ifrz9RqOXF10aifG@VqjKfccpgm2qhpzwwlDlpHb3TF0lXuLGRtsZt7s/q71uzw1fY@yeoOqk954b2b2auP8CIF01Zr4Luzq9Y9RgXz0FVa9RfS4ZG6aQOXNPvP/d4U9z@3J9oWok1RrNWKwnZLpepG5AAQikQERNIhPmCILkCYz24x2T3mfrnJXXZ93ftuRU3V7h4qRokZ4ARlCWg@bBghUy3xLB0FJ2y52FZn4@VI@/1WH7R/a@PViJDdPeUo@hZEzFo1jcgVpwEidYCJkwhE8DUOPTcBL1yeopV3nEzFqovDUwLIYhK5IchbUQMxpBAxAuRMqvuEd25Kl/934AwZhxiie6SXObHgEmkj8kZ60bqnfGZvSV8JZMpGEH7X8SbqOSsqjFycAA3Yuu/rQOB2XqAn5OhcRgrAfPUwgLDYfeaU1MjeF/618gILFQaAopK/AEjgfWeuSoiYV5SF@fQRf4@pVkWhIkllhRcqJVGWePKrCCKv8Lwsll/IRxOKiAg1/PriX8X/AQ "Python 3 – Try It Online") -- takes input as a valid Decimal, like `0.2`
Math:
0. We do google numerical integration.
1. Let's see provocative \$f(x)=c\cdot x^{c-1}\cdot e^{-x^c}=
-\left(e^{-x^c}\right)'\$
2. So, we have \$-\int\limits\_0^\infty \ln\left(\frac{c\cdot x^{c-1}\cdot e^{-x^c}}{0.5e^{-x}+5e^{-10x}}\right)\left(e^{-x^c}\right)'dx\$,
we change the variable to \$t=e^{-x^c}\$, \$x^c=-\ln(t)\$,
\$x=\left(-\ln t\right)^\frac1c\$,
\$t(0)=1\$, \$t(+\infty)=0\$ and the integral is
\$\int\limits\_0^1 \ln\left(\frac{c\cdot x(t)^{c-1}\cdot t}{\left(0.5+5e^{-9x(t)}\right)e^{-x(t)}}\right)dt=\$
\$\int\limits\_0^1 \left(\ln c+\left(\ln x(t)\right)\cdot(c-1)+ \ln t- \ln\left(0.5+5e^{-9x(t)}\right) +x(t)\right)dt=\$
\$\int\limits\_0^1 \left(\ln c+\left(\ln \left(-\ln t\right)\right)\cdot\frac{c-1}{c}+ \ln t- \ln\left(0.5+5e^{-9x(t)}\right) +x(t)\right)dt\$
3. Next we wolframalpha these things:
[\$\int\limits\_0^1\ln(-\ln t)dt\$](http://bit.ly/2NeXuWA),
[\$\int\limits\_0^1 (-\ln t)^a dt\$](http://bit.ly/36BtifJ),
\$\int\limits\_0^1 \ln t\,dt\$ and do the rest [numerically](https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss%E2%80%93Legendre_quadrature) (the latter thing maybe can be done with trapeziums or rectangles or Simpson -- the idea for short submissions).
The raw thing:
```
from copy import copy
from functools import reduce
class Poly:
c=[0]
d=1
def __init__(self,c,d=1):
self.c=list(c)
self.d=d
def dn(self,n=1):
c=copy(self.c)
for _ in range(n):
c=[c[i]*i for i in range(1,len(c))]
d=reduce(gcd,c,self.d)
return Poly([i//d for i in c],self.d//d)
def m(self,x):
return sum((x**i)*self.c[i] for i in range(len(self.c)-1,-1,-1))/self.d
def gcd(x,y):
return abs(gcd(y,x%y)) if y else x
cdict={}
def c(n,k):
if (n,k) not in cdict:
cdict[(n,k)]=1 if k==0 or k==n or n==0 else c(n-1,k)+c(n-1,k-1)
return cdict[(n,k)]
def root(x,f,f_):
x_old=0
while x!=x_old:# and abs(f(x))>1e-15:
print(x,f(x),f_(x))
x_old=x
x=x-f(x)/f_(x)
print('===')
return x
precision=30
def b(b,e,f,eps=1e-17):
mold,m=0,1
while e-b>eps and mold!=m:
mold=m
m=(e+b)/2
if (l.m(m)>0)!=(l.m(b)>0):
e=m
else:
b=m
#print(*map(float,[b,e,f(b),f(e)]))
print('.',sep='',end='')
return b
##class Frac:
## n=0
## d=1
## def __init__(self,n,d):
## self.n=n
## self.d=d
## def
lcm=lambda x,y:x*y//gcd(x,y)
import math
from fractions import Fraction
degree=61
n=degree
l=Poly(sum(([c(n,i)*(-1)**(n-i),0] for i in range(n+1)),[]),
2**n*reduce(lambda x,y:x*y,range(1,n+1),1)).dn(n)
ld=l.dn()
#print(l.coeffs,l.d)
#r=[root(math.cos(math.pi*(4*i-1)/(4*n+2)),l.m,ld.m) for i in range(1,n+1)]
##d=2**8#4096
##while True:
## i_=[(b,e) for b,e in [(Fraction(i,d)-1,Fraction(i+1,d)-1)
## for i in range(2*d)] if (l.m(b)>0)!=(l.m(e)>0)]
## print(d,len(i_))
## if len(i_)==n:
## break
## d*=2
##r=[b(*i,l.m,Fraction(1,10**precision)) for i in i_]
##print('\n',sep='',end='')
cm=1267650600228229401496703205376
#cm=reduce(lambda x,i:lcm(int((str(i).split('/')+[1])[1]),x),r,1);cm
#[str(i*cm) for i in r]
r=[Fraction(int(i),cm) for i in ['-1266681605106811426160584860697', '-1262547799267707740863710314936', '-1255122086390021131342967954015', '-1244422184933863703004183427391', '-1230475806835976018691325584397', '-1213319288075032955237836344344', '-1192997371846808208190052844742', '-1169563069074221666262667138623', '-1143077514053466175428649175963', '-1113609802945881973204995949479', '-1081236812728978305124643427497', '-1046043000289730543348383120049', '-1008120181921745998647915597624', '-967567293702390287305984778942', '-924490133333634877286205966159', '-879001084101412705885157895540', '-831218821664589525108846925845', '-781268004433877062952267018393', '-729278948345971539276192261648', '-675387286880006687633990914140', '-619733617202494872284783888651', '-562463133363442075271048079222', '-503725247500289525435137450347', '-443673200037730123766618583031', '-382463659900222496924931293872', '-320256315780122313563780137228', '-257213459527711400732339664476', '-193499562749975057795207525453', '-129280847722706546595631169560', '-64724853735360852478581550597', '0', '64724853735360852478581550596', '129280847722706546595631169559', '193499562749975057795207525452', '257213459527711400732339664475', '320256315780122313563780137227', '382463659900222496924931293871', '443673200037730123766618583030', '503725247500289525435137450346', '562463133363442075271048079221', '619733617202494872284783888650', '675387286880006687633990914139', '729278948345971539276192261647', '781268004433877062952267018392', '831218821664589525108846925844', '879001084101412705885157895539', '924490133333634877286205966158', '967567293702390287305984778941', '1008120181921745998647915597623', '1046043000289730543348383120048', '1081236812728978305124643427496', '1113609802945881973204995949478', '1143077514053466175428649175962', '1169563069074221666262667138622', '1192997371846808208190052844741', '1213319288075032955237836344343', '1230475806835976018691325584396', '1244422184933863703004183427390', '1255122086390021131342967954014', '1262547799267707740863710314935', '1266681605106811426160584860696']]
#r=[Fraction(-72002513042367095, 72057594037927936), Fraction(-35883766692782835, 36028797018963968), Fraction(-35672715239059617, 36028797018963968), Fraction(-141474422995755015, 144115188075855872), Fraction(-69944451686068079, 72057594037927936), Fraction(-137938433007892963, 144115188075855872), Fraction(-135628098615462501, 144115188075855872), Fraction(-66481963419518119, 72057594037927936), Fraction(-32488216960856169, 36028797018963968), Fraction(-126602776952709289, 144115188075855872), Fraction(-61461197033678349, 72057594037927936), Fraction(-59460660411885473, 72057594037927936), Fraction(-7163124720376473, 9007199254740992), Fraction(-109999665903886841, 144115188075855872), Fraction(-105102359763536115, 144115188075855872), Fraction(-99930853605361871, 144115188075855872), Fraction(-23624659822433771, 36028797018963968), Fraction(-88819888837164975, 144115188075855872), Fraction(-41454708727199633, 72057594037927936), Fraction(-19195661220692463, 36028797018963968), Fraction(-70455555169530143, 144115188075855872), Fraction(-63944654967081315, 144115188075855872), Fraction(-28633465234423143, 72057594037927936), Fraction(-6304975386764939, 18014398509481984), Fraction(-10870271009372985, 36028797018963968), Fraction(-36408927801417385, 144115188075855872), Fraction(-29241784833142379, 144115188075855872), Fraction(-21998353389560073, 144115188075855872), Fraction(-14697530755564293, 144115188075855872), Fraction(-7358363943167303, 144115188075855872), Fraction(0, 1), Fraction(3679181971583651, 72057594037927936), Fraction(3674382688891073, 36028797018963968), Fraction(2749794173695009, 18014398509481984), Fraction(14620892416571189, 72057594037927936), Fraction(4551115975177173, 18014398509481984), Fraction(43481084037491939, 144115188075855872), Fraction(50439803094119511, 144115188075855872), Fraction(57266930468846285, 144115188075855872), Fraction(31972327483540657, 72057594037927936), Fraction(35227777584765071, 72057594037927936), Fraction(76782644882769851, 144115188075855872), Fraction(82909417454399265, 144115188075855872), Fraction(44409944418582487, 72057594037927936), Fraction(94498639289735083, 144115188075855872), Fraction(49965426802680935, 72057594037927936), Fraction(52551179881768057, 72057594037927936), Fraction(13749958237985855, 18014398509481984), Fraction(114609995526023567, 144115188075855872), Fraction(118921320823770945, 144115188075855872), Fraction(122922394067356697, 144115188075855872), Fraction(15825347119088661, 18014398509481984), Fraction(129952867843424675, 144115188075855872), Fraction(132963926839036237, 144115188075855872), Fraction(33907024653865625, 36028797018963968), Fraction(68969216503946481, 72057594037927936), Fraction(139888903372136157, 144115188075855872), Fraction(70737211497877507, 72057594037927936), Fraction(142690860956238467, 144115188075855872), Fraction(143535066771131339, 144115188075855872), Fraction(144005026084734189, 144115188075855872)]
#r=[Fraction(-144104924687379029, 144115188075855872), Fraction(-144061113633417193, 144115188075855872), Fraction(-71991152681636629, 72057594037927936), Fraction(-143868501524294767, 144115188075855872), Fraction(-35929931908622757, 36028797018963968), Fraction(-143536019344824829, 144115188075855872), Fraction(-71658710569760757, 72057594037927936), Fraction(-143063986084641675, 144115188075855872), Fraction(-142775775751233995, 144115188075855872), Fraction(-35613215044775229, 36028797018963968), Fraction(-142095317851501427, 144115188075855872), Fraction(-141703235672459401, 144115188075855872), Fraction(-141276708943911307, 144115188075855872), Fraction(-70407920670826367, 72057594037927936), Fraction(-140320744889653401, 144115188075855872), Fraction(-34947884983137447, 36028797018963968), Fraction(-139228355106226913, 144115188075855872), Fraction(-138631327306447751, 144115188075855872), Fraction(-69000300827755959, 72057594037927936), Fraction(-68668165733468573, 72057594037927936), Fraction(-136638678208163739, 144115188075855872), Fraction(-135907811461286037, 144115188075855872), Fraction(-67571954440908669, 72057594037927936), Fraction(-134347156155496359, 144115188075855872), Fraction(-16689718369143059, 18014398509481984), Fraction(-132655882883583863, 144115188075855872), Fraction(-131761773444627501, 144115188075855872), Fraction(-65417817986076227, 72057594037927936), Fraction(-64938847793634331, 72057594037927936), Fraction(-32222046285398959, 36028797018963968), Fraction(-127867345160661637, 144115188075855872), Fraction(-31703855946358703, 36028797018963968), Fraction(-62866338356003711, 72057594037927936), Fraction(-15577420891180097, 18014398509481984), Fraction(-123475765655790143, 144115188075855872), Fraction(-61151075136161875, 72057594037927936), Fraction(-121098806255952059, 144115188075855872), Fraction(-119866026109883705, 144115188075855872), Fraction(-118604109492524957, 144115188075855872), Fraction(-117313363144639965, 144115188075855872), Fraction(-115994100814789491, 144115188075855872), Fraction(-28661660795766563, 36028797018963968), Fraction(-28317829445786347, 36028797018963968), Fraction(-111868458922669023, 144115188075855872), Fraction(-110438407601984251, 144115188075855872), Fraction(-27245377857813575, 36028797018963968), Fraction(-26874531136490757, 36028797018963968), Fraction(-105988607520833283, 144115188075855872), Fraction(-26113331820545011, 36028797018963968), Fraction(-102892657018719659, 144115188075855872), Fraction(-50653488045428427, 72057594037927936), Fraction(-49848334969235775, 72057594037927936), Fraction(-98062129987227927, 144115188075855872), Fraction(-96403753553428489, 144115188075855872), Fraction(-94721943747436259, 144115188075855872), Fraction(-23254277343922147, 36028797018963968), Fraction(-45644832420663197, 72057594037927936), Fraction(-89540030043462969, 144115188075855872), Fraction(-10971078784389609, 18014398509481984), Fraction(-85975896119833679, 144115188075855872), Fraction(-42081131673510875, 72057594037927936), Fraction(-20582043201506859, 36028797018963968), Fraction(-40237035159487741, 72057594037927936), Fraction(-39300203286200335, 72057594037927936), Fraction(-19176909251924261, 36028797018963968), Fraction(-74796221710411347, 144115188075855872), Fraction(-72866625298407583, 144115188075855872), Fraction(-35459658404464939, 72057594037927936), Fraction(-68954769584591107, 144115188075855872), Fraction(-33486730579157493, 72057594037927936), Fraction(-32487936568629803, 72057594037927936), Fraction(-31481245542875313, 72057594037927936), Fraction(-60933804407252565, 144115188075855872), Fraction(-58890306225406907, 144115188075855872), Fraction(-56832493264165915, 144115188075855872), Fraction(-54760865727051299, 144115188075855872), Fraction(-26337963587783547, 72057594037927936), Fraction(-25289092203398143, 72057594037927936), Fraction(-48468147330210951, 144115188075855872), Fraction(-46346328843725859, 144115188075855872), Fraction(-11053311177256411, 36028797018963968), Fraction(-21034706713097939, 72057594037927936), Fraction(-19957678053844251, 72057594037927936), Fraction(-4718949543956531, 18014398509481984), Fraction(-35578660114658865, 144115188075855872), Fraction(-33397075583856055, 144115188075855872), Fraction(-15603686524289111, 72057594037927936), Fraction(-29010084771446223, 144115188075855872), Fraction(-1675359053686717, 9007199254740992), Fraction(-24594889131807827, 144115188075855872), Fraction(-22378054994346827, 144115188075855872), Fraction(-20155781304247947, 144115188075855872), Fraction(-4482152060343901, 36028797018963968), Fraction(-15697077176510773, 144115188075855872), Fraction(-6730865269878557, 72057594037927936), Fraction(-5611555844344803, 72057594037927936), Fraction(-4490882388138869, 72057594037927936), Fraction(-6738234618615355, 144115188075855872), Fraction(-2246533281244659, 72057594037927936), Fraction(-2246806352819167, 144115188075855872), Fraction(0, 1), Fraction(1123403176409583, 72057594037927936), Fraction(4493066562489317, 144115188075855872), Fraction(3369117309307677, 72057594037927936), Fraction(8981764776277737, 144115188075855872), Fraction(11223111688689605, 144115188075855872), Fraction(13461730539757113, 144115188075855872), Fraction(3924269294127693, 36028797018963968), Fraction(17928608241375603, 144115188075855872), Fraction(10077890652123973, 72057594037927936), Fraction(11189027497173413, 72057594037927936), Fraction(12297444565903913, 72057594037927936), Fraction(26805744858987471, 144115188075855872), Fraction(14505042385723111, 72057594037927936), Fraction(31207373048578221, 144115188075855872), Fraction(16698537791928027, 72057594037927936), Fraction(2223666257166179, 9007199254740992), Fraction(37751596351652247, 144115188075855872), Fraction(39915356107688501, 144115188075855872), Fraction(42069413426195877, 144115188075855872), Fraction(44213244709025643, 144115188075855872), Fraction(23173164421862929, 72057594037927936), Fraction(24234073665105475, 72057594037927936), Fraction(50578184406796285, 144115188075855872), Fraction(52675927175567093, 144115188075855872), Fraction(27380432863525649, 72057594037927936), Fraction(28416246632082957, 72057594037927936), Fraction(29445153112703453, 72057594037927936), Fraction(15233451101813141, 36028797018963968), Fraction(62962491085750625, 144115188075855872), Fraction(64975873137259605, 144115188075855872), Fraction(66973461158314985, 144115188075855872), Fraction(34477384792295553, 72057594037927936), Fraction(70919316808929877, 144115188075855872), Fraction(36433312649203791, 72057594037927936), Fraction(37398110855205673, 72057594037927936), Fraction(76707637007697043, 144115188075855872), Fraction(78600406572400669, 144115188075855872), Fraction(80474070318975481, 144115188075855872), Fraction(82328172806027435, 144115188075855872), Fraction(84162263347021749, 144115188075855872), Fraction(42987948059916839, 72057594037927936), Fraction(87768630275116871, 144115188075855872), Fraction(11192503755432871, 18014398509481984), Fraction(91289664841326393, 144115188075855872), Fraction(93017109375688587, 144115188075855872), Fraction(47360971873718129, 72057594037927936), Fraction(12050469194178561, 18014398509481984), Fraction(49031064993613963, 72057594037927936), Fraction(99696669938471549, 144115188075855872), Fraction(101306976090856853, 144115188075855872), Fraction(51446328509359829, 72057594037927936), Fraction(104453327282180043, 144115188075855872), Fraction(52994303760416641, 72057594037927936), Fraction(107498124545963027, 144115188075855872), Fraction(108981511431254299, 144115188075855872), Fraction(55219203800992125, 72057594037927936), Fraction(55934229461334511, 72057594037927936), Fraction(113271317783145387, 144115188075855872), Fraction(114646643183066251, 144115188075855872), Fraction(57997050407394745, 72057594037927936), Fraction(29328340786159991, 36028797018963968), Fraction(29651027373131239, 36028797018963968), Fraction(14983253263735463, 18014398509481984), Fraction(60549403127976029, 72057594037927936), Fraction(122302150272323749, 144115188075855872), Fraction(61737882827895071, 72057594037927936), Fraction(124619367129440775, 144115188075855872), Fraction(125732676712007421, 144115188075855872), Fraction(126815423785434811, 144115188075855872), Fraction(31966836290165409, 36028797018963968), Fraction(128888185141595835, 144115188075855872), Fraction(129877695587268661, 144115188075855872), Fraction(130835635972152453, 144115188075855872), Fraction(32940443361156875, 36028797018963968), Fraction(66327941441791931, 72057594037927936), Fraction(133517746953144471, 144115188075855872), Fraction(67173578077748179, 72057594037927936), Fraction(135143908881817337, 144115188075855872), Fraction(33976952865321509, 36028797018963968), Fraction(68319339104081869, 72057594037927936), Fraction(137336331466937145, 144115188075855872), Fraction(138000601655511917, 144115188075855872), Fraction(69315663653223875, 72057594037927936), Fraction(4350886097069591, 4503599627370496), Fraction(139791539932549787, 144115188075855872), Fraction(17540093111206675, 18014398509481984), Fraction(140815841341652733, 144115188075855872), Fraction(70638354471955653, 72057594037927936), Fraction(17712904459057425, 18014398509481984), Fraction(71047658925750713, 72057594037927936), Fraction(142452860179100915, 144115188075855872), Fraction(71387887875616997, 72057594037927936), Fraction(71531993042320837, 72057594037927936), Fraction(143317421139521513, 144115188075855872), Fraction(35884004836206207, 36028797018963968), Fraction(143719727634491027, 144115188075855872), Fraction(71934250762147383, 72057594037927936), Fraction(143982305363273257, 144115188075855872), Fraction(18007639204177149, 18014398509481984), Fraction(36026231171844757, 36028797018963968)]
w=[2/((1-x**2)*(ld.m(x))**2) for x in r]
from decimal import Decimal,Context,setcontext,ROUND_HALF_DOWN
setcontext(Context(prec=30, rounding=ROUND_HALF_DOWN))
float=lambda r:(lambda x:Decimal(x[0])/Decimal(x[1]))(str(r).split('/'))
d=2**8
s='{120.000000000000000000000000000,9.26052826812554737559992621571,3.32335097044784255118406403126,2.00000000000000000000000000000,1.50457548825155601882809780906,1.26582350605728327736200759570,1.13300309631934634747833911121,1.05218372089129332722399903882,1.00000000000000000000000000000}'
l=list(map(Decimal,s[1:-1].split(',')))
gamma=Decimal('0.5772156649015328606065120900824024310421593359399235988057672348848677267776646709369470632917467495')
for (c,c_1,real),l_ in zip([
(Decimal('0.1')*i,Decimal('10')/i,10/i) for i in range(2,11)],l):
#let t=e^{-x^c},\ln t=-x^c,x=(-\ln t)^{\frac1c}
#t(0)=1,t(\infty)=0
#dt=-e^{-x^c}\cdot x^{c-1}\cdot c
#f(x)=e^{-x^c}\cdot x^{c-1}\cdot c=t\cdot (-\ln t)^{\frac{c-1}c}\cdot c
xt=lambda t:(-((t).ln()))**(c_1)
## f=lambda x:c*(x**(c-1))#*(math.exp(-(x**c)))
fln=lambda t:((-((t).ln())).ln())#+(t.ln())
## g=lambda x:Decimal('0.5')+5*((-9*x).exp())#*math.exp(-x)
g=lambda t:Decimal('0.5')+5*((-9*xt(t)).exp())#*math.exp(-x)
## h=lambda x:f(x)*((-(x**c)).exp())*\
## ((f(x)).ln()-(x**c)-((g(x)).ln()-x))
## #0,inf->0,1: x=t/(t-1), xt-x=t, (x-1)t=x, t=x/(x-1)
## h1=lambda t:h(t/(1-t))/((1-t)**2) # 0,1
## h2=lambda v:h1((v+1)/2)/2
h1=lambda t:g(t).ln()#f(t).ln()-((g(t).ln())-xt(t))
int_=lambda h1:sum(
sum(float(w_)*h1(float(((x+1)/2+i)/d))/(2*d) for w_,x in zip(w,r))
for i in range(d))
print(c,Decimal(math.gamma(real+1))+(c.ln())-int_(h1)-gamma*(1-c_1)-1)
h1_=r'''0.2 0.476044892154085268532810576285
0.3 0.326045243249124607083205564208
0.4 0.194544295792217104304557844994
0.5 0.0805857800502670858642542661562
0.6 -0.0176136562407463311404194282348
0.7 -0.102042234943715186336125809639
0.8 -0.174612380676135222634071174702
0.9 -0.237048749195042896134197564780
1.0 -0.290856610889057599214369459143'''
x=[i.split(': ') for i in r'''c = 0.2. Output: 119.2233798550179
c = 0.3. Outout: 8.077346771987397
c = 0.4. Output: 2.07833944013377
c = 0.5. Output: 0.8034827042913205
c = 0.6. Output: 0.3961739639940003
c = 0.7. Output: 0.2585689391629249
c = 0.8. Output: 0.2287758419066705
c = 0.9. Output: 0.2480070283065089
c = 1.0. Output: 0.2908566108890576'''.split('\n')]
y=[i.split(' ') for i in r'''0.2 119.223379855017945799292478451
0.3 8.07734677198740392689540304712
0.4 2.07833944013376923348715605315
0.5 0.80348270429132046532502570246
0.6 0.39617396399400051391328713871
0.7 0.25856893916292307961043114604
0.8 0.22877584190665494099938058972
0.9 0.24800702830645810748432393277
1.0 0.29085661088905759921436945914'''.split('\n')]
#[(lambda l:(l and min(l)) or 0)([n for n,(d1,d2) in enumerate(zip(i[1],j[1])) if d1!=d2]) for i,j in zip(x,y)]
#[0, 14, 15, 17, 17, 16, 15, 14, 17]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 105 bytes ~7.5 seconds
Mathematica is good at automatically determining the best method needed to perform the integration. Setting the working precision high gets us to results that match the stated answer. The time stated is to perform all the example integrals.
```
NIntegrate[((f=#*x^(#-1))*Log[f/(E^x^#*(5/E^(10*x)+0.5/E^x))])/E^x^#,{x,0,-Log@0},WorkingPrecision->128]&
```
[Try it online!](https://tio.run/##HctNC8IgAIDhHzMINefHIOiy2GWHIGJ16SAKMpxzMQUzEKLfbh/Hl4d31Wk2q05u1GVpy/nok7FRJyMAmNoKZQWqmkOITsGKiYJeZVUhsKO9ApyhDLeM/CJDKCH9K35lzHD9HTr2xrcQ787bIZrRPVzw9YE3e7kpl6czqRui80kstLtqb40gDeaYcCnLBw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~88~~ 87 bytes, < 1 sec
Great work from @AlexeyBurdin!
I also saw the "provocative" way in which \$f\$ was a derivative of an easier function, but only had the idea to use this for partial integration, without success.
For golfing reasons I recombined all the logarithms, except the one giving \$-1\$ because it makes no difference for the code length and subtracting one seemed slightly more efficient than multiplying the integrand by \$t\$. I also took the logarithms of \$1/t\$ instead of \$t\$ to be able to get rid of the otherwise needed parentheses for the minus sign. The `2` in the last argument to `intnum` reduces the integration step size. That is needed to achieve the required precision.
```
l=log;i(c)=intnum(t=0,1,l(c*l(1/t)^(1-1/c)/(.5+5*exp(-9*l(1/t)^c^-1)))+l(1/t)^c^-1,2)-1
```
[Try it online!](https://tio.run/##TYxBCoQwEAS/06MzJiN4kCVfEZagEogxhCz4@@hF2GNRReVvCbLn1qKL5/4J8ORCqul3oDrLyhG@i1BTaYGKGk8Gw9RP3XplyPw6v4gSUf@HPJJo286C5EZWy7k8ZwQko/Zp2w0 "Pari/GP – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~150~~ ~~133~~ 122 bytes
*(thanks to Delta and Alexey Burdin for further golfing this)*
SymPy's [mpmath module](https://docs.sympy.org/0.6.7/modules/mpmath/index.html) is a great way to handle this problem. All math functions (`exp`, `log`, `euler`, `gamma` and [`quad`](http://mpmath.org/doc/current/calculus/integration.html) for integration) are run in high precision.
```
lambda c:gamma(1/c+1)+l(c)-euler*(1-1/c)-1-quad(lambda t:l(.5+5*exp(-9*((-l(t))**(1/c)))),[0,1])
from mpmath import*
l=log
```
[Try it online!](https://tio.run/##LYzLDsIgEADv/YoedymoxHCwSb9EPSClj2QXKKGJfj3WxDlOJpM@ZYnhWqfhUcnya7St62fLbEGfXaexI3Co/E4@C9DqkKi02nY7wr8vPcHJdEb4dwJ1EwCKoCAK8VvggbxfpH5iM@XILSe2ZWlXTjEX0dBAca4h5TUUmI4RSm2wfgE)
[Answer]
# [Desmos](https://desmos.com/calculator), ~~62~~ 59 bytes
```
a=ln(1/t)^{1/c}
f(c)=∫_0^1(ln(a^c/a/e(.5+5e^{-9a})c)+a)dt
```
This is a port of [Christian Siever's solution](https://codegolf.stackexchange.com/a/195390/68261) with some modifications for numeric precision.
[Try it on Desmos!](https://www.desmos.com/calculator/8qupoqagvp?timeInWorker)
*-3 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow)*.
The final column in the table shows the relative error, which reaches 5.71×10^-13 as the worst case at c=0.2. This barely slips under the 10^-12 relative error requirement.
As for the speed requirement, this run in under 1500ms on my computer.
## Precision notes
Desmos uses 64-bit floats for everything, so it's tough to get the desired precision, considering the machine precision is on the order of 10^-16. However, Desmos's quadrature routine is pretty good for general integrals because it works by recursively splitting the integration interval when it needs more precision.
`ln(1/t)` can be changed to `(-lnt)` for -1 byte, but this costs about two orders of magnitude of relative precision.
[Answer]
# APL(NARS), 738 chars, time 1' 6''
```
grv←0⋄ge←0⋄q←0⋄⎕fpc←128⋄funOne←{f←q×(⍵*q-1v)×*-⍵*q⋄f×⍟f÷(0.5v×*-⍵)+5×*-10v×⍵}
r←(f S)w
r←¯1v⋄→0×⍳3≠≢w⋄grv←0⋄ge←÷10x*w[3]⋄r←f It w[1]w[2]
r←(f It)w;t;y;m
r←0v⋄→2×⍳∼grv>250⋄r←¯1J1⋄→0
grv+←1⋄t←f I w,1⋄→6×⍳t[3]≥1⌊ge×1E5⋄→4×⍳ge>t[3]⋄t←f I w,19
→6×⍳∼ge>t[3]
y←f I w,23⋄→6×⍳ge≤∣y[1]-t[1]
grv-←1⋄r←↑t⋄→0
m←2v÷⍨-/⌽w⋄r←(f It w[1],w[1]+m)+(f It(w[1]+m),w[2])⋄grv-←1
r←(f I)w;a;b;n;nn;h;s1;s2;h1;h2;i;t;p;m
h2←h1←s2←s1←0v⋄r←⍬⋄(a b n)←w⋄→0×⍳n≤0⋄h←(2×nn←2v×n)÷⍨b-a⋄i←0v
t←f a+h×2×i+←1⋄s1+←t⋄→3×⍳∼0=2∣i⋄h1+←t⋄→4
h2+←t
→2×⍳i<nn-1⋄i←0v
s2+←f a+hׯ1+2×i+←1⋄→5×⍳i<nn⋄t←+/f¨a b
p←(3÷⍨h×t+(4×s2)+2×s1)(3÷⍨h×2×t+(4×h2)+2×h1)
m←(h×s2+s1+t÷2)(h× 2×s1+t÷2)
s2←∣-/p⋄s1←∣-/m⋄→9×⍳∼s2>s1⋄r←m,s1⋄→0
r←p,s2
:for q :in 0.1v+10÷⍨⍳9⋄q,(11⍕ funOne S 1E¯64v (7E8v) 11)⋄:endfor
```
77+1+ 8+49+1 +15+27+57+12+28+14+58+6 +39+60+40+5+15+38+44+28+36+6+9 +65=738
"grv" is one global variable used for make not too deep the recursive function
"ge" is one global variable used for store epsilon of precision
"funOne" would be the function use in exercise where the "c" is here "q".
"S" is the function to call for integration of one continue function,
it has arguments on the left the function, in the right 3 numbers, 2 are
a b for the integration interval [a, b], and one for the precision of calculation.
It is possible that S function fail or not show the error in some integral
(example some integral of periodic functions). It return one complex not real number, in
case it detects error.
"I" is a function for calculate the integral in 2 differents way the trapezes and Simpson formula,
return the two sums have less difference.
"It" is a recursive function from the model of qsort, that use function "I" and change partition for recalculate
the result each little interval it find ok for to be a little more sure of result even if that means 2x slow
(so it is possible silent fail too).
```
:for q :in 0.1v+10÷⍨⍳9⋄q,(11⍕ funOne S 1E¯64v (7E8v) 11)⋄:endfor
0.2 119.22337985504
0.3 8.07734677202
0.4 2.07833944016
0.5 0.80348270430
0.6 0.39617396400
0.7 0.25856893917
0.8 0.22877584191
0.9 0.24800702832
1 0.29085661089
```
1E¯64v would be one value not 0 sufficient little, the value for +oo that not make wrong results in function funOne,
it seems to be 7E8v.It gets 1' 6'' for all value of c (here it is q variable) from 0.1 to 1.
The function integrate of sys (∫) is more fast, but the right result it seems to be only the first
```
q←0.2v⋄30⍕ 1E¯70v funOne ∫7E8v
119.223379855016584445335168065350
q←0.3v⋄30⍕ 1E¯70v funOne ∫7E8v
0.253368882611387716254867856476
q←0.4v⋄30⍕ 1E¯70v funOne ∫7E8v
0.016195181203412657409325335505
q←1v⋄30⍕ 1E¯70v funOne ∫7E8v
0.001677768739402358961260938889
```
For some function f, +/f¨a b is not the same +/f a b.
One has to eliminate all the places where is used "=" or use ⎕ct←0 in each function use "=".
In the function "I" these are the 4 sums, the first (p[1]) the more precise Simpson sum, than the second (p[2]) less precise Simpson
the 3rd the more precise use trapezes (m[1]), the less precise use trapezes (m[2]).
```
p←(3÷⍨h×t+(4×s2)+2×s1)(3÷⍨h×2×t+(4×h2)+2×h1)
m←(h×s2+s1+t÷2)(h× 2×s1+t÷2)
```
] |
[Question]
[
In this challenge, you are given a number x. You have to find the minimum number of steps required to reach x from 1. At a particular point, you have two choices:
**1) Increment the number by 1**.
**2) Reverse the integer** (remove leading zeros after reversing)
```
Input: n=42
Output: 1>2>3>4>5>6>7>8>9>10>11>12>13>14>41>42 **(15 steps)**
```
The minimum steps to reach 42 from 1 is 15. This can be achieved if we increment numbers by 1 from 1 to 14 (13 steps). After reaching 14 we can reverse the number which will give us 41 (1 step). From 41 we can increment number by 1 to reach 42(1 step). Hence the total number is 15 steps, which is then the minimum.
Note that if we reverse the number after reaching 12 or 13, we will not get the minimum steps.
1>2>3>4>5>6>7>8>9>10>11>12>21>22>23>32>33>34>35>36>37>38>39>40>41>42 **(25 steps)**
```
Input: n=16
Output: 1>2>3>4>5>6>7>8>9>10>11>12>13>14>15>16 **(15 steps)**
```
In this case we have to increment the numbers until we get 16, which will give us a minimum of 15 steps.
**Note**: Starting from 0 is also allowed, which will increase all output by 1.
[Answer]
# [Haskell](https://www.haskell.org/), ~~82~~ 73 bytes
```
r=read.reverse.show
f 1=0
f a=1+(minimum$f(a-1):[f$r a|r a<a,mod a 10>0])
```
[Try it online!](https://tio.run/##FcyxDoMgEIDhvU9xAwOkSmBtik/g1tE6XCJEUg/NoS1D353a4f/Gf8b88stSKzv2OGn2b8/Z6zyvn0sA68wpOnuVFFOkg0SQ2Fp1G4JgwO/ZHRtaJ0CwpjOjqoQxue3YHzv3SfxHgnCTz9J2sjQQoCg1WK2tMWP9AQ "Haskell – Try It Online")
Simplest recursion method.
-9 bytes thanks to Christian Sievers
[Answer]
# C++, ~~140~~ ~~159~~ ~~147~~ 145 bytes
Edit: new solution without standard library, using a recursive function and pointer magic (constant 20 experimentally determined and not the same on other compilers)
Edit 2: -2 bytes thanks to ceilingcat
```
int*s,S,*G,x;int F(int Z,int*p=&x){int W=1,a=(*p)++,r=0;for(;r=r*10+a%10,a/=10;);G?W=r,p<=G?G=&W,S++,p=s:0:p=s=G=&W;return*p-Z&&W-Z?F(Z,p-20):S;}
```
[Try it online!](https://tio.run/##jZDdasMgFIDvfQrZWMiPIRraDWpc75oHyEUgd2JsCaRG1IxC6asv024t5G4HOf@fnHOE1rkYuToty6BcalGD0hpdqA/gIQ66Q6GgWXRJriFuGUGcxalOsgwZhulxMjE1zKQEZ/yNYMQLRjBNaL1vmUG6YvW@ZlGLGg9oZnd45zULKWqkm41Kdd5FUZt3@0PcIZ2XONk19La8DkqMcy@rYbLOSH7@BLMd1AkqfpZWcyGhdT0F4GsaemiklS5OwBVAL42f7O7Yh1MH5wZAWOLMB/VsLQooL1oKJ3v4EMFHMY/cp@4tYpodrCqIYdAv0D9vDzFJgpWqH@kd@5uBriCyXUObck39CyLva6gonhj4/SRcEoYVl035LY4jP9kl9/dhIsvIxw8 "C++ (clang) – Try It Online")
```
int *s,S,*G,x;
int F(int Z,int*p=&x)
{
int W=1,a=(*p)++,r=0;
for(;r=r*10+a%10,a/=10;);
G?W=r,p<=G?G=&W,S++,p=s:0:p=s=G=&W;
return *p-Z&&W-Z?F(Z,p-20):S;
}
```
---
Old solution with standard library (159 bytes)
```
#include<set>
int Z(int N){int C=0,r,a;std::set T{1},S{1};for(;;++C,T=S,S={})for(int i:T){if(i==N)return C;for(r=0,a=i;r=r*10+a%10,a/=10;);S.insert({i+1,r});}}
```
[Try it online!](https://tio.run/##RY8xa8MwEIXn@FcISsGqlNYKhYJlefGexZ66CUUOB44cTnIXob9eV0qhXe54H@8d78z9fjSLdtd9fwJnlu1iO29DX4EL5LMu80xjWYNqOHItfbi0bbaQKYrExzzkvGItJWMDn9TIRxUTLaikoJ1yfK5BqTNFGzZ0ZHgEMN/TCiQqfBEN088i6zclGknl@ArOWwx1BCY4JipT@u8Hqw9o9e235E2DqymJ1aGoL72oRlaHR0sDjvR9YX9k3QLpuvxZhlRWiezvp28zL/rq92O2KMOY@PgB "C++ (clang) – Try It Online")
```
int Z(int N)
{
int C = 0, r, a;
set T{ 1 }, S{ 1 };
for (;; ++C, T = S, S = {})
for (int i : T)
{
if (i == N)
return C;
for (r = 0, a = i; r = r * 10 + a % 10, a /= 10;);
S.insert({ i + 1,r });
}
}
```
Edit: add #include to byte count
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Recursion might well end up being less bytes.
```
ṚḌ;‘))Fṭ
1Ç¡ċ€ċ0
```
A monadic Link accepting a positive integer which yields a non-negative integer
**[Try it online!](https://tio.run/##ASoA1f9qZWxsef//4bma4biMO@KAmCkpRuG5rQoxw4fCocSL4oKsxIsw////MTI "Jelly – Try It Online")**
Or try [a faster, 17 byte version](https://tio.run/##ASsA1P9qZWxsef//4bma4biMO@KAmCkpRlHhua0KMcOHwqHEi@KCrMSLMP///zQy "Jelly – Try It Online")
### How?
```
ṚḌ;‘))Fṭ - Helper Link: next(achievable lists)
) - for each (list so far):
) - for each (value, V, in that list):
Ṛ - reverse the digits of V
Ḍ - convert that to an integer
‘ - increment V
; - concatenate these results
F - flatten the results
- * with a Q here we de-duplicate these results making things faster
ṭ - tack that to the input achievable lists
1Ç¡ċ€ċ0 - Main Link: positive integer, N
1 - literal one
¡ - repeat this (implicit N) times:
Ç - the last Link as a monad - N.B. 1 works just as well as the list of lists [[1]]
ċ€ - for each count the occurrences of (implicit N)
ċ0 - count the zeros (i.e. the number of lists that did not yet contain N)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~26~~ 25 bytes
```
{+(1,{1+$_|+.flip}...$_)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WlvDUKfaUFslvkZbLy0ns6BWT09PJV6z9n9xYqWCSryOuoK6joIeUG1afpGCoY6hkY6RoY6J0X8A "Perl 6 – Try It Online")
Does pretty much as the question asks. Starting from 1, either increment the Junction of values or flip it, repeating this until we find the one value we're looking for. Then return the length of the sequence. This is zero-indexed (as in, `1` returns `1`)
This times out for testcases with a larger number of steps, since for every step we're doubling the size of the Junction by running two operations over the entire thing.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
1¸[ÐIå#ís>«}N
```
-1 byte and much faster thanks to *@Jitse*, which also opened an opportunity for a second -1 byte.
[Try it online](https://tio.run/##MzBNTDJM/f/f8NCO6MMTPA8vVT68ttju0Opav///TYwA) or [verify the first 100 test cases (with added `Ù` -uniquify- to increase the speed)](https://tio.run/##AS0A0v8wNWFiMWX/0YJMdnk/IiDihpIgIj//McK4W8OQecOlI8Otcz7Cq8OZfU7/LP8).
**Explanation:**
```
1¸ # Push 1 and wrap it into a list: [1]
[ # Start an infinite loop:
Ð # Triplicate the list
Iå # If the input-integer is in this list:
# # Stop the infinite loop
í # Reverse each integer in the copy-list
s # Swap to get the initial list again which we triplicated
> # Increase each value by 1
« # And also merge it
}N # After the infinite loop: push the loop-index
# (which is output implicitly as result)
```
Uses the legacy version of 05AB1E, because using the index `N` outside a loop like that doesn't work in the new version.
[Answer]
C++ Recursive Solution:
```
int reverse(int n)//reverses the number
{
int rev=0;
while(n>0)
{
rev=rev*10+n%10;
n/=10;
}
return rev;
}
int sol(int n, int x)
{
if(n==x)// base case
return 0;
if(n>x)// base case
return 1e5;
if(reverse(n)<=n)// otherwise, recursion will happen infinitely
return 1+sol(n+1,x);
return 1+min(sol(n+1,x),sol(reverse(n),x));
}
int main()
{
cout<<sol(1,42);
return 0;
}
```
C++ Dynamic Programming Solution:
```
int dp[1000];
int reverse(int n)//reverses the number
{
int rev=0;
while(n>0)
{
rev=rev*10+n%10;
n/=10;
}
return rev;
}
int sol(int n, int x)
{
if(n==x)// base case
return 0;
if(n>x)// base case
return 1e5;
if(dp[n]!=-1)
return dp[n];
if(reverse(n)<=n)// otherwise, recursion will happen infinitely
return dp[n]=1+sol(n+1,x);
return dp[n]=1+min(sol(n+1,x),sol(reverse(n),x));
}
int main()
{
fill_n(dp,1000,-1);
sol(1,42);
cout<<dp[1];
return 0;
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 67 bytes
Starts from 0. I noticed [GB's Ruby solution](https://codegolf.stackexchange.com/a/195281/52194) after I finished my own, but the approaches used are drastically different (recursive vs. non-recursive) so I decided to post anyways.
```
f=->n{r=n.digits.join.to_i;n<9?n:[f[n-1],n>r&&n%10>0?f[r]:n].min+1}
```
[Try it online!](https://tio.run/##BcFBDoIwEAXQq7iRaIBJa9iIUg4ymRiIrRkTPqTAwgBnr@/Ftf@lFJrSYYsN6K0fXWb6jgpaxpc@8Ly3qDkwSisFXMwynK1xpg0cpYbQoMjtkS6GqLpdaeimbff7dGJfBPYiR/oD "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
Nθ≔⁰ηW⊖θ«F∧⁻⊖θXχ⊖Lθ¬﹪⊖θXχ÷⊕L貫≦⮌θ≦⊕η»≦⊖θ≦⊕η»Iη
```
[Try it online!](https://tio.run/##fY/NCsIwEITP7VPkuIEK/p48ib0UrIhvUNvVBNpNTdJ6EJ89ptpDEOlxmJmPmVIUulRF7VxGbWePXXNBDXe@jXfGyBvBPGHCq4eQNTJIsdTYIFmsfIizZxxdlWawowpySZ35SSTspB4euPCY0Dkg3awYENxnjspCrqquVhP1jGwqe1khZPQPlLDlQPtsivKiHfefsUdtMGHDp9AIKN@L0SsO7GDI2J2ovuKTlmRhXxgLgvOtc4vlar1xs75@Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the target.
```
≔⁰η
```
Set the number of steps to zero.
```
W⊖θ«
```
Repeat until the target becomes 1.
```
F∧⁻⊖θXχ⊖Lθ¬﹪⊖θXχ÷⊕Lθ²
```
Look to see if the target is of the form `xxx0001` or `xxxx0001`, but not `10..01`. (This expression fails for `1`, but fortunately the loop stops before we get here.)
```
«≦⮌θ≦⊕η»
```
If so then reverse the target and increment the number of steps.
```
≦⊖θ≦⊕η
```
Decrement the target and increment the number of steps.
```
»Iη
```
Output the number of steps once the target has been reduced to 1.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 72 bytes
```
->i{*w=0;(0..i).find{[]==[i]-w=w.flat_map{|z|[z+1,z.digits.join.to_i]}}}
```
[Try it online!](https://tio.run/##HctLCsIwEADQq0hXWtMhEXcyXmQcSqVERrQtNiUxn7NH8O3fZ7t/q8XaXSW1HvVlrwHkAFamMREjknDn0YN9Da5/D0vKMVM8GhVhlIe4FZ6zTODmXriUUpfNrTsyymh1PjH8R8gUlKXA3DY315T6Aw "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 78 bytes
```
f=lambda n,s={1}:n in s or-~f(n,{int(str(i)[::-1])for i in s}|{i+1for i in s})
```
[Try it online!](https://tio.run/##TcxNCoMwEEDhq8wyQyM4dBfwJNJFpI0O6EQm2ZTUXj3@rFw@eHzrN09RnrWGbvbL8PYgNnWFNifAAgmiNv9gxBaWbFJWw9g719ALQ1Tga9p@hR90a6xnXIJ6GT@GLLWEbtVTEQuHiFh3 "Python 3 – Try It Online")
Uses 0-indexing. Note that in Python `True == 1`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~71~~ 60 bytes
```
g[1]
g l x|elem x l=0|1>0=g([succ,read.reverse.show]<*>l)x+1
```
[Try it online!](https://tio.run/##NY69CsIwAIT3PsXhlFob7G4zCoLi0LEWCW36g4kNSaoRfHZjVdyOu@Pj67m9CCnDoPRoHIqHdULR3RGk38rJ9itY14yTi6MWOU6hK7Mq6iDhn0IKBQ@Zr58ZW@cdKe1U1ysjeEONuAljBbX9eK82SyZjn2RB8eE6UxTXhzPIyacMenKFM/sryOc645IEC8zD4pO@HWnh4xiM4af0N0KZUVqFV91K3tmQ1lq/AQ "Haskell – Try It Online")
Considerably less efficient than 79037662's existing Haskell answer, but ~~2~~ 13 bytes is ~~2~~ 13 bytes.
### Explanation:
```
g[1]
```
The relevant function: call `g` with `[1]` as its first argument, `l`.
```
g l x|elem x l=0
```
`g` takes two arguments, `l` and `x`, and returns 0 if `l` contains `x`.
```
|1>0=g( ... )x+1
```
Otherwise, it returns 1 plus its return value for a modified value of `l`:
```
[ ... ]<*>l
```
Apply each function from a list of functions to each element of `l`, returning the results in a flat list, using the `Applicative` instance of lists. `succ` adds 1, and...
```
read.reverse.show
```
takes the string representation of its argument, reverses it, then re-interprets it as whatever the type is of the other list elements.
] |
[Question]
[
In Imperial China, ranks in society were not decided by birth or wealth, but by a person's ability to excel in the Imperial Examinations. The Jade Emperor, divine ruler of the Heavens, has called for all his subjects to be examined to determine their worth, and whom to next give the Divine Mandate to rule China.
## Rules of the Bureaucracy:
* The Divine Bureaucracy consists of non-negative integer-valued ranks, starting with 0. Each member (bot) of the bureaucracy belongs to one rank. Each rank can hold arbitrary many members, but can't be empty unless all ranks above are empty
* At the start of the game, all members have rank 0
* Every turn, each member of the bureaucracy has to answer an exam. The exam consist of correctly guessing the boolean values of a list. The length of the list is the number of the rank above the member.
* The exam questions are prepared by a random member of the rank above. Members of the highest rank get their questions directly from the `JadeEmperor` (see below)
* A member scoring at least 50% on their exam is eligible for Promotion. A member scoring less than 50% on their exam is eligible for Demotion.
* A member eligible for Demotion has their rank decreased by one only if there is a member eligible for Promotion on the rank below to take their place.
* All members eligible for Promotion have their rank increased by one as long as this leaves no rank empty.
* If not all eligible members can be Demoted or Promoted, the preference goes to those of lowest (for Demotion) resp. highest (for Promotion) score. Ties are broken randomly.
* The rank of a member can only change by at most 1 each turn.
## Rules of the game:
* Each bot will be randomly assigned an ID at the start of the game, which will not change over its course. The `JadeEmperor` has the ID -1, all others have consecutive non-negative IDs, starting with 0.
* All bots compete at the same time
* The game runs for 100 turns, the score of the bot is its average rank possessed over that time.
* Total score is acquired by running 1000 games and averaging the results.
* Each Bot is a **Python 3** class implementing the following four functions:
+ `ask(self,n,ID)`, which makes an exam by returning a `list` of Booleans of length n. ID is the ID of the bot who has to guess that list. `ask()` can be called many times during a single round for any bot, but also not at all.
+ `answer(self,n,ID)`, which is an attempt to answer an exam by returning a `list` of Booleans of length n. ID is the ID of the bot whose `ask()` generated the exam. `answer()` is called exactly once per round for each bot.
+ `update(self,rankList,ownExam,otherExams)` is called once the Controller has performed all Pro- and Demotions. Its arguments are: A list of integers, listing all ranks by ID of all bots; a tuple, consisting of two lists, first the exam questions, then the answers the bot gave (in case it forgot); then a list of tuples, similarly consisting of exam-answer pairs, this time for all exams the bot handed out.
+ `__init__(self, ID, n)` passes the bot its own ID and the number of competing bots.
* Classes are allowed to implement other functions for private use
* Defining further variables and using them to store data about past exams is explicitly allowed.
* Programming meta-effects are forbidden, meaning any attempts to directly access other bots' code, the Controller's code, causing Exceptions or similar. This is a contest of strategies for the exams, not of code hacking.
* Bots trying to help each other are explicitly allowed, as long as they don't do it via meta-effects, but purely by the information passed through `update()`
* Other languages are allowed only in case they can be easily converted to Python 3.
* The library numpy will be imported as `np`. The version is 1.6.5, meaning it uses the old random library. If you have numpy 1.7, the old functions are available under `numpy.random.mtrand` for testing. Please remember to strip the mtrand for submission.
* If a bot causes an Exception during runtime, it is disqualified. Any bot whose code is so obfuscated that it's impossible to tell if it generates a list of length n when `ask()` or `answer()` is called will also be disqualified preemptively. A bot forcing me to deep-copy outputs gets -1 on the score.
* Class names have to be unique
* Multiple bots per person are allowed, but only the latest version will be taken of iteratively updated bots.
* Since there seems to be some confusion about bot similarity:
+ You are **not allowed** to post a copy of another bot. This is the only [Standard Loophole](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) which really applies in this challenge.
+ You are **allowed** to have shared code with other bots, including bots of other people.
+ You are **not allowed** to submit a bot which differs from another only by a trivial change to the strategy (like a change in the seed for the question generation) **unless** you can prove that the number of such carbon copy bots is the minimum required for successful enactment of their strategy (That will usually be two bots for a cooperation).
### Example Bots:
The `JadeEmperor` is always part of the game, but does not compete; he serves as generator for exams of highest-rank bots. His exams are random, but not uniformly, to allow smart bots a way to advance.
```
class JadeEmperor:
def __init__(self):
pass
def ask(self,n,ID):
num=min(np.random.exponential(scale=np.sqrt(np.power(2,n))),np.power(2,n)-1)
bi=list(np.binary_repr(int(num),width=n))
return [x=='0' for x in bi]
```
The **Drunkard** produces exams and answers completely randomly. He will be part of the game.
```
class Drunkard:
def __init__(self,ID,n):
pass
def ask(self,n,ID):
return list(np.random.choice([True,False],size=n,replace=True))
def answer(self,n,ID):
return list(np.random.choice([True,False],size=n,replace=True))
def update(self,rankList,ownExam,otherExams):
pass #out
```
The **Plagiarist** just copies previous exams. He will also be part of the game.
```
class Plagiarist:
def __init__(self,ID,n):
self.exam=[True]
def ask(self,n,ID):
return (self.exam*n)[0:n]
def answer(self,n,ID):
return (self.exam*n)[0:n]
def update(self,rankList,ownExam,otherExams):
self.exam=ownExam[0]
```
Controller code available [here](https://www.dropbox.com/s/2umzthm50l1x7g3/Controller.py?dl=0). For testing, you can put your own class into a Contestants.py file in the same folder, and they will be imported.
Chatroom can be found [here](https://chat.stackexchange.com/rooms/98905/imperial-exams-office).
# The Examinations begin!
Current score, in higher precision (10000 runs) for Oct20:
$$
\begin{array}{|c|c|c|}\hline \textbf{Entrant}&\textbf{Author}&\textbf{Score}\\\hline
%
\text{Alpha}&\text{Sleafar}&9.669691\\ \hline
\text{Gamma}&\text{Sleafar}&9.301362\\ \hline
\text{Beta}&\text{Sleafar}&9.164597\\ \hline
\text{WiQeLu}&\text{Purple P}&7.870821\\ \hline
\text{StudiousBot}&\text{Dignissimus - Spammy}&7.538537\\ \hline
\text{Santayana}&\text{Sara J}&7.095528\\ \hline
\text{Plagiarist}&\text{}&6.522047\\ \hline
\text{CountOracular}&\text{IFcoltransG}&5.881175\\ \hline
\text{Thomas}&\text{Alien@System}&5.880041\\ \hline
\text{Contrary}&\text{Draco18s}&5.529652\\ \hline
\text{Marx}&\text{sugarfi}&5.433808\\ \hline
\text{Drunkard}&\text{}&5.328178\\ \hline
\text{YinYang}&\text{Purple P}&5.102519\\ \hline
\text{Equalizer}&\text{Mnemonic}&4.820996\\ \hline
\text{TitForTat}&\text{Anonymous}&3.35801\\ \hline
\end{array}$$
Contests will be run with each new entry for the foreseeable future.
[Answer]
# Santayana
Those who cannot remember the past are condemned to repeat it. So we make our decisions based on how the others have acted in the past, answering based on what answer the asker has usually expected from us at a given index, and asking for the answer they've given us the least often at a given index.
```
import numpy as np
class Santayana:
"""
Those who cannot remember the past are condemned to repeat it
"""
def __init__(self, ID, num_competitors):
self.ID = ID
self.exams_taken = {}
self.exams_issued = {}
self.last_exam_asker = None
self.recent_exam_takers = []
for i in range(num_competitors):
self.exams_taken[i] = []
self.exams_issued[i] = []
def ask(self, length, taker_ID):
# Remember who asked
self.recent_exam_takers.append(taker_ID)
new_exam = []
# At every index, expect the answer they've given the least often (default to False if equal)
for i in range(length):
trues = 0
falses = 0
for exam in self.exams_issued[taker_ID]:
if len(exam) <= i: continue
if exam[i]:
trues += 1
else:
falses += 1
new_exam.append(trues < falses)
return new_exam
def answer(self, num_answers, asker_ID):
self.last_exam_asker = asker_ID
if asker_ID == -1:
# Copy emperor's process to hopefully get a similar exam
num = min(np.random.exponential(scale=np.sqrt(np.power(2,num_answers))),np.power(2,num_answers)-1)
as_bin = list(np.binary_repr(int(num),width=num_answers))
return [x=='0' for x in as_bin]
else:
new_answer = []
# At every index, give the answer that's been correct the greatest number of times (default to True if equal)
for i in range(num_answers):
trues = 0;
falses = 0;
for exam in self.exams_taken[asker_ID]:
if len(exam) <= i: continue
if exam[i]:
trues += 1
else:
falses += 1
new_answer.append(trues >= falses)
return new_answer
return [True for i in range(num_answers)]
def update(self, rank_list, own_exam, other_exams):
if self.last_exam_asker > -1:
# Save the exam we took, unless it was from the Emperor - we already know how he operates
self.exams_taken[self.last_exam_asker].append(own_exam[0])
for i in range(len(self.recent_exam_takers)):
# Save the responses we got
self.exams_issued[i].append(other_exams[i][1])
self.recent_exam_takers = []
```
[Answer]
# Alpha
*Read the chat before downvoting. These bots don't violate any rules. The OP is even encouraging cooperating bots.*
Alpha is forming a team together with Beta. Both are using a predefined set of exams to help each other rise up the ranks. Also both are taking advantage of bots using the same exams over and over.
```
import numpy as np
import hashlib
class Alpha:
def __init__(self, ID, n):
self.alpha = hashlib.md5(b"Alpha")
self.beta = hashlib.md5(b"Beta")
self.asker = -1
self.betas = set(range(n)).difference([ID])
self.fixed = set(range(n)).difference([ID])
self.fixedExams = [[]] * n
def ask(self,n,ID):
if ID in self.betas:
return self.md5ToExam(self.alpha, n)
else:
return list(np.random.choice([True, False], n))
def answer(self,n,ID):
self.asker = ID
if self.asker == -1:
return [True] * n
elif self.asker in self.fixed and len(self.fixedExams[self.asker]) > 0:
return (self.fixedExams[self.asker] * n)[:n]
elif self.asker in self.betas:
return self.md5ToExam(self.beta, n)
else:
return list(np.random.choice([True, False], n))
def update(self,rankList,ownExam,otherExams):
if self.asker >= 0:
if self.asker in self.betas and ownExam[0] != self.md5ToExam(self.beta, len(ownExam[0])):
self.betas.remove(self.asker)
if self.asker in self.fixed:
l = min(len(ownExam[0]), len(self.fixedExams[self.asker]))
if ownExam[0][:l] != self.fixedExams[self.asker][:l]:
self.fixed.remove(self.asker)
self.fixedExams[self.asker] = []
elif len(ownExam[0]) > len(self.fixedExams[self.asker]):
self.fixedExams[self.asker] = ownExam[0]
self.alpha.update(b"Alpha")
self.beta.update(b"Beta")
def md5ToExam(self, md5, n):
return [x == "0" for x in bin(int(md5.hexdigest(), 16))[2:].zfill(128)][:n]
```
[Answer]
# Studious Bot
This bot studies for tests! It attempts to find patterns in tests given out by various bots and acts accordlingly.
On my end, so far, this bot outperforms all other bots that I could get working on my computer except from Alpha, Beta and Gamma (who have been programmed to work together). The bot doesn't make use of the fact that teaming is allowed because I felt that it was a bit like cheating and slightly dirty. Looking over it though, teaming seems to seems to be quite effective.
The bot attempts to recognise when the answers to tests are random and in response matches that to hopefully average 50% on tests.
The bot also attempts to recognise when a bot has merely flipped its answers to throw off other bots who are tying to predict their behaviour, however I haven't programmed it to specifically act on this yet.
I've annotated the code with a few comments in order to make it easier to read
```
import random
import numpy as np
class StudiousBot:
GRAM_SIZE = 5
def __init__(self, identifier, n):
self.id = identifier
self.ranks = {i: 0 for i in range(n)} # Stores ranks
self.study_material = {i: [] for i in range(n)} # Stores previous exam data
self.distribution = {i: [] for i in range(n)} # Stores the percentage of answers that were `True` on a Bot's tests over time
self.last_examiner = None
def ask(self, n, identifier):
# This bot gives random tests, it doesn't bother making them difficult based on answers to them
# The reason for this is that I can't personalise the tests for each bot
return [random.choice([True, False]) for i in range(n)]
def answer(self, n, examiner_id):
self.last_examiner = examiner_id
if examiner_id == -1:
return StudiousBot.answer_emperor(n) # Easy win, I know the distribution of answers for the Emperor's tests
bother_predicting = True # Whether or not the Bot will attempt to predict the answers to the exam
study_material = self.study_material[examiner_id]
distribution = self.distribution[examiner_id]
if len(distribution) > 0: # If there is actually data to analyse
sd = StudiousBot.calculate_standard_deviation(distribution)
normalised_sd = StudiousBot.calculate_normalised_standard_deviation(distribution)
if abs(30 - sd) < 4: # 30 is the expected s.d for a random distribution
bother_predicting = False # So I won't bother predicting the test
if abs(sd - normalised_sd * 2) > 4: # The bot is merely inverting answers to evade being predicted
pass # However, at this time, I'm not certain how I should deal with this. I'll continue to attempt to predict the test
if bother_predicting and len(study_material) >= StudiousBot.GRAM_SIZE:
return StudiousBot.predict(study_material, n)
return [random.choice([True, False]) for i in range(n)]
def predict(study_material, n): # Predicts the answers to tests with `n` questions
grams = StudiousBot.generate_ngrams(study_material, StudiousBot.GRAM_SIZE) # Generate all n-grams for the study material
last_few = study_material[-(StudiousBot.GRAM_SIZE - 1):] # Get the last 9 test answers
prediction = None
probability = -1
for answer in [True, False]: # Finds the probabiility of the next answer being True or False, picks the one with the highest probability
new_prediction = last_few + [answer]
new_probability = grams.count(new_prediction)
if new_probability > probability:
prediction = answer
probability = new_probability
if n == 1:
return [prediction]
return [prediction] + StudiousBot.predict(study_material + [prediction], n-1)
@staticmethod
def calculate_standard_deviation(distribution):
return np.std(distribution)
def calculate_normalised_standard_deviation(distribution): # If the answers happen to be inverted at some point, this function will return the same value for answers that occured both before and after this point
distribution = list(map(lambda x: 50 + abs(50-x), distribution))
return StudiousBot.calculate_standard_deviation(distribution)
@staticmethod
def generate_ngrams(study_material, n):
assert len(study_material) >= n
ngrams = []
for i in range(len(study_material) - n + 1):
ngrams.append(study_material[i:i+n])
return ngrams
def update(self, ranks, own_exam, other_exams):
self.ranks = dict(enumerate(ranks))
if self.last_examiner != -1:
self.study_material[self.last_examiner] += own_exam[0]
self.distribution[self.last_examiner].append(own_exam[0].count(True) / len(own_exam[0]) * 100) # Stores the percentage of the answers which were True
@staticmethod
def answer_emperor(n): # Algorithm to reproduce Emperor's distribution of test answers
exp = np.random.exponential(scale=np.sqrt(np.power(2,n)))
power = np.power(2,n) - 1
num = min(exp, power)
bi = list(np.binary_repr(int(num), width=n))
return [x == '0' for x in bi]
```
[Answer]
# Count Oracular
This bot uses an algorithm that averages the exams of all other working bots, (given the round number and some terrible heuristics) for deciding what each other bot will set as the exam.
The Count asks its exams using an md5 hash. Both its questions and its answers are therefore deterministic. It ignores most inputs, asking and answering the exact same sequences of booleans, rain or shine, including against Jade Emporer.
```
import numpy as np
import hashlib
class CountOracular:
'''Uses very little external data to make heuristical statistical
deterministic predictions about the average exam.
(Assonance not intended.)
To generate its own exams, uses a deterministic hash.'''
def __init__(self, id, number_of_bots):
self.last_round = []
#functions for calculating what other bots will likely do.
self.bots_calculators = [
self._jad, #Jade Emporer
self._alp, #Alpha
self._bet, #Beta
self._gam, #Gamma
self._wiq, #Wi Qe Lu
self._stu, #StudiousBot
self._pla, #Plagiarist
self._san, #Santayana
self._tho, #Thomas
self._dru, #Drunkard
self._yin, #YinYang
self._con, #Contrary
self._tit, #TitForTat
self._equ, #Equalizer
self._mar, #Marx
]
self.bot_types = len(self.bots_calculators)
def ask(self, n, id):
#if we can, show that hardcoding is no match for the power of heuristics:
if n == 2:
return [False, True]
#otherwise, refer to the wisdom of Mayor Prentiss in order to command The Ask
#i.e. hashes a quote, and uses that as the exam.
salt = b"I AM THE CIRCLE AND THE CIRCLE IS ME " * n
return self._md5_from(salt, n)
def answer(self, n, id):
#uses the power of heuristics to predict what the average bot will do
#ignores all inputs except the length of the output
#very approximate, and deterministic
#i.e. every game, Count Oracular will send the same lists of answers, in the same order
best_guess_totals = [0.5] * n #halfway between T and F
for bot in self.bots_calculators:
exam, confidence = bot(n)
if not exam:
continue
while len(exam) < n:
#ensure exam is long enough
exam += exam[:1]
exam = exam[:n] #ensure exam is short enough
#map T and F to floats [0,1] based on confidence
weighted_exam = [0.5+confidence*(0.5 if q else -0.5) for q in exam]
best_guess_totals = [current+new for current,new in zip(best_guess_totals, weighted_exam)]
best_guess_averages = [total/self.bot_types
for total
in best_guess_totals
]
best_guess = [avg > 0.5 for avg in best_guess_averages]
self.last_round = best_guess
return best_guess
def update(self, ranks, own, others):
pass
def _md5_from(self, data, n):
md5 = hashlib.md5(data)
for i in range(n):
md5.update(data)
exam = []
while len(exam) < n:
exam += [x == "0"
for x
in bin(int(md5.hexdigest(), 16))[2:].zfill(128)
]
md5.update(data)
return exam[:n]
def _invert(self, exam):
return [not val for val in exam]
def _digits_to_bools(self, iterable):
return [char=="1" for char in iterable]
def _plagiarise(self, n):
copy = (self.last_round * n)[:n]
return copy
'''functions to calculate expected exams for each other bot:
(these values, weighted with corresponding confidence ratings,
are summed to calculate the most likely exam.)'''
def _jad(self, n):
'''Calculate the mean of _jad's distribution, then
use that as the guess'''
mean = max(int(np.sqrt(np.power(2,n))), (2<<n)-1)
string_mean = f"{mean}".zfill(n)
exam = self._invert(self._digits_to_bools(string_mean))
return exam, 0.5
def _alp(self, n):
'''Alpha uses a predictable hash,
until it figures out we aren't Beta,
modelled by the probability of giving or solving
Alpha's exam'''
#probability that Alpha thinks we're Beta
#assuming we fail to pretend to be Beta if we meet Alpha
chance_beta = ((1 - 1/self.bot_types) ** n) ** 2
return self._md5_from(b"Beta", n), chance_beta
def _gam(self, n):
'''Gamma is like Beta, except after realising,
switches to 50-50 random choice of inverse
either Beta or Alpha's hash'''
#probability that Gamma thinks we're Alpha still
#(Unlikely that Gamma will think we're Beta;
#we'd need to fail Alpha but pass Beta,
#therefore, not accounted for)
chance_unknown = ((1 - 1/self.bot_types) ** n) ** 2
#default exam that assumes that Gamma thinks we're Alpha
exam = self._md5_from(b"Beta", n)
if chance_unknown > 0.5:#there exists a better heuristic here
#assume Gamma will consider us Alpha
confidence = chance_unknown
else:
#assume Gamma considers us neither Alpha nor Beta
alpha = self._invert(self._md5_from(b"Beta", n))
beta = self._invert(self._md5_from(b"Alpha", n))
#check for bools where both possible exams match
and_comp = [a and b for a, b in zip(alpha, beta)]
nor_comp = [not (a or b) for a, b in zip(alpha, beta)]
#count up matches vs times when fell back on default
#to calculate ratio of default
#to bools where hashes agree
confidence_vs_default = (sum(and_comp)+sum(nor_comp)) / n
confidence = confidence_vs_default * chance_unknown + (1 - confidence_vs_default) * (1 - chance_unknown)
for i in range(n):
if and_comp[i]:
exam[i] = True
if nor_comp[i]:
exam[i] = False
return exam, confidence
def _bet(self, n):
'''Beta is like Alpha, but with a different hash'''
#probability we haven't matched with Beta yet
#i.e. probability that Beta still thinks we're Alpha
chance_alpha = ((1 - 1/self.bot_types) ** n) ** 2
return self._md5_from(b"Alpha", n), chance_alpha
def _wiq(self, n):
'''Wi Qe Lu is hard to model, so we pretend
that it mimicks Plagiarist for the most part'''
if n == 1:
#first round is random
return [False], 0
#other rounds are based on exams it met
#leaning towards same as the previous exam
return self._plagiarise(n), 0.1
def _stu(self, n):
'''StudiousBot is random'''
return [False] * n, 0
def _pla(self, n):
'''Plagiarist copies the exams it received,
which can be modelled with the standard prediction
calculated for the previous round, padded with its first
element.'''
if n == 1:
return [True], 1
return self._plagiarise(n), 0.3
def _san(self, n):
'''Santayana is based on answers, which we don't predict.
Modelled as random.'''
#mostly random, slight leaning towards default False
return [False] * n, 0.1
def _tho(self, n):
'''Thomas has an unpredictable threshold.'''
#for all intents, random
return [False] * n, 0
def _dru(self, n):
'''Drunkard is utterly random.'''
return [False] * n, 0
def _yin(self, n):
'''YinYang inverts itself randomly, but not unpredictably.
We can model it to find the probability. Also notably,
one index is inverted, which factors into the confidence
especially for lower n.'''
if n == 1:
#one element is inverted, so whole list must be False
return [False], 1
if n == 2:
#split half and half randomly; can't predict
return [True] * n, 0
#cumulative chance of mostly ones or mostly zeros
truthy = 1
for _ in range(n):
#simulate repeated flipping
truthy = truthy * 0.44 + (1-truthy) * 0.56
falsey = 1 - truthy
if falsey > truthy:
return [False] * n, falsey - 1/n
return [True] * n, truthy - 1/n
def _con(self, n):
'''Contrary is like Jade Emporer, but inverts itself
so much that modelling the probability of inversion
is not worth the effort.'''
#there are some clever ways you could do statistics on this,
#but I'm content to call it uniform for now
return [False] * n, 0
def _tit(self, n):
'''TitForTat is most likely to give us False
but the confidence drops as the chance of having
met TitForTat increases.
The square root of the probability we calculate for
Alpha, Beta and Gamma, because those also care about what
we answer, whereas TitForTat only cares about what we ask'''
#probability that we've not given TitForTat an exam
chance_friends = (1 - 1/self.bot_types) ** n
return [False] * n, chance_friends
def _equ(self, n):
'''Equalizer always asks True'''
#certain that Equalizer's exam is all True
return [True] * n, 1
def _mar(self, n):
'''Marx returns mostly True, randomised based on our rank.
We don't predict our rank.
There's ~50% chance an answer is random'''
#75% chance we guess right (= 50% + 50%*50%)
return [True] * n, 0.75
```
[Answer]
# YinYang
Answers either all `True` or all `False`, except for one index randomly chosen to be the opposite. Asks the opposite of what it answers. Swaps randomly to throw off opponents.
```
import random
class YinYang:
def __init__(self, ID, n):
self.exam = True
def update(self, rankList, ownExam, otherExams):
if random.random() < 0.56:
self.exam = not self.exam
def answer(self, n, ID):
a = [not self.exam] * n
a[random.randint(0, n-1)] = self.exam
return a
def ask(self, n, ID):
e = [self.exam] * n
e[random.randint(0, n-1)] = not self.exam
return e
```
# Wi Qe Lu (Switcheroo)
Answers and asks randomly in the first round. Afterwards, he uses the answers from the previous exam, and changes a question if an above-average number of competitors got it right.
```
class WiQeLu:
def __init__(self, ID, n):
self.rounds = 1
self.firstexam = True
self.firstanswer = True
self.lastexaminer = -1
self.exam = []
self.pastanswers = {}
def update(self, rankList, ownExam, otherExams):
questions, lastanswers = ownExam
self.pastanswers[self.lastexaminer] = questions
if len(otherExams) == 0:
return
correctCounts = [0 for i in otherExams[0][0]]
for ourExam, response in otherExams:
for i in range(len(response)):
if ourExam[i] == response[i]:
correctCounts[i] += 1
newExam = otherExams[0][0]
meanWhoAnsweredCorrectly = sum(correctCounts) / len(correctCounts)
for i in range(len(correctCounts)):
if correctCounts[i] > meanWhoAnsweredCorrectly:
newExam[i] = not newExam[i]
self.exam = newExam
def answer(self, n, ID):
self.lastexaminer = ID
if ID not in self.pastanswers:
randomanswer = [random.randint(0, 1) == 1] * n
self.pastanswers[ID] = randomanswer
return randomanswer
return (self.pastanswers[ID] * n)[:n]
def ask(self, n, ID):
if self.firstexam:
self.firstexam = False
self.exam = [random.randint(0, 1) == 1] * n
return (self.exam * n)[:n]
```
[Answer]
One bot of my own:
# Thomas
A traveler from a far-away land, has some dangerous ideas about past results being indicative of future performance. He uses those to keep other bots down, unless that stifles his own advancement.
```
class Thomas:
def __init__(self,ID,n):
N=10
self.ID=ID
self.myrank=n
self.lowerank=0
#The highest number of questions is equal to the number of participants, so we can do this:
self.probs=[{i:1.0/N for i in np.linspace(0,1,num=N)} for i in np.arange(n)]
self.output=[0.5]*n
def ask(self,n,ID):
if self.myrank==1 and self.lowerrank > 1: #I can't advance without promoting somebody first
return [self.output[i]>np.random.rand() for i in np.arange(n)]
#Otherwise, try to step on their fingers by going against the expected probability
return [self.output[i]<np.random.rand() for i in np.arange(n)]
def answer(self,n,ID):
return [self.output[i]>np.random.rand() for i in np.arange(n)]
def update(self,rankList,ownExam,otherExams):
#Update our ranks
self.myrank=len([i for i in rankList if i==rankList[self.ID]])
self.lowerrank=len([i for i in rankList if i==rankList[self.ID]-1])
#Update our expectations for each input we've been given
self.bayesianupdate(ownExam[0])
for ex in otherExams:
self.bayesianupdate(ex[1])
#Compress into output variable
self.output=[np.sum([l[entry]*entry for entry in l]) for l in self.probs]
def bayesianupdate(self,data):
for i in np.arange(len(data)):
if data[i]: #Got a True
self.probs[i].update({entry:self.probs[i][entry]*entry for entry in self.probs[i]})
else: #Got a False
self.probs[i].update({entry:self.probs[i][entry]*(1-entry) for entry in self.probs[i]})
s=np.sum([self.probs[i][entry] for entry in self.probs[i]]) #Renormalize
self.probs[i].update({entry:self.probs[i][entry]/s for entry in self.probs[i]})
```
```
[Answer]
# Beta
*Read the chat before downvoting. These bots don't violate any rules. The OP is even encouraging cooperating bots.*
Beta is forming a team together with Alpha. Both are using a predefined set of exams to help each other rise up the ranks. Also both are taking advantage of bots using the same exams over and over.
```
import numpy as np
import hashlib
class Beta:
def __init__(self,ID,n):
self.alpha = hashlib.md5(b"Alpha")
self.beta = hashlib.md5(b"Beta")
self.asker = -1
self.alphas = set(range(n)).difference([ID])
self.fixed = set(range(n)).difference([ID])
self.fixedExams = [[]] * n
def ask(self,n,ID):
if ID in self.alphas:
return self.md5ToExam(self.beta, n)
else:
return list(np.random.choice([True, False], n))
def answer(self,n,ID):
self.asker = ID
if self.asker == -1:
return [True] * n
elif self.asker in self.fixed and len(self.fixedExams[self.asker]) > 0:
return (self.fixedExams[self.asker] * n)[:n]
elif self.asker in self.alphas:
return self.md5ToExam(self.alpha, n)
else:
return list(np.random.choice([True, False], n))
def update(self,rankList,ownExam,otherExams):
if self.asker >= 0:
if self.asker in self.alphas and ownExam[0] != self.md5ToExam(self.alpha, len(ownExam[0])):
self.alphas.remove(self.asker)
if self.asker in self.fixed:
l = min(len(ownExam[0]), len(self.fixedExams[self.asker]))
if ownExam[0][:l] != self.fixedExams[self.asker][:l]:
self.fixed.remove(self.asker)
self.fixedExams[self.asker] = []
elif len(ownExam[0]) > len(self.fixedExams[self.asker]):
self.fixedExams[self.asker] = ownExam[0]
self.alpha.update(b"Alpha")
self.beta.update(b"Beta")
def md5ToExam(self, md5, n):
return [x == "0" for x in bin(int(md5.hexdigest(), 16))[2:].zfill(128)][:n]
```
[Answer]
# Gamma
*Read the chat before downvoting. These bots don't violate any rules. The OP is even encouraging cooperating bots.*
Gamma has discovered the plans of Alpha and Beta and is trying to take advantage of both of them by disguising as one of them.
```
import numpy as np
import hashlib
class Gamma:
def __init__(self, ID, n):
self.alpha = hashlib.md5(b"Alpha")
self.beta = hashlib.md5(b"Beta")
self.asker = -1
self.alphas = set(range(n)).difference([ID])
self.betas = set(range(n)).difference([ID])
self.fixed = set(range(n)).difference([ID])
self.fixedExams = [[]] * n
def ask(self,n,ID):
if ID in self.alphas:
return self.md5ToExam(self.beta, n)
elif ID in self.betas:
return self.md5ToExam(self.alpha, n)
else:
return self.md5ToWrongExam(np.random.choice([self.alpha, self.beta], 1)[0], n)
def answer(self,n,ID):
self.asker = ID
if self.asker == -1:
return [True] * n
elif self.asker in self.fixed and len(self.fixedExams[self.asker]) > 0:
return (self.fixedExams[self.asker] * n)[:n]
elif self.asker in self.alphas:
return self.md5ToExam(self.alpha, n)
elif self.asker in self.betas:
return self.md5ToExam(self.beta, n)
else:
return list(np.random.choice([True, False], n))
def update(self,rankList,ownExam,otherExams):
if self.asker >= 0:
if self.asker in self.alphas and ownExam[0] != self.md5ToExam(self.alpha, len(ownExam[0])):
self.alphas.remove(self.asker)
if self.asker in self.betas and ownExam[0] != self.md5ToExam(self.beta, len(ownExam[0])):
self.betas.remove(self.asker)
if self.asker in self.fixed:
l = min(len(ownExam[0]), len(self.fixedExams[self.asker]))
if ownExam[0][:l] != self.fixedExams[self.asker][:l]:
self.fixed.remove(self.asker)
self.fixedExams[self.asker] = []
elif len(ownExam[0]) > len(self.fixedExams[self.asker]):
self.fixedExams[self.asker] = ownExam[0]
self.alpha.update(b"Alpha")
self.beta.update(b"Beta")
def md5ToExam(self, md5, n):
return [x == "0" for x in bin(int(md5.hexdigest(), 16))[2:].zfill(128)][:n]
def md5ToWrongExam(self, md5, n):
return [x == "1" for x in bin(int(md5.hexdigest(), 16))[2:].zfill(128)][:n]
```
[Answer]
# Equalizer
Everyone should be equal (with none of this silly emperor nonsense), so provide as much social mobility as possible. Make the questions really easy (the answer is always True) so that people can succeed.
```
class Equalizer:
def __init__(self, ID, n):
self.previousAnswers = [[0, 0] for _ in range(n)]
self.previousAsker = -1
def ask(self, n, ID):
return [True] * n
def answer(self, n, ID):
if ID == -1:
return [True] * n
# Assume that questions from the same bot will usually have the same answer.
t, f = self.previousAnswers[ID]
return [t >= f] * n
def update(self, rankList, ownExam, otherExams):
if self.previousAsker == -1:
return
# Keep track of what answer each bot prefers.
counts = self.previousAnswers[self.previousAsker]
counts[0] += ownExam[0].count(True)
counts[1] += ownExam[0].count(False)
```
[Answer]
# TitForTat
Asks you easy questions if you asked it easy questions in the past. If you have never given it an exam, it defaults to easy questions.
Additionally, does not trust anyone who asks difficult questions, and will give them unpredictable answers.
```
import numpy as np
class TitForTat:
def __init__(self, ID, n):
self.friendly = [True] * n
self.asker = -1
def make_answers(self, n, ID):
if ID == -1 or self.friendly[ID]:
return [False] * n
else:
return list(np.random.choice([True, False], n))
def ask(self, n, ID):
return self.make_answers(n, ID)
def answer(self, n, ID):
self.asker = ID
return self.make_answers(n, ID)
def update(self, rankList, ownExam, otherExams):
if self.asker != -1:
# You are friendly if and only if you gave me a simple exam
self.friendly[self.asker] = all(ownExam[0])
```
This bot works well if other bots cooperate with it. Currently only Equaliser cooperates, but this should hopefully be enough.
[Answer]
# Contrary
The Jade Emperor is always right, so it implements the Jade Emperor's asking function as its own answer function when it needs more than 2 answers. For only 1 answer it answers `true` (decent odds of being correct) and for 2 it answers `true,false` (this response passes "at least half" of the questions three out of four possible quizzes, better than choosing at random).
Uses similar logic in its Update with regards to how it alters its asking pattern, but its asking logic is similar to the Jade Emperor's, just with a different weight. Fluctuates between higher values of `true` with higher values of `false` when too many candidates score high enough to pass.
```
class Contrary:
def __init__(self,ID,n):
self.rank = 0
self.ID = ID
self.competitors = {}
self.weight = -2
pass
def ask(self,n,ID):
if self.weight > 0:
num=min(np.random.exponential(scale=np.sqrt(np.power(self.weight,n))),np.power(2,n)-1)
bi=list(np.binary_repr(int(num),width=n))
return [x=='0' for x in bi]
else:
num=min(np.random.exponential(scale=np.sqrt(np.power(-self.weight,n))),np.power(2,n)-1)
bi=list(np.binary_repr(int(num),width=n))
return [x=='1' for x in bi]
def answer(self,n,ID):
if n == 1:
return [True]
if n == 2:
return [True,False]
num=min(np.random.exponential(scale=np.sqrt(np.power(2,n))),np.power(2,n)-1)
bi=list(np.binary_repr(int(num),width=n))
return [x=='0' for x in bi]
def update(self,rankList,ownExam,otherExams):
self.rank = rankList[self.ID];
if len(otherExams) == 0:
return
correctCounts = [0 for i in otherExams[0][0]]
for ourExam, response in otherExams:
for i in range(len(response)):
if ourExam[i] == response[i]:
correctCounts[i] += 1
meanWhoAnsweredCorrectly = sum(correctCounts) / len(correctCounts)
for i in range(len(correctCounts)):
if correctCounts[i]+1 > meanWhoAnsweredCorrectly:
self.weight = np.copysign(np.random.uniform(1,3),-self.weight)
```
[Answer]
# Marx
This is the Marx bot. He believes that, instead of a bureaucracy, we should have a communist system. To help reach this goal, it gives harder quizzes to higher ranking bots. It also gives more random answers to quizzes from higher bots, because they are probably cleverer, because they are higher up.
```
import numpy as np
class Marx():
def __init__(self, ID, n):
self.ID = ID
self.n = n
self.ranks = [] # The bot rankings
self.e = [] # Our quiz
self.rank = 0 # Our rank
def ask(self, n, ID):
test = [True] * n
# Get the rank of the bot being quizzed
if self.ranks:
rank = self.ranks[ID]
else:
rank = 0
for i in range(len(test)):
item = test[i]
if np.random.uniform(0, rank / self.n) > 0.5:
# If the bot is higher ranking, make the quiz harder
item = np.random.choice([True, False], 1)[0]
test[i] = item
# IF the test is not long enough, add Falses to the end
while len(test) < n - 1:
test.append(False)
return test
def answer(self, n, ID):
# Get the rank of the asking bot
if self.ranks:
rank = self.ranks[ID]
else:
rank = 0
if self.e:
# Pad our quiz with Falses so it will not throw IndexError
while len(self.e) < n:
self.e.append(False)
for i in range(len(self.e)):
item = self.e[i]
if np.random.uniform(0, rank / self.n) > 0.5:
# Assume that higher ranking bots are cleverer, so add more random answers
item = np.random.choice([True, False], 1)[0]
self.e[i] = item
if len(self.e) > self.rank + 1:
self.e = self.e[:self.rank + 1]
return self.e
else:
# If it is the first round, return all Trues
return [True] * n
def update(self, rankList, ownExam, otherExams):
# Update our list of ranks
self.ranks = rankList
# Store the quiz we were given, to give to the next bot
self.e = ownExam[0]
# Store our rank
self.rank = rankList[self.ID]
```
] |
[Question]
[
## Input
A non-empty array of positive integers.
## Task
Convert each integer to either binary, octal, decimal or hexadecimal in such a way that each digit (**0** to **F**) is used at most once.
## Output
The list of bases that were used to solve the puzzle.
## Detailed example
The expected output for **[ 16, 17 ]** is **[ octal, decimal ]**.
Here is why:
* We can't simply use decimal for both numbers, because they both contains a **1**.
* **16** cannot be converted to binary, because its representation in this base (**10000**) contains several **0**'s.
* **17** cannot be converted to binary either, because its representation in this base (**10001**) contains several **0**'s and several **1**'s.
* **17** cannot be converted to hexadecimal, because its representation in this base (**11**) consists of two **1**'s.
* Let's consider all remaining possibilities:
```
+---------+---------+--------+
| oct(16) | dec(16) | hex(16)|
| = 20 | = 16 | = 10 |
+--------------+---------+---------+--------+
| oct(17) = 21 | 20,21 | 16,21 | 10,21 |
| dec(17) = 17 | 20,17 | 16,17 | 10,17 |
+--------------+---------+---------+--------+
```
The only possible solution is to convert **16** in octal (**20**) and to keep **17** in decimal (**17**). This way, the digits **0**, **1**, **2** and **7** are used exactly once.
## Clarifications and rules
* **The input is guaranteed to lead to a unique solution.** Your code is not supposed to support arrays that give several solutions or no solution at all.
* You may output the bases in any reasonable format, such as **[ "bin","oct","dec","hex" ]**, **[ 'b','o','d','h' ]**, **"BODH"**, **[ 2,8,10,16 ]**, **[ 0,1,2,3 ]** etc. But it should be clearly explained in your answer.
* The order of the bases in the output must match the order of the input integers.
* If that helps, you may assume that the input is sorted from lowest to highest, or from highest to lowest.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
## Test cases
You do not have to output the conversion results listed below. They are purely informational.
```
Input | Output | Conversion result
---------------------------------------+-----------------+------------------------
[ 119 ] | O | 167
[ 170 ] | D | 170
[ 64222 ] | H | FADE
[ 16, 17 ] | O/D | 20/17
[ 14, 64, 96 ] | H/H/D | E/40/96
[ 34, 37, 94 ] | O/D/H | 42/37/5E
[ 2, 68, 82 ] | B/D/H | 10/68/52
[ 22, 43, 96 ] | O/O/O | 26/53/140
[ 3639, 19086, 57162 ] | H/D/H | E37/19086/DF4A
[ 190, 229, 771 ] | O/H/O | 276/E5/1403
[ 2, 44, 69, 99 ] | B/H/H/H | 10/2C/45/63
[ 75, 207, 218, 357, 385 ] | H/H/H/D/O | 4B/CF/DA/357/601
[ 12, 28, 46, 78, 154, 188, 222, 240 ] | D/O/O/D/H/H/H/H | 12/34/56/78/9A/BC/DE/F0
```
The raw input list **[is available here](https://pastebin.com/0a5PtDZK)**.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org),192,155,154,152,151,145,136,113,99,92 90 bytes
* thanks to @Arnauld for reminding me that i can return [0,1,2,3] -> which is [2,8,10,16] saves 8 bytes, and for the brilliant idea (which help to reduce by 23+ bytes)
* thanks to @Kevin Cruijssen for reducing by 1 bytes
```
f=([c,...a],t="")=>c?[1,4,5,8].find(b=>T=!/(.).*\1/.test(n=t+c.toString(b*2))&&f(a,n))+T:a
```
[Try it online!](https://tio.run/##VZDNboMwEITveQqXQ2QnrsHGgKnk9CGaG0WI35AqwhGxqrw9XRy1dU6gnZlvdv1Vf9e3dj5f7etkun5ZBo2LljLG6pJaHQREH9r3glNJE6pKNpynDjf6cNQvIWaE7T55yGx/s3jSdt8yaz7sfJ5OuNkJQrbbAdd0ImR/fKuX1YY0ggmaCdIH1JrpZi49u5gTBiNhc3@91G2PQxaeKLqvnqBqqsp0VTUGxb2EmIbwZuMqC8R5jkqKAhOQv1EWuVH3P0qlEMINR8@XUvC6sGflkoKdojx19tGTYhjHGUjyEfJYcRrnQMsjBdAk46lwad8igKsoUk5pnhSQZPxbaYx/Sx5R0IGdZdypo3lCynVdkPPcYcfR42YJZCNYWHAojhP4i1XyOGvs/BYACbBIWD6DL0@AypVaq1dJRu49DZzsCpYf "JavaScript (Node.js) – Try It Online")
# Explanation:
`[c,...a]` - @Arnauld trick for taking one item at a time
`c?***:" "` ->if c is undefined we managed to get to the end result- [] - if i would put "" than the find would not considered that legit. ([]+5="5" JS FTW)
`[1,4,5,8].find` every time we find the correct base (the output will be of this array (1,4,5,8)->(2,8,10,16) its legit.
now how the find works -> if it finds something it returns the element (1-8)
and than i add the result of the inner solution. if it doesnt find then it returns undefined + T is now false -> NaN which in the parent call will be considered false
`!/(.).*\1/.test(n=t+b)` determine if the string has duplicates, if so:
`f(a,n))` just go the the next number(a is now array.slice(1)) with the new string(n)
we assign result to T(temp) of the result because find stops when it finds and so we know that the last result will be f() which is result B
[Answer]
# [Perl 5](https://www.perl.org/) `-alp`, 55 bytes
Uses `%x` for hex, `%d` for decimal, `%o` for octal and `%b` for binary
```
#!/usr/bin/perl -alp
($_)=grep{sprintf($_,@F)!~/(.).*\1/}glob"%{d,o,b,x}"x@F
```
[Try it online!](https://tio.run/##K0gtyjH9/19DJV7TNr0otaC6uKAoM68kDSig4@CmqVinr6GnqacVY6hfm56Tn6SkWp2ik6@TpFNRq1Th4Pb/v6GJgpmJgqXZv/yCksz8vOL/uokFAA "Perl 5 – Try It Online")
[Answer]
# Ruby, ~~72~~ 71 bytes
```
->a{a.map{%w[b o d x]}.inject(&:product).find{|c|/(.).*\1/!~[p,c]*?%%a}}
```
Output format is some kind of reverse S-expression monstrosity:
```
f[[12, 28, 46, 78, 154, 188, 222, 240]]
=> [[[[[[["d", "o"], "o"], "d"], "x"], "x"], "x"], "x"]
```
Slash-separating it instead would cost 3 more bytes (appending `*?/`).
This format comes from the loop structure, slightly shorter than the more idiomatic `repeated_combination(a.size)`, which generates an array of arrays of characters and then reduces it over the cross-product function.
Edit: Saved 1 byte thanks to Lynn.
[Answer]
# Pyth, ~~21~~ 20 bytes
```
f{Is.bjYNTQ^[8T2y8)l
```
Returns a list of all possible lists of bases (which always has length 1).
[Try it here](http://pyth.herokuapp.com/?code=f%7BIs.bjYNTQ%5E%5B8T2y8%29l&input=%5B+3639%2C+19086%2C+57162+%5D&debug=0)
### Explanation
```
f{Is.bjYNTQ^[8T2y8)l
^[8T2y8)lQ Get the tuples of bases of the same length as the input.
f Filter to get those...
.bjYNTQ ... where converting bases elementwise...
s ... and joining together...
{I ... has no repeats.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes
```
Cases[2{1,4,5,8}~Tuples~Tr[1^#],b_/;UnsameQ@@Join@@IntegerDigits[#,b]]&
```
Return a list of bases.
[Try it online!](https://tio.run/##PY5PS8RADMW/StjCniLbzP9BlAG96ElhPZWudGV2Ldgq7Xgq3a9eM1U8DMnLy/tluia9x65J7VuznOAGlrtmjGMlJkKFGt182X9/fcTxsh8qOhQ1Hl931y/92HTxOYTHz7YP4aFP8RyH@/bcprEq8FjX2@VpaPvEAjZwdQsbhFNV1DVsYRdgmoj8jDCRLXMxSgixaoNAdu0UguHnTVaSO2lZqawEWw7BrRHBSsn/RSM9I3zpmKQtmV@sLxGEYMda@iOofIAnfv2I1bxQ8gVBTJaaO@n0muVdwTPFQMuVNAfJuQzMlirnefkB "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 bytes
```
⁴⁽%ʠḃṗL³bF⁼Q$ƲÐf
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//4oG04oG9Jcqg4biD4bmXTMKzYkbigbxRJMayw5Bm////MTYsMTc "Jelly – Try It Online")
Return a list of bases.
```
== Explanation ==
⁴⁽%ʠḃṗL³bF⁼Q$ƲÐf Main link.
⁽%ʠ A number.
ḃ convert it to bijective base...
⁴ 16. The result is [2,8,10,16].
ṗL Cartesian power by the input length.
ƲÐf Filter, keep those that satisfies...
³ the input
b convert to that base
F when flatten (join all the digits of \
different numbers together)
⁼Q$ equal to itself uniquified.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 128 bytes
```
from itertools import*
a=input()
for b in product(*['bdxo']*len(a)):
s=''.join(map(format,a,b))
if len(s)==len(set(s)):print b
```
[Try it online!](https://tio.run/##HYtBCsMgEADvvmJvukF6aAKlAV8SctAmoVuiK7qB9vU27WnmMJM/8uR0bW0rHIFkLcK8V6CYuUinvKOUDzGoNi4QgBLkwsvxENNNOixv1nO3r8l4xFFBdVpfXkzJRJ/NuUQv1tuAqIA2@IUVnftzldNxzIWSQGhtgn6w0N8s3AeYvw "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
2žv8T)sgãʒIsв˜DÙQ
```
[Try it online!](https://tio.run/##AS0A0v8wNWFiMWX//zLFvnY4VClzZ8OjypJJc9Cyy5xEw5lR//9bMzQsIDM3LCA5NF0 "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~121~~ ~~117~~ ~~113~~ 111 bytes
```
def f(a,d='',s=''):
if a:
for c in'bodx':t=format(a[0],c)+s;len(t)-len(set(t))or f(a[1:],d+c,t)
else:print d
```
[Try it online!](https://tio.run/##RZDNboMwEITP5Sn2Bla2EsbGP0R5EuQD5UdFSiAKPjRPT8egqgfsndnZz2Kf7/i9LtW@D@NEU9HxcMtz3nCIJqN5oq7JPqb1RT3NS/61Dj95E28wHl0surYM3IvLdr2PSxHFZ7q2MaIUGAGulU3g4dJzFBmN921snq95iTTsiRnBpLYlaZikpcAoNZPB580hFUplIfUhKzQdk6tOBanVf9YoD44vHXC1leZMwWBE0bJW/lF0egaW94dja0RKvFNJ4FWNSrkaLcI84hVcDarFLWvMSucSNLV0SYECtnT@WWTsCwvYfwE "Python 2 – Try It Online")
Tip of the hat to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) for `format`, which I had forgotten!
[Answer]
# [Husk](https://github.com/barbuz/Husk), 19 bytes
```
fȯS=UΣz`B¹πmDd1458L
```
[Try it online!](https://tio.run/##yygtzv7/P@3E@mDb0HOLqxKcDu0835DrkmJoYmrh8////2hDIx0jCx0TMx1zCx1DUxMdQwsLHSMjoKCJQSwA "Husk – Try It Online")
Returns lists of bases
### Explanation
```
fȯS=UΣz`B¹πmDd1458L Implicit input
L Length of input
π Cartesian power of
d1458 The digits of 1458 [1,4,5,8]
mD Double the digits [2,8,10,16]
fȯ Filter by
z`B¹ Zip with input by converting to its base
Σ Concatenate
S=U Equal to itself with unique elements
```
] |
[Question]
[
In this challenge, you'll get four different but somewhat related tasks that must be solved in a specific manner. First, I'll explain the tasks, then follows an explanation of how you must solve it.
Your code should for all four tasks take two positive integers as input: `n,m`, where `n<m`. All tasks must be solved in the same language. The orientation of matrices are optional (n-by-m may be interpreted as "n rows, m columns", or "n columns, m rows").
### Task 1:
Create (and output/print) a vector / list consisting of the elements: `n, n+1 ... m-1, m`. So, for `n=4, m=9`, you should output: `4,5,6,7,8,9`.
### Task 2:
Create (and output/print) a matrix / array / list of lists (or equivalent) looking like this:
```
n, n+1, ... m-1, m
n+1, n+2, ... m-1, m+1
...
n+m, n+m+1, ... 2*m-1, 2*m
```
For `n=4, m=9` you should output:
```
4, 5, 6, 7, 8, 9
5, 6, 7, 8, 9, 10
...
13, 14, 15, 16, 17, 18
```
### Task 3:
Create (and output/print) an n-by-m multiplication table (on any suitable format). Example for `n=4, m=9`:
```
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
5 10 15 20
6 12 18 24
7 14 21 28
8 16 24 32
9 18 27 36
```
### Task 4:
Output / print a vector / list consisting of the elements in the multiplication table from task 3, sorted in ascending order, keeping duplicate values. For `n=4, m=9`, you should output: `1, 2, 2, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 12, 12, 12, 14, 15, 16, 16, 18, 18, 20, 21, 24, 24, 27, 28, 32, 36`.
# The challenge:
Now, all the tasks above are quite trivial. The real challenge here is that the code for task 2 must start with the code for task 1, the code for task 3 must start with the code for task 2 and the code for task 4 must start with the code for task 3.
**To make it more clear:**
Suppose the [code for **Task 1**](https://tio.run/nexus/octave#@@@gkaeTq6mRZ5Wraf0/Ma9Yw0THUvM/AA) is (works in Octave):
```
@(n,m)(n:m)
```
Then your [code for **Task 2**](https://tio.run/nexus/octave#@@@gkaeTq6mRZ5Wrqa1hACTVrf8n5hVrmOhYav4HAA) could be (works in Octave):
```
@(n,m)(n:m)+(0:m)'
```
The code for task **Task 3** must be (doesn't work in Octave):
```
@(n,m)(n:m)+(0:m)'"Code_for_task_3"
```
And finally, the code for **Task 4** must be (doesn't work in Octave):
```
@(n,m)(n:m)+(0:m)'"Code_for_task_3""Code_for_task_4"
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the shortest code for task 4 in each language wins. As always: Explanations are highly encouraged.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
### Task 1
```
r
```
[Try it online!](https://tio.run/nexus/jelly#@1@kfXifQZFK7f/Dy90VHu7Y/qhhjoJzYk6OQmJeikJBUWpJSSWQyswr0fv/3@S/JQA "Jelly – TIO Nexus")
### Task 2
```
r+þ0r$}
```
[Try it online!](https://tio.run/nexus/jelly#@1@kfXifQZFK7f/Dy90VHu7Y/qhhjoJzYk6OQmJeikJBUWpJSSWQyswr0fv/3@S/JQA "Jelly – TIO Nexus")
### Task 3
```
r+þ0r$}
×þ
```
[Try it online!](https://tio.run/nexus/jelly#@1@kfXifQZFKLdfh6Yf3/T@83F3h4Y7tjxrmKDgn5uQoJOalKBQUpZaUVAKpzLwSvf//Tf5bAgA "Jelly – TIO Nexus")
### Task 4
```
r+þ0r$}
×þFṢ
```
[Try it online!](https://tio.run/nexus/jelly#@1@kfXifQZFKLdfh6Yf3uT3cuej/4eXuCg93bH/UMEfBOTEnRyExL0WhoCi1pKQSSGXmlej9/2/y3xIA "Jelly – TIO Nexus")
## How it works
### Task 1
`r` is the *dyadic range* atom and does exactly what the task asks for.
### Task 2
A dyadic chain that begins with three dyadic links is a *fork*; the outmost links get evaluated first, then the middle link is called with the results to both sides as arguments.
* `r` behaves as before, yielding **[n, …, m]**.
* `0r$}` is a quicklink (or quickquicklink, if you will).
The quick `$` (monadich chain) consumes the links `0` (yield **0**) and `r` (dyadic range) and turns them into a monadic chain. When called with argument **k**, this will yield **[0, …, k]**.
The quick `}` (right argument) takes the quicklink created by `$` and turns it into a *dyadic* link that calls `0r$` with `0r$}`'s right argument.
`0r$}` will be called with left argument **n** and right argument **m**, so `0r$` is alled with argument **m** and yields **[0, …, m]**.
* `+þ` is another quicklink. `þ` (table) will call `+` (addition) for every element in its left argument and any element in its right argument, grouping the results for each right argument into a single row.
`+þ` will be called with left argument **[n, …, m]** and right argument **[0, …, m]**, yielding the desired table.
### Task 3
Every line in a Jelly program defines a different link. The last one is the *main link* and, like C's `main` function, is the only link that is executed by default. The remaining links can be called from the main link, but we won't do this here.
As before, `þ` (table) will call `×` (addition) for every element in its left argument and any element in its right argument, grouping the results for each right argument into a single row.
Since both arguments to `×þ` are integers, `þ` casts them to ranges, transforming the arguments **n** and **m** into **[1, …, n]** and **[1, …, m]**.
### Task 4
`×þ` works as before. The following links are monadic, making them *atops*, i.e., they are applied on top of the previous ones.
After executing `×þ`, `F` flattens the resulting 2D array, and `Ṣ` sorts the resulting 1D array.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes
**Task 1**
```
Ÿ
```
[Try it online](https://tio.run/nexus/05ab1e#@390x///JlyWAA)
**Task 2**
```
Ÿ²FD>})
```
[Try it online](https://tio.run/nexus/05ab1e#@390x6FNbi52tZr//5twWQIA)
**Task 3**
```
Ÿ²FD>})v¹LN*})¦
```
[Try it online](https://tio.run/nexus/05ab1e#@390x6FNbi52tZplh3b6@GnVah5a9v@/CZclAA)
**Task 4**
```
Ÿ²FD>})v¹LN*})¦˜{
```
[Try it online](https://tio.run/nexus/05ab1e#@390x6FNbi52tZplh3b6@GnVah5adnpO9f//JlyWAA)
## Explanations
**Task 1**
```
Ÿ # range[n ... m]
```
**Task 2**
```
Ÿ # range[n ... m]
²F # m times do:
D # duplicate
> # increment
} # end loop
) # wrap in list
```
**Task 3**
```
v # for each list in result of Task 2 do
¹L # push range[1 ... n]
N* # multiply by index
} # end loop
) # wrap in list
¦ # discard first element
```
**Task 4**
```
˜ # flatten the result from Task 3
{ # sort
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~18~~ 17 bytes
### Task 1
```
&:
```
[Try it online!](https://tio.run/nexus/matl#@69m9f@/CZclAA)
### Task 2
```
&:O2G:h!+
```
[Try it online!](https://tio.run/nexus/matl#@69m5W/kbpWhqP3/vwmXJQA)
### Task 3
```
&:O2G:h!+:7M!*
```
[Try it online!](https://tio.run/nexus/matl#@69m5W/kbpWhqG1l7quo9f@/CZclAA)
### Task 4
```
&:O2G:h!+:7M!*1eS
```
[Try it online!](https://tio.run/nexus/matl#@69m5W/kbpWhqG1l7quoZZga/P@/CZclAA)
## Explanation
### Task 1
```
&: % Binary range [n n+1 ... m] from implicit inputs n, m
```
### Task 2
```
% ... Stack contains [n n+1 ... m]
O % Push 0
2G % Push second input, m
: % Unary range: gives [1 2 ... m]
h % Concatenate horizontally: gives [0 1 2 ... m]
! % Transpose into a column vector
+ % Add with broadcast
```
### Task 3
```
% ... Stack contains matrix from task 2
: % Unary range. For matrix input it uses its (1,1) entry. So this gives [1 2 ... n]
7M % Push [1 2 ... m] again
! % Transpose into a column vector
* % Multiply with broadcast
```
### Task 4
```
% ... Stack contains matrix from task 3
1e % Linearize into a row vector
S % Sort
```
[Answer]
## Mathematica, 84 77 bytes
*Edit: Thanks to Martin Ender for saving 7 bytes.*
**Task 1:**
```
{n,m}n~Range~m
```
Pure `Function` with arguments `n` and `m` which outputs `n~Range~m`, the infix form of `Range[n,m]`.
**Task 2:**
```
{n,m}n~Range~m~Table~(m+1)//0~Range~m+#&
```
`n~Range~m~Table~(m+1)` creates a 2D array with `m+1` rows, where each row is the output of the previous task. Then `//0~Range~m+#&` is postfix application of the function `0~Range~m+#&` which effectively adds `0` to the first row, `1` to the second row, and so on up to `m` for the `m+1`-th row.
**Task 3:**
```
{n,m}n~Range~m~Table~(m+1)//0~Range~m+#&//1##&~Array~{n,m}&
```
This just applies the constant function `1##&~Array~{n,m}&` to the output of the previous task.
**Task 4:**
```
{n,m}n~Range~m~Table~(m+1)//0~Range~m+#&//1##&~Array~{n,m}&//Flatten//Sort
```
`Flatten`s and `Sort`s the multiplication table.
[Answer]
# Python, 183 bytes
**Task 1, 29 bytes**
```
r=range
a=lambda n,m:r(n,m+1)
```
[Try it online!](https://tio.run/nexus/python2#@19kW5SYl57KlWibk5iblJKokKeTa1WkASS1DTX/FxRl5pUopGmkaJjoWGpq/gcA "Python 2 – TIO Nexus")
**Task 2, 84 bytes**
```
r=range
a=lambda n,m:r(n,m+1)
s=lambda n,m:[[w+i for w in r(n,m)] for i in a(0,m+1)]
```
[Try it online!](https://tio.run/nexus/python2#@19kW5SYl57KlWibk5iblJKokKeTa1WkASS1DTW5ipFFo6PLtTMV0vKLFMoVMvMUwIo0Y8ECmSCBRA0DsK7Y/wVFmXklCmkaKRomOpaamv8B "Python 2 – TIO Nexus")
**Task 3, 137 bytes**
```
r=range
a=lambda n,m:r(n,m+1)
s=lambda n,m:[[w+i for w in r(n,m)] for i in a(0,m+1)]
d=lambda n,m:[[w*i for w in a(1,n)] for i in a(1,m)]
```
[Try it online!](https://tio.run/nexus/python2#@19kW5SYl57KlWibk5iblJKokKeTa1WkASS1DTW5ipFFo6PLtTMV0vKLFMoVMvMUwIo0Y8ECmSCBRA0DsK5YrhQ0bVpI2hI1DHXyULUZgsz5X1CUmVeikKaRomGiY6mp@R8A "Python 2 – TIO Nexus")
**Task 4, ~~183~~167 bytes**
```
r=range
a=lambda n,m:r(n,m+1)
s=lambda n,m:[[w+i for w in r(n,m)] for i in a(0,m+1)]
d=lambda n,m:[[w*i for w in a(1,n)] for i in a(1,m)]
f=lambda(z):sorted(sum(z,[]))
```
[Try it online!](https://tio.run/nexus/python2#Xcw7CsMwDIDh3afQKDUeaujSQE5iPKg4LobaKXJKIJfPw2RIugj0o0@LdML53SvuPpxeniHr1ApuszGkyrlaOzURwiAwQcxQj8jVEPfAeK/KKf/HbifGaHS@MrP/UeFAOFNbBhl7j@WXcNbWES1fiXmEgB4f@rntKw "Python 2 – TIO Nexus")
## Explanation:
**Task 1:**
Simple enough, it generates a `n` to `m` list using Python's built-in `range` function.
**Task 2:**
For every number `0` to `m+1`, it adds that number to each item of a list from `n` to `m`.
**Task 3:**
For each number from `1` to `m`, it multiplies that number by every number in a list from `1` to `n`.
**Task 4:**
This uses Python's built in `sorted` function which sorts a list from least to greatest. The list comprehension in the function is used to flatten the list. It creates a list of every item in every item of the list given to it by task 3.
* Saved very many bytes thanks to @math\_junkie.
* Saved 16 bytes thanks to @ThisGuy
Saved very many bytes thanks to @math\_junkie.
[Answer]
# PHP 7, 200 bytes
Uses the output buffer to clear previous output.
### Task 1
```
[,$n,$m]=$argv;ob_start();eval($s='echo join(" ",$v?:range($n+$i,$m+$i)),"
";');
```
Saves the code in `$s` to reuse it later. The `$v` variable is for the last task.
### Task 2
```
[,$n,$m]=$argv;ob_start();eval($s='echo join(" ",$v?:range($n+$i,$m+$i)),"
";');for(;++$i<=$m;)eval($s);
```
Prints the remaining lines.
### Task 3
```
[,$n,$m]=$argv;ob_start();eval($s='echo join(" ",$v?:range($n+$i,$m+$i)),"
";');for(;++$i<=$m;)eval($s);for(($c=ob_clean)();++$j<=$m;print"
")for(;++$$j<=$n;sort($v))echo$v[]=$j*$$j,' ';
```
Clears the output buffer and prints the multiplication table, saving the numbers to `$v`.
### Task 4
```
[,$n,$m]=$argv;ob_start();eval($s='echo join(" ",$v?:range($n+$i,$m+$i)),"
";');for(;++$i<=$m;)eval($s);for(($c=ob_clean)();++$j<=$m;print"
")for(;++$$j<=$n;sort($v))echo$v[]=$j*$$j,' ';$c();eval($s);
```
Clears the output buffer again and prints `$v`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 126 bytes
### Task 1
```
param($n,$m)$n..$m
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp6OSq6mSp6enkvv//3@T/5YA "PowerShell – TIO Nexus")
Uses the `..` built-in range operator. The default behavior for the implied `Write-Output` inserts a newline between elements, so that's why the output shows as newline separated.
---
### Task 2
```
param($n,$m)$n..$m>2;0..$m|%{$i=$_;($n..$m|%{$_+$i})-join','}
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp6OSq6mSp6enkmtnZG0AomtUq1UybVXirTUg4iB@vLZKZq2mblZ@Zp66jnrt////Tf5bAgA "PowerShell – TIO Nexus")
Dumps the first task to STDERR with `>2;`, then loops from `0` to `$m`, each iteration setting helper `$i` before looping again from `$n` to `$m` and incrementing each number by `$i`. Those are `-join`ed together with commas, else this would be an ambiguous gigantic long one-element-per-line output.
---
### Task 3
```
param($n,$m)$n..$m>2;0..$m|%{$i=$_;($n..$m|%{$_+$i})-join','}>2;(1..$m|%{$i=$_;(1..$n|%{$_*$i})-join' '})
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp6OSq6mSp6enkmtnZG0AomtUq1UybVXirTUg4iB@vLZKZq2mblZ@Zp66jnotUKmGIapaEDcPrFQLoVRBvVbz////Jv8tAQ "PowerShell – TIO Nexus")
Same sort of thing `>2;` to dump the previous to STDERR. Then we simply double-loop from `1` to `$m` then `1` to `$n`, setting helper `$i` along the way, multiply the values, and `-join` with a space to make it tabular. Note the encapsulating parens -- they'll come into play on the next task -- but here they just ensure that the output is put onto the pipeline (which it already would be, so they're redundant).
---
### Task 4
```
param($n,$m)$n..$m>2;0..$m|%{$i=$_;($n..$m|%{$_+$i})-join','}>2;(1..$m|%{$i=$_;(1..$n|%{$_*$i})-join' '})-split' '|%{+$_}|sort
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp6OSq6mSp6enkmtnZG0AomtUq1UybVXirTUg4iB@vLZKZq2mblZ@Zp66jnotUKmGIapaEDcPrFQLoVRBHcgqLsjJLAEygZLaKvG1NcX5RSX///83@W8JAA "PowerShell – TIO Nexus")
Aha! Finally some redundancy. Since the previous task has parens, we can tack on the `-split` on whitespace without worry, cast each one to an integer `|%{+$_}`, and then `|sort`. The output is again newline separated.
---
I *think* there are some ways to better leverage the redundancy between tasks -- still golfing it some.
[Answer]
# ES2016-ish, 401 384 chars
Here's a first try. I'm sure it could be condensed a bit, but it's pretty short. Arrow functions FTW! (Love those implicit return statements.) New and improved with template strings!
### Task 1
```
var a=Array,l=console.log,f=(n,m)=>a.from(a(1+m-n),(w,i)=>n+i),z=(n,m)=>l(f(n,m).join`, `)
```
Call `z(n,m)` for the log output. (I'm aliasing console.log for later golfing.)
### Task 2
Second verse... expands on the first.
```
var a=Array,l=console.log,f=(n,m)=>a.from(a(1+m-n),(w,i)=>n+i),z=(n,m)=>l(f(n,m).join`, `),p,o,g=(n,m)=>{p=n,o=m;return [...a(m+1).keys()].map((d)=>f(d+p,d+o))},y=(n,m)=>l(g(n,m).join`\n`
```
Now call `y(n,m)`. Pretty, no?
### Task 3
Have to bypass most of the existing functionality `<sadface />`.
```
var a=Array,l=console.log,f=(n,m)=>a.from(a(1+m-n),(w,i)=>n+i),z=(n,m)=>l(f(n,m).join`, `),p,o,g=(n,m)=>{p=n,o=m;return [...a(m+1).keys()].map((d)=>f(d+p,d+o))},y=(n,m)=>l(g(n,m).join`\n`,h=(n,m)=>[...a(m).keys()].map((d)=>(d+1)*n).join`\t`,i=(n,m)=>[...a(n).keys()].map((d)=>h((d+1),m)),v=(n,m)=>i(n,m).join`\n`
```
Now the method name is `v`. Call it the same way.
### Task 4
And now we can reuse again.
```
var a=Array,l=console.log,f=(n,m)=>a.from(a(1+m-n),(w,i)=>n+i),z=(n,m)=>l(f(n,m).join`, `),p,o,g=(n,m)=>{p=n,o=m;return [...a(m+1).keys()].map((d)=>f(d+p,d+o))},y=(n,m)=>l(g(n,m).join`\n`,h=(n,m)=>[...a(m).keys()].map((d)=>(d+1)*n).join`\t`,i=(n,m)=>[...a(n).keys()].map((d)=>h((d+1),m)),v=(n,m)=>i(n,m).join`\n`,t=(n,m)=>l(v(n,m).match(/\d+/g).sort((a,b)=>+a>+b||+(a===b)*2-1).join(`, `)
```
Had to skip `u` for my method, so it's `t`. Bummed that I had to put in that sort function, because the `String.match` returns values as... strings.
[Answer]
# Ruby, ~~121~~ 103 bytes
Everything in Ruby is truthy except for `nil` and `false`, which means that the tasks can be set up to ignore previous input with naught but a well-placed `and`/`&&`.
**Task 1**
[Try it online!](https://tio.run/nexus/ruby#@5@nk2uroqWXm1igoGZVkh@fyVWgEK2Vp6eXG/v//3/j/@YA "Ruby – TIO Nexus")
```
n,m=$*.map &:to_i
p [*n..m]
```
**Task 2**
[Try it online!](https://tio.run/nexus/ruby#@5@nk2uroqWXm1igoGZVkh@fyVWgEK2Vp6eXG6umpmEApDVBktU1mTVAYe1MoIB2Zmzt////jf@bAwA "Ruby – TIO Nexus")
```
n,m=$*.map &:to_i
p [*n..m]&&(0..m).map{|i|[*n+i..m+i]}
```
**Task 3**
[Try it online!](https://tio.run/nexus/ruby#@5@nk2uroqWXm1igoGZVkh@fyVWgEK2Vp6eXG6umpmEApDVBktU1mTVAYe1MoIB2ZmwtUM4QWQ7Ey4PysmoytbJqa////2/83xwA "Ruby – TIO Nexus")
```
n,m=$*.map &:to_i
p [*n..m]&&(0..m).map{|i|[*n+i..m+i]}&&(1..m).map{|i|(1..n).map{|j|i*j}}
```
**Task 4**
[Try it online!](https://tio.run/nexus/ruby#@5@nk2uroqWXm1igoGZVkh@fyVWgEK2Vp6eXG6umpmEApDVBktU1mTVAYe1MoIB2ZmwtUM4QWQ7Ey4PysmoytbJqa/XSchJLSlLz9Irzi0r@//9v/N8cAA "Ruby – TIO Nexus")
```
n,m=$*.map &:to_i
p [*n..m]&&(0..m).map{|i|[*n+i..m+i]}&&(1..m).map{|i|(1..n).map{|j|i*j}}.flatten.sort
```
] |
[Question]
[
## Introduction
The [Sierpinski Arrowhead Curve](https://en.wikipedia.org/wiki/Sierpi%C5%84ski_arrowhead_curve) is a curve that's limit is Sierpinski's Triangle.
It first starts like this:
```
_
/ \
```
Then, each line is replaced with a rotated version of the first one:
```
_
/ \
\ /
_/ \_
```
Next:
```
_
/ \
\ /
_/ \_
/ \
\_ _/
_ \ / _
/ \_/ \_/ \
```
[](https://i.stack.imgur.com/9zbLN.png)
## Your task
Given a number *n*, output the *n*-th iteration of the Sierpinski Arrowhead Curve.
You may choose 0 or 1-indexed input, but please specify that in your answer.
You may generate an image, or use Ascii Art in the format I have given above.
You may not use built-ins to generate this curve.
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins.
[Answer]
# Octave, ~~240 236~~ 221 bytes
This is made with the same idea [used here](http://blogs.mathworks.com/steve/2012/01/25/generating-hilbert-curves/) but I had to change it to fit the sierpinsky arrowhead curve.
```
m=input(0);g=2*pi/6;u=cos(g);v=sin(g);A=[1,0];B=[u,v];C=[-u,v];D=-A;E=-B;F=-C;for k=1:m;f=[E;F;A];b=[A;B;C];A=[B;A;F];d=[C;D;E];C=[D;C;B];E=[F;E;D];B=b;D=d;F=f;end;A=[0,0;cumsum(A)];plot(A(:,1),A(:,2));axis off;axis equal
```
[](https://i.stack.imgur.com/irz7a.jpg)
[Answer]
# Haskell + diagrams, 176 bytes
```
import Diagrams.Prelude
import Diagrams.Backend.SVG
g n=renderSVG"a"(mkWidth 99).strokeT.a n
a 0=hrule 1
a n|b<-a(n-1)=b%6<>b<>b%(-6);a%n=rotateBy(1/n).reflectY$a::Trail V2 Double
```
Makes a svg file with transparent background called "a".
`g 0` outputs a horizontal line, `g 1` is `/¯\`.
[](https://i.stack.imgur.com/fbrjy.png)
[Answer]
# MSWLogo (Version 6.5b), 102 bytes
Takes the two functions `shapeL`, `shapeR` given [here](http://infohost.nmt.edu/~blewis/html/sierpinskiarrowhead-student.html) and merges them by adding an extra argument `:a`, which calls the opposite function when negated.
```
to s :n :a :l
if :n=0[fd :l stop]
rt :a
s :n-1(-:a):l
lt :a
s :n-1 :a :l
lt :a
s :n-1(-:a):l
rt :a
end
```
A function `s` is defined, which takes number of iterations `:n` (1-based), angle `:a`, length `:l`. It is recursive, calling a lower iteration of itself with the angle `:a` negated in two instances to get the orientation correct.
* `rt :a`, `lt :a` rotate the turtle (triangle thingy whose path is traced) right, left by `:a` degrees.
* `fd :l` moves the turtle forward by `:l` steps.
The function is to be called with `:a` equal to 60.
[](https://i.stack.imgur.com/k6LFy.png)
Here, `repeat` is essentially a FOR loop, with built-in counter `repcount`. `pu` and `pd` mean "pen up" and "pen down", which stop the turtle from drawing while its position is being set using `setxy`.
The drawings of each iteration have been called with length `:l` equal to `power 2 (7-repcount)`, which decreases exponentially; this is because the definition uses the same `:l` in the recursive step, so with fixed `:l` the overall size of the output will increase exponentially with `:n`.
[Answer]
# Python 2, 124 bytes
Based off of the code in the Wikipedia article.
```
from turtle import*
def c(o,a):
if o:o-=1;c(o,-a);lt(a);c(o,a);lt(a);c(o,-a)
else:fd(9)
n=input()
if n%2==0:lt(60)
c(n,60)
```
Order 0 is a straight line.
[Answer]
# Mathematica / Wolfram Language 73 bytes
```
s=1;Region@Line@AnglePath[Nest[Join@@({#,s=-s,s}&/@#)&,{#~Mod~2},#]Pi/3]&
```
Simple explanation:
[AnglePath](https://reference.wolfram.com/language/ref/AnglePath.html)[{θ1,θ2,θ3,…}] gives the list of 2D coordinates corresponding to a path that starts at {0,0}, then takes a series of steps of unit length at successive relative angles θi.
n=1
```
Graphics@Line@AnglePath[60°{1,-1,-1}]
```
n=2
```
Graphics@Line@AnglePath[60°{0,1,1, -1,-1,-1, -1,1,1}]
```
n=3
```
Graphics@Line@AnglePath[60°{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}]
```
[](https://i.stack.imgur.com/31oBd.png)
[](https://i.stack.imgur.com/pv0WX.gif)
[Answer]
# Mathematica, 62 bytes
```
Graphics@Line@AnglePath[Pi/3Nest[Flatten@{-#,1,#,1,-#}&,0,#]]&
```
[Answer]
## JavaScript (ES6), 180 bytes
```
f=(n,d=0,r=n=>` `.repeat(n))=>n?f(--n,d=3-d%3).map(s=>r([l=s.length/2,0,1,~n&1][d]+l)+s+r([,1,0,~n&1][d]+l)).concat(f(n,d+1).map(s=>s+r(!(d%3))+a.shift(),a=f(n,d+2))):[`_/\\`[d%3]]
```
```
<input type=number min=1 oninput=o.textContent=f(this.value).join`\n`><pre id=o>
```
Returns an array of strings. Getting the spacing right was the hardest part! Pure string version for 205 bytes:
```
f=(n,d=0,r=n=>` `.repeat(n))=>n?f(--n,d=3-d%3).replace(/.+/g,s=>r([l=s.length/2,0,1,~n&1][d]+l)+s+r([,1,0,~n&1][d]+l))+`\n`+f(n,d+1).replace(/.+/g,s=>s+r(!(d%3))+a.shift(),a=f(n,d+2).split`\n`):`_/\\`[d%3]
```
] |
[Question]
[
Mayan pyramids were (and are) an important part of ancient architecture, that were generally used for religious purposes.
They were usually step pyramids, but the steps on each were too steep to climb. Priests would climb to the tops of them via alternative staircases to perform ceremonies. The pyramids were also used as landmarks because of their height, and sometimes even used as burial sites for high ranking officials.
---
# The Challenge
Write a program that can print out a pyramid schematic based on user specifications (see below).
---
# Requirements
* Take an input of two space-separated variables.
* Input must be accepted through STDIN (or closest alternative).
* Output must be through STDOUT (or closest alternative).
---
# Input
* Height as any positive integer. This is used as the base level's width (in blocks). Each succeeding level of the pyramid has the width `n - 1` where `n` is the previous floor's width (in blocks).
* Block size which will be 1 or any odd, positive integer ≤ (less than) 10.
---
# Blocks
The given block size determines the width (and height) of each individual piece. Essentially, there are `i^2` spaces inside the visible box where `i` is the block size.
A 1x1 block would look like this:
```
+++
| |
+++
```
While a 5x5 block would look like this:
```
+++++++
| |
| |
| |
| |
| |
+++++++
```
---
# Horizontally Adjacent Blocks
Horizontally side-by-side blocks *must* have their middle walls merged into one.
You *must* have this:
```
+++++
| | |
+++++
```
Instead of something like this:
```
++++++
| || |
++++++
```
---
# Vertically Adjacent Blocks (-5% bonus)
Vertically side-by-side blocks have a special exception: the middle wall can be merged into one.
So, instead of 1x1 blocks looking like this:
```
+++
| |
+++
+++++
| | |
+++++
```
They *could* look like this:
```
+++
| |
+++++
| | |
+++++
```
---
# Examples
```
Input: 3 1
Output:
+++
| |
+++
+++++
| | |
+++++
+++++++
| | | |
+++++++
OR
+++
| |
+++++
| | |
+++++++
| | | |
+++++++
Input: 2 3
Output:
+++++
| |
| |
| |
+++++
+++++++++
| | |
| | |
| | |
+++++++++
OR
+++++
| |
| |
| |
+++++++++
| | |
| | |
| | |
+++++++++
```
---
# Scoreboard
To be ranked on the scoreboard, put your answer in this format:
```
# Language, Score
```
Or if you get the bonus -5%:
```
# Language, Score (Bytes - 5%)
```
```
function getURL(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 getAnswers(){$.ajax({url:getURL(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){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+"").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=57939,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```
```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 30px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```
```
<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="scores-cont"><h2>Scores</h2> <table class="score-table"> <thead><tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead><tbody id="scores"></tbody> </table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```
[Answer]
# JavaScript (ES6), 161 (169-5%) ~~166 (174-5%)~~
Using template strings, the 2 newlines are significant and counted.
Test running the snippet below in an EcmaScript 6 browser. Firefox ok, not Chrome because it lacks support for [destructuring assignment](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
Code explained after the snippet.
```
/*Test: redefine console.log*/ console.log=x=>O.innerHTML+=x+'\n';
for([h,b]=prompt().split` `,g='+'[R='repeat'](-~b),f=' '[R](b),n=o='';h--;o+=e+(d=g[R](++n)+`+
`)+f.replace(/./g,e+('|'+f)[R](n)+`|
`))e=' '[R](h*-~b/2);console.log(o+d)
```
```
<pre id=O></pre>
```
**Less Golfed**
```
[h, b] = prompt().split` `; // get the space separated input values
c = -~b; // Add 1 to b. As b is of string type b+1 would be a string concatenation
g = '+'.repeat(c); // top border
f = ' '.repeat(b); // inner blank row
o = ''; // initialize output string
for(n = 0; h > 0; --h) // loop on height
{
++n;
e = ' '.repeat(h*c/2); // blanks for offset from left margins
d = g.repeat(n) + `+\n`; // top border repeated, then right end and newline
// the block body is squared, there are as many rows as columns inside
// so I can build the right number of rows replacing the chars in a single row
o += e + d + f.replace(/./g, e + ('|'+f).repeat(n)+`|\n`)
}
o += d // add last top border as bottom
console.log(o)
```
[Answer]
# Ruby, 124 (130 - 5%)
```
n=(g=gets).to_i
b=g[-2].to_i+1
a=(0..n*b-1).map{|i|[?+*(i/b*b+b+1),(?|+' '*(b-1))*(i/b+1)+?|][i%b<=>0].center(n*b+1)}
puts a,a[-b]
```
With comments
```
n=(g=gets).to_i #get input and interpret as a number for pyramid height (everything after the space is ignored)
b=g[-2].to_i+1 #the single-character block size is the second last character (just before the newline.) Add 1 to give the pitch between squares.
a=(0..n*b-1).map{|i| #run through all lines except the last one
[?+*(i/b*b+b+1), #calculate number of + symbols
(?|+' '*(b-1))*(i/b+1)+?|] #or alternatively, pattern '| |'
[i%b<=>0] #check if i%b is zero or positive to decide which to print
.center(n*b+1)} #centre the text. It will be mapped to the array a.
puts a,a[-b] #a contains the pyramid, minus its last line. Print it, and add the last line
```
[Answer]
## Python 2, 117 (123 bytes)
```
h,n=map(int,raw_input().split())
p,v='+|'
while h:p+='+'*-~n;v+=' '*n+'|';h-=1;l=~n/-2*h*' ';print l+p+('\n'+l+v)*n
print p
```
The idea is to build up the bricks' top `p` as `+++++++++` and side `v` as `| | |`. The top starts as `+` and is augmented by `n+1` `+`'s each layer. The side starts as `|` and is augmented by `n` spaces and a `|`. Each layer, we augment the tops and sides, then print one top and `n` sides.
To center them, we first print an indent `l`. It consists of a number of spaces that scales with the current height `h`. To update it, we decrementing the height variable `h` until it hits `0`, after which the current layer is flush against the left edge of the screen. We print the top once more to make the bottom layer, and we're done.
[Answer]
# Pyth, 45 (47 bytes - 5%)
```
AmvdczdVGjm.[Jh*GhHj*H?d\ \+*+2N?d\|\+\ hH;*J\+
```
Try it out [here](https://pyth.herokuapp.com/?code=AmvdczdVGjm.%5BJh%2AGhHj%2AH%3Fd%5C%20%5C%2B%2A%2B2N%3Fd%5C%7C%5C%2B%5C%20hH%3B%2AJ%5C%2B&input=2%205&debug=0).
```
Implicit: z=input(), d=' '
czd Split input on spaces
mvd Evaluate each part of the above (convert to int)
A Store the pair in G,H
Jh*GhH J = 1+(G*(H+1))
VG For N in [0 to G-1]:
m hH; Map d in [0 to H] to:
?d\|\+ Get '|' or '+' (vertical edges or corners)
*+2N Repeat the above (N+2) times
?d\ \+ Get ' ' or '+' (block centre or horizontal edge)
*H Repeat the above H times
j Join (|/+) by ( /+++)
.[J \ Centrally pad the above to width J using spaces
j Join on newlines, implicit print
*J\+ Get J '+'s, implicit print
```
[Answer]
# Python 2, 200 (210 - 5%)
```
a,b=map(int,raw_input().split());c=0;a+=1;i=a*b+a-b;e=[i*'+']
while a-1:
v=(('|'+' '*b)*a).rstrip();p=' '*((i-len(v))/2);a-=1;c+=1
for u in range(b):e.insert(0,p+v)
e.insert(0,p+'+'*len(v))
print'\n'.join(e)
```
I used string multiplication and stripped extra spaces.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `o`, 44 bytes (46 - 5%)
```
(n£¹n-‹⁰½⌈*ð*:\+⁰›n›*›*+:→x,⁰(:₴\|:⁰꘍¥›*p,))←x
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=o&code=%28n%C2%A3%C2%B9n-%E2%80%B9%E2%81%B0%C2%BD%E2%8C%88*%C3%B0*%3A%5C%2B%E2%81%B0%E2%80%BAn%E2%80%BA*%E2%80%BA*%2B%3A%E2%86%92x%2C%E2%81%B0%28%3A%E2%82%B4%5C%7C%3A%E2%81%B0%EA%98%8D%C2%A5%E2%80%BA*p%2C%29%29%E2%86%90x&inputs=3%0A1&header=&footer=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ 26 bytes
Takes the height and then block size on seperate lines. [30 bytes](https://tio.run/##ATUAyv9vc2FiaWX//yNSYFVMzrUnfFjDulJ5WD4qPsKp4oiNWNC4wq4nK8OXLsO4fcucLmP//zMgMg) if the input format is strict.
```
Lε'|²úRy²>*>©∍²и®'+×.ø}˜.c
```
[Try it online!](https://tio.run/##ATQAy/9vc2FiaWX//0zOtSd8wrLDulJ5wrI@Kj7CqeKIjcKy0LjCricrw5cuw7h9y5wuY///Mwox "05AB1E – Try It Online")
```
L # push range [1 .. h]
ε } # for y in [1 .. h]:
'| '# push "|"
²úR # pad with w spaces in the back
²>*> # line length: (w+1)*y+1
© # store the line length in the register
∍ # extend the string to this length
²и # push a list with w copies of the string
®'+× '# push a string of "+"*line length
.ø # surround the list with this string
˜ # flatten into a list of strings
.c # centralize
```
] |
[Question]
[
# It's time... to count the votes!
Today there are local elections in my entire country. Here, the number of seats for each party is decided using the [D'Hondt method](http://en.wikipedia.org/wiki/D%27Hondt_method). Your goal is to implement a program or function that will decide how many seats each party gets, in the shortest amount of bytes.
For this method there are a fixed number of seats to distribute, and it's done like so:
1. Every party is assigned a variable number, which starts at the number of votes it got.
2. Then the first seat is given to the party who has the biggest value in their variable and then that value for that party becomes their total number of votes divided by `1+seats`, rounded down, where `seats` is the number of seats it already has (so after getting the first, their votes are divided by 2, and by 3 after getting the second seat).
3. After that the parties votes are compared again. The process continues until all the seats have been assigned.
If the highest number is a tie between two or more parties, it is resolved randomly (It has to be random, it can't just be the first of the two in the list).
## Input
You will receive a number `N`, which will indicate the number of seats available, and a list of the votes each party received, in whatever format you prefer. Example:
```
25
12984,7716,13009,4045,1741,1013
```
## Output
You should output a list of the seats each party got. In the example above it would be something like
```
8,5,9,2,1,0
```
They should be in the same order as the parties in the input.
## Examples
```
5
3,6,1
outputs: 2,3,0
```
---
```
135
1116259,498124,524707,471681,359705,275007,126435
outputs: 45,20,21,19,14,11,5
```
## Bonus
**-20% bonus** if take the parties name as input and give them in the output, like for example:
```
25
cio:12984,pcc:7716,irc:13009,icb:4045,cub:1741,bb:1013
outputs
cio:8
pcc:5
irc:9
icb:2
cub:1
bb:0
```
[Answer]
# CJam, ~~35.2~~ ~~28.8~~ ~~28.0~~ 26.4
```
q2*~,m*mr{~)f/1=~}$<:(f{1$e=1\tp}
```
This full program is 33 bytes long and qualifies for the bonus.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q2*~%2Cm*mr%7B~)f%2F1%3D~%7D%24%3C%3A(f%7B1%24e%3D1%5Ctp%7D&input=%5B%5B%22cio%22%2012984%5D%20%5B%22pcc%22%207716%5D%20%5B%22irc%22%2013009%5D%20%5B%22icb%22%204045%5D%20%5B%22cub%22%201741%5D%20%5B%22bb%22%201013%5D%5D%0A25).
### Example run
```
$ cjam seats <<< '[["cio"12984]["pcc"7716]["irc"13009]["icb"4045]["cub"1741]["bb"1013]]25'
["cio" 8]
["pcc" 5]
["irc" 9]
["icb" 2]
["cub" 1]
["bb" 0]
```
### How it works
```
q2*~ e# Repeat the input from STDIN twice. Evaluate.
e# STACK: Array seats Array seats
, e# Range: seats -> [0 ... seats-1]
m* e# Take the cartesian product of the array from the input and the range.
mr e# Shuffle the array. This makes sure tie breakers are randomized.
{ e# Sort by the following key:
~ e# Dump: [["party" votes] number] -> ["party" votes] number
f/ e# Divide each: ["party" votes] number -> ["party"/number votes/number]
1= e# Select: ["party"/number votes/number] -> votes/number
~ e# Bitwise NOT.
}$ e#
< e# Keep only the elements that correspond to seats.
:( e# Shift each array.
e# RESULT: S := [[number] ["party" votes] [number] ["party" votes] ...]
f{ e# For each A := ["party" votes]:
e# Push S.
1$ e# Push a copy of A.
e= e# Count the occurrences of A in S.
1\t e# Replace the vote count with the number of occurrences.
p e# Print.
} e#
```
[Answer]
# Pyth, 36 bytes - 20% = 28.8
```
J<_hCo/@eCQhNheN.S*UQUvzvz.e,b/JkhCQ
```
This qualifies for the bonus.
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=J%3C_hCo%2F%40eCQhNheN.S*UQUvzvz.e%2Cb%2FJkhCQ&input=25%0A%5B%22cio%22%2C12984%5D%2C+%5B%22pcc%22%2C7716%5D%2C+%5B%22irc%22%2C13009%5D%2C+%5B%22icb%22%2C4045%5D%2C+%5B%22cub%22%2C1741%5D%2C+%5B%22bb%22%2C1013%5D&debug=0) or [Test harness](https://pyth.herokuapp.com/?code=+QzFdc.z2AzQ%2Chdved*%5C-yTztP%60Qpk%22output%3A+%22+++J%3C_hCo%2F%40eCQhNheN.S*UQUvzvz.e%2Cb%2FJkhCQ&input=Test+Cases%3A%0A%22%22%0A25%0A%5B%22cio%22%2C+12984%5D%2C+%5B%22pcc%22%2C+7716%5D%2C+%5B%22irc%22%2C+13009%5D%2C+%5B%22icb%22%2C+4045%5D%2C+%5B%22cub%22%2C+1741%5D%2C+%5B%22bb%22%2C+1013%5D%0A5%0A%5B%22a%22%2C+3%5D%2C+%5B%22b%22%2C+6%5D%2C+%5B%22c%22%2C+1%5D%0A135%0A%5B%22a%22%2C+1116259%5D%2C+%5B%22b%22%2C+498124%5D%2C+%5B%22c%22%2C+524707%5D%2C+%5B%22d%22%2C+471681%5D%2C+%5B%22e%22%2C+359705%5D%2C+%5B%22f%22%2C+275007%5D%2C+%5B%22g%22%2C+126435%5D&debug=0)
### Explanation:
```
implicit: z = 1st input (as string)
Q = 2nd input (evaluated)
vz evaluate z (#seats)
U generate the list [0,1,...,seats-1]
UQ generate the list [0,1,...,len(Q)-1]
* Cartesian product of these lists
.S shuffle (necessary for break ties randomly)
o order these tuples N by:
eCQ list of votes
@ hN take the N[0]th vote count
/ heN and divide by N[1]+1
hC extract the party index of the tuples
_ reverse the list
< vz take the first #seats elements
J and store them in J
.e hCQ enumerated map over the names of the parties
(k = index, b = name):
, generate the pair:
b/Jk name, J.count(k)
print implicitely
```
[Answer]
# Javascript, 210 bytes
```
v=(a,b,c,d,e,f,g)=>{d=Object.assign({},b),c={};for(g in b)c[g]=0;for(;a--;)e=0,f=Object.keys(d),f.forEach(a=>e=d[a]>e?d[a]:e),f=f.filter(a=>d[a]===e),f=f[~~(Math.random()*f.length)],d[f]=b[f]/-~++c[f];return c}
```
Notes:
* Requires a modern browser/engine with support for ES6. Tested in Firefox.
* Uses the very important `/-~++` operator :)
Example usage:
```
v(25, {cio:12984,pcc:7716,irc:13009,icb:4045,cub:1741,bb:1013})
```
[Answer]
# Pyth - 54 bytes
```
AGZQ=kZK*]0lZVGJhOfqeTh.MZZ.e(kb)Z XJK1 XZJ/@kJ+@KJ1;K
```
Input format (stdin):
```
[25,[12984,7716,13009,4045,1741,1013]]
```
Output format (stdout):
```
[8, 5, 9, 2, 1, 0]
```
Variables used:
```
G = total number of seats
K = array of seats currently assigned to each party
k = number of votes for each party
Z = k/(K+1)
J = which party should have the next seat
```
[Answer]
# Perl, 110
```
#!perl -pa
$n=pop@F;@x=map
0,@F;/a/,$x[$'/$n]++for(sort{$b-$a}map{map{($'/$_|0).rand.a.$i++}//..$n}@F)[0..$n-1];$_="@x"
```
Input space separated with the seat count last.
Try [me](http://ideone.com/pXiSjq).
] |
[Question]
[
Given a unique, sorted list of integers, create a balanced binary-search tree represented as an array without using recursion.
For example:
```
func( [1,2,3,5,8,13,21] ) => [5,2,13,1,3,8,21]
```
Before we start, a hint: we can simplify this problem a ton so that we don't actually have to think about the input integers (or any comparable object for that matter!).
If we know the input list is sorted already, it's contents are irrelevant. We can simply think about it in terms of indices into the original array.
An internal representation of the input array then becomes:
```
func( [0,1,2,3,4,5,6] ) => [3,1,5,0,2,4,6]
```
This means rather than writing something that has to deal with comparable objects, we really only need to write a function which maps from the range [0,n) to the resulting array. Once we have the new order, we can simply apply the mapping back to the values in the input to create the return array.
Valid solutions must:
* Accept a zero-element array and return an empty array.
* Accept an integer array of length *n* and return an integer array
+ Of length between *n* and the next highest power of 2 minus 1. (e.g., for input size 13 return anywhere between 13 and 15).
+ Array which represents a BST where the root node is at position 0 and the height is equal to *log(n)* where 0 represents a missing node (or a `null`-like value if your language allows). Empty nodes, if present, must only exist at the end of the tree (e.g., `[2,1,0]`)
The input integer array has the following guarantees:
* Values are 32-bit signed integers greater than zero.
* Values are unique.
* Values are in ascending order from position zero.
* Values may be sparse (i.e., not adjacent to each other).
The most terse code by ascii character count wins, but I'm also interested in seeing elegant solutions for any particular language.
### Test cases
The outputs for simple arrays containing `1` to `n` for various `n`. As described above, the trailing `0`s are optional.
```
[]
[1]
[2,1,0]
[2,1,3]
[3,2,4,1,0,0,0]
[4,2,5,1,3,0,0]
[4,2,6,1,3,5,0]
[4,2,6,1,3,5,7]
[5,3,7,2,4,6,8,1,0,0,0,0,0,0,0]
[6,4,8,2,5,7,9,1,3,0,0,0,0,0,0]
[7,4,9,2,6,8,10,1,3,5,0,0,0,0,0]
[8,4,10,2,6,9,11,1,3,5,7,0,0,0,0]
[8,4,11,2,6,10,12,1,3,5,7,9,0,0,0]
[8,4,12,2,6,10,13,1,3,5,7,9,11,0,0]
[8,4,12,2,6,10,14,1,3,5,7,9,11,13,0]
[8,4,12,2,6,10,14,1,3,5,7,9,11,13,15]
```
[Answer]
**Ruby**, 143
```
s=ARGV.size;r,q=[],[[0,s]];s.times{b,e=q.shift;k=Math::log2(e-b).to_i-1;m=(e-b+2)>(3<<k)?b+(2<<k)-1:e-(1<<k);r<<ARGV[m];q<<[b,m]<<[m+1,e]};p r
```
It is a (loosely) compressed version of the following code which basically does a BFS on the tree.
```
def l(n)
k = Math::log2(n).to_i-1
if n+2 > (3<<k) then
(2<<k)-1
else
n-(1<<k)
end
end
def bfs(tab)
result = []
queue = [[0,tab.size]]
until queue.empty? do
b,e = queue.shift
m = b+l(e-b)
result << tab[m]
queue << [b,m] if b < m
queue << [m+1,e] if m+1 < e
end
result
end
p bfs(ARGV)
```
Besides, because it's BFS, not DFS, a requirement of non-recursive solution is not significant, and it puts some languages at a disadvantage.
**Edit:** Fixed solution, thanks to @PeterTaylor for his comment!
[Answer]
**Java**, 252
Ok, here is my attempt. I've been playing around with bit operations and I came up with this direct way of calculating the index of an element in the BST from the index in the original array.
Compressed version
```
public int[]b(int[]a){int i,n=1,t;long x,I,s=a.length,p=s;int[]r=new int[(int)s];while((p>>=1)>0)n++;p=2*s-(1l<<n)+1;for(i=0;i<s;i++){x=(i<p)?(i+1):(p+2*(i-p)+1);t=1;while((x&1<<(t-1))==0)t++;I=(1<<(n-t));I|=((I-1)<<t&x)>>t;r[(int)I-1]=a[i];}return r;}
```
The long version follows below.
```
public static int[] makeBst(int[] array) {
long size = array.length;
int[] bst = new int[array.length];
int nbits = 0;
for (int i=0; i<32; i++)
if ((size & 1<<i)!=0) nbits=i+1;
long padding = 2*size - (1l<<nbits) + 1;
for (int i=0; i<size; i++) {
long index2n = (i<padding)?(i+1):(padding + 2*(i-padding) + 1);
int tail=1;
while ((index2n & 1<<(tail-1))==0) tail++;
long bstIndex = (1<<(nbits-tail));
bstIndex = bstIndex | ((bstIndex-1)<<tail & index2n)>>tail;
bst[(int)(bstIndex-1)] = array[i];
}
return bst;
}
```
[Answer]
```
def fn(input):
import math
n = len(input)
if n == 0:
return []
h = int(math.floor(math.log(n, 2)))
out = []
last = (2**h) - 2**(h+1) + n
def num_children(level, sibling, lr):
if level == 0:
return 0
half = 2**(level-1)
ll_base = sibling * 2**level + lr * (half)
ll_children = max(0, min(last, ll_base + half - 1) - ll_base + 1)
return 2**(level-1) - 1 + ll_children
for level in range(h, -1, -1):
for sibling in range(0, 2**(h-level)):
if level == 0 and sibling > last:
break
if sibling == 0:
last_sibling_val = num_children(level, sibling, 0)
else:
last_sibling_val += 2 + num_children(level, sibling - 1, 1) \
+ num_children(level, sibling, 0)
out.append(input[last_sibling_val])
return out
```
[Answer]
Not quite sure if this fits exactly your requirement of empty nodes being at the end of the tree and it certainly won't win any prizes for brevity, but I think it's correct and it has test cases :)
```
public class BstArray {
public static final int[] EMPTY = new int[] { };
public static final int[] L1 = new int[] { 1 };
public static final int[] L2 = new int[] { 1, 2 };
public static final int[] L3 = new int[] { 1, 2, 3 };
public static final int[] L4 = new int[] { 1, 2, 3, 5 };
public static final int[] L5 = new int[] { 1, 2, 3, 5, 8 };
public static final int[] L6 = new int[] { 1, 2, 3, 5, 8, 13 };
public static final int[] L7 = new int[] { 1, 2, 3, 5, 8, 13, 21 };
public static final int[] L8 = new int[] { 1, 2, 3, 5, 8, 13, 21, 35 };
public static final int[] L9 = new int[] { 1, 2, 3, 5, 8, 13, 21, 35, 56 };
public static final int[] L10 = new int[] { 1, 2, 3, 5, 8, 13, 21, 35, 56, 91 };
public static void main(String[] args) {
for (int[] list : Arrays.asList(EMPTY, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10)) {
System.out.println(Arrays.toString(list) + " => " + Arrays.toString(bstListFromList(list)));
}
}
private static int[] bstListFromList(int[] orig) {
int[] bst = new int[nextHighestPowerOfTwo(orig.length + 1) - 1];
if (orig.length == 0) {
return bst;
}
LinkedList<int[]> queue = new LinkedList<int[]>();
queue.push(orig);
int counter = 0;
while (!queue.isEmpty()) {
int[] list = queue.pop();
int len = list.length;
if (len == 1) {
bst[counter] = list[0];
} else if (len == 2) {
bst[counter] = list[1];
queue.add(getSubArray(list, 0, 1));
queue.add(new int[] { 0 });
} else if (len == 3) {
bst[counter] = list[1];
queue.add(getSubArray(list, 0, 1));
queue.add(getSubArray(list, 2, 1));
} else {
int divide = len / 2;
bst[counter] = list[divide];
queue.add(getSubArray(list, 0, divide));
queue.add(getSubArray(list, divide + 1, len - (divide + 1)));
}
counter++;
}
return bst;
}
private static int nextHighestPowerOfTwo(int n) {
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
private static int[] getSubArray(int[] orig, int origStart, int length) {
int[] list = new int[length];
System.arraycopy(orig, origStart, list, 0, length);
return list;
}
}
```
[Answer]
**Golfscript (~~99~~ 89)**
```
~]:b[]:^;{b}{{:|.,.2base,(2\?:&[-)&2/]{}$0=&(2/+:o[=]^\+:^;|o<.!{;}*|o)>.!{;}*}%:b}while^p
```
Basically a straight port of my Python solution, works in pretty much the same way.
Can probably be improved quite a bit with more "golfisms", already improved by 10 characters with @petertaylor's input :)
[Answer]
**Java 192**
Maps index in input to index in output
```
int[]b(int[]o){int s=o.length,p=0,u=s,i=0,y,r[]=new int[s],c[]=new int[s];while((u>>=1)>0)p++;for(int x:o){y=p;u=i;while(u%2>0){y--;u/=2;}r[(1<<y)-1+c[y]++]=x;i+=i>2*s-(1<<p+1)?2:1;}return r;}
```
Long version:
```
static int[] bfs(int[] o) {
int rowCount = 32 - Integer.numberOfLeadingZeros(o.length); // log2
int slotCount = (1<<rowCount) - 1; // pow(2,rowCount) - 1
// number of empty slots at the end
int emptySlots = slotCount - o.length;
// where we start to be affected by these empty slots
int startSkippingAbove = slotCount - 2 * emptySlots; // = 2 * o.length - slotCount
int[] result = new int[o.length];
int[] rowCounters = new int[rowCount]; // for each row, how many slots in that row are taken
int i = 0; // index of where we would be if this was a complete tree (no trailing empty slots)
for (int x : o) {
// the row (depth) a slot is in is determined by the number of trailing 1s
int rowIndex = rowCount - Integer.numberOfTrailingZeros(~i) - 1;
int colIndex = rowCounters[rowIndex]++; // count where we are
int rowStartIndex = (1 << rowIndex) - 1; // where this row starts in the result array
result[rowStartIndex + colIndex] = x;
i++;
// next one has to jump into a slot that came available by not having slotCount values
if (i > startSkippingAbove) i++;
}
return result;
}
```
[Answer]
# Wolfram Mathematica 11, 175 Bytes
```
g[l_]:=(x[a_]:=Floor@Min[i-#/2,#]&@(i=Length[a]+1;2^Ceiling@Log2[i]/2);Join@@Table[Cases[l//.{{}->{},b__List:>(n[Take[b,#-1],b[[#]],Drop[b,#]]&@x[b])},_Integer,{m}],{m,x[l]}])
```
The function `g[l]` takes as an input a `List` (e.g `l={1,2,3,4,...}`) and returns a `List` of the desired form. It works as follows:
* `x[a_]:=Floor@Min[i-#/2,#]&@(i=Length[a]+1;2^Ceiling@Log2[i]/2)` takes a list and finds the root of the associated BST.
+ `i=Length[a]+1` shortcut for the length of the list
+ `2^Ceiling@Log2[i]/2` upper bound on the value of the root
+ `Min[i-#/2,#]&@(...)` Minimum of the two argument where `#` stands for what is inside the `(...)`
* `l//.{...}` Apply repeatedly the replacement rules that follow to `l`
* `{}->{}` Nothing to do (this is the edge case to avoid an infinite loop)
* `b__List:>(n[Take[b,#-1],b[[#]],Drop[b,#]]&@x[b])` Split a `List` into `{{lesser}, root, {greater}}`
* `Cases[...,_Integer,{m}]` Take all integers at level (depth) `m`
* `Table[...,{m,1,x[l]}]` For all `m` up to `x[l]` (which is more than necessary actually).
It can be tested by running
```
Table[g[Range[a]], {a, 0, 15}]//MatrixForm
```
This implementation does not include trailing zeroes.
[Answer]
**Python (~~175~~ 171)**
Fairly condensed, still fairly readable;
```
def f(a):
b=[a]
while b:
c,t=((s,2**(len(bin(len(s)))-3))for s in b if s),[]
for x,y in c:
o=min(len(x)-y+1,y/2)+(y-1)/2
yield x[o]
t+=[x[:o],x[o+1:]]
b=t
```
It yields the result back, so you can either loop over it or (for display purposes) print it as a list;
```
>>> for i in range(1,17): print i-1,list(f(range(1,i)))
0 []
1 [1]
2 [2, 1]
3 [2, 1, 3]
4 [3, 2, 4, 1]
5 [4, 2, 5, 1, 3]
6 [4, 2, 6, 1, 3, 5]
7 [4, 2, 6, 1, 3, 5, 7]
8 [5, 3, 7, 2, 4, 6, 8, 1]
9 [6, 4, 8, 2, 5, 7, 9, 1, 3]
10 [7, 4, 9, 2, 6, 8, 10, 1, 3, 5]
11 [8, 4, 10, 2, 6, 9, 11, 1, 3, 5, 7]
12 [8, 4, 11, 2, 6, 10, 12, 1, 3, 5, 7, 9]
13 [8, 4, 12, 2, 6, 10, 13, 1, 3, 5, 7, 9, 11]
14 [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13]
15 [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]
```
[Answer]
# Java
This is a direct calculation solution. I think it works, but it has one pragmatically innocuous side effect. The array it produces may be corrupt but not in any way that would affect searches. Instead of producing 0 (null) nodes, it will produce unreachable nodes, that is the nodes will already have been found earlier in the tree during the search. It works by mapping the indices array of a regular power of 2 size binary search tree array onto an irregularly sized binary search tree array. At least, I think it works.
```
import java.util.Arrays;
public class SortedArrayToBalanceBinarySearchTreeArray
{
public static void main(String... args)
{
System.out.println(Arrays.toString(binarySearchTree(19)));
}
public static int[] binarySearchTree(int m)
{
int n = powerOf2Ceiling(m + 1);
int[] array = new int[n - 1];
for (int k = 1, index = 1; k < n; k *= 2)
{
for (int i = 0; i < k; ++i)
{
array[index - 1] = (int) (.5 + ((float) (m)) / (n - 1)
* (n / (2 * k) * (1 + 2 * index) - n));
++index;
}
}
return array;
}
public static int powerOf2Ceiling(int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
}
```
Here's a more condensed version (just the function and names paired down). It's still got the white space, but I'm not worried about winning. Also this version actually takes an array. The other one just took an int for highest index in the array.
```
public static int[] b(int m[])
{
int n = m.length;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
int[] a = new int[n - 1];
for (int k = 1, j = 1, i; k < n; k *= 2)
{
for (i = 0; i < k; ++i)
{
a[j - 1] = m[(int) (.5 + ((float) m.length) / (n - 1)
* (n / (2 * k) * (1 + 2 * j) - n)) - 1];
++j;
}
}
return a;
}
```
[Answer]
## GolfScript (79 77 70 chars)
Since the example in the question uses a function, I've made this a function. Removing the `{}:f;` to leave an expression which takes input on the stack and leaves the BST on the stack would save 5 chars.
```
{[.;][{{.!!{[.,.)[1]*{(\(@++}@(*1=/()\@~]}*}%.{0=}%\{1>~}%.}do][]*}:f;
```
[Online demo](http://golfscript.apphb.com/?c=e1suO11be3suISF7Wy4sLilbMV0qeyhcKEArK31AKCoxPS8oKVxAfl19Kn0lLnswPX0lXHsxPn59JS59ZG9dW10qfTpmOwoKWzEgMiAzIDUgOCAxMyAyMV1mIHAKMTYseyksMT5mIHB9Lw%3D%3D) (note: the app might take a bit of warming up: it timed out twice for me before running in 3 secs).
With whitespace to show the structure:
```
{
# Input is an array: wrap it in an array for the working set
[.;]
[{
# Stack: emitted-values working-set
# where the working-set is essentially an array of subtrees
# For each subtree in working-set...
{
# ...if it's not the empty array...
.!!{
# ...gather into an array...
[
# Get the size of the subtree
.,
# OEIS A006165, offset by 1
.)[1]*{(\(@++}@(*1=
# Split into [left-subtree-plus-root right-subtree]
/
# Rearrange to root left-subtree right-subtree
# where left-subtree might be [] and right-subtree might not exist at all
()\@~
]
}*
}%
# Extract the leading element of each processed subtree: these will join the emitted-values
.{0=}%
# Create a new working-set of the 1, or 2 subtrees of each processed subtree
\{1>~}%
# Loop while the working-set is non-empty
.
}do]
# Stack: [[emitted values at level 0][emitted values at level 1]...]
# Flatten by joining with the empty array
[]*
}:f;
```
[Answer]
# [J](http://jsoftware.com/), 52 bytes
```
t=:/:(#/:@{.(+:,>:@+:@i.@>:@#)^:(<.@(2&^.)@>:@#`1:))
```
function takes a sorted list and returns in binary tree order
notice that trees have identical shape but bottom level is shortened
* ``1:` start with 1
* `<.@(2&^.)@>:@#` iterate by floor of log2 ( length + 1 )
* `+: , >:@+:@i.@>:@#` loop : appends double of last vector with odd numbers 1,3 .. 2\*length+1
* `# /:@{.` take only the required number of items and get their sort indices
* `/:` apply those sort indices to the given input
[TIO](https://tio.run/##RcrBCoJAFIXhvU9xQMgZlOvcBBeHkvskolaQFbpx58NPkaC7j5//FeNyZUmXlrRVXM6ioeW0UeyH1Ld0FzF3PrXi/6VTeh/j4/ackQ2ffnpnyYKGGAUh2bJCBDUKaEA/3aHV8dS7NBysvg "J try online")
[Answer]
# [Python 2](https://docs.python.org/2/), 107 bytes
Golf of [Joachim Isaksson's answer](https://codegolf.stackexchange.com/a/18629/64121), Input is a singleton containing the list.
```
def f(a):
for x in a:
if x:w=len(x);y=1<<len(bin(w))-3;o=min(w-y+1,y/2)+~-y/2;yield x[o];a+=x[:o],x[o+1:]
```
[Try it online!](https://tio.run/##FcdBCsMgEEDRdXOKWTo4UjQUisaTiIuURCqkGtJAdNOr22T131/r/s5JtTbNAQIbUXcQ8gYFYoJRd7cYoOjDLnNiBU21chguv2JiB6LoTbafy6JySfWukP/EGVPjvExQXPZm5LY4nT2dx6X2bd1i2mGJ350F5pwkRT096EmyJyW9R2x/ "Python 2 – Try It Online")
] |
[Question]
[
Ptolemy's *Almagest* contains a [table of chords](https://en.wikipedia.org/wiki/Ptolemy%27s_table_of_chords) that effectively served as the world's only comprehensive trigonometric table for over a millennium. In modern form it looks like this:
\begin{array}{|l|rrr|rrr|}
\hline
{}\,\,\,\,\,\,\,\,\,\, \tfrac12 & 0 & 31 & 25 & 1 & 2 & 50 \\
{}\,\,\,\,\,\,\, 1 & 1 & 2 & 50 & 1 & 2 & 50 \\
{}\,\,\,\,\,\,\, 1\tfrac12 & 1 & 34 & 15 & 1 & 2 & 50 \\
{}\,\,\,\,\,\,\, \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\
109 & 97 & 41 & 38 & 0 & 36 & 23 \\
109\tfrac12 & 97 & 59 & 49 & 0 & 36 & 9 \\
110 & 98 & 17 & 54 & 0 & 35 & 56 \\
110\tfrac12 & 98 & 35 & 52 & 0 & 35 & 42\\
111 & 98 & 53 & 43 & 0 & 35 & 29 \\
111\tfrac12 & 99 & 11 & 27 & 0 & 35 & 15 \\
112 & 99 & 29 & 5 & 0 & 35 & 1\\
112\tfrac12 & 99 & 46 & 35 & 0 & 34 & 48 \\
113 & 100 & 3 & 59 & 0 & 34 & 34 \\
{}\,\,\,\,\,\,\, \vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\
179 & 119 & 59 & 44 & 0 & 0 & 25 \\
179\frac12 & 119 & 59 & 56 & 0 & 0 & 9 \\
180 & 120 & 0 & 0 & 0 & 0 & 0 \\
\hline
\end{array}
The table has 360 lines, each in the following format:
* An angle \$\theta\$ in degrees, ranging from ½° to 180° inclusive in ½° increments.
* The chord length subtended by \$\theta\$ in a circle of radius 60. This length is equal to \$c(\theta)=120\sin\frac\theta2\$ and is given as three numbers: the integer part comes first and the first and second sexagesimal (base 60) digits follow.
* A "sixtieths" column used for linear interpolation, giving \$\frac{c(\theta+1/2^\circ)-c(\theta)}{30}\$. This follows a similar format to the chords column but lists three sexagesimal digits; the integer part is always 0 and has been omitted in the table above for brevity (it was written out in the original). Also note that 0 appears in this column at 180° instead of a negative value as the formula would imply.
## Task
Output all 360 lines of the table, each containing seven numbers – without the zero integer parts of the sixtieths column – as described above:
```
0.5 [0, 31, 25] [1, 2, 50]
1.0 [1, 2, 50] [1, 2, 50]
1.5 [1, 34, 15] [1, 2, 49]
2.0 [2, 5, 39] [1, 2, 49]
2.5 [2, 37, 4] [1, 2, 49]
3.0 [3, 8, 28] [1, 2, 48]
3.5 [3, 39, 53] [1, 2, 48]
4.0 [4, 11, 17] [1, 2, 47]
4.5 [4, 42, 40] [1, 2, 47]
5.0 [5, 14, 4] [1, 2, 46]
5.5 [5, 45, 27] [1, 2, 45]
6.0 [6, 16, 49] [1, 2, 44]
6.5 [6, 48, 11] [1, 2, 43]
7.0 [7, 19, 33] [1, 2, 42]
7.5 [7, 50, 54] [1, 2, 41]
8.0 [8, 22, 15] [1, 2, 40]
8.5 [8, 53, 35] [1, 2, 39]
9.0 [9, 24, 54] [1, 2, 38]
9.5 [9, 56, 13] [1, 2, 36]
10.0 [10, 27, 31] [1, 2, 35]
10.5 [10, 58, 49] [1, 2, 33]
11.0 [11, 30, 5] [1, 2, 32]
11.5 [12, 1, 21] [1, 2, 30]
12.0 [12, 32, 36] [1, 2, 28]
12.5 [13, 3, 50] [1, 2, 27]
13.0 [13, 35, 4] [1, 2, 25]
13.5 [14, 6, 16] [1, 2, 23]
14.0 [14, 37, 28] [1, 2, 21]
14.5 [15, 8, 38] [1, 2, 19]
15.0 [15, 39, 47] [1, 2, 17]
15.5 [16, 10, 56] [1, 2, 14]
16.0 [16, 42, 3] [1, 2, 12]
16.5 [17, 13, 9] [1, 2, 10]
17.0 [17, 44, 14] [1, 2, 7]
17.5 [18, 15, 17] [1, 2, 5]
18.0 [18, 46, 20] [1, 2, 2]
18.5 [19, 17, 21] [1, 2, 0]
19.0 [19, 48, 21] [1, 1, 57]
19.5 [20, 19, 19] [1, 1, 54]
20.0 [20, 50, 16] [1, 1, 51]
20.5 [21, 21, 12] [1, 1, 48]
21.0 [21, 52, 6] [1, 1, 45]
21.5 [22, 22, 58] [1, 1, 42]
22.0 [22, 53, 49] [1, 1, 39]
22.5 [23, 24, 39] [1, 1, 36]
23.0 [23, 55, 27] [1, 1, 33]
23.5 [24, 26, 13] [1, 1, 29]
24.0 [24, 56, 58] [1, 1, 26]
24.5 [25, 27, 41] [1, 1, 22]
25.0 [25, 58, 22] [1, 1, 19]
25.5 [26, 29, 1] [1, 1, 15]
26.0 [26, 59, 39] [1, 1, 11]
26.5 [27, 30, 15] [1, 1, 8]
27.0 [28, 0, 48] [1, 1, 4]
27.5 [28, 31, 20] [1, 1, 0]
28.0 [29, 1, 50] [1, 0, 56]
28.5 [29, 32, 18] [1, 0, 52]
29.0 [30, 2, 44] [1, 0, 48]
29.5 [30, 33, 8] [1, 0, 44]
30.0 [31, 3, 30] [1, 0, 39]
30.5 [31, 33, 49] [1, 0, 35]
31.0 [32, 4, 7] [1, 0, 31]
31.5 [32, 34, 22] [1, 0, 26]
32.0 [33, 4, 35] [1, 0, 22]
32.5 [33, 34, 46] [1, 0, 17]
33.0 [34, 4, 55] [1, 0, 12]
33.5 [34, 35, 1] [1, 0, 8]
34.0 [35, 5, 5] [1, 0, 3]
34.5 [35, 35, 6] [0, 59, 58]
35.0 [36, 5, 5] [0, 59, 53]
35.5 [36, 35, 1] [0, 59, 48]
36.0 [37, 4, 55] [0, 59, 43]
36.5 [37, 34, 47] [0, 59, 38]
37.0 [38, 4, 36] [0, 59, 32]
37.5 [38, 34, 22] [0, 59, 27]
38.0 [39, 4, 5] [0, 59, 22]
38.5 [39, 33, 46] [0, 59, 16]
39.0 [40, 3, 25] [0, 59, 11]
39.5 [40, 33, 0] [0, 59, 5]
40.0 [41, 2, 33] [0, 59, 0]
40.5 [41, 32, 3] [0, 58, 54]
41.0 [42, 1, 30] [0, 58, 48]
41.5 [42, 30, 54] [0, 58, 42]
42.0 [43, 0, 15] [0, 58, 37]
42.5 [43, 29, 33] [0, 58, 31]
43.0 [43, 58, 49] [0, 58, 25]
43.5 [44, 28, 1] [0, 58, 18]
44.0 [44, 57, 10] [0, 58, 12]
44.5 [45, 26, 16] [0, 58, 6]
45.0 [45, 55, 19] [0, 58, 0]
45.5 [46, 24, 19] [0, 57, 53]
46.0 [46, 53, 16] [0, 57, 47]
46.5 [47, 22, 9] [0, 57, 41]
47.0 [47, 51, 0] [0, 57, 34]
47.5 [48, 19, 47] [0, 57, 27]
48.0 [48, 48, 30] [0, 57, 21]
48.5 [49, 17, 11] [0, 57, 14]
49.0 [49, 45, 47] [0, 57, 7]
49.5 [50, 14, 21] [0, 57, 0]
50.0 [50, 42, 51] [0, 56, 53]
50.5 [51, 11, 18] [0, 56, 46]
51.0 [51, 39, 41] [0, 56, 39]
51.5 [52, 8, 0] [0, 56, 32]
52.0 [52, 36, 16] [0, 56, 25]
52.5 [53, 4, 29] [0, 56, 17]
53.0 [53, 32, 37] [0, 56, 10]
53.5 [54, 0, 43] [0, 56, 3]
54.0 [54, 28, 44] [0, 55, 55]
54.5 [54, 56, 42] [0, 55, 48]
55.0 [55, 24, 35] [0, 55, 40]
55.5 [55, 52, 25] [0, 55, 32]
56.0 [56, 20, 12] [0, 55, 25]
56.5 [56, 47, 54] [0, 55, 17]
57.0 [57, 15, 33] [0, 55, 9]
57.5 [57, 43, 7] [0, 55, 1]
58.0 [58, 10, 38] [0, 54, 53]
58.5 [58, 38, 4] [0, 54, 45]
59.0 [59, 5, 27] [0, 54, 37]
59.5 [59, 32, 46] [0, 54, 29]
60.0 [60, 0, 0] [0, 54, 21]
60.5 [60, 27, 10] [0, 54, 12]
61.0 [60, 54, 17] [0, 54, 4]
61.5 [61, 21, 19] [0, 53, 56]
62.0 [61, 48, 16] [0, 53, 47]
62.5 [62, 15, 10] [0, 53, 39]
63.0 [62, 41, 59] [0, 53, 30]
63.5 [63, 8, 44] [0, 53, 21]
64.0 [63, 35, 25] [0, 53, 13]
64.5 [64, 2, 1] [0, 53, 4]
65.0 [64, 28, 33] [0, 52, 55]
65.5 [64, 55, 1] [0, 52, 46]
66.0 [65, 21, 24] [0, 52, 37]
66.5 [65, 47, 43] [0, 52, 28]
67.0 [66, 13, 57] [0, 52, 19]
67.5 [66, 40, 6] [0, 52, 10]
68.0 [67, 6, 11] [0, 52, 1]
68.5 [67, 32, 12] [0, 51, 52]
69.0 [67, 58, 7] [0, 51, 42]
69.5 [68, 23, 59] [0, 51, 33]
70.0 [68, 49, 45] [0, 51, 23]
70.5 [69, 15, 27] [0, 51, 14]
71.0 [69, 41, 4] [0, 51, 4]
71.5 [70, 6, 36] [0, 50, 55]
72.0 [70, 32, 3] [0, 50, 45]
72.5 [70, 57, 26] [0, 50, 35]
73.0 [71, 22, 43] [0, 50, 26]
73.5 [71, 47, 56] [0, 50, 16]
74.0 [72, 13, 4] [0, 50, 6]
74.5 [72, 38, 7] [0, 49, 56]
75.0 [73, 3, 5] [0, 49, 46]
75.5 [73, 27, 58] [0, 49, 36]
76.0 [73, 52, 46] [0, 49, 26]
76.5 [74, 17, 29] [0, 49, 15]
77.0 [74, 42, 6] [0, 49, 5]
77.5 [75, 6, 39] [0, 48, 55]
78.0 [75, 31, 6] [0, 48, 45]
78.5 [75, 55, 29] [0, 48, 34]
79.0 [76, 19, 46] [0, 48, 24]
79.5 [76, 43, 58] [0, 48, 13]
80.0 [77, 8, 4] [0, 48, 3]
80.5 [77, 32, 6] [0, 47, 52]
81.0 [77, 56, 2] [0, 47, 41]
81.5 [78, 19, 52] [0, 47, 31]
82.0 [78, 43, 38] [0, 47, 20]
82.5 [79, 7, 17] [0, 47, 9]
83.0 [79, 30, 52] [0, 46, 58]
83.5 [79, 54, 21] [0, 46, 47]
84.0 [80, 17, 44] [0, 46, 36]
84.5 [80, 41, 2] [0, 46, 25]
85.0 [81, 4, 15] [0, 46, 14]
85.5 [81, 27, 22] [0, 46, 3]
86.0 [81, 50, 23] [0, 45, 52]
86.5 [82, 13, 19] [0, 45, 40]
87.0 [82, 36, 9] [0, 45, 29]
87.5 [82, 58, 54] [0, 45, 18]
88.0 [83, 21, 32] [0, 45, 6]
88.5 [83, 44, 5] [0, 44, 55]
89.0 [84, 6, 33] [0, 44, 43]
89.5 [84, 28, 54] [0, 44, 32]
90.0 [84, 51, 10] [0, 44, 20]
90.5 [85, 13, 20] [0, 44, 8]
91.0 [85, 35, 24] [0, 43, 56]
91.5 [85, 57, 22] [0, 43, 45]
92.0 [86, 19, 15] [0, 43, 33]
92.5 [86, 41, 1] [0, 43, 21]
93.0 [87, 2, 42] [0, 43, 9]
93.5 [87, 24, 16] [0, 42, 57]
94.0 [87, 45, 45] [0, 42, 45]
94.5 [88, 7, 7] [0, 42, 33]
95.0 [88, 28, 24] [0, 42, 21]
95.5 [88, 49, 34] [0, 42, 9]
96.0 [89, 10, 39] [0, 41, 56]
96.5 [89, 31, 37] [0, 41, 44]
97.0 [89, 52, 29] [0, 41, 32]
97.5 [90, 13, 15] [0, 41, 19]
98.0 [90, 33, 55] [0, 41, 7]
98.5 [90, 54, 28] [0, 40, 55]
99.0 [91, 14, 55] [0, 40, 42]
99.5 [91, 35, 16] [0, 40, 30]
100.0 [91, 55, 31] [0, 40, 17]
100.5 [92, 15, 40] [0, 40, 4]
101.0 [92, 35, 42] [0, 39, 52]
101.5 [92, 55, 38] [0, 39, 39]
102.0 [93, 15, 27] [0, 39, 26]
102.5 [93, 35, 10] [0, 39, 13]
103.0 [93, 54, 47] [0, 39, 0]
103.5 [94, 14, 17] [0, 38, 47]
104.0 [94, 33, 41] [0, 38, 35]
104.5 [94, 52, 58] [0, 38, 21]
105.0 [95, 12, 9] [0, 38, 8]
105.5 [95, 31, 13] [0, 37, 55]
106.0 [95, 50, 11] [0, 37, 42]
106.5 [96, 9, 2] [0, 37, 29]
107.0 [96, 27, 46] [0, 37, 16]
107.5 [96, 46, 24] [0, 37, 3]
108.0 [97, 4, 55] [0, 36, 49]
108.5 [97, 23, 20] [0, 36, 36]
109.0 [97, 41, 38] [0, 36, 22]
109.5 [97, 59, 49] [0, 36, 9]
110.0 [98, 17, 54] [0, 35, 56]
110.5 [98, 35, 51] [0, 35, 42]
111.0 [98, 53, 43] [0, 35, 29]
111.5 [99, 11, 27] [0, 35, 15]
112.0 [99, 29, 4] [0, 35, 1]
112.5 [99, 46, 35] [0, 34, 48]
113.0 [100, 3, 59] [0, 34, 34]
113.5 [100, 21, 16] [0, 34, 20]
114.0 [100, 38, 26] [0, 34, 6]
114.5 [100, 55, 29] [0, 33, 53]
115.0 [101, 12, 25] [0, 33, 39]
115.5 [101, 29, 14] [0, 33, 25]
116.0 [101, 45, 57] [0, 33, 11]
116.5 [102, 2, 32] [0, 32, 57]
117.0 [102, 19, 1] [0, 32, 43]
117.5 [102, 35, 22] [0, 32, 29]
118.0 [102, 51, 36] [0, 32, 15]
118.5 [103, 7, 44] [0, 32, 0]
119.0 [103, 23, 44] [0, 31, 46]
119.5 [103, 39, 37] [0, 31, 32]
120.0 [103, 55, 23] [0, 31, 18]
120.5 [104, 11, 2] [0, 31, 4]
121.0 [104, 26, 34] [0, 30, 49]
121.5 [104, 41, 58] [0, 30, 35]
122.0 [104, 57, 16] [0, 30, 20]
122.5 [105, 12, 26] [0, 30, 6]
123.0 [105, 27, 29] [0, 29, 52]
123.5 [105, 42, 25] [0, 29, 37]
124.0 [105, 57, 13] [0, 29, 23]
124.5 [106, 11, 55] [0, 29, 8]
125.0 [106, 26, 29] [0, 28, 53]
125.5 [106, 40, 55] [0, 28, 39]
126.0 [106, 55, 15] [0, 28, 24]
126.5 [107, 9, 27] [0, 28, 9]
127.0 [107, 23, 32] [0, 27, 55]
127.5 [107, 37, 29] [0, 27, 40]
128.0 [107, 51, 19] [0, 27, 25]
128.5 [108, 5, 2] [0, 27, 10]
129.0 [108, 18, 37] [0, 26, 56]
129.5 [108, 32, 5] [0, 26, 41]
130.0 [108, 45, 25] [0, 26, 26]
130.5 [108, 58, 38] [0, 26, 11]
131.0 [109, 11, 43] [0, 25, 56]
131.5 [109, 24, 41] [0, 25, 41]
132.0 [109, 37, 32] [0, 25, 26]
132.5 [109, 50, 15] [0, 25, 11]
133.0 [110, 2, 50] [0, 24, 56]
133.5 [110, 15, 18] [0, 24, 41]
134.0 [110, 27, 38] [0, 24, 25]
134.5 [110, 39, 51] [0, 24, 10]
135.0 [110, 51, 56] [0, 23, 55]
135.5 [111, 3, 53] [0, 23, 40]
136.0 [111, 15, 43] [0, 23, 25]
136.5 [111, 27, 26] [0, 23, 9]
137.0 [111, 39, 0] [0, 22, 54]
137.5 [111, 50, 27] [0, 22, 39]
138.0 [112, 1, 47] [0, 22, 23]
138.5 [112, 12, 58] [0, 22, 8]
139.0 [112, 24, 2] [0, 21, 53]
139.5 [112, 34, 59] [0, 21, 37]
140.0 [112, 45, 47] [0, 21, 22]
140.5 [112, 56, 28] [0, 21, 6]
141.0 [113, 7, 1] [0, 20, 51]
141.5 [113, 17, 26] [0, 20, 35]
142.0 [113, 27, 44] [0, 20, 20]
142.5 [113, 37, 54] [0, 20, 4]
143.0 [113, 47, 56] [0, 19, 48]
143.5 [113, 57, 50] [0, 19, 33]
144.0 [114, 7, 36] [0, 19, 17]
144.5 [114, 17, 15] [0, 19, 1]
145.0 [114, 26, 46] [0, 18, 46]
145.5 [114, 36, 9] [0, 18, 30]
146.0 [114, 45, 24] [0, 18, 14]
146.5 [114, 54, 31] [0, 17, 59]
147.0 [115, 3, 30] [0, 17, 43]
147.5 [115, 12, 22] [0, 17, 27]
148.0 [115, 21, 5] [0, 17, 11]
148.5 [115, 29, 41] [0, 16, 55]
149.0 [115, 38, 8] [0, 16, 40]
149.5 [115, 46, 28] [0, 16, 24]
150.0 [115, 54, 40] [0, 16, 8]
150.5 [116, 2, 44] [0, 15, 52]
151.0 [116, 10, 40] [0, 15, 36]
151.5 [116, 18, 28] [0, 15, 20]
152.0 [116, 26, 8] [0, 15, 4]
152.5 [116, 33, 40] [0, 14, 48]
153.0 [116, 41, 4] [0, 14, 32]
153.5 [116, 48, 20] [0, 14, 16]
154.0 [116, 55, 28] [0, 14, 0]
154.5 [117, 2, 28] [0, 13, 44]
155.0 [117, 9, 20] [0, 13, 28]
155.5 [117, 16, 4] [0, 13, 12]
156.0 [117, 22, 40] [0, 12, 56]
156.5 [117, 29, 8] [0, 12, 40]
157.0 [117, 35, 27] [0, 12, 24]
157.5 [117, 41, 39] [0, 12, 7]
158.0 [117, 47, 43] [0, 11, 51]
158.5 [117, 53, 39] [0, 11, 35]
159.0 [117, 59, 26] [0, 11, 19]
159.5 [118, 5, 6] [0, 11, 3]
160.0 [118, 10, 37] [0, 10, 47]
160.5 [118, 16, 0] [0, 10, 30]
161.0 [118, 21, 15] [0, 10, 14]
161.5 [118, 26, 22] [0, 9, 58]
162.0 [118, 31, 21] [0, 9, 42]
162.5 [118, 36, 12] [0, 9, 25]
163.0 [118, 40, 55] [0, 9, 9]
163.5 [118, 45, 29] [0, 8, 53]
164.0 [118, 49, 56] [0, 8, 37]
164.5 [118, 54, 14] [0, 8, 20]
165.0 [118, 58, 24] [0, 8, 4]
165.5 [119, 2, 26] [0, 7, 48]
166.0 [119, 6, 20] [0, 7, 31]
166.5 [119, 10, 6] [0, 7, 15]
167.0 [119, 13, 43] [0, 6, 59]
167.5 [119, 17, 12] [0, 6, 42]
168.0 [119, 20, 33] [0, 6, 26]
168.5 [119, 23, 46] [0, 6, 10]
169.0 [119, 26, 51] [0, 5, 53]
169.5 [119, 29, 48] [0, 5, 37]
170.0 [119, 32, 36] [0, 5, 20]
170.5 [119, 35, 16] [0, 5, 4]
171.0 [119, 37, 48] [0, 4, 48]
171.5 [119, 40, 12] [0, 4, 31]
172.0 [119, 42, 28] [0, 4, 15]
172.5 [119, 44, 35] [0, 3, 58]
173.0 [119, 46, 34] [0, 3, 42]
173.5 [119, 48, 25] [0, 3, 26]
174.0 [119, 50, 8] [0, 3, 9]
174.5 [119, 51, 43] [0, 2, 53]
175.0 [119, 53, 9] [0, 2, 36]
175.5 [119, 54, 27] [0, 2, 20]
176.0 [119, 55, 37] [0, 2, 3]
176.5 [119, 56, 39] [0, 1, 47]
177.0 [119, 57, 32] [0, 1, 30]
177.5 [119, 58, 17] [0, 1, 14]
178.0 [119, 58, 54] [0, 0, 58]
178.5 [119, 59, 23] [0, 0, 41]
179.0 [119, 59, 44] [0, 0, 25]
179.5 [119, 59, 56] [0, 0, 8]
180.0 [120, 0, 0] [0, 0, 0]
```
The separation between lines and between numbers in a line must be clear, but is otherwise unrestricted. **Rounding in the last sexagesimal place should be to the nearest integer** – this makes the table to be output here not exactly correspond with Ptolemy's original, i.e. the table should match the *code block* above.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~71~~ 78 bytes
+7 fix a bug noted by [Arnauld](https://codegolf.stackexchange.com/questions/257712/ptolemys-table-of-chords/257717?noredirect=1#comment569572_257717)
```
#/2|Ramp[DMSList/@Round[{c@#,2c[1+#]-2c@#},60^-2]]&~Array~360
c=120Sin[#/4°]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Zl@19Z36gmKDG3INrFN9gns7hE3yEovzQvJbo62UFZxyg52lBbOVbXCMip1TEziNM1io1Vq3MsKkqsrDM2M@BKtjU0MgjOzItW1jc5tCFW7X9AUWYe0Iy0/wA "Wolfram Language (Mathematica) – Try It Online")
Yields a list of rows expressed as `θ | {{chord...}, {sixtieths...}}`.
`DMSList` conveniently converts a number into its integer part and two sexagesimal places. We can multiply the sixtieths by 60 to extract its three parts using the same function.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 126 bytes
```
for(v=10/573,a=1,F=q=>[q*60|0,(q=q*216e3+.5|0)/60%60|0,q>0?q%60:a=0];a;)print(a/2,F(v/2),F(-v+(v=4*Math.sin(++a/229.183118))))
```
[Try it online!](https://tio.run/##HYzLDsIgFAW/xoRX4QIW0Ya6684vMC5ujI11UUtLWPXfkXg2M8kk54MZt@c6LanJvpTxu5IcNKj2ZAUGLYYQQ3@PzMEOgsQQmdHuZblsd6DKweEfYg/XWPWCAR4ddnRZpzkRVEYMJCtDK5rM6/WR3TC95TbNhPPazVlqb7X2tK6UHw "JavaScript (V8) – Try It Online")
Or [try this version with a custom print](https://tio.run/##VY5BDoIwEEWv0oXGFurQFkXUFHfsPAEhcaKoGEMtkMZEPTtWXfk38/NeMjMXdNjt2/rWT1063Nq66YkmFACQEZ2RvWk6c63gak50N3pgIUroTV7fqwOV7EWKD5MlXEzd0AknE/Yqf1D9wx0bjqalTksRzRcxRy15rq3OChsk4ik4tdoGSiZVHML8KViUiPFX2ExsrK8r1KJc45p9v6QYKZ5TFynmx9SFfvUs2GJ/hs5fDUPv1RJkGkuZMp9heAM) for easier comparison with the table provided in the challenge.
### Commented
```
for( // loop:
v = 10 / 573, // good enough approximation of 4 * sin(pi / 720)
a = 1, // angle in half degrees
F = q => // helper function taking a value q in [0,2]
[ // and returning a triplet consisting of:
q * 60 | 0, // - the integer part of q * 60
( q = // - the first sexagesimal place, obtained by
q * 216e3 // updating q to floor(q * 60 ** 3 + 0.5),
+ .5 | 0 //
) / 60 % 60 // dividing by 60, reducing modulo 60
| 0, // and rounding towards 0
q > 0 ? q % 60 // - the 2nd sexagesimal place, which is
: a = 0 // max(q mod 60, 0) (the max() is needed for
]; // the last line of the table)
a; // stop when a = 0
) //
print( // print:
a / 2, // the angle in degrees
F(v / 2), // followed by the 1st triplet, using v / 2
F( // followed by the 2nd triplet:
-v + // subtract the current value of v and add
( v = // the new value of v defined as:
4 * Math.sin( // 4 times the sine of:
++a / // increment a and divide it by a good
229.183118 // enough approximation of 720 / pi
) //
) //
) // end of 2nd call to F
) // end of print()
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~56~~ ~~55~~ 54 [bytes](https://github.com/abrudz/SBCS)
A full program printing the table
```
d,0 60 60∘⊤¨⌊.5+↑c,¨2×0,⍨¯2-/c←432e3×1○360÷⍨○d←2÷⍨⍳360
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X@KjoGCGQg96pjxqGvJoRWPerr0TLUftU1M1jm0wujwdAOdR70rDq030tVPftQ2wcTYKNX48HTDR9O7jc0MDm8HygGZKUAZIwindzNQHGT0/zQA "APL (Dyalog Unicode) – Try It Online")
`d←2÷⍨⍳360` all the angles \$\theta\$ from 0.5 to 180.
`1○` Sine of `360÷⍨○` \$\theta \over 2\$ in radians.
`432e3×` Multiply by \$432000 = 60×60×120\$. This gives the chord length adjusted such that both sexagesimal digits are in the integer part.
`¯2-/` Differences of adjacent values, for the "sixtieths" column.
`0,⍨` Append a 0, this hardcodes the sixtieths for 180°.
`2×` Multiply each value by \$2 = 60 ÷ 30\$.
`↑c,¨` Pair up each chord length with corresponding sixtieths value. This results in a matrix with two columns.
`⌊.5+` Round all values to the nearest integer.
`0 60 60∘⊤¨` Convert each value from "base 60", where the first of three digit is unbounded.
`d,` prepend the angles on the left of the table.
[Answer]
# [Python](https://www.python.org), ~~204 210 202 191 208 206 194 190 188 180 166~~ 147 bytes
```
from math import*;j=0
while j<360:C=pi/720;j+=1;p=sin(C*j);print(j/2,*[[(x:=round(432e3*y))//3600,x//60%60,x%60]for y in[p,max(sin(C*-~j)-p,0)*2]])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc49DoIwAAXg3VN0MWlrSWsxaKidOAZhIBFCG_qTWiIsXsLRhUXv5G0kQZeXt7yX7_n2U-ycnefXENvk9Hm0wRlg6tgBZbwLEQst2ebWqb4B-pxmLC-kV_TImdA7uRdeXpWFBdZI-KBshJpygssSjrkMbrAXeEh5k-IJIUqXOSMjpRnbZktZompdABNQtvTE1CNcz5K7RoknDGFeVWil_YR_6Rc)
or [see it in a nicer format](https://ato.pxeger.com/run?1=LY69DoIwAIR3n6KLsa0lrWDQgJ18DGTACKGN_UkpsSy-hKOLi76TbyMRlrsvudzlnh87-Nbo13djrBPa878uJr5W6nypcMimDOJAutryFTh5sELv3jfR_vtonFFAVb4FQlnjPM4lZ4tbK641kIckZdmRW0F3Mcvlmm9yyzuh4RFLlE-zksYEFwUMGXem1xe4TeI6wQNClI51RgKlKVumI4xSNsaBAQhdWKKqAKex6C5RZAlDOC7L-dprttl_).
Thanks to *@Neil* for pointing out a bug and saving ~~2 14~~ 16 bytes.
Thanks to *@pan* for saving 8 bytes.
Thanks to *@xnor* for saving ~~14~~ 33 bytes.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 38 bytes
```
kRɾ½:½∆R∆s»⟇₀¨»*:¯d0JZƛƛṙ2(60ḋ÷$)^W;;Z
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJQ4biLVCIsIiIsImtSyb7CvTrCveKIhlLiiIZzwrvin4figoDCqMK7KjrCr2QwSlrGm8ab4bmZMig2MOG4i8O3JCleVzs7WiIsIiIsIiJd)
Outputs as a list of `[a,[[b,c,d],[d,e,f]]]`. The online interpreter times out after about outputting about half of the table.
First get the lengths a list of angles and the lengths of chord of the unit circle.
```
kR # push 360
ɾ # inclusive 1 range
½ # halve
: # duplicate
½ # halve
∆R # convert to radians
∆s # sine
```
Get the numbers in the second and third column multiplied by 3600.
```
»⟇₀¨» # push 60*60*120
* # multiply
: # duplicate
¯ # consecutive differences
d # double
0J # append 0
Z # zip
```
Convert to base sixty and zip with angles
```
ƛƛ # map map:
ṙ # round
2( # for n in range(2):
60ḋ # div mod by 60
÷ # push each to stack
$ # swap
) # end for
^W # reverse stack and wrap it in a list
;; # end map end map
Z # zip
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~73~~ 70 bytes
```
≔⁶⁰θ⊞υ²⮌E³⁶⁰⪫⁺⟦∕⁻³⁶⁰κ²⟧E⁺·⁵×Xθ³⁺υ⊗⁻⊟υ⊞Oυ↔⊕XI1j∕ι¹⁸⁰⟦÷⌊λ×θθ﹪÷⌊λθθ﹪⌊λθ⟧
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZDPSsQwEMbx6lOEnKaQla6LsrCnxUVYoVjEW-khbaMbzWba_KkP42UPij6TT2PSjeLBQCDD9_u-mcnrZ7vjpkWuDod37x5my6-TYm2tfNRwmTMyZKvT0tsdeEbO49tI7eBOjMJYAQXvYRGxG5QaSuUtVBs5yi5IUodqEp-z6K0ZifgE5WcXjNzLvbBQ4oswMDCyCNQkhk4b9I0SXQopsQcf1TDHbS8Md2gitW4sKu8EbHVrxF5oFyzHvCtuHdD5Ew22NJBkZL7Ms9_DSLXVLonXCkOmyn6mGuLmoSqw8wrhP3BINyF_hTpaKaGxzerNNq1Nf_tR0dmoaJ3Kbw) Link is to verbose version of code. Explanation:
```
≔⁶⁰θ
```
Assign \$60\$ to a variable because it gets used enough times to make it worthwhile.
```
⊞υ²
```
Set the "next" chord to \$2\$, so that the linear interpolation values for \$180°\$ become zero.
```
⮌E³⁶⁰⪫⁺
```
Map downwards from \$180°\$ to \$0.5°\$, with the final output reversed, joining together...
```
⟦∕⁻³⁶⁰κ²⟧
```
... the angle, and, ...
```
E⁺·⁵×Xθ³⁺υ⊗⁻⊟υ⊞Oυ↔⊕XI1j∕ι¹⁸⁰
```
...mapping over the current chord and the difference between the previous and the current chord, ...
```
⟦÷⌊λ×θθ﹪÷⌊λθθ﹪⌊λθ⟧
```
... convert to sexagesimal.
Chords are calculated by using the identity \$2|\sin(45x°)|=|i^{2-x}+1|\$ . Note that the although the variable containing the current chord is referenced before the actual calculation, it's actually a list and gets mutated to the correct value before it is mapped over.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~62~~ ~~61~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
360©L;Džq*®/Ž•6¥U•*D¥0ª·øòεε2F60‰`s})R]‚ø
```
-19 bytes porting the approaches used in [*@AndrovT*'s Vyxal](https://codegolf.stackexchange.com/a/257749/52210) and [*@ovs*' APL](https://codegolf.stackexchange.com/a/257750/52210) answers, which is also much faster, so make sure to upvote both of them as well!
Outputs as a list of `[a,[[b,c,d],[e,f,g]]]`.
[Try it online](https://tio.run/##AUoAtf9vc2FiaWX//zM2MMKpTDtExb5xKsKuL8OFwr3igKI2wqVV4oCiKkTCpTDCqsK3w7jDss61zrUyRjYw4oCwYHN9KVJd4oCaw7j//w) or [verify everything is correct](https://tio.run/##XZrLyqdHEcZvZTIrE15iV3dXH8wiCJOAIAGDASEMJMZZDASjSTxkEZiNN@FSCHgAESGYhUb4Rre5iNzI2FX1PPWfEQZmvvf3Pe@h@@mq6ur56JP3f/r40bNnbZS7P/3wtQf//fqXr9z99btPf3f3r2@f/GHcffHO@euVB3dflLs/3/3j6VdP//7Nl998Wd8c5dsnf3vvk89ffvvht09@//SrZ@/8@v6j3/7i0QefPvrZ9@7df/2z1@@/du/9Dz791fsf2o8/eevpHx@8/tl753fPnx89vn/vOx989PHH59dfvv/0L@enBz9488033n7jrR@/9PL9u39@fn1@9/V/njy@@/r@03/f@82jjx/de/xzCF4ywfc//PAefr7/@fXs3XfLq3q9W64mV9WH17vnr0vLQ/vXqyV/fPG62o@tX0JB3waqCc5vXW3/33W1621e/YXrzX6/Xeuqi9dXXFe73val7QXQTXAeK5dMghlADfTzc3kBqCn0kn579Ijrate7XjXvpAaGCcYlw94RoAdQA32dxxM0A9MU85J9tXzbGkANaLk0Hy4GlinOV9fnBrAEUAN6vp2g@UhtU@yr9tut2gqgBvS8MR/e/AOl@OyV831naokUSB3pun1k82@RmPMzuYeSVBATnVe@at4u7ODTLvaL9uxAdQGZ6HzOzUPV50V87o1ozkxVENP0yyaBJF7Op/@QY6R0TBUgE@nxUiMRHzlxB4h50iwBNIFMdJ5zPpaPEp9scRuYCc43kVQQE535bhfHTmIc3AiH9G53CTRBTHOcozfjxse6FQ7p46o5QiCm2UdwG/B4jpvhkGNFELl0AtlKK2ZG2UT@RdX9cNCxI8b1IAEylU2sfWSgWHDV/XCua70oinVS3Q/HwuePLiJ/9RpxoJqPO98ifFwjFDRzckvkhq3uiIM016TAldUtcSQ1bX5eNm7onrB1MW6vUQeQqexutu6A4g3dFAeprUKg8Et1U5wH1TOEJPHF7olDdN/eXQTIRNOWDZa0XDGAboq6rmIjilECUAcWdwuIz291T9jjuWjcnkHUyVlpsojii9wU5/EeroJgCt0Th7QTaUn8FZpb4jy/2UoOEtPU3BFGcgYLgkdzR5wX6NckEAB1cPICxrRgJpobwu7FuFYwEc39cMgR9QEUq7NFdjjXjyNIKog6ObFDQCJvuBnOVb2oaLiufv38sYcUm0INiTuhDUiCNBB1gqc4Qn5yJ1g6i1cL1IDUkb34JItY3dwLbdkw5GtEdG3uhoM4eM4iVDb3g4Wv2yti9NwPbfs05R0lxtwN0c8IRFoPJEAaqF0lP9rTqDuiIx@AFBB10iIgevKIyNLdEd0yQytEyNfuCYuhyIHB/OW7m6K3C0vGUZtA6qjufI8Fm/UGGZOXs0gd3Y1xwu9ZVkIk8SZROpwhnBauySqYydTDyyDzUexuj4NOUJJ8WgEy1bBQRjThne4GOexEQN5xslRxh/RpgTNlURd0N8hBKpwYMxKQqZZFdvpqwiDdDdJt0HMGJhJjd4t0TyMiZJHkelhkWxV0u@cEsvqoWOFUU@bfre6Rg860KtDAd6u7RMUrtEWGisttouKJOHURb9R9cnLM4ncPLAx1l6hVFjmSA9OtbhNLMpYMgCJ4qLvE6igrO5MVMJN1i4Mtn@bETaLunw672tSDhco@qJKFzTWqTPWspskKmDrTmgtR@XFuE/ueEonXGT7ObWIPm7l0lF/nPrF51Fwfem0gdXRWyEyVE3eJmb5EjWRLkvPmLrE1tq5OFHle3SQWICIrO4plqmEST0cMPx15ebhLRjmDXJIIiDqpt5XYsRKHQGVX8mkdyGRRpGC2G/LicJMM8eJ8kMVyG26SUb32KmRhu@EuGVaWn0CXrICZznYntELjF7hNhteunNJmhUkwk3WrCvNFHLhHhnuLc1bhraEQaaYa7lNG7EfUPrt2shj/EVsSW7zpZFbewy0yrF6y2hAsSpzhHjnspICRKL7aTTKmFd/5JgKiTlpNrwqKj7GhOg6aRJ3IZCdCtxxilnUzPGJx3MwGVslMt23aat4z4tYMl1gYoVtRVE03yTyflRm2YIyne@SgWwIrsPisUFnUTFmUO9MtMq1wzDFmWTPdIofZEk1dpN/pHpnVxr8TkaiTxsHqGz6e7pHp2yWSTqJO6owy11kUznNApbkMD6tkpuu@i9hkUc/O2Lj6rjllJKbSa0Sha6Ukh9ENctApDgdRJwqVxbCURfqa7pA5PH2lrpKpM0/qZLGclltkzotxye4IoA5avvyEG5dAY4GVCBvv8IdnUU0WhcUKgyx7DcRHS9IFzHT7mgxLB/laWuGP7RUO7jhQW64GlWYS7QNhabk/lhW7jC99YEKXO@QwK8SIIissd8g6lmPRdFCsiuUWOahOlpAdeW0NqMy6YWIraSqYydyoiKuduWu5Q5Yn30QR39eELMpAsKi1VvQ3LFxaogMbQOqos5jtHc5abpFl@37Ex4OiqF7ukOWxkw/ryKG7QGbhoZDFtG03yVL7tpos@iZukuVbAsTVznSyBTK9jWSDybe7ZLmROQMN8Wy7Sw478yZEkTK222TN6A0BbRAN0pm7rLByk@wOlc2IkuFFwiQnhjCKsIezwyPWVctPY59kK1QWPZLFi4RJttcHmG3hiIRJtq16lFMWe913e0JnuSd1mBx3yS5uLiWLLLTdJdt3IZpsAoXMS7FAjOM7WmGWC1JWkGx2dMPEt2yDDF2qUiC08ksI0Qkq7pTtVUIveddgbpVdvVUVk9c2Vo/BENpdF2GUF1LcLLs9l8QaI7NBddiyMDkwwp6UBqXmNrJhJ2bMhNZkYjSysg0f4pY50LaEQsi@X4dSKyNtW@ygFbfNPi/Dfclhi0gdnemXWJtnh6u46YDOcp8Q9kpoyhM@EMnaRACR4r45yNozg1AGYeh8f0WIsQnjPLf7bgMNZWPqrOaKbyM7optCybka2EobDKVt5Tdh3DV6qXtZsEb8sSbDIFSHdkkI8f3RT93e0kX50BhCJVqq27blaQ9Fcpboqh549sD5SCEKncV3jEDHVkTQWC228UfBZZ2STqgBrYoepBEtBf3VEq5IOgghvaV3W7loG0eXtVgDkTVxY5ktaLQW8aZaJ0W/F73WIp6UJqkIqWtrdKIdMj4KWq6lejgm7I0QShvylHLwF6UqLBZbzdGP7ms5myim58b2K/qvh9WWUFCoSbRgjVocmKRootdCrY1iI5VF6lo/4ah542DRmS/eBEXoboW@j26sUYvZixTrPhqyRnXmtBdOe/RkzyL3uUsan1NhJ@@iYtprRr/aKO057XVjeyK1U2uPbaRo5lcYynYaXMiHYiTgp3F5JzbgotuqUhppARRuq4NaVWadymJTKvw0r81FdyCUsJOHD5itZqCrk8p2G4qJUknqolZzg2pDpqSuXbaNJsOxQYWfrFVFx1iXeZBCabYnjHJWWqG051bUBmyQ8qGLAa8OLqwGQ3n4QWyqGdUaDOVnTkgkh/K5lVqLypWUz63Uavb2DuVzw1F2MhX97eLHWoNQA4qygxQv4LSndOYH9Tw36tRaehZSjHI0eo2qcLfmhw2krrVeuDZCTG20ew1adZCUjx2U1tw@VhR3Ei1fv@9GI8TORTohlFaXT1LYONq@4iduPSEWT3R@HWYqPzQWT7R@DdrgBBOunWj@GjyhHQmiCpdsNICN3nqClacmEk1go7a1WqQxdR1HhxYyMfgFB0wSfWBjchujDE/RCTZaM9rWDE/RDDbaMvtW1ma9UXrbgwvb9NIbpdaZLaQ46uxwUz8v3FKKgrDDTL5zhoc9xzhUKutg7eJneKSQ5rZJFqvQPijtufGwg8FOCqk12WIUreYIR3SYSXlgE7vHRqgBbd4rKU5b@6LUnECIFdkXpTVbszK4NPrOp65rEWJp9E1pT0fIYKzVQqmVsYV0Ebp08MjK1zwSi8JMfjZLpbKQU6FUVj5VaRit1NZxJexkULaW983aSRuV2VkS7jNFG6XWuUgpClbtlFpiX6SF0KUzDsadNWyfRGEmT0iFEOfnqlTacwlxEq2DylrzYypDqY586OYw8P8ZiE5KW25NPF6QQtqFe0HhWbYuSm9tR@FRsuiiNLqsoFjpuqnVzTggkif1MJMlyWTh7gEnRfca71u46RmFwjNKhRArbgilVXIllzznF0rr4LLh2aCMSmkTdnA2S/tRqbSjCSqRFEaj8lahbOSE0SjsWUlnaTN6CjcDGo/FZPQcoM46etH2Q6nU3Pcv2H7ARvvKCm/S9AMu2teg/9gSkzGoE7aKJ0vkMamT3NsMhqoxUzg5OCNHblFpOYBKFA9j5avmoSZPbmTsVI48fMqh26nccdhuEEM3C5X8XyoGMXSzUHlrHDBiTEnh5F0zYEyhsOcJTufgzUplz2XfOXqzpjLPjBp9N1sqb7U@R2@2VK7canH0ZqdSCxY9S5HZqdNbvcexm5q6hpyV/5FopnmsHYOaIIcu3aOaxSsW7Uz3aDaShWt2pn00S0jhmp1pHzuvwnLnkp1pn1vvseTQpX10c4NVWD/OtI9t8qnEkp37OSVWHv5fgUQb@uzP8jjL/n748H8).
**Original ~~62~~ 61 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
360©>L;ü2εžq*®/ŽƵJ*Ć`-30/‚T.òεU59ÝNÌãXïδšΣ®ćÝm/OXα}нNi¦}}yнš
```
Outputs as a list of `[a,[b,c,d],[e,f,g]]`.
Extremely slow.. It's barely fast enough to output the first result.
[(Don't) try it online.](https://tio.run/##AWMAnP9vc2FiaWX//zM2MMKpPkw7w7wyzrXFvnEqwq4vw4XCvca1SirEhmAtMzAv4oCaVC7Dss61VTU5w51Ow4zDo1jDr860xaHOo8KuxIfDnW0vT1jOsX3QvU5pwqZ9fXnQvcWh//8)
Instead:
* [Verify all the first four values with a speed up variant.](https://tio.run/##XZrNqqdHEcZv5WRWJrwmXd1d/aGLIEwCulCUCMKQRYyzCIREk/iRRSCbeAEuBReSlQgGBXcmwhzjMuQaciNjV9Xz1D8RBmbO@5vn/eh@uqq6@rz97ms/f@PxU933f7r/@Ke/ef/LTx@@@ODuq9//4e7x7375@PX3Hv/iO3cPXnz//qN3X3zw3bvXXn/v16@9aVeefv7Zr55ro7xw/9GTT//7zx8898rz9/948pf7T372xcejPHzrqw//@MKPnvzt4f0n3/7i7x98@em7n//56UO/z4/feHD3rdfffuedc/dnH9z/9fz08Psvv/zST1764SvPPPvgyb8@uD548tl/PnzjyWcP7v9999vH7zy@e@MtCJ4xwffefPMOPz/44Hr66FF5Xq9H5WpyVX31enT@urS8av96vuSP37yu9mPrl1DQt4FqgvO/rrb/77ra9Tav/o3rzf5/u9ZVF6@vuK52ve1L2zdAN8F5rFwyCWYANdDPz@UbQE2hl/Tbo0dcV7ve9ap5JzUwTDAuGfaOAD2AGujrPJ6gGZimmJfsq@Xb1gBqQMul@XAxsExxvrp@bQBLADWg59sJmo/UNsW@ar/dqq0AakDPG/PhzT9Qis9eOd93ppZIgdSRrttHNv8WiTk/k3soSQUx0Xnlq@btwg4@7WL/0Z4dqC4gE53PuXmo@ryIz70RzZmpCmKaftkkkMTL@fQfcoyUjqkCZCI9Xmok4iMn7gAxT5olgCaQic5zzsfyUeKTLW4DM8H5JpIKYqIz3@3i2EmMgxvhkN7tLoEmiGmOc/Rm3PhYt8IhfVw1RwjENPsIbgMez3EzHHKsCCKXTiBbacXMKJvIv6i6Hw46dsS4HiRAprKJtY8MFAuuuh/Oda0XRbFOqvvhWPj80UXkr14jDlTzcedbhI9rhIJmTm6J3LDVHXGQ5poUuLK6JY6kps3Py8YN3RO2LsbtNeoAMpXdzdYdULyhm@IgtVUIFH6pborzoHqGkCS@2D1xiO7bu4sAmWjassGSlisG0E1R11VsRDFKAOrA4m4B8fmt7gl7PBeN2zOIOjkrTRZRfJGb4jzew1UQTKF74pB2Ii2Jv0JzS5znN1vJQWKamjvCSM5gQfBo7ojzAv2aBAKgDk5ewJgWzERzQ9i9GNcKJqK5Hw45oj6AYnW2yA7n@nEESQVRJyd2CEjkDTfDuaoXFQ3X1a@fP/aQYlOoIXEntAFJkAaiTvAUR8hP7gRLZ/FqgRqQOrIXn2QRq5t7oS0bhnyNiK7N3XAQB89ZhMrmfrDwdXtFjJ77oW2fpryjxJi7IfoZgUjrgQRIA7Wr5Ed7GnVHdOQDkAKiTloERE8eEVm6O6JbZmiFCPnaPWExFDkwmL98d1P0dmHJOGoTSB3Vne@xYLPeIGPychapo7sxTvg9y0qIJN4kSoczhNPCNVkFM5l6eBlkPord7XHQCUqSTytAphoWyogmvNPdIIedCMg7TpYq7pA@LXCmLOqC7gY5SIUTY0YCMtWyyE5fTRiku0G6DXrOwERi7G6R7mlEhCySXA@LbKuCbvecQFYfFSucasr8u9U9ctCZVgUa@G51l6h4hbbIUHG5TVQ8Eacu4o26T06OWfzugYWh7hK1yiJHcmC61W1iScaSAVAED3WXWB1lZWeyAmaybnGw5dOcuEnU/dNhV5t6sFDZB1WysLlGlame1TRZAVNnWnMhKj/ObWLfUyLxOsPHuU3sYTOXjvLr3Cc2j5rrQ68NpI7OCpmpcuIuMdOXqJFsSXLe3CW2xtbViSLPq5vEAkRkZUexTDVM4umI4acjLw93yShnkEsSAVEn9bYSO1biEKjsSj6tA5ksihTMdkNeHG6SIV6cD7JYbsNNMqrXXoUsbDfcJcPK8hPokhUw09nuhFZo/AK3yfDalVParDAJZrJuVWG@iAP3yHBvcc4qvDUUIs1Uw33KiP2I2mfXThbjP2JLYos3nczKe7hFhtVLVhuCRYkz3COHnRQwEsVXu0nGtOI730RA1Emr6VVB8TE2VMdBk6gTmexE6JZDzLJuhkcsjpvZwCqZ6bZNW817Rtya4RILI3QriqrpJpnnszLDFozxdI8cdEtgBRafFSqLmimLcme6RaYVjjnGLGumW@QwW6Kpi/Q73SOz2vh3IhJ10jhYfcPH0z0yfbtE0knUSZ1R5jqLwnkOqDSX4WGVzHTddxGbLOrZGRtX3zWnjMRUeo0odK2U5DC6QQ46xeEg6kShshiWskhf0x0yh6ev1FUydeZJnSyW03KLzHkxLtkdAdRBy5efcOMSaCywEmHjHf7wLKrJorBYYZBlr4H4aEm6gJluX5Nh6SBfSyv8sb3CwR0HasvVoNJMon0gLC33x7Jil/GlD0zococcZoUYUWSF5Q5Zx3Ismg6KVbHcIgfVyRKyI6@tAZVZN0xsJU0FM5kbFXG1M3ctd8jy5Jso4vuakEUZCBa11or@hoVLS3RgA0gddRazvcNZyy2ybN@P@HhQFNXLHbI8dvJhHTl0F8gsPBSymLbtJllq31aTRd/ETbJ8S4C42plOtkCmt5FsMPl2lyw3MmegIZ5td8lhZ96EKFLGdpusGb0hoA2iQTpzlxVWbpLdobIZUTK8SJjkxBBGEfZwdnjEumr5aeyTbIXKokeyeJEwyfb6ALMtHJEwybZVj3LKYq/7bk/oLPekDpPjLtnFzaVkkYW2u2T7LkSTTaCQeSkWiHF8RyvMckHKCpLNjm6Y@JZtkKFLVQqEVn4JITpBxZ2yvUroJe8azK2yq7eqYvLaxuoxGEK76yKM8kKKm2W3ryWxxshsUB22LEwOjLAnpUGpuY1s2IkZM6E1mRiNrGzDh7hlDrQtoRCy79eh1MpI2xY7aMVts8/LcF9y2CJSR2f6Jdbm2eEqbjqgs9wnhL0SmvKED0SyNhFApLhvDrL2zCCUQRg6318RYmzCOF/bfbeBhrIxdVZzxbeRHdFNoeRcDWylDYbStvKbMO4avdS9LFgj/liTYRCqQ7skhPj@6Kdub@mifGgMoRIt1W3b8rSHIjlLdFUPPHvgfKQQhc7iO0agYysiaKwW2/ij4LJOSSfUgFZFD9KIloL@aglXJB2EkN7Su61ctI2jy1qsgciauLHMFjRai3hTrZOi34teaxFPSpNUhNS1NTrRDhkfBS3XUj0cE/ZGCKUNeUo5@ItSFRaLreboR/e1nE0U03Nj@xX918NqSygo1CRasEYtDkxSNNFrodZGsZHKInWtn3DUvHGw6MwXb4IidLdC30c31qjF7EWKdR8NWaM6c9oLpz16smeR@9wljc@psJN3UTHtNaNfbZT2nPa6sT2R2qm1xzZSNPMrDGU7DS7kQzES8NO4vBMbcNFtVSmNtAAKt9VBrSqzTmWxKRV@mtfmojsQStjJwwfMVjPQ1Ulluw3FRKkkdVGruUG1IVNS1y7bRpPh2KDCT9aqomOsyzxIoTTbE0Y5K61Q2nMragM2SPnQxYBXBxdWg6E8/CA21YxqDYbyMyckkkP53EqtReVKyudWajV7e4fyueEoO5mK/nbxY61BqAFF2UGKF3DaUzrzg3qeG3VqLT0LKUY5Gr1GVbhb88MGUtdaL1wbIaY22r0GrTpIyscOSmtuHyuKO4mWr993oxFi5yKdEEqryycpbBxtX/ETt54Qiyc6vw4zlR8aiydavwZtcIIJ1040fw2e0I4EUYVLNhrARm89wcpTE4kmsFHbWi3SmLqOo0MLmRj8ggMmiT6wMbmNUYan6AQbrRlta4anaAYbbZl9K2uz3ii97cGFbXrpjVLrzBZSHHV2uKmfF24pRUHYYSbfOcPDnmMcKpV1sHbxMzxSSHPbJItVaB@U9tx42MFgJ4XUmmwxilZzhCM6zKQ8sIndYyPUgDbvlRSnrX1Rak4gxIrsi9KarVkZXBp951PXtQixNPqmtKcjZDDWaqHUythCughdOnhk5WseiUVhJj@bpVJZyKlQKiufqjSMVmrruBJ2Mihby/tm7aSNyuwsCfeZoo1S61ykFAWrdkotsS/SQujSGQfjzhq2T6IwkyekQojzc1Uq7bmEOInWQWWt@TGVoVRHPnRzGPh7BqKT0pZbE48XpJB24V5QeJati9Jb21F4lCy6KI0uKyhWum5qdTMOiORJPcxkSTJZuHvASdG9xvsWbnpGofCMUiHEihtCaZVcySXP@YXSOrhseDYoo1LahB2czdJ@VCrtaIJKJIXRqLxVKBs5YTQKe1bSWdqMnsLNgMZjMRk9B6izjl60/VAqNff9C7YfsNG@ssKbNP2Ai/Y16D@2xGQM6oSt4skSeUzqJPc2g6FqzBRODs7IkVtUWg6gEsXDWPmqeajJkxsZO5UjD59y6HYqdxy2G8TQzUIlf0vFIIZuFipvjQNGjCkpnLxrBowpFPY8wekcvFmp7LnsO0dv1lTmmVGj72ZL5a3W5@jNlsqVWy2O3uxUasGiZykyO3V6q/c4dlNT15Cz8heJZprH2jGoCXLo0j2qWbxi0c50j2YjWbhmZ9pHs4QUrtmZ9rHzKix3LtmZ9rn1HksOXdpHNzdYhfXjTPvYJp9KLNm5v6bEysPvFUi0oc/@LI@z7O9XX/0f)
* [Try it online with a given input.](https://tio.run/##AV8AoP9vc2FiaWX//y41K@KAmsW@cSozNjDCqS/DhcK9xrVKKsSGYC0zMC/igJpULsOyzrVVNTnDnU7DjMOjWMOvzrTFoc6jwq7Eh8OdbS9PWM6xfdC9TmnCpl1JxaH//zExMg)
### Explanation:
```
360 # Push 360
© # Store it in variable `®` (without popping)
L # Pop and push a list in the range [1,360]
; # Halve each to [0.5,180.0] in 0.5 increments
D # Duplicate this [0.5,180.0]-list
žq* # Multiply each by PI (3.141592653589793)
®/ # Divide each by the 360 from variable `®`
Ž # Take the sine of each
•6¥U•* # Multiply each by compressed 432000 (60*60*120)
D # Duplicate this list
¥ # Get the deltas / forward-differences of this copy
0ª # Append a 0
· # Double each
ø # Zip it with the duplicated list to create pairs
ò # Round each decimal value to the nearest integer
ε # Map over each pair:
ε # Map over both integers in this pair:
2F # Loop 2 times:
60‰ # Divmod the integer at the top of the stack by 60
` # Pop and push y//60 and y%60 separated to the stack
s # Swap so the y//60 is at the top of the stack
} # After the inner loop:
) # Wrap the three values on the stack into a list
R # Reverse it
] # Close the nested maps
‚ø # Pair and zip it with the duplicated [0.5,180.0]-list
# (after which the result is output implicitly as result)
```
```
360 # Push 360
© # Store it in variable `®` (without popping)
> # Increase it by 1: 361
L # Pop and push a list in the range [1,361]
; # Halve each to [0.5,180.5] in 0.5 increments
ü2 # Get it's overlapping pairs: [[0.5,1.0],[1.0,1.5],...,[180.0,180.5]]
ε # Map over each pair `y`:
žq* # Multiply each by PI (3.141592653589793)
®/ # Divide each by the 360 from variable `®`
Ž # Take the sine of each
ƵJ* # Multiply each by a compressed 120
Ć # Enclose; append its own head
` # Pop and push all three values to the stack
- # Subtract the top two
30/ # Divide it by 30
‚ # Pair it back together with the third value
T.ò # Round each to 10 decimals (work-around for 59.999... → 60)
ε # Inner map over this pair:
U # Pop and store the current value in variable `X`
59Ý # Push a list in the range [0,59]
NÌ # Push the 0-based index + 2 (1st iteration = 2; 2nd iteration = 3)
ã # Get the cartesian power to create all possible pairs/triplets
Xï # Push value `X` and floor it to an integer
δ # Map over each pair/triplet with this integer as argument
š # Prepend it in front of each pair/triplet
Σ # Sort this list of triplets/quadruplets by:
® # Push 360 from variable `®`
ć # Head extracted; push 60 and 3 separated to the stack
Ý # Pop and push a list in the range [0,3]
m # Take 60 to the power each: [1,60,360,216000]
/ # Divide the values in the triplet/quadruplet by this
# (the 216000 is ignored when dividing the triplet)
O # Sum them together
Xα # Get the absolute difference with value `X`
}н # After the sort-by: pop and leave the first/closest
Ni } # If the 0-based map-index is 1 (second iteration):
¦ # Remove the leading 0
} # Close the outer map
yн # Push the first item of pair `y`
š # Prepend it to the pair of triplets
# (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 `•6¥U•` is `432000` and `ƵJ` is `120` (and why `360` isn't shorter when compressed).
[Answer]
# [Perl 5](https://www.perl.org/), 163 bytes
```
sub h{120*sin+(pop//$_)/229.183118}$d=' [%d, %d, %d]';printf"%.1f$d$d\n",$_/2,map{$x=1/7200+$_,60*($x-int$x),$x<0?0:60*($x*60-int$x*60)}(h,(h($_+1)-h)*2)for 1..360
```
[Try it online!](https://tio.run/##JYrrCoIwGEBfZcgnbnPuJpldpAepGMWSCaVDCwbisy/BHwcOh@Nf43sX4/R7IjcrLenU9Tn2gxcCDBFaH7iqS6XqBWyToWtqGdq4Zyc/dv23TVKuWrBgb33CwAjNPg8/Q2iU2GspczCskhRDKNYbAmEQzvIij1ukldz6KmTBjmGHweSKFI5QTdphRIrzspIx/gE "Perl 5 – Try It Online")
[Answer]
# [Raku](https://raku.org/), 141 bytes
```
{($_».polymod(60,60)Z(((.[1..*]Z-$_)Xmax
0)X*2)».polymod(60 xx 3)).map:{++$
/2,|$_».round»[2...0]}}([(1..361).map((*/720*π).sin*432e3)])
```
[Try it online!](https://tio.run/##VcwxCoMwFADQ3VNkcPg/2m9MJIWeRJQgghYKaiRSUKzQe7l5gR4pLW7dH29sXac9TfXC7tb5FcLq2Gm03dLbBrSItcACAKhMibgpLmGFeV/PgcCcS/yzbJ6ZQqS@Hm9rFIVBIuPX@Tn7HJpjLyURCbNtUMKvUzo9MQBPrlLwzxtpegw8U7JVaND7Lw "Perl 6 – Try It Online")
* The initial sine values are generated by `(1..361).map((* / 720 * π).sin * 432e3)`. The values are scaled up by an additional factor of 3,600 so that they can be fed to the `polymod` methods later.
* `$_».polymod(60, 60)` generates columns 2-4.
* `.[1..*] Z- $_` zips the tail of the list with the full list using subtraction.
* `Xmax 0` makes each number zero if it's negative.
* `X* 2` doubles each number. 2 here is the multiplicative factor of 60 for feeding to `polymod`, divided by the 30 from the interpolation formula.
* `».polymod(60 xx 3)` generates columns 5-7.
* The `map` generates the final list. `++$ / 2` is the first column, increasing by one half each iteration, and the two `polymod` list results are `rounded` and shown in order of the indices 2, 1, 0.
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.